Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(attachments): send SVG inputs as files instead of model images (#969)

Liu Zhiyu1bc1a5d73bf2
diff --git a/apps/desktop/electron/main/composer-paste.ts b/apps/desktop/electron/main/composer-paste.ts
index 4acd1b539..56946b407 100644
--- a/apps/desktop/electron/main/composer-paste.ts
+++ b/apps/desktop/electron/main/composer-paste.ts
@@ -8,9 +8,11 @@ import {
} from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { basename, extname, isAbsolute, join } from "node:path";
-import type {
- ComposerPasteFile,
- ComposerPastedFile,
+import {
+ isSvgAttachment,
+ SVG_MIME_TYPE,
+ type ComposerPasteFile,
+ type ComposerPastedFile,
} from "@pi-desktop/shared";
const SAFE_SESSION_ID = /^[A-Za-z0-9_-]+$/;
@@ -31,6 +33,7 @@ const IMAGE_EXTENSIONS = new Set([
]);
const MIME_EXTENSIONS: Record<string, string> = {
+ [SVG_MIME_TYPE]: ".svg",
"image/gif": ".gif",
"image/jpeg": ".jpg",
"image/png": ".png",
@@ -62,6 +65,7 @@ function isImageMimeType(mimeType: string): boolean {
}
function isImageFile(name: string, mimeType: string): boolean {
+ if (isSvgAttachment(mimeType, name)) return false;
if (isImageMimeType(mimeType)) return true;
return IMAGE_EXTENSIONS.has(extname(name).toLowerCase());
}
@@ -126,10 +130,13 @@ export async function saveComposerPasteFiles(
if (totalBytes > MAX_TOTAL_BYTES) {
throw new Error(`pasted files are too large (maximum ${MAX_TOTAL_BYTES} bytes)`);
}
- const mimeType =
+ const suppliedMimeType =
typeof file.mimeType === "string" && file.mimeType.trim()
? file.mimeType.trim().toLowerCase()
: "application/octet-stream";
+ const mimeType = isSvgAttachment(suppliedMimeType, file.name)
+ ? SVG_MIME_TYPE
+ : suppliedMimeType;
return {
bytes,
mimeType,
diff --git a/apps/desktop/electron/main/prompt-attachments.ts b/apps/desktop/electron/main/prompt-attachments.ts
index 061ee5773..18f829cb8 100644
--- a/apps/desktop/electron/main/prompt-attachments.ts
+++ b/apps/desktop/electron/main/prompt-attachments.ts
@@ -21,6 +21,8 @@ import { isAbsolute, join, relative, resolve } from "node:path";
import {
ErrorCodes,
formatFileInsert,
+ isSvgAttachment,
+ SVG_MIME_TYPE,
MAX_INLINE_IMAGE_BYTES,
type AgentPromptAttachment,
type MessageAttachment,
@@ -86,7 +88,8 @@ function canonicalPath(path: string): string | undefined {
}
}
-function promptMimeType(path: string, supplied?: string): string {
+function promptMimeType(path: string, supplied?: string, name?: string): string {
+ if (isSvgAttachment(supplied, path, name)) return SVG_MIME_TYPE;
const value = supplied?.trim().toLowerCase();
if (value) return value;
const extension = path.split(".").at(-1)?.toLowerCase() ?? "";
@@ -97,7 +100,8 @@ function isImagePromptAttachment(
attachment: AgentPromptAttachment,
path: string,
): boolean {
- const mimeType = promptMimeType(path, attachment.mimeType);
+ const mimeType = promptMimeType(path, attachment.mimeType, attachment.name);
+ if (mimeType === SVG_MIME_TYPE) return false;
const extension = path.split(".").at(-1)?.toLowerCase() ?? "";
return (
attachment.kind === "image" ||
@@ -234,7 +238,7 @@ export async function preparePromptAttachments(
});
}
const name = attachment.name.trim() || source.absolute.split(/[\\/]/).at(-1) || "attachment";
- const mimeType = promptMimeType(source.absolute, attachment.mimeType);
+ const mimeType = promptMimeType(source.absolute, attachment.mimeType, name);
const isImage = isImagePromptAttachment(attachment, source.absolute);
if (!isImage) {
prepared.push({
@@ -245,7 +249,9 @@ export async function preparePromptAttachments(
...(mimeType !== "application/octet-stream" ? { mimeType } : {}),
...(Number.isFinite(attachment.size) ? { size: attachment.size } : {}),
},
- fallbackPath: displayPromptPath(source, projectPath),
+ fallbackPath: mimeType === SVG_MIME_TYPE && source.root === "attachment"
+ ? await fallbackPathForStoredAttachment(dataRoot, sessionId, source, name)
+ : displayPromptPath(source, projectPath),
});
continue;
}
diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjs
index 46a160fbd..cc9085ede 100644
--- a/apps/desktop/test/composer-paste-files.test.mjs
+++ b/apps/desktop/test/composer-paste-files.test.mjs
@@ -8,14 +8,14 @@ import { readMainSource } from "./helpers/main-source.mjs";
const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
-const [composer, api, main, attachments, saver, protocol, sidecar, picker] = await Promise.all([
+const [composer, api, main, attachments, saver, protocol, history, picker] = await Promise.all([
readComposerSource(),
read("../src/lib/api.ts"),
readMainSource(),
read("../electron/main/prompt-attachments.ts"),
read("../electron/main/composer-paste.ts"),
read("../../../packages/shared/src/protocol.ts"),
- read("../../../packages/agent-runtime/src/sidecar.ts"),
+ read("../../../packages/agent-runtime/src/attachment-history.ts"),
read("../electron/main/composer-picker.ts"),
]);
@@ -268,9 +268,9 @@ test("large image attachments avoid whole-file startup reads", () => {
assert.match(attachments, /const inline = supportsVision && size <= MAX_INLINE_IMAGE_BYTES/);
assert.match(attachments, /await copyFile\(source, target, fsConstants\.COPYFILE_EXCL\)/);
assert.doesNotMatch(attachments, /const bytes = readFileSync\(source\.absolute\)/);
- assert.match(sidecar, /const size = \(await stat\(canonical\)\)\.size/);
- assert.match(sidecar, /shouldInline && size <= MAX_INLINE_IMAGE_BYTES/);
- assert.match(sidecar, /await copyFile\(source, target, fsConstants\.COPYFILE_EXCL\)/);
+ assert.match(history, /const size = \(await stat\(canonical\)\)\.size/);
+ assert.match(history, /shouldInline && size <= MAX_INLINE_IMAGE_BYTES/);
+ assert.match(history, /await copyFile\(source, target, fsConstants\.COPYFILE_EXCL\)/);
});
test("paste results separate display names from unique storage paths", async () => {
diff --git a/apps/desktop/test/svg-attachments.test.mjs b/apps/desktop/test/svg-attachments.test.mjs
new file mode 100644
index 000000000..c5d192590
--- /dev/null
+++ b/apps/desktop/test/svg-attachments.test.mjs
@@ -0,0 +1,240 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { isAbsolute, join, relative } from "node:path";
+import test from "node:test";
+import { importComposerFiles, saveComposerPasteFiles } from "../electron/main/composer-paste.ts";
+import { appendPromptFallbackPaths, preparePromptAttachments } from "../electron/main/prompt-attachments.ts";
+
+const SVG_MIME = "image/svg+xml";
+const svg = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><text y="12">SVG regression</text></svg>');
+const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9z8AAAAASUVORK5CYII=", "base64");
+const sessionId = "svg-regression";
+
+async function fixture(t) {
+ const root = await mkdtemp(join(tmpdir(), "pi-svg attachments-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const data = join(root, "data");
+ const project = join(root, "project");
+ const scratch = join(data, "scratch", sessionId);
+ await Promise.all([mkdir(project, { recursive: true }), mkdir(scratch, { recursive: true })]);
+ return { root, data, project, scratch };
+}
+
+function assertInside(root, path) {
+ const child = relative(root, path);
+ assert.ok(child && !child.startsWith("..") && !isAbsolute(child), path);
+}
+
+for (const [name, mimeType, expectedName] of [
+ ["diagram.svg", SVG_MIME, "diagram.svg"],
+ ["pasted-diagram", SVG_MIME, "pasted-diagram.svg"],
+ ["", " IMAGE/SVG+XML ; charset=UTF-8 ", "pasted-file-1.svg"],
+ ["diagram.SVG", "", "diagram.SVG"],
+ ["diagram.svg", "application/octet-stream", "diagram.svg"],
+ ["diagram.svg", "image/png", "diagram.svg"],
+ ["diagram.png", SVG_MIME, "diagram.png"],
+]) {
+ test(`SVG paste stays a readable file: ${JSON.stringify([name, mimeType])}`, async (t) => {
+ const { data } = await fixture(t);
+ const input = { name, mimeType, data: new Uint8Array(svg) };
+ const before = structuredClone(input);
+ const [saved] = await saveComposerPasteFiles(data, sessionId, [input]);
+ assert.equal(saved.kind, "file");
+ assert.equal(saved.mimeType, SVG_MIME);
+ assert.equal(saved.name, expectedName);
+ assert.deepEqual(await readFile(saved.path), svg);
+ const prepared = await preparePromptAttachments(data, sessionId, undefined, [saved], true);
+ assert.equal(prepared[0].message.kind, "file");
+ assert.equal(prepared[0].inlineData, undefined);
+ assert.equal(prepared[0].message.mimeType, SVG_MIME);
+ assert.ok(appendPromptFallbackPaths("Explain this diagram", prepared).includes(saved.path));
+ assert.deepEqual(input, before);
+ });
+}
+
+test("picker import and project-path drop use the same SVG fallback", async (t) => {
+ const { data, project } = await fixture(t);
+ const source = join(project, "diagram.SVG");
+ await writeFile(source, svg);
+ const [picked] = await importComposerFiles(data, sessionId, [source]);
+ assert.equal(picked.kind, "file");
+ assert.equal(picked.mimeType, SVG_MIME);
+ assert.deepEqual(await readFile(picked.path), svg);
+ const dropped = { path: source, name: "diagram.SVG", kind: "image", mimeType: "image/png" };
+ for (const supportsVision of [false, true]) {
+ const prepared = await preparePromptAttachments(data, sessionId, project, [picked, dropped], supportsVision);
+ assert.ok(prepared.every((item) => item.message.kind === "file" && item.inlineData === undefined));
+ assert.ok(prepared.every((item) => item.message.mimeType === SVG_MIME));
+ assert.ok(appendPromptFallbackPaths("Explain both", prepared).includes("diagram.SVG"));
+ }
+ assert.deepEqual(await readFile(source), svg);
+});
+
+test("legacy content-store SVG retries produce a session-readable file, not an image", async (t) => {
+ const { data, scratch } = await fixture(t);
+ const ref = `attachments/${createHash("sha256").update(svg).digest("hex")}`;
+ await mkdir(join(data, "attachments"));
+ await writeFile(join(data, ref), svg);
+ for (const metadata of [
+ { name: "pasted-diagram.bin", mimeType: SVG_MIME },
+ { name: "diagram.svg", mimeType: "image/png" },
+ ]) {
+ const attachment = { kind: "image", path: ref, ...metadata };
+ const before = structuredClone(attachment);
+ const [prepared] = await preparePromptAttachments(data, sessionId, undefined, [attachment], true);
+ assert.equal(prepared.message.kind, "file");
+ assert.equal(prepared.message.ref, ref);
+ assert.equal(prepared.message.mimeType, SVG_MIME);
+ assert.equal(prepared.inlineData, undefined);
+ assertInside(scratch, prepared.fallbackPath);
+ assert.deepEqual(await readFile(prepared.fallbackPath), svg);
+ assert.deepEqual(attachment, before);
+ }
+ assert.deepEqual(await readFile(join(data, ref)), svg);
+});
+
+test("mixed SVG and PNG paste keeps PNG image bytes and SVG file references", async (t) => {
+ const { data } = await fixture(t);
+ const saved = await saveComposerPasteFiles(data, sessionId, [
+ { name: "diagram.svg", mimeType: SVG_MIME, data: svg },
+ { name: "pixel.png", mimeType: "image/png", data: png },
+ ]);
+ const prepared = await preparePromptAttachments(data, sessionId, undefined, saved, true);
+ assert.deepEqual(prepared.map((item) => item.message.kind), ["file", "image"]);
+ assert.equal(prepared[0].inlineData, undefined);
+ assert.equal(prepared[1].message.mimeType, "image/png");
+ assert.deepEqual(Buffer.from(prepared[1].inlineData, "base64"), png);
+ const text = appendPromptFallbackPaths("Compare", prepared);
+ assert.ok(text.startsWith("Compare\n"));
+ assert.ok(text.includes(saved[0].path));
+ assert.ok(!text.includes(saved[1].path));
+ const nonVision = await preparePromptAttachments(data, sessionId, undefined, saved, false);
+ assert.ok(nonVision.every((item) => item.inlineData === undefined));
+ assert.ok(appendPromptFallbackPaths("Compare", nonVision).includes(saved[1].path));
+});
+
+test("SVG classification does not bypass attachment roots or mutate failed input", async (t) => {
+ const { data, project, root } = await fixture(t);
+ const outside = join(root, "outside.svg");
+ await writeFile(outside, svg);
+ const attachment = { kind: "image", path: outside, name: "outside.svg", mimeType: SVG_MIME };
+ const before = structuredClone(attachment);
+ await assert.rejects(
+ preparePromptAttachments(data, sessionId, project, [attachment], true),
+ { errorCode: "PATH_OUTSIDE_WORKSPACE" },
+ );
+ assert.deepEqual(attachment, before);
+ assert.deepEqual(await readFile(outside), svg);
+ const link = join(project, "escape.svg");
+ try {
+ await symlink(outside, link);
+ } catch (error) {
+ if (error.code === "EPERM" || error.code === "EACCES") return;
+ throw error;
+ }
+ await assert.rejects(
+ preparePromptAttachments(data, sessionId, project, [{ ...attachment, path: link }], true),
+ { errorCode: "PATH_OUTSIDE_WORKSPACE" },
+ );
+});
+
+// The history service is imported without booting a sidecar or using a provider.
+const { hydrateAttachmentHistory } = await import("../../../packages/agent-runtime/src/attachment-history.ts");
+
+test("restoring legacy SVG history strips image data and keeps a readable scratch fallback", async (t) => {
+ const { data, project, scratch } = await fixture(t);
+ const attachmentsDir = join(data, "attachments");
+ await mkdir(attachmentsDir);
+ const svgRef = `attachments/${createHash("sha256").update(svg).digest("hex")}`;
+ const pngRef = `attachments/${createHash("sha256").update(png).digest("hex")}`;
+ await Promise.all([writeFile(join(data, svgRef), svg), writeFile(join(data, pngRef), png)]);
+ const history = [{
+ id: "legacy-user", role: "user", content: "Explain the diagram", ts: 1,
+ attachments: [
+ { kind: "image", name: "pasted-diagram.bin", mimeType: " IMAGE/SVG+XML ; charset=utf-8", ref: svgRef, data: svg.toString("base64") },
+ { kind: "image", name: "pixel.png", mimeType: "image/png", ref: pngRef },
+ ],
+ }];
+ const before = structuredClone(history);
+ const [restored] = await hydrateAttachmentHistory(history, {
+ scratchDir: scratch, projectPath: project, attachmentsDir, supportsVision: true,
+ });
+ const [vector, raster] = restored.attachments;
+ assert.equal(vector.kind, "file");
+ assert.equal(vector.mimeType, SVG_MIME);
+ assert.equal(vector.data, undefined);
+ assert.equal(vector.ref, svgRef);
+ assert.equal(raster.kind, "image");
+ assert.deepEqual(Buffer.from(raster.data, "base64"), png);
+ assert.ok(restored.content.startsWith("Explain the diagram\n"));
+ const fallback = restored.content.match(/@"([^"\n]+)"/)?.[1];
+ assert.ok(fallback);
+ assertInside(scratch, fallback);
+ assert.deepEqual(await readFile(fallback), svg);
+ assert.deepEqual(history, before);
+ assert.deepEqual(await readFile(join(data, svgRef)), svg);
+});
+
+test("history SVG filename metadata overrides stale kind and MIME", async (t) => {
+ const { data, scratch } = await fixture(t);
+ const path = join(scratch, "diagram.SVG");
+ await writeFile(path, svg);
+ for (const supportsVision of [false, true]) {
+ const [restored] = await hydrateAttachmentHistory([{
+ id: "named-svg", role: "user", content: "", ts: 1,
+ attachments: [{ kind: "image", name: "legacy.bin", ref: path, mimeType: "image/png", data: svg.toString("base64") }],
+ }], { scratchDir: scratch, attachmentsDir: join(data, "attachments"), supportsVision });
+ assert.equal(restored.attachments[0].kind, "file");
+ assert.equal(restored.attachments[0].data, undefined);
+ assert.ok(restored.content.includes(path));
+ }
+});
+
+test("missing or outside-root SVG history never retains a stale image payload", async (t) => {
+ const { scratch, root } = await fixture(t);
+ const outside = join(root, "outside.svg");
+ await writeFile(outside, svg);
+ for (const ref of [outside, join(scratch, "missing.svg"), ""]) {
+ const attachment = { kind: "image", name: "diagram.svg", ref, data: svg.toString("base64") };
+ const before = structuredClone(attachment);
+ const [restored] = await hydrateAttachmentHistory([{
+ id: "unavailable-svg", role: "user", content: "Keep this prompt", ts: 1, attachments: [attachment],
+ }], { scratchDir: scratch, supportsVision: true });
+ assert.equal(restored.attachments[0].kind, "file");
+ assert.equal(restored.attachments[0].data, undefined);
+ assert.equal(restored.content, "Keep this prompt");
+ assert.deepEqual(attachment, before);
+ }
+});
+
+test("history non-vision images and non-user messages preserve existing behavior", async (t) => {
+ const { scratch } = await fixture(t);
+ const path = join(scratch, "pixel.png");
+ await writeFile(path, png);
+ const assistant = { id: "assistant", role: "assistant", content: "Unchanged", ts: 2 };
+ const [restored, unchanged] = await hydrateAttachmentHistory([{
+ id: "user", role: "user", content: "Explain", ts: 1,
+ attachments: [{ kind: "image", name: "pixel.png", ref: path, mimeType: "image/png" }],
+ }, assistant], { scratchDir: scratch, supportsVision: false });
+ assert.equal(restored.attachments[0].kind, "image");
+ assert.equal(restored.attachments[0].data, undefined);
+ assert.ok(restored.content.includes(path));
+ assert.equal(unchanged, assistant);
+});
+
+test("existing non-SVG image metadata is not narrowed to a new provider allowlist", async (t) => {
+ const { data } = await fixture(t);
+ // These fixtures test classification/transport, not image decoding.
+ for (const extension of ["png", "jpeg", "gif", "webp", "avif", "bmp", "heic", "tiff"]) {
+ const mimeType = `image/${extension}`;
+ const bytes = Buffer.from(`transport fixture: ${extension}`);
+ const [saved] = await saveComposerPasteFiles(data, sessionId, [{ name: `fixture.${extension}`, mimeType, data: bytes }]);
+ assert.equal(saved.kind, "image");
+ const [prepared] = await preparePromptAttachments(data, sessionId, undefined, [saved], true);
+ assert.equal(prepared.message.kind, "image");
+ assert.equal(prepared.message.mimeType, mimeType);
+ assert.deepEqual(Buffer.from(prepared.inlineData, "base64"), bytes);
+ }
+});
diff --git a/docs/spec/03-runtime/svg-attachment-input.md b/docs/spec/03-runtime/svg-attachment-input.md
new file mode 100644
index 000000000..1bd2ef3d6
--- /dev/null
+++ b/docs/spec/03-runtime/svg-attachment-input.md
@@ -0,0 +1,56 @@
+# SVG attachment input
+
+This supplements [the agent runtime](02-agent-runtime.md) and
+[model-aware image transport](../../adr/0101-model-aware-image-attachments.md)
+for issue #946. It does not change the model capability decision, protocol,
+storage schema, or attachment-root permissions.
+
+## Transport contract
+
+SVG is a file attachment, not a raw model-image payload. Recognize it by the
+`image/svg+xml` MIME essence (case-insensitive, ignoring parameters) or a `.svg`
+filename/path (case-insensitive). SVG metadata takes precedence over a stale
+`kind: "image"` or conflicting raster MIME label. This rule does not infer that
+other image formats are universally supported by every provider.
+
+Clipboard persistence supplies `.svg` when an SVG has no filename extension.
+Native-picker imports, project-path attachments, retries, and history restore
+use the same classification. SVG bytes are preserved; no rasterization, script
+execution, or external resource fetching is introduced.
+
+The live prompt gets the existing safe `@path` file reference instead of inline
+base64. Legacy content-addressed SVG attachments retain their durable reference
+and get a readable copy in the owning session's scratch `replayed/` directory.
+History hydration also clears any stale transient image data, including when a
+reference cannot be resolved. It does not rewrite the stored transcript or
+remove the original attachment. A missing or forbidden live attachment still
+fails the existing path boundary; this fix must not turn that failure into an
+unvalidated file reference.
+
+Raster classification, vision capability checks, the inline size bound, and
+non-vision file fallback retain their existing behavior.
+
+## E2E-ATTACHMENTS-svg-file-fallback
+
+- **Preconditions:** Isolated desktop profile and workspace; local mock provider
+ with image input enabled; SVG and PNG fixtures; no live provider credentials.
+- **Steps:** Paste SVG, import it through the native picker, and drop a project
+ SVG into the composer. Send each with text, then send SVG and PNG together.
+ Retry a legacy SVG attachment and reopen a session whose stored SVG is marked
+ as an image. Repeat with image input disabled. Attempt an outside-root path.
+- **Expected:** SVG remains readable as a file and never appears in a provider
+ image block; PNG still uses the existing vision transport when enabled.
+ Original bytes and unrelated prompt text are preserved. Legacy SVG is safely
+ replayed through session scratch. Forbidden paths remain rejected.
+- **Specs:** This document; 03-runtime/02-agent-runtime.
+- **Acceptance:** Attachment transport and session-root confinement.
+- **Milestone:** Maintenance.
+- **Status:** Service-level regression coverage in
+ `apps/desktop/test/svg-attachments.test.mjs`; full Electron/provider-boundary
+ E2E remains required before declaring desktop integration verified.
+
+Run the service regressions after building the workspace dependencies:
+
+```sh
+node --test apps/desktop/test/svg-attachments.test.mjs
+```
diff --git a/docs/spec/NAV.md b/docs/spec/NAV.md
index f3ef704db..d524b15a2 100644
--- a/docs/spec/NAV.md
+++ b/docs/spec/NAV.md
@@ -44,6 +44,7 @@
- [20-speech.md](03-runtime/20-speech.md)
- [21-image-generation.md](03-runtime/21-image-generation.md)
- [22-config-sync.md](03-runtime/22-config-sync.md)
+- [svg-attachment-input.md](03-runtime/svg-attachment-input.md)
## 4. UX
- [README.md](04-ux/README.md)
diff --git a/docs/zh-CN/spec/03-runtime/svg-attachment-input.md b/docs/zh-CN/spec/03-runtime/svg-attachment-input.md
new file mode 100644
index 000000000..906e400f5
--- /dev/null
+++ b/docs/zh-CN/spec/03-runtime/svg-attachment-input.md
@@ -0,0 +1,48 @@
+# SVG 附件输入
+
+> 本页为中文说明;规范以[英文源规格](/spec/03-runtime/svg-attachment-input)为准。
+
+本文针对 issue #946 补充[代理运行时](02-agent-runtime.md)和
+[按模型能力传输图片](../../../adr/0101-model-aware-image-attachments.md)。
+不改变模型能力判定、协议、存储结构或附件根目录权限。
+
+## 传输约定
+
+SVG 是文件附件,不是直接发送给模型的图片载荷。通过 MIME 主类型
+`image/svg+xml`(忽略大小写及参数)或 `.svg` 文件名、路径(忽略大小写)
+识别。SVG 元数据优先于旧的 `kind: "image"` 或冲突的位图 MIME 标记。
+这不意味着其他图片格式被所有服务商普遍支持。
+
+剪贴板中的 SVG 没有文件扩展名时,保存时补充 `.svg`。原生文件选择器、
+项目路径附件、重试和历史恢复采用同一分类规则。保留 SVG 原始字节,
+不引入栅格化、脚本执行或外部资源获取。
+
+新提示词使用现有的安全 `@path` 文件引用,而不是内联 base64。
+历史内容寻址 SVG 保留持久化引用,并在所属会话的 scratch `replayed/`
+目录中生成可读取副本。历史恢复还会清除旧的临时图片数据,引用无法解析
+时也一样。不会改写已存储的会话或删除原始附件。缺失或越界的新附件仍然
+通过现有路径边界报错,不得退化为未经校验的文件引用。
+
+位图分类、视觉能力判断、内联大小上限和非视觉模型的文件回退保持不变。
+
+## E2E-ATTACHMENTS-svg-file-fallback
+
+- **前置条件:** 隔离的桌面配置和工作区;启用图片输入的本地模拟服务商;
+ SVG、PNG 测试文件;不使用真实服务商凭据。
+- **步骤:** 粘贴 SVG,通过原生选择器导入 SVG,将项目 SVG 拖入输入框。
+ 分别附带文字发送,再混合发送 SVG 和 PNG。重试旧 SVG 附件,重新打开
+ 包含旧图片类型 SVG 的会话。关闭图片输入后重复,并尝试越界路径。
+- **预期:** SVG 保持为可读文件,不出现在服务商图片内容块中;启用视觉
+ 输入时 PNG 仍使用原有图片传输。原始字节和无关提示词文字保留。
+ 旧 SVG 通过所属会话 scratch 安全恢复。越界路径仍被拒绝。
+- **规范:** 本文;03-runtime/02-agent-runtime。
+- **验收:** 附件传输和会话根目录限制。
+- **里程碑:** 维护。
+- **状态:** `apps/desktop/test/svg-attachments.test.mjs` 提供服务层回归覆盖;
+ 宣布桌面集成验证完成前,仍需完整 Electron/服务商边界端到端验证。
+
+构建工作区依赖后运行服务层回归:
+
+```sh
+node --test apps/desktop/test/svg-attachments.test.mjs
+```
diff --git a/docs/zh-CN/spec/NAV.md b/docs/zh-CN/spec/NAV.md
index 3064b461e..86397e23d 100644
--- a/docs/zh-CN/spec/NAV.md
+++ b/docs/zh-CN/spec/NAV.md
@@ -47,6 +47,7 @@
- [20-speech.md](/zh-CN/spec/03-runtime/20-speech)
- [21-image-generation.md](/zh-CN/spec/03-runtime/21-image-generation)
- [22-config-sync.md](/zh-CN/spec/03-runtime/22-config-sync)
+- [svg-attachment-input.md](/zh-CN/spec/03-runtime/svg-attachment-input)
## 4. 用户体验
- [README.md](/zh-CN/spec/04-ux/README)
diff --git a/packages/agent-runtime/src/attachment-history.ts b/packages/agent-runtime/src/attachment-history.ts
new file mode 100644
index 000000000..7868f9c81
--- /dev/null
+++ b/packages/agent-runtime/src/attachment-history.ts
@@ -0,0 +1,141 @@
+/** Session-root-confined attachment hydration for restored user messages. */
+import { createHash } from "node:crypto";
+import { constants as fsConstants } from "node:fs";
+import { copyFile, mkdir, readFile, realpath, stat } from "node:fs/promises";
+import { isAbsolute, relative, resolve } from "node:path";
+import {
+ formatFileInsert,
+ isSvgAttachment,
+ MAX_INLINE_IMAGE_BYTES,
+ SVG_MIME_TYPE,
+ type MessageAttachment,
+ type UiMessage,
+} from "@pi-desktop/shared";
+
+export type AttachmentHistoryContext = {
+ scratchDir?: string;
+ projectPath?: string;
+ attachmentsDir?: string;
+ supportsVision: boolean;
+};
+
+function pathInside(root: string, candidate: string): boolean {
+ const child = relative(root, candidate);
+ return child === "" || (!child.startsWith("..") && !isAbsolute(child));
+}
+
+async function replayedAttachmentPath(
+ params: AttachmentHistoryContext,
+ attachment: NonNullable<UiMessage["attachments"]>[number],
+ source: string,
+): Promise<string> {
+ if (!params.scratchDir || !attachment.ref.startsWith("attachments/")) {
+ return source;
+ }
+ const root = resolve(params.scratchDir, "replayed");
+ await mkdir(root, { recursive: true });
+ const safeName =
+ attachment.name.replace(/[^\p{L}\p{N}._-]+/gu, "_") || "attachment";
+ const suffix = createHash("sha256")
+ .update(attachment.ref)
+ .digest("hex")
+ .slice(0, 12);
+ const target = resolve(root, `${safeName}-${suffix}`);
+ try {
+ await copyFile(source, target, fsConstants.COPYFILE_EXCL);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") throw error;
+ }
+ return target;
+}
+
+export async function hydrateAttachmentHistory(
+ history: UiMessage[],
+ params: AttachmentHistoryContext,
+): Promise<UiMessage[]> {
+ const supportsVision = params.supportsVision;
+ const roots = [
+ params.scratchDir,
+ params.projectPath,
+ params.attachmentsDir,
+ ].filter((value): value is string => Boolean(value));
+ const canonicalRoots = await Promise.all(
+ roots.map(async (root) => {
+ try {
+ return await realpath(root);
+ } catch {
+ return undefined;
+ }
+ }),
+ );
+ const resolveAttachment = async (
+ sourceAttachment: NonNullable<UiMessage["attachments"]>[number],
+ ): Promise<{ attachment: MessageAttachment; fallbackPath?: string }> => {
+ // Old transcripts can still label SVG as an image. Normalize before every
+ // early return, and discard any stale transient data without mutating history.
+ const attachment: MessageAttachment = isSvgAttachment(
+ sourceAttachment.mimeType, sourceAttachment.name, sourceAttachment.ref,
+ )
+ ? { ...sourceAttachment, kind: "file", mimeType: SVG_MIME_TYPE, data: undefined }
+ : sourceAttachment;
+ const ref = attachment.ref.trim();
+ if (!ref) return { attachment };
+ const candidate =
+ ref.startsWith("attachments/") && params.attachmentsDir
+ ? resolve(params.attachmentsDir, ref.slice("attachments/".length))
+ : isAbsolute(ref)
+ ? resolve(ref)
+ : params.projectPath
+ ? resolve(params.projectPath, ref)
+ : undefined;
+ if (!candidate) return { attachment };
+ try {
+ const canonical = await realpath(candidate);
+ if (!canonicalRoots.some((root) => root && pathInside(root, canonical))) {
+ return { attachment };
+ }
+ const shouldInline = attachment.kind === "image" && supportsVision;
+ const size = (await stat(canonical)).size;
+ const bytes =
+ shouldInline && size <= MAX_INLINE_IMAGE_BYTES
+ ? await readFile(canonical)
+ : undefined;
+ if (attachment.kind === "image" && supportsVision && bytes) {
+ return { attachment: { ...attachment, data: bytes.toString("base64") } };
+ }
+ return {
+ attachment,
+ fallbackPath: await replayedAttachmentPath(
+ params,
+ attachment,
+ canonical,
+ ),
+ };
+ } catch {
+ return { attachment };
+ }
+ };
+
+ return Promise.all(
+ history.map(async (message) => {
+ if (message.role !== "user" || !message.attachments?.length) return message;
+ const resolved = await Promise.all(message.attachments.map(resolveAttachment));
+ const fallbackPaths = resolved
+ .map((item) => item.fallbackPath)
+ .filter((path): path is string => Boolean(path))
+ .map((path) => formatFileInsert(path, "file"))
+ .join("")
+ .trim();
+ const content = message.content.trim()
+ ? fallbackPaths
+ ? `${message.content}\n${fallbackPaths}`
+ : message.content
+ : fallbackPaths;
+ return {
+ ...message,
+ content,
+ attachments: resolved.map((item) => item.attachment),
+ };
+ }),
+ );
+}
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index 63d81da17..d23efc9cc 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -3,13 +3,11 @@
* Protocol: NDJSON JSON-RPC on stdio with Electron main.
* Host access is proxied through main (single host-core process).
*/
-import { createHash, randomUUID } from "node:crypto";
-import { constants as fsConstants } from "node:fs";
-import { copyFile, mkdir, readFile, realpath, stat } from "node:fs/promises";
-import { isAbsolute, relative, resolve } from "node:path";
+import { randomUUID } from "node:crypto";
import type { ModelAuth } from "@earendil-works/pi-ai";
import { ParentHostProxy } from "./parent-host-proxy.js";
import { visionFromModelConfig } from "./model-capabilities.js";
+import { hydrateAttachmentHistory } from "./attachment-history.js";
import { classifyAgentError } from "./agent-errors.js";
import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import {
@@ -30,9 +28,7 @@ import {
import { applyNodeNetworkProxy } from "./node-proxy.js";
import { NATIVE_PI_SESSION_PREFIX, nativePiService } from "./native-pi-session.js";
import {
- formatFileInsert,
isCommandShellOption,
- MAX_INLINE_IMAGE_BYTES,
normalizeMode,
normalizeNetworkProxy,
OAUTH_AUTH_KIND,
@@ -46,7 +42,6 @@ import type {
ContextCompactionSettings,
CommandShellOption,
Mode,
- MessageAttachment,
PlanExecution,
SessionThinkingLevel,
UiMessage,
@@ -159,122 +154,6 @@ function respond(id: string | number, result?: unknown, error?: unknown) {
else write({ jsonrpc: "2.0", id, result });
}
-function pathInside(root: string, candidate: string): boolean {
- const child = relative(root, candidate);
- return child === "" || (!child.startsWith("..") && !isAbsolute(child));
-}
-
-async function replayedAttachmentPath(
- params: RuntimeParams,
- attachment: NonNullable<UiMessage["attachments"]>[number],
- source: string,
-): Promise<string> {
- if (!params.scratchDir || !attachment.ref.startsWith("attachments/")) {
- return source;
- }
- const root = resolve(params.scratchDir, "replayed");
- await mkdir(root, { recursive: true });
- const safeName =
- attachment.name.replace(/[^\p{L}\p{N}._-]+/gu, "_") || "attachment";
- const suffix = createHash("sha256")
- .update(attachment.ref)
- .digest("hex")
- .slice(0, 12);
- const target = resolve(root, `${safeName}-${suffix}`);
- try {
- await copyFile(source, target, fsConstants.COPYFILE_EXCL);
- } catch (error) {
- if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") throw error;
- }
- return target;
-}
-
-async function hydrateAttachmentHistory(
- history: UiMessage[],
- params: RuntimeParams,
-): Promise<UiMessage[]> {
- // Same helper the live prompt path uses, on the same override-shaped config,
- // so a replayed image is inlined exactly when a fresh one would be.
- const supportsVision = visionFromModelConfig(params.provider.modelConfig);
- const roots = [
- params.scratchDir,
- params.projectPath,
- params.attachmentsDir,
- ].filter((value): value is string => Boolean(value));
- const canonicalRoots = await Promise.all(
- roots.map(async (root) => {
- try {
- return await realpath(root);
- } catch {
- return undefined;
- }
- }),
- );
- const resolveAttachment = async (
- attachment: NonNullable<UiMessage["attachments"]>[number],
- ): Promise<{ attachment: MessageAttachment; fallbackPath?: string }> => {
- const ref = attachment.ref.trim();
- if (!ref) return { attachment };
- const candidate =
- ref.startsWith("attachments/") && params.attachmentsDir
- ? resolve(params.attachmentsDir, ref.slice("attachments/".length))
- : isAbsolute(ref)
- ? resolve(ref)
- : params.projectPath
- ? resolve(params.projectPath, ref)
- : undefined;
- if (!candidate) return { attachment };
- try {
- const canonical = await realpath(candidate);
- if (!canonicalRoots.some((root) => root && pathInside(root, canonical))) {
- return { attachment };
- }
- const shouldInline = attachment.kind === "image" && supportsVision;
- const size = (await stat(canonical)).size;
- const bytes =
- shouldInline && size <= MAX_INLINE_IMAGE_BYTES
- ? await readFile(canonical)
- : undefined;
- if (attachment.kind === "image" && supportsVision && bytes) {
- return { attachment: { ...attachment, data: bytes.toString("base64") } };
- }
- return {
- attachment,
- fallbackPath: await replayedAttachmentPath(
- params,
- attachment,
- canonical,
- ),
- };
- } catch {
- return { attachment };
- }
- };
-
- return Promise.all(
- history.map(async (message) => {
- if (message.role !== "user" || !message.attachments?.length) return message;
- const resolved = await Promise.all(message.attachments.map(resolveAttachment));
- const fallbackPaths = resolved
- .map((item) => item.fallbackPath)
- .filter((path): path is string => Boolean(path))
- .map((path) => formatFileInsert(path, "file"))
- .join("")
- .trim();
- const content = message.content.trim()
- ? fallbackPaths
- ? `${message.content}\n${fallbackPaths}`
- : message.content
- : fallbackPaths;
- return {
- ...message,
- content,
- attachments: resolved.map((item) => item.attachment),
- };
- }),
- );
-}
-
async function runtimeFor(
params: RuntimeParams,
currentPrompt?: string,
@@ -365,7 +244,13 @@ async function runtimeFor(
compaction?: ContextCompactionRecord;
} | null;
}>("session.get", { id: sessionId });
- history = await hydrateAttachmentHistory(detail?.session?.messages ?? [], params);
+ const supportsVision = visionFromModelConfig(params.provider.modelConfig);
+ history = await hydrateAttachmentHistory(detail?.session?.messages ?? [], {
+ scratchDir: params.scratchDir,
+ projectPath: params.projectPath,
+ attachmentsDir: params.attachmentsDir,
+ supportsVision,
+ });
compaction = detail?.session?.compaction;
} catch {
// History restore is best-effort; a prompt can still start cleanly.
diff --git a/packages/shared/src/attachment-formats.ts b/packages/shared/src/attachment-formats.ts
new file mode 100644
index 000000000..391b2ed43
--- /dev/null
+++ b/packages/shared/src/attachment-formats.ts
@@ -0,0 +1,13 @@
+/** SVG can be previewed locally, but must not be sent as a raw model image. */
+export const SVG_MIME_TYPE = "image/svg+xml";
+
+/** MIME parameters and legacy filename metadata must not bypass the SVG fallback. */
+export function isSvgAttachment(
+ mimeType: string | undefined,
+ ...names: (string | undefined)[]
+): boolean {
+ return (
+ mimeType?.split(";", 1)[0]?.trim().toLowerCase() === SVG_MIME_TYPE ||
+ names.some((name) => typeof name === "string" && /\.svg$/i.test(name.trim()))
+ );
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 2b6ab7723..d77291100 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -50,6 +50,7 @@ export * from "./model-catalog.js";
export * from "./github-feedback.js";
export * from "./network-proxy.js";
export * from "./attachment-limits.js";
+export * from "./attachment-formats.js";
export * from "./speech.js";
export * from "./image-generation.js";
export * from "./font-size.js";