A local-first multi-agent app development platform, built on PenguinHarness
web: 回复里的图片从工作区取,不再指向 App 自己的源
lmliheng9a88883ab015
diff --git a/changelog/unreleased/2026-10-29-reply-image-from-workspace.md b/changelog/unreleased/2026-10-29-reply-image-from-workspace.mdnew file mode 100644index 00000000..d31c0303--- /dev/null+++ b/changelog/unreleased/2026-10-29-reply-image-from-workspace.md@@ -0,0 +1,52 @@+# A reply's picture is fetched from the Workspace, not from the App's own origin++- **Date:** 2026-10-29+- **Type:** fix+- **Scope:** `web`, `ui`+- **Breaking:** no++[中文](2026-10-29-reply-image-from-workspace.zh.md)++A model names the pictures it made the way a README would — ``, relative to the+Workspace it works in. A conversation rendered that src as written, so the browser resolved it+against the App's own route (`/chat/shot.png`, a page that does not exist) and every Workspace+picture in a reply was a broken image. The image plugin shipped last round went further and told+the agent never to use Markdown image syntax at all, because the only way to see a generated+picture was to open it in the Files panel.++Inside a conversation an image src is now sorted the way a link already was. One that names a+Workspace file is fetched from that Session's own file route, so the picture renders in the+transcript (and on a Session that lives on a machine, from that machine). One that names another+site keeps its own src, and one that resolves to nothing — a `..` climbing out of the Workspace, a+`~` path, an emptied src — stays exactly as written, the browser's broken-image state being the+truth about it.++## Details++- `packages/ui/src/components/content/prose/prose.tsx`: `ProseImagesProvider` / `ProseImageResolver`+ and the `img` adapter, the same shape as the link resolver beside it. With no resolver above, an+ image keeps the src the Markdown wrote, so every surface that renders a README, a handbook page or+ a document is unchanged. An empty src renders no `src` attribute at all (rather than `src=""`,+ which asks the browser for the page itself).+- `packages/ui/src/components/content/prose/prose.css`: `.md-body img` — the reading column is the+ widest a picture may get, with its aspect ratio kept, so a 2000px screenshot does not widen the+ transcript.+- `packages/web/src/lib/reply-image.ts`: `resolveReplyImage` — the pure rule, `external` / `file` /+ `none`, reusing `toWorkspaceRelative` and the scheme test the link resolver uses (`isExternalRef`,+ now exported from `lib/reply-link.ts` rather than written twice).+- `packages/web/src/features/chat/workspace-refs.tsx` (was `workspace-links.tsx`): the conversation+ provides both resolvers; it names itself after what it now does. `MessageStream`'s render context+ gained `workspaceFileUrl`, which `chat-page.tsx` builds from the Session's id — absent while+ drafting, where there is no Session whose files could be read.+- `plugins/use-seedream/skills/seedream/SKILL.md`: the "handing the result over" section now asks+ for the picture itself instead of telling the agent that image syntax does not resolve.+- Tests: `packages/web/test/reply-image.test.ts` (the rule), `packages/web/test/md.test.ts` (what+ reaches the DOM through the real pipeline), `packages/ui/test/prose.test.ts` (the adapter and its+ default), `packages/web/e2e/reply-image.spec.mjs` (a real browser: the picture decodes, the other+ two srcs are untouched) with a branch in the e2e mock model.++## Compatibility++- No API, on-disk or protocol change. A Markdown surface outside a conversation renders exactly as+ before; only a reply's images are fetched from a different URL, and that URL is the one the Files+ panel has always used.diff --git a/changelog/unreleased/2026-10-29-reply-image-from-workspace.zh.md b/changelog/unreleased/2026-10-29-reply-image-from-workspace.zh.mdnew file mode 100644index 00000000..89f5a7c3--- /dev/null+++ b/changelog/unreleased/2026-10-29-reply-image-from-workspace.zh.md@@ -0,0 +1,43 @@+# 回复里的图片从工作区取,不再指向 Web App 自己的源++- **日期:** 2026-10-29+- **类型:** fix+- **范围:** `web`、`ui`+- **破坏性:** 无++[English](2026-10-29-reply-image-from-workspace.md)++模型写图片的方式和写 README 一样 —— ``,路径相对它工作的那个工作区。会话以前+照原样渲染这个 src,于是浏览器把它解析成 App 自己的路由(`/chat/shot.png`,一个不存在的页面),+回复里每一张工作区图片都是一个坏图。上一轮装上的图像插件更进一步:它直接告诉 Agent **别用**+Markdown 图片语法,因为要看见生成的图只能去文件面板里打开。++现在会话里的图片 src 与链接走同一套判断。指向工作区文件的,从这个会话自己的文件路由取,图片就在+对话里显示(会话在机器上,就从那台机器取);指向别的站点的,src 原样保留;解析不到东西的 —— 爬出+工作区的 `..`、`~` 路径、被渲染器清空的 src —— 一律照原样保留,坏图本身就是那句话的真相。++## 细节++- `packages/ui/src/components/content/prose/prose.tsx`:新增 `ProseImagesProvider` /+ `ProseImageResolver` 与 `img` 适配器,与旁边的链接解析器同形。上面没有解析器时,图片保留+ Markdown 写的 src,所以渲染 README、手册、文档的每一处界面都不变。空 src 不渲染 `src` 属性+ (而不是 `src=""`,那是在向浏览器要当前页面)。+- `packages/ui/src/components/content/prose/prose.css`:`.md-body img` —— 阅读栏就是图片的最大宽度,+ 按原比例缩放,2000px 的截图不会把对话撑宽。+- `packages/web/src/lib/reply-image.ts`:`resolveReplyImage` —— 纯规则,`external` / `file` /+ `none`,复用 `toWorkspaceRelative` 与链接解析器用的那个 scheme 判断(`isExternalRef`,从+ `lib/reply-link.ts` 导出,不再写第二份)。+- `packages/web/src/features/chat/workspace-refs.tsx`(原 `workspace-links.tsx`):会话同时提供两个+ 解析器,文件按它现在做的事改名。`MessageStream` 的渲染上下文多了 `workspaceFileUrl`,由+ `chat-page.tsx` 按会话 id 构造 —— 起草时没有(那时还没有会话的文件可读)。+- `plugins/use-seedream/skills/seedream/SKILL.md`:「把结果交给用户」一节改成让 Agent 直接给图,+ 不再说图片语法解析不了。+- 测试:`packages/web/test/reply-image.test.ts`(规则)、`packages/web/test/md.test.ts`(真管线里+ 进到 DOM 的东西)、`packages/ui/test/prose.test.ts`(适配器与它的默认行为)、+ `packages/web/e2e/reply-image.spec.mjs`(真浏览器:那张图真的解码了,另两个 src 原样不动),+ 并在 e2e 的 mock 模型里加了一条分支。++## 兼容++- 接口、磁盘格式、线上协议都没变。会话之外的 Markdown 界面渲染与以前完全一致;只有回复里的图片换+ 了一个取法,而那个 URL 正是文件面板一直在用的。diff --git a/packages/ui/src/components/content/prose/prose.css b/packages/ui/src/components/content/prose/prose.cssindex fd47ef4d..004f05a9 100644--- a/packages/ui/src/components/content/prose/prose.css+++ b/packages/ui/src/components/content/prose/prose.css@@ -84,6 +84,17 @@color: var(--ui-fg-link-hover);}}+/* A picture in a body: the reading column is the widest it may get, so a 2000px screenshot fits+ instead of widening the transcript (mobile included), and its own aspect ratio is kept when the+ width is capped. `display: block` because an inline image sits on a text baseline, leaving a+ sliver of line box under it. */+.md-body img {+ display: block;+ max-width: 100%;+ height: auto;+ margin: 0.5rem 0;+ border-radius: var(--ui-radius-lg);+}/* The same chip the InlineCode component draws. */.md-body code {border-radius: var(--ui-radius-sm);diff --git a/packages/ui/src/components/content/prose/prose.tsx b/packages/ui/src/components/content/prose/prose.tsxindex 684b0e8a..1c900882 100644--- a/packages/ui/src/components/content/prose/prose.tsx+++ b/packages/ui/src/components/content/prose/prose.tsx@@ -105,6 +105,33 @@ export function ProseLinksProvider({return <ProseLinksContext.Provider value={resolve}>{children}</ProseLinksContext.Provider>;}+/**+ * What an image in the Markdown points at, as the surface above decides it: the src an `<img>`+ * gets. `null` keeps the one the Markdown wrote.+ */+export type ProseImageResolver = (src: string, alt: string) => { src: string } | null;++const ProseImagesContext = createContext<ProseImageResolver | null>(null);++/**+ * Hands the Markdown below an image resolver; `null` restores the default, the src as written.+ *+ * Same shape and same cost as the link resolver above: a context change re-renders every image in+ * the tree, memoized bodies included, so pass a resolver that keeps its identity while its inputs+ * do. It exists because a relative src in a reply names a file of the Session's Workspace, which+ * the browser resolves against the App's own origin — a broken image. The surface that knows how+ * to serve a Workspace file says so here; every other Markdown surface renders untouched.+ */+export function ProseImagesProvider({+ resolve,+ children,+}: {+ resolve: ProseImageResolver | null;+ children?: ReactNode;+}): ReactElement {+ return <ProseImagesContext.Provider value={resolve}>{children}</ProseImagesContext.Provider>;+}+/*** Link adapter. With no resolver above, every link opens in a new tab (`target="_blank"` +* `rel="noreferrer"`, which also implies `noopener`), unconditionally, so a click never navigates@@ -129,6 +156,31 @@ function MdLink({);}+/**+ * Image adapter. With no resolver above, an image keeps the src the Markdown wrote — every surface+ * that renders a README, a handbook page or a document gets exactly what react-markdown gave it+ * before this adapter existed. A resolver may point it somewhere else (the Web App's conversation+ * sends a Workspace-relative src to that Session's file route, see lib/reply-image.ts). An empty+ * src renders no `src` attribute at all rather than `src=""`, which would ask the browser for the+ * page itself. Everything else react-markdown supplies (width, height, title, ...) is forwarded;+ * only its non-DOM `node` prop is stripped. Sizing is CSS (`.md-body img` in prose.css), so an+ * oversized picture fits the reading column instead of widening the transcript.+ */+function MdImage({+ node: _node,+ src,+ alt,+ ...imageProps+}: ComponentPropsWithoutRef<"img"> & ExtraProps) {+ const resolve = useContext(ProseImagesContext);+ const written = typeof src === "string" ? src : "";+ const resolved = written === "" ? null : (resolve?.(written, alt ?? "") ?? null);+ const href = resolved?.src ?? written;+ return (+ <img {...imageProps} {...(href === "" ? {} : { src: href })} alt={alt ?? ""} loading="lazy" />+ );+}+/*** The two `components` maps, built once at module scope instead of inline per render.* react-markdown uses `components.pre` as the element **type**, so a fresh arrow each render is@@ -137,16 +189,18 @@ function MdLink({* streams, including for blocks that closed long ago. `streaming` is the only thing the adapter* closes over, so one frozen map per value is enough; the single flip between them happens on* the settle render, which re-parses the message anyway — the same render the rehype stage- * flips on. The `a` adapter closes over nothing — its resolver comes from context, not from a- * closure — so both maps share the one `MdLink` reference.+ * flips on. The `a` and `img` adapters close over nothing — their resolvers come from context,+ * not from a closure — so both maps share the one reference to each.*/const STREAMING_COMPONENTS: Components = {pre: (props) => <MdPre streaming>{props.children}</MdPre>,a: MdLink,+ img: MdImage,};const SETTLED_COMPONENTS: Components = {pre: (props) => <MdPre streaming={false}>{props.children}</MdPre>,a: MdLink,+ img: MdImage,};/**diff --git a/packages/ui/test/prose.test.ts b/packages/ui/test/prose.test.tsindex 510b731c..03144da2 100644--- a/packages/ui/test/prose.test.ts+++ b/packages/ui/test/prose.test.ts@@ -1,6 +1,7 @@/*** Prose and Md: Markdown in its reading box, the three densities, the link default and the- * resolver that overrides it, fenced code routed into CodeBlock, and the stylesheet the box reads.+ * resolver that overrides it, the image adapter and the resolver that points a src elsewhere,+ * fenced code routed into CodeBlock, and the stylesheet the box reads.* How the pipeline typesets math is prose-math.test.ts; where a bare URL ends is* remark-autolink-boundary.test.ts.*/@@ -12,10 +13,11 @@ import {Md,PROSE_NEW_TAB,Prose,+ ProseImagesProvider,ProseLinksProvider,SETTLED_MD_COMPONENTS,} from "../src/components/content/prose/prose";-import type { ProseLinkResolver } from "../src/components/content/prose/prose";+import type { ProseImageResolver, ProseLinkResolver } from "../src/components/content/prose/prose";import { DEFAULT_UI_STRINGS, UiStringsProvider } from "../src/strings";import { classTokens, renderStatic } from "../src/testing";import { SRC_DIR } from "./helpers/paths";@@ -26,6 +28,10 @@ const read = (name: string) => readFileSync(join(PROSE, name), "utf8");/** All rendered <a ...> opening tags. */const anchors = (html: string) => html.match(/<a\b[^>]*>/g) ?? [];+/** The src of every rendered <img>, in order. */+const imageSrcs = (html: string) =>+ (html.match(/<img\b[^>]*>/g) ?? []).map((tag) => /src="([^"]*)"/.exec(tag)?.[1] ?? "");+describe("Prose", () => {it("wraps the Markdown in the reading box, in the reading face, with the caller's ink", () => {const html = renderStatic(@@ -83,6 +89,49 @@ describe("Md links", () => {});});+describe("Md images", () => {+ it("keep the src the Markdown wrote when no resolver is provided", () => {+ const srcs = imageSrcs(renderStatic(createElement(Md, { text: "" })));+ expect(srcs).toEqual(["shots/cat.png"]);+ });++ it("take what a resolver decides, per src, and answer with null to keep the written one", () => {+ const seen: [string, string][] = [];+ const resolve: ProseImageResolver = (src, alt) => {+ seen.push([src, alt]);+ return src.endsWith(".png") ? { src: `/files/${src}` } : null;+ };+ const srcs = imageSrcs(+ renderStatic(+ createElement(ProseImagesProvider, {+ resolve,+ children: createElement(Md, { text: " " }),+ }),+ ),+ );+ expect(srcs).toEqual(["/files/a.png", "https://x.dev/b.jpg"]);+ expect(seen).toEqual([+ ["a.png", "截图"],+ ["https://x.dev/b.jpg", "remote"],+ ]);+ // The rest of the element is untouched: alt text and lazy loading are the adapter's own.+ const tags = renderStatic(+ createElement(ProseImagesProvider, {+ resolve,+ children: createElement(Md, { text: "" }),+ }),+ ).match(/<img\b[^>]*>/g);+ expect(tags?.[0]).toContain('alt="截图"');+ expect(tags?.[0]).toContain('loading="lazy"');+ });++ it('never render src="", which would ask the browser for the page itself', () => {+ const tags = renderStatic(createElement(Md, { text: "![a]()" })).match(/<img\b[^>]*>/g);+ expect(tags?.[0]).toContain('alt="a"');+ expect(tags?.[0]).not.toContain("src=");+ });+});+describe("Md code", () => {it("routes a fenced block into CodeBlock, named in the interface's words", () => {const zh = { ...DEFAULT_UI_STRINGS, copyCode: "复制代码" };@@ -103,7 +152,9 @@ describe("Md code", () => {});it("lets a surface add adapters over the settled map without losing the code block", () => {- expect(Object.keys(SETTLED_MD_COMPONENTS).sort()).toEqual(["a", "pre"]);+ // The map's own three: the link and image resolvers and the code-block pre override. A+ // surface adds over them (the file browser's img is exactly that), never instead of them.+ expect(Object.keys(SETTLED_MD_COMPONENTS).sort()).toEqual(["a", "img", "pre"]);const html = renderStatic(createElement(Md, {text: "\n\n```\nx\n```",diff --git a/packages/web/e2e/mock-llm.mjs b/packages/web/e2e/mock-llm.mjsindex acf785a3..082001ea 100644--- a/packages/web/e2e/mock-llm.mjs+++ b/packages/web/e2e/mock-llm.mjs@@ -32,6 +32,9 @@* (path-hints.spec: the card's shortened subtitle keeps the whole path one hover away)* - "scroll bounce test" -> a three-line paragraph every 50ms for ~4s, for every request of* that conversation (scroll-follow-bounce.spec wheels up while each reply streams)+ * - "image reply test" -> one text answer carrying three image srcs: a Workspace file, a path+ * outside the Workspace, and another site's (reply-image.spec: only the first is fetched from+ * the Session's file route)* - last message has tool_result -> final text (turn 2)* - otherwise (first user turn) -> thinking + text + tool_use(exec_command)*/@@ -601,6 +604,21 @@ const server = http.createServer((req, res) => {return;}+ // Reply-image test case (reply-image.spec): a single-turn answer that shows a picture it made+ // into the Workspace, beside one src that names nothing this Session can serve and one that is+ // another site's — the three shapes a reply's image src comes in. No tool call: the point is+ // what the transcript does with the Markdown, not what the Agent did.+ if (flat.includes("image reply test") && !hasToolResult) {+ block(res, 0, { type: "text", text: "" }, [+ { type: "text_delta", text: "Here it is.\n\n" },+ { type: "text_delta", text: "\n\n" },+ { type: "text_delta", text: "\n\n" },+ { type: "text_delta", text: "\n" },+ ]);+ messageStop(res, "end_turn", 40);+ return;+ }+// Slow tool-output test case (reload-midstream.spec): a real exec_command whose output// streams one line every 200ms for ~8s — long enough to reload the page mid-stream and// watch the output keep growing afterwards.diff --git a/packages/web/e2e/reply-image.spec.mjs b/packages/web/e2e/reply-image.spec.mjsnew file mode 100644index 00000000..f9de5b24--- /dev/null+++ b/packages/web/e2e/reply-image.spec.mjs@@ -0,0 +1,97 @@+/**+ * A reply's pictures are fetched from where they actually live.+ *+ * A model names the pictures it made the way a README would — ``, relative to the+ * Workspace it works in. Before this, the browser resolved that src against the SPA's own route+ * (`/chat/shot.png`), so every Workspace picture in a reply was a broken image, and the image+ * plugin's skill had to tell the agent never to use Markdown image syntax at all. The transcript+ * now sends such a src to the Session's own file route, while a src that names another site keeps+ * its own and one that resolves to nothing stays exactly as written.+ *+ * Seeded through the API against the mock model (mock-llm.mjs, branch "image reply test"), with a+ * real PNG written into the Session's Workspace first — the picture has to load, not merely+ * render an <img>.+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const U = "replyimage";+const P = "password123";++/** A 2×2 PNG: small enough to inline, real enough that a browser decodes it (naturalWidth > 0). */+const PNG_2X2 =+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVQIW2P8z8Dwn4GBgYGJAQ0AAB6nAgHkPj0eAAAAAElFTkSuQmCC";++test("a picture of the Workspace renders, and only that src is rewritten", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;++ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();++ // A Workspace of the test's own, already holding the picture the reply will name.+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-reply-image-"));+ fs.writeFileSync(path.join(workspace, "shot.png"), Buffer.from(PNG_2X2, "base64"));++ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8", workspace },+ })+ ).json();+ const sessionId = sess.session.sessionId;+ expect(sess.session.workspace, "the Session runs in the test's Workspace").toBe(workspace);++ await page.goto(`${BASE}/chat/${sessionId}`);+ const ta = page.getByPlaceholder(/输入消息/);+ await ta.waitFor();+ await ta.fill("image reply test, please");+ await page.getByRole("button", { name: "发送" }).click();++ const images = page.locator(".md-body img");+ await expect(images).toHaveCount(3, { timeout: 30_000 });++ // 1. The Workspace picture: fetched from the Session's file route, and actually decoded.+ const own = images.nth(0);+ await expect(own).toHaveAttribute(+ "src",+ new RegExp(`/api/sessions/${sessionId}/files/content\\?path=shot\\.png`),+ );+ await expect(own).toHaveAttribute("alt", "the picture");+ await expect(own).toHaveAttribute("loading", "lazy");+ await expect+ .poll(() => own.evaluate((img) => img.complete && img.naturalWidth > 0), { timeout: 15_000 })+ .toBe(true);++ // 2. A src that resolves to nothing keeps what the Markdown wrote — the browser's own broken+ // image, never a request for a file outside the Workspace.+ await expect(images.nth(1)).toHaveAttribute("src", "../../outside.png");+ expect(await images.nth(1).evaluate((img) => img.naturalWidth)).toBe(0);++ // 3. Another site's picture is left alone: no file route is involved.+ await expect(images.nth(2)).toHaveAttribute("src", "https://example.com/remote.png");++ // The stylesheet caps an oversized picture instead of widening the transcript (this one is 2px,+ // so the assertion is about the rule being in force, not about the clamp itself).+ const box = await own.boundingBox();+ expect(box?.width ?? 0).toBeGreaterThan(0);+ expect(box?.width ?? 0).toBeLessThanOrEqual(1280);+});diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 2315b730..f2d6a0cf 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -1963,6 +1963,20 @@ export function ChatPage() {return promotedPricing(m?.pricing, m?.discount);};const modelPricing = pricingOf(activeModelRef);+ /**+ * The Session's own file route, for an `<img>` in a reply: a picture the Agent wrote into the+ * Workspace is served from there, while the same relative src resolves against the App's own+ * origin and is a page that does not exist. Stable per Session for the reason+ * `openWorkspaceFile` is — every image in the transcript reads it through context — and absent+ * while drafting, where there is no Session whose files could be read.+ */+ const workspaceFileUrl = useMemo(+ () =>+ selectedSessionId === null+ ? undefined+ : (path: string) => api.workspaceFileUrl(selectedSessionId, path),+ [selectedSessionId],+ );const ctx: StreamRenderContext = {pendingApprovals: stream.pendingApprovals,onApprove,@@ -1984,6 +1998,7 @@ export function ChatPage() {void onStop();},onOpenFile: openWorkspaceFile,+ ...(workspaceFileUrl === undefined ? {} : { workspaceFileUrl }),onOpenSubagent: (sessionId, origin) => {// Chip click: the agents tab focused on that child (the focus chain ends with the// child's own id), with the graph pinned to this chip's Task.diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex 422fd399..30db7448 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -16,7 +16,7 @@ import type { MemoryChangeRow } from "../../lib/omni/memory-changes";import type { TaskStats } from "../../lib/omni/task-stats";import type { PendingApproval } from "./use-session-stream";import { MessageItem } from "./message-item";-import { WorkspaceLinksProvider } from "./workspace-links";+import { WorkspaceRefsProvider } from "./workspace-refs";import { SessionWorkGroup, isWorkItem } from "./work-group";import { createStreamFollow, followToBottom, stickToBottom } from "./stream-follow";import type { StreamFollow } from "./stream-follow";@@ -59,9 +59,17 @@ export interface StreamRenderContext {* Opens the Files panel and navigates to this file (a file-summary card's row, or a link in* the stream's Markdown naming a Workspace file; takes a Workspace-relative path). The card* doesn't render and links keep opening a new tab if this isn't wired up. Must be stable:- * every rendered link reads it through context (see WorkspaceLinksProvider).+ * every rendered link reads it through context (see WorkspaceRefsProvider).*/onOpenFile?: (path: string) => void;+ /**+ * A URL an `<img>` in a reply can fetch for a Workspace-relative path — the Session's own file+ * route, so a picture the Agent made into the Workspace shows in the transcript instead of+ * pointing at a page of the App (see lib/reply-image.ts). Images keep the src the Markdown wrote+ * if this isn't wired up. Must be stable: every rendered image reads it through context (see+ * WorkspaceRefsProvider).+ */+ workspaceFileUrl?: (path: string) => string;/** Opens the subagents panel focused on this child session (subagent chip click); `origin` is the ctx.origin at the chip's render level — the child's ancestor chain, excluding its own id. */onOpenSubagent?: (sessionId: string, origin: string[]) => void;/** Opens the Memory panel on its list (memory-changes card header); the button doesn't render if this isn't wired up. */@@ -535,10 +543,16 @@ export function MessageStream({<EmptyState title={S.chat.emptyStream} />) : (// Links in replies, reasoning and compaction summaries name files of this Session's- // Workspace: they open in its Files panel rather than a new tab (see workspace-links.tsx).- <WorkspaceLinksProvider workspace={ctx.workspace ?? null} onOpenFile={ctx.onOpenFile}>+ // Workspace: they open in its Files panel rather than a new tab, and an image the+ // Agent made into that Workspace is fetched from its file route rather than from the+ // App's own origin (see workspace-refs.tsx).+ <WorkspaceRefsProvider+ workspace={ctx.workspace ?? null}+ onOpenFile={ctx.onOpenFile}+ fileUrl={ctx.workspaceFileUrl}+ ><MessageItems items={items} ctx={ctx} />- </WorkspaceLinksProvider>+ </WorkspaceRefsProvider>)}</div></div>diff --git a/packages/web/src/features/chat/workspace-links.tsx b/packages/web/src/features/chat/workspace-links.tsxdeleted file mode 100644index bffbda99..00000000--- a/packages/web/src/features/chat/workspace-links.tsx+++ /dev/null@@ -1,35 +0,0 @@-/**- * Makes the links in the Markdown below Workspace-aware: a link naming a file of `workspace` opens- * it through `onOpenFile` (the Files panel) instead of a new tab — see lib/reply-link.ts for how an- * href is sorted. With no `onOpenFile` the links keep the package's default, a new tab for every- * link.- *- * Only a conversation provides it (MessageStream); every other surface — Memory, the handbook,- * tickets — renders without it and keeps a new tab for every link. The resolver is memoized on its- * two inputs: a context change re-renders every link in the transcript, memoized message bodies- * included, so `onOpenFile` has to be a stable callback.- */-import { useMemo } from "react";-import type { ReactNode } from "react";-import { ProseLinksProvider } from "@adelie/ui";-import type { ProseLinkResolver } from "@adelie/ui";-import { replyLinkBehavior } from "../../lib/reply-link";--export function WorkspaceLinksProvider({- workspace,- onOpenFile,- children,-}: {- workspace: string | null;- onOpenFile: ((path: string) => void) | undefined;- children: ReactNode;-}) {- const resolve = useMemo<ProseLinkResolver | null>(- () =>- onOpenFile === undefined- ? null- : (href) => replyLinkBehavior(href, { workspace, openFile: onOpenFile }),- [workspace, onOpenFile],- );- return <ProseLinksProvider resolve={resolve}>{children}</ProseLinksProvider>;-}diff --git a/packages/web/src/features/chat/workspace-refs.tsx b/packages/web/src/features/chat/workspace-refs.tsxnew file mode 100644index 00000000..93118cfe--- /dev/null+++ b/packages/web/src/features/chat/workspace-refs.tsx@@ -0,0 +1,58 @@+/**+ * Makes the Markdown below Workspace-aware: a link naming a file of `workspace` opens it through+ * `onOpenFile` (the Files panel) instead of a new tab — see lib/reply-link.ts for how an href is+ * sorted — and an image whose src names one is fetched from this Session's own file route instead+ * of from the App's origin, which serves no file at all (lib/reply-image.ts). With no `onOpenFile`+ * the links keep the package's default, a new tab for every link; with no `fileUrl` the images keep+ * the src the Markdown wrote.+ *+ * Only a conversation provides it (MessageStream); every other surface — Memory, the handbook,+ * tickets — renders without it and keeps a new tab for every link and every image src as written.+ * Both resolvers are memoized on their inputs and the two enter/leave together: a context change+ * re-renders every link and image in the transcript, memoized message bodies included, so+ * `onOpenFile` and `fileUrl` have to be stable callbacks.+ */+import { useMemo } from "react";+import type { ReactNode } from "react";+import { ProseImagesProvider, ProseLinksProvider } from "@adelie/ui";+import type { ProseImageResolver, ProseLinkResolver } from "@adelie/ui";+import { replyLinkBehavior } from "../../lib/reply-link";+import { resolveReplyImage } from "../../lib/reply-image";++export function WorkspaceRefsProvider({+ workspace,+ onOpenFile,+ fileUrl,+ children,+}: {+ workspace: string | null;+ onOpenFile: ((path: string) => void) | undefined;+ /** A URL an `<img>` can fetch for a Workspace-relative path. */+ fileUrl: ((path: string) => string) | undefined;+ children: ReactNode;+}) {+ const resolveLink = useMemo<ProseLinkResolver | null>(+ () =>+ onOpenFile === undefined+ ? null+ : (href) => replyLinkBehavior(href, { workspace, openFile: onOpenFile }),+ [workspace, onOpenFile],+ );+ // An external src and one the App cannot serve both come back `null`, which keeps the src the+ // Markdown wrote — the browser's own broken-image state is the truth about the latter.+ const resolveImage = useMemo<ProseImageResolver | null>(+ () =>+ fileUrl === undefined+ ? null+ : (src) => {+ const image = resolveReplyImage(src, workspace);+ return image.kind === "file" ? { src: fileUrl(image.path) } : null;+ },+ [workspace, fileUrl],+ );+ return (+ <ProseLinksProvider resolve={resolveLink}>+ <ProseImagesProvider resolve={resolveImage}>{children}</ProseImagesProvider>+ </ProseLinksProvider>+ );+}diff --git a/packages/web/src/lib/reply-image.ts b/packages/web/src/lib/reply-image.tsnew file mode 100644index 00000000..89aaa97d--- /dev/null+++ b/packages/web/src/lib/reply-image.ts@@ -0,0 +1,52 @@+/**+ * Where a picture in a conversation's Markdown comes from.+ *+ * A model names the pictures it made the way a README would — ``, relative to the+ * Workspace it works in. The browser resolves that src against the SPA's own route+ * (`/chat/shot.png`, a page that does not exist), so every Workspace picture a reply pointed at+ * rendered as a broken image and the only way to see it was the Files panel — which is why the+ * image plugin's own skill told the agent not to use Markdown image syntax at all. Inside a+ * conversation a src is therefore sorted before it renders:+ *+ * - `external` — it names a scheme (`https:`, `data:`, …) or is protocol-relative (`//host`).+ * The browser fetches it as it stands.+ * - `file` — anything else that resolves to a Workspace-relative path. The src is percent-decoded+ * first (the renderer encodes non-ASCII, so a CJK file name arrives as `%E4%B8%AD…`), its query+ * and hash are dropped — `shot.png#v=2` is a cache-buster a model sometimes writes — and it is+ * then normalized exactly as a file link is (`toWorkspaceRelative`): `./` and empty segments+ * drop, an inner `..` pops, and an absolute path counts only when it lies inside the Session's+ * Workspace.+ * - `none` — the rest: a `..` that climbs out of the Workspace, an absolute path outside it, a+ * `~` path, an in-page `#…` reference, and a src the renderer emptied. Nothing in the App can+ * serve it.+ *+ * Existence is deliberately not checked, exactly like a file link: the file route answers 404 and+ * the browser shows its own broken-image state, which is the truth about that src.+ */+import { toWorkspaceRelative } from "./file-path";+import { isExternalRef } from "./reply-link";++export type ReplyImage = { kind: "external" } | { kind: "file"; path: string } | { kind: "none" };++const EXTERNAL: ReplyImage = { kind: "external" };+const NONE: ReplyImage = { kind: "none" };++function decode(text: string): string | null {+ try {+ return decodeURIComponent(text);+ } catch {+ return null;+ }+}++/** Sorts one image src from a conversation's Markdown; `workspace` is the Session's absolute Workspace path. */+export function resolveReplyImage(src: string | undefined, workspace: string | null): ReplyImage {+ if (src === undefined || src === "") return NONE;+ if (isExternalRef(src)) return EXTERNAL;+ // An in-page reference can only mean a place inside the rendered Markdown, never a file.+ if (src.startsWith("#")) return NONE;+ const decoded = decode(src.replace(/[?#].*$/, ""));+ if (decoded === null) return NONE;+ const path = toWorkspaceRelative(decoded, workspace);+ return path === null ? NONE : { kind: "file", path };+}diff --git a/packages/web/src/lib/reply-link.ts b/packages/web/src/lib/reply-link.tsindex 9c8fa104..388e8205 100644--- a/packages/web/src/lib/reply-link.ts+++ b/packages/web/src/lib/reply-link.ts@@ -36,6 +36,16 @@ export type ReplyLink =/** A URL scheme, as the URL parser reads one: a letter, then letters, digits, `+`, `.` or `-`, then `:`. */const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;+/**+ * Whether a reference names another site rather than a file of the Workspace: it carries a scheme+ * (`https:`, `mailto:`, `data:`, …) or is protocol-relative (`//host`). Shared with the image+ * resolver (reply-image.ts), which sorts an image src by exactly this rule — one copy, so a link+ * and the picture beside it never disagree about what counts as external.+ */+export function isExternalRef(ref: string): boolean {+ return ref.startsWith("//") || SCHEME_RE.test(ref);+}+const EXTERNAL: ReplyLink = { kind: "external" };const NONE: ReplyLink = { kind: "none" };@@ -54,7 +64,7 @@ export function resolveReplyLink(href: string | undefined, workspace: string | nconst id = decode(href.slice(1));return id === null || id === "" ? NONE : { kind: "anchor", id };}- if (href.startsWith("//") || SCHEME_RE.test(href)) return EXTERNAL;+ if (isExternalRef(href)) return EXTERNAL;const decoded = decode(href.replace(/[?#].*$/, ""));if (decoded === null) return NONE;const path = toWorkspaceRelative(decoded, workspace);diff --git a/packages/web/test/md.test.ts b/packages/web/test/md.test.tsindex 57434121..70a9db99 100644--- a/packages/web/test/md.test.ts+++ b/packages/web/test/md.test.ts@@ -3,20 +3,23 @@* (node env, no DOM):* - outside a conversation every link — explicit [text](url), bare autolinked URL (remark-gfm),* relative or #anchor — opens in a new tab: target="_blank" + rel="noreferrer";- * - inside one (WorkspaceLinksProvider, features/chat/workspace-links.tsx, as MessageStream+ * - inside one (WorkspaceRefsProvider, features/chat/workspace-refs.tsx, as MessageStream* renders it) only an external link does:* a link to a Workspace file, an #anchor and a relative href with nowhere to go render without* a target, because a relative href resolves against the SPA's own route. What their clicks do* is covered in reply-link.test.ts — static markup carries no handlers;* - fenced code still routes through the module-scope pre override into CodeBlock (its chrome- * renders; Shiki only loads in an effect, which static markup never runs).+ * renders; Shiki only loads in an effect, which static markup never runs);+ * - an image whose src names a Workspace file is fetched from that Session's file route, while an+ * external or unresolvable src keeps the one the Markdown wrote. How a src is sorted is+ * reply-image.test.ts.*/import { describe, expect, it, vi } from "vitest";import { createElement } from "react";import type { MouseEvent } from "react";import { renderToStaticMarkup } from "react-dom/server";import { Md } from "@adelie/ui";-import { WorkspaceLinksProvider } from "../src/features/chat/workspace-links";+import { WorkspaceRefsProvider } from "../src/features/chat/workspace-refs";import { replyLinkBehavior, resolveReplyLink } from "../src/lib/reply-link";const render = (text: string, streaming = false) =>@@ -35,9 +38,12 @@ const renderWithOpener = (streaming = false,) =>renderToStaticMarkup(- createElement(WorkspaceLinksProvider, {+ createElement(WorkspaceRefsProvider, {workspace: WS,onOpenFile,+ // A conversation serves a picture out of its own file route; reply-image.test.ts covers+ // how a src is sorted, this file covers that the src reaching the DOM is that one.+ fileUrl: (path) => `/api/sessions/s1/files/raw?path=${encodeURIComponent(path)}`,children: createElement(Md, { text, streaming }),}),);@@ -48,6 +54,10 @@ const renderInConversation = (text: string, streaming = false) =>/** All rendered <a ...> opening tags. */const anchors = (html: string) => html.match(/<a\b[^>]*>/g) ?? [];+/** The src attribute of every rendered <img>, as react-dom escaped it. */+const images = (html: string) =>+ (html.match(/<img\b[^>]*>/g) ?? []).map((tag) => /src="([^"]*)"/.exec(tag)?.[1] ?? "");+/** The href attribute of a rendered opening tag, as react-dom escaped it. */const hrefOf = (tag: string | undefined) => /href="([^"]*)"/.exec(tag ?? "")?.[1];@@ -177,6 +187,37 @@ describe("Md links inside a conversation", () => {});});+describe("Md images", () => {+ it("a picture of the Workspace is fetched from the Session's file route", () => {+ const srcs = images(renderInConversation(""));+ expect(srcs).toHaveLength(1);+ expect(srcs[0]).toBe("/api/sessions/s1/files/raw?path=shots%2Fcat.png");+ });++ it("a src the browser can fetch itself keeps what the Markdown wrote", () => {+ const srcs = images(+ renderInConversation(" "),+ );+ expect(srcs).toEqual(["https://example.com/a.png", "//cdn.example.com/b.png"]);+ // The pipeline empties `data:` — react-markdown trusts no scheme it does not know — so what a+ // data URL arrives as is ""; the resolver is never asked (reply-image.test.ts sorts that).+ expect(images(renderInConversation(""))).toEqual([""]);+ });++ it("a src with nowhere to go keeps the written one, as a broken picture", () => {+ const srcs = images(renderInConversation(""));+ expect(srcs).toEqual(["../../etc/passwd.png"]);+ });++ it("renders in both streaming and settled maps", () => {+ for (const streaming of [true, false]) {+ expect(images(renderInConversation("", streaming))).toEqual([+ "/api/sessions/s1/files/raw?path=x.png",+ ]);+ }+ });+});+describe("Md code blocks", () => {it("fenced code still renders through the CodeBlock pre override", () => {const html = render("```js\nconst a = 1;\n```");diff --git a/packages/web/test/reply-image.test.ts b/packages/web/test/reply-image.test.tsnew file mode 100644index 00000000..666a3b81--- /dev/null+++ b/packages/web/test/reply-image.test.ts@@ -0,0 +1,85 @@+/**+ * reply-image.ts: how an image src in a conversation's Markdown is sorted. The srcs here are the+ * shapes the renderer actually hands the image adapter — micromark percent-encodes non-ASCII, and+ * react-markdown empties any scheme it does not trust — which md.test.ts pins through the real+ * pipeline.+ */+import { describe, expect, it } from "vitest";+import { resolveReplyImage } from "../src/lib/reply-image";++const WS = "/home/user/workspaces/tmp-1";++describe("resolveReplyImage", () => {+ it("a relative src is a Workspace file", () => {+ expect(resolveReplyImage("shot.png", WS)).toEqual({ kind: "file", path: "shot.png" });+ expect(resolveReplyImage("shots/cat.png", WS)).toEqual({ kind: "file", path: "shots/cat.png" });+ });++ it("a leading ./ and inner . segments drop", () => {+ expect(resolveReplyImage("./shot.png", WS)).toEqual({ kind: "file", path: "shot.png" });+ expect(resolveReplyImage("./sub/./a.png", WS)).toEqual({ kind: "file", path: "sub/a.png" });+ });++ it("percent-encoding is decoded, so CJK and spaced names resolve to the name on disk", () => {+ expect(resolveReplyImage("%E9%B9%88%E9%B9%95.png", WS)).toEqual({+ kind: "file",+ path: "鹈鹕.png",+ });+ expect(resolveReplyImage("shots/%E7%8C%AB%20v2.png", WS)).toEqual({+ kind: "file",+ path: "shots/猫 v2.png",+ });+ });++ it("a cache-busting query or hash is ignored for the lookup", () => {+ expect(resolveReplyImage("shot.png?v=2", WS)).toEqual({ kind: "file", path: "shot.png" });+ expect(resolveReplyImage("shot.png#crop", WS)).toEqual({ kind: "file", path: "shot.png" });+ expect(resolveReplyImage("?v=2", WS)).toEqual({ kind: "none" });+ });++ it("a .. that climbs out of the Workspace goes nowhere; one that stays inside pops", () => {+ expect(resolveReplyImage("../secret.png", WS)).toEqual({ kind: "none" });+ expect(resolveReplyImage("a/../b.png", WS)).toEqual({ kind: "file", path: "b.png" });+ });++ it("an absolute path counts inside the Workspace and nowhere else", () => {+ expect(resolveReplyImage(`${WS}/shots/cat.png`, WS)).toEqual({+ kind: "file",+ path: "shots/cat.png",+ });+ expect(resolveReplyImage("/home/user/elsewhere/cat.png", WS)).toEqual({ kind: "none" });+ // A drive letter is a scheme as the URL parser reads one, exactly as it is for a link — and+ // the renderer empties such a path before the adapter ever sees it.+ expect(resolveReplyImage("C:\\ws\\shots\\cat.png", "C:/ws")).toEqual({ kind: "external" });+ });++ it("a scheme or a protocol-relative host is the browser's own business", () => {+ for (const src of [+ "https://example.com/a.png",+ "http://example.com/a.png",+ "data:image/png;base64,AA",+ "blob:http://localhost:4000/abc",+ "//cdn.example.com/a.png",+ ]) {+ expect(resolveReplyImage(src, WS)).toEqual({ kind: "external" });+ }+ });++ it("an in-page reference, an emptied src and a missing one go nowhere", () => {+ expect(resolveReplyImage("#crop", WS)).toEqual({ kind: "none" });+ expect(resolveReplyImage("", WS)).toEqual({ kind: "none" });+ expect(resolveReplyImage(undefined, WS)).toEqual({ kind: "none" });+ // react-markdown empties the schemes it does not trust, drive-letter paths included, so the+ // adapter is handed "" rather than a path it could resolve.+ expect(resolveReplyImage("", "C:/ws")).toEqual({ kind: "none" });+ });++ it("with no Workspace a relative src still names a path inside it — the same answer a link gets", () => {+ // Nothing here doubles as a check that the Workspace exists: a relative src means "a file of+ // this Session's Workspace" whatever that directory turns out to be, and a surface with no+ // Session to read from installs no resolver at all (workspace-refs.tsx).+ expect(resolveReplyImage("shot.png", null)).toEqual({ kind: "file", path: "shot.png" });+ expect(resolveReplyImage("https://example.com/a.png", null)).toEqual({ kind: "external" });+ expect(resolveReplyImage("/home/user/elsewhere/cat.png", null)).toEqual({ kind: "none" });+ });+});diff --git a/plugins/use-seedream/plugin.json b/plugins/use-seedream/plugin.jsonindex 97746f6e..e0211137 100644--- a/plugins/use-seedream/plugin.json+++ b/plugins/use-seedream/plugin.json@@ -3,6 +3,6 @@"description_zh": "用火山方舟的豆包 Seedream 模型把提示词生成成图片,落到工作区。运行时是一个零依赖的 Node 脚本,走同步的图片生成接口:参考图内联成 base64、一次请求出组图、按图层拆分出一张底图加若干透明 PNG 图层;每个文件先落临时路径、写完才改名,最后打一行 JSON,给出绝对路径、按 z 排序的图层与耗时。密钥从密钥库以 ARK_API_KEY 注入,不落盘。","short_description": "Generate images from a prompt with Ark Doubao Seedream, saved into the workspace.","short_description_zh": "用火山方舟豆包 Seedream 按提示词生成图片并落到工作区。",- "version": "2026.10.28.1",+ "version": "2026.10.29.1","category": "office-productivity"}diff --git a/plugins/use-seedream/skills/seedream/SKILL.md b/plugins/use-seedream/skills/seedream/SKILL.mdindex 7854c549..700dfbf6 100644--- a/plugins/use-seedream/skills/seedream/SKILL.md+++ b/plugins/use-seedream/skills/seedream/SKILL.md@@ -122,15 +122,17 @@ may already have been billed. Read the `upstream` field before saying anything a## Handing the result to the user-Give the user the files, not a base64 blob — and give them as paths, not as Markdown images:+Give the user the picture itself, not a base64 blob:-- Save them into the workspace (the default output already does) and name each one in your reply- by its workspace-relative path in backticks, with the model that made it. Markdown image syntax- (``) does **not** resolve in the chat — it points at the web app's own origin,- not at the workspace — so the user opens the file from the Files panel instead.+- Save it into the workspace (the default output already does) and show it with Markdown image+ syntax — ``, the workspace-relative path. A reply's image src is+ resolved against the conversation's workspace, so the picture renders in the chat. Name the+ model that made it in the sentence around it, and keep the path in backticks too when the user+ may want to open it in the Files panel.- For a layer split, show the base image as the preview and mention that the transparent layerssit beside it — a PNG viewer that stacks by filename order will not reassemble them, so say the- layers are separate files.+ layers are separate files (one image per layer is a wall of pictures in the chat; list the+ layers by path instead).- Keep `request_id` in your reply when the user may ask about the request later; the same seedplus the same options is a reproducible take.