graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: start the Electron desktop on Linux
Cursor Agentd6c5a6a4571c
diff --git a/apps/native/README.md b/apps/native/README.mdindex 3d49fb5f..eb9937e0 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -152,7 +152,8 @@ Graff, including `/compact`. New tabs inherit it before starting a coding sessioCommand behavior belongs to the engine; terminal display settings retain theirterminal meaning. Menus remain inside the window and scroll independently.-The desktop adapts familiar Ghostty bindings to chats and split panes:+The desktop adapts familiar Ghostty bindings to chats and split panes.+On Linux and Windows, Command in this table is Ctrl. Split resize is Ctrl+Alt with the arrow keys, and Ctrl+Alt+= equalizes splits.| Keys | Action ||---|---|@@ -178,7 +179,7 @@ The File menu lists the main actions. Standard copy, paste, undo and text selectremain native. Terminal-only actions such as sending escape sequences have nochat equivalent. A web browser reserves some shortcuts for its own tabs.-The macOS workspace terminal opens your login shell in the active folder. Drag+The macOS workspace terminal opens your login shell in the active folder. On Linux it opens `$SHELL` through a POSIX PTY. Dragits top edge to resize it. Hiding it preserves the session; **End session** stopsit. Up to four workspace shells can stay open, with bounded output history.diff --git a/apps/native/app/api/fs/route.ts b/apps/native/app/api/fs/route.tsindex 68b793bc..804a795c 100644--- a/apps/native/app/api/fs/route.ts+++ b/apps/native/app/api/fs/route.ts@@ -3,6 +3,7 @@ import { readdirSync, createReadStream, statSync } from "node:fs";import path from "node:path";import { Readable } from "node:stream";import { filePreview } from "@/lib/file-preview";+import { hostOpenCommand } from "@/lib/host-open";import { NextRequest } from "next/server";import { resolveRoot } from "@/lib/server-root";@@ -144,16 +145,11 @@ export async function POST(req: NextRequest) {const root = resolved.root;const target = resolveInRoot(root, body.path ?? "");if (!target) return Response.json({ error: "path escapes the workspace" }, { status: 400 });- if (process.platform !== "darwin") {- return Response.json({ error: "open/reveal is macOS-only here" }, { status: 501 });+ const command = hostOpenCommand(body.action ?? "", target);+ if (!command) {+ if (body.action === "reveal" || body.action === "open") return Response.json({ error: "open/reveal is unavailable on this system" }, { status: 501 });+ return Response.json({ error: `unknown action: ${body.action}` }, { status: 400 });}- if (body.action === "reveal") {- spawn("open", ["-R", target], { stdio: "ignore", detached: true }).unref();- return Response.json({ ok: true });- }- if (body.action === "open") {- spawn("open", [target], { stdio: "ignore", detached: true }).unref();- return Response.json({ ok: true });- }- return Response.json({ error: `unknown action: ${body.action}` }, { status: 400 });+ spawn(command.bin, command.args, { stdio: "ignore", detached: true }).unref();+ return Response.json({ ok: true });}diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsxindex a2611313..d6f5f1a0 100644--- a/apps/native/components/primitives/SidebarNav.tsx+++ b/apps/native/components/primitives/SidebarNav.tsx@@ -18,6 +18,7 @@ import {} from "@/lib/icons";import CodeGraffMark from "./CodeGraffMark";import GlideMenu from "@/components/primitives/GlideMenu";+import { useCommandGlyph } from "@/lib/shortcut-glyph";import ActionMenu from "./ActionMenu";import WorkspaceMenu from "./WorkspaceMenu";@@ -199,6 +200,7 @@ export default function SidebarNav({onSeeAll,agentsCount = 0,}: SidebarNavProps) {+ const mod = useCommandGlyph();const [collapsed, setCollapsed] = useState(false);useEffect(() => { onCollapsedChange?.(collapsed); }, [collapsed, onCollapsedChange]);useEffect(() => {@@ -318,7 +320,7 @@ export default function SidebarNav({ref={collapseButtonRef}type="button"aria-label={onCloseNavigation ? "Close navigation" : "Collapse sidebar"}- title={onCloseNavigation ? "Close navigation" : "Collapse sidebar (⌘B)"}+ title={onCloseNavigation ? "Close navigation" : `Collapse sidebar (${mod}B)`}aria-hidden={collapsed}tabIndex={collapsed ? -1 : 0}onClick={collapse}@@ -330,7 +332,7 @@ export default function SidebarNav({ref={expandButtonRef}type="button"aria-label="Expand sidebar"- title="Expand sidebar (⌘B)"+ title={`Expand sidebar (${mod}B)`}aria-hidden={!collapsed}tabIndex={collapsed ? 0 : -1}onClick={() => { setCollapsed(false); requestAnimationFrame(() => collapseButtonRef.current?.focus()); }}diff --git a/apps/native/components/primitives/WorkspaceMenu.tsx b/apps/native/components/primitives/WorkspaceMenu.tsxindex 7f8d0bd8..6998544d 100644--- a/apps/native/components/primitives/WorkspaceMenu.tsx+++ b/apps/native/components/primitives/WorkspaceMenu.tsx@@ -2,11 +2,13 @@import { useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { monogram, compareWorkspaceActivity, workspaceSourceLabel, type Workspace } from '@/lib/workspaces';+import { useCommandGlyph } from '@/lib/shortcut-glyph';type Row = Workspace;export default function WorkspaceMenu({position,current,rows,onSwitch,onNew,onSettings,onClose}:{position:{top:number;left:number};current?:string;rows:Row[];onSwitch?:(path:string)=>void;onNew?:()=>void;onSettings?:()=>void;onClose:()=>void;}) {const [query,setQuery]=useState('');const input=useRef<HTMLInputElement>(null);const menu=useRef<HTMLDivElement>(null);+ const mod = useCommandGlyph();const close=useRef(onClose);close.current=onClose;useEffect(()=>{const previous=document.activeElement as HTMLElement|null;input.current?.focus();const escape=(e:KeyboardEvent)=>{if(e.key==='Escape'){e.preventDefault();close.current();}};window.addEventListener('keydown',escape);return()=>{window.removeEventListener('keydown',escape);previous?.focus();};},[]);const list=rows.filter(row=>`${row.name} ${row.path}`.toLowerCase().includes(query.toLowerCase())).sort((a,b)=>Number(b.path===current)-Number(a.path===current)||compareWorkspaceActivity(a,b));@@ -31,7 +33,7 @@ export default function WorkspaceMenu({position,current,rows,onSwitch,onNew,onSe{!list.length&&<p className="p-3 text-sm text-ink-3">{query?'No matching workspaces.':'Open a folder to start a workspace.'}</p>}</div><div className="shrink-0 border-t border-line p-1.5">- <button type="button" onClick={pick(onNew)} className="flex w-full justify-between rounded-lg px-3 py-2 text-sm text-ink hover:bg-hover">Open a folder…<kbd className="text-xs text-ink-3">⌘O</kbd></button>+ <button type="button" onClick={pick(onNew)} className="flex w-full justify-between rounded-lg px-3 py-2 text-sm text-ink hover:bg-hover">Open a folder…<kbd className="text-xs text-ink-3">{mod}O</kbd></button><button type="button" onClick={pick(onSettings)} className="w-full rounded-lg px-3 py-2 text-left text-sm text-ink hover:bg-hover">Project settings…</button></div></div>,document.querySelector('[data-navigation-panel]:popover-open') ?? document.body);diff --git a/apps/native/components/site/ChatSplitLayout.tsx b/apps/native/components/site/ChatSplitLayout.tsxindex b74df3f3..8b402210 100644--- a/apps/native/components/site/ChatSplitLayout.tsx+++ b/apps/native/components/site/ChatSplitLayout.tsx@@ -6,6 +6,7 @@ import { createComposerDraft, type ComposerDraftStore } from "@/lib/composer-draimport SplitDivider from "./SplitDivider";import paneStyles from "./chat-pane.module.css";import {flatSplit,pruneSplit,splitGeometry,paneStyle,type SplitTree} from "@/lib/split-tree";+import { useCommandGlyph } from "@/lib/shortcut-glyph";export default function ChatSplitLayout({ threads, liveChatIds, activeId, direction, layout, onLayoutChange, onFocus, onClose, folder, body, split, claims = [] }: {threads: Chat[]; activeId: number; direction: "row" | "column"; layout?: SplitTree;liveChatIds?: number[];@@ -13,6 +14,7 @@ export default function ChatSplitLayout({ threads, liveChatIds, activeId, directfolder(thread: Chat): { name: string; path?: string }; body(thread: Chat): ReactNode; split: boolean;claims?: { kind: string; key: string; session: string }[];}) {+ const mod = useCommandGlyph();const drafts = useRef(new Map<number, ComposerDraftStore>());const liveKey = liveChatIds?.join(",");useEffect(() => {@@ -53,7 +55,7 @@ export default function ChatSplitLayout({ threads, liveChatIds, activeId, direct<span key={`${claim.kind}:${claim.key}`} title={`${claim.kind} ${claim.key}`} className="max-w-[45%] truncate rounded-full bg-inset px-2 py-0.5 text-[10px] text-ink-3">{claim.kind === "pull_request" ? `PR ${claim.key}` : claim.kind === "issue" ? `#${claim.key}` : claim.key}</span>)}{split && <span title={folder(thread).path} className="flex min-w-0 max-w-[40%] items-center gap-1 text-[11px] text-ink-3"><IconFolder size={13}/><span className="truncate">{folder(thread).name}</span></span>}- {split && <button type="button" aria-label="Close this split" title="Close this chat (⌘W)" onClick={()=>onClose(thread.id)} className="flex size-6 shrink-0 items-center justify-center rounded text-ink-3 hover:bg-hover hover:text-ink">×</button>}+ {split && <button type="button" aria-label="Close this split" title={`Close this chat (${mod}W)`} onClick={()=>onClose(thread.id)} className="flex size-6 shrink-0 items-center justify-center rounded text-ink-3 hover:bg-hover hover:text-ink">×</button>}</header>}<ComposerDraftContext.Provider value={draftFor(thread.id)}>{body(thread)}</ComposerDraftContext.Provider></section>diff --git a/apps/native/components/site/DesktopTitlebar.tsx b/apps/native/components/site/DesktopTitlebar.tsxindex de4a0fe4..f5f5e9e3 100644--- a/apps/native/components/site/DesktopTitlebar.tsx+++ b/apps/native/components/site/DesktopTitlebar.tsx@@ -2,7 +2,16 @@import { useEffect, useState, type CSSProperties } from "react";export default function DesktopTitlebar() {const [enabled, setEnabled] = useState(false);- useEffect(() => { if (window.graffDesktop) { setEnabled(true); document.documentElement.dataset.desktop = "true"; } }, []);+ useEffect(() => {+ const bridge = window.graffDesktop;+ if (!bridge) return;+ document.documentElement.dataset.desktop = "true";+ if (bridge.frame === "system") {+ document.documentElement.dataset.desktopFrame = "system";+ return;+ }+ setEnabled(true);+ }, []);return enabled ? <><style>{`html[data-desktop="true"] { --desktop-title-height: 36px; }html[data-desktop-fullscreen="true"] { --desktop-title-height: 0px; }diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsxindex 4c375d6e..f47a32e8 100644--- a/apps/native/components/site/HarnessChrome.tsx+++ b/apps/native/components/site/HarnessChrome.tsx@@ -8,6 +8,7 @@ import type { PointerEvent, MouseEvent, ReactNode } from "react";import type { Chat } from "./harness-types";import reviewStyles from "./ChangesPane.module.css";import { archiveTaskWorkspace, createTaskWorkspace, gcTaskWorkspaces, landTaskWorkspace, runTaskWorkspace, updateTaskWorkspace } from "./harness-task-workspace";+import { useCommandGlyph } from "@/lib/shortcut-glyph";type Props = {navigationToggle?: ReactNode; sidebarVisible?: boolean;@@ -30,6 +31,7 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,conversationsOpen, openConversations, split, toggleSplit, filesOpen, onFiles, chatCwd,workspaceName, onFolder, openChanges, changesOpen = false, reviewsOpen = false, onReviews, browserOpen, onBrowser, pinCount, terminalVisible,toggleTerminal, agentsOpen, onAgents, workingAgents = 0, tasksOpen = false, taskCount = 0, onTasks, splitNotice, onTabPointerDown, onTabClickCapture}: Props) {+ const mod = useCommandGlyph();return (<div data-workspace-toolbar data-workspace-root={chatCwd} className={`${reviewStyles.chatbar} flex shrink-0 flex-col ${sidebarVisible ? "overflow-visible bg-transparent" : "overflow-hidden rounded-[14px] border border-line bg-page"}`}>{!sidebarVisible && <div data-session-tab-strip className="flex h-10 min-w-0 shrink-0 items-center gap-1 px-2">@@ -40,7 +42,7 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,<SessionTabs chats={chats} activeId={activeId} busyIds={busyIds} unreadIds={unreadIds}agentsOpen={agentsOpen} focusChat={focusChat} closeChat={closeChat}onTabPointerDown={onTabPointerDown} onTabClickCapture={onTabClickCapture} />- <button type="button" aria-label="New chat" title="New chat (⌘T)" onClick={newChat}+ <button type="button" aria-label="New chat" title={`New chat (${mod}T)`} onClick={newChat}className="ml-0.5 flex size-7 shrink-0 items-center justify-center rounded-full text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden><path d="M12 5v14M5 12h14" />@@ -62,18 +64,18 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,<button type="button" aria-label="Land task workspace" onClick={() => void landTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>Land</button><button type="button" aria-label="Archive task workspace" onClick={() => void archiveTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>Archive</button><button type="button" aria-label="Clear unused task trees" onClick={() => void gcTaskWorkspaces(chatCwd).catch(err => window.alert(String(err.message || err)))}>Clear unused trees</button>- <button type="button" aria-label="Toggle terminal" aria-pressed={terminalVisible} onClick={toggleTerminal}>Terminal <span className="ml-auto text-ink-3">⌘J</span></button>+ <button type="button" aria-label="Toggle terminal" aria-pressed={terminalVisible} onClick={toggleTerminal}>Terminal <span className="ml-auto text-ink-3">{mod}J</span></button><button type="button" aria-label="Browser" aria-pressed={browserOpen} onClick={onBrowser}>Browser{pinCount > 0 ? ` (${pinCount})` : ""}</button><button type="button" aria-label="Files" aria-pressed={filesOpen && !changesOpen} onClick={onFiles}>Files</button></ActionMenu>{(taskCount > 0 || tasksOpen) && onTasks && <button type="button" aria-label="Show tasks" aria-pressed={tasksOpen} onClick={onTasks} className={paneBtn(tasksOpen)}>Tasks{taskCount ? ` (${taskCount})` : ""}</button>}<ActionMenu label="Chat actions" text="More" className="shrink-0">- {!sidebarVisible && <button type="button" onClick={newChat}>New chat <span className="ml-auto text-ink-3">⌘T</span></button>}- <button type="button" aria-pressed={split} onClick={toggleSplit}>{split ? "Close splits" : "Split view"} <span className="ml-auto text-ink-3">⌘\</span></button>+ {!sidebarVisible && <button type="button" onClick={newChat}>New chat <span className="ml-auto text-ink-3">{mod}T</span></button>}+ <button type="button" aria-pressed={split} onClick={toggleSplit}>{split ? "Close splits" : "Split view"} <span className="ml-auto text-ink-3">{mod}\</span></button><button type="button" aria-label="Conversations" aria-pressed={conversationsOpen} onClick={openConversations}>All conversations</button><button type="button" onClick={onFolder}>Open a folder…</button></ActionMenu>- {!sidebarVisible && <button type="button" aria-label="Expand sidebar" title="Expand sidebar (⌘B)"+ {!sidebarVisible && <button type="button" aria-label="Expand sidebar" title={`Expand sidebar (${mod}B)`}onClick={() => window.dispatchEvent(new CustomEvent("graff-toggle-sidebar"))}className="hidden size-7 shrink-0 items-center justify-center rounded-full text-ink-3 hover:bg-hover hover:text-ink lg:flex"><IconSidebarLeftOpen size={16} />diff --git a/apps/native/components/site/TerminalPane.tsx b/apps/native/components/site/TerminalPane.tsxindex 7bca98f7..de1869a5 100644--- a/apps/native/components/site/TerminalPane.tsx+++ b/apps/native/components/site/TerminalPane.tsx@@ -3,15 +3,17 @@ import {useEffect,useRef,useState} from 'react';import type {Terminal} from '@xterm/xterm';import '@xterm/xterm/css/xterm.css';import {desktop,type TerminalEvent} from '@/lib/desktop';+import { useCommandGlyph } from '@/lib/shortcut-glyph';export default function TerminalPane({cwd,visible,onHide}:{cwd:string;visible:boolean;onHide():void}) {const host=useRef<HTMLDivElement>(null),terminal=useRef<Terminal|null>(null),id=useRef<string|null>(null);const [height,setHeight]=useState(240),[generation,setGeneration]=useState(0),[error,setError]=useState(''),[status,setStatus]=useState('Starting shell…');const shown=useRef(visible);shown.current=visible;+ const mod=useCommandGlyph();const start=visible||id.current!==null;useEffect(()=>{if(!start)return;- const bridge=desktop();if(!bridge?.terminal||!bridge.terminalSubscribe){setError('The workspace terminal is available in the macOS desktop app.');return;}+ const bridge=desktop();if(!bridge?.terminal||!bridge.terminalSubscribe){setError('The workspace terminal is available in the desktop app.');return;}let disposed=false,off=()=>{},resize:ResizeObserver|undefined,theme:MutationObserver|undefined;const request=bridge.terminal;const send=(action:string,params:Record<string,unknown>={})=>request(action,{id:id.current,...params}).catch(e=>{if(!disposed)setError(String(e.message||e));});@@ -28,7 +30,12 @@ export default function TerminalPane({cwd,visible,onHide}:{cwd:string;visible:boapplyTheme();theme=new MutationObserver(applyTheme);theme.observe(document.documentElement,{attributes:true,attributeFilter:['data-theme','style','class']});term.onData(data=>{if(id.current)void send('input',{data});});term.onResize(({cols,rows})=>{if(id.current)void send('resize',{cols,rows});});- term.attachCustomKeyEventHandler(event=>{if(event.metaKey&&event.key.toLowerCase()==='k'){if(event.type==='keydown')term.clear();event.preventDefault();return false;}return !event.metaKey;});+ term.attachCustomKeyEventHandler(event=>{+ const mac=/Mac|iPhone|iPad/.test(navigator.platform);+ const command=mac?event.metaKey:(event.ctrlKey||event.metaKey);+ if(command&&!event.altKey&&!event.shiftKey&&event.key.toLowerCase()==='k'){if(event.type==='keydown')term.clear();event.preventDefault();return false;}+ return mac?!event.metaKey:true;+ });let ready=false;const queued:TerminalEvent[]=[];const deliver=(event:TerminalEvent)=>{if(event.id!==id.current)return;@@ -67,9 +74,9 @@ export default function TerminalPane({cwd,visible,onHide}:{cwd:string;visible:boonPointerUp={event=>event.currentTarget.releasePointerCapture(event.pointerId)} /><header className="flex h-9 items-center gap-3 border-b border-line px-3 text-xs"><strong className="font-medium">Terminal</strong><span title={cwd} className="min-w-0 flex-1 truncate text-ink-3">{cwd.split('/').pop()||cwd}</span><span role="status" className="text-ink-3">{status}</span>- <button onClick={()=>terminal.current?.clear()} title="Clear terminal (⌘K)" className="hover:text-accent-ink">Clear</button>+ <button onClick={()=>terminal.current?.clear()} title={`Clear terminal (${mod}K)`} className="hover:text-accent-ink">Clear</button><button onClick={()=>{if(id.current)void desktop()?.terminal?.('close',{id:id.current});if(terminal.current)terminal.current.options.disableStdin=true;setStatus('Shell exited');}} className="hover:text-accent-ink">End session</button>- <button aria-label="Hide terminal" title="Hide terminal (⌘J)" onClick={onHide} className="px-1 hover:text-accent-ink">×</button>+ <button aria-label="Hide terminal" title={`Hide terminal (${mod}J)`} onClick={onHide} className="px-1 hover:text-accent-ink">×</button></header>{error&&<div role="alert" className="absolute inset-x-2 top-10 z-10 rounded bg-surface p-3 text-xs text-red">{error}<button onClick={()=>void end()} className="ml-3 underline">Retry</button></div>}{status.startsWith('Shell exited')&&<button onClick={()=>void end()} className="absolute right-4 top-11 z-10 rounded bg-surface px-3 py-1 text-xs shadow-hairline">New session</button>}diff --git a/apps/native/components/site/useDesktopShortcuts.ts b/apps/native/components/site/useDesktopShortcuts.tsindex bf69b962..74985c36 100644--- a/apps/native/components/site/useDesktopShortcuts.ts+++ b/apps/native/components/site/useDesktopShortcuts.ts@@ -39,10 +39,13 @@ export function useDesktopShortcuts(actions: Actions) {const onKey=(e:KeyboardEvent)=>{// Dialogs own their typing and navigation. Escape and Tab remain local.if(e.isComposing||e.keyCode===229)return;- if(e.target instanceof Element&&e.target.closest('[data-workspace-terminal]')&&!e.metaKey)return;+ const mac=/Mac|iPhone|iPad/.test(navigator.platform);+ const shortcut=e.metaKey||(!mac&&e.ctrlKey);+ if(e.target instanceof Element&&e.target.closest('[data-workspace-terminal]')&&!shortcut)return;if(document.querySelector('[role="dialog"]'))return;const a=ref.current,k=e.key.toLowerCase();let handled=false;const command=e.metaKey||e.ctrlKey;+ const chord=mac?e.metaKey&&e.ctrlKey:e.ctrlKey&&e.altKey;const focus=(id:number)=>{a.focusChat(id);requestAnimationFrame(()=>{@@ -52,8 +55,8 @@ export function useDesktopShortcuts(actions: Actions) {const cycle=(ids:number[],delta:number)=>{const index=ids.indexOf(a.activeId);const id=ids[(index+delta+ids.length)%ids.length];if(id!==undefined)focus(id);};if(e.ctrlKey&&!e.metaKey&&k==='tab'){cycle(a.chats.map(c=>c.id),e.shiftKey?-1:1);handled=true;}else if(command){- if(e.metaKey&&e.ctrlKey&&k.startsWith('arrow')){a.resizePane(k==='arrowleft'||k==='arrowup'?-0.2:0.2);handled=true;}- else if(e.metaKey&&e.ctrlKey&&['=','+'].includes(k)){a.equalize();handled=true;}+ if(chord&&k.startsWith('arrow')){a.resizePane(k==='arrowleft'||k==='arrowup'?-0.2:0.2);handled=true;}+ else if(chord&&['=','+'].includes(k)){a.equalize();handled=true;}else if(e.altKey&&k.startsWith('arrow')){cycle(a.columns,k==='arrowleft'||k==='arrowup'?-1:1);handled=true;}else if(!e.altKey){if(k==='j'&&!e.shiftKey)handled=dispatch('terminal');diff --git a/apps/native/electron/README.md b/apps/native/electron/README.mdindex e12b3925..46ca569e 100644--- a/apps/native/electron/README.md+++ b/apps/native/electron/README.md@@ -197,6 +197,10 @@ score. Chromium chooses its supported GPU backend; no forced driver flags orcustom Metal pipeline are needed for the current DOM-based interface.See [repeatable performance scenarios](VISUAL-TESTS.md) for the model-free runner.+## Linux desktop++`build.sh` on Linux writes an unpacked app at `zig-out/electron/codegraff`, a `.deb`, and an AppImage when `appimagetool` is installed. Launch with `codegraff` in that directory. The window uses system decorations. The terminal helper is a POSIX PTY. macOS activity, Liquid Glass, and computer use stay out of the bundle. The launcher uses the setuid sandbox helper when the deb install sets it, a user namespace when `unshare --user` works, and `--no-sandbox` otherwise so the app still opens.+## Building a distribution disk image`build.sh` produces a development app with a local signature. For public downloads,diff --git a/apps/native/electron/build-icon.cjs b/apps/native/electron/build-icon.cjsindex d3e6ddb1..e5764a1e 100644--- a/apps/native/electron/build-icon.cjs+++ b/apps/native/electron/build-icon.cjs@@ -7,8 +7,15 @@ const { execFileSync } = require('node:child_process');async function main() {const output = process.argv[2];- if (!output) throw new Error('Provide the output .icns path.');+ const sizeArg = Number(process.argv[3] || 0);+ if (!output) throw new Error('Provide the output icon path.');const source = path.join(__dirname, '../desktop/icon.svg');+ if (output.endsWith('.png')) {+ const size = sizeArg || 256;+ await sharp(source).resize(size, size).png().toFile(path.resolve(output));+ return;+ }+ if (!output.endsWith('.icns')) throw new Error('Provide an .icns or .png output path.');const work = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-icon-'));const iconset = path.join(work, 'Codegraff.iconset');try {diff --git a/apps/native/electron/build-linux.sh b/apps/native/electron/build-linux.shnew file mode 100755index 00000000..4946aa01--- /dev/null+++ b/apps/native/electron/build-linux.sh@@ -0,0 +1,135 @@+# Sourced from build.sh after the UI and graff binary exist.+stage_linux_app() {+ local dist="$ui/node_modules/electron/dist"+ local app="$out/codegraff"+ if [[ ! -x "$dist/electron" ]]; then+ echo "Electron for this OS is not installed." >&2+ exit 1+ fi+ rm -rf "$app"+ mkdir -p "$app"+ cp -a "$dist/." "$app/"+ rm -f "$app/resources/default_app.asar"+ mv "$app/electron" "$app/codegraff.bin"+ chmod 755 "$app/codegraff.bin"+ local resources="$app/resources"+ mkdir -p "$resources/app" "$resources/native" "$resources/ui/.next"+ if [[ "${GRAFF_DEV:-0}" == "1" ]]; then touch "$resources/codegraff-development"; fi+ cp "$here/"*.cjs "$resources/app/"+ bun build "$here/updater-runtime.cjs" --target=node --format=cjs --external electron --outfile "$resources/app/updater-runtime.cjs"+ printf '{"name":"codegraff","productName":"%s","version":"%s","main":"main.cjs"}\n' "$app_name" "$version" > "$resources/app/package.json"+ cp -a "$ui/.next/standalone/." "$resources/ui/"+ cp -a "$ui/.next/static" "$resources/ui/.next/static"+ if [[ -d "$ui/public" ]]; then cp -a "$ui/public" "$resources/ui/public"; fi+ bun "$here/prepare-bundle.cjs" "$resources/ui"+ rm -rf "$resources/ui/node_modules/@img"+ cp -L "$(command -v bun)" "$resources/bun"+ chmod 755 "$resources/bun"+ cp "$root/zig-out/bin/graff" "$resources/graff"+ chmod 755 "$resources/graff"+ cc -O2 -Wall -Wextra "$here/native/terminal.c" -o "$resources/native/graff-terminal" -lutil+ chmod 755 "$resources/native/graff-terminal"+ bun "$here/build-icon.cjs" "$app/codegraff.png" 256+ cp "$here/linux/codegraff.sh" "$app/codegraff"+ chmod 755 "$app/codegraff"+ cat > "$app/codegraff.desktop" <<EOF+[Desktop Entry]+Type=Application+Name=$app_name+Exec=$app/codegraff %U+Icon=$app/codegraff.png+Terminal=false+Categories=Development;+StartupWMClass=codegraff+EOF+ for file in "$app/codegraff" "$app/codegraff.bin" "$resources/graff" "$resources/bun" "$resources/native/graff-terminal" "$resources/ui/server.js" "$resources/app/main.cjs" "$app/codegraff.png"; do+ if [[ ! -e "$file" ]]; then+ echo "Linux bundle is missing $file" >&2+ exit 1+ fi+ done+ if [[ -e "$resources/native/activity.node" ]]; then+ echo "Linux bundle must not include the macOS activity addon." >&2+ exit 1+ fi+ package_linux_deb "$app"+ if ! package_linux_appimage "$app"; then+ echo "AppImage tool unavailable; unpacked app and deb are ready." >&2+ fi+ echo "$app"+}++package_linux_deb() {+ local app="$1" arch+ case "$(uname -m)" in+ x86_64) arch=amd64 ;;+ aarch64|arm64) arch=arm64 ;;+ *) echo "No deb for $(uname -m)" >&2; return 0 ;;+ esac+ local stage="$out/deb-root"+ rm -rf "$stage"+ mkdir -p "$stage/DEBIAN" "$stage/opt" "$stage/usr/bin" "$stage/usr/share/applications" "$stage/usr/share/icons/hicolor/256x256/apps"+ cp -a "$app" "$stage/opt/codegraff"+ cat > "$stage/usr/share/applications/codegraff.desktop" <<EOF+[Desktop Entry]+Type=Application+Name=$app_name+Exec=/opt/codegraff/codegraff %U+Icon=codegraff+Terminal=false+Categories=Development;+StartupWMClass=codegraff+EOF+ cp "$app/codegraff.png" "$stage/usr/share/icons/hicolor/256x256/apps/codegraff.png"+ ln -s /opt/codegraff/codegraff "$stage/usr/bin/codegraff"+ cat > "$stage/DEBIAN/control" <<EOF+Package: codegraff+Version: ${version}+Section: devel+Priority: optional+Architecture: ${arch}+Maintainer: Codegraff <[email protected]>+Depends: libgtk-3-0 | libgtk-3-0t64, libnotify4, libnss3, libxss1, libxtst6, xdg-utils, libatspi2.0-0 | libatspi2.0-0t64, libuuid1, libsecret-1-0, libasound2 | libasound2t64, libgbm1+Description: Codegraff desktop+ Graphical client for the graff harness.+EOF+ cat > "$stage/DEBIAN/postinst" <<'EOF'+#!/bin/sh+set -e+helper=/opt/codegraff/chrome-sandbox+if [ -f "$helper" ]; then+ chown root:root "$helper" 2>/dev/null || true+ chmod 4755 "$helper" 2>/dev/null || true+fi+if command -v update-desktop-database >/dev/null 2>&1; then+ update-desktop-database /usr/share/applications >/dev/null 2>&1 || true+fi+exit 0+EOF+ chmod 755 "$stage/DEBIAN/postinst"+ dpkg-deb --root-owner-group --build "$stage" "$out/codegraff_${version}_${arch}.deb"+}++package_linux_appimage() {+ local app="$1" tool=""+ if command -v appimagetool >/dev/null 2>&1; then tool="$(command -v appimagetool)"+ elif [[ -n "${APPIMAGETOOL:-}" && -x "${APPIMAGETOOL}" ]]; then tool="$APPIMAGETOOL"+ else return 1+ fi+ local dir="$out/Codegraff.AppDir"+ rm -rf "$dir"+ mkdir -p "$dir"+ cp -a "$app/." "$dir/"+ cp "$dir/codegraff" "$dir/AppRun"+ chmod 755 "$dir/AppRun"+ cat > "$dir/codegraff.desktop" <<EOF+[Desktop Entry]+Type=Application+Name=$app_name+Exec=codegraff+Icon=codegraff+Categories=Development;+EOF+ cp "$app/codegraff.png" "$dir/codegraff.png"+ (cd "$out" && ARCH="$(uname -m)" "$tool" "$dir" "$out/codegraff-${version}-$(uname -m).AppImage")+}diff --git a/apps/native/electron/build.sh b/apps/native/electron/build.shold mode 100644new mode 100755index 09b3f77a..72b53e3b--- a/apps/native/electron/build.sh+++ b/apps/native/electron/build.sh@@ -25,6 +25,12 @@ elif [[ ! -x "$root/zig-out/bin/graff" ]]; thenecho "No built graff executable to reuse. Run without GRAFF_REUSE_ENGINE." >&2exit 1fi+if [[ "$(uname -s)" == "Linux" ]]; then+ # shellcheck disable=SC1091+ source "$here/build-linux.sh"+ stage_linux_app+ exit 0+fimkdir -p "$out"# This directory is an isolated build artifact, never the installed application.rm -rf "$bundle"diff --git a/apps/native/electron/cli-launcher.cjs b/apps/native/electron/cli-launcher.cjsindex f50711a1..d4365e50 100644--- a/apps/native/electron/cli-launcher.cjs+++ b/apps/native/electron/cli-launcher.cjs@@ -1,10 +1,37 @@const fs = require('node:fs/promises');const path = require('node:path');const marker = '# Codegraff GUI terminal launcher';+const desktopMarker = '# Codegraff GUI desktop entry';+const linuxMarker = 'Codegraff Linux desktop launcher';const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";+function bundleRoot(exe, platform = process.platform) {+ if (platform === 'darwin') return path.resolve(exe, '../../..');+ return path.dirname(exe);+}++function bundleExecutable(bundle) {+ const candidates = [+ path.join(bundle, 'Contents/MacOS/Codegraff'),+ path.join(bundle, 'codegraff.bin'),+ path.join(bundle, 'Codegraff.exe'),+ ];+ for (const file of candidates) {+ try { if (require('node:fs').statSync(file).isFile()) return file; } catch { /* try the next layout */ }+ }+ return candidates[0];+}++function launchCommand(bundle) {+ const wrapper = path.join(bundle, 'codegraff');+ try {+ if (require('node:fs').readFileSync(wrapper, 'utf8').includes(linuxMarker)) return wrapper;+ } catch { /* macOS bundles have no Linux wrapper */ }+ return bundleExecutable(bundle);+}+function launcherSource(bundle) {- const binary = path.join(bundle, 'Contents/MacOS/Codegraff');+ const binary = launchCommand(bundle);return `#!/bin/sh${marker}APP_BIN=${quote(binary)}@@ -33,8 +60,36 @@ nohup "\$APP_BIN" </dev/null >/dev/null 2>&1 &`;}+async function installDesktopEntry(home, command, bundle) {+ const applications = path.join(home, '.local/share/applications');+ const file = path.join(applications, 'codegraff.desktop');+ try {+ const previous = await fs.readFile(file, 'utf8');+ if (!previous.includes(desktopMarker)) throw Error('An unrelated codegraff desktop entry already exists.');+ } catch (error) { if (error.code !== 'ENOENT') throw error; }+ const icon = path.join(bundle, 'codegraff.png');+ let iconName = 'codegraff';+ try { await fs.access(icon); iconName = icon; } catch { /* theme icon name */ }+ const body = `${desktopMarker}+[Desktop Entry]+Type=Application+Name=Codegraff+Exec="${command.replaceAll('"', '\\"')}" %U+Icon=${iconName}+Terminal=false+Categories=Development;+StartupWMClass=codegraff+`;+ await fs.mkdir(applications, { recursive: true });+ await fs.writeFile(file, body, { mode: 0o644 });+ return file;+}+async function installLauncher(bundle, home) {- await fs.access(path.join(bundle, 'Contents/MacOS/Codegraff'), require('node:fs').constants.X_OK);+ const binary = bundleExecutable(bundle);+ await fs.access(binary, require('node:fs').constants.X_OK);+ const command = launchCommand(bundle);+ if (command !== binary) await fs.access(command, require('node:fs').constants.X_OK);const directory = path.join(home, '.local/bin'), file = path.join(directory, 'codegraff');await fs.mkdir(directory, { recursive: true });try {@@ -50,6 +105,7 @@ async function installLauncher(bundle, home) {await fs.writeFile(temporary, launcherSource(bundle), { mode: 0o755, flag: 'wx' });await fs.rename(temporary, file);} finally { await fs.rm(temporary, { force: true }); }+ if (command !== binary) await installDesktopEntry(home, command, bundle);return file;}-module.exports = { launcherSource, installLauncher };+module.exports = { launcherSource, installLauncher, bundleRoot, launchCommand };diff --git a/apps/native/electron/cli-launcher.test.cjs b/apps/native/electron/cli-launcher.test.cjsindex ebc98fc2..b08303e6 100644--- a/apps/native/electron/cli-launcher.test.cjs+++ b/apps/native/electron/cli-launcher.test.cjs@@ -28,3 +28,28 @@ test('terminal launcher passes literal folders/files and rejects invalid argumenexpect(fs.readFileSync(launcher, 'utf8')).toContain('echo custom');} finally { fs.rmSync(home, { recursive: true, force: true }); }});++test('linux launcher targets the sandbox wrapper and writes a desktop entry', async () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-cli-linux-'));+ try {+ const bundle = path.join(home, 'bundle'), capture = path.join(home, 'capture');+ fs.mkdirSync(bundle);+ fs.writeFileSync(path.join(bundle, 'codegraff.bin'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ fs.writeFileSync(path.join(bundle, 'codegraff'), '#!/bin/sh\n# Codegraff Linux desktop launcher\nexit 0\n', { mode: 0o755 });+ fs.writeFileSync(path.join(bundle, 'codegraff.png'), 'png');+ const launcher = await installLauncher(bundle, home);+ expect(fs.readFileSync(launcher, 'utf8')).toContain(path.join(bundle, 'codegraff'));+ expect(fs.readFileSync(launcher, 'utf8')).not.toContain('codegraff.bin');+ const desktop = fs.readFileSync(path.join(home, '.local/share/applications/codegraff.desktop'), 'utf8');+ expect(desktop).toContain('Codegraff GUI desktop entry');+ expect(desktop).toContain(path.join(bundle, 'codegraff.png'));+ fs.writeFileSync(path.join(bundle, 'codegraff.bin'), `#!/bin/sh\nprintf '%s\\n' "\${GRAFF_OPEN_PATH-unset}" > ${quote(capture)}\n`, { mode: 0o755 });+ fs.writeFileSync(path.join(bundle, 'codegraff'), `#!/bin/sh\n# Codegraff Linux desktop launcher\nexec ${quote(path.join(bundle, 'codegraff.bin'))} "$@"\n`, { mode: 0o755 });+ const folder = path.join(home, 'project');+ fs.mkdirSync(folder);+ expect(spawnSync('/bin/sh', [launcher, folder], { cwd: home, encoding: 'utf8', timeout: 2000 }).status).toBe(0);+ const end = Date.now() + 1500;+ while (!fs.existsSync(capture) && Date.now() < end) await Bun.sleep(10);+ expect(fs.readFileSync(capture, 'utf8').trim()).toBe(fs.realpathSync(folder));+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+});diff --git a/apps/native/electron/computer.cjs b/apps/native/electron/computer.cjsindex d0f755f0..d0f6f3c3 100644--- a/apps/native/electron/computer.cjs+++ b/apps/native/electron/computer.cjs@@ -10,6 +10,10 @@ class ComputerUse {return result;}async configure() {+ if (process.platform !== 'darwin') {+ await dialog.showMessageBox(this.window, { title: 'Computer use', type: 'info', buttons: ['OK'], message: 'Computer use is available on macOS.' });+ return this.status();+ }const status = this.native('permissions');const { response } = await dialog.showMessageBox(this.window, {title: 'Computer use', type: 'info', buttons: [this.enabled ? 'Disable computer use' : 'Enable computer use', 'Cancel'], cancelId: 1,@@ -22,7 +26,10 @@ class ComputerUse {}return this.status();}- status() { return { enabled: this.enabled, platform: process.platform, ...this.native('permissions') }; }+ status() {+ if (process.platform !== 'darwin') return { enabled: false, platform: process.platform, accessibility: false, screenRecording: false };+ return { enabled: this.enabled, platform: process.platform, ...this.native('permissions') };+ }async command(method, params = {}) {if (method === 'status') return this.status();if (!this.enabled) throw new Error('Enable Computer use from the Codegraff menu first. The agent cannot enable it.');diff --git a/apps/native/electron/linux-launch.test.cjs b/apps/native/electron/linux-launch.test.cjsnew file mode 100644index 00000000..39f3c372--- /dev/null+++ b/apps/native/electron/linux-launch.test.cjs@@ -0,0 +1,34 @@+const { test } = require('node:test');+const assert = require('node:assert/strict');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++function layout() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-linux-launch-'));+ const binDir = path.join(root, 'bin');+ fs.mkdirSync(binDir);+ const log = path.join(root, 'args');+ fs.copyFileSync(path.join(__dirname, 'linux/codegraff.sh'), path.join(root, 'codegraff'));+ fs.chmodSync(path.join(root, 'codegraff'), 0o755);+ fs.writeFileSync(path.join(root, 'codegraff.bin'), `#!/bin/sh\nprintf '%s\\n' "$@" > ${JSON.stringify(log)}\n`, { mode: 0o755 });+ return { root, binDir, log };+}++function run(root, binDir, status) {+ fs.writeFileSync(path.join(binDir, 'unshare'), `#!/bin/sh\nexit ${status}\n`, { mode: 0o755 });+ return spawnSync(path.join(root, 'codegraff'), ['--folder'], {+ encoding: 'utf8', env: { ...process.env, PATH: `${binDir}:/usr/bin:/bin` }, timeout: 2000,+ });+}++test('user namespaces keep the sandbox and a failed probe drops it', () => {+ const { root, binDir, log } = layout();+ try {+ assert.equal(run(root, binDir, 0).status, 0);+ assert.deepEqual(fs.readFileSync(log, 'utf8').trim().split('\n'), ['--class=codegraff', '--disable-setuid-sandbox', '--folder']);+ assert.equal(run(root, binDir, 1).status, 0);+ assert.deepEqual(fs.readFileSync(log, 'utf8').trim().split('\n'), ['--class=codegraff', '--no-sandbox', '--folder']);+ } finally { fs.rmSync(root, { recursive: true, force: true }); }+});diff --git a/apps/native/electron/linux/codegraff.sh b/apps/native/electron/linux/codegraff.shnew file mode 100755index 00000000..a2a2b27d--- /dev/null+++ b/apps/native/electron/linux/codegraff.sh@@ -0,0 +1,25 @@+#!/bin/sh+# Codegraff Linux desktop launcher+# Starts the bundled Electron binary. A setuid chrome-sandbox or a working+# user namespace keeps the Chromium sandbox; otherwise the app still opens.+set -eu+here=$(CDPATH= cd -- "$(dirname "$0")" && pwd)+bin="$here/codegraff.bin"+if [ ! -x "$bin" ]; then+ echo "Codegraff executable is missing. Reinstall the app." >&2+ exit 1+fi+sandboxed=0+namespace=0+if [ -u "$here/chrome-sandbox" ]; then+ sandboxed=1+elif command -v unshare >/dev/null 2>&1 && unshare --user true >/dev/null 2>&1; then+ namespace=1+fi+if [ "$sandboxed" -eq 1 ]; then+ exec "$bin" --class=codegraff "$@"+fi+if [ "$namespace" -eq 1 ]; then+ exec "$bin" --class=codegraff --disable-setuid-sandbox "$@"+fi+exec "$bin" --class=codegraff --no-sandbox "$@"diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjsindex ae57a1d3..14967139 100644--- a/apps/native/electron/main.cjs+++ b/apps/native/electron/main.cjs@@ -90,7 +90,9 @@ app.whenReady().then(async () => {void require('./mcp-install.cjs').installMcp(binary, home, { once: true, version: app.getVersion() }).catch(error => dialog.showErrorBox('MCP setup incomplete', `${error.message}\nRetry from Tools → Configure MCP clients.`));void require('./engine-launcher.cjs').installEngine(binary, home, {- extraBin: ['/opt/homebrew/bin', '/usr/local/bin', path.join(home, 'bin')],+ extraBin: process.platform === 'darwin'+ ? ['/opt/homebrew/bin', '/usr/local/bin', path.join(home, 'bin')]+ : [path.join(home, 'bin')],}).then(() => {const dir = path.join(home, '.local/bin');const parts = (process.env.PATH || '').split(':').filter(Boolean);@@ -102,9 +104,7 @@ app.whenReady().then(async () => {const token = randomBytes(32).toString('hex');const liveGlass = process.platform === 'darwin' && !testDesktop;let glassOn = false;- win = createWindow({ width: 1440, height: 920, minWidth: 900, minHeight: 600,- title: appName, titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 14, y: 11 },- transparent: liveGlass, backgroundColor: liveGlass ? '#00000000' : '#fafaf9', show: false,+ win = createWindow({ ...require('./window-chrome.cjs').mainWindowChrome({ liveGlass, title: appName }),webPreferences: { preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:app',contextIsolation: true, sandbox: true, nodeIntegration: false, backgroundThrottling: !process.env.GRAFF_ELECTRON_SMOKE } });const projects = require('./project-store.cjs').projectStore(app.getPath('userData'));@@ -242,7 +242,7 @@ app.whenReady().then(async () => {win.on('restore', () => win.webContents.send('browser-event', { type: 'layout' }));const updateMenu = require('./updates.cjs').installUpdates({ app, win, ipcMain, trusted, resources });Menu.setApplicationMenu(Menu.buildFromTemplate([- { label: appName, submenu: [{ role: 'about' }, ...updateMenu, { type: 'separator' }, { label: 'Activity…', accelerator: 'CmdOrCtrl+,', click: () => void activity().catch(error => dialog.showErrorBox('Activity', error.message)) }, { label: 'Computer use…', click: () => void computer.configure().catch(error => dialog.showErrorBox('Computer use', error.message)) }, { type: 'separator' }, { role: 'quit' }] },+ { label: appName, submenu: [{ role: 'about' }, ...updateMenu, { type: 'separator' }, { label: 'Activity…', accelerator: 'CmdOrCtrl+,', click: () => void activity().catch(error => dialog.showErrorBox('Activity', error.message)) }, { label: 'Computer use…', visible: process.platform === 'darwin', click: () => void computer.configure().catch(error => dialog.showErrorBox('Computer use', error.message)) }, { type: 'separator' }, { role: 'quit' }] },{ label: 'File', submenu: [['New chat', 'CmdOrCtrl+N', 'new'], ['New tab', 'CmdOrCtrl+T', 'new'],['Close chat', 'CmdOrCtrl+W', 'close'], ['Reopen closed chat', 'CmdOrCtrl+Shift+T', 'reopen'],@@ -254,12 +254,15 @@ app.whenReady().then(async () => {const detail = await require('./mcp-install.cjs').installMcp(path.join(resources, 'graff'), app.getPath('home'));await dialog.showMessageBox(win, { message: 'MCP clients configured', detail });} catch (error) { dialog.showErrorBox('MCP setup', error.message); }- } }, { label: 'Install codegraff terminal command…', enabled: app.isPackaged && process.platform === 'darwin', click: async () => {+ } }, { label: 'Install codegraff terminal command…', enabled: app.isPackaged && (process.platform === 'darwin' || process.platform === 'linux'), click: async () => {try {await require('./engine-launcher.cjs').installEngine(path.join(resources, 'graff'), app.getPath('home'), {- extraBin: ['/opt/homebrew/bin', '/usr/local/bin', path.join(app.getPath('home'), 'bin')],+ extraBin: process.platform === 'darwin'+ ? ['/opt/homebrew/bin', '/usr/local/bin', path.join(app.getPath('home'), 'bin')]+ : [path.join(app.getPath('home'), 'bin')],});- const installed = await require('./cli-launcher.cjs').installLauncher(path.resolve(app.getPath('exe'), '../../..'), app.getPath('home'));+ const launch = require('./cli-launcher.cjs');+ const installed = await launch.installLauncher(launch.bundleRoot(app.getPath('exe')), app.getPath('home'));await dialog.showMessageBox(win, { message: 'Terminal command installed', detail: `Run graff for the CLI or codegraff . for the GUI. Open a new terminal to load the PATH update (${path.dirname(installed)}).` });} catch (error) { dialog.showErrorBox('Terminal command', error.message); }} }, { label: 'Browser passkey help…', click: () => void require('./webauthn.cjs').showPasskeyHelp({@@ -278,7 +281,8 @@ app.whenReady().then(async () => {] },{ role: 'windowMenu' },]));- await win.loadURL(backend.origin); win.setWindowButtonVisibility(true);+ await win.loadURL(backend.origin);+ require('./window-chrome.cjs').revealWindowButtons(win);if (process.platform === 'darwin') {try {const native = require(path.join(resources, 'native/activity.node'));diff --git a/apps/native/electron/native/terminal.c b/apps/native/electron/native/terminal.cindex 00b2cbc0..cadce687 100644--- a/apps/native/electron/native/terminal.c+++ b/apps/native/electron/native/terminal.c@@ -1,6 +1,10 @@// Small macOS PTY bridge. stdin: opcode + little-endian uint32 size + payload.// Input opcode 0; resize opcode 1 with little-endian uint16 columns, rows.+#if defined(__APPLE__)#include <util.h>+#else+#include <pty.h>+#endif#include <sys/ioctl.h>#include <sys/wait.h>#include <poll.h>diff --git a/apps/native/electron/preload.cjs b/apps/native/electron/preload.cjsindex 0b10fffa..c5c33a36 100644--- a/apps/native/electron/preload.cjs+++ b/apps/native/electron/preload.cjs@@ -1,5 +1,7 @@const { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('graffDesktop', {+ frame: process.platform === 'darwin' ? 'inset' : 'system',+ platform: process.platform,workspaceSubscribe: callback => {const listener = (_event, target) => callback(target);ipcRenderer.on('workspace-open', listener);diff --git a/apps/native/electron/project-store.cjs b/apps/native/electron/project-store.cjsindex 9a319bbb..16e3a249 100644--- a/apps/native/electron/project-store.cjs+++ b/apps/native/electron/project-store.cjs@@ -1,9 +1,10 @@const fs = require('node:fs/promises');const path = require('node:path');+const { isWorkspacePath } = require('./workspace-path.cjs');function validate(value) {if (!value || !Array.isArray(value.list) || value.list.length > 50) throw Error('Invalid project list');const list = value.list.map(row => {- if (!row || typeof row.path !== 'string' || !path.isAbsolute(row.path) || row.path.length > 4096 || typeof row.name !== 'string' || row.name.length > 512) throw Error('Invalid project');+ if (!row || !isWorkspacePath(row.path) || typeof row.name !== 'string' || row.name.length > 512) throw Error('Invalid project');return { path: row.path, name: row.name, ...(typeof row.model === 'string' ? { model: row.model.slice(0, 256) } : {}),...(typeof row.yolo === 'boolean' ? { yolo: row.yolo } : {}), ...(typeof row.mcp === 'boolean' ? { mcp: row.mcp } : {}) };});diff --git a/apps/native/electron/project-store.test.cjs b/apps/native/electron/project-store.test.cjsindex a33ffe85..7796fcf1 100644--- a/apps/native/electron/project-store.test.cjs+++ b/apps/native/electron/project-store.test.cjs@@ -10,5 +10,12 @@ test('project choices survive a new process/store and preserve the latest selectawait Promise.all([store.save({ list, active: list[0].path }), store.save({ list, active: list[1].path })]);expect(await projectStore(root).load()).toEqual({ list, active: '/projects/two' });expect(() => store.save({ list: [{ path: '../escape', name: 'bad' }] })).toThrow('Invalid project');+ const xdg = path.join(root, '.config', 'Codegraff Electron');+ const portable = projectStore(xdg);+ const windows = [{ path: 'C:\\Users\\graff\\src', name: 'drive' }, { path: '\\\\server\\share\\repo', name: 'unc' }];+ await portable.save({ list: windows, active: windows[0].path });+ expect(await projectStore(xdg).load()).toEqual({ list: windows, active: windows[0].path });+ const mode = (await fs.stat(path.join(xdg, 'projects.json'))).mode & 0o777;+ expect(mode).toBe(0o600);} finally { await fs.rm(root, { recursive: true }); }});diff --git a/apps/native/electron/smoke-launch.cjs b/apps/native/electron/smoke-launch.cjsindex 5d4a5f5e..2f71027a 100644--- a/apps/native/electron/smoke-launch.cjs+++ b/apps/native/electron/smoke-launch.cjs@@ -20,14 +20,22 @@ async function run({ win, backend, browser, token }) {const { app } = require('electron');assert.equal(app.isPackaged, true, 'Packaged launch must report isPackaged');assert.notEqual(path.basename(process.execPath), 'Electron', 'Packaged executable must not keep the development name');+ assert.notEqual(path.basename(process.execPath).toLowerCase(), 'electron', 'Packaged executable must not keep the development name');const resources = process.env.GRAFF_ELECTRON_RESOURCES || process.resourcesPath;- const native = require(path.join(resources, 'native/activity.node'));- assert.equal(typeof native.show, 'function');+ let nativeCheck = 'macOS native extras omitted';+ if (process.platform === 'darwin') {+ const native = require(path.join(resources, 'native/activity.node'));+ assert.equal(typeof native.show, 'function');+ nativeCheck = 'native module ABI';+ } else {+ assert.equal(fs.existsSync(path.join(resources, 'native/activity.node')), false);+ assert.equal(fs.existsSync(path.join(resources, 'native/graff-terminal')), true);+ }const version = execFileSync(path.join(resources, 'graff'), ['--version'], { encoding: 'utf8', timeout: 10000 }).trim().split('\n')[0];assert.match(version, /graff/i);if (process.env.GRAFF_SMOKE_HTML_TOOL) await require('./smoke-html.cjs').run({ win, backend, token });if (process.env.GRAFF_SMOKE_TITLES) await require('./smoke-titles.cjs').run({ win, backend });- const report = { appVersion: app.getVersion(), passed: ['bundled server', 'production composer', 'empty browser lifecycle', 'request authentication', 'native module ABI', 'bundled engine executable', 'packaged executable'], version };+ const report = { appVersion: app.getVersion(), passed: ['bundled server', 'production composer', 'empty browser lifecycle', 'request authentication', nativeCheck, 'bundled engine executable', 'packaged executable'], version };if (process.env.GRAFF_SMOKE_WEBAUTHN) report.passed.push(await require('./smoke-webauthn.cjs').run({ browser, backend, resources }));fs.writeFileSync(process.env.GRAFF_ELECTRON_SMOKE, JSON.stringify(report, null, 2));console.log(process.env.GRAFF_SMOKE_TITLES ? 'Packaged title checks passed.' : process.env.GRAFF_SMOKE_HTML_TOOL ? 'Packaged launch and offline HTML tool checks passed.' : 'Packaged launch checks passed. No prompt sent or coding setting changed.');diff --git a/apps/native/electron/terminal.cjs b/apps/native/electron/terminal.cjsindex 211313bf..668c2b9c 100644--- a/apps/native/electron/terminal.cjs+++ b/apps/native/electron/terminal.cjs@@ -2,12 +2,18 @@ const {spawn}=require('node:child_process');const {realpathSync,statSync}=require('node:fs');const {StringDecoder}=require('node:string_decoder');const os=require('node:os');+const {isWorkspacePath}=require('./workspace-path.cjs');const LIMIT=128*1024;+function loginShell(){+ if(process.env.SHELL)return process.env.SHELL;+ try{if(os.userInfo().shell)return os.userInfo().shell;}catch{}+ return process.platform==='darwin'?'/bin/zsh':'/bin/bash';+}function frame(kind,payload){const header=Buffer.alloc(5);header[0]=kind;header.writeUInt32LE(payload.length,1);return Buffer.concat([header,payload]);}class Terminals {- constructor(binary,emit,options={}){this.binary=binary;this.emit=emit;this.shell=options.shell||os.userInfo().shell||'/bin/zsh';this.sessions=new Map();}+ constructor(binary,emit,options={}){this.binary=binary;this.emit=emit;this.shell=options.shell||loginShell();this.sessions=new Map();}open(cwd){- if(typeof cwd!=='string'||!cwd.startsWith('/')||cwd.includes('\0'))throw Error('Choose a workspace folder first.');+ if(!isWorkspacePath(cwd))throw Error('Choose a workspace folder first.');const id=realpathSync(cwd);if(!statSync(id).isDirectory())throw Error('Workspace is not a folder.');let slot=this.sessions.get(id);if(!slot){diff --git a/apps/native/electron/terminal.test.cjs b/apps/native/electron/terminal.test.cjsindex 75cf1384..6320707c 100644--- a/apps/native/electron/terminal.test.cjs+++ b/apps/native/electron/terminal.test.cjs@@ -2,13 +2,16 @@ const {test,after}=require('node:test');const assert=require('node:assert/strict');const {execFileSync}=require('node:child_process');const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const {Terminals,frame}=require('./terminal.cjs');const temp=fs.mkdtempSync(path.join(os.tmpdir(),'graff-pty-test-')),binary=path.join(temp,'pty');-if(process.platform==='darwin')execFileSync('xcrun',['clang','-O2',path.join(__dirname,'native/terminal.c'),'-o',binary]);+const source=path.join(__dirname,'native/terminal.c');+if(process.platform==='darwin')execFileSync('xcrun',['clang','-O2',source,'-o',binary]);+else if(process.platform==='linux')execFileSync('cc',['-O2','-Wall',source,'-o',binary,'-lutil']);+const pty=process.platform==='darwin'||process.platform==='linux';after(()=>fs.rmSync(temp,{recursive:true,force:true}));const wait=async condition=>{for(let i=0;i<200;i++){if(condition())return;await new Promise(r=>setTimeout(r,20));}throw Error('PTY timed out');};test('PTY frames preserve input bytes and resize dimensions',()=>{const value=frame(0,Buffer.from('hello\r'));assert.equal(value.readUInt32LE(1),6);assert.equal(value.subarray(5).toString(),'hello\r');});-test('real workspace PTY supports input, resize, interrupt, hide and cleanup',{skip:process.platform!=='darwin'},async()=>{+test('real workspace PTY supports input, resize, interrupt, hide and cleanup',{skip:!pty},async()=>{const cwd=path.join(temp,'folder with spaces');fs.mkdirSync(cwd);let output='';const manager=new Terminals(binary,event=>{if(event.data){output+=event.data;manager.command('ack',{id:event.id,length:event.data.length});}},{shell:'/bin/sh'});try {@@ -29,7 +32,7 @@ test('terminal rejects a file as a workspace and starts no shell',()=>{assert.throws(()=>manager.open(file),/folder/);assert.equal(manager.sessions.size,0);});-test('ending a noisy terminal releases a helper blocked by renderer backpressure',{skip:process.platform!=='darwin'},async()=>{+test('ending a noisy terminal releases a helper blocked by renderer backpressure',{skip:!pty},async()=>{const manager=new Terminals(binary,()=>{},{shell:'/bin/sh'});try {const {id}=manager.open(temp),slot=manager.sessions.get(id);diff --git a/apps/native/electron/window-chrome.cjs b/apps/native/electron/window-chrome.cjsnew file mode 100644index 00000000..80cd1163--- /dev/null+++ b/apps/native/electron/window-chrome.cjs@@ -0,0 +1,19 @@+function mainWindowChrome({ platform = process.platform, liveGlass = false, title = 'Codegraff' } = {}) {+ const base = { width: 1440, height: 920, minWidth: 900, minHeight: 600, title, show: false };+ if (platform === 'darwin') {+ return {+ ...base,+ titleBarStyle: 'hiddenInset',+ trafficLightPosition: { x: 14, y: 11 },+ transparent: liveGlass,+ backgroundColor: liveGlass ? '#00000000' : '#fafaf9',+ };+ }+ return { ...base, backgroundColor: '#fafaf9' };+}++function revealWindowButtons(win, platform = process.platform) {+ if (platform === 'darwin') win.setWindowButtonVisibility(true);+}++module.exports = { mainWindowChrome, revealWindowButtons };diff --git a/apps/native/electron/window-chrome.test.cjs b/apps/native/electron/window-chrome.test.cjsnew file mode 100644index 00000000..a90014c9--- /dev/null+++ b/apps/native/electron/window-chrome.test.cjs@@ -0,0 +1,30 @@+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { mainWindowChrome, revealWindowButtons } = require('./window-chrome.cjs');++test('macOS keeps the inset titlebar and Linux uses system decorations', () => {+ const mac = mainWindowChrome({ platform: 'darwin', liveGlass: true, title: 'Codegraff' });+ assert.equal(mac.titleBarStyle, 'hiddenInset');+ assert.equal(mac.transparent, true);+ assert.deepEqual(mac.trafficLightPosition, { x: 14, y: 11 });+ const linux = mainWindowChrome({ platform: 'linux', liveGlass: true, title: 'Codegraff' });+ assert.equal(linux.titleBarStyle, undefined);+ assert.equal(linux.transparent, undefined);+ assert.equal(linux.trafficLightPosition, undefined);+ assert.equal(linux.backgroundColor, '#fafaf9');+ const calls = [];+ revealWindowButtons({ setWindowButtonVisibility: () => calls.push('shown') }, 'linux');+ assert.deepEqual(calls, []);+ revealWindowButtons({ setWindowButtonVisibility: () => calls.push('shown') }, 'darwin');+ assert.deepEqual(calls, ['shown']);+});++test('the main process does not call the macOS window-button API on its own', () => {+ const source = fs.readFileSync(path.join(__dirname, 'main.cjs'), 'utf8');+ assert.match(source, /revealWindowButtons/);+ assert.equal(source.includes('setWindowButtonVisibility'), false);+ assert.match(source, /visible: process\.platform === 'darwin'/);+ assert.match(source, /process\.platform === 'linux'/);+});diff --git a/apps/native/electron/workspace-path.cjs b/apps/native/electron/workspace-path.cjsnew file mode 100644index 00000000..f13fd329--- /dev/null+++ b/apps/native/electron/workspace-path.cjs@@ -0,0 +1,8 @@+const path = require('node:path');++function isWorkspacePath(value) {+ return typeof value === 'string' && value.length > 0 && value.length <= 4096 && !value.includes('\0') &&+ (path.win32.isAbsolute(value) || path.posix.isAbsolute(value));+}++module.exports = { isWorkspacePath };diff --git a/apps/native/electron/workspace-path.test.cjs b/apps/native/electron/workspace-path.test.cjsnew file mode 100644index 00000000..1c6c6756--- /dev/null+++ b/apps/native/electron/workspace-path.test.cjs@@ -0,0 +1,10 @@+const { test } = require('node:test');+const assert = require('node:assert/strict');+const { isWorkspacePath } = require('./workspace-path.cjs');++test('workspace paths accept Linux, XDG, drive-letter, and UNC forms', () => {+ for (const value of ['/home/user/src', '/home/user/.config/Codegraff Electron', 'C:\\Users\\graff\\src', '\\\\server\\share\\repo']) {+ assert.equal(isWorkspacePath(value), true, value);+ }+ for (const value of ['', 'relative/src', '../escape', 'C:relative', 'has\0nul']) assert.equal(isWorkspacePath(value), false);+});diff --git a/apps/native/lib/desktop.ts b/apps/native/lib/desktop.tsindex b5d35b8e..097d0589 100644--- a/apps/native/lib/desktop.ts+++ b/apps/native/lib/desktop.ts@@ -6,6 +6,8 @@ export type LinkDestination = 'system' | 'graff';export type TerminalEvent = { id: string; seq: number; data?: string; exit?: number };export type UpdateState = { status: 'idle' | 'unavailable' | 'checking' | 'current' | 'downloading' | 'ready' | 'installing' | 'error'; currentVersion: string; version?: string; percent?: number; automatic: boolean; interactive: boolean; message?: string };export type DesktopBridge = {+ frame?: "inset" | "system";+ platform?: string;workspaceSubscribe?(callback: (target: { cwd: string; file?: string }) => void): () => void;linkSettings?(action: 'load' | 'save', value?: LinkDestination): Promise<LinkDestination>;projects?(action: 'load' | 'save', value?: { list: import('./workspaces').Workspace[]; active: string | null }): Promise<{ list: import('./workspaces').Workspace[]; active: string | null } | null | void>;diff --git a/apps/native/lib/host-open.test.ts b/apps/native/lib/host-open.test.tsnew file mode 100644index 00000000..8c55f2d1--- /dev/null+++ b/apps/native/lib/host-open.test.ts@@ -0,0 +1,12 @@+import assert from "node:assert/strict";+import test from "node:test";+import { hostOpenCommand } from "./host-open.ts";++test("open and reveal use the host file manager", () => {+ assert.deepEqual(hostOpenCommand("open", "/src/app.ts", "darwin"), { bin: "open", args: ["/src/app.ts"] });+ assert.deepEqual(hostOpenCommand("reveal", "/src/app.ts", "darwin"), { bin: "open", args: ["-R", "/src/app.ts"] });+ assert.deepEqual(hostOpenCommand("open", "/src/app.ts", "linux"), { bin: "xdg-open", args: ["/src/app.ts"] });+ assert.deepEqual(hostOpenCommand("reveal", "/src/app.ts", "linux"), { bin: "xdg-open", args: ["/src"] });+ assert.equal(hostOpenCommand("open", "C:\\src\\app.ts", "win32"), null);+ assert.equal(hostOpenCommand("rename", "/src/app.ts", "linux"), null);+});diff --git a/apps/native/lib/host-open.ts b/apps/native/lib/host-open.tsnew file mode 100644index 00000000..7773b202--- /dev/null+++ b/apps/native/lib/host-open.ts@@ -0,0 +1,8 @@+import path from "node:path";++export function hostOpenCommand(action: string, target: string, platform = process.platform): { bin: string; args: string[] } | null {+ if (action !== "open" && action !== "reveal") return null;+ if (platform === "darwin") return { bin: "open", args: action === "reveal" ? ["-R", target] : [target] };+ if (platform === "linux") return { bin: "xdg-open", args: [action === "reveal" ? path.dirname(target) : target] };+ return null;+}diff --git a/apps/native/lib/shortcut-glyph.test.ts b/apps/native/lib/shortcut-glyph.test.tsnew file mode 100644index 00000000..97fda86c--- /dev/null+++ b/apps/native/lib/shortcut-glyph.test.ts@@ -0,0 +1,10 @@+import assert from "node:assert/strict";+import test from "node:test";+import { commandGlyph } from "./shortcut-glyph.ts";++test("shortcut labels use Command on macOS and Ctrl elsewhere", () => {+ assert.equal(commandGlyph("MacIntel"), "⌘");+ assert.equal(commandGlyph("iPhone"), "⌘");+ assert.equal(commandGlyph("Linux x86_64"), "Ctrl+");+ assert.equal(commandGlyph("Win32"), "Ctrl+");+});diff --git a/apps/native/lib/shortcut-glyph.ts b/apps/native/lib/shortcut-glyph.tsnew file mode 100644index 00000000..4297daa0--- /dev/null+++ b/apps/native/lib/shortcut-glyph.ts@@ -0,0 +1,12 @@+"use client";+import { useEffect, useState } from "react";++export function commandGlyph(platform = typeof navigator === "undefined" ? "" : navigator.platform): string {+ return /Mac|iPhone|iPad/.test(platform) ? "⌘" : "Ctrl+";+}++export function useCommandGlyph(): string {+ const [glyph, setGlyph] = useState("⌘");+ useEffect(() => { setGlyph(commandGlyph()); }, []);+ return glyph;+}diff --git a/docs/adr/0156-linux-desktop-sandbox-fallback.md b/docs/adr/0156-linux-desktop-sandbox-fallback.mdnew file mode 100644index 00000000..94a276a1--- /dev/null+++ b/docs/adr/0156-linux-desktop-sandbox-fallback.md@@ -0,0 +1,27 @@+# 0156. Linux desktop uses system chrome and a sandbox fallback++Status: accepted 2026-09-21++## Context++The packaged desktop copied `Electron.app`, called+`setWindowButtonVisibility`, and compiled only the Darwin PTY helper. That+path cannot start on Linux. Chromium's sandbox also aborts when+`chrome-sandbox` is not setuid and user namespaces are blocked, which is the+usual case for an unpacked tree before a deb install.++## Decision++- Linux packages are an unpacked directory, a `.deb`, and an AppImage when+ `appimagetool` is on `PATH`. The macOS `.app` build is unchanged.+- The window uses system decorations. The inset titlebar and traffic lights+ stay on Darwin.+- `codegraff` execs `codegraff.bin` with the setuid helper when `chrome-sandbox` is mode 4755. Otherwise it uses a user namespace (`--disable-setuid-sandbox`) when `unshare --user` works, and `--no-sandbox` when it does not. The deb `postinst` sets the helper setuid.+- The workspace terminal is the POSIX PTY helper and `$SHELL`. macOS-only+ activity, glass, and computer use stay unloaded.++## Consequences++An unpacked Linux build opens without a root step. A deb install can turn+the sandbox helper setuid. Signing the packages is still a separate release+step.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex fef80de6..76241147 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -177,6 +177,7 @@ record only when you need the evidence or the edge cases.| [0153](0153-task-workspaces-copy-and-scripts.md) | Task workspaces copy gitignored include files from the main checkout and run setup/run/archive scripts from `.graff/workspace.toml`. Finish is still not archive. || [0154](0154-parked-shells-yield-the-parent.md) | Interactive parked shells yield the parent like subagents: 15s foreground wait, then the prompt is yours until the job-exit wake. || [0155](0155-resume-reenters-saved-worktree.md) | Resume of a linked-worktree save re-enters that tree; `$HOME` origin stays history-only. |+| [0156](0156-linux-desktop-sandbox-fallback.md) | Linux desktop uses system window decorations, a POSIX terminal, and a sandbox fallback when user namespaces or the setuid helper are unavailable. |## When to write onediff --git a/scripts/build_and_run.sh b/scripts/build_and_run.shindex 70f9ca3a..ad2477a8 100755--- a/scripts/build_and_run.sh+++ b/scripts/build_and_run.sh@@ -1,6 +1,10 @@#!/usr/bin/env bashset -euo pipefailroot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+if [[ "$(uname -s)" == "Linux" ]]; then+ GRAFF_DEV=1 bash "$root/apps/native/electron/build.sh"+ exec "$root/zig-out/electron-dev/codegraff/codegraff"+fiapp="$root/zig-out/electron-dev/Codegraff Dev.app"# Only stop this checkout's dev bundle, never the installed desktop.while IFS= read -r pid; do