A local-first multi-agent app development platform, built on PenguinHarness
fix(web,server): the Files panel refreshes after every turn, and SVG renders (#460)
Yaowei Zheng845baa807d83
diff --git a/changelog/unreleased/2026-08-24-file-preview-svg-refresh.md b/changelog/unreleased/2026-08-24-file-preview-svg-refresh.mdnew file mode 100644index 00000000..b5ffa74d--- /dev/null+++ b/changelog/unreleased/2026-08-24-file-preview-svg-refresh.md@@ -0,0 +1,47 @@+# The Files panel refreshes after every turn, and SVG renders++- **Date:** 2026-08-24+- **Type:** fix+- **Scope:** `web`, `server`+- **PR:** [#460](https://github.com/Prism-Shadow/penguin-harness/pull/460)++[中文版](2026-08-24-file-preview-svg-refresh.zh.md)++Three things were wrong with the Web App's Files panel: it went stale the moment the Agent+wrote anything, `.svg` was a broken image everywhere it appeared, and a Markdown file with an+SVG in it could shake without settling.++## The listing and the open file re-read when a turn settles++The panel refreshed on mount, on navigation, and when it went from hidden to visible — never+on the one event that changes a Workspace: a Task ending. It now re-reads on that edge (the+same active→idle transition that reloads the session and agent lists), and so does whatever+file is open in the preview: watching a file the Agent is editing is why the panel sits next+to the conversation.++A re-read leaves the user's own state alone — the rendered/source choice stays, the mobile+sheet does not jump — and a re-read that fails (the file was deleted mid-turn) keeps the+preview that is on screen instead of replacing it with "unsupported". Image and PDF previews+remount so the bytes are actually re-fetched, images inside a Markdown preview carry the read+number so a rewritten diagram repaints, and `/files/content` is now `Cache-Control: no-store`+— a Workspace path holds whatever the Agent last wrote to it.++## SVG renders again++Inline `/files/content` downgraded every scriptable type to `text/plain` as a same-origin XSS+defense, which covers HTML but also made every `.svg` — as a preview and as an `<img>` inside+a Markdown preview — a broken image. SVG now keeps `image/svg+xml` inline: an `<img>` never+runs an SVG's scripts. What the real type re-opens is a direct visit to that URL rendering it+as a same-origin document, and a `Content-Security-Policy: sandbox` (no `allow-scripts`, no+`allow-same-origin`) closes that — the sandbox directive is ignored for a subresource, so the+`<img>` path is unaffected. HTML keeps its plain-text downgrade. Benchmark case material,+which is browsed the same way, gets the same treatment.++## The shake++An SVG carries no pixel size, so its rendered height is whatever its width divides to — which+makes the preview's content height a function of whether a scrollbar is present. That closes a+loop: content overflows → the scrollbar takes width → the image shrinks → content fits → the+scrollbar goes → content overflows again, forever. The preview's scroll container now reserves+the gutter (`scrollbar-gutter: stable`), which breaks the feedback path; it is inert where+scrollbars are overlays.diff --git a/changelog/unreleased/2026-08-24-file-preview-svg-refresh.zh.md b/changelog/unreleased/2026-08-24-file-preview-svg-refresh.zh.mdnew file mode 100644index 00000000..d4a97479--- /dev/null+++ b/changelog/unreleased/2026-08-24-file-preview-svg-refresh.zh.md@@ -0,0 +1,38 @@+# 文件面板每轮对话后自动刷新,SVG 也能渲染了++- **Date:** 2026-08-24+- **Type:** fix+- **Scope:** `web`, `server`+- **PR:** [#460](https://github.com/Prism-Shadow/penguin-harness/pull/460)++[English](2026-08-24-file-preview-svg-refresh.md)++Web App 的文件面板有三处毛病:Agent 一写文件它就过期、`.svg` 出现在哪里都是一张裂图、带 SVG 的+Markdown 打开后会持续抖动。++## 一轮结束即重读列表与打开中的文件++此前面板只在挂载、目录跳转、以及从隐藏转为可见时刷新——唯独不在真正会改变 Workspace 的那个时刻:+一轮 Task 结束。现在它在该边沿重读(与刷新会话列表、Agent 列表的 active→idle 同一个转换),预览中+打开的文件同样重读:把面板放在对话旁边,为的就是看着 Agent 改文件。++重读不碰用户自己的状态——渲染/源码的选择保持不变,移动端抽屉不会跳起——重读失败(文件在这一轮里被+删掉)时保留屏幕上已有的预览,而不是把它换成「不支持的类型」。图片与 PDF 预览重新挂载以真正重新取+字节,Markdown 预览里的图片带上本次读取序号,被改写的图示因此会重绘;`/files/content` 也改为+`Cache-Control: no-store`——Workspace 的一个路径,装的就是 Agent 最后写进去的东西。++## SVG 恢复渲染++内联的 `/files/content` 出于同源 XSS 防御,把所有可执行脚本的类型降级为 `text/plain`。这对 HTML+成立,却也让每一个 `.svg`——无论作为预览还是作为 Markdown 预览里的 `<img>`——变成裂图。SVG 现在内+联保留 `image/svg+xml`:`<img>` 永远不会执行 SVG 里的脚本。真实类型重新打开的风险是**直接访问该+URL**时浏览器把它当同源文档渲染,`Content-Security-Policy: sandbox`(不给 `allow-scripts`、不给+`allow-same-origin`)堵住这一条;sandbox 指令对子资源不生效,`<img>` 这条路径不受影响。HTML 维持+纯文本降级。以同样方式浏览的 Benchmark 用例素材同步处理。++## 抖动++SVG 不带像素尺寸,渲染高度完全由宽度按比例换算——于是预览的内容高度成了「有没有滚动条」的函数。这+形成一个闭环:内容溢出 → 滚动条占去宽度 → 图片变矮 → 内容装得下 → 滚动条消失 → 再次溢出,如此往+复。预览的滚动容器现在恒定预留滚动条槽位(`scrollbar-gutter: stable`),把这条反馈路径切断;在滚+动条本就悬浮的平台上该属性不产生任何影响。diff --git a/packages/server/src/http/routes/benchmarks.ts b/packages/server/src/http/routes/benchmarks.tsindex ac7923c9..84eeb168 100644--- a/packages/server/src/http/routes/benchmarks.ts+++ b/packages/server/src/http/routes/benchmarks.ts@@ -58,12 +58,17 @@ function readCaseFile(deps: AppDeps, material: CaseMaterial) {material,boundedPreview ? { maxBytes: TEXT_PREVIEW_BYTES } : undefined,);+ // Case material is browsed the same way a Workspace is, and gets the same inline+ // hardening (see the session file-content route for the reasoning behind each branch).+ const inertSvg = !download && scriptable === "svg";return new Response(new Uint8Array(data), {status: 200,headers: {- "Content-Type": !download && scriptable ? "text/plain; charset=utf-8" : contentType,+ "Content-Type":+ !download && scriptable === "html" ? "text/plain; charset=utf-8" : contentType,"Content-Disposition": `${download ? "attachment" : "inline"}; filename*=UTF-8''${encodeURIComponent(fileName)}`,"X-Content-Type-Options": "nosniff",+ ...(inertSvg ? { "Content-Security-Policy": "sandbox" } : {}),...(truncated ? { "X-Content-Truncated": "1" } : {}),},});diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex d7866c8f..6c15a95e 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -1201,24 +1201,36 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {rel,);const disposition = download ? "attachment" : "inline";- // Same-origin XSS defense: html/svg inline previews are always returned as plain- // text (Workspace files may be Agent-generated and untrusted); downloads- // (attachment) keep the real content type, and sandboxed previews keep it under the- // CSP above. Paired with nosniff to prevent MIME sniffing from undoing this.+ // Same-origin XSS defense: an inline HTML preview is always returned as plain text+ // (Workspace files may be Agent-generated and untrusted); downloads (attachment) keep+ // the real content type, and sandboxed previews keep it under the CSP above. Paired+ // with nosniff to prevent MIME sniffing from undoing this.+ // An SVG is a document AND an image. Downgrading it to text/plain made every <img> in a+ // Markdown preview (and every .svg preview) a broken image, so it keeps its real type —+ // an image never runs the SVG's scripts. What the type does re-open is a DIRECT+ // navigation to this URL, where the browser would render it as a same-origin document:+ // the sandbox CSP closes that (no allow-scripts, no allow-same-origin — opaque origin,+ // no script execution), and CSP sandbox is ignored for a subresource, so the <img> path+ // is unaffected.+ const inertSvg = !download && !preview && scriptable === "svg";const effectiveType =- !download && scriptable && !preview ? "text/plain; charset=utf-8" : contentType;+ !download && scriptable === "html" && !preview ? "text/plain; charset=utf-8" : contentType;return new Response(new Uint8Array(data), {status: 200,headers: {"Content-Type": effectiveType,"Content-Disposition": `${disposition}; filename*=UTF-8''${encodeURIComponent(fileName)}`,"X-Content-Type-Options": "nosniff",+ // A Workspace file is whatever the Agent last wrote to that path. Letting a browser+ // cache it by URL is how a re-read after a settled turn paints the previous version.+ "Cache-Control": "no-store",...(preview && scriptable? {"Content-Security-Policy":"sandbox allow-scripts allow-popups allow-modals allow-forms",}: {}),+ ...(inertSvg ? { "Content-Security-Policy": "sandbox" } : {}),},});});diff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.tsindex 5034c61d..a1c339b9 100644--- a/packages/server/src/services/workspace-files-service.ts+++ b/packages/server/src/services/workspace-files-service.ts@@ -46,8 +46,14 @@ export interface WorkspaceFileContent {data: Buffer;fileName: string;contentType: string;- /** Types whose same-origin inline rendering would execute scripts (html/svg): inline preview must fall back to plain text. */- scriptable: boolean;+ /**+ * Which kind of scriptable document this is, or false. Both kinds would execute scripts if+ * a browser rendered them as a same-origin document, but they need different inline+ * handling: `"html"` falls back to plain text, while `"svg"` keeps its real type so an+ * `<img>` can render it (an image never runs the SVG's scripts) and is served with a+ * sandbox CSP so a direct navigation to it stays inert. See the file-content routes.+ */+ scriptable: "html" | "svg" | false;/** True when a bounded preview returned only the beginning of the file. */truncated?: boolean;}@@ -276,7 +282,7 @@ export class WorkspaceFilesService {data,fileName: path.basename(file),contentType: CONTENT_TYPES[ext] ?? "application/octet-stream",- scriptable: ext === ".html" || ext === ".htm" || ext === ".svg",+ scriptable: ext === ".html" || ext === ".htm" ? "html" : ext === ".svg" ? "svg" : false,...(truncated ? { truncated: true } : {}),};}diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.tsindex 305c8bdd..fd641fa2 100644--- a/packages/server/test/workspace-files.test.ts+++ b/packages/server/test/workspace-files.test.ts@@ -185,6 +185,42 @@ describe("files/stat route (batch existence check)", () => {expect(txt.headers.get("content-security-policy")).toBeNull();});+ it("files/content on svg: inline keeps image/svg+xml under a sandbox CSP, so an <img> renders it and a direct visit stays inert", async () => {+ await fs.writeFile(+ path.join(workspace, "chart.svg"),+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><script>1</script></svg>',+ );+ const url = `/api/sessions/${sessionId}/files/content?path=chart.svg`;++ // The real type is what makes it renderable at all: downgraded to text/plain, every+ // <img> pointing at it — a Markdown preview's included — was a broken image.+ const inline = await owner.get(url);+ expect(inline.status).toBe(200);+ expect(inline.headers.get("content-type")).toContain("image/svg+xml");+ // What the type re-opens is a direct visit rendering it as a same-origin document:+ // the sandbox denies both scripting and the origin, and is ignored for a subresource.+ const csp = inline.headers.get("content-security-policy") ?? "";+ expect(csp).toContain("sandbox");+ expect(csp).not.toContain("allow-scripts");+ expect(csp).not.toContain("allow-same-origin");+ expect(inline.headers.get("x-content-type-options")).toBe("nosniff");++ // A download is an attachment either way — nothing renders it, so no CSP is needed.+ const download = await owner.get(`${url}&download=1`);+ expect(download.headers.get("content-type")).toContain("image/svg+xml");+ expect(download.headers.get("content-security-policy")).toBeNull();++ // HTML keeps its own handling: still plain text inline.+ await fs.writeFile(path.join(workspace, "p.html"), "<b>x</b>");+ const html = await owner.get(`/api/sessions/${sessionId}/files/content?path=p.html`);+ expect(html.headers.get("content-type")).toContain("text/plain");+ });++ it("files/content is never cached: the path holds whatever the Agent last wrote", async () => {+ const res = await owner.get(`/api/sessions/${sessionId}/files/content?path=a.txt`);+ expect(res.headers.get("cache-control")).toBe("no-store");+ });+it("existing files return in order, deduplicated; missing / directory / out-of-bounds all count as nonexistent, always 200", async () => {const res = await owner.post(`/api/sessions/${sessionId}/files/stat`, {paths: ["sub/b.md", "a.txt", "sub/b.md", "nope.txt", "sub", "../escape.txt", "/etc/passwd"],diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex ceb967b4..a0fdf601 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -665,6 +665,8 @@ export function ChatPage() {id: selectedSessionId,state: "idle",});+ /** Settled-turn counter handed to the Files panel; every bump means "re-read". */+ const [filesReloadSignal, setFilesReloadSignal] = useState(0);useEffect(() => {const prev = prevTaskRef.current;const sameSession = prev.id === selectedSessionId;@@ -676,6 +678,11 @@ export function ChatPage() {if (prev.state !== "idle" && stream.taskState === "idle") {void reloadSessions();void reloadAgents();+ // The turn that just ended is when the Agent's file writes landed: the Files panel's+ // listing and whatever it has open are stale from this moment on (see the browser's+ // reloadSignal). Same edge, same guard — a phantom "idle" from a detaching stream+ // never reaches here.+ setFilesReloadSignal((n) => n + 1);}}, [stream.taskState, selectedSessionId, reloadSessions, reloadAgents]);@@ -1485,7 +1492,12 @@ export function ChatPage() {);case "workspace":return (- <WorkspaceBrowser session={selected} openRequest={fileOpenRequest} active={active} />+ <WorkspaceBrowser+ session={selected}+ openRequest={fileOpenRequest}+ active={active}+ reloadSignal={filesReloadSignal}+ />);case "memory":return (diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex d23df1f2..72bf1815 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -149,6 +149,7 @@ export function WorkspaceBrowser({openRequest,active,onPreviewOpen,+ reloadSignal,}: {session: SessionInfo;/** External navigation command (from clicking a file chip in a message): navigates to the@@ -161,6 +162,13 @@ export function WorkspaceBrowser({active?: boolean;/** Callback when entering file preview (used by the mobile Sheet to raise its snap point to full). */onPreviewOpen?: () => void;+ /**+ * Bumped by the parent every time a Task settles on this session: the turn that just ended+ * is exactly when the Agent's writes land, so the listing — and whatever file is open in+ * the preview — is stale the moment it does. Any change of the number means "re-read",+ * so the initial value is irrelevant and no edge tracking is needed.+ */+ reloadSignal?: number;}) {// Whether the HTML preview lands on a separate origin. True routes both the in-app// rendered view and "open in new tab" through the preview origin; false downgrades@@ -211,7 +219,7 @@ export function WorkspaceBrowser({return () => {cancelled = true;};- }, [session.sessionId, path, reloadTick]);+ }, [session.sessionId, path, reloadTick, reloadSignal]);// Session switched: back to the root directory with no preview. Reset during render// (React's documented "adjust state when a prop changes" pattern), not in an effect —@@ -243,9 +251,17 @@ export function WorkspaceBrowser({const onPreviewOpenRef = useRef(onPreviewOpen);onPreviewOpenRef.current = onPreviewOpen;+ /**+ * Opens `filePath` in the preview. `refresh` re-reads a file already on screen (the+ * settled-turn refresh below): it must not touch the things that belong to the user's+ * hands — the mobile sheet's snap point, the rendered/source choice — and a failed+ * re-read leaves what is on screen alone instead of replacing a working preview with+ * "unsupported".+ */const previewPath = useCallback(- async (filePath: string) => {- onPreviewOpenRef.current?.();+ async (filePath: string, opts?: { refresh?: boolean }) => {+ const refresh = opts?.refresh === true;+ if (!refresh) onPreviewOpenRef.current?.();const name = filePath.includes("/")? filePath.slice(filePath.lastIndexOf("/") + 1): filePath;@@ -257,8 +273,10 @@ export function WorkspaceBrowser({const present = (p: Preview) => {if (nonce === previewSeq) setPreview(p);};- setRichView("rendered");- setSourceError(null);+ if (!refresh) {+ setRichView("rendered");+ setSourceError(null);+ }if (IMAGE_EXTS.has(ext)) {present({ path: filePath, name, kind: "image", nonce });return;@@ -296,7 +314,9 @@ export function WorkspaceBrowser({// Oversized Markdown defaults to the source view (benefiting from the unhighlighted// highlight=false path): feeding the whole block to remark for parsing is a one-time// main-thread cost; the user can still manually switch to "rendered view" as an informed choice.- if (isMd && full.length > HIGHLIGHT_LIMIT && nonce === previewSeq) setRichView("source");+ if (!refresh && isMd && full.length > HIGHLIGHT_LIMIT && nonce === previewSeq) {+ setRichView("source");+ }present({path: filePath,name,@@ -306,7 +326,9 @@ export function WorkspaceBrowser({nonce,});} catch {- present({ path: filePath, name, kind: "unsupported", nonce });+ // A re-read that fails (the Agent deleted the file mid-turn, a blip) keeps the+ // preview the user is looking at; only a fresh open reports it as unsupported.+ if (!refresh) present({ path: filePath, name, kind: "unsupported", nonce });}},[session.sessionId],@@ -349,6 +371,21 @@ export function WorkspaceBrowser({};}, [preview, richView, previewIsolated, session.sessionId]);+ // The same settled-turn signal re-reads whatever is open in the preview: watching a file+ // the Agent is editing is the reason this panel sits next to the conversation. Skipped on+ // the first run (the mount already read it) and while no preview is open. Reading the path+ // from a ref keeps this effect keyed on the signal alone — depending on `preview` would+ // re-run it on every preview change and re-read a file that was just read.+ const previewPathRef = useRef<string | null>(null);+ previewPathRef.current = preview?.path ?? null;+ const lastReloadSignal = useRef(reloadSignal);+ useEffect(() => {+ if (reloadSignal === lastReloadSignal.current) return;+ lastReloadSignal.current = reloadSignal;+ const open = previewPathRef.current;+ if (open !== null) void previewPath(open, { refresh: true });+ }, [reloadSignal, previewPath]);+// External navigation command (clicking a file chip in a message / a file card): navigates to// the directory and previews the target path. Also refreshes the list: the target is most// likely a file the Agent just wrote, so the cached list is very likely stale; and when it's@@ -503,15 +540,26 @@ export function WorkspaceBrowser({{S.files.download}</a></div>- <div className="min-h-0 flex-1 overflow-auto p-3">+ {/* scrollbar-gutter: an SVG carries no pixel size, so its height is whatever its width+ divides to — which makes the content height a function of the scrollbar's presence.+ Without a reserved gutter that closes a loop: content overflows -> scrollbar takes+ width -> the image shrinks -> content fits -> scrollbar goes -> repeat, forever, as+ a visible shake. Reserving it always breaks the feedback path (and is inert where+ scrollbars are overlays). */}+ <div className="min-h-0 flex-1 overflow-auto p-3 [scrollbar-gutter:stable]">{preview.kind === "image" ? (+ // Keyed on the nonce like the isolated HTML iframe: the src alone is unchanged+ // when the same file is re-read, so only a remount re-requests the bytes the+ // Agent just rewrote.<img+ key={preview.nonce}src={api.workspaceFileUrl(session.sessionId, preview.path)}alt={preview.name}className="max-w-full rounded-md border border-gray-200 dark:border-gray-800"/>) : preview.kind === "pdf" ? (<iframe+ key={preview.nonce}src={api.workspaceFileUrl(session.sessionId, preview.path)}title={preview.name}className="h-full min-h-[60vh] w-full rounded-md border border-gray-200 dark:border-gray-800"@@ -569,14 +617,18 @@ export function WorkspaceBrowser({remarkPlugins={REMARK_PLUGINS}components={{// Relative images are resolved against the md file's directory into the file API (otherwise resolving against the app's origin would always 404).+ // `v` is the read nonce, not a cache-buster for its own sake: a+ // Workspace image is rewritten under the same path, and without it a+ // re-read of the Markdown would keep painting the previous bytes from+ // the browser's image cache.img: ({ src, alt }) => (<imgsrc={typeof src === "string" && !EXTERNAL_REF_RE.test(src)- ? api.workspaceFileUrl(+ ? `${api.workspaceFileUrl(session.sessionId,resolveRelative(dirOf(preview.path), src),- )+ )}&v=${preview.nonce}`: src}alt={alt ?? ""}