import { test, expect, describe, afterEach, beforeEach } from "bun:test"; import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { extractTosImageUrls, TOS_IMAGE_BASE } from "@bbbug/shared/protocol"; import { workspaceImagePromptBlock } from "@bbbug/shared/workspace_images"; /** * 这一组守的是「工单截图必须变成本机文件」。 * * 真实事故:feature 91cacd19 的需求正文只有一句话 +「![image.png]()」, * 评估 agent 在 TestSpec 里写下「the pixel-level spec in the unreachable screenshot」 * 就交卷了 —— 图从来没被下载到卫星上。原因是创建对话框走 POST /api/uploads/image, * 对象名是裸 `.png`,而当时只有 `images/plan-.` 这一种引用会被物化。 * * 两条独立的性质,少一条都不够: * 1. 字节要下到工作区 images/,正文引用改成相对路径; * 2. 评估器要被告知那些文件的**绝对**路径 —— 它的 cwd 是代码工作树,相对路径读不到。 */ // WORKSPACE_ROOT is read once at module load, and another test file may have // imported workspace.ts before this one — so the bootstrap cases ask the module // itself where a workspace goes instead of assuming an env var took effect, and // use throwaway ids they delete afterwards. const { materializeDescriptionImages, bootstrapFeatureWorkspace, workspaceDirForFeature } = await import("../src/workspace"); const PNG = Buffer.from("89504e470d0a1a0a", "hex"); // PNG 魔数,够证明写下去的是响应体 const FILE = "97c77351-cdbe-4ca9-b8cc-063a0299bc04.png"; const URL_ = `${TOS_IMAGE_BASE}/${FILE}`; const INTRO = `![image.png](${URL_})\n讲 Notes app 的 ai chat 对话栏改成截图里的 liquid glass 样式`; const realFetch = globalThis.fetch; let fetched: string[] = []; function stubFetch(ok = true) { fetched = []; globalThis.fetch = (async (input: RequestInfo | URL) => { fetched.push(String(input)); return ok ? new Response(PNG, { status: 200, headers: { "content-type": "image/png" } }) : new Response("nope", { status: 404 }); }) as typeof fetch; } const dirs: string[] = []; function workspace(): string { const dir = mkdtempSync(path.join(tmpdir(), "desc-img-")); dirs.push(dir); return dir; } beforeEach(() => stubFetch()); afterEach(() => { globalThis.fetch = realFetch; while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); }); describe("extractTosImageUrls", () => { test("认得对话框上传的裸 .png,去重,不碰别的域名", () => { const blob = `${URL_}\n${URL_}\nhttps://example.com/a.png\n${TOS_IMAGE_BASE}/plan-6a9ce296-683a-4a2c-b17f-f2a2d00e2923.png`; const found = extractTosImageUrls(blob); expect(found.map((r) => r.file)).toEqual([FILE, "plan-6a9ce296-683a-4a2c-b17f-f2a2d00e2923.png"]); }); test("文件名里不可能出现 /,物化时逃不出 images/ 目录", () => { expect(extractTosImageUrls(`${TOS_IMAGE_BASE}/../../etc/passwd.png`)).toEqual([]); }); }); describe("materializeDescriptionImages", () => { test("字节落到 images/,正文里的 URL 换成相对引用", async () => { const dir = workspace(); const r = await materializeDescriptionImages(INTRO, dir); expect(r.downloaded).toBe(1); expect(r.failed).toBe(0); expect(readFileSync(path.join(dir, "images", FILE))).toEqual(PNG); expect(r.description).toContain(`![image.png](images/${FILE})`); expect(r.description).not.toContain(TOS_IMAGE_BASE); }); test("幂等:已经在盘上的图不再重下", async () => { const dir = workspace(); await materializeDescriptionImages(INTRO, dir); const first = fetched.length; const again = await materializeDescriptionImages(INTRO, dir); expect(fetched.length).toBe(first); expect(again.description).toContain(`images/${FILE}`); }); test("下载失败时保留原 URL —— 正文绝不指向盘上没有的文件", async () => { stubFetch(false); const dir = workspace(); const r = await materializeDescriptionImages(INTRO, dir); expect(r.failed).toBe(1); expect(r.changed).toBe(false); expect(r.description).toBe(INTRO); expect(existsSync(path.join(dir, "images", FILE))).toBe(false); }); test("没有图的正文一个字节都不动,也不发请求", async () => { const dir = workspace(); const plain = "把 tab 栏的红点去掉"; const r = await materializeDescriptionImages(plain, dir); expect(r.description).toBe(plain); expect(fetched).toEqual([]); }); }); describe("已 bootstrap 的老工作区(91cacd19 就是这个形状)", () => { test("重新 bootstrap 时把漏下的图补上,并回传改写后的正文给 DB 镜像", async () => { const id = `desc-img-rescue-${Date.now()}`; const dir = workspaceDirForFeature(id); mkdirSync(dir, { recursive: true }); const header = "# 需求\n\n> Imported: 2026-09-04T15:16:38.018Z\n\n---\n\n"; writeFileSync(path.join(dir, "OriginalIntro.md"), header + INTRO, "utf8"); const res = await bootstrapFeatureWorkspace({ featureId: id, title: "需求", description: INTRO }); expect(existsSync(path.join(dir, "images", FILE))).toBe(true); expect(res.description).toContain(`images/${FILE}`); const onDisk = readFileSync(path.join(dir, "OriginalIntro.md"), "utf8"); expect(onDisk.startsWith("# 需求")).toBe(true); // 头部保留 expect(onDisk).toContain(`images/${FILE}`); rmSync(dir, { recursive: true, force: true }); }); test("没图可补时不重写 OriginalIntro.md(不覆盖人工编辑)", async () => { const id = `desc-img-noop-${Date.now()}`; const dir = workspaceDirForFeature(id); mkdirSync(dir, { recursive: true }); const body = "# 需求\n\n---\n\n人工改过的正文"; writeFileSync(path.join(dir, "OriginalIntro.md"), body, "utf8"); const res = await bootstrapFeatureWorkspace({ featureId: id, title: "需求", description: "别的内容" }); expect(res.description).toBeNull(); expect(readFileSync(path.join(dir, "OriginalIntro.md"), "utf8")).toBe(body); rmSync(dir, { recursive: true, force: true }); }); }); describe("任务换到另一台节点(正文里只剩相对路径)", () => { // 第一台节点把绝对链接改写成 images/ 并回写了 DB;生产上 feature ea44b49d / // 8b34b012 在执行节点上的 images/ 是空的,描述里的截图从来没被下下来。 const RELATIVE = `![image.png](images/${FILE})\n讲 Notes app 的 ai chat 对话栏改成截图里的 liquid glass 样式`; test("按对象名从 TOS 找回字节,正文不动", async () => { const dir = workspace(); const r = await materializeDescriptionImages(RELATIVE, dir); expect(fetched).toEqual([URL_]); expect(readFileSync(path.join(dir, "images", FILE))).toEqual(PNG); expect(r.description).toBe(RELATIVE); expect(r.changed).toBe(false); }); test("本机已有就不重下;Meego 附件(images/00.png)不归这里管", async () => { const dir = workspace(); mkdirSync(path.join(dir, "images"), { recursive: true }); writeFileSync(path.join(dir, "images", FILE), PNG); await materializeDescriptionImages(`${RELATIVE}\n![image](images/00.png)`, dir); expect(fetched).toEqual([]); }); test("新节点首次 bootstrap 就把图补齐", async () => { const id = `desc-img-migrate-${Date.now()}`; const dir = workspaceDirForFeature(id); try { await bootstrapFeatureWorkspace({ featureId: id, title: "需求", description: RELATIVE }); expect(existsSync(path.join(dir, "images", FILE))).toBe(true); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("老工作区里漏掉的图在重新 bootstrap 时补上", async () => { const id = `desc-img-migrate-old-${Date.now()}`; const dir = workspaceDirForFeature(id); try { mkdirSync(path.join(dir, "images"), { recursive: true }); writeFileSync(path.join(dir, "OriginalIntro.md"), "# 需求\n\n---\n\n" + RELATIVE, "utf8"); const res = await bootstrapFeatureWorkspace({ featureId: id, title: "需求", description: RELATIVE }); expect(existsSync(path.join(dir, "images", FILE))).toBe(true); expect(res.description).toBeNull(); // 正文没变,不用回写 } finally { rmSync(dir, { recursive: true, force: true }); } }); }); describe("workspaceImagePromptBlock", () => { test("有图时给出绝对路径 —— 评估器的 cwd 不是工作区", () => { const block = workspaceImagePromptBlock(`![image.png](images/${FILE})`, "/Users/x/bug_workspace_ios/feature-1"); expect(block).toContain(`/Users/x/bug_workspace_ios/feature-1/images/${FILE}`); expect(block).toContain("Read"); }); test("没图时为空 —— 这些任务的 prompt 保持逐字不变,RSI 重放语料才可比", () => { expect(workspaceImagePromptBlock("没有截图的需求", "/Users/x/ws")).toBe(""); expect(workspaceImagePromptBlock(`![a](images/${FILE})`, null)).toBe(""); }); test("plan 编辑器插入的图同样被指向", () => { const block = workspaceImagePromptBlock("![](images/plan-6a9ce296-683a-4a2c-b17f-f2a2d00e2923.png)", "/ws"); expect(block).toContain("/ws/images/plan-6a9ce296-683a-4a2c-b17f-f2a2d00e2923.png"); }); });