Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
fix(chat): SVG output shows as a picture and send_file says what the user sees
leen.zhou2e6f5767684e
diff --git a/apps/desktop/src/renderer/features/chat/messages/MessageAttachments.tsx b/apps/desktop/src/renderer/features/chat/messages/MessageAttachments.tsxindex 5092be6..4b38951 100644--- a/apps/desktop/src/renderer/features/chat/messages/MessageAttachments.tsx+++ b/apps/desktop/src/renderer/features/chat/messages/MessageAttachments.tsx@@ -1,4 +1,5 @@-import { type Attachment, previewKind } from "@pibot/protocol";+// Present persisted chat attachments through their format-specific preview paths.+import { type Attachment, canPreviewSvg, previewKind } from "@pibot/protocol";import { RevealFileButton, useRpc, useT } from "@pibot/renderer-kit";import { Button, CloseButton } from "@pibot/ui";import {@@ -17,6 +18,7 @@ import { OfficeAttachment } from "../../office/OfficeAttachment.tsx";import { FileCard } from "../composer/Attachments.tsx";import styles from "../composer/attachments.module.css";import { imageKey, imagePreviewCache } from "./image-preview-cache.ts";+import { SvgAttachment } from "./SvgAttachment.tsx";const zeroVersion = () => 0;@@ -271,6 +273,8 @@ export function MessageAttachments({>{attachment.kind === "image" ? (<ImagePreview attachment={attachment} messageId={messageId} />+ ) : messageId && !readOnly && canPreviewSvg(attachment) ? (+ <SvgAttachment attachment={attachment} messageId={messageId} />) : previewKind(attachment.name) && messageId ? (<OfficeAttachment attachment={attachment} messageId={messageId} readOnly={readOnly} />) : (diff --git a/apps/desktop/src/renderer/features/chat/messages/SvgAttachment.tsx b/apps/desktop/src/renderer/features/chat/messages/SvgAttachment.tsxnew file mode 100644index 0000000..ed53925--- /dev/null+++ b/apps/desktop/src/renderer/features/chat/messages/SvgAttachment.tsx@@ -0,0 +1,122 @@+// Display an SVG as an image using the authorized preview read, with its file card as fallback.+import type { Attachment } from "@pibot/protocol";+import { useRpc, useT } from "@pibot/renderer-kit";+import {+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ useSyncExternalStore,+} from "react";+import { FilePreviewContext } from "../../file-preview/context.tsx";+import { attachmentTarget } from "../../file-preview/state.ts";+import { OfficeAttachment } from "../../office/OfficeAttachment.tsx";+import styles from "../composer/attachments.module.css";+import { imageKey, imagePreviewCache } from "./image-preview-cache.ts";++const zeroVersion = () => 0;++function useSvgSource(attachment: Attachment, messageId: string, visible: boolean) {+ const { peer } = useRpc();+ const cache = peer ? imagePreviewCache(peer) : undefined;+ const key = imageKey(attachment);+ // biome-ignore lint/correctness/useExhaustiveDependencies: the key covers all attachment metadata.+ const image = useMemo(() => attachment, [key]);+ const subscribe = useCallback(+ (notify: () => void) => cache?.subscribe(key, notify) ?? (() => {}),+ [cache, key],+ );+ useSyncExternalStore(subscribe, cache?.version ?? zeroVersion);+ const revision = cache?.authorityVersion(image);+ const [result, setResult] = useState<{+ cache: typeof cache;+ messageId: string;+ revision: typeof revision;+ source?: string;+ }>();+ const current =+ result?.cache === cache && result?.messageId === messageId && result?.revision === revision+ ? result+ : undefined;++ useEffect(() => {+ if (!cache || !visible) {+ setResult(undefined);+ return;+ }+ const controller = new AbortController();+ const request = { cache, messageId, revision };+ void cache.svgSource(image, messageId, controller.signal).then(+ (source) => {+ if (!controller.signal.aborted) setResult({ ...request, source });+ },+ () => {+ if (!controller.signal.aborted) setResult(request);+ },+ );+ return () => controller.abort();+ }, [cache, image, messageId, revision, visible]);++ return {+ source: visible ? current?.source : undefined,+ failed: visible && !!current && !current.source,+ fail: () => setResult({ cache, messageId, revision }),+ };+}++export function SvgAttachment({+ attachment,+ messageId,+}: {+ attachment: Attachment;+ messageId: string;+}) {+ const t = useT();+ const openPreview = useContext(FilePreviewContext);+ const { peer } = useRpc();+ const container = useRef<HTMLDivElement>(null);+ const [visible, setVisible] = useState(false);+ useEffect(() => {+ const element = container.current;+ if (!element) return;+ const observer = new IntersectionObserver(+ ([entry]) => setVisible(entry?.isIntersecting ?? false),+ { rootMargin: "200px" },+ );+ observer.observe(element);+ return () => observer.disconnect();+ }, []);+ const { source, failed, fail } = useSvgSource(attachment, messageId, visible && !!openPreview);++ return (+ <div ref={container}>+ {source && openPreview ? (+ <button+ type="button"+ className={styles.imageButton}+ onClick={() => openPreview(attachmentTarget(attachment, messageId))}+ aria-label={t("attachments.view", { name: attachment.name })}+ >+ <img+ src={source}+ alt={attachment.name}+ className={styles.thumbnail}+ onLoad={({ currentTarget }) => {+ if (currentTarget.naturalWidth * currentTarget.naturalHeight > 40_000_000) fail();+ }}+ onError={fail}+ loading="lazy"+ />+ </button>+ ) : failed || !peer || !openPreview ? (+ <OfficeAttachment attachment={attachment} messageId={messageId} readOnly={false} />+ ) : (+ <span className={styles.placeholder} role="status">+ {t("common.loading")}+ </span>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/chat/messages/image-preview-cache.ts b/apps/desktop/src/renderer/features/chat/messages/image-preview-cache.tsindex e36de4a..c302f93 100644--- a/apps/desktop/src/renderer/features/chat/messages/image-preview-cache.ts+++ b/apps/desktop/src/renderer/features/chat/messages/image-preview-cache.ts@@ -1,3 +1,4 @@+// Share bounded image reads across the visible conversation without retaining full previews.import type { ChatPeer } from "@pibot/client-core";import { type ChatReadCache, chatReadCache } from "@pibot/client-core";import {@@ -247,6 +248,38 @@ export class ImagePreviewCache {signal,);}+ async svgSource(attachment: Attachment, messageId: string, signal: AbortSignal) {+ const identity = this.identity(attachment, messageId);+ const version = identity.version;+ const key = imageKey(attachment);+ return this.reads.read(+ `image-svg:${key}:${messageId}`,+ async (queued) => {+ const release = await this.slot(queued);+ const read = AbortSignal.any([queued, AbortSignal.timeout(30_000)]);+ try {+ // The preview RPC checks the original message link and applies SVG byte limits.+ const image = await this.reads.peer.call(+ "preview.read",+ { requestId: crypto.randomUUID(), messageId, attachmentId: attachment.id },+ { signal: read, timeoutMs: 35_000 },+ );+ read.throwIfAborted();+ if (+ image.kind !== "svg" ||+ this.disposed ||+ identity !== this.identities.get(key) ||+ version !== identity.version+ )+ throw new Error("SVG preview unavailable");+ return `data:image/svg+xml;base64,${image.data}`;+ } finally {+ release();+ }+ },+ signal,+ );+ }/*** The brain returns a small cached thumbnail, so the UI thread never receives, validates or* decodes the full image just to show it. Older brains fall back to the local worker path.diff --git a/packages/brain/src/conversations/attachments/file-preview-rpc.ts b/packages/brain/src/conversations/attachments/file-preview-rpc.tsindex c97c399..0d52b6b 100644--- a/packages/brain/src/conversations/attachments/file-preview-rpc.ts+++ b/packages/brain/src/conversations/attachments/file-preview-rpc.ts@@ -1,8 +1,10 @@+// Resolve and read preview bytes under the same authority as their source message or run.import type { DatabaseSync } from "node:sqlite";import type { ExecutionTarget } from "@pibot/execution";import {type KernelMethodParams,type KernelMethodResults,+ PREVIEW_TEXT_BYTES,previewKind,RpcError,RpcErrorCodes,@@ -86,7 +88,7 @@ export function registerPreviewRpc(const fresh = await previewSource(deps, input, signal);if (fresh.path !== item.path || fresh.root !== item.root) fail("preview_changed");if (kind === "markdown" || kind === "code" || kind === "svg") {- if (read.bytes.length > 2_097_152) fail("preview_limit");+ if (read.bytes.length > PREVIEW_TEXT_BYTES) fail("preview_limit");let text: string;try {text = new TextDecoder("utf-8", { fatal: true }).decode(read.bytes);diff --git a/packages/brain/src/conversations/attachments/send-files.ts b/packages/brain/src/conversations/attachments/send-files.tsindex 054e94c..a3e5dc7 100644--- a/packages/brain/src/conversations/attachments/send-files.ts+++ b/packages/brain/src/conversations/attachments/send-files.ts@@ -4,7 +4,13 @@ import { lstat, open, realpath } from "node:fs/promises";import { basename } from "node:path";import { canonicalPath, ExecError, sameFile } from "@pibot/execution";import { containsPath } from "@pibot/policy";-import { FILE_LIMIT, RpcError, RpcErrorCodes } from "@pibot/protocol-base";+import {+ type Attachment,+ canPreviewSvg,+ FILE_LIMIT,+ RpcError,+ RpcErrorCodes,+} from "@pibot/protocol-base";import { AttachmentsRepo, MessagesRepo, RunsRepo, transaction } from "@pibot/storage";import { auditLeaf } from "../../core/audit-fields.ts";import type { PreparedTool, ToolRunContext } from "../../core/local-types.ts";@@ -68,6 +74,21 @@ async function readSource(}}+function deliveryText(items: Attachment[]): string {+ const lines: string[] = [];+ if (items.some((item) => item.kind === "image"))+ lines.push("Raster images are attached as inline pictures. / 位图已作为对话中的图片附上。");+ if (items.some(canPreviewSvg))+ lines.push(+ "SVG files are attached. Desktop chat shows them inline when the preview loads. Phones and failed previews show file cards. Describe them as attached. / SVG 已附上。桌面端预览成功后会内联显示,手机端和预览失败时显示文件卡片。请说明 SVG 已附上。",+ );+ if (items.some((item) => item.kind === "file" && !canPreviewSvg(item)))+ lines.push(+ "Other files are attached as file cards the user can click to open or preview. Do not say those files are embedded. / 其他文件以文件卡片附上,可点击打开或预览。不要说这些文件已内联显示。",+ );+ return lines.join("\n");+}+export async function sendFiles(local: LocalService,context: ToolRunContext,@@ -147,7 +168,7 @@ export async function sendFiles(local.deps.logger.warn("Attachment notification deferred; history retains committed metadata");}return {- text: "Files attached to your reply. Images are visible to the user; do not say you cannot display them. / 文件已附到回复,图片可直接查看,不要再说无法显示图片。",+ text: deliveryText(batch.items.map((item) => item.metadata)),summary: "send_file",};}diff --git a/packages/protocol-base/src/chat/attachments.ts b/packages/protocol-base/src/chat/attachments.tsindex 170ad32..a7c4064 100644--- a/packages/protocol-base/src/chat/attachments.ts+++ b/packages/protocol-base/src/chat/attachments.ts@@ -1,3 +1,4 @@+// Keep stored attachment metadata separate from the formats accepted by image decoders.import { z } from "zod";export const IMAGE_LIMIT = 10 * 1024 * 1024;@@ -66,6 +67,7 @@ export const TEXT_EXTENSIONS = new Set(["hs",]);export const FILE_MIMES = [+ "image/svg+xml","text/plain","text/markdown","text/csv",@@ -81,6 +83,7 @@ export const FILE_MIMES = [] as const;export function fileMime(name: string): (typeof FILE_MIMES)[number] | undefined {const ext = name.split(".").at(-1)?.toLowerCase() ?? "";+ if (ext === "svg") return "image/svg+xml";if (ext === "pdf") return "application/pdf";if (ext === "docx")return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";diff --git a/packages/protocol-base/src/chat/file-preview.ts b/packages/protocol-base/src/chat/file-preview.tsindex 9cc2a47..fc99be3 100644--- a/packages/protocol-base/src/chat/file-preview.ts+++ b/packages/protocol-base/src/chat/file-preview.ts@@ -1,5 +1,19 @@+// Define the file formats and read limits shared by the preview clients and brain.import { z } from "zod";import { IdSchema } from "../core/ids.ts";+import type { Attachment } from "./attachments.ts";++export const PREVIEW_TEXT_BYTES = 2_097_152;++/** Old SVGs were stored with a generic MIME. Keep them in the file preview path. */+export function canPreviewSvg(attachment: Pick<Attachment, "kind" | "name" | "size">): boolean {+ return (+ attachment.kind === "file" &&+ previewKind(attachment.name) === "svg" &&+ attachment.size > 0 &&+ attachment.size <= PREVIEW_TEXT_BYTES+ );+}export const PreviewKindSchema = z.enum(["docx",@@ -98,7 +112,7 @@ export const PreviewFileSchema = z.strictObject({revision: z.string().regex(/^[a-f0-9]{64}$/),// Base64 is the original local file for visual formats; text has already been redacted.data: z.string().max(27_962_028),- text: z.string().max(2_097_152).optional(),+ text: z.string().max(PREVIEW_TEXT_BYTES).optional(),});export const PreviewMethods = {"preview.read": {