Skip to content

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

feat(chat): render visualization references as inline cards

zszz3cffaed033bab
diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx
new file mode 100644
index 000000000..9828af295
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx
@@ -0,0 +1,136 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { GEN_UI_INITIAL_HEIGHT, type GenUiErrorCode, type GenUiReference } from "@pi-desktop/shared";
+import { Button, TooltipButton } from "../../../components/ui";
+import { IconCircleAlert, IconPanelMaximize } from "../../../components/icons";
+import { GenUiDialog } from "./GenUiDialog";
+import { GenUiFrame } from "./GenUiFrame";
+import { genUiFramePool } from "./gen-ui-frames";
+import {
+ genUiCardSource,
+ genUiUnavailableReasonKey,
+ type GenUiOwner,
+ type GenUiUnavailableReason,
+} from "./gen-ui-source";
+import { isGenUiViewportLive, useGenUiViewport } from "./gen-ui-viewport";
+import "../../../styles/gen-ui.css";
+
+/** Display name: the model's title, else the referenced file name. */
+export function genUiCardTitle(reference: GenUiReference): string {
+ if (reference.title) return reference.title;
+ if (reference.location) return reference.location.fileName;
+ const parts = reference.path.replaceAll("\\", "/").split("/");
+ return parts.at(-1) || reference.path;
+}
+
+function UnavailableCard({ title, reason }: { title: string; reason: GenUiUnavailableReason }) {
+ const { t } = useTranslation();
+ return (
+ <div className="gen-ui-card is-unavailable" role="note">
+ <IconCircleAlert size={14} className="gen-ui-unavailable-icon" />
+ <div className="gen-ui-unavailable-text">
+ <span className="gen-ui-title">{t("chat.genUi.unavailable", { title })}</span>
+ <span className="gen-ui-unavailable-reason">{t(genUiUnavailableReasonKey(reason))}</span>
+ </div>
+ </div>
+ );
+}
+
+export function GenUiCard({ reference, ...owner }: { reference: GenUiReference } & GenUiOwner) {
+ const title = genUiCardTitle(reference);
+ const source = genUiCardSource(reference, owner);
+ if (source.kind === "unavailable") return <UnavailableCard title={title} reason={source.reason} />;
+ return <LiveGenUiCard key={source.url} url={source.url} title={title} />;
+}
+
+function LiveGenUiCard({ url, title }: { url: string; title: string }) {
+ const [error, setError] = useState<GenUiErrorCode | null>(null);
+ if (error) return <UnavailableCard title={title} reason={error} />;
+ return <PooledGenUiCard url={url} title={title} onError={setError} />;
+}
+
+function PooledGenUiCard({
+ url,
+ title,
+ onError,
+}: {
+ url: string;
+ title: string;
+ onError: (code: GenUiErrorCode) => void;
+}) {
+ const { t } = useTranslation();
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const [viewport, dispatch] = useGenUiViewport(rootRef);
+ const [expanded, setExpanded] = useState(false);
+ // The last reported height keeps a released or reloading card from jumping.
+ const [height, setHeight] = useState(GEN_UI_INITIAL_HEIGHT);
+ const live = isGenUiViewportLive(viewport);
+ const slot = useRef(Symbol(url));
+ const visible = useRef(viewport.visible);
+
+ useEffect(() => {
+ visible.current = viewport.visible;
+ }, [viewport.visible]);
+
+ useEffect(() => {
+ if (!live) return;
+ const id = slot.current;
+ genUiFramePool.acquire(id, () => dispatch({ type: "evict" }), visible.current);
+ return () => genUiFramePool.release(id);
+ }, [live, dispatch]);
+
+ useEffect(() => {
+ if (live) genUiFramePool.setVisible(slot.current, viewport.visible);
+ }, [live, viewport.visible]);
+
+ const closeDialog = useCallback(() => setExpanded(false), []);
+ const frameTitle = t("chat.genUi.frameTitle", { title });
+
+ return (
+ <div ref={rootRef} className="gen-ui-card" data-gen-ui-url={url}>
+ <header className="gen-ui-header">
+ <span className="gen-ui-title">{title}</span>
+ <TooltipButton
+ type="button"
+ className="icon-btn gen-ui-action"
+ tooltip={t("chat.genUi.expand")}
+ ariaLabel={t("chat.genUi.expand")}
+ onClick={() => setExpanded(true)}
+ >
+ <IconPanelMaximize size={14} />
+ </TooltipButton>
+ </header>
+ <div className="gen-ui-body">
+ {live ? (
+ <GenUiFrame url={url} title={frameTitle} initialHeight={height} onHeight={setHeight} onError={onError} />
+ ) : (
+ <div className="gen-ui-placeholder" style={{ height }}>
+ {viewport.evicted ? (
+ <Button type="button" variant="ghost" size="sm" onClick={() => dispatch({ type: "load" })}>
+ {t("chat.genUi.loadPrompt")}
+ </Button>
+ ) : null}
+ </div>
+ )}
+ </div>
+ {expanded ? <GenUiDialog url={url} title={title} onClose={closeDialog} /> : null}
+ </div>
+ );
+}
+
+/** Cards for the references split out of one completed assistant message. */
+export function GenUiCards({
+ references,
+ sessionId,
+ remote,
+}: { references: readonly GenUiReference[] } & GenUiOwner) {
+ if (references.length === 0) return null;
+ return (
+ <div className="gen-ui-cards">
+ {references.map((reference, index) => (
+ // References are positional within an immutable completed message.
+ <GenUiCard key={`${index}-${reference.path}`} reference={reference} sessionId={sessionId} remote={remote} />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsx
new file mode 100644
index 000000000..210cd37d8
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsx
@@ -0,0 +1,102 @@
+import { useEffect, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { OverlayBackdrop, portalOverlay, TooltipButton } from "../../../components/ui";
+import { IconClose } from "../../../components/icons";
+import { GenUiFrame } from "./GenUiFrame";
+
+/**
+ * Where Tab should move focus inside the dialog, or null to let the browser
+ * move it. Focus outside the dialog (e.g. after the guest frame handed it
+ * back) re-enters at the first control.
+ */
+export function genUiDialogTabTarget<T>(focusable: readonly T[], active: unknown, backward: boolean): T | null {
+ if (focusable.length === 0) return null;
+ const first = focusable[0];
+ const last = focusable[focusable.length - 1];
+ if (!focusable.includes(active as T)) return backward ? last : first;
+ if (backward && active === first) return last;
+ if (!backward && active === last) return first;
+ return null;
+}
+
+const FOCUSABLE = "button:not([disabled]), iframe";
+
+/**
+ * Expanded view. It loads a fresh frame for the same URL: moving the inline
+ * iframe would reload it anyway, and v1 guests keep no state worth carrying.
+ */
+export function GenUiDialog({
+ url,
+ title,
+ onClose,
+}: {
+ url: string;
+ title: string;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation();
+ const closeRef = useRef<HTMLButtonElement | null>(null);
+ const dialogRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ const previouslyFocused = document.activeElement as HTMLElement | null;
+ closeRef.current?.focus();
+ const focusable = () => [...(dialogRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? [])];
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ onClose();
+ return;
+ }
+ if (event.key !== "Tab") return;
+ const target = genUiDialogTabTarget(focusable(), document.activeElement, event.shiftKey);
+ if (!target) return;
+ event.preventDefault();
+ target.focus();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown);
+ if (previouslyFocused?.isConnected) previouslyFocused.focus();
+ };
+ }, [onClose]);
+
+ // Tab inside the out-of-process guest never reaches this window, so the
+ // browser moves focus past the frame. These guards catch it at the dialog
+ // edges and wrap it back in.
+ const wrapTo = (edge: "first" | "last") => () => {
+ const items = [...(dialogRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? [])];
+ (edge === "first" ? items[0] : items.at(-1))?.focus();
+ };
+
+ return portalOverlay(
+ <OverlayBackdrop
+ className="overlay gen-ui-overlay"
+ role="presentation"
+ onClick={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ >
+ <span tabIndex={0} className="gen-ui-focus-guard" aria-hidden="true" onFocus={wrapTo("last")} />
+ <div ref={dialogRef} className="dialog gen-ui-dialog" role="dialog" aria-modal="true" aria-label={title}>
+ <header className="gen-ui-header">
+ <span className="gen-ui-title">{title}</span>
+ <TooltipButton
+ ref={closeRef}
+ type="button"
+ className="icon-btn gen-ui-action"
+ tooltip={t("chat.genUi.close")}
+ ariaLabel={t("chat.genUi.close")}
+ onClick={onClose}
+ >
+ <IconClose size={14} />
+ </TooltipButton>
+ </header>
+ <div className="gen-ui-dialog-body">
+ <GenUiFrame url={url} title={t("chat.genUi.frameTitle", { title })} fill onEscape={onClose} />
+ </div>
+ </div>
+ <span tabIndex={0} className="gen-ui-focus-guard" aria-hidden="true" onFocus={wrapTo("first")} />
+ </OverlayBackdrop>,
+ );
+}
diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx
new file mode 100644
index 000000000..2bb061676
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx
@@ -0,0 +1,116 @@
+import { useEffect, useRef, useState } from "react";
+import {
+ GEN_UI_INITIAL_HEIGHT,
+ GEN_UI_THEME_MESSAGE,
+ GEN_UI_VIEW_MESSAGE,
+ type GenUiErrorCode,
+} from "@pi-desktop/shared";
+import {
+ genUiErrorFromMessage,
+ genUiHeightFromMessage,
+ genUiKeyFromMessage,
+ genUiWheelFromMessage,
+ isGenUiReadyMessage,
+} from "./gen-ui-frames";
+import { currentGenUiTheme, subscribeGenUiTheme, type GenUiThemePayload } from "./gen-ui-theme";
+
+/**
+ * One sandboxed guest frame. The guest has an opaque origin (no
+ * `allow-same-origin`), so it can neither reach the host DOM nor the preload
+ * bridge; the only channel is `postMessage`, and only messages from this
+ * frame's own window are honored.
+ */
+export function GenUiFrame({
+ url,
+ title,
+ fill = false,
+ initialHeight = GEN_UI_INITIAL_HEIGHT,
+ onHeight,
+ onError,
+ onEscape,
+}: {
+ url: string;
+ title: string;
+ /** Fill the container (expanded view) instead of following guest height. */
+ fill?: boolean;
+ /** Height before the guest reports one, e.g. the last height of a reloaded card. */
+ initialHeight?: number;
+ onHeight?: (height: number) => void;
+ /** Main served an error shell for this URL. */
+ onError?: (code: GenUiErrorCode) => void;
+ /** Escape was pressed inside the guest. */
+ onEscape?: () => void;
+}) {
+ const frameRef = useRef<HTMLIFrameElement | null>(null);
+ const [height, setHeight] = useState(initialHeight);
+ const callbacks = useRef({ onHeight, onError, onEscape });
+ useEffect(() => {
+ callbacks.current = { onHeight, onError, onEscape };
+ });
+
+ useEffect(() => {
+ const post = (message: unknown) => {
+ // The guest origin is opaque, so "*" is the only target that reaches
+ // it; theme variables and the view mode carry no secrets.
+ frameRef.current?.contentWindow?.postMessage(message, "*");
+ };
+ const postTheme = (theme: GenUiThemePayload) => post({ type: GEN_UI_THEME_MESSAGE, ...theme });
+ // Sent when the guest runtime announces itself (before first paint) and
+ // again on `load` in case the announcement raced the listener.
+ const postSetup = () => {
+ post({ type: GEN_UI_VIEW_MESSAGE, view: fill ? "expanded" : "inline" });
+ postTheme(currentGenUiTheme());
+ };
+ const onMessage = (event: MessageEvent) => {
+ const frameWindow = frameRef.current?.contentWindow;
+ const next = genUiHeightFromMessage(event, frameWindow);
+ if (next !== null) {
+ setHeight(next);
+ callbacks.current.onHeight?.(next);
+ return;
+ }
+ // Wheel input inside the out-of-process guest never reaches this
+ // document, so a scroll chaining out of the card looks programmatic to
+ // the transcript and follow mode pulls the reader back. Replay it on the
+ // frame element: an untrusted event scrolls nothing, it only lets
+ // gesture listeners attribute the scroll that the browser already does.
+ const wheel = genUiWheelFromMessage(event, frameWindow);
+ if (wheel !== null) {
+ frameRef.current?.dispatchEvent(new WheelEvent("wheel", { ...wheel, bubbles: true }));
+ return;
+ }
+ if (isGenUiReadyMessage(event, frameWindow)) {
+ postSetup();
+ return;
+ }
+ const error = genUiErrorFromMessage(event, frameWindow);
+ if (error !== null) {
+ callbacks.current.onError?.(error);
+ return;
+ }
+ if (genUiKeyFromMessage(event, frameWindow) === "Escape") callbacks.current.onEscape?.();
+ };
+ window.addEventListener("message", onMessage);
+ const frame = frameRef.current;
+ frame?.addEventListener("load", postSetup);
+ const unsubscribe = subscribeGenUiTheme(postTheme);
+ return () => {
+ window.removeEventListener("message", onMessage);
+ frame?.removeEventListener("load", postSetup);
+ unsubscribe();
+ };
+ }, [fill]);
+
+ return (
+ <iframe
+ ref={frameRef}
+ className="gen-ui-frame"
+ src={url}
+ title={title}
+ sandbox="allow-scripts"
+ loading="lazy"
+ referrerPolicy="no-referrer"
+ style={fill ? undefined : { height }}
+ />
+ );
+}
diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts
new file mode 100644
index 000000000..8950013c5
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts
@@ -0,0 +1,143 @@
+/**
+ * Pure frame-side rules for inline visualizations: which guest messages the
+ * host trusts, how reported heights are bounded, and how many guest frames may
+ * be live at once.
+ */
+import {
+ GEN_UI_ERROR_MESSAGE,
+ GEN_UI_KEY_MESSAGE,
+ GEN_UI_MAX_HEIGHT,
+ GEN_UI_MIN_HEIGHT,
+ GEN_UI_READY_MESSAGE,
+ GEN_UI_SIZE_MESSAGE,
+ GEN_UI_WHEEL_MESSAGE,
+ isGenUiErrorCode,
+ type GenUiErrorCode,
+} from "@pi-desktop/shared";
+
+type FrameMessageEvent = { source: unknown; data: unknown };
+
+/**
+ * The payload of a message from `frameWindow` with the given `type`, or null.
+ * Any guest can post to the host window, so the source check is what binds a
+ * message to its own card.
+ */
+function ownFrameMessage(
+ event: FrameMessageEvent,
+ frameWindow: unknown,
+ type: string,
+): Record<string, unknown> | null {
+ if (!frameWindow || event.source !== frameWindow) return null;
+ const data = event.data;
+ if (!data || typeof data !== "object") return null;
+ const record = data as Record<string, unknown>;
+ return record.type === type ? record : null;
+}
+
+/** Clamp a guest-reported height into the inline card's bounds. */
+export function clampGenUiHeight(height: number): number {
+ return Math.min(GEN_UI_MAX_HEIGHT, Math.max(GEN_UI_MIN_HEIGHT, Math.ceil(height)));
+}
+
+/**
+ * The bounded height from a `message` event, or `null` when the event did not
+ * come from `frameWindow` or is not a well-formed size report. Any guest can
+ * post to the host window, so the source check is what binds a report to its
+ * own card.
+ */
+export function genUiHeightFromMessage(event: FrameMessageEvent, frameWindow: unknown): number | null {
+ const record = ownFrameMessage(event, frameWindow, GEN_UI_SIZE_MESSAGE);
+ if (!record) return null;
+ const height = record.height;
+ if (typeof height !== "number" || !Number.isFinite(height)) return null;
+ return clampGenUiHeight(height);
+}
+
+export type GenUiWheel = { deltaX: number; deltaY: number; deltaMode: number };
+
+const MAX_WHEEL_DELTA = 10_000;
+
+const boundedDelta = (value: unknown): number | null =>
+ typeof value === "number" && Number.isFinite(value)
+ ? Math.max(-MAX_WHEEL_DELTA, Math.min(MAX_WHEEL_DELTA, value))
+ : null;
+
+/**
+ * A wheel report from this card's own frame, or null. The values only feed a
+ * synthetic event that never scrolls anything, but stay shape-checked and
+ * bounded because the guest is untrusted.
+ */
+export function genUiWheelFromMessage(event: FrameMessageEvent, frameWindow: unknown): GenUiWheel | null {
+ const record = ownFrameMessage(event, frameWindow, GEN_UI_WHEEL_MESSAGE);
+ if (!record) return null;
+ const deltaX = boundedDelta(record.deltaX);
+ const deltaY = boundedDelta(record.deltaY);
+ const deltaMode = record.deltaMode;
+ if (deltaX === null || deltaY === null) return null;
+ if (deltaMode !== 0 && deltaMode !== 1 && deltaMode !== 2) return null;
+ return { deltaX, deltaY, deltaMode };
+}
+
+/** The error code from this card's own frame's error shell, or null. */
+export function genUiErrorFromMessage(event: FrameMessageEvent, frameWindow: unknown): GenUiErrorCode | null {
+ const record = ownFrameMessage(event, frameWindow, GEN_UI_ERROR_MESSAGE);
+ return record && isGenUiErrorCode(record.code) ? record.code : null;
+}
+
+/** A forwarded key from this card's own frame; only `Escape` is accepted. */
+export function genUiKeyFromMessage(event: FrameMessageEvent, frameWindow: unknown): "Escape" | null {
+ const record = ownFrameMessage(event, frameWindow, GEN_UI_KEY_MESSAGE);
+ return record?.key === "Escape" ? "Escape" : null;
+}
+
+/** Whether this card's own frame announced that its runtime is running. */
+export function isGenUiReadyMessage(event: FrameMessageEvent, frameWindow: unknown): boolean {
+ return ownFrameMessage(event, frameWindow, GEN_UI_READY_MESSAGE) !== null;
+}
+
+/** Upper bound on simultaneously mounted guest frames across all panes. */
+export const GEN_UI_MAX_LIVE_FRAMES = 8;
+
+type LiveFrame = { onEvict: () => void; visible: boolean };
+
+/**
+ * Bounded set of live frames. Cards hold a slot only while near the viewport
+ * and release it when they scroll away, so the pool overflows only when many
+ * cards are near at once (tall windows, split panes). Acquiring beyond the
+ * limit evicts the longest-live frame that is off-screen, and only when every
+ * other frame is on screen the longest-live one overall. An off-screen
+ * newcomer never displaces a frame the reader is looking at: it is evicted
+ * itself and loads once it scrolls into view.
+ */
+export function createGenUiFramePool(limit = GEN_UI_MAX_LIVE_FRAMES) {
+ const live = new Map<symbol, LiveFrame>();
+ const victim = (newcomer: symbol): symbol => {
+ for (const [id, frame] of live) if (!frame.visible) return id;
+ for (const id of live.keys()) if (id !== newcomer) return id;
+ return newcomer;
+ };
+ return {
+ acquire(id: symbol, onEvict: () => void, visible = true): void {
+ live.delete(id);
+ live.set(id, { onEvict, visible });
+ while (live.size > limit) {
+ const evicted = victim(id);
+ const frame = live.get(evicted);
+ live.delete(evicted);
+ frame?.onEvict();
+ }
+ },
+ setVisible(id: symbol, visible: boolean): void {
+ const frame = live.get(id);
+ if (frame) frame.visible = visible;
+ },
+ release(id: symbol): void {
+ live.delete(id);
+ },
+ get size(): number {
+ return live.size;
+ },
+ };
+}
+
+export const genUiFramePool = createGenUiFramePool();
diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-source.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-source.ts
new file mode 100644
index 000000000..a16934b24
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-source.ts
@@ -0,0 +1,62 @@
+/**
+ * What an inline visualization card shows for a reference: a live frame URL
+ * or the reason it is unavailable.
+ */
+import {
+ genUiUrl,
+ isGenUiSessionId,
+ type GenUiErrorCode,
+ type GenUiReference,
+ type SessionSummary,
+} from "@pi-desktop/shared";
+import { isRemoteSession } from "../../../lib/remote-session-safety";
+
+export type GenUiUnavailableReason = "outside" | "remote" | GenUiErrorCode;
+
+export type GenUiCardSource =
+ | { kind: "live"; url: string }
+ | { kind: "unavailable"; reason: GenUiUnavailableReason };
+
+/** The session that renders the message; see `genUiCardSource`. */
+export type GenUiOwner = { sessionId: string; remote: boolean };
+
+/**
+ * Whether a session's tools write somewhere Main cannot serve: a RACP remote
+ * session, or a local session bound to a remote host workspace (whose runtime
+ * gets no visualization directory).
+ */
+export function isGenUiRemoteOwner(
+ sessionId: string,
+ session: Pick<SessionSummary, "source" | "remoteWorkspace"> | undefined,
+): boolean {
+ return isRemoteSession({ id: sessionId, source: session?.source }) || Boolean(session?.remoteWorkspace);
+}
+
+/**
+ * The reference path must still name a file under a visualization directory,
+ * but the card always loads the owning session's copy: a forked session gets
+ * its own copies (with rewritten paths), and a path naming another session
+ * must never reach that session's files. Remote sessions write on their host,
+ * which Main cannot serve.
+ */
+export function genUiCardSource(reference: GenUiReference, owner: GenUiOwner): GenUiCardSource {
+ if (owner.remote) return { kind: "unavailable", reason: "remote" };
+ if (!reference.location || !isGenUiSessionId(owner.sessionId)) {
+ return { kind: "unavailable", reason: "outside" };
+ }
+ return { kind: "live", url: genUiUrl({ sessionId: owner.sessionId, fileName: reference.location.fileName }) };
+}
+
+const REASON_KEYS = {
+ outside: "chat.genUi.unavailableOutside",
+ remote: "chat.genUi.unavailableRemote",
+ "not-found": "chat.genUi.unavailableNotFound",
+ "too-large": "chat.genUi.unavailableTooLarge",
+ "not-fragment": "chat.genUi.unavailableNotFragment",
+ "runtime-unavailable": "chat.genUi.unavailableRuntime",
+} as const satisfies Record<GenUiUnavailableReason, string>;
+
+/** i18n key of the reason line under an unavailable card. */
+export function genUiUnavailableReasonKey(reason: GenUiUnavailableReason): (typeof REASON_KEYS)[GenUiUnavailableReason] {
+ return REASON_KEYS[reason];
+}
diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-split.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-split.ts
new file mode 100644
index 000000000..699bff8e6
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-split.ts
@@ -0,0 +1,38 @@
+import { useMemo } from "react";
+import { splitGenUiReferences, type GenUiSplit } from "@pi-desktop/shared";
+
+const EMPTY: GenUiSplit["references"] = [];
+
+const REFERENCE_PREFIX = "::visualize";
+
+/**
+ * Drop a trailing line that is, or may still become, a `::visualize` reference
+ * so a streaming reply never flashes the raw line and its absolute path. Only
+ * the last non-blank line is considered: an earlier line is complete text.
+ */
+export function hideStreamingGenUiReference(content: string): string {
+ const trimmedEnd = content.trimEnd();
+ const lineStart = trimmedEnd.lastIndexOf("\n") + 1;
+ const line = trimmedEnd.slice(lineStart).trim();
+ if (!line) return content;
+ const partial = line.startsWith(REFERENCE_PREFIX)
+ ? line.length === REFERENCE_PREFIX.length || line[REFERENCE_PREFIX.length] === "{"
+ : REFERENCE_PREFIX.startsWith(line);
+ if (!partial) return content;
+ return trimmedEnd.slice(0, lineStart).trimEnd();
+}
+
+/**
+ * Visualization references are parsed only once a message is complete: a
+ * streaming reply may still be writing the line (or its file), and a card that
+ * appears mid-stream would flash an "unavailable" state. Until then a trailing
+ * reference line is hidden.
+ */
+export function genUiSplitFor(content: string, streaming: boolean): GenUiSplit {
+ if (streaming) return { content: hideStreamingGenUiReference(content), references: EMPTY };
+ return splitGenUiReferences(content);
+}
+
+export function useGenUiSplit(content: string, streaming: boolean): GenUiSplit {
+ return useMemo(() => genUiSplitFor(content, streaming), [content, streaming]);
+}
diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-theme.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-theme.ts
new file mode 100644
index 000000000..261c224c4
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-theme.ts
@@ -0,0 +1,143 @@
+/**
+ * Theme bridge for inline visualizations (ADR gen-ui-inline-visualization).
+ *
+ * The guest document has an opaque origin and cannot read the host's CSS, so
+ * the host resolves its own design tokens and posts them as a small, stable
+ * set of guest variables. Guest variable names are a contract with the shell
+ * Electron Main serves; host token names may change freely behind this map.
+ */
+
+/**
+ * Guest variable → host design token it is resolved from. The guest names are
+ * the MCP Apps host-style variables the bundled visualize stylesheet derives
+ * its agent-facing tokens (`--background`, `--foreground`, `--primary`, …)
+ * from; see `apps/desktop/resources/gen-ui/visualize.css`.
+ */
+export const GEN_UI_THEME_TOKENS: Readonly<Record<string, string>> = {
+ "--color-background-primary": "--ds-bg-primary",
+ "--color-background-secondary": "--ds-bg-elevated-opaque",
+ "--color-background-info": "--ds-accent-soft",
+ "--color-text-primary": "--ds-text-primary",
+ "--color-text-secondary": "--ds-text-muted",
+ "--color-text-info": "--ds-accent",
+ // Text on `--color-text-info` fills, as the primary button sets it.
+ "--color-text-inverse": "--ds-bg-primary",
+ "--color-text-warning": "--ds-warning",
+ "--color-border-primary": "--ds-border-default",
+ "--color-border-secondary": "--ds-border-subtle",
+ "--color-ring-primary": "--ds-focus",
+ "--font-sans": "--font-sans",
+ "--font-mono": "--font-mono",
+};
+
+/**
+ * Resolve guest theme variables through `readToken` (normally a computed
+ * style lookup). Tokens that resolve empty are omitted so the guest keeps its
+ * own fallback instead of receiving a blank value.
+ */
+export function genUiThemeVars(readToken: (name: string) => string): Record<string, string> {
+ const vars: Record<string, string> = {};
+ for (const [guestName, hostToken] of Object.entries(GEN_UI_THEME_TOKENS)) {
+ const value = readToken(hostToken).trim();
+ if (value) vars[guestName] = value;
+ }
+ return vars;
+}
+
+/** Guest theme variables resolved from the live document root. */
+export function readDocumentGenUiTheme(): Record<string, string> {
+ if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return {};
+ const style = getComputedStyle(document.documentElement);
+ return genUiThemeVars((name) => style.getPropertyValue(name));
+}
+
+/**
+ * The resolved light/dark scheme of the host. The visualize stylesheet uses
+ * `light-dark()` fallbacks, so the guest must follow the host rather than the
+ * OS preference.
+ */
+export function readDocumentGenUiColorScheme(): "light" | "dark" {
+ if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return "light";
+ const scheme = getComputedStyle(document.documentElement).colorScheme;
+ return /\bdark\b/.test(scheme) && !/\blight\b/.test(scheme) ? "dark" : "light";
+}
+
+/** What the host posts to a guest frame as `GEN_UI_THEME_MESSAGE`. */
+export type GenUiThemePayload = { vars: Record<string, string>; colorScheme: "light" | "dark" };
+
+export function readDocumentGenUiThemePayload(): GenUiThemePayload {
+ return { vars: readDocumentGenUiTheme(), colorScheme: readDocumentGenUiColorScheme() };
+}
+
+export function sameGenUiTheme(a: GenUiThemePayload, b: GenUiThemePayload): boolean {
+ if (a.colorScheme !== b.colorScheme) return false;
+ const keys = Object.keys(a.vars);
+ if (keys.length !== Object.keys(b.vars).length) return false;
+ return keys.every((key) => a.vars[key] === b.vars[key]);
+}
+
+/**
+ * One shared theme source for every frame. `observe` reports root mutations;
+ * each mutation resolves the theme once and notifies subscribers only when the
+ * resolved payload changed. The root `style` attribute is also rewritten for
+ * layout (e.g. the composer height on every resize), which must not re-post
+ * the theme to every frame.
+ */
+export function createGenUiThemeChannel(
+ read: () => GenUiThemePayload,
+ observe: (onMutation: () => void) => () => void,
+) {
+ const listeners = new Set<(payload: GenUiThemePayload) => void>();
+ let last: GenUiThemePayload | null = null;
+ let stop: (() => void) | null = null;
+ const refresh = () => {
+ const next = read();
+ if (last && sameGenUiTheme(last, next)) return;
+ last = next;
+ for (const listener of [...listeners]) listener(next);
+ };
+ return {
+ /** The theme resolved now, for a frame that just became ready. */
+ current(): GenUiThemePayload {
+ return read();
+ },
+ subscribe(listener: (payload: GenUiThemePayload) => void): () => void {
+ listeners.add(listener);
+ if (!stop) {
+ last = read();
+ stop = observe(refresh);
+ }
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0 && stop) {
+ stop();
+ stop = null;
+ last = null;
+ }
+ };
+ },
+ };
+}
+
+/**
+ * Attributes on the document root that change resolved tokens: the light/dark
+ * switch, contributed plugin themes, and the inline font override.
+ */
+const THEME_ATTRIBUTES = ["data-theme", "data-plugin-theme", "style"];
+
+const documentThemeChannel = createGenUiThemeChannel(readDocumentGenUiThemePayload, (onMutation) => {
+ if (typeof MutationObserver === "undefined" || typeof document === "undefined") return () => undefined;
+ const observer = new MutationObserver(onMutation);
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: THEME_ATTRIBUTES });
+ return () => observer.disconnect();
+});
+
+/** The host theme as guests should currently see it. */
+export function currentGenUiTheme(): GenUiThemePayload {
+ return documentThemeChannel.current();
+}
+
+/** Subscribe to resolved-theme changes; returns the unsubscribe function. */
+export function subscribeGenUiTheme(listener: (payload: GenUiThemePayload) => void): () => void {
+ return documentThemeChannel.subscribe(listener);
+}
diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-viewport.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-viewport.ts
new file mode 100644
index 000000000..5029985ad
--- /dev/null
+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-viewport.ts
@@ -0,0 +1,83 @@
+/**
+ * Viewport lifecycle of one inline visualization card: whether its frame is
+ * mounted. A card mounts when it nears the viewport and unmounts (releasing
+ * its live-frame slot) when it moves away, so slots follow what the reader
+ * can reach instead of the order cards were first seen.
+ */
+import { useEffect, useReducer, type RefObject } from "react";
+
+export type GenUiViewportState = {
+ /** Within the preload margin of the viewport. */
+ near: boolean;
+ /** Actually intersecting the viewport. */
+ visible: boolean;
+ /** The live-frame pool took this card's slot while it was near. */
+ evicted: boolean;
+};
+
+export type GenUiViewportEvent =
+ | { type: "near"; value: boolean }
+ | { type: "visible"; value: boolean }
+ | { type: "evict" }
+ | { type: "load" };
+
+export const GEN_UI_VIEWPORT_INITIAL: GenUiViewportState = { near: false, visible: false, evicted: false };
+
+/**
+ * Leaving the near zone clears an eviction, so re-entry reloads without a
+ * click. Scrolling an evicted card into view retries once per entry; while it
+ * stays visible it waits for the reader, which keeps two evicting cards from
+ * trading the same slot back and forth.
+ */
+export function genUiViewportReducer(state: GenUiViewportState, event: GenUiViewportEvent): GenUiViewportState {
+ switch (event.type) {
+ case "near":
+ if (!event.value) return { near: false, visible: false, evicted: false };
+ return state.near ? state : { ...state, near: true };
+ case "visible":
+ if (event.value === state.visible) return state;
+ return event.value ? { ...state, visible: true, evicted: false } : { ...state, visible: false };
+ case "evict":
+ return state.evicted ? state : { ...state, evicted: true };
+ case "load":
+ return state.evicted ? { ...state, evicted: false } : state;
+ }
+}
+
+export function isGenUiViewportLive(state: GenUiViewportState): boolean {
+ return state.near && !state.evicted;
+}
+
+/** Preload margin: frames mount a little before they scroll into view. */
+const NEAR_MARGIN = "240px 0px";
+
+/** Track `ref` against the viewport; always live without IntersectionObserver. */
+export function useGenUiViewport(ref: RefObject<HTMLElement | null>) {
+ const [state, dispatch] = useReducer(genUiViewportReducer, GEN_UI_VIEWPORT_INITIAL);
+ useEffect(() => {
+ const element = ref.current;
+ if (!element || typeof IntersectionObserver === "undefined") {
+ dispatch({ type: "near", value: true });
+ dispatch({ type: "visible", value: true });
+ return;
+ }
+ const watch = (type: "near" | "visible", rootMargin: string) => {
+ const observer = new IntersectionObserver(
+ (entries) => {
+ const entry = entries.at(-1);
+ if (entry) dispatch({ type, value: entry.isIntersecting });
+ },
+ { rootMargin },
+ );
+ observer.observe(element);
+ return observer;
+ };
+ const near = watch("near", NEAR_MARGIN);
+ const visible = watch("visible", "0px");
+ return () => {
+ near.disconnect();
+ visible.disconnect();
+ };
+ }, [ref]);
+ return [state, dispatch] as const;
+}
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
index 89f607f9c..02e57046b 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
@@ -5,6 +5,10 @@ import type { SubagentOutcome, SubagentTiming } from "../../../lib/subagent-topo
import { useAppStore } from "../../../stores/app-store";
import { Markdown } from "../../../components/Markdown";
import { useSmoothText } from "../../../hooks/useSmoothText";
+import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";
+import { GenUiCards } from "../gen-ui/GenUiCard";
+import { useGenUiSplit } from "../gen-ui/gen-ui-split";
+import { isGenUiRemoteOwner } from "../gen-ui/gen-ui-source";
import { ActivityGroup } from "./ActivityGroup";
import { AssistantErrorMessage } from "./shared";
import { useRenderBlocks, type RenderBlock } from "./render-blocks";
@@ -20,12 +24,19 @@ const SmoothMessageBubble = memo(function SmoothMessageBubble({ message, streami
const enabled = smoothStreaming && !prefersReducedMotion;
const displayContent = useSmoothText(message.content || "", streaming, enabled);
const showCursor = streaming && enabled && Boolean(displayContent);
+ const genUi = useGenUiSplit(displayContent, streaming);
+ // Cards load the pane session's own copy, never the session a path names.
+ const sessionId = useSlotSessionId();
+ const remote = useAppStore((s) =>
+ isGenUiRemoteOwner(sessionId, s.sessions.find((session) => session.id === sessionId)),
+ );
return (
<div
className={`message-bubble assistant-turn-fragment${streaming ? " streaming" : ""}${showCursor ? " smooth-cursor" : ""}`}
data-message-id={message.id}
>
- {displayContent ? <div className="prose-chat"><Markdown source={displayContent} streaming={streaming} /></div> : null}
+ {genUi.content ? <div className="prose-chat"><Markdown source={genUi.content} streaming={streaming} /></div> : null}
+ <GenUiCards references={genUi.references} sessionId={sessionId} remote={remote} />
{message.error ? <AssistantErrorMessage message={message} /> : null}
</div>
);
diff --git a/apps/desktop/src/styles/gen-ui.css b/apps/desktop/src/styles/gen-ui.css
new file mode 100644
index 000000000..098ca9a9f
--- /dev/null
+++ b/apps/desktop/src/styles/gen-ui.css
@@ -0,0 +1,118 @@
+/* Inline generative UI visualizations (ADR gen-ui-inline-visualization). */
+.gen-ui-cards {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin-top: 10px;
+}
+
+.gen-ui-card {
+ display: flex;
+ min-width: 0;
+ flex-direction: column;
+ overflow: hidden;
+ border: 1px solid var(--ds-border-default);
+ border-radius: var(--radius-md);
+ background: var(--ds-tool-row-bg);
+}
+
+.gen-ui-header {
+ display: flex;
+ min-width: 0;
+ min-height: 30px;
+ align-items: center;
+ gap: 6px;
+ padding: 2px 4px 2px 12px;
+ border-bottom: 1px solid var(--ds-border-subtle);
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm-plus);
+}
+
+.gen-ui-title {
+ min-width: 0;
+ flex: 1 1 auto;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.gen-ui-action {
+ flex: 0 0 auto;
+}
+
+.gen-ui-body {
+ min-width: 0;
+}
+
+.gen-ui-frame {
+ display: block;
+ width: 100%;
+ border: 0;
+ background: transparent;
+ color-scheme: normal;
+}
+
+.gen-ui-placeholder {
+ display: flex;
+ min-height: 120px;
+ align-items: center;
+ justify-content: center;
+ color: var(--ds-text-muted);
+}
+
+.gen-ui-card.is-unavailable {
+ flex-direction: row;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 8px 12px;
+ color: var(--ds-text-muted);
+ font-size: var(--text-sm-plus);
+}
+
+.gen-ui-unavailable-icon {
+ flex: 0 0 auto;
+ margin-top: 2px;
+}
+
+.gen-ui-unavailable-text {
+ display: flex;
+ min-width: 0;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.gen-ui-unavailable-text .gen-ui-title {
+ color: var(--ds-text-secondary);
+}
+
+.gen-ui-unavailable-reason {
+ font-size: var(--text-xs);
+}
+
+.gen-ui-dialog {
+ display: flex;
+ width: min(100%, 1100px);
+ height: min(86vh, 900px);
+ flex-direction: column;
+ overflow: hidden;
+ padding: 0;
+}
+
+.gen-ui-dialog-body {
+ min-height: 0;
+ flex: 1 1 auto;
+}
+
+.gen-ui-dialog-body .gen-ui-frame {
+ height: 100%;
+}
+
+/* Focus guards around the expanded dialog; see GenUiDialog. */
+.gen-ui-focus-guard {
+ position: fixed;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ opacity: 0;
+ pointer-events: none;
+}
diff --git a/apps/desktop/test/gen-ui-card.test.mjs b/apps/desktop/test/gen-ui-card.test.mjs
new file mode 100644
index 000000000..d61c2e122
--- /dev/null
+++ b/apps/desktop/test/gen-ui-card.test.mjs
@@ -0,0 +1,213 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import { createElement } from "react";
+import { catalogs } from "@pi-desktop/i18n";
+import { slotSsr } from "./helpers/slot-ssr.mjs";
+
+const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
+
+const SESSION = "sess_1";
+const VIS_PATH = `/Users/me/.pi-desktop/visualizations/${SESSION}/chart.html`;
+const MESSAGE = `Here is the chart.\n\n::visualize{"path":"${VIS_PATH}","title":"Growth"}`;
+
+test("references are split out only once the message is no longer streaming", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiSplitFor } = await ssr.load("/src/features/chat/gen-ui/gen-ui-split.ts");
+
+ const streaming = genUiSplitFor(MESSAGE, true);
+ // The trailing reference line is hidden while streaming, not parsed.
+ assert.equal(streaming.content, "Here is the chart.");
+ assert.deepEqual(streaming.references, []);
+
+ const done = genUiSplitFor(MESSAGE, false);
+ assert.equal(done.content, "Here is the chart.");
+ assert.equal(done.references.length, 1);
+ assert.equal(done.references[0].title, "Growth");
+ assert.deepEqual(done.references[0].location, { sessionId: SESSION, fileName: "chart.html" });
+});
+
+test("the assistant bubble renders split content and cards; Markdown stays gen-ui free", async () => {
+ const bubble = await read("../src/features/chat/transcript/AssistantTurnParts.tsx");
+ assert.match(bubble, /const genUi = useGenUiSplit\(displayContent, streaming\);/);
+ assert.match(bubble, /<Markdown source=\{genUi\.content\} streaming=\{streaming\} \/>/);
+ assert.match(bubble, /<GenUiCards references=\{genUi\.references\} sessionId=\{sessionId\} remote=\{remote\} \/>/);
+ assert.match(bubble, /const sessionId = useSlotSessionId\(\);/);
+ const markdown = await read("../src/components/Markdown.tsx");
+ assert.doesNotMatch(markdown, /gen-ui|genUi|GenUi/);
+});
+
+test("the guest frame is sandboxed to scripts only with an opaque origin", async (t) => {
+ const ssr = await slotSsr(t);
+ const { GenUiFrame } = await ssr.load("/src/features/chat/gen-ui/GenUiFrame.tsx");
+ const html = ssr.render(
+ createElement(GenUiFrame, { url: `pi-genui://session/${SESSION}/chart.html`, title: "Visualization: Growth" }),
+ );
+ const sandbox = /<iframe[^>]* sandbox="([^"]*)"/.exec(html);
+ assert.ok(sandbox, html);
+ assert.equal(sandbox[1], "allow-scripts");
+ assert.doesNotMatch(html, /allow-same-origin|allow-popups|allow-forms|allow-top-navigation/);
+ assert.match(html, /src="pi-genui:\/\/session\/sess_1\/chart\.html"/);
+ assert.match(html, /referrerPolicy="no-referrer"|referrerpolicy="no-referrer"/);
+ assert.match(html, /loading="lazy"/);
+ assert.match(html, /height:240px/);
+});
+
+test("size reports are honored only from the card's own frame and are clamped", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiHeightFromMessage, clampGenUiHeight } = await ssr.load(
+ "/src/features/chat/gen-ui/gen-ui-frames.ts",
+ );
+ const own = {};
+ const other = {};
+ const report = (height, source = own, type = "pi-genui:size") => ({ source, data: { type, height } });
+
+ assert.equal(genUiHeightFromMessage(report(480), own), 480);
+ assert.equal(genUiHeightFromMessage(report(480, other), own), null);
+ assert.equal(genUiHeightFromMessage(report(480), null), null);
+ assert.equal(genUiHeightFromMessage(report(480, own, "pi-genui:theme"), own), null);
+ assert.equal(genUiHeightFromMessage(report(Number.NaN), own), null);
+ assert.equal(genUiHeightFromMessage(report("480"), own), null);
+ assert.equal(genUiHeightFromMessage({ source: own, data: "pi-genui:size" }, own), null);
+ assert.equal(genUiHeightFromMessage(report(10), own), 120);
+ assert.equal(genUiHeightFromMessage(report(99999), own), 2000);
+ assert.equal(clampGenUiHeight(300.2), 301);
+});
+
+test("wheel reports are honored only from the card's own frame and are bounded", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiWheelFromMessage } = await ssr.load("/src/features/chat/gen-ui/gen-ui-frames.ts");
+ const own = {};
+ const wheel = (data, source = own) => ({ source, data: { type: "pi-genui:wheel", ...data } });
+
+ assert.deepEqual(genUiWheelFromMessage(wheel({ deltaX: 0, deltaY: -120, deltaMode: 0 }), own), {
+ deltaX: 0,
+ deltaY: -120,
+ deltaMode: 0,
+ });
+ assert.equal(genUiWheelFromMessage(wheel({ deltaX: 0, deltaY: -120, deltaMode: 0 }, {}), own), null);
+ assert.equal(genUiWheelFromMessage(wheel({ deltaX: 0, deltaY: -120, deltaMode: 0 }), null), null);
+ assert.equal(genUiWheelFromMessage(wheel({ deltaX: 0, deltaY: "x", deltaMode: 0 }), own), null);
+ assert.equal(genUiWheelFromMessage(wheel({ deltaX: 0, deltaY: 1, deltaMode: 7 }), own), null);
+ assert.deepEqual(genUiWheelFromMessage(wheel({ deltaX: 1e9, deltaY: -1e9, deltaMode: 0 }), own), {
+ deltaX: 10000,
+ deltaY: -10000,
+ deltaMode: 0,
+ });
+});
+
+test("guest wheel input reaches the transcript as a gesture on the frame element", async () => {
+ // The guest is an out-of-process frame: its wheel events never reach the
+ // transcript's gesture listeners, so a scroll that chains out of the card
+ // looked programmatic and follow mode dragged the reader back down.
+ const frame = await read("../src/features/chat/gen-ui/GenUiFrame.tsx");
+ assert.match(frame, /const frameWindow = frameRef\.current\?\.contentWindow;/);
+ assert.match(frame, /genUiWheelFromMessage\(event, frameWindow\)/);
+ assert.match(frame, /new WheelEvent\("wheel", \{ \.\.\.wheel, bubbles: true \}\)/);
+ const shell = await read("../electron/main/gen-ui-document.ts");
+ assert.match(shell, /addEventListener\("wheel", \(event\) => \{/);
+ assert.match(shell, /\{ passive: true \}/);
+});
+
+test("the expanded view tells its guest to center content", async () => {
+ // A fragment laid out for the narrow inline card otherwise sits in the
+ // top-left corner of the much larger dialog.
+ const frame = await read("../src/features/chat/gen-ui/GenUiFrame.tsx");
+ assert.match(frame, /type: GEN_UI_VIEW_MESSAGE, view: fill \? "expanded" : "inline"/);
+ const shell = await read("../electron/main/gen-ui-document.ts");
+ assert.match(shell, /root\.dataset\.piGenuiView = data\.view/);
+ assert.match(
+ shell,
+ /html\[data-pi-genui-view="expanded"\] body \{[^}]*min-height: 100vh;[^}]*justify-content: safe center;[^}]*align-items: safe center;/,
+ );
+});
+
+test("the live-frame pool evicts the oldest frame beyond its limit", async (t) => {
+ const ssr = await slotSsr(t);
+ const { createGenUiFramePool } = await ssr.load("/src/features/chat/gen-ui/gen-ui-frames.ts");
+ const pool = createGenUiFramePool(2);
+ const evicted = [];
+ const [a, b, c] = [Symbol("a"), Symbol("b"), Symbol("c")];
+ pool.acquire(a, () => evicted.push("a"));
+ pool.acquire(b, () => evicted.push("b"));
+ pool.acquire(c, () => evicted.push("c"));
+ assert.deepEqual(evicted, ["a"]);
+ assert.equal(pool.size, 2);
+ pool.release(b);
+ pool.acquire(a, () => evicted.push("a"));
+ assert.deepEqual(evicted, ["a"]);
+ assert.equal(pool.size, 2);
+});
+
+test("theme variables map from host design tokens and skip empty values", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiThemeVars, GEN_UI_THEME_TOKENS } = await ssr.load(
+ "/src/features/chat/gen-ui/gen-ui-theme.ts",
+ );
+ const tokens = { "--ds-text-primary": " #fff ", "--ds-bg-primary": "#181818", "--font-mono": "" };
+ const vars = genUiThemeVars((name) => tokens[name] ?? "");
+ assert.deepEqual(vars, {
+ "--color-text-primary": "#fff",
+ "--color-background-primary": "#181818",
+ "--color-text-inverse": "#181818",
+ });
+
+ // Every posted guest variable is one the bundled visualize stylesheet reads.
+ const kitSheet = await read("../resources/gen-ui/visualize.css");
+ for (const guestName of Object.keys(GEN_UI_THEME_TOKENS)) {
+ assert.match(kitSheet, new RegExp(`var\\(\\s*${guestName}[,)\\s]`), guestName);
+ }
+
+ const tokenSheet = await read("../src/styles/tokens.css");
+ for (const hostToken of Object.values(GEN_UI_THEME_TOKENS)) {
+ assert.match(tokenSheet, new RegExp(`${hostToken}:`), hostToken);
+ }
+});
+
+test("a reference outside the visualization directory renders an unavailable card", async (t) => {
+ const ssr = await slotSsr(t);
+ const { GenUiCard } = await ssr.load("/src/features/chat/gen-ui/GenUiCard.tsx");
+ const html = ssr.render(
+ createElement(GenUiCard, {
+ reference: { path: "/tmp/evil.html", title: undefined, location: null },
+ sessionId: SESSION,
+ remote: false,
+ }),
+ );
+ assert.match(html, /gen-ui-card is-unavailable/);
+ assert.match(html, /Visualization unavailable: evil\.html/);
+ assert.match(html, new RegExp(catalogs.en.chat.genUi.unavailableOutside.replace("'", "&#x27;")));
+ assert.doesNotMatch(html, /<iframe/);
+});
+
+test("a live card starts as a placeholder with a localized expand control", async (t) => {
+ const ssr = await slotSsr(t);
+ const { GenUiCard } = await ssr.load("/src/features/chat/gen-ui/GenUiCard.tsx");
+ const html = ssr.render(
+ createElement(GenUiCard, {
+ reference: { path: VIS_PATH, title: "Growth", location: { sessionId: SESSION, fileName: "chart.html" } },
+ sessionId: SESSION,
+ remote: false,
+ }),
+ );
+ assert.match(html, /data-gen-ui-url="pi-genui:\/\/session\/sess_1\/chart\.html"/);
+ assert.match(html, />Growth</);
+ assert.match(html, /aria-label="Expand visualization"/);
+ // Frames mount only after the card nears the viewport (an effect).
+ assert.doesNotMatch(html, /<iframe/);
+});
+
+test("every locale defines the gen-ui strings", () => {
+ const keys = ["expand", "close", "unavailable", "unavailableOutside", "loadPrompt", "frameTitle"];
+ for (const [locale, catalog] of Object.entries(catalogs)) {
+ for (const key of keys) {
+ const value = catalog.chat?.genUi?.[key];
+ assert.equal(typeof value, "string", `${locale} chat.genUi.${key}`);
+ assert.ok(value.trim(), `${locale} chat.genUi.${key}`);
+ }
+ for (const key of ["unavailable", "frameTitle"]) {
+ assert.match(catalog.chat.genUi[key], /\{\{title\}\}/, `${locale} ${key}`);
+ }
+ }
+ assert.equal(Object.keys(catalogs).length, 9);
+});
diff --git a/apps/desktop/test/gen-ui-runtime.test.mjs b/apps/desktop/test/gen-ui-runtime.test.mjs
new file mode 100644
index 000000000..0e9927452
--- /dev/null
+++ b/apps/desktop/test/gen-ui-runtime.test.mjs
@@ -0,0 +1,262 @@
+/**
+ * Behavior of the inline-visualization host runtime: guest message parsing,
+ * the error / ready / key channel, theme re-post diffing, streaming reference
+ * hiding, the live-frame eviction policy, and which URL a card loads.
+ */
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+import { createElement } from "react";
+import { catalogs } from "@pi-desktop/i18n";
+import { slotSsr } from "./helpers/slot-ssr.mjs";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const SESSION = "sess_owner";
+const FORKED_FROM = "sess_parent";
+const VIS_PATH = `/Users/me/.pi-desktop/visualizations/${FORKED_FROM}/chart.html`;
+
+test("error, key, and ready messages are honored only from the card's own frame", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiErrorFromMessage, genUiKeyFromMessage, isGenUiReadyMessage } = await ssr.load(
+ "/src/features/chat/gen-ui/gen-ui-frames.ts",
+ );
+ const own = {};
+ const other = {};
+ const event = (data, source = own) => ({ source, data });
+
+ assert.equal(genUiErrorFromMessage(event({ type: "pi-genui:error", code: "not-found" }), own), "not-found");
+ assert.equal(genUiErrorFromMessage(event({ type: "pi-genui:error", code: "too-large" }), own), "too-large");
+ assert.equal(genUiErrorFromMessage(event({ type: "pi-genui:error", code: "not-found" }, other), own), null);
+ assert.equal(genUiErrorFromMessage(event({ type: "pi-genui:error", code: "not-found" }), null), null);
+ assert.equal(genUiErrorFromMessage(event({ type: "pi-genui:error", code: "/etc/passwd" }), own), null);
+ assert.equal(genUiErrorFromMessage(event({ type: "pi-genui:size", code: "not-found" }), own), null);
+ assert.equal(genUiErrorFromMessage(event("pi-genui:error"), own), null);
+
+ assert.equal(genUiKeyFromMessage(event({ type: "pi-genui:key", key: "Escape" }), own), "Escape");
+ assert.equal(genUiKeyFromMessage(event({ type: "pi-genui:key", key: "Escape" }, other), own), null);
+ assert.equal(genUiKeyFromMessage(event({ type: "pi-genui:key", key: "Enter" }), own), null);
+ assert.equal(genUiKeyFromMessage(event({ type: "pi-genui:error", key: "Escape" }), own), null);
+
+ assert.equal(isGenUiReadyMessage(event({ type: "pi-genui:ready" }), own), true);
+ assert.equal(isGenUiReadyMessage(event({ type: "pi-genui:ready" }, other), own), false);
+ assert.equal(isGenUiReadyMessage(event({ type: "pi-genui:ready" }), null), false);
+ assert.equal(isGenUiReadyMessage(event({ type: "pi-genui:size" }), own), false);
+});
+
+test("the error shell reports a code and never echoes caller text", async () => {
+ const { buildGenUiErrorDocument } = await import("../electron/main/gen-ui-document.ts");
+ for (const code of ["not-found", "too-large", "not-fragment", "runtime-unavailable"]) {
+ const html = buildGenUiErrorDocument(code);
+ assert.match(html, new RegExp(`"type":"pi-genui:error","code":"${code}"`), code);
+ // English fallback content stays in case the host cannot localize.
+ assert.match(html, /<p[^>]*>Visualization[^<]+<\/p>/, code);
+ }
+ assert.match(buildGenUiErrorDocument("not-found"), />Visualization not found\.</);
+ // An unknown code (e.g. a caller passing a message) degrades to not-found.
+ const unknown = buildGenUiErrorDocument("<b>x</b>");
+ assert.doesNotMatch(unknown, /<b>x<\/b>|&lt;b&gt;/);
+ assert.match(unknown, /"code":"not-found"/);
+});
+
+test("the guest runtime announces readiness and forwards only Escape", async () => {
+ const { buildGenUiDocument } = await import("../electron/main/gen-ui-document.ts");
+ const html = buildGenUiDocument("<p>hi</p>", { kit: { css: "", runtime: "", vendorUrls: new Map() } });
+ const head = html.slice(0, html.indexOf("</head>"));
+ assert.match(head, /const READY = "pi-genui:ready"/);
+ assert.match(head, /parent\.postMessage\(\{ type: READY \}, "\*"\)/);
+ assert.match(head, /const KEY = "pi-genui:key"/);
+ assert.match(head, /event\.key !== "Escape"/);
+ assert.match(head, /parent\.postMessage\(\{ type: KEY, key: "Escape" \}, "\*"\)/);
+});
+
+test("theme changes notify frames only when resolved values change", async (t) => {
+ const ssr = await slotSsr(t);
+ const { createGenUiThemeChannel } = await ssr.load("/src/features/chat/gen-ui/gen-ui-theme.ts");
+ let theme = { vars: { "--color-text-primary": "#fff" }, colorScheme: "dark" };
+ let reads = 0;
+ let mutate = null;
+ let observing = 0;
+ const channel = createGenUiThemeChannel(
+ () => {
+ reads += 1;
+ return { vars: { ...theme.vars }, colorScheme: theme.colorScheme };
+ },
+ (onMutation) => {
+ observing += 1;
+ mutate = onMutation;
+ return () => {
+ observing -= 1;
+ mutate = null;
+ };
+ },
+ );
+ const seen = [[], []];
+ const off0 = channel.subscribe((payload) => seen[0].push(payload));
+ const off1 = channel.subscribe((payload) => seen[1].push(payload));
+ assert.equal(observing, 1, "one shared observer");
+
+ // A style rewrite that changes no token (e.g. composer resize) posts nothing.
+ const before = reads;
+ mutate();
+ mutate();
+ assert.deepEqual(seen, [[], []]);
+ assert.equal(reads - before, 2, "resolved once per mutation, not once per frame");
+
+ theme = { vars: { "--color-text-primary": "#000" }, colorScheme: "light" };
+ mutate();
+ assert.equal(seen[0].length, 1);
+ assert.deepEqual(seen[0][0], theme);
+ assert.deepEqual(seen[1], seen[0]);
+ mutate();
+ assert.equal(seen[0].length, 1);
+ assert.deepEqual(channel.current(), theme);
+
+ off0();
+ off1();
+ assert.equal(observing, 0, "observer released with the last subscriber");
+});
+
+test("a streaming reply hides a trailing reference line, even a partial one", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiSplitFor, hideStreamingGenUiReference } = await ssr.load(
+ "/src/features/chat/gen-ui/gen-ui-split.ts",
+ );
+ const body = "Here is the chart.\n\n";
+ for (const tail of [":", "::", "::vis", "::visualize", '::visualize{"path":"/Users/me/x', " ::visualize{}"]) {
+ assert.equal(hideStreamingGenUiReference(`${body}${tail}`), "Here is the chart.", tail);
+ assert.equal(genUiSplitFor(`${body}${tail}`, true).content, "Here is the chart.", tail);
+ assert.deepEqual(genUiSplitFor(`${body}${tail}`, true).references, []);
+ }
+ assert.equal(hideStreamingGenUiReference(`${body}::visualize{}\n`), "Here is the chart.");
+ assert.equal(hideStreamingGenUiReference("::vis"), "");
+ for (const content of [`${body}Done.`, `${body}::other`, `${body}a ::visualize`, "x\n::visualizer", "plain"]) {
+ assert.equal(hideStreamingGenUiReference(content), content, content);
+ }
+});
+
+test("eviction prefers off-screen frames and only then the oldest", async (t) => {
+ const ssr = await slotSsr(t);
+ const { createGenUiFramePool, GEN_UI_MAX_LIVE_FRAMES } = await ssr.load(
+ "/src/features/chat/gen-ui/gen-ui-frames.ts",
+ );
+ assert.equal(GEN_UI_MAX_LIVE_FRAMES, 8);
+ const pool = createGenUiFramePool(2);
+ const evicted = [];
+ const [a, b, c, d] = [Symbol("a"), Symbol("b"), Symbol("c"), Symbol("d")];
+ pool.acquire(a, () => evicted.push("a"), true);
+ pool.acquire(b, () => evicted.push("b"), true);
+ pool.setVisible(b, false);
+ pool.acquire(c, () => evicted.push("c"), true);
+ assert.deepEqual(evicted, ["b"], "the off-screen frame goes before the older visible one");
+ // An off-screen newcomer does not push out frames the reader is looking at.
+ pool.acquire(d, () => evicted.push("d"), false);
+ assert.deepEqual(evicted, ["b", "d"]);
+ assert.equal(pool.size, 2);
+ pool.release(a);
+ assert.equal(pool.size, 1);
+});
+
+test("a card releases its frame off-screen and reloads on re-entry", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiViewportReducer, GEN_UI_VIEWPORT_INITIAL, isGenUiViewportLive } = await ssr.load(
+ "/src/features/chat/gen-ui/gen-ui-viewport.ts",
+ );
+ let state = GEN_UI_VIEWPORT_INITIAL;
+ const step = (event) => {
+ state = genUiViewportReducer(state, event);
+ return isGenUiViewportLive(state);
+ };
+ assert.equal(isGenUiViewportLive(state), false);
+ assert.equal(step({ type: "near", value: true }), true);
+ assert.equal(step({ type: "visible", value: true }), true);
+ assert.equal(step({ type: "evict" }), false, "evicted while on screen shows the load prompt");
+ assert.equal(step({ type: "load" }), true, "manual load");
+ assert.equal(step({ type: "evict" }), false);
+ assert.equal(step({ type: "visible", value: true }), false, "no reload storm while it stays visible");
+ assert.equal(step({ type: "visible", value: false }), false);
+ assert.equal(step({ type: "visible", value: true }), true, "scrolling back into view reloads");
+ assert.equal(step({ type: "evict" }), false);
+ assert.equal(step({ type: "near", value: false }), false, "leaving releases the slot");
+ assert.equal(state.evicted, false);
+ assert.equal(step({ type: "near", value: true }), true, "re-entry reloads without a click");
+});
+
+test("cards load the owning session's copy and refuse remote sessions", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiCardSource } = await ssr.load("/src/features/chat/gen-ui/gen-ui-source.ts");
+ const reference = { path: VIS_PATH, title: "Growth", location: { sessionId: FORKED_FROM, fileName: "chart.html" } };
+ assert.deepEqual(genUiCardSource(reference, { sessionId: SESSION, remote: false }), {
+ kind: "live",
+ url: `pi-genui://session/${SESSION}/chart.html`,
+ });
+ assert.deepEqual(genUiCardSource(reference, { sessionId: SESSION, remote: true }), {
+ kind: "unavailable",
+ reason: "remote",
+ });
+ assert.deepEqual(genUiCardSource({ path: "/tmp/x.html", location: null }, { sessionId: SESSION, remote: false }), {
+ kind: "unavailable",
+ reason: "outside",
+ });
+ assert.deepEqual(genUiCardSource(reference, { sessionId: "", remote: false }), {
+ kind: "unavailable",
+ reason: "outside",
+ });
+ assert.deepEqual(genUiCardSource(reference, { sessionId: "native-pi:abc", remote: false }), {
+ kind: "unavailable",
+ reason: "outside",
+ });
+});
+
+test("a remote session renders the localized unavailable card without a frame", async (t) => {
+ const ssr = await slotSsr(t);
+ const { GenUiCards } = await ssr.load("/src/features/chat/gen-ui/GenUiCard.tsx");
+ const html = ssr.render(
+ createElement(GenUiCards, {
+ references: [{ path: VIS_PATH, title: "Growth", location: { sessionId: FORKED_FROM, fileName: "chart.html" } }],
+ sessionId: SESSION,
+ remote: true,
+ }),
+ );
+ assert.match(html, /gen-ui-card is-unavailable/);
+ assert.match(html, new RegExp(catalogs.en.chat.genUi.unavailableRemote.replace("'", "&#x27;")));
+ assert.doesNotMatch(html, /<iframe|data-gen-ui-url/);
+
+ const live = ssr.render(
+ createElement(GenUiCards, {
+ references: [{ path: VIS_PATH, title: "Growth", location: { sessionId: FORKED_FROM, fileName: "chart.html" } }],
+ sessionId: SESSION,
+ remote: false,
+ }),
+ );
+ assert.match(live, new RegExp(`data-gen-ui-url="pi-genui://session/${SESSION}/chart\\.html"`));
+});
+
+test("every locale has a reason for each unavailable state", () => {
+ const keys = [
+ "unavailableRemote",
+ "unavailableNotFound",
+ "unavailableTooLarge",
+ "unavailableNotFragment",
+ "unavailableRuntime",
+ ];
+ for (const [locale, catalog] of Object.entries(catalogs)) {
+ for (const key of keys) {
+ const value = catalog.chat?.genUi?.[key];
+ assert.equal(typeof value, "string", `${locale} chat.genUi.${key}`);
+ assert.ok(value.trim(), `${locale} chat.genUi.${key}`);
+ }
+ }
+});
+
+test("the expanded dialog traps Tab and closes on the guest's Escape", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiDialogTabTarget } = await ssr.load("/src/features/chat/gen-ui/GenUiDialog.tsx");
+ const [first, middle, last] = [{ id: "first" }, { id: "middle" }, { id: "last" }];
+ const focusable = [first, middle, last];
+ assert.equal(genUiDialogTabTarget(focusable, last, false), first);
+ assert.equal(genUiDialogTabTarget(focusable, first, true), last);
+ assert.equal(genUiDialogTabTarget(focusable, middle, false), null);
+ assert.equal(genUiDialogTabTarget(focusable, { id: "outside" }, false), first);
+ assert.equal(genUiDialogTabTarget([], first, false), null);
+});
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 9be23e871..6c387977e 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -648,6 +648,19 @@ export const de = {
"tool": "Tool",
"userMessage": "Benutzernachricht",
"assistantMessage": "Assistentennachricht",
+ "genUi": {
+ "expand": "Visualisierung vergrößern",
+ "close": "Visualisierung schließen",
+ "unavailable": "Visualisierung nicht verfügbar: {{title}}",
+ "unavailableOutside": "Die Datei liegt außerhalb des Visualisierungsverzeichnisses dieser Sitzung.",
+ "unavailableRemote": "Remote-Sitzungen können keine Inline-Visualisierungen anzeigen.",
+ "unavailableNotFound": "Die Visualisierungsdatei wurde nicht gefunden.",
+ "unavailableTooLarge": "Die Visualisierungsdatei ist zu groß für die Anzeige.",
+ "unavailableNotFragment": "Die Datei ist ein vollständiges HTML-Dokument, kein Fragment.",
+ "unavailableRuntime": "Die Visualisierungslaufzeit ist nicht verfügbar.",
+ "loadPrompt": "Visualisierung laden",
+ "frameTitle": "Visualisierung: {{title}}",
+ },
"model": "Modell",
recentModels: "Zuletzt verwendet",
otherModels: "Weitere Modelle",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index ed9da2a67..fd0f834f4 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -660,6 +660,19 @@ export const en = {
tool: "Tool",
userMessage: "User message",
assistantMessage: "Assistant message",
+ genUi: {
+ expand: "Expand visualization",
+ close: "Close visualization",
+ unavailable: "Visualization unavailable: {{title}}",
+ unavailableOutside: "The file is outside this session's visualization directory.",
+ unavailableRemote: "Remote sessions cannot show inline visualizations.",
+ unavailableNotFound: "The visualization file was not found.",
+ unavailableTooLarge: "The visualization file is too large to display.",
+ unavailableNotFragment: "The file is a full HTML document, not a fragment.",
+ unavailableRuntime: "The visualization runtime is unavailable.",
+ loadPrompt: "Load visualization",
+ frameTitle: "Visualization: {{title}}",
+ },
model: "Model",
recentModels: "Recently used",
otherModels: "Other models",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index f5b0e4233..ef414a2a8 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -648,6 +648,19 @@ export const es = {
"tool": "Herramienta",
"userMessage": "Mensaje de usuario",
"assistantMessage": "Mensaje del asistente",
+ "genUi": {
+ "expand": "Ampliar visualización",
+ "close": "Cerrar visualización",
+ "unavailable": "Visualización no disponible: {{title}}",
+ "unavailableOutside": "El archivo está fuera del directorio de visualizaciones de esta sesión.",
+ "unavailableRemote": "Las sesiones remotas no pueden mostrar visualizaciones integradas.",
+ "unavailableNotFound": "No se encontró el archivo de visualización.",
+ "unavailableTooLarge": "El archivo de visualización es demasiado grande para mostrarse.",
+ "unavailableNotFragment": "El archivo es un documento HTML completo, no un fragmento.",
+ "unavailableRuntime": "El entorno de ejecución de visualizaciones no está disponible.",
+ "loadPrompt": "Cargar visualización",
+ "frameTitle": "Visualización: {{title}}",
+ },
"model": "Modelo",
recentModels: "Usados recientemente",
otherModels: "Otros modelos",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 7bcb32202..411597eb8 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -648,6 +648,19 @@ export const fr = {
"tool": "Outil",
"userMessage": "Message utilisateur",
"assistantMessage": "Message de l'assistant",
+ "genUi": {
+ "expand": "Agrandir la visualisation",
+ "close": "Fermer la visualisation",
+ "unavailable": "Visualisation indisponible : {{title}}",
+ "unavailableOutside": "Le fichier se trouve hors du dossier de visualisations de cette session.",
+ "unavailableRemote": "Les sessions distantes ne peuvent pas afficher de visualisations intégrées.",
+ "unavailableNotFound": "Le fichier de visualisation est introuvable.",
+ "unavailableTooLarge": "Le fichier de visualisation est trop volumineux pour être affiché.",
+ "unavailableNotFragment": "Le fichier est un document HTML complet, pas un fragment.",
+ "unavailableRuntime": "L'environnement d'exécution des visualisations est indisponible.",
+ "loadPrompt": "Charger la visualisation",
+ "frameTitle": "Visualisation : {{title}}",
+ },
"model": "Modèle",
recentModels: "Récemment utilisés",
otherModels: "Autres modèles",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 3acb0bf81..45c2ad1c4 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -657,6 +657,19 @@ export const ko = {
tool: "도구",
userMessage: "사용자 메시지",
assistantMessage: "어시스턴트 메시지",
+ genUi: {
+ expand: "시각화 확대",
+ close: "시각화 닫기",
+ unavailable: "시각화를 사용할 수 없음: {{title}}",
+ unavailableOutside: "파일이 이 세션의 시각화 디렉터리 밖에 있습니다.",
+ unavailableRemote: "원격 세션에서는 인라인 시각화를 표시할 수 없습니다.",
+ unavailableNotFound: "시각화 파일을 찾을 수 없습니다.",
+ unavailableTooLarge: "시각화 파일이 너무 커서 표시할 수 없습니다.",
+ unavailableNotFragment: "파일이 조각이 아닌 완전한 HTML 문서입니다.",
+ unavailableRuntime: "시각화 런타임을 사용할 수 없습니다.",
+ loadPrompt: "시각화 불러오기",
+ frameTitle: "시각화: {{title}}",
+ },
model: "모델",
recentModels: "최근 사용",
otherModels: "다른 모델",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index f4c4d842e..9f58764ef 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -647,6 +647,19 @@ export const ptBR = {
tool: "Ferramenta",
userMessage: "Mensagem do usuário",
assistantMessage: "Mensagem do assistente",
+ genUi: {
+ expand: "Expandir visualização",
+ close: "Fechar visualização",
+ unavailable: "Visualização indisponível: {{title}}",
+ unavailableOutside: "O arquivo está fora do diretório de visualizações desta sessão.",
+ unavailableRemote: "Sessões remotas não podem exibir visualizações embutidas.",
+ unavailableNotFound: "O arquivo de visualização não foi encontrado.",
+ unavailableTooLarge: "O arquivo de visualização é grande demais para ser exibido.",
+ unavailableNotFragment: "O arquivo é um documento HTML completo, não um fragmento.",
+ unavailableRuntime: "O runtime de visualizações não está disponível.",
+ loadPrompt: "Carregar visualização",
+ frameTitle: "Visualização: {{title}}",
+ },
model: "Modelo",
recentModels: "Usados recentemente",
otherModels: "Outros modelos",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index fd807b195..f95093781 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -657,6 +657,19 @@ export const tr = {
tool: "Araç",
userMessage: "Kullanıcı iletisi",
assistantMessage: "Asistan iletisi",
+ genUi: {
+ expand: "Görselleştirmeyi genişlet",
+ close: "Görselleştirmeyi kapat",
+ unavailable: "Görselleştirme kullanılamıyor: {{title}}",
+ unavailableOutside: "Dosya bu oturumun görselleştirme dizininin dışında.",
+ unavailableRemote: "Uzak oturumlar satır içi görselleştirme gösteremez.",
+ unavailableNotFound: "Görselleştirme dosyası bulunamadı.",
+ unavailableTooLarge: "Görselleştirme dosyası görüntülenemeyecek kadar büyük.",
+ unavailableNotFragment: "Dosya bir parça değil, tam bir HTML belgesi.",
+ unavailableRuntime: "Görselleştirme çalışma zamanı kullanılamıyor.",
+ loadPrompt: "Görselleştirmeyi yükle",
+ frameTitle: "Görselleştirme: {{title}}",
+ },
model: "Model",
recentModels: "Son kullanılanlar",
otherModels: "Diğer modeller",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 968c3b4d8..8aa583c1a 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -653,6 +653,19 @@ export const zhCN = {
tool: "工具",
userMessage: "用户消息",
assistantMessage: "助手消息",
+ genUi: {
+ expand: "展开可视化",
+ close: "关闭可视化",
+ unavailable: "可视化不可用:{{title}}",
+ unavailableOutside: "该文件不在本会话的可视化目录中。",
+ unavailableRemote: "远程会话无法显示内联可视化。",
+ unavailableNotFound: "未找到可视化文件。",
+ unavailableTooLarge: "可视化文件过大,无法显示。",
+ unavailableNotFragment: "该文件是完整的 HTML 文档,而非片段。",
+ unavailableRuntime: "可视化运行时不可用。",
+ loadPrompt: "加载可视化",
+ frameTitle: "可视化:{{title}}",
+ },
model: "模型",
recentModels: "最近使用",
otherModels: "其他模型",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 998ecc381..4f427611b 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -653,6 +653,19 @@ export const zhTW = {
tool: "工具",
userMessage: "使用者訊息",
assistantMessage: "助手訊息",
+ genUi: {
+ expand: "展開視覺化",
+ close: "關閉視覺化",
+ unavailable: "視覺化無法使用:{{title}}",
+ unavailableOutside: "此檔案不在本工作階段的視覺化目錄中。",
+ unavailableRemote: "遠端工作階段無法顯示內嵌視覺化。",
+ unavailableNotFound: "找不到視覺化檔案。",
+ unavailableTooLarge: "視覺化檔案過大,無法顯示。",
+ unavailableNotFragment: "此檔案是完整的 HTML 文件,而非片段。",
+ unavailableRuntime: "視覺化執行環境無法使用。",
+ loadPrompt: "載入視覺化",
+ frameTitle: "視覺化:{{title}}",
+ },
model: "模型",
recentModels: "最近使用",
otherModels: "其他模型",