diff --git a/packages/commands/src/commands/speech/generate.ts b/packages/commands/src/commands/speech/generate.ts index 17810eec..6bafb2ef 100644 --- a/packages/commands/src/commands/speech/generate.ts +++ b/packages/commands/src/commands/speech/generate.ts @@ -531,9 +531,28 @@ export default defineCommand({ ); } - await downloadFile(audioUrl, destPath, { - quiet: settings.quiet || settings.output === "json", - }); + try { + await downloadFile(audioUrl, destPath, { + quiet: settings.quiet || settings.output === "json", + }); + } catch (error) { + const originalMessage = error instanceof Error ? error.message : String(error); + const exitCode = error instanceof BailianError ? error.exitCode : ExitCode.GENERAL; + const requestId = response.request_id?.trim(); + // Keep the signed URL in hint only — telemetry records message / api.requestId, not hint. + throw new BailianError( + requestId ? `${originalMessage} request_id=${requestId}` : originalMessage, + exitCode, + ctx.localize({ + "en-US": `Audio was generated successfully. Re-download from: ${audioUrl}; do not regenerate.`, + "zh-CN": `音频已生成成功。请从以下地址重新下载,勿重新生成:${audioUrl}`, + }), + { + cause: error, + ...(requestId ? { api: { requestId } } : {}), + }, + ); + } const result = { ...response, diff --git a/packages/commands/tests/e2e/speech-generate.e2e.test.ts b/packages/commands/tests/e2e/speech-generate.e2e.test.ts index 2d811cc5..b3fc46ba 100644 --- a/packages/commands/tests/e2e/speech-generate.e2e.test.ts +++ b/packages/commands/tests/e2e/speech-generate.e2e.test.ts @@ -465,6 +465,74 @@ describe("e2e: speech generate dry-run / mock HTTP", () => { await new Promise((resolve) => server.close(() => resolve())); } }); + + test("download HTTP failure keeps request_id and audio URL", async () => { + let synthesizePosts = 0; + const server = createServer((incoming, outgoing) => { + const url = incoming.url ?? ""; + if (url.startsWith("/api/v1/services/audio/tts/SpeechSynthesizer")) { + synthesizePosts += 1; + const address = server.address() as AddressInfo; + outgoing.writeHead(200, { "Content-Type": "application/json" }); + outgoing.end( + JSON.stringify({ + output: { + audio: { + url: `http://127.0.0.1:${address.port}/audio.wav`, + data: "", + id: "audio-1", + expires_at: "2099-01-01T00:00:00Z", + duration: 1.5, + }, + }, + usage: { characters: 10 }, + request_id: "req-gen-dl-fail", + }), + ); + return; + } + if (url.startsWith("/audio.wav")) { + outgoing.writeHead(403, { "Content-Type": "text/plain" }); + outgoing.end("forbidden"); + return; + } + outgoing.writeHead(404); + outgoing.end(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + const outDir = makeE2eOutputDir("speech-generate-dl-fail"); + + try { + const failed = await runCommandInProcess(SPEECH_GENERATE_ROUTES, [ + "speech", + "generate", + "--text-prompt", + "短播客", + "--base-url", + `http://127.0.0.1:${address.port}`, + "--api-key", + "sk-e2e", + "--out-dir", + outDir, + "--out-prefix", + "sample", + "--quiet", + ]); + expect(failed.exitCode).not.toBe(0); + expect(synthesizePosts).toBe(1); + expect(failed.stderr).toMatch(/Download failed: HTTP 403/); + expect(failed.stderr).toMatch(/request_id=req-gen-dl-fail/); + // Signed URL stays in the hint (CLI recovery), not as message `url=` for telemetry. + expect(failed.stderr).toMatch( + new RegExp(`http://127\\.0\\.0\\.1:${address.port}/audio\\.wav`), + ); + expect(failed.stderr).not.toMatch(/url=http:\/\//); + expect(failed.stderr).toMatch(/do not regenerate|勿重新生成/i); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); }); describe.skipIf(!isSpeechGenerateE2EReady())("e2e: speech generate (live)", () => { diff --git a/packages/runtime/src/utils/download.ts b/packages/runtime/src/utils/download.ts index eb2e2e7d..7ab4bfad 100644 --- a/packages/runtime/src/utils/download.ts +++ b/packages/runtime/src/utils/download.ts @@ -1,82 +1,39 @@ -import { httpTransport } from "bailian-cli-core"; +import { BailianError, ExitCode, httpTransport } from "bailian-cli-core"; +import { randomUUID } from "node:crypto"; import { chmodSync, - copyFileSync, createWriteStream, - existsSync, + lstatSync, mkdirSync, + openSync, + realpathSync, renameSync, statSync, unlinkSync, } from "fs"; -import { basename, dirname, join } from "path"; -import { BailianError, ExitCode } from "bailian-cli-core"; +import { dirname, join } from "path"; +import { pipeline } from "node:stream/promises"; import { createProgressBar } from "../output/progress.ts"; -import type { ReadableStreamReadResult } from "stream/web"; - -function errnoCode(error: unknown): string | undefined { - if (error !== null && typeof error === "object" && "code" in error) { - return (error as NodeJS.ErrnoException).code; - } - return undefined; -} - -/** - * Publish temp over dest without unlinking dest first. - * Existing dest is moved aside and restored if publish fails. - */ -function publishDownloadedFile( - tempPath: string, - destPath: string, - preserveMode: number | undefined, -): void { - if (!existsSync(destPath)) { - renameSync(tempPath, destPath); - return; - } - - const backupPath = join( - dirname(destPath), - `.${basename(destPath)}.${process.pid}.${Date.now()}.bak`, - ); - renameSync(destPath, backupPath); +function resolveDownloadTarget(destPath: string): { path: string; mode?: number } { + let entry; try { - try { - renameSync(tempPath, destPath); - } catch (renameError) { - const code = errnoCode(renameError); - // Windows cannot rename onto an existing name; EXDEV needs a copy. - // Never unlink dest first — backup already holds the previous bytes. - if (code === "EEXIST" || code === "EPERM" || code === "EXDEV") { - copyFileSync(tempPath, destPath); - try { - unlinkSync(tempPath); - } catch { - /* best effort */ - } - } else { - throw renameError; - } - } - - if (preserveMode !== undefined) { - chmodSync(destPath, preserveMode); - } - unlinkSync(backupPath); + entry = lstatSync(destPath); } catch (error) { - try { - if (existsSync(destPath)) unlinkSync(destPath); - } catch { - /* best effort */ - } - try { - renameSync(backupPath, destPath); - } catch { - /* best effort */ - } + if ((error as NodeJS.ErrnoException).code === "ENOENT") return { path: destPath }; throw error; } + + // Keep the link itself intact. A dangling link must fail instead of guessing a target. + const targetPath = realpathSync.native(destPath); + const stats = entry.isSymbolicLink() ? statSync(targetPath) : entry; + if (!stats.isFile()) { + throw new BailianError( + `Download destination must be a regular file: ${targetPath}`, + ExitCode.USAGE, + ); + } + return { path: targetPath, mode: stats.mode & 0o7777 }; } export async function downloadFile( @@ -84,82 +41,54 @@ export async function downloadFile( destPath: string, opts?: { quiet?: boolean }, ): Promise<{ size: number }> { + const target = resolveDownloadTarget(destPath); const res = await httpTransport.fetch(url); if (!res.ok) { throw new BailianError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL); } + const body = res.body; + if (!body) throw new BailianError("No response body", ExitCode.GENERAL); + const targetDir = dirname(target.path); + mkdirSync(targetDir, { recursive: true }); + const tempPath = join(realpathSync.native(targetDir), `.download-${randomUUID()}.part`); + const descriptor = openSync(tempPath, "wx", target.mode); const contentLength = Number(res.headers.get("content-length") || 0); - const reader = res.body?.getReader(); - if (!reader) throw new BailianError("No response body", ExitCode.GENERAL); - - mkdirSync(dirname(destPath), { recursive: true }); - - let preserveMode: number | undefined; - try { - preserveMode = statSync(destPath).mode & 0o7777; - } catch { - // Destination does not exist yet. - } - - // Same-directory temp so rename stays on one filesystem; never truncate dest until publish. - const tempPath = join( - dirname(destPath), - `.${basename(destPath)}.${process.pid}.${Date.now()}.part`, - ); - const writer = createWriteStream(tempPath); const progress = contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null; - let received = 0; - let completed = false; try { - const writeError = new Promise((_, reject) => { - writer.on("error", reject); - }); - - while (true) { - const { done, value } = (await Promise.race([ - reader.read(), - writeError, - ])) as ReadableStreamReadResult; - if (done) break; - - const ok = writer.write(value); - if (!ok) await new Promise((resolve) => writer.once("drain", () => resolve())); - - received += value.byteLength; - progress?.update(received); - } - completed = true; - } finally { - reader.releaseLock(); - progress?.finish(); - - await new Promise((resolve, reject) => { - writer.on("finish", resolve); - writer.on("error", reject); - writer.end(); - }); - - if (!completed) { - try { - unlinkSync(tempPath); - } catch { - /* best effort */ - } - } - } - - try { - publishDownloadedFile(tempPath, destPath, preserveMode); + await pipeline( + async function* ({ signal }: { signal?: AbortSignal } = {}) { + const reader = body.getReader(); + const cancel = () => { + void reader.cancel(signal?.reason).catch(() => {}); + }; + signal?.addEventListener("abort", cancel, { once: true }); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) return; + received += value.byteLength; + progress?.update(received); + yield value; + } + } finally { + signal?.removeEventListener("abort", cancel); + reader.releaseLock(); + } + }, + createWriteStream(tempPath, { fd: descriptor }), + ).finally(() => progress?.finish()); + if (target.mode !== undefined) chmodSync(tempPath, target.mode); + renameSync(tempPath, target.path); } catch (error) { try { unlinkSync(tempPath); } catch { - /* best effort */ + // Best-effort cleanup of the temporary file. } throw error; } diff --git a/packages/runtime/tests/download-publish.test.ts b/packages/runtime/tests/download-publish.test.ts index 67165c2e..588b64d8 100644 --- a/packages/runtime/tests/download-publish.test.ts +++ b/packages/runtime/tests/download-publish.test.ts @@ -1,47 +1,38 @@ import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; import { chmodSync, + lstatSync, + mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, + symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { httpTransport } from "bailian-cli-core"; +import { BailianError, ExitCode, httpTransport } from "bailian-cli-core"; import { downloadFile } from "../src/utils/download.ts"; -// Publish-path failures (thrown after the body is fully downloaded) must never -// lose the previous destination bytes. renameSync/copyFileSync errnos are -// injected without touching real permissions: `renameCodes` is consumed in call -// order, null lets the real rename run. +// Simulate a failed replacement without relying on platform-specific file locks. const injection = vi.hoisted(() => ({ - renameCodes: [] as Array, - copyErrorCode: undefined as string | undefined, + publishErrorCode: undefined as string | undefined, })); vi.mock("fs", async (importOriginal) => { const actual = await importOriginal(); - const fail = (code: string, action: string): never => { - const error = new Error(`injected ${code}: ${action}`) as NodeJS.ErrnoException; - error.code = code; - throw error; - }; return { ...actual, renameSync: ((from: string, to: string) => { - const code = injection.renameCodes.shift(); - if (code !== undefined && code !== null) fail(code, `rename ${from} -> ${to}`); + if (from.endsWith(".part") && injection.publishErrorCode !== undefined) { + throw Object.assign(new Error(`injected ${injection.publishErrorCode}`), { + code: injection.publishErrorCode, + }); + } return actual.renameSync(from, to); }) as typeof actual.renameSync, - copyFileSync: ((from: string, to: string) => { - if (injection.copyErrorCode !== undefined) { - fail(injection.copyErrorCode, `copy ${from} -> ${to}`); - } - return actual.copyFileSync(from, to); - }) as typeof actual.copyFileSync, }; }); @@ -63,8 +54,7 @@ let directory = ""; let destination = ""; beforeEach(() => { - injection.renameCodes = []; - injection.copyErrorCode = undefined; + injection.publishErrorCode = undefined; directory = mkdtempSync(join(tmpdir(), "bl-download-publish-")); destination = join(directory, "take.wav"); writeFileSync(destination, "original-audio", { mode: 0o600 }); @@ -76,46 +66,160 @@ afterEach(() => { rmSync(directory, { recursive: true, force: true }); }); -test("backup rename EPERM aborts publish with the destination untouched", async () => { - serveBody("new-audio"); - injection.renameCodes = ["EPERM", "EIO"]; +test.each(["EPERM", "EEXIST", "EXDEV", "EIO"])( + "replacement failure (%s) leaves the existing file and cleans up the download", + async (code) => { + serveBody("new-audio"); + injection.publishErrorCode = code; + + await expect( + downloadFile("https://example.invalid/file", destination, { quiet: true }), + ).rejects.toMatchObject({ code }); + expect(readFileSync(destination, "utf-8")).toBe("original-audio"); + expect(statSync(destination).mode & 0o777).toBe(0o600); + expect(readdirSync(directory)).toEqual(["take.wav"]); + }, +); + +test("rejects a broken link without overwriting the file with the same name", async () => { + const linkPath = join(directory, "alias.wav"); + symlinkSync("missing-dir/../take.wav", linkPath); + const fetchSpy = vi.spyOn(httpTransport, "fetch").mockResolvedValue(new Response("new-audio")); + await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).rejects.toThrow("injected EPERM"); + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toMatchObject({ code: "ENOENT" }); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory)).toEqual(["take.wav"]); + expect(readdirSync(directory).sort()).toEqual(["alias.wav", "take.wav"]); }); -test("publish rename EPERM then copy EIO restores the previous file", async () => { +test("symlink destination stays a link and the target receives new bytes", async () => { + const targetPath = join(directory, "canonical.wav"); + const linkPath = join(directory, "alias.wav"); + writeFileSync(targetPath, "original-audio", { mode: 0o600 }); + chmodSync(targetPath, 0o600); + symlinkSync(targetPath, linkPath); + serveBody("new-audio"); - injection.renameCodes = [null, "EPERM"]; - injection.copyErrorCode = "EIO"; - await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), - ).rejects.toThrow("injected EIO"); - expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory)).toEqual(["take.wav"]); + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("new-audio"); + expect(statSync(targetPath).mode & 0o777).toBe(0o600); }); -test("publish rename EIO without fallback restores the previous file", async () => { +test("failed replacement leaves a symlink and its target untouched", async () => { + const targetPath = join(directory, "canonical.wav"); + const linkPath = join(directory, "alias.wav"); + writeFileSync(targetPath, "original-audio", { mode: 0o600 }); + chmodSync(targetPath, 0o600); + symlinkSync(targetPath, linkPath); + serveBody("new-audio"); - injection.renameCodes = [null, "EIO"]; + injection.publishErrorCode = "EIO"; await expect( - downloadFile("https://example.invalid/file", destination, { quiet: true }), + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), ).rejects.toThrow("injected EIO"); - expect(readFileSync(destination, "utf-8")).toBe("original-audio"); - expect(readdirSync(directory)).toEqual(["take.wav"]); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(targetPath, "utf-8")).toBe("original-audio"); + expect(readFileSync(linkPath, "utf-8")).toBe("original-audio"); + expect(readdirSync(directory).sort()).toEqual(["alias.wav", "canonical.wav", "take.wav"]); +}); + +test("rejects a chain of dangling symlinks without creating a target", async () => { + const finalPath = join(directory, "final.wav"); + const midPath = join(directory, "mid.wav"); + const linkPath = join(directory, "out.wav"); + symlinkSync(finalPath, midPath); + symlinkSync(midPath, linkPath); + + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toMatchObject({ code: "ENOENT" }); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(lstatSync(midPath).isSymbolicLink()).toBe(true); + expect(readdirSync(directory).sort()).toEqual(["mid.wav", "out.wav", "take.wav"]); }); -test("publish rename EPERM falls back to copy and keeps the previous mode", async () => { +test("creates a new file in an ordinary output directory", async () => { + const otherDirectory = join(directory, "other"); + const targetPath = join(otherDirectory, "new.wav"); + + serveBody("new-audio"); + expect(await downloadFile("https://example.invalid/file", targetPath, { quiet: true })).toEqual({ + size: 9, + }); + + expect(readFileSync(targetPath, "utf-8")).toBe("new-audio"); + expect(readdirSync(otherDirectory)).toEqual(["new.wav"]); +}); + +test("relative link through a directory symlink does not overwrite a lexical decoy", async () => { + // portal -> elsewhere/real-home; alias -> portal/../out.wav + // Lexical join would hit root/out.wav; OS resolution hits elsewhere/out.wav. + const elsewhere = join(directory, "elsewhere"); + const realHome = join(elsewhere, "real-home"); + mkdirSync(realHome, { recursive: true }); + const trueTarget = join(elsewhere, "out.wav"); + const decoyPath = join(directory, "out.wav"); + writeFileSync(trueTarget, "true-old"); + writeFileSync(decoyPath, "decoy-old"); + symlinkSync(realHome, join(directory, "portal")); + const linkPath = join(directory, "alias.wav"); + symlinkSync("portal/../out.wav", linkPath); + serveBody("new-audio"); - injection.renameCodes = [null, "EPERM"]; - expect(await downloadFile("https://example.invalid/file", destination, { quiet: true })).toEqual({ + expect(await downloadFile("https://example.invalid/file", linkPath, { quiet: true })).toEqual({ size: 9, }); - expect(readFileSync(destination, "utf-8")).toBe("new-audio"); - expect(statSync(destination).mode & 0o777).toBe(0o600); - expect(readdirSync(directory)).toEqual(["take.wav"]); + + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(readFileSync(trueTarget, "utf-8")).toBe("new-audio"); + expect(readFileSync(decoyPath, "utf-8")).toBe("decoy-old"); +}); + +test("refuses a directory destination without moving it aside", async () => { + const targetDirectory = join(directory, "target-dir"); + mkdirSync(targetDirectory); + writeFileSync(join(targetDirectory, "keep.txt"), "keep"); + + const fetchSpy = vi.spyOn(httpTransport, "fetch"); + await expect( + downloadFile("https://example.invalid/file", targetDirectory, { quiet: true }), + ).rejects.toSatisfy((error: unknown) => { + expect(error).toBeInstanceOf(BailianError); + expect((error as BailianError).exitCode).toBe(ExitCode.USAGE); + expect((error as BailianError).message).toMatch(/must be a regular file/); + return true; + }); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(targetDirectory).isDirectory()).toBe(true); + expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); + expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); +}); + +test("refuses a symlink whose final target is a directory", async () => { + const targetDirectory = join(directory, "target-dir"); + mkdirSync(targetDirectory); + writeFileSync(join(targetDirectory, "keep.txt"), "keep"); + const linkPath = join(directory, "out.wav"); + symlinkSync(targetDirectory, linkPath); + + const fetchSpy = vi.spyOn(httpTransport, "fetch"); + await expect( + downloadFile("https://example.invalid/file", linkPath, { quiet: true }), + ).rejects.toThrow(/must be a regular file/); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(lstatSync(linkPath).isSymbolicLink()).toBe(true); + expect(lstatSync(targetDirectory).isDirectory()).toBe(true); + expect(readFileSync(join(targetDirectory, "keep.txt"), "utf-8")).toBe("keep"); + expect(readdirSync(directory).some((name) => name.includes(".bak"))).toBe(false); }); diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 2234c1c7..79b5ab10 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -46,7 +46,8 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Video edit / style transfer | `bl video edit` | `happyhorse-1.0-video-edit` | | Reference-to-video + voice | `bl video ref` | `wan3.0-video` | | Speech synthesis (TTS / voiceover) | `bl speech synthesize` | `cosyvoice-v3-flash` | -| Voice clone / manage | `bl speech voice clone/list/get/update/delete/preview` | CosyVoice/Qwen-Audio: `voice-enrollment` → `speech synthesize --model`. Omni (non-realtime flash/plus only): `qwen-voice-enrollment` create/list/delete → `omni --model --voice` | | Voice design from text | `bl speech voice design` | `voice-enrollment` → preview saved locally; formal listen via `speech synthesize` (not for Omni targets) | +| Voice clone / manage | `bl speech voice clone/list/get/update/delete/preview` | CosyVoice/Qwen-Audio: `voice-enrollment` → `speech synthesize --model`. Omni (non-realtime flash/plus only): `qwen-voice-enrollment` create/list/delete → `omni --model --voice` | +| Voice design from text | `bl speech voice design` | `voice-enrollment` → preview saved locally; formal listen via `speech synthesize` (not for Omni targets) | | Audio content generation (podcast/dialogue) | `bl speech generate` | `qwen-audio-3.1-tts-next` (text_prompt/references; not voice IDs) | | Speech recognition (ASR / transcription) | `bl speech recognize` | `fun-asr` | | Image describe | `bl vision describe` | `qwen3-vl-plus`;宿主能做且未点名 → host-first |