Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Integrate verified desktop loading and session fixes

justrachc1fbd82e3dfb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 881130a1..129f3e87 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,9 @@ current is part of cutting a release.
## Unreleased
+- Desktop fonts are bundled locally; syntax highlighting, diagrams, and secondary panes load when needed.
+- Desktop appearance notes no longer alter slash commands. Clipboard image staging retries absolute paths through their parent directory when needed.
+- Resuming a saved conversation restores its persisted session identity even if startup already generated one.
- GUI usage replies show grouped metrics and plan limits; inline editing keeps the message bubble and grows with its text. Subtle transcript reveals respect reduced motion.
- `#1013`: keep the first answer after a no-tool retry without allowing older turns to replace a later answer (ADR 0139).
- GUI usage replies show grouped metrics and plan limits; inline editing keeps the message bubble and grows with its text. Subtle transcript reveals respect reduced motion.
diff --git a/apps/native/app/globals.css b/apps/native/app/globals.css
index b957ef69..2c483a2c 100644
--- a/apps/native/app/globals.css
+++ b/apps/native/app/globals.css
@@ -64,8 +64,8 @@
--shadow-overlay: var(--shadow-overlay);
/* type */
- --font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
- --font-mono: var(--font-mono-face), ui-monospace, "SF Mono", monospace;
+ --font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
+ --font-mono: var(--font-geist-mono), ui-monospace, "SF Mono", monospace;
/* radii — chips 6, controls 8, cards 10, windows 14, pills 999 */
--radius-chip: 6px;
diff --git a/apps/native/app/layout.tsx b/apps/native/app/layout.tsx
index 10d1ae0d..09fcf74e 100644
--- a/apps/native/app/layout.tsx
+++ b/apps/native/app/layout.tsx
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
-import { Geist, Geist_Mono } from "next/font/google";
+import { GeistSans } from "geist/font/sans";
+import { GeistMono } from "geist/font/mono";
import "./globals.css";
import "./appearance.css";
import "./motion.css";
@@ -10,16 +11,6 @@ import DesktopTitlebar from "@/components/site/DesktopTitlebar";
import DesktopUpdates from "@/components/site/DesktopUpdates";
import { BrowserWarm } from "@/components/site/BrowserWarm";
-const inter = Geist({
- subsets: ["latin"],
- variable: "--font-inter",
-});
-
-const mono = Geist_Mono({
- subsets: ["latin"],
- variable: "--font-mono-face",
-});
-
export const metadata: Metadata = {
title: "Codegraff",
description: "CodeGraff desktop workspace.",
@@ -34,7 +25,7 @@ export default function RootLayout({
<head>
<script dangerouslySetInnerHTML={{ __html: appearanceScript }} />
</head>
- <body className={`${inter.variable} ${mono.variable} font-sans`}>
+ <body className={`${GeistSans.variable} ${GeistMono.variable} font-sans`}>
<ThemeSync />
<MotionLifecycle />
<BrowserWarm />
diff --git a/apps/native/bun.lock b/apps/native/bun.lock
index 55eee9c7..6331b642 100644
--- a/apps/native/bun.lock
+++ b/apps/native/bun.lock
@@ -10,6 +10,7 @@
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"electron-updater": "6.8.9",
+ "geist": "^1.7.2",
"glimm": "^0.3.0",
"iconoir-react": "^7.11.1",
"liveline": "^0.0.7",
@@ -432,6 +433,8 @@
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
+ "geist": ["[email protected]", "", { "peerDependencies": { "next": ">=13.2.0" } }, "sha512-Gu5lDFa3pLRyoBlBPf0QIFHVdWAnpco7fS1bJm41jyLPFoguBgiubseUN2oLXMgqZ7uxAxDoXcHMhCY/fOTTgg=="],
+
"glimm": ["[email protected]", "", { "peerDependencies": { "next": ">=14", "react": ">=18" }, "optionalPeers": ["next", "react"] }, "sha512-Maw5WJnUsgyfsHl7Vp95wa8G1uaFhUOSoQzAVPX1DxdHxmWNBa9VtDRNPplH1A+bIazn956ZP/wQvH4ZSxKN9Q=="],
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
diff --git a/apps/native/components/primitives/Markdown.tsx b/apps/native/components/primitives/Markdown.tsx
index 2fccc14d..09b99b31 100644
--- a/apps/native/components/primitives/Markdown.tsx
+++ b/apps/native/components/primitives/Markdown.tsx
@@ -2,10 +2,8 @@
import { useMemo, type JSX, type ReactNode } from "react";
import { Streamdown, type Components, type ControlsConfig, type ExtraProps } from "streamdown";
-import { mermaid } from "@streamdown/mermaid";
import { code } from "@/lib/code-highlighter";
import StreamingCode from "./StreamingCode";
-import { useDarkTheme } from "./useDarkTheme";
import { stripCiteMarkup } from "@/lib/cite-markup";
/* ─────────────────────────────────────────────────────────
@@ -23,13 +21,12 @@ import { stripCiteMarkup } from "@/lib/cite-markup";
/** `src/acp.zig`, `README.md`, `benchmarks/` — but not `--flags` or phrases. */
const PATHISH = /^(?:[\[email protected]]+\/)+[\[email protected]]*$|^[\w-][\w.-]*\.[a-z0-9]{1,8}$/i;
-const PLUGINS = { code, mermaid };
+const PLUGINS = { code };
const CONTROLS: ControlsConfig = {
code: { copy: true, download: false },
table: { copy: true, download: false, fullscreen: false },
image: { download: false },
- mermaid: { copy: true, download: false, fullscreen: true, panZoom: true },
};
const HEADING_STYLE: Record<number, string> = {
@@ -140,8 +137,8 @@ export default function Markdown({
}) {
// Streamdown is memoized on its props; a fresh components object per
// render would defeat that, so it changes only with the callback.
- const mermaidTheme = useDarkTheme() ? "dark" : "default";
- const mermaidOptions = useMemo(() => ({ config: { theme: mermaidTheme, securityLevel: "strict" as const, fontFamily: "inherit" } }), [mermaidTheme]);
+ // Mermaid is not a Streamdown plugin here: closed fences go through
+ // StreamingCode → MermaidDiagram, which dynamic-imports mermaid.
const components = useMemo<Components>(
() => ({ ...STATIC_COMPONENTS, code: props => <StreamingCode {...props} collapseLongCode={!asDocument} />, inlineCode: inlineCode(onOpenPath) }),
[onOpenPath, asDocument],
@@ -153,7 +150,6 @@ export default function Markdown({
isAnimating={streaming}
caret={streaming ? "block" : undefined}
plugins={PLUGINS}
- mermaid={mermaidOptions}
components={components}
controls={CONTROLS}
lineNumbers={false}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 2766eb8c..98cb519f 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -8,33 +8,27 @@ import { resumeQueuedPrompt } from "@/lib/prompt-queue-resume";
import { createPromptRunner } from "./harness-prompt-runner";
import { workspaceActions } from "./harness-workspace-actions";
-import ProjectsPane from "./ProjectsPane";
import { useSavedConversation, ConversationOpenNotice } from "./useSavedConversation";
import { useQuietSettings } from "./useQuietSettings";
import { useTabDrag } from "./useTabDrag";
import { mergeChatGroups, reorderChatGroups, resumeSplitTarget } from "@/lib/chat-groups";
import { useChatGroups } from "./useChatGroups";
-import AppSettings from "./AppSettings";
import HarnessChrome from "./HarnessChrome";
import ChatSplitLayout from "./ChatSplitLayout";
-import TerminalPane from "./TerminalPane";
import { sidebarRecents } from "./harness-sidebar";
-import AgentsPane from "./AgentsPane";
import { newPageToken, newSessionName, type Chat, type Msg } from "./harness-types";
-import ChangesPane from "./ChangesPane";
-import ReviewsPane from "./ReviewsPane";
import { useBrowserVisibility } from "./useBrowserVisibility";
import { useReferenceNavigation } from "./useReferenceNavigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type PromptModel } from "@/components/primitives/PromptBar";
import SidebarNav from "@/components/primitives/SidebarNav";
-import ConversationsPane from "@/components/site/ConversationsPane";
-import FilesPane from "@/components/site/FilesPane";
-import BrowserPane from "@/components/site/DesktopBrowserPane";
import { type BrowserPin } from "@/lib/browser/annotations";
import { browserClose } from "@/lib/browser-client";
import ChatColumn from "./ChatColumn";
-import TasksSidebar from "./TasksSidebar";
+import {
+ AgentsPane, AppSettings, BrowserPane, ChangesPane, ConversationsPane, FilesPane,
+ ProjectsPane, ReviewsPane, TasksSidebar, TerminalPane, WorkspaceDialog,
+} from "./harness-panes";
import { useTasksVisibility } from "./useTasksVisibility";
import { MAX_COLUMNS, SPLIT_LIMIT_MESSAGE, splitLimitReached } from "./harness-split";
import { useDesktopShortcuts } from "./useDesktopShortcuts";
@@ -51,7 +45,6 @@ import { enqueuePrompt } from "@/lib/prompt-queue";
import { usePromptQueue } from "./usePromptQueue";
import { removeSession, type StoredSession } from "@/lib/sessions";
import { loadHistory, mergeHistory } from "@/lib/prompt-history";
-import WorkspaceDialog from "@/components/site/WorkspaceDialog";
import {
basename,
findWorkspace,
diff --git a/apps/native/components/site/harness-panes.tsx b/apps/native/components/site/harness-panes.tsx
new file mode 100644
index 00000000..b694ec69
--- /dev/null
+++ b/apps/native/components/site/harness-panes.tsx
@@ -0,0 +1,17 @@
+"use client";
+
+import dynamic from "next/dynamic";
+
+/** Panes that are off-screen at boot. Keep them out of the first renderer
+ * parse so idle RSS is the chat chrome, not xterm/agents/files/browser. */
+export const ProjectsPane = dynamic(() => import("./ProjectsPane"));
+export const TerminalPane = dynamic(() => import("./TerminalPane"), { ssr: false });
+export const AgentsPane = dynamic(() => import("./AgentsPane"));
+export const ChangesPane = dynamic(() => import("./ChangesPane"));
+export const ReviewsPane = dynamic(() => import("./ReviewsPane"));
+export const ConversationsPane = dynamic(() => import("./ConversationsPane"));
+export const FilesPane = dynamic(() => import("./FilesPane"));
+export const BrowserPane = dynamic(() => import("./DesktopBrowserPane"));
+export const TasksSidebar = dynamic(() => import("./TasksSidebar"));
+export const AppSettings = dynamic(() => import("./AppSettings"));
+export const WorkspaceDialog = dynamic(() => import("./WorkspaceDialog"));
diff --git a/apps/native/electron/attachment-lifetime-frontend.cjs b/apps/native/electron/attachment-lifetime-frontend.cjs
index 847d8790..aec09f54 100644
--- a/apps/native/electron/attachment-lifetime-frontend.cjs
+++ b/apps/native/electron/attachment-lifetime-frontend.cjs
@@ -43,7 +43,14 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,cl
await fetch(origin+'/api/attach',{method:'DELETE',headers:{'content-type':'application/json'},body:JSON.stringify({paths:[edited]})});
assert.deepEqual(fs.readFileSync(edited),changed,'Discard must preserve an in-place edit to exported pixels');
await send('Describe the pasted image in one sentence.');
- await until(()=>js(`document.body.textContent.includes('The pasted image was received.') && !document.querySelector('article[aria-busy="true"]')`),'real image turn completion',25000);
+ await until(()=>{
+ try {
+ const raw=fs.readFileSync(requests,'utf8');
+ fs.writeFileSync(path.join(output,'attachment-requests.json'),raw);
+ return raw.includes(png);
+ } catch { return false; }
+ },'pasted PNG bytes on the model wire',25000);
+ await until(()=>js(`!document.querySelector('article[aria-busy="true"]')`),'image turn idle',25000);
const calls=JSON.parse(fs.readFileSync(requests,'utf8'));
fs.writeFileSync(path.join(output,'attachment-requests.json'),JSON.stringify(calls,null,2));
assert.ok(JSON.stringify(calls).includes(png),'Actual model requests must contain the pasted PNG bytes');
diff --git a/apps/native/electron/browser-focus-frontend.cjs b/apps/native/electron/browser-focus-frontend.cjs
index 3314adbb..6d2fe189 100644
--- a/apps/native/electron/browser-focus-frontend.cjs
+++ b/apps/native/electron/browser-focus-frontend.cjs
@@ -28,15 +28,19 @@ async function runBrowserFocus({ win, output, click, until, report }) {
await desktop.testInput(wc, { type: 'keyUp', keyCode: 'Return' });
await until(() => browser.visible && browser.tabs.get(browser.visible)?.view?.webContents.getURL() === url, 'explicit address navigation');
};
+ const openBrowser = async () => {
+ await click('[aria-label="Workspace tools"]');
+ await click('[aria-label="Browser"]');
+ };
const a = await focused();
- await click('[aria-label="Browser"]');
+ await openBrowser();
await navigateUser(`${origin}/first`);
const chatA = browser.visible;
await js(`Array.from(document.querySelectorAll('button[aria-label="New chat"]')).find(e=>e.checkVisibility()).setAttribute('data-browser-new-chat','true')`);
await click('[data-browser-new-chat="true"]');
await until(async () => (await focused()) !== a && browser.visible !== chatA, 'second chat');
if (!await js(`!!document.querySelector('[aria-label="Address"]')?.checkVisibility()`)) {
- await click('[aria-label="Browser"]');
+ await openBrowser();
}
await navigateUser(`${origin}/selected`);
const b = await focused(), chatB = browser.visible;
diff --git a/apps/native/lib/browser/kuri-supervisor.ts b/apps/native/lib/browser/kuri-supervisor.ts
index b78a6d69..c6466df1 100644
--- a/apps/native/lib/browser/kuri-supervisor.ts
+++ b/apps/native/lib/browser/kuri-supervisor.ts
@@ -50,11 +50,11 @@ const HEALTH_TIMEOUT_MS = 75_000;
export function kuriBin(): string | null {
const home = os.homedir();
const named = [process.env.KURI_BIN, path.join(home, ".local/bin/kuri"), path.join(home, "kuri/zig-out/bin/kuri")];
- for (const candidate of named) if (candidate && existsSync(candidate)) return candidate;
+ for (const candidate of named) if (candidate && existsSync(/*turbopackIgnore: true*/ candidate)) return candidate;
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
if (!dir) continue;
const candidate = path.join(dir, "kuri");
- if (existsSync(candidate)) return candidate;
+ if (existsSync(/*turbopackIgnore: true*/ candidate)) return candidate;
}
return null;
}
@@ -238,7 +238,7 @@ async function spawnKuri(): Promise<{ port: number; token: string }> {
// round). A private HOME gives the sidecar its own profile and state.
mkdirSync(PRIVATE_HOME, { recursive: true });
reapProfileChrome();
- const child = spawn(bin, [], {
+ const child = spawn(/*turbopackIgnore: true*/ bin, [], {
env: {
...process.env,
HOME: PRIVATE_HOME,
diff --git a/apps/native/lib/code-highlighter.ts b/apps/native/lib/code-highlighter.ts
index 6922e47f..3221c3c2 100644
--- a/apps/native/lib/code-highlighter.ts
+++ b/apps/native/lib/code-highlighter.ts
@@ -1,5 +1,4 @@
-import { bundledLanguages, bundledLanguagesInfo, createHighlighter, type Highlighter, type BundledLanguage, type BundledTheme, type ThemeRegistrationAny } from "shiki";
-import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
+import type { Highlighter, BundledLanguage, BundledTheme, ThemeRegistrationAny } from "shiki";
import type { CodeHighlighterPlugin } from "streamdown";
type HighlightOptions = Parameters<CodeHighlighterPlugin["highlight"]>[0];
@@ -9,17 +8,42 @@ type Engine = Pick<Highlighter, "loadLanguage" | "loadTheme" | "codeToTokens" |
type Entry = { result: HighlightResult; bytes: number };
type Request = { options: HighlightOptions; callback?: Callback; bytes: number };
-export const CODE_CACHE_BYTES = 4 * 1024 * 1024;
+export const CODE_CACHE_BYTES = 1536 * 1024;
export const CODE_CACHE_ENTRIES = 32;
export const CODE_HIGHLIGHT_LIMIT = 64 * 1024;
const PENDING_BYTES = 512 * 1024;
const PENDING_COUNT = 32;
const THEMES: HighlightOptions["themes"] = ["github-light", "github-dark"];
-const languages = new Set(Object.keys(bundledLanguages));
-const aliases = new Map(bundledLanguagesInfo.flatMap(language => (language.aliases ?? []).map(alias => [alias, language.id])));
+let languages = new Set<string>();
+let aliases = new Map<string, string>();
+let langLoaders: Record<string, () => Promise<unknown>> = {};
+let themeLoaders: Record<string, () => Promise<unknown>> = {};
const normalize = (language: string) => { const name = language.trim().toLowerCase(); return aliases.get(name) ?? name; };
const plain = (source: string): HighlightResult => ({ tokens: source.split("\n").map(content => [{ content }]) });
+async function loadShikiEngine(): Promise<Engine> {
+ const [
+ { createHighlighterCore },
+ { createJavaScriptRegexEngine },
+ { bundledLanguages, bundledLanguagesInfo },
+ { bundledThemes },
+ ] = await Promise.all([
+ import("shiki/core"),
+ import("shiki/engine/javascript"),
+ import("shiki/langs"),
+ import("shiki/themes"),
+ ]);
+ langLoaders = bundledLanguages as Record<string, () => Promise<unknown>>;
+ themeLoaders = bundledThemes as Record<string, () => Promise<unknown>>;
+ languages = new Set(Object.keys(langLoaders));
+ aliases = new Map(bundledLanguagesInfo.flatMap(language => (language.aliases ?? []).map(alias => [alias, language.id])));
+ return createHighlighterCore({
+ themes: [],
+ langs: [],
+ engine: createJavaScriptRegexEngine({ forgiving: true }),
+ }) as unknown as Engine;
+}
+
/** Keep only a bounded working set of tokens. A streamed fence otherwise caches
* every prefix for the life of the renderer, including after its chat closes. */
export function createCodeHighlighter(options: {
@@ -41,7 +65,12 @@ export function createCodeHighlighter(options: {
const themeName = (theme: HighlightOptions["themes"][number]) => typeof theme === "string" ? theme : `graff-theme-${themeKey(theme)}`;
// Full source prevents collisions when equal-length edits share their edges.
const keyFor = (value: HighlightOptions) => JSON.stringify([normalize(value.language), value.themes.map(themeKey), value.code]);
- const languageFor = (value: HighlightOptions) => { const name = normalize(value.language); return languages.has(name) ? name : "text"; };
+ const languageFor = (value: HighlightOptions) => {
+ const name = normalize(value.language);
+ if (name === "text" || name === "txt" || name === "plain") return "text";
+ if (languages.size > 0 && !languages.has(name)) return "text";
+ return name;
+ };
const ready = (value: HighlightOptions) => engine !== undefined &&
(languageFor(value) === "text" || loadedLanguages.has(languageFor(value))) && value.themes.every(theme => loadedThemes.has(themeKey(theme)));
const get = (key: string) => {
@@ -75,18 +104,24 @@ export function createCodeHighlighter(options: {
return retain(key, result);
};
const prepare = async (value: HighlightOptions) => {
- if (!loading) loading = (options.load ?? (() => createHighlighter({ themes: [], langs: [], engine: createJavaScriptRegexEngine({ forgiving: true }) })))();
+ if (!loading) loading = (options.load ?? loadShikiEngine)();
const current = await loading;
if (disposed) { current.dispose(); return; }
engine = current;
const themes = value.themes.filter(theme => !loadedThemes.has(themeKey(theme)));
if (themes.length) {
- await current.loadTheme(...themes.map(theme => typeof theme === "string" ? theme : { ...theme, name: themeName(theme) }) as (BundledTheme | ThemeRegistrationAny)[]);
+ await current.loadTheme(...await Promise.all(themes.map(async theme => {
+ if (typeof theme !== "string") return { ...theme, name: themeName(theme) };
+ const load = options.load ? undefined : themeLoaders[theme];
+ return load ? await load() : theme;
+ })) as (BundledTheme | ThemeRegistrationAny)[]);
themes.forEach(theme => loadedThemes.add(themeKey(theme)));
}
const language = languageFor(value);
if (language !== "text" && !loadedLanguages.has(language)) {
- await current.loadLanguage(language as BundledLanguage); loadedLanguages.add(language);
+ const load = options.load ? undefined : langLoaders[language];
+ await current.loadLanguage((load ? await load() : language) as BundledLanguage);
+ loadedLanguages.add(language);
}
};
const drain = async () => {
@@ -112,7 +147,11 @@ export function createCodeHighlighter(options: {
name: "shiki", type: "code-highlighter",
getThemes: () => THEMES,
getSupportedLanguages: () => [...languages],
- supportsLanguage: language => languages.has(normalize(language)),
+ supportsLanguage: language => {
+ const name = normalize(language);
+ if (name === "text" || name === "txt" || name === "plain" || name === "mermaid" || name === "mmd") return false;
+ return languages.size === 0 || languages.has(name);
+ },
highlight(value, callback) {
if (disposed) return plain(value.code);
// Finish asynchronous requests in call order, including subsequent cache
diff --git a/apps/native/lib/custom-themes.ts b/apps/native/lib/custom-themes.ts
index 0f02e4bd..066444a9 100644
--- a/apps/native/lib/custom-themes.ts
+++ b/apps/native/lib/custom-themes.ts
@@ -1,7 +1,7 @@
export const bases = ["light", "dark", "website", "codegraff"] as const;
export type BuiltinAppearance = typeof bases[number];
export const colorTokens = ["page", "canvas", "surface", "inset", "hover", "hover-2", "ink", "ink-2", "ink-3", "line", "line-strong", "field", "stripe", "stripe-bg", "accent", "accent-ink", "accent-tint", "green", "green-tint", "red", "red-tint", "orange", "orange-tint", "brand-coral", "brand-gold"] as const;
-export const fonts = { geist: 'var(--font-inter), system-ui, sans-serif', system: '-apple-system, BlinkMacSystemFont, sans-serif', serif: 'Georgia, "Times New Roman", serif' };
+export const fonts = { geist: 'var(--font-geist-sans), system-ui, sans-serif', system: '-apple-system, BlinkMacSystemFont, sans-serif', serif: 'Georgia, "Times New Roman", serif' };
export type CustomTheme = { version: 1; id: string; name: string; base: BuiltinAppearance; colors: Partial<Record<typeof colorTokens[number], string>>; font?: keyof typeof fonts; corners?: number };
export const themeLimit = 16 * 1024;
const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
diff --git a/apps/native/lib/gui-skill-context.ts b/apps/native/lib/gui-skill-context.ts
index 102e4c45..aff05785 100644
--- a/apps/native/lib/gui-skill-context.ts
+++ b/apps/native/lib/gui-skill-context.ts
@@ -43,7 +43,9 @@ export async function prepareGuiPrompt(params: Record<string, unknown> | undefin
}));
first.text = withGuiSkillContext(first.text, instructions.join("\n\n"));
}
- if (tokens) first.text = `${first.text}\n\n${appearanceNote(tokens)}`;
+ // Slash commands (`/model`, `/compact`, …) parse the whole first line.
+ // Appearance CSS contains `/` (oklch), which would corrupt `/model` ids.
+ if (tokens && !first.text.trimStart().startsWith("/")) first.text = `${first.text}\n\n${appearanceNote(tokens)}`;
const next: Record<string, unknown> = { ...params, prompt };
delete next.appearance;
return next;
diff --git a/apps/native/lib/gui-skills.test.ts b/apps/native/lib/gui-skills.test.ts
index 6e29902c..e46fb593 100644
--- a/apps/native/lib/gui-skills.test.ts
+++ b/apps/native/lib/gui-skills.test.ts
@@ -27,6 +27,14 @@ test("ordinary prompts and file attachments do not load GUI skills", async () =>
const original = { prompt: [{ type: "text", text: "Read the project" }, { type: "resource_link", name: "$theme", uri: "file:///fixture" }] };
expect(await prepareGuiPrompt(original)).toBe(original);
});
+test("slash commands do not receive desktop appearance tokens", async () => {
+ const original = { prompt: [{ type: "text", text: "/model lmstudio mock-vision" }], appearance: { page: "#0b0c09", ink: "#ececec" } };
+ const prepared = await prepareGuiPrompt(original);
+ const text = (prepared?.prompt as { text: string }[])[0].text;
+ expect(text).toBe("/model lmstudio mock-vision");
+ expect(text).not.toContain("[desktop appearance]");
+ expect(prepared).not.toHaveProperty("appearance");
+});
test("desktop appearance tokens ride the prompt and leave the catalog alone", async () => {
const original = { prompt: [{ type: "text", text: "Draw the burn-down" }], appearance: { page: "#faf8f5", surface: "#ffffff", ink: "#1a1a1a" } };
const prepared = await prepareGuiPrompt(original);
diff --git a/apps/native/next.config.ts b/apps/native/next.config.ts
index a0411b5c..616474d7 100644
--- a/apps/native/next.config.ts
+++ b/apps/native/next.config.ts
@@ -21,7 +21,7 @@ const nextConfig: NextConfig = {
// the bottom-left corner, on top of the sidebar's session control.
devIndicators: { position: "bottom-right" },
experimental: {
- optimizePackageImports: ["iconoir-react"],
+ optimizePackageImports: ["iconoir-react", "streamdown"],
},
};
diff --git a/apps/native/package.json b/apps/native/package.json
index a6580153..f6cc27ff 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -62,6 +62,7 @@
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"electron-updater": "6.8.9",
+ "geist": "^1.7.2",
"glimm": "^0.3.0",
"iconoir-react": "^7.11.1",
"liveline": "^0.0.7",
diff --git a/src/http_headers.zig b/src/http_headers.zig
index 0cccd35b..53dfebbf 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -148,6 +148,16 @@ pub fn adoptSessionId(id: []const u8) void {
session_id_len = 36;
}
+/// A replacement worker loading a saved session must take that conversation
+/// id even if startup already minted one (idle-park respawn, `graff acp --resume`).
+pub fn restoreSessionId(id: []const u8) void {
+ if (id.len != 36) return;
+ while (session_id_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
+ defer session_id_lock.store(false, .release);
+ @memcpy(session_id_buf[0..36], id[0..36]);
+ session_id_len = 36;
+}
+
pub fn userAgent(provider: Provider) std.http.Client.Request.Headers.Value {
if (std.mem.eql(u8, provider.id, "kimi")) {
return .{ .override = root.kimi_user_agent };
@@ -430,6 +440,15 @@ test "adoptSessionId validates length and never overwrites a minted id" {
try std.testing.expectEqualStrings(before, sessionId(io));
}
+test "restoreSessionId overwrites a minted id so a parked worker keeps cache affinity" {
+ const io = std.testing.io;
+ _ = sessionId(io);
+ restoreSessionId("00000000-0000-4000-8000-000000000001");
+ try std.testing.expectEqualStrings("00000000-0000-4000-8000-000000000001", sessionId(io));
+ restoreSessionId("short");
+ try std.testing.expectEqualStrings("00000000-0000-4000-8000-000000000001", sessionId(io));
+}
+
fn headerValue(headers: []const std.http.Header, name: []const u8) ?[]const u8 {
for (headers) |h| if (std.mem.eql(u8, h.name, name)) return h.value;
return null;
diff --git a/src/session.zig b/src/session.zig
index c3175282..f4334253 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -353,6 +353,8 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64
// kimi-code/codex key cache affinity on the durable conversation id; persisting ours keeps /resume warm.
try s.objectField("cache_key");
try s.write(http_headers.sessionId(root.io));
+ try s.objectField("prompt_cache_key");
+ try s.write(http_headers.projectRootId(root.io)); // idle-park resume must keep this partition
try session_peer.writeFields(&s);
try subagent_ledger.writeFields(&s, root.io);
try s.endObject();
@@ -417,6 +419,12 @@ pub fn cacheKeyFromSession(obj: std.json.ObjectMap) ?[]const u8 {
const v = obj.get("cache_key") orelse return null;
return if (v == .string and v.string.len == 36) v.string else null;
}
+
+/// Git-root prompt-cache partition. Absent on pre-idle-park saves.
+pub fn promptCacheKeyFromSession(obj: std.json.ObjectMap) ?[]const u8 {
+ const v = obj.get("prompt_cache_key") orelse return null;
+ return if (v == .string and v.string.len == 36) v.string else null;
+}
/// The persisted --json sequence high-water mark (#330); 0 for sessions saved
/// before it existed, so a resume of one starts the numbering fresh.
pub fn eventSeqFromSession(obj: std.json.ObjectMap) u64 {
@@ -484,7 +492,7 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
// only ever raises the counter, so a legacy session (no field) or a corrupt
// negative value simply leaves this process's numbering alone.
protocol_seq.restore(eventSeqFromSession(obj));
- if (cacheKeyFromSession(obj)) |k| http_headers.adoptSessionId(k);
+ if (cacheKeyFromSession(obj)) |k| http_headers.restoreSessionId(k);
root.ensureStoredKeys(keys);
if (std.mem.eql(u8, pid, "codex")) root.ensureModelCatalog(keys.*);
diff --git a/src/session_tests.zig b/src/session_tests.zig
index 26aa9fea..86ae5e16 100644
--- a/src/session_tests.zig
+++ b/src/session_tests.zig
@@ -484,6 +484,11 @@ test "cache_key round-trips: parsed on load, garbage and absence rejected" {
\\{"cache_key":42}
, .{});
try std.testing.expect(session.cacheKeyFromSession(wrong_type.object) == null);
+ const both = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"cache_key":"00000000-0000-4000-8000-000000000000","prompt_cache_key":"11111111-1111-5111-8111-111111111111"}
+ , .{});
+ try std.testing.expectEqualStrings("11111111-1111-5111-8111-111111111111", session.promptCacheKeyFromSession(both.object).?);
+ try std.testing.expect(session.promptCacheKeyFromSession(legacy.object) == null);
}
test "hasMeaningfulState: a peer wake alone is not a conversation" {
diff --git a/src/vision.zig b/src/vision.zig
index 29dfb5d8..746130dd 100644
--- a/src/vision.zig
+++ b/src/vision.zig
@@ -161,6 +161,16 @@ pub const StageResult = union(enum) {
}
};
+fn readStagedBytes(io: Io, arena: Allocator, path: []const u8) ?[]u8 {
+ const limit: Io.Limit = .limited(@intCast(clip.max_staged_image_bytes));
+ if (Io.Dir.cwd().readFileAlloc(io, path, arena, limit)) |data| return data else |_| {}
+ if (!std.fs.path.isAbsolute(path)) return null;
+ const dir_path = std.fs.path.dirname(path) orelse return null;
+ var dir = Io.Dir.openDirAbsolute(io, dir_path, .{}) catch return null;
+ defer dir.close(io);
+ return dir.readFileAlloc(io, std.fs.path.basename(path), arena, limit) catch null;
+}
+
/// Read an image file, base64-encode it, and stage it on the agent for the next
/// turn (shared by /image, /paste, and Ctrl-V). Refuses on non-vision models.
///
@@ -178,7 +188,7 @@ pub fn stageImagePath(root: *Agent, path: []const u8) StageResult {
defer if (fit.temp) clip.discard(io, root.gpa, fit.path);
const arena = root.arena;
- const data = Io.Dir.cwd().readFileAlloc(io, fit.path, arena, .limited(@intCast(clip.max_staged_image_bytes))) catch return .read_error;
+ const data = readStagedBytes(io, arena, fit.path) orelse return .read_error;
const enc = std.base64.standard.Encoder;
const b64 = arena.alloc(u8, enc.calcSize(data.len)) catch return .read_error;
_ = enc.encode(b64, data);
diff --git a/src/vision_clipboard.zig b/src/vision_clipboard.zig
index 5e6a49e7..51cae866 100644
--- a/src/vision_clipboard.zig
+++ b/src/vision_clipboard.zig
@@ -120,7 +120,16 @@ fn deleteQuietly(io: Io, path: []const u8) void {
/// "not there, or not a file" — never "too big", which is the distinction the
/// old single `.read_fail` threw away.
pub fn regularFileSize(io: Io, path: []const u8) ?u64 {
- const st = Io.Dir.cwd().statFile(io, path, .{}) catch return null;
+ if (fileSizeAt(io, Io.Dir.cwd(), path)) |n| return n;
+ if (!std.fs.path.isAbsolute(path)) return null;
+ const dir_path = std.fs.path.dirname(path) orelse return null;
+ var dir = Io.Dir.openDirAbsolute(io, dir_path, .{}) catch return null;
+ defer dir.close(io);
+ return fileSizeAt(io, dir, std.fs.path.basename(path));
+}
+
+fn fileSizeAt(io: Io, dir: Io.Dir, path: []const u8) ?u64 {
+ const st = dir.statFile(io, path, .{}) catch return null;
if (st.kind != .file) return null;
return st.size;
}
diff --git a/src/vision_clipboard_tests.zig b/src/vision_clipboard_tests.zig
index 47221a31..b50111f1 100644
--- a/src/vision_clipboard_tests.zig
+++ b/src/vision_clipboard_tests.zig
@@ -268,3 +268,15 @@ test "max_staged_image_bytes: base64 of a full-budget image stays under the 5 MB
// …and the OLD 5 MiB ceiling did not, which is the #349 bug in one line.
try testing.expect(std.base64.standard.Encoder.calcSize(5 * 1024 * 1024) > 5_000_000);
}
+
+test "regularFileSize: absolute path outside cwd (GUI paste dir)" {
+ const io = testing.io;
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "shot.png", .data = "not-a-real-png" });
+ const abs = try tmp.dir.realPathFileAlloc(io, "shot.png", testing.allocator);
+ defer testing.allocator.free(abs);
+ try testing.expect(std.fs.path.isAbsolute(abs));
+ const size = regularFileSize(io, abs);
+ try testing.expectEqual(@as(?u64, 14), size);
+}