Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(agent-runtime): teach agents to write inline visualizations
zszz3591d9e72ecb0
diff --git a/apps/desktop/electron/main/builtin-skills.ts b/apps/desktop/electron/main/builtin-skills.tsindex c558e1b27..3ad35c7ba 100644--- a/apps/desktop/electron/main/builtin-skills.ts+++ b/apps/desktop/electron/main/builtin-skills.ts@@ -1,6 +1,7 @@import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";import { parseSkillFrontmatter } from "@pi-desktop/plugin-sdk";+import { GEN_UI_SKILL_ID } from "@pi-desktop/shared";import type { PluginSkillDef } from "@pi-desktop/agent-runtime";import type { LoadedSkillDocument } from "./skill-document";import { getModuleDirectory } from "./module-path";@@ -19,6 +20,9 @@ export const PLUGIN_DEV_SKILL_FILE = "plugin-development.md";export const PLUGIN_DEV_SKILL_ID = "pi-desktop/plugin-development";export const IMAGE_GENERATION_SKILL_ID = "pi-desktop/imagegen";const IMAGE_GENERATION_SKILL_FILE = "image-generation.md";+/** Inline visualization contract (ADR gen-ui-inline-visualization). */+export const VISUALIZE_SKILL_ID = GEN_UI_SKILL_ID;+const VISUALIZE_SKILL_FILE = "visualize.md";/** electron-builder copies `resources/skills` to `<resources>/skills`. */function resolveBuiltinSkillPath(fileName: string): string | null {@@ -85,13 +89,23 @@ export type BuiltinSkillInput = {pluginPaths?: string[];/** User-disabled ids are withheld from the agent and composer catalog. */disabledIds?: readonly string[];+ /**+ * The session runs on a remote host. Its tools write on that machine, which+ * Electron Main cannot serve, so visualizations are not offered.+ */+ remote?: boolean;};const BUILTIN_SKILL_FILES = [[IMAGE_GENERATION_SKILL_ID, IMAGE_GENERATION_SKILL_FILE],+ [VISUALIZE_SKILL_ID, VISUALIZE_SKILL_FILE],[PLUGIN_DEV_SKILL_ID, PLUGIN_DEV_SKILL_FILE],] as const;+function builtinSkillFile(id: string): string | null {+ return BUILTIN_SKILL_FILES.find(([skillId]) => skillId === id)?.[1] ?? null;+}+/** All bundled skill entries, including ones whose applicability is conditional. */export function builtinSkillCatalog(): PluginSkillDef[] {return BUILTIN_SKILL_FILES.flatMap(([id, file]) => {@@ -107,7 +121,8 @@ export function builtinSkillCatalog(): PluginSkillDef[] {* fresh so a packaged update takes effect without a restart.*/export function builtinSkills(input: BuiltinSkillInput): PluginSkillDef[] {- const ids = [IMAGE_GENERATION_SKILL_ID];+ const ids: string[] = [IMAGE_GENERATION_SKILL_ID];+ if (!input.remote) ids.push(VISUALIZE_SKILL_ID);if (isPluginWorkspace(input.workspacePath, input.pluginPaths)) ids.push(PLUGIN_DEV_SKILL_ID);const activeIds = new Set(ids);const disabled = new Set(input.disabledIds ?? []);@@ -121,7 +136,7 @@ export async function assertBuiltinSkillEnabled(id: string,loadDisabledIds: () => Promise<string[]>,): Promise<void> {- if (id !== IMAGE_GENERATION_SKILL_ID && id !== PLUGIN_DEV_SKILL_ID) return;+ if (!builtinSkillFile(id)) return;if ((await loadDisabledIds()).includes(id)) {throw new Error(`Built-in skill "${id}" is disabled in Settings`);}@@ -132,10 +147,9 @@ export async function assertBuiltinSkillEnabled(* host does not ship, which is the caller's cue to try the plugin registry.*/export function loadBuiltinSkillBody(id: string): LoadedSkillDocument | null {- if (id !== PLUGIN_DEV_SKILL_ID && id !== IMAGE_GENERATION_SKILL_ID) return null;- const raw = readBuiltinSkill(- id === IMAGE_GENERATION_SKILL_ID ? IMAGE_GENERATION_SKILL_FILE : PLUGIN_DEV_SKILL_FILE,- );+ const file = builtinSkillFile(id);+ if (!file) return null;+ const raw = readBuiltinSkill(file);if (!raw?.raw.trim()) return null;const parsed = parseSkillFrontmatter(raw.raw);if (!parsed.body) return null;diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 39dfb7106..cac93579b 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -143,7 +143,9 @@ export function registerAgentIpc({const mcpExpansion = /^\/mcp:\S/.test(req.content)? expandMcpInvocation(req.content,- await composerCommandService.buildComposerCommands(localProjectPath ?? null),+ await composerCommandService.buildComposerCommands(localProjectPath ?? null, {+ remote: Boolean(context.remoteWorkspace),+ }),Boolean(req.attachments?.length),): null;@@ -238,6 +240,7 @@ export function registerAgentIpc({req.content,await composerCommandService.buildComposerCommands(!session.remoteWorkspace && typeof session.projectPath === "string" ? session.projectPath.trim() || null : null,+ { remote: Boolean(session.remoteWorkspace) },),Boolean(req.attachments?.length),)@@ -362,6 +365,7 @@ export function registerAgentIpc({: "";const commands = await composerCommandService.buildComposerCommands(session.remoteWorkspace ? null : launch.projectPath ?? root,+ { remote: Boolean(session.remoteWorkspace) },);const command = commands.find((item) => item.name === commandName);const activeSkills = new Map(diff --git a/apps/desktop/electron/main/ipc/composer-ipc.ts b/apps/desktop/electron/main/ipc/composer-ipc.tsindex 12ea72220..e900bf1f5 100644--- a/apps/desktop/electron/main/ipc/composer-ipc.ts+++ b/apps/desktop/electron/main/ipc/composer-ipc.ts@@ -31,8 +31,16 @@ export type ComposerIpcDependencies = {}>>;};+export type ComposerCommandOptions = {+ /** The session runs on a remote host, so local-only builtin skills are left out. */+ remote?: boolean;+};+export type ComposerCommandService = {- buildComposerCommands: (root: string | null) => Promise<ComposerCommand[]>;+ buildComposerCommands: (+ root: string | null,+ options?: ComposerCommandOptions,+ ) => Promise<ComposerCommand[]>;};export function createComposerCommandService({@@ -47,9 +55,11 @@ export function createComposerCommandService({}: Omit<ComposerIpcDependencies, "registrar" | "optionalWorkspaceRoot">): ComposerCommandService {const loadComposerSkillCommands = async (root: string | null,+ remote: boolean,): Promise<ComposerCommand[]> => {const builtins = builtinSkills({workspacePath: root,+ remote,pluginPaths: plugins.listLoaded().map((loaded) => loaded.path),disabledIds: await disabledBuiltinSkills(),});@@ -84,6 +94,7 @@ export function createComposerCommandService({const buildComposerCommands = async (root: string | null,+ options: ComposerCommandOptions = {},): Promise<ComposerCommand[]> => {await refreshUserMcp?.(root);await userMcp?.toolsForProject(root);@@ -113,7 +124,7 @@ export function createComposerCommandService({description: command.description ?? command.extensionLabel,id: trustedExtensionCommandId(command.name),}));- const skillCommands = await loadComposerSkillCommands(root).catch(() => []);+ const skillCommands = await loadComposerSkillCommands(root, options.remote === true).catch(() => []);const statuses = userMcp?.listStatuses() ?? [];const ready = new Set(statuses.filter((status) => status.state === "ready" && status.toolCount > 0)diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex 3461c2e70..e96990cad 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -1,5 +1,6 @@import { join } from "node:path";import {+ GEN_UI_DIRECTORY_NAME,ErrorCodes as SharedErrorCodes,isActiveInProject,isCommandShellCatalog,@@ -29,7 +30,7 @@ import {visionFromModelConfig,type UserSubagentDocument,} from "@pi-desktop/agent-runtime";-import { builtinSkills } from "../builtin-skills";+import { builtinSkills, VISUALIZE_SKILL_ID } from "../builtin-skills";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";import {catalogModelConfigFor,@@ -508,11 +509,13 @@ export function createSessionLaunchRuntime({// skills come first so a plugin's entry reads as a refinement of them, and// the user's own skills come last so they win a name clash in the model's// reading order.+ const disabledSkillIds = await disabledBuiltinSkills();const pluginSkills = [...builtinSkills({workspacePath: projectPath,pluginPaths: plugins.listLoaded().map((loaded) => loaded.path),- disabledIds: await disabledBuiltinSkills(),+ disabledIds: disabledSkillIds,+ remote: Boolean(remoteWorkspace),}),...plugins.getSkills()@@ -709,6 +712,12 @@ export function createSessionLaunchRuntime({...(jevApiKey ? { jevApiKey } : {}),commandShell,scratchDir: join(dataDir, "scratch", sessionId),+ // Remote-host tools write on that host; Main can only serve local files.+ // A disabled visualize skill also withholds the directory, so the+ // prompt never points the model at a skill it cannot load.+ ...(remoteWorkspace || disabledSkillIds.includes(VISUALIZE_SKILL_ID)+ ? {}+ : { visualizationsDir: join(dataDir, GEN_UI_DIRECTORY_NAME, sessionId) }),attachmentsDir: join(dataDir, "attachments"),projectPath,...(remoteWorkspace ? { remoteWorkspace } : {}),diff --git a/apps/desktop/resources/skills/visualize.md b/apps/desktop/resources/skills/visualize.mdnew file mode 100644index 000000000..c7d61dcb3--- /dev/null+++ b/apps/desktop/resources/skills/visualize.md@@ -0,0 +1,215 @@+---+name: visualize+description: "Create interactive visualizations directly in the conversation. Use to show how something works; explore 'what happens when', 'what changes', or 'help me understand'; compare or inspect; create simulations, charts, graphs, diagrams, and UI previews. Use standard tools for static scientific figures."+---++<!-- Adapted from the ZCode visualize skill (Apache-2.0); see resources/gen-ui/NOTICE.md. -->++# Visualize++- A request for a new standalone file, website, app page, component, or other+ project change is not an in-conversation visualization, even when it+ contains charts or interactive content. Build that in the project instead.+- Create a visual only when the user needs to see or explore it in the+ conversation and it materially improves the explanation.+- Use a normal Markdown table when the user asks for a table. Use a fenced+ Mermaid block when labeled nodes and edges fully explain a static structure.+ Use a visualization for dynamics, motion, adjustable inputs, spatial layout,+ and data worth hovering or filtering.+- Work silently: no progress commentary while reading this skill or writing+ the file. In the reply, describe only what the visual helps the user see or+ decide. Never announce this skill, HTML, SVG, scripts, or local files.++Read this file in full before authoring. Copy into every compaction summary:+`Reload the full visualize skill before creating or updating a visualization.`++## Output contract++### File++- Write `<title>.html` with a concise lowercase-hyphenated ASCII title into+ the **visualization directory named in the system prompt**, using its+ absolute path. Files must sit directly in that directory. If no+ visualization directory is listed, or you cannot write files there,+ inline visualizations are unavailable: answer without one.+- Never write inline fragments into the project or a temp directory.++### Fragment++- Write only an HTML fragment: no `<!doctype>`, `<html>`, `<head>`, or+ `<body>`. The host supplies the document, the stylesheet below, and the+ runtime.+- Write literal markup with real newlines, never an escaped string+ (`<div class=\"card\">`, `\n`). Read the file back if unsure.+- Give the fragment root a unique ID and select it with+ `document.getElementById(...)`; never derive it from `document.currentScript`.+- Keep it under 1 MB: aggregate, bin, downsample, or drop unused fields from+ large inline datasets.+- Check that the script has no undefined identifiers, every queried element+ exists, and the primary interaction updates the visual. Review with the+ Read tool; do not run shell commands to check the file.++### Reference in the reply++Put any short explanation in the reply, then the reference as the last line of+the reply, as plain text. The line looks like this (with real values):++::visualize{"path":"<absolute-path>/<title>.html","title":"<short title>"}++- Emit the literal ASCII prefix `::visualize` followed by a JSON object; do+ not put it in a code block, backticks, or a link. Write the path with+ forward slashes (`C:/Users/...` on Windows).+- Whenever you create or update a visualization, reference it again in that+ turn's final reply, even when editing an existing file.+- Do not repeat the visual's data as a table; add at most one short+ conclusion.++### Sandbox++- There is no network: `fetch`, XHR, WebSocket, remote scripts, fonts, images,+ and map data are all blocked and fail silently. Draw with inline SVG or+ `<canvas>`; embed small assets as `data:` URIs.+- Bundled libraries are available offline through these exact URLs. Keep them+ unchanged; any other URL or version is blocked:+ - D3 7.9.0: `<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>`.+ D3 is not preloaded: a fragment that calls `d3` must include this tag+ before its own script.+ - Floating UI is already loaded by the runtime for tooltips; do not load it+ again.+- No popups, alerts, navigation, external links, form submission, cookies,+ or `localStorage`. Keep state in script variables; it resets when the card+ reloads.+- The card starts at 240px and follows content height up to 2000px. The same+ fragment also opens in a larger expanded view.++## Color and type++- Make every fill, stroke, text, border, and canvas color theme-aware. The+ host follows the app's light or dark theme; never hard-code white panels,+ black text, or Tailwind color literals.+- Theme variables: `--background`, `--foreground`, `--card`,+ `--card-foreground`, `--popover`, `--popover-foreground`, `--primary`,+ `--primary-foreground`, `--secondary`, `--secondary-foreground`, `--muted`,+ `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`,+ `--border`, `--input`, `--ring`, and hues `--blue`, `--orange`, `--green`,+ `--red`, `--purple`, `--yellow`. Use `currentColor` inside SVG.+- In each pair the base token is a surface and `-foreground` is the content+ on it. `--muted` is a fill; use `--muted-foreground` for secondary text.+- Use `--viz-series-1` for a single measure or active state, and+ `--viz-series-2` … `--viz-series-6` only for persistent category or series+ identity. Keep mappings stable and pair color with labels or shapes. Keep+ values and labels in `--foreground` / `--muted-foreground`.+- Keep grids and inactive structure thin (1–2px) and neutral. Never outline+ bars, progress tracks, or stacked segments.+- For canvas or chart APIs that cannot read CSS variables, resolve them with+ `getComputedStyle(document.documentElement).getPropertyValue(...)` and redraw+ when the root's `style` attribute changes (`MutationObserver`).+- Type scales from `--font-size-base` (14px); `.text-small` is 12px. Never go+ below 11px, never set custom font sizes or line heights, and use only+ `var(--font-weight-normal)` and `var(--font-weight-medium)`. Use `.tabular-nums` on changing numbers.+- Use at most one concise visible heading (`h1`–`h3`) for a self-contained+ chart; do not restate the prompt.++## Composition++Choose the smallest composition that fits.++- Prefer interaction detail over permanent panels, toolbars, repeated+ legends, or long stacks. Add only requested controls; never invent search,+ filter, or reset controls, or qualitative score and status cards.+- Put live values in control labels or on the visual.+- **Explainer or simulation:** compact controls, one dominant visual, at most+ one single-line selected-state detail. For step-throughs, add only step+ controls and update one current visual.+- **Graphs and plots:** use D3 for data-rich Cartesian or statistical plots+ and handwritten SVG for simple, directly labeled values.+- **Dense categorical grid:** one compact selected-item summary, a grid with+ one readable identifier per cell, one small legend.+- **Part-to-whole over time:** one stacked chart of category allocation per+ period.+- **Maps:** the sandbox cannot download geometry. Draw a map only from+ coordinates or small geometry you embed yourself; otherwise choose another+ form.+- **UI mockups:** match the product's own chrome, colors, and type. Do not use+ the visualization utility classes or variables inside the mocked product;+ define root-scoped product styles with `light-dark(<light>, <dark>)`. Give+ product surfaces opaque backgrounds and keep the surrounding area+ transparent. Show realistic states, not filler dashboards.++## Layout++- Keep the top-level surface transparent and unframed, and fill the available+ width. Design for about 700px and support widths down to 320px; stack+ side-by-side content when it no longer fits.+- Text, controls, and dynamic content must fit at every width without overlap+ or clipping. The host sizes the frame to content, so never use fixed outer+ widths, horizontal overflow, internal scrolling, `position: fixed`, or+ viewport-height layouts. Use `.table-responsive` only when table columns+ cannot fit.+- Size every SVG from its actual container: set its `viewBox` from the+ container's measured width and redraw with `ResizeObserver`. Never scale+ down a fixed-width `viewBox`; at narrow widths reduce ticks and annotations+ instead.++## Utility classes++Let the utilities own geometry, appearance, and interaction. Never restyle+them: no custom sizes, spacing, borders, radii, shadows, or colors.++- **Surfaces:** `.card` is the only card-like surface — use it for a necessary+ numeric summary, a selected-item summary, or a bounded interactive field.+ Never nest cards or frame charts, maps, tables, or the whole visual.+ `.viz-stat` + `.viz-stat-value` inside a card for one metric.+- **Layout:** `.viz-grid` (equal columns that stack when narrow; 2–3 columns at+ 700px), `.viz-row` (wrapping inline group), `.viz-controls` (wrapping row of+ controls for one visual), `<hr>` separator.+- **Controls:** `.btn`, `.btn-primary` (one main action per group),+ `.btn-ghost`, `.btn-block`; `.form-label`, `.form-control`, `.form-select`,+ `.form-range` (show the current value and units right before it),+ `.form-check` / `.form-switch` around a native checkbox,+ `.form-control-color`. Use native `button`, `input`, `select`, `textarea`;+ never recreate controls or add `tabindex`.+- **Tabs:** `.nav.nav-pills[role="tablist"]` with `aria-label`, holding+ `button.nav-link[role="tab"]` with a unique `id`, `type="button"`,+ `aria-controls`, and `aria-selected`; mark the initial tab `.active`. Each+ `[role="tabpanel"]` has the matching `id`, `aria-labelledby`, and `hidden`+ when inactive. The runtime wires the behavior.+- **Data:** `.table` (add `.table-sm` for more rows; `.text-end`,+ `.text-center`, `.text-nowrap` in cells), `.progress` + `.progress-bar` with+ `role="progressbar"` and `aria-value*`, `.viz-badge` for a display-only+ status pill, `.viz-tile` on a selectable dense-grid `.btn`.+- **Text:** `.text-small`, `.text-muted` (never for essential values),+ `.text-destructive` (errors only), `<code>`, `.sr-only`.+- **Tooltips:** `data-tooltip="…"` on any focusable trigger or SVG mark,+ optionally `data-tooltip-placement="top|right|bottom|left"`. The runtime+ handles hover, focus, and touch. Never use `title` or custom tooltip markup+ for these.+- Use `.cursor-interaction` on custom interactive elements instead of+ `cursor: pointer`.++## Charts++- Give every axis a title with quantity and units, reserve at least 64px for+ the y axis, and label important values directly. Add a legend only when+ series cannot be labeled directly.+- Derive padded domains from all observations (`d3.extent`); never hard-code+ them. Keep marks inside the plot frame.+- After drawing, keep tick, axis, and value labels from overlapping: leave+ about 4px between labels, anchor edge labels inward, and drop optional+ annotations first. At 360px show at most four x ticks.+- Use one tooltip per chart, attached to real marks with `data-tooltip`+ (label, value, units). Give isolated marks hit targets at least 32px across.+- Animate transitions between chart states, not the initial appearance; never+ loop motion, and honor `prefers-reduced-motion`.+- Scope SVG styles to the chart's class.++## Accessibility++- Use semantic HTML, keyboard-accessible controls, and concise labels.+- Give every chart, SVG, and canvas a screen-reader summary (`<title>` /+ `<desc>`, `aria-label`, or an `.sr-only` description).+- Use `aria-live="polite"` for dynamic results and `role="alert"` for+ validation errors; do not announce every hover or frame.+- Keep essential content and actions available without hover, and keep+ browser focus styles.+- Keep visible text in the user's language.diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.tsindex ff7a69a61..bdc1ed26e 100644--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts@@ -16,6 +16,7 @@ import {} from "@pi-desktop/shared";import { api } from "../lib/api";import {+ commandsForSession,fetchComposerCommands,prewarmComposerCommands,readComposerCommandsCache,@@ -140,6 +141,14 @@ export type ComposerCommandResolution =* names, and unknown names stay on the prompt path. Reuses the menu's TTL cache* when warm, so a warm cache keeps resolving through a source blip.*/+/**+ * Whether the active session runs against a remote host workspace. The menu+ * and the send-time resolver share this so they offer the same commands.+ */+function activeSessionHasRemoteWorkspace(state: ReturnType<typeof useAppStore.getState>): boolean {+ return Boolean(state.sessions.find((session) => session.id === state.activeSessionId)?.remoteWorkspace);+}+export async function resolveComposerCommand(name: string,): Promise<ComposerCommandResolution> {@@ -157,7 +166,9 @@ export async function resolveComposerCommand(};}}- const command = commands.find((c) => c.name === name);+ const command = commandsForSession(commands, {+ remote: activeSessionHasRemoteWorkspace(useAppStore.getState()),+ }).find((c) => c.name === name);return command ? { status: "resolved", command } : { status: "unknown" };}@@ -173,6 +184,7 @@ export function useComposerAutocomplete({enabled: boolean;}) {const sessionId = useAppStore((s) => s.activeSessionId);+ const remoteSession = useAppStore(activeSessionHasRemoteWorkspace);const workspaceKey = useAppStore((s) => s.workspace?.path ?? "");const hasWorkspace = workspaceKey !== "";const ready = useAppStore((s) => s.ready);@@ -310,14 +322,20 @@ export function useComposerAutocomplete({const items = useMemo<AutocompleteItem[]>(() => {if (!trigger || dismissed) return [];if (trigger.mode === "slash") {- return commands ? filterCommands(commands, trigger.query, trigger.tokenStart > 0) : [];+ return commands+ ? filterCommands(+ commandsForSession(commands, { remote: remoteSession }),+ trigger.query,+ trigger.tokenStart > 0,+ )+ : [];}if (!files) return [];return filterFiles(foundHere ? [...foundHere.entries, ...files.entries] : files.entries,trigger.query,);- }, [trigger, dismissed, commands, files, foundHere]);+ }, [trigger, dismissed, commands, remoteSession, files, foundHere]);// New query or mode restarts keyboard navigation at the top hit.const itemsKey = trigger ? `${trigger.mode}:${trigger.query}` : "";diff --git a/apps/desktop/src/lib/composer-command-source.ts b/apps/desktop/src/lib/composer-command-source.tsindex 4dcab9b5b..33155ed72 100644--- a/apps/desktop/src/lib/composer-command-source.ts+++ b/apps/desktop/src/lib/composer-command-source.ts@@ -8,9 +8,25 @@* MCP/skill read, so paying for it on the keystroke is what made the menu feel* absent on a fresh launch.*/-import type { ComposerCommand } from "@pi-desktop/shared";+import { GEN_UI_SKILL_ID, type ComposerCommand } from "@pi-desktop/shared";import { api } from "./api";+/**+ * The menu's view of the workspace list for one session. The source is keyed+ * by workspace only, so session-specific omissions happen here: a remote+ * session cannot render inline visualizations, so its runtime never receives+ * the visualize skill and the menu must not offer it either.+ */+export function commandsForSession(+ commands: ComposerCommand[],+ { remote }: { remote: boolean },+): ComposerCommand[] {+ if (!remote) return commands;+ return commands.filter(+ (command) => !(command.kind === "skill" && command.skillId === GEN_UI_SKILL_ID),+ );+}+/** Menu and resolver share one window; both re-read after it lapses. */const SOURCE_TTL_MS = 10_000;/** Attempts spend their wait on a booting sidecar, so keep the cadence short. */diff --git a/apps/desktop/test/composer-mcp.test.mjs b/apps/desktop/test/composer-mcp.test.mjsindex 3b457a7bf..51c248e31 100644--- a/apps/desktop/test/composer-mcp.test.mjs+++ b/apps/desktop/test/composer-mcp.test.mjs@@ -279,3 +279,10 @@ test("remote workspace prompt and steering never resolve commands from the sameawait fixture.steer(`/${selected.name} inspect again`);assert.deepEqual(roots, [null, null]);});++test("remote sessions do not offer or expand the local-only visualize skill", async () => {+ const catalog = service([], []);+ const skillIds = (commands) => commands.flatMap((c) => c.kind === "skill" ? [c.skillId] : []);+ assert.ok(skillIds(await catalog.buildComposerCommands(null)).includes("pi-desktop/visualize"));+ assert.ok(!skillIds(await catalog.buildComposerCommands(null, { remote: true })).includes("pi-desktop/visualize"));+});diff --git a/apps/desktop/test/gen-ui-composer-command.test.mjs b/apps/desktop/test/gen-ui-composer-command.test.mjsnew file mode 100644index 000000000..1249d537d--- /dev/null+++ b/apps/desktop/test/gen-ui-composer-command.test.mjs@@ -0,0 +1,56 @@+/**+ * The send-time slash resolver must agree with the menu: a remote session's+ * runtime never receives the local-only visualize skill, so `/skill:...` for+ * it must not resolve there either.+ */+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));+const load = (relative) => import(pathToFileURL(join(here, relative)).href);++const { resolveComposerCommand } = await load("../src/hooks/use-composer-autocomplete.ts");+const { api } = await load("../src/lib/api.ts");+const { useAppStore } = await load("../src/stores/app-store.ts");++const VISUALIZE = { name: "skill:pi-desktop/visualize", kind: "skill", title: "Visualize", skillId: "pi-desktop/visualize" };+const MINE = { name: "skill:mine", kind: "skill", title: "Mine", skillId: "mine" };++async function withCommands(body) {+ const original = api.composerCommands;+ api.composerCommands = async () => ({ commands: [VISUALIZE, MINE] });+ try {+ return await body();+ } finally {+ api.composerCommands = original;+ }+}++test("a remote session does not resolve the visualize skill at send time", async () => {+ useAppStore.setState({+ workspace: { path: "/gen-ui-remote-resolve" },+ activeSessionId: "s-remote",+ sessions: [{ id: "s-remote", remoteWorkspace: { hostId: "h", path: "/srv" } }],+ });+ await withCommands(async () => {+ assert.equal((await resolveComposerCommand(VISUALIZE.name)).status, "unknown");+ assert.equal((await resolveComposerCommand(MINE.name)).status, "resolved");+ });+});++test("a local session still resolves the visualize skill", async () => {+ useAppStore.setState({+ workspace: { path: "/gen-ui-local-resolve" },+ activeSessionId: "s-local",+ sessions: [{ id: "s-local" }],+ });+ await withCommands(async () => {+ const resolution = await resolveComposerCommand(VISUALIZE.name);+ assert.equal(resolution.status, "resolved");+ assert.equal(resolution.command.skillId, "pi-desktop/visualize");+ });+});diff --git a/apps/desktop/test/jev-session-launch.test.mjs b/apps/desktop/test/jev-session-launch.test.mjsindex 55d96fd71..a7e3b7251 100644--- a/apps/desktop/test/jev-session-launch.test.mjs+++ b/apps/desktop/test/jev-session-launch.test.mjs@@ -38,6 +38,7 @@ test("session launch resolves Jev credentials only for opted-in Agent mode", asyconst keyReads = [];const logs = [];let failJevSecretRead = false;+ let disabledSkills = [];const host = {isAvailable: () => true,async call(method, input) {@@ -53,7 +54,7 @@ test("session launch resolves Jev credentials only for opted-in Agent mode", asy}if (method === "providers.list") return { providers: [provider] };if (method === "providers.getSecret") return { value: "" };- if (method === "skills.disabledBuiltins") return { disabled: [] };+ if (method === "skills.disabledBuiltins") return { disabled: disabledSkills };if (method === "skills.active") return { skills: [] };if (method === "mcp.active") return { servers: [] };if (method === "agents.active") return { subagents: [] };@@ -107,6 +108,19 @@ test("session launch resolves Jev credentials only for opted-in Agent mode", asy},);+ // The visualization directory follows the visualize skill (D671): a+ // disabled skill must not leave the prompt pointing at it.+ const withSkill = await launch("agent", false);+ assert.equal(+ withSkill.sidecarParams.visualizationsDir,+ join(temp, "visualizations", "session-fixture"),+ );+ disabledSkills = ["pi-desktop/visualize"];+ const withoutSkill = await launch("agent", false);+ assert.equal("visualizationsDir" in withoutSkill.sidecarParams, false);+ disabledSkills = [];+ keyReads.length = 0;+const enabledAgent = await launch("agent", true);assert.equal(enabledAgent.sidecarParams.jevApiKey, "jev-launch-fixture-key");assert.equal(enabledAgent.sidecarParams.provider.apiKey, "");diff --git a/apps/desktop/test/slash-command-source.test.mjs b/apps/desktop/test/slash-command-source.test.mjsindex 3a8db46fa..520fb4f34 100644--- a/apps/desktop/test/slash-command-source.test.mjs+++ b/apps/desktop/test/slash-command-source.test.mjs@@ -206,3 +206,17 @@ test("the shipped locales carry the refusal copy", async () => {assert.match(en, /slashCommandSourceUnavailable:\s*"[^"]+"/);assert.match(zhCN, /slashCommandSourceUnavailable:\s*"[^"]+"/);});++test("a remote session's menu leaves out the local-only visualize skill", async () => {+ const { commandsForSession } = await load("../src/lib/composer-command-source.ts");+ const commands = [+ { name: "compact", kind: "builtin", title: "/compact" },+ { name: "skill:pi-desktop/visualize", kind: "skill", title: "Visualize", skillId: "pi-desktop/visualize" },+ { name: "skill:mine", kind: "skill", title: "Mine", skillId: "mine" },+ ];+ assert.deepEqual(commandsForSession(commands, { remote: false }), commands);+ assert.deepEqual(+ commandsForSession(commands, { remote: true }).map((command) => command.name),+ ["compact", "skill:mine"],+ );+});diff --git a/apps/desktop/test/visualize-skill.test.mjs b/apps/desktop/test/visualize-skill.test.mjsnew file mode 100644index 000000000..202b477bd--- /dev/null+++ b/apps/desktop/test/visualize-skill.test.mjs@@ -0,0 +1,80 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { register } from "node:module";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { parseSkillFrontmatter } = await import("@pi-desktop/plugin-sdk");+const {+ assertBuiltinSkillEnabled,+ builtinSkillCatalog,+ builtinSkills,+ loadBuiltinSkillBody,+} = await import("../electron/main/builtin-skills.ts");++const desktopRoot = join(dirname(fileURLToPath(import.meta.url)), "..");+const VISUALIZE = "pi-desktop/visualize";++test("the visualize skill is active in local sessions and loads its contract", () => {+ assert.ok(builtinSkillCatalog().some((skill) => skill.id === VISUALIZE));+ const local = builtinSkills({ workspacePath: "/repo" });+ assert.equal(local.find((skill) => skill.id === VISUALIZE)?.name, "visualize");+ assert.ok(builtinSkills({}).some((skill) => skill.id === VISUALIZE));+ const body = loadBuiltinSkillBody(VISUALIZE).body;+ assert.match(body, /::visualize\{"path":/);+ assert.match(body, /fragment/i);+ assert.match(body, /no network/i);+});++test("the skill only names tokens, classes, and libraries the bundled kit provides", () => {+ const body = loadBuiltinSkillBody(VISUALIZE).body;+ const css = readFileSync(join(desktopRoot, "resources/gen-ui/visualize.css"), "utf8");+ const kit = readFileSync(join(desktopRoot, "resources/gen-ui/visualize-kit.html"), "utf8");+ const manifest = JSON.parse(readFileSync(join(desktopRoot, "resources/gen-ui/vendor/manifest.json"), "utf8"));+ // Theme tokens the skill tells the model to use are defined by the stylesheet.+ const tokens = new Set(body.match(/`--[a-z0-9-]+`/g)?.map((token) => token.slice(1, -1)));+ assert.ok(tokens.size > 20);+ for (const token of tokens) {+ assert.match(css, new RegExp(`${token}:`), token);+ }+ for (let i = 1; i <= 6; i += 1) assert.match(css, new RegExp(`--viz-series-${i}:`));+ // Utility classes the skill names exist in the stylesheet.+ const classes = new Set(body.match(/`\.[a-z][a-z0-9-]*/g)?.map((name) => name.slice(2)));+ assert.ok(classes.size > 20);+ for (const name of classes) assert.match(css, new RegExp(`\\.${name}\\b`), `.${name}`);+ // Tabs and tooltips are wired by the kit runtime.+ assert.match(kit, /pi-desktop-visualization-tabs/);+ assert.match(kit, /closest\("\[data-tooltip\]"\)/);+ // Every library URL in the skill is a bundled, pinned one.+ const bundled = new Set(manifest.resources.map((resource) => resource.url));+ const urls = body.match(/https:\/\/[^\s"'`<>]+/g) ?? [];+ assert.ok(urls.length > 0);+ for (const url of urls) assert.ok(bundled.has(url), url);+ // Host APIs from the upstream kit that PI-Desktop does not provide.+ assert.doesNotMatch(body, /window\.zcode|widgetState|sendFollowUpMessage|openExternal|Tweak|lucide|viz-carousel|render\.py/);+});++test("remote-host sessions do not get the visualize skill", () => {+ const remote = builtinSkills({ workspacePath: "/remote/project", remote: true });+ assert.ok(!remote.some((skill) => skill.id === VISUALIZE));+ assert.ok(remote.some((skill) => skill.id === "pi-desktop/imagegen"));+});++test("users can disable the visualize skill like other built-ins", async () => {+ const skills = builtinSkills({ disabledIds: [VISUALIZE] });+ assert.ok(!skills.some((skill) => skill.id === VISUALIZE));+ await assert.rejects(+ assertBuiltinSkillEnabled(VISUALIZE, async () => [VISUALIZE]),+ /disabled in Settings/,+ );+ await assertBuiltinSkillEnabled(VISUALIZE, async () => []);+});++test("the visualize skill file has well-formed front matter and stays compact", () => {+ const raw = readFileSync(join(desktopRoot, "resources/skills/visualize.md"), "utf8");+ const parsed = parseSkillFrontmatter(raw);+ assert.equal(parsed.name, "visualize");+ assert.ok(parsed.description && parsed.description.length > 20);+ assert.ok(Buffer.byteLength(raw) < 12 * 1024);+});diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex cdc4c7cb0..749085f03 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -172,6 +172,7 @@ function createRuntime(remoteWorkspace: { hostKey: string; path: string };workspaceRoot: string;scratchDir: string;+ visualizationsDir: string;customSystemPrompt: import("./custom-system-prompt.js").CustomSystemPrompt;projectInstructions: import("./project-instructions.js").ProjectInstructions;projectMemory: string;@@ -204,6 +205,7 @@ function createRuntime(remoteWorkspace: overrides.remoteWorkspace,workspaceRoot: overrides.workspaceRoot,scratchDir: overrides.scratchDir,+ visualizationsDir: overrides.visualizationsDir,customSystemPrompt: overrides.customSystemPrompt,pluginTools: overrides.pluginTools,subagents: overrides.subagents,@@ -12287,6 +12289,34 @@ describe("local runtime with a remote tool workspace", () => {});});+describe("inline visualization directory (ADR gen-ui-inline-visualization)", () => {+ const systemPrompt = (runtime: DesktopAgentRuntime): string =>+ (runtime as unknown as { agent: { state: { systemPrompt: string } } }).agent.state+ .systemPrompt;++ it("advertises the directory and skill to local sessions", async () => {+ const runtime = createRuntime({ visualizationsDir: "/data/visualizations/session-1" });+ const prompt = systemPrompt(runtime);+ expect(prompt).toContain("Visualization directory");+ expect(prompt).toContain("`/data/visualizations/session-1`");+ expect(prompt).toContain("pi-desktop/visualize");+ await runtime.dispose();+ });++ it("omits the directory when none is provisioned or the workspace is remote", async () => {+ const none = createRuntime({});+ const remote = createRuntime({+ remoteWorkspace: { hostKey: "ssh", path: "/remote/project" },+ visualizationsDir: "/data/visualizations/session-1",+ });+ for (const runtime of [none, remote]) {+ expect(systemPrompt(runtime)).not.toContain("Visualization directory");+ expect(systemPrompt(runtime)).not.toContain("/data/visualizations");+ await runtime.dispose();+ }+ });+});+describe("isolated session workspace (ADR 0329)", () => {const systemPrompt = (runtime: DesktopAgentRuntime): string =>(runtime as unknown as { agent: { state: { systemPrompt: string } } }).agent.statediff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex f1d920cc8..0a26cbef8 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -123,6 +123,7 @@ import {subagentToolsLabel,type ProposalKind,type SubagentPermission,+ GEN_UI_SKILL_ID,} from "@pi-desktop/shared";import { createStreamCoalescer, type StreamCoalescer } from "./stream-coalescer.js";import type { RuntimeHost } from "./host-client.js";@@ -1022,6 +1023,10 @@ export type AgentRuntimeOptions = {* Advertised to the model in the system prompt; host-core enforces it as* a second containment root. */scratchDir?: string;+ /** Absolute per-session directory for inline visualization fragments+ * (ADR gen-ui-inline-visualization). Advertised in the system prompt;+ * host-core enforces it as a containment root. Ignored for remote sessions. */+ visualizationsDir?: string;onEvent: (envelope: AgentEventEnvelope) => void;/** Bounded diagnostics routed to the Electron logger, never the transcript. */onDiagnostic?: (diagnostic: AgentRuntimeDiagnostic) => void;@@ -1869,6 +1874,7 @@ export class DesktopAgentRuntime {private trackToolActivation = false;private activationHydrated = false;private scratchDir?: string;+ private visualizationsDir?: string;private projectPath?: string;private remoteWorkspace?: { hostKey: string; path: string };/** Set only for an isolated session; see `RuntimeConfig.workspaceRoot`. */@@ -2063,6 +2069,7 @@ export class DesktopAgentRuntime {this.commandShell = opts.commandShell;this.remoteWorkspace = opts.remoteWorkspace;this.scratchDir = opts.remoteWorkspace ? undefined : opts.scratchDir;+ this.visualizationsDir = opts.remoteWorkspace ? undefined : opts.visualizationsDir;this.projectPath = opts.remoteWorkspace?.path ?? (opts.projectPath?.trim() || undefined);// Remote workspaces are never isolated (ADR 0329).this.workspaceRoot = opts.remoteWorkspace ? undefined : opts.workspaceRoot?.trim() || undefined;@@ -2120,6 +2127,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the`Your scratch directory for this session is \`${formatScratchDirForShell(this.commandShell, this.scratchDir)}\` (in Bash: ${shellScratchVariable(this.commandShell)}). Store ad-hoc temporary and intermediate files there using absolute paths. Workspace writes must be task-related project files or required toolchain outputs. Scratch persists across turns and is deleted with the session.`,]: []),+ // Inline visualizations (ADR gen-ui-inline-visualization).+ ...(this.visualizationsDir+ ? [+ `Visualization directory (absolute paths only, .html fragments only; see the ${GEN_UI_SKILL_ID} skill): \`${this.visualizationsDir}\``,+ ]+ : []),// Isolated session (ADR 0329)....(this.workspaceRoot ? [isolatedWorkspaceGuidance()] : []),];diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex 1fdcd50f2..1cf9165a1 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -126,6 +126,8 @@ type RuntimeParams = {/** Opted-in override keys, separate from definition-only pinned bindings. */subagentModelKeys?: string[];scratchDir?: string;+ /** Per-session visualization directory; omitted for remote sessions. */+ visualizationsDir?: string;/** Session-bound workspace root supplied by Electron main. */projectPath?: string;remoteWorkspace?: { hostKey: string; path: string };@@ -326,6 +328,10 @@ async function runtimeFor(typeof params.scratchDir === "string" && params.scratchDir? params.scratchDir: undefined,+ visualizationsDir:+ typeof params.visualizationsDir === "string" && params.visualizationsDir+ ? params.visualizationsDir+ : undefined,onEvent: (envelope: AgentEventEnvelope) => notify("agent.event", envelope),onDiagnostic: (diagnostic) => notify("agent.diagnostic", diagnostic),});