Skip to content

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

Python

Desktop: optional interface sounds, with cuelume notices

justrachb19122c4a916
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77038d41..1f886c8f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,9 @@ current is part of cutting a release.
## v0.0.302.4
- A background command that exits resumes the same session with its exit status and output, instead of waiting for another message (#1154).
+- Desktop interface sounds are optional and off until turned on. Cuelume notices ship with the app bundle.
+- Desktop task workspaces get their own Git checkouts, with a keep gate so dirty or unique trees are not dropped.
+- OpenAI Platform prompt-cache breakpoints cover GPT-5.6 and later. Platform GPT-6 can use the Responses WebSocket. Resume restores the saved prompt-cache key.
- Composer send/stop stays a circle: more inset so the 32px corner no longer clips it into a square (#1152).
- New chat stays in the folder already open, on the desktop and through ACP. Worktrees and other GUI workspace changes have to match the ACP session; that rule is in AGENTS.md and docs/notices.
- GUI transcript drag-selection paints, and each message has a copy icon at the bottom.
diff --git a/apps/native/ATTRIBUTION.md b/apps/native/ATTRIBUTION.md
index 3b383761..376114e7 100644
--- a/apps/native/ATTRIBUTION.md
+++ b/apps/native/ATTRIBUTION.md
@@ -19,3 +19,12 @@ Native window pattern from https://github.com/justrach/merjs
merjs is not vendored as a web framework here. The UI is Next.js so the
React primitives can be used as-is. The Zig file in `desktop/` is the
WKWebView shell only.
+
+## Cuelume
+
+Interface sounds use the `cuelume` package (MIT) by Daniel Belyi, synthesized
+in the page. Off until the user turns them on. License:
+`third-party/cuelume/LICENSE`. Also listed in `THIRD_PARTY_NOTICES.md`.
+
+https://github.com/Danilaa1/cuelume
+
diff --git a/apps/native/README.md b/apps/native/README.md
index 3d49fb5f..3e27df72 100644
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@ -23,13 +23,16 @@ Copied from Beautiful UI:
Dropped:
- **posthog** / `instrumentation-client.ts` / email capture
-- **cuelume** interaction sounds
- **dialkit** tuning overlay
- **`@central-icons-react`** — commercial; `CENTRAL_LICENSE_KEY` is not set
here, so SidebarNav uses the free stroke set in `lib/icons.tsx`
- Ice-cream `SCENARIOS` / `matchScenario` demo data
-Kept (free): `tailwindcss` v4, `shadow-plugin`, `iconoir-react`, `liveline`.
+Kept (free): `tailwindcss` v4, `shadow-plugin`, `iconoir-react`, `liveline`,
+and optional [cuelume](https://github.com/Danilaa1/cuelume) interface sounds
+(MIT, off by default). See `THIRD_PARTY_NOTICES.md` and
+`third-party/cuelume/`.
+
The prompt-bar feedback uses a short native browser animation; it does not
allocate a shader canvas.
diff --git a/apps/native/THIRD_PARTY_NOTICES.md b/apps/native/THIRD_PARTY_NOTICES.md
new file mode 100644
index 00000000..a12a9153
--- /dev/null
+++ b/apps/native/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,52 @@
+# Third-party notices
+
+The desktop app includes material from the projects below. Full license
+texts travel with the source and are copied into the app bundle.
+
+## cuelume
+
+Interface sounds use the `cuelume` package (MIT) by Daniel Belyi. Sounds are
+synthesized in the page; they are off until the user turns them on. The
+license is also in `third-party/cuelume/LICENSE`.
+
+https://github.com/Danilaa1/cuelume
+
+MIT License
+
+Copyright (c) 2026 Daniel Belyi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## Beautiful UI
+
+Copied primitives and tokens (MIT). See `LICENSE.beautiful-ui`.
+
+https://github.com/slev12397/beautiful-ui
+
+## merjs
+
+Native window pattern (MIT). See `LICENSE.merjs`. merjs is not vendored as a
+web framework here.
+
+https://github.com/justrach/merjs
+
+## Google Sans Code
+
+The bundled face in `app/fonts/` is under the SIL Open Font License. See
+`app/fonts/OFL.txt`.
diff --git a/apps/native/bun.lock b/apps/native/bun.lock
index 6331b642..eeef025a 100644
--- a/apps/native/bun.lock
+++ b/apps/native/bun.lock
@@ -9,6 +9,7 @@
"@streamdown/mermaid": "^1.0.2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+ "cuelume": "^0.2.2",
"electron-updater": "6.8.9",
"geist": "^1.7.2",
"glimm": "^0.3.0",
@@ -323,6 +324,8 @@
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+ "cuelume": ["[email protected]", "", {}, "sha512-TiNzJRjhddjC4jy4M7sv63V/86VaFhdIs6iHUCrc4CKhqypaxRBv1aedCBGebrz/cO7nroPkEfqHe/P7fOE2GQ=="],
+
"cytoscape": ["[email protected]", "", {}, "sha512-yfYGhRcGAntq6YBD583j4n0Eg3jIxvWmZtz/5uz9UYkeIStSlMxuUja+ec5j3iBD8nv1rwaOAYMW09tBdkSeaQ=="],
"cytoscape-cose-bilkent": ["[email protected]", "", { "dependencies": { "cose-base": "^1.0.0" }, "peerDependencies": { "cytoscape": "^3.2.0" } }, "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ=="],
diff --git a/apps/native/components/atoms/SegmentedControl.tsx b/apps/native/components/atoms/SegmentedControl.tsx
index b70a03da..1982cb53 100644
--- a/apps/native/components/atoms/SegmentedControl.tsx
+++ b/apps/native/components/atoms/SegmentedControl.tsx
@@ -1,4 +1,5 @@
"use client";
+import { playUiSound } from "@/lib/ui-sounds";
/** Segmented control — equal-width segments, sliding thumb. */
export function SegmentedControl<T extends string>({
@@ -35,7 +36,7 @@ export function SegmentedControl<T extends string>({
key={opt}
role="tab"
aria-selected={opt === value}
- onClick={() => onChange(opt)}
+ onClick={() => { if (opt === value) return; onChange(opt); playUiSound("toggle"); }}
className={`relative z-10 rounded-full px-3 text-[13px] font-medium
transition-colors duration-150
${opt === value ? "text-ink" : "text-ink-3 hover:text-ink-2"}`}
diff --git a/apps/native/components/atoms/Switch.tsx b/apps/native/components/atoms/Switch.tsx
index c847e3c1..7c8af0a4 100644
--- a/apps/native/components/atoms/Switch.tsx
+++ b/apps/native/components/atoms/Switch.tsx
@@ -1,13 +1,16 @@
"use client";
+import { playUiSound } from "@/lib/ui-sounds";
export function Switch({
checked,
onChange,
label,
+ disabled = false,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label?: string;
+ disabled?: boolean;
}) {
return (
<button
@@ -15,8 +18,9 @@ export function Switch({
role="switch"
aria-checked={checked}
aria-label={label}
- onClick={() => onChange(!checked)}
- className={`relative h-6 w-10 shrink-0 rounded-full transition-colors duration-200
+ disabled={disabled}
+ onClick={() => { onChange(!checked); playUiSound("toggle"); }}
+ className={`relative h-6 w-10 shrink-0 rounded-full transition-colors duration-200 disabled:cursor-not-allowed disabled:opacity-40
${checked ? "bg-ink" : "bg-line-strong"}`}
>
<span
diff --git a/apps/native/components/primitives/CodeBlock.tsx b/apps/native/components/primitives/CodeBlock.tsx
index 3d9503e5..a5331528 100644
--- a/apps/native/components/primitives/CodeBlock.tsx
+++ b/apps/native/components/primitives/CodeBlock.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useState } from "react";
+import { copyText } from "@/lib/ui-sounds";
/* ─────────────────────────────────────────────────────────
* CODE BLOCK
@@ -49,10 +50,10 @@ export default function CodeBlock() {
}, [count, done]);
const copy = useCallback(() => {
- navigator.clipboard.writeText(RAW).then(() => {
+ void copyText(RAW).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
- });
+ }).catch(() => {});
}, []);
return (
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index 6e810ecf..635c2fd6 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -24,6 +24,7 @@ import {
withAttachmentMarkers,
} from "@/lib/attachments";
import { entryAt, historyKeyIntent, stepHistory } from "@/lib/prompt-history";
+import { playUiSound } from "@/lib/ui-sounds";
/* ─────────────────────────────────────────────────────────
* PROMPT BAR
@@ -304,7 +305,7 @@ export default function PromptBar({
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
setFailedAttaches((current) => [...current, { id, name: file.name || "attachment", error, file }]);
- setAttachError(error);
+ setAttachError(error); playUiSound("error");
} finally { setUploads(count => count - 1); }
}));
if (inputRef.current?.closest("[data-promptbar]")?.contains(document.activeElement)) inputRef.current.focus();
@@ -339,7 +340,7 @@ export default function PromptBar({
const send = () => {
if (!canSend) return;
if (/^\/(effort|reasoning)$/.test(draft.trim()) && model.effortLevels?.length) { modelRef.current?.dispatchEvent(new Event("graff-effort-open")); setDraft(""); return; }
- onSend?.(withAttachmentMarkers(draft.trim(), attachments));
+ playUiSound("press"); onSend?.(withAttachmentMarkers(draft.trim(), attachments));
releaseAttachments(attachments);
setDraft("");
setAttachments([]);
diff --git a/apps/native/components/primitives/ToolOutput.tsx b/apps/native/components/primitives/ToolOutput.tsx
index 449f17be..b95eadd6 100644
--- a/apps/native/components/primitives/ToolOutput.tsx
+++ b/apps/native/components/primitives/ToolOutput.tsx
@@ -1,5 +1,6 @@
"use client";
import { useState } from "react";
+import { copyText } from "@/lib/ui-sounds";
/** Mount only on disclosure. Long output scrolls inside the call, never the page. */
export default function ToolOutput({ detail, mono }: { detail: { text: string; tone?: "add" }[]; mono?: boolean }) {
@@ -8,7 +9,7 @@ export default function ToolOutput({ detail, mono }: { detail: { text: string; t
const text = detail.map(line => line.text).join("\n");
return <div className="my-1 ml-2 min-w-0 border-l border-line pl-3.5">
<button type="button" className="mb-1 text-xs text-ink-3 hover:text-ink" onClick={() => {
- void navigator.clipboard.writeText(text).then(() => { setCopied(true); setError(false); }).catch(() => setError(true));
+ void copyText(text).then(() => { setCopied(true); setError(false); }).catch(() => setError(true));
}}>{copied ? "Copied" : "Copy output"}</button>
{error && <span role="alert" className="ml-2 text-xs text-red">Could not copy. Select the output to copy it.</span>}
<div data-tool-output tabIndex={0} role="region" aria-label="Tool output" className="max-h-64 overflow-auto overscroll-contain rounded outline-offset-2">
diff --git a/apps/native/components/site/FilesPane.tsx b/apps/native/components/site/FilesPane.tsx
index 61246728..f42105f3 100644
--- a/apps/native/components/site/FilesPane.tsx
+++ b/apps/native/components/site/FilesPane.tsx
@@ -10,6 +10,7 @@ import {
} from "@/lib/fs-client";
import { IconCrossSmall, IconFolder } from "@/lib/icons";
import { useFilesPane, type FileRequest } from "./useFilesPane";
+import { copyText } from "@/lib/ui-sounds";
/* ─────────────────────────────────────────────────────────
* FILES PANE
@@ -61,10 +62,10 @@ function TextViewer({ file }: { file: FsFile }) {
const [wrap, setWrap] = useState(false);
const [copied, setCopied] = useState(false);
const copy = useCallback(() => {
- navigator.clipboard.writeText(file.text).then(() => {
+ void copyText(file.text).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
- });
+ }).catch(() => {});
}, [file.text]);
const lines = file.text.split("\n");
if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
diff --git a/apps/native/components/site/HtmlArtifact.tsx b/apps/native/components/site/HtmlArtifact.tsx
index fa7744ed..ff4fecd8 100644
--- a/apps/native/components/site/HtmlArtifact.tsx
+++ b/apps/native/components/site/HtmlArtifact.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useMemo, useRef, useState } from 'react';
import { previewDocument } from '@/lib/html-preview';
+import { copyText } from '@/lib/ui-sounds';
type Artifact = { title: string; html: string };
export default function HtmlArtifact({ id }: { id: string }) {
@@ -36,7 +37,7 @@ export default function HtmlArtifact({ id }: { id: string }) {
return <section ref={root} data-html-artifact={id} className="my-3 overflow-hidden rounded-window border border-line bg-surface" aria-label="Saved HTML explanation">
<header className="flex flex-wrap items-center justify-between gap-2 border-b border-line px-3 py-2">
<div className="min-w-0"><div className="truncate text-sm font-medium">{data?.title || 'HTML explanation'}</div><div className="text-[10px] text-ink-3">Static HTML · scripts and external resources are disabled</div></div>
- <div className="flex gap-1"><button data-html-preview aria-pressed={!source} className={button(!source)} onClick={()=>setSource(false)}>Preview</button><button data-html-source aria-pressed={source} className={button(source)} onClick={()=>setSource(true)}>HTML</button><button data-html-copy disabled={!data} className={button()} onClick={async()=>{try{await navigator.clipboard.writeText(data!.html);setCopied(true);}catch{setError('Copy failed. You can select the source from HTML.');}}}>{copied?'Copied':'Copy'}</button><button data-html-hide aria-expanded={!hidden} className={button()} onClick={()=>setHidden(!hidden)}>{hidden?'Show':'Hide'}</button></div>
+ <div className="flex gap-1"><button data-html-preview aria-pressed={!source} className={button(!source)} onClick={()=>setSource(false)}>Preview</button><button data-html-source aria-pressed={source} className={button(source)} onClick={()=>setSource(true)}>HTML</button><button data-html-copy disabled={!data} className={button()} onClick={async()=>{try{await copyText(data!.html);setCopied(true);}catch{setError('Copy failed. You can select the source from HTML.');}}}>{copied?'Copied':'Copy'}</button><button data-html-hide aria-expanded={!hidden} className={button()} onClick={()=>setHidden(!hidden)}>{hidden?'Show':'Hide'}</button></div>
</header>
{!hidden && <div className="min-h-[440px]">
{error && <p role="status" className="p-4 text-sm text-ink-3">{error}</p>}
diff --git a/apps/native/components/site/InterfaceSounds.tsx b/apps/native/components/site/InterfaceSounds.tsx
new file mode 100644
index 00000000..15b02f68
--- /dev/null
+++ b/apps/native/components/site/InterfaceSounds.tsx
@@ -0,0 +1,40 @@
+"use client";
+import { useEffect, useState } from "react";
+import { Switch } from "../atoms/Switch";
+import { readUiSoundPrefs, reducedMotion, uiSoundsEvent, writeUiSoundPrefs, type UiSoundPrefs } from "@/lib/ui-sounds";
+
+const off: UiSoundPrefs = { interface: false, ready: false };
+
+/** Appearance-panel controls. Playback lives in lib/ui-sounds; this only stores the choice. */
+export default function InterfaceSounds() {
+ const [prefs, setPrefs] = useState<UiSoundPrefs>(off);
+ const [muted, setMuted] = useState(false);
+ useEffect(() => {
+ const sync = () => { setPrefs(readUiSoundPrefs()); setMuted(reducedMotion()); };
+ sync();
+ const query = window.matchMedia("(prefers-reduced-motion: reduce)");
+ query.addEventListener("change", sync);
+ window.addEventListener(uiSoundsEvent, sync);
+ window.addEventListener("storage", sync);
+ return () => {
+ query.removeEventListener("change", sync);
+ window.removeEventListener(uiSoundsEvent, sync);
+ window.removeEventListener("storage", sync);
+ };
+ }, []);
+ const update = (next: UiSoundPrefs) => { writeUiSoundPrefs(next); setPrefs(next); };
+ return <fieldset className="mt-4 border-t border-line pt-3">
+ <legend className="mb-1 text-xs font-medium">Interface sounds</legend>
+ <p className="mb-3 text-xs text-ink-3">Off until you turn them on. Quiet clicks on switches, Send, and copy. Nothing on hover.</p>
+ <div className="flex items-center justify-between gap-3 py-1">
+ <span className="text-xs">Sounds</span>
+ <Switch checked={prefs.interface} label="Interface sounds" onChange={on => update({ ...prefs, interface: on })} />
+ </div>
+ <div className="flex items-center justify-between gap-3 py-1">
+ <span id="ui-sounds-ready" className="text-xs text-ink-2">Ding when a reply finishes</span>
+ <Switch checked={prefs.interface && prefs.ready} disabled={!prefs.interface} label="Ding when a reply finishes" onChange={on => update({ ...prefs, ready: on })} />
+ </div>
+ {!prefs.interface && <p className="mt-2 text-xs text-ink-3">Turn sounds on to use the reply ding. Turning sounds off keeps that choice for later.</p>}
+ {muted && <p className="mt-2 text-xs text-ink-3">Muted while Reduce motion is on. Your choice is saved.</p>}
+ </fieldset>;
+}
diff --git a/apps/native/components/site/ReviewActions.tsx b/apps/native/components/site/ReviewActions.tsx
index aec5f673..6ea58adc 100644
--- a/apps/native/components/site/ReviewActions.tsx
+++ b/apps/native/components/site/ReviewActions.tsx
@@ -1,5 +1,6 @@
"use client";
import { useEffect, useRef, useState, type RefObject } from "react";
+import { copyText, playUiSound } from "@/lib/ui-sounds";
export default function ReviewActions({ diff, path, root, viewport, count }: {
count: number; diff: string; path: string; root?: string; viewport: RefObject<HTMLElement | null>;
@@ -16,14 +17,14 @@ export default function ReviewActions({ diff, path, root, viewport, count }: {
nodes[next].scrollIntoView({ block: "start", behavior: "auto" }); setHunk(next);
};
const copy = async () => {
- try { await navigator.clipboard.writeText(diff); setError(""); setCopied(true); clearTimeout(timer.current); timer.current = setTimeout(() => setCopied(false), 1800); }
+ try { await copyText(diff); setError(""); setCopied(true); clearTimeout(timer.current); timer.current = setTimeout(() => setCopied(false), 1800); }
catch { setError("Couldn't copy the diff. Try again."); }
};
const reveal = async () => {
try {
const reply = await fetch("/api/fs", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action: "reveal", path, root }) });
if (!reply.ok) throw Error(); setError("");
- } catch { setError("Couldn't reveal this file in Finder."); }
+ } catch { playUiSound("error"); setError("Couldn't reveal this file in Finder."); }
};
const button = "rounded-[6px] px-2 py-1 text-[11px] text-ink-3 hover:bg-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-30";
return <footer className="shrink-0 border-t border-line bg-inset px-2 py-1.5">
diff --git a/apps/native/components/site/ThemeToggle.tsx b/apps/native/components/site/ThemeToggle.tsx
index 92876ed3..431e7e77 100644
--- a/apps/native/components/site/ThemeToggle.tsx
+++ b/apps/native/components/site/ThemeToggle.tsx
@@ -4,6 +4,7 @@ import { createPortal } from "react-dom";
import { restoreActionFocus } from "../primitives/ActionMenu";
import CustomThemes from "./CustomThemes";
import DesktopSettings from "./DesktopSettings";
+import InterfaceSounds from "./InterfaceSounds";
import { appearanceEvent, appearanceKey, applyAppearance, readAppearance, type Appearance } from "@/lib/appearance";
const themes = [
@@ -66,6 +67,7 @@ export function ThemeToggle({ labeled = false }: { labeled?: boolean }) {
<span className="block text-[11px] font-medium text-ink">{option.name}</span><span className="block text-[9px] leading-4 text-ink-3">{option.detail}</span>
</button>)}</div>
<CustomThemes selected={theme} />
+ <InterfaceSounds />
<DesktopSettings embedded />
</div>
</div>
diff --git a/apps/native/components/site/harness-prompt-runner.ts b/apps/native/components/site/harness-prompt-runner.ts
index 100554dd..d890abe1 100644
--- a/apps/native/components/site/harness-prompt-runner.ts
+++ b/apps/native/components/site/harness-prompt-runner.ts
@@ -9,6 +9,7 @@ import { pushHistory, saveHistory } from "@/lib/prompt-history";
import type { QueuedPrompt } from "@/lib/prompt-queue";
import type { createQueueSteerer } from "@/lib/prompt-queue-steer";
import type { Chat } from "./harness-types";
+import { playUiSound } from "@/lib/ui-sounds";
type Ref<T> = MutableRefObject<T>;
type Setter<T> = Dispatch<SetStateAction<T>>;
type Props = {
@@ -115,10 +116,14 @@ export function createPromptRunner({onStarted, onCompleted, runningRef, steerer,
if (/^\/(effort|reasoning|fast)(?:\s|$)/.test(trimmed)) void adoptCatalog(chatId);
turn = finishAcpTurn(turn);
painter.finish(turn);
- if (turn.status === "done" && !turn.error) onCompleted(chatId);
+ if (turn.status === "done" && !turn.error) {
+ onCompleted(chatId);
+ if (!trimmed.startsWith("/")) playUiSound("ready");
+ } else if (turn.error) playUiSound("error");
} catch (err) {
turn = finishAcpTurn({ ...turn, error: err instanceof Error ? err.message : String(err), status: "error" });
painter.finish(turn);
+ playUiSound("error");
} finally {
painter.dispose();
steerer.finish(chatId);
diff --git a/apps/native/components/site/idle-peer-turns.ts b/apps/native/components/site/idle-peer-turns.ts
index 63e26db8..1b8bc4f1 100644
--- a/apps/native/components/site/idle-peer-turns.ts
+++ b/apps/native/components/site/idle-peer-turns.ts
@@ -2,6 +2,7 @@ import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/
import { idleUpdates, type ChatHandle } from "@/lib/acp-client";
import { holdIdleUntilAbort } from "@/lib/idle-http";
import type { Chat } from "./harness-types";
+import { playUiSound } from "@/lib/ui-sounds";
/** Paint unsolicited ACP session/update while the page is idle (#1007).
* Every idle HTTP stream is dropped while ANY prompt turn runs, so an attach
@@ -18,6 +19,7 @@ export async function pumpIdlePeerTurns(opts: {
let asstId: number | undefined;
const paint = (update: Parameters<typeof applyAcpUpdate>[1]) => {
if (opts.running() || opts.signal.aborted) return;
+ let cue: "error" | "ready" | null = null;
opts.setChats(current => current.map(chat => {
if (chat.id !== opts.chatId) return chat;
const existing = asstId != null
@@ -35,12 +37,14 @@ export async function pumpIdlePeerTurns(opts: {
if (update.sessionUpdate === "gui_turn_end") {
turn = finishAcpTurn(turn);
asstId = undefined;
+ cue = turn.error ? "error" : "ready";
}
return {
...chat,
messages: messages.map(message => message.role === "assistant" && message.id === id ? { ...message, turn } : message),
};
}));
+ if (cue) playUiSound(cue);
};
await holdIdleUntilAbort({
diff --git a/apps/native/desktop/build-app.sh b/apps/native/desktop/build-app.sh
index b3488120..c8a6f1c8 100644
--- a/apps/native/desktop/build-app.sh
+++ b/apps/native/desktop/build-app.sh
@@ -60,6 +60,8 @@ if [[ "${SKIP_UI:-0}" != "1" ]]; then
if [[ -d "$ui/public" ]]; then
ditto "$ui/public" "$app/Contents/Resources/ui/public"
fi
+ cp "$ui/THIRD_PARTY_NOTICES.md" "$app/Contents/Resources/THIRD_PARTY_NOTICES.md"
+ ditto "$ui/third-party" "$app/Contents/Resources/third-party"
# 31 MB of image-resizing native code that this app never runs: images
# are `unoptimized` in next.config.ts, so nothing ever loads it. Dropping
# it also leaves the payload with no native code at all to sign.
diff --git a/apps/native/electron/build.sh b/apps/native/electron/build.sh
index 09b3f77a..329011a6 100644
--- a/apps/native/electron/build.sh
+++ b/apps/native/electron/build.sh
@@ -38,6 +38,8 @@ printf '{"name":"codegraff","productName":"%s","version":"%s","main":"main.cjs"}
ditto "$ui/.next/standalone" "$resources/ui"
ditto "$ui/.next/static" "$resources/ui/.next/static"
[[ ! -d "$ui/public" ]] || ditto "$ui/public" "$resources/ui/public"
+cp "$ui/THIRD_PARTY_NOTICES.md" "$resources/THIRD_PARTY_NOTICES.md"
+ditto "$ui/third-party" "$resources/third-party"
bun "$here/prepare-bundle.cjs" "$resources/ui"
rm -rf "$resources/ui/node_modules/@img"
cp "$(command -v bun)" "$resources/bun"
diff --git a/apps/native/lib/ui-sounds.test.ts b/apps/native/lib/ui-sounds.test.ts
new file mode 100644
index 00000000..fa4f958d
--- /dev/null
+++ b/apps/native/lib/ui-sounds.test.ts
@@ -0,0 +1,33 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { cueAllowed, parseUiSoundPrefs } from "./ui-sounds.ts";
+
+describe("parseUiSoundPrefs", () => {
+ it("stays off for missing, corrupt, or partial data", () => {
+ for (const raw of [null, "", "{", "null", "true", "[]", "{}", '{"interface":"yes"}', '{"ready":1}']) {
+ assert.deepEqual(parseUiSoundPrefs(raw), { interface: false, ready: false });
+ }
+ });
+ it("accepts only explicit true flags", () => {
+ assert.deepEqual(parseUiSoundPrefs('{"interface":true}'), { interface: true, ready: false });
+ assert.deepEqual(parseUiSoundPrefs('{"interface":true,"ready":true,"extra":1}'), { interface: true, ready: true });
+ assert.deepEqual(parseUiSoundPrefs('{"interface":false,"ready":true}'), { interface: false, ready: true });
+ });
+});
+
+describe("cueAllowed", () => {
+ const on = { interface: true, ready: false };
+ it("mutes everything until interface sounds are on", () => {
+ assert.equal(cueAllowed({ interface: false, ready: true }, false, "press"), false);
+ assert.equal(cueAllowed({ interface: false, ready: true }, false, "ready"), false);
+ });
+ it("keeps the reply ding behind its own switch", () => {
+ assert.equal(cueAllowed(on, false, "toggle"), true);
+ assert.equal(cueAllowed(on, false, "ready"), false);
+ assert.equal(cueAllowed({ interface: true, ready: true }, false, "ready"), true);
+ });
+ it("lets reduced motion force mute without forgetting the preference", () => {
+ assert.equal(cueAllowed({ interface: true, ready: true }, true, "success"), false);
+ assert.equal(cueAllowed({ interface: true, ready: true }, true, "ready"), false);
+ });
+});
diff --git a/apps/native/lib/ui-sounds.ts b/apps/native/lib/ui-sounds.ts
new file mode 100644
index 00000000..874c9f4a
--- /dev/null
+++ b/apps/native/lib/ui-sounds.ts
@@ -0,0 +1,74 @@
+/** Desktop interface sounds. The app owns the preference; Cuelume does not.
+ * Off is the default, and off never loads the sound library. */
+
+export const uiSoundsKey = "graff-ui-sounds";
+export const uiSoundsEvent = "graff-ui-sounds";
+export const uiSoundVolume = 0.4;
+
+export type UiSoundPrefs = { interface: boolean; ready: boolean };
+export type UiCue = "toggle" | "press" | "success" | "error" | "ready";
+
+const off: UiSoundPrefs = { interface: false, ready: false };
+
+export function parseUiSoundPrefs(raw: string | null): UiSoundPrefs {
+ if (!raw) return off;
+ try {
+ const value = JSON.parse(raw) as unknown;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return off;
+ const record = value as Record<string, unknown>;
+ return { interface: record.interface === true, ready: record.ready === true };
+ } catch {
+ return off;
+ }
+}
+
+export function cueAllowed(prefs: UiSoundPrefs, reduced: boolean, name: UiCue): boolean {
+ if (reduced || prefs.interface !== true) return false;
+ return name === "ready" ? prefs.ready === true : true;
+}
+
+export function readUiSoundPrefs(): UiSoundPrefs {
+ try { return parseUiSoundPrefs(localStorage.getItem(uiSoundsKey)); }
+ catch { return off; }
+}
+
+export function writeUiSoundPrefs(next: UiSoundPrefs): void {
+ const stored = { interface: next.interface === true, ready: next.ready === true };
+ localStorage.setItem(uiSoundsKey, JSON.stringify(stored));
+ window.dispatchEvent(new Event(uiSoundsEvent));
+}
+
+export function reducedMotion(): boolean {
+ try { return window.matchMedia("(prefers-reduced-motion: reduce)").matches; }
+ catch { return false; }
+}
+
+let loading: Promise<typeof import("cuelume")> | null = null;
+
+function library() {
+ loading ??= import("cuelume").then(mod => {
+ mod.setVolume(uiSoundVolume);
+ return mod;
+ });
+ return loading;
+}
+
+/** No-op unless interface sounds are on and the OS is not asking for less motion. */
+export function playUiSound(name: UiCue): void {
+ if (typeof window === "undefined") return;
+ if (!cueAllowed(readUiSoundPrefs(), reducedMotion(), name)) return;
+ void library().then(mod => {
+ if (!cueAllowed(readUiSoundPrefs(), reducedMotion(), name)) return;
+ mod.play(name, { volume: uiSoundVolume });
+ }).catch(() => {});
+}
+
+/** Copy, then cue success or a recoverable failure. The rejection still propagates. */
+export function copyText(text: string): Promise<void> {
+ return navigator.clipboard.writeText(text).then(() => {
+ playUiSound("success");
+ }, (err: unknown) => {
+ playUiSound("error");
+ throw err;
+ });
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index c68db358..f914cb28 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -10,7 +10,7 @@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/diff-chip-label.test.ts lib/motion-throttle.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/prompt-queue-resume.test.ts lib/streaming-code.test.ts lib/run-traces.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/queued-attachments.test.ts lib/idle-http.test.ts lib/composer-model-pick.test.ts lib/composer-keyboard.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts lib/extension-bridge.test.ts lib/close-confirm.test.ts components/site/harness-split.test.ts components/site/appearance-panel.test.ts",
+ "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/diff-chip-label.test.ts lib/motion-throttle.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/prompt-queue-resume.test.ts lib/streaming-code.test.ts lib/run-traces.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/queued-attachments.test.ts lib/idle-http.test.ts lib/composer-model-pick.test.ts lib/composer-keyboard.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts lib/extension-bridge.test.ts lib/close-confirm.test.ts components/site/harness-split.test.ts components/site/appearance-panel.test.ts lib/ui-sounds.test.ts",
"electron:build": "bash electron/build.sh",
"test:electron": "bun test electron/policy.test.cjs",
"test:webauthn": "node scripts/test-webauthn.mjs",
@@ -62,6 +62,7 @@
"@streamdown/mermaid": "^1.0.2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+ "cuelume": "^0.2.2",
"electron-updater": "6.8.9",
"geist": "^1.7.2",
"glimm": "^0.3.0",
diff --git a/apps/native/third-party/cuelume/LICENSE b/apps/native/third-party/cuelume/LICENSE
new file mode 100644
index 00000000..efd31e4f
--- /dev/null
+++ b/apps/native/third-party/cuelume/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Daniel Belyi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/gui/src-tauri/examples/generate_desktop_contracts.rs b/gui/src-tauri/examples/generate_desktop_contracts.rs
index efe2f1b6..0a114814 100644
--- a/gui/src-tauri/examples/generate_desktop_contracts.rs
+++ b/gui/src-tauri/examples/generate_desktop_contracts.rs
@@ -10,6 +10,7 @@ use codegraff_gui_lib::dto::{
ConversationViewSnapshotDto, ConversationsPayloadDto, CreateGitBranchInput,
CreateSavedWorkspaceInput, FileOperationDto, FollowupKind, FollowupOptionDto,
FollowupRequestDto, FollowupResponseDto, GitWorkspaceKindDto, HandoffChatInput, McpImportInput,
+ TaskWorkspaceActionDto, TaskWorkspaceActionInput, TaskWorkspaceReviewDto, TaskWorkspaceSummaryDto,
McpServerActionInput, McpServerSummaryDto, McpSettingsPayloadDto, OutputPreviewDto,
PromptModelOptionDto, PromptSettingsDto, ProviderAuthMethodDto, ProviderAuthMethodKindDto,
ProviderEnvOverrideDto,
@@ -76,6 +77,10 @@ fn main() -> anyhow::Result<()> {
export_decl::<SendPromptInput>(&config),
export_decl::<ChatHandoffTargetDto>(&config),
export_decl::<HandoffChatInput>(&config),
+ export_decl::<TaskWorkspaceActionDto>(&config),
+ export_decl::<TaskWorkspaceActionInput>(&config),
+ export_decl::<TaskWorkspaceReviewDto>(&config),
+ export_decl::<TaskWorkspaceSummaryDto>(&config),
export_decl::<RuntimeStatusDto>(&config),
export_decl::<GitWorkspaceKindDto>(&config),
export_decl::<CloneRepositoryInput>(&config),
diff --git a/gui/src-tauri/src/commands_workspace.rs b/gui/src-tauri/src/commands_workspace.rs
index 12cce4c5..288d11e4 100644
--- a/gui/src-tauri/src/commands_workspace.rs
+++ b/gui/src-tauri/src/commands_workspace.rs
@@ -1,6 +1,7 @@
use super::map_command_error;
use crate::dto::{
CheckoutGitBranchInput, CloneRepositoryInput, CommitGitChangesInput, CreateGitBranchInput,
+ TaskWorkspaceActionInput, TaskWorkspaceReviewDto,
CreateSavedWorkspaceInput, QuickStartProjectInput, QuickStartVisibility, RuntimeStatusDto,
SaveConversationLayoutInput, SessionSnapshotDto, TerminalCloseInput, TerminalOpenInput,
TerminalResizeInput, TerminalSessionDto, TerminalWriteInput, UpdateSavedWorkspaceLayoutInput,
@@ -195,6 +196,30 @@ pub(crate) async fn get_conversation_layout(
.map_err(map_command_error)
}
+#[tauri::command]
+pub(crate) async fn task_workspace_action(
+ input: TaskWorkspaceActionInput,
+ state: tauri::State<'_, DesktopState>,
+) -> Result<SessionSnapshotDto, String> {
+ state
+ .manager
+ .task_workspace_action(input)
+ .await
+ .map_err(map_command_error)
+}
+
+#[tauri::command]
+pub(crate) async fn task_workspace_review(
+ workspace_path: String,
+ state: tauri::State<'_, DesktopState>,
+) -> Result<TaskWorkspaceReviewDto, String> {
+ state
+ .manager
+ .task_workspace_review(workspace_path)
+ .await
+ .map_err(map_command_error)
+}
+
#[tauri::command]
pub(crate) async fn create_saved_workspace(
input: CreateSavedWorkspaceInput,
diff --git a/gui/src-tauri/src/dto/mod.rs b/gui/src-tauri/src/dto/mod.rs
index 17a5e762..bf4c19fa 100644
--- a/gui/src-tauri/src/dto/mod.rs
+++ b/gui/src-tauri/src/dto/mod.rs
@@ -25,6 +25,7 @@ pub use runtime::{
ChatHandoffTargetDto, CheckoutGitBranchInput, CloneRepositoryInput, CommitGitChangesInput,
CompleteProviderAuthInput, CreateGitBranchInput, CreateSavedWorkspaceInput,
GitWorkspaceKindDto, HandoffChatInput, ProviderEnvOverrideDto, PromptModelOptionDto,
+ TaskWorkspaceActionDto, TaskWorkspaceActionInput, TaskWorkspaceReviewDto,
PromptSettingsDto, ProviderAuthMethodDto, ProviderAuthMethodKindDto, ProviderAuthSessionDto,
ProviderAuthSessionKindDto, ProviderOAuthCallbackDto, ProviderSummaryDto, ProviderUrlParamDto,
ProviderUrlParamValueDto, QuickStartProjectInput, QuickStartVisibility, RemoveProviderInput,
@@ -35,7 +36,7 @@ pub use session::{
ChatBindingDto, ConversationSessionSummaryDto, ConversationViewSnapshotDto,
SavedWorkspaceDetailDto, SavedWorkspaceSummaryDto, SessionMessageDto, SessionRecapDto,
SessionRecapSourceDto, SessionRecapStatusDto, SessionSnapshotDto, SessionTodoDto,
- SessionTodoStatusDto, WorkspaceKindDto, WorkspaceSessionDto,
+ SessionTodoStatusDto, TaskWorkspaceSummaryDto, WorkspaceKindDto, WorkspaceSessionDto,
};
pub use terminal::{
TerminalCloseInput, TerminalErrorEventDto, TerminalExitEventDto, TerminalOpenInput,
diff --git a/gui/src-tauri/src/dto/runtime.rs b/gui/src-tauri/src/dto/runtime.rs
index ca9b9541..f9825c32 100644
--- a/gui/src-tauri/src/dto/runtime.rs
+++ b/gui/src-tauri/src/dto/runtime.rs
@@ -452,6 +452,45 @@ pub struct HandoffChatInput {
pub branch_name: Option<String>,
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
+#[serde(rename_all = "snake_case")]
+#[ts(rename = "TaskWorkspaceAction")]
+pub enum TaskWorkspaceActionDto {
+ Create,
+ Archive,
+ Discard,
+ MergeBack,
+ UpdateFromBase,
+ SyncMerged,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(rename = "TaskWorkspaceActionInput")]
+pub struct TaskWorkspaceActionInput {
+ pub action: TaskWorkspaceActionDto,
+ pub source_workspace_path: Option<String>,
+ pub workspace_path: Option<String>,
+ pub branch_name: Option<String>,
+ pub base_branch: Option<String>,
+ pub setup_script: Option<String>,
+ pub run_script: Option<String>,
+ pub teardown_script: Option<String>,
+ pub delete_branch: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(rename = "TaskWorkspaceReview")]
+pub struct TaskWorkspaceReviewDto {
+ pub workspace_path: String,
+ pub branch: String,
+ pub base_branch: String,
+ pub stat: String,
+ pub patch: String,
+ pub error: Option<String>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename = "CloneRepositoryInput")]
diff --git a/gui/src-tauri/src/dto/session.rs b/gui/src-tauri/src/dto/session.rs
index 4d7d4513..6cd003a3 100644
--- a/gui/src-tauri/src/dto/session.rs
+++ b/gui/src-tauri/src/dto/session.rs
@@ -191,6 +191,28 @@ pub struct WorkspaceSessionDto {
pub configuration_error: Option<String>,
pub selected_conversation_id: Option<String>,
pub conversations: Vec<ConversationSessionSummaryDto>,
+ /// Present when this project is a task checkout (#1119). Omitted otherwise
+ /// so older snapshots and tests stay valid.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[ts(optional)]
+ pub task: Option<TaskWorkspaceSummaryDto>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
+#[serde(rename_all = "camelCase")]
+#[ts(rename = "TaskWorkspaceSummary")]
+pub struct TaskWorkspaceSummaryDto {
+ pub branch: String,
+ pub base_branch: String,
+ pub base_commit: String,
+ pub checkout_bytes: u64,
+ pub keep_reason: Option<String>,
+ pub setup_script: Option<String>,
+ pub run_script: Option<String>,
+ pub teardown_script: Option<String>,
+ pub setup_error: Option<String>,
+ pub run_error: Option<String>,
+ pub merged_back: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
diff --git a/gui/src-tauri/src/lib.rs b/gui/src-tauri/src/lib.rs
index 251501ab..ae7b26d9 100644
--- a/gui/src-tauri/src/lib.rs
+++ b/gui/src-tauri/src/lib.rs
@@ -1,5 +1,6 @@
mod clipboard_files;
mod commands;
+mod task_workspace;
mod cli_install;
mod debug_bridge;
mod desktop_open;
@@ -32,6 +33,7 @@ use commands::{
create_git_branch, create_managed_chat, create_saved_workspace, delete_saved_workspace,
ensure_conversation_view, export_workflow_draft, get_conversation_layout, get_prompt_settings,
get_runtime_status, get_saved_workspace, get_session_snapshot, handoff_chat, import_mcp_config,
+ task_workspace_action, task_workspace_review,
list_commands, list_mcp_servers, list_providers, login_mcp_server, logout_mcp_server,
open_external_url, open_in_target, open_path_default, open_path_for_edit, open_path_in_target,
open_workspace,
@@ -122,6 +124,8 @@ pub fn run() {
start_new_chat,
create_managed_chat,
handoff_chat,
+ task_workspace_action,
+ task_workspace_review,
send_prompt,
compact_conversation,
run_slash_command,
diff --git a/gui/src-tauri/src/persistence/project_store.rs b/gui/src-tauri/src/persistence/project_store.rs
index e82e7713..caa16c00 100644
--- a/gui/src-tauri/src/persistence/project_store.rs
+++ b/gui/src-tauri/src/persistence/project_store.rs
@@ -49,6 +49,34 @@ pub struct SavedWorkspaceSummaryRecord {
pub updated_at: i64,
}
+#[derive(Debug, Clone, QueryableByName)]
+pub struct TaskWorkspaceRecord {
+ #[diesel(sql_type = Text)]
+ pub path: String,
+ #[diesel(sql_type = Text)]
+ pub branch: String,
+ #[diesel(sql_type = Text)]
+ pub base_branch: String,
+ #[diesel(sql_type = Text)]
+ pub base_commit: String,
+ #[diesel(sql_type = Nullable<Text>)]
+ pub setup_script: Option<String>,
+ #[diesel(sql_type = Nullable<Text>)]
+ pub run_script: Option<String>,
+ #[diesel(sql_type = Nullable<Text>)]
+ pub teardown_script: Option<String>,
+ #[diesel(sql_type = BigInt)]
+ pub setup_ran: i64,
+ #[diesel(sql_type = Nullable<Text>)]
+ pub setup_error: Option<String>,
+ #[diesel(sql_type = Nullable<Text>)]
+ pub run_error: Option<String>,
+ #[diesel(sql_type = Nullable<Text>)]
+ pub keep_reason: Option<String>,
+ #[diesel(sql_type = BigInt)]
+ pub merged_back: i64,
+}
+
#[derive(Debug, Clone, QueryableByName)]
pub struct SavedWorkspaceRecord {
#[diesel(sql_type = Text)]
@@ -461,6 +489,123 @@ impl ProjectStore {
})
}
+ pub fn upsert_task_workspace(&self, record: &TaskWorkspaceRecord) -> anyhow::Result<()> {
+ self.with_connection(|connection| {
+ sql_query(
+ "
+ INSERT INTO task_workspaces (
+ path, branch, base_branch, base_commit, setup_script, run_script,
+ teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back
+ )
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
+ ON CONFLICT(path) DO UPDATE SET
+ branch = excluded.branch,
+ base_branch = excluded.base_branch,
+ base_commit = excluded.base_commit,
+ setup_script = excluded.setup_script,
+ run_script = excluded.run_script,
+ teardown_script = excluded.teardown_script,
+ setup_ran = excluded.setup_ran,
+ setup_error = excluded.setup_error,
+ run_error = excluded.run_error,
+ keep_reason = excluded.keep_reason,
+ merged_back = excluded.merged_back
+ ",
+ )
+ .bind::<Text, _>(&record.path)
+ .bind::<Text, _>(&record.branch)
+ .bind::<Text, _>(&record.base_branch)
+ .bind::<Text, _>(&record.base_commit)
+ .bind::<Nullable<Text>, _>(record.setup_script.as_deref())
+ .bind::<Nullable<Text>, _>(record.run_script.as_deref())
+ .bind::<Nullable<Text>, _>(record.teardown_script.as_deref())
+ .bind::<BigInt, _>(record.setup_ran)
+ .bind::<Nullable<Text>, _>(record.setup_error.as_deref())
+ .bind::<Nullable<Text>, _>(record.run_error.as_deref())
+ .bind::<Nullable<Text>, _>(record.keep_reason.as_deref())
+ .bind::<BigInt, _>(record.merged_back)
+ .execute(connection)?;
+ Ok(())
+ })
+ }
+
+ pub fn list_task_workspaces(&self) -> anyhow::Result<Vec<TaskWorkspaceRecord>> {
+ self.with_connection(|connection| {
+ let rows = sql_query(
+ "
+ SELECT path, branch, base_branch, base_commit, setup_script, run_script,
+ teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back
+ FROM task_workspaces
+ ORDER BY path
+ ",
+ )
+ .load(connection)?;
+ Ok(rows)
+ })
+ }
+
+ pub fn get_task_workspace(&self, path: &Path) -> anyhow::Result<Option<TaskWorkspaceRecord>> {
+ let canonical = canonicalize_workspace_removal_path(path);
+ self.with_connection(|connection| {
+ let row = sql_query(
+ "
+ SELECT path, branch, base_branch, base_commit, setup_script, run_script,
+ teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back
+ FROM task_workspaces
+ WHERE path = ?1
+ ",
+ )
+ .bind::<Text, _>(canonical)
+ .get_result(connection)
+ .optional()?;
+ Ok(row)
+ })
+ }
+
+ pub fn set_task_keep_reason(&self, path: &str, reason: Option<&str>) -> anyhow::Result<()> {
+ self.with_connection(|connection| {
+ sql_query("UPDATE task_workspaces SET keep_reason = ?2 WHERE path = ?1")
+ .bind::<Text, _>(path)
+ .bind::<Nullable<Text>, _>(reason)
+ .execute(connection)?;
+ Ok(())
+ })
+ }
+
+ pub fn set_task_setup_result(
+ &self,
+ path: &str,
+ error: Option<&str>,
+ ) -> anyhow::Result<()> {
+ self.with_connection(|connection| {
+ sql_query(
+ "UPDATE task_workspaces SET setup_ran = 1, setup_error = ?2 WHERE path = ?1",
+ )
+ .bind::<Text, _>(path)
+ .bind::<Nullable<Text>, _>(error)
+ .execute(connection)?;
+ Ok(())
+ })
+ }
+
+ pub fn set_task_merged_back(&self, path: &str) -> anyhow::Result<()> {
+ self.with_connection(|connection| {
+ sql_query("UPDATE task_workspaces SET merged_back = 1, keep_reason = NULL WHERE path = ?1")
+ .bind::<Text, _>(path)
+ .execute(connection)?;
+ Ok(())
+ })
+ }
+
+ pub fn delete_task_workspace(&self, path: &str) -> anyhow::Result<()> {
+ self.with_connection(|connection| {
+ sql_query("DELETE FROM task_workspaces WHERE path = ?1")
+ .bind::<Text, _>(path)
+ .execute(connection)?;
+ Ok(())
+ })
+ }
+
fn init(&self) -> anyhow::Result<()> {
if let Some(parent) = self.db_path.parent() {
fs::create_dir_all(parent).with_context(|| {
@@ -504,6 +649,21 @@ impl ProjectStore {
updated_at INTEGER NOT NULL,
FOREIGN KEY(workspace_id) REFERENCES saved_workspaces(id) ON DELETE CASCADE
);
+
+ CREATE TABLE IF NOT EXISTS task_workspaces (
+ path TEXT PRIMARY KEY,
+ branch TEXT NOT NULL,
+ base_branch TEXT NOT NULL,
+ base_commit TEXT NOT NULL,
+ setup_script TEXT,
+ run_script TEXT,
+ teardown_script TEXT,
+ setup_ran INTEGER NOT NULL DEFAULT 0,
+ setup_error TEXT,
+ run_error TEXT,
+ keep_reason TEXT,
+ merged_back INTEGER NOT NULL DEFAULT 0
+ );
",
)?;
ensure_column_exists(connection, "opened_projects", "display_name", "TEXT")?;
diff --git a/gui/src-tauri/src/task_workspace.rs b/gui/src-tauri/src/task_workspace.rs
new file mode 100644
index 00000000..689fed22
--- /dev/null
+++ b/gui/src-tauri/src/task_workspace.rs
@@ -0,0 +1,911 @@
+//! Desktop task-workspace worktrees (#1119, #1121, #1123, #1124, #1118).
+//!
+//! The engine's isolation rules stay where they are. This module is the
+//! surface: one branch per task checkout, a keep gate that will not drop
+//! dirty / unique / unverifiable trees, and merge-back that refuses to
+//! clobber uncommitted work on the base.
+
+use std::fs;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use anyhow::{Context, Result, bail};
+
+pub const KEEP_DIRTY: &str = "has uncommitted changes";
+pub const KEEP_UNIQUE: &str = "has commits nothing else references";
+pub const KEEP_UNVERIFIABLE: &str = "could not verify it is safe to remove";
+pub const KEEP_TEARDOWN: &str = "teardown hook failed";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KeepReason {
+ Removed,
+ Dirty,
+ UniqueCommits,
+ Unverifiable,
+}
+
+impl KeepReason {
+ pub fn text(self) -> Option<&'static str> {
+ match self {
+ Self::Removed => None,
+ Self::Dirty => Some(KEEP_DIRTY),
+ Self::UniqueCommits => Some(KEEP_UNIQUE),
+ Self::Unverifiable => Some(KEEP_UNVERIFIABLE),
+ }
+ }
+}
+
+/// Same proof rule as the engine: every axis must be positively clean.
+/// `contained_elsewhere` is true when some ref other than this branch
+/// already has `head`. An empty head or a failed status read keeps the tree.
+pub fn keep_reason(
+ status_ok: bool,
+ porcelain: &str,
+ head: &str,
+ base_commit: &str,
+ contained_elsewhere: bool,
+) -> KeepReason {
+ if !status_ok {
+ return KeepReason::Unverifiable;
+ }
+ if !porcelain.trim().is_empty() {
+ return KeepReason::Dirty;
+ }
+ if head.is_empty() || base_commit.is_empty() {
+ return KeepReason::Unverifiable;
+ }
+ if head == base_commit || contained_elsewhere {
+ return KeepReason::Removed;
+ }
+ KeepReason::UniqueCommits
+}
+
+pub fn is_release_or_hotfix(branch: &str) -> bool {
+ let name = short_branch(branch);
+ name.starts_with("release/")
+ || name.starts_with("hotfix/")
+ || name.starts_with("release-")
+ || name.starts_with("hotfix-")
+}
+
+pub fn is_session_scratch(branch: &str) -> bool {
+ short_branch(branch).starts_with("worktree-")
+}
+
+pub fn is_agent_scratch(branch: &str) -> bool {
+ let name = short_branch(branch);
+ name.starts_with("graff/agents/") || name.starts_with("agent-")
+}
+
+pub fn is_experiment_tree(path: &str, branch: &str) -> bool {
+ path.contains(".graff/worktrees/exp-") || short_branch(branch).starts_with("graff/exp/")
+}
+
+fn short_branch(branch: &str) -> &str {
+ branch
+ .trim()
+ .strip_prefix("refs/heads/")
+ .unwrap_or(branch.trim())
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ReapVerdict {
+ Remove,
+ KeepMain,
+ KeepLocked,
+ KeepRelease,
+ KeepSession,
+ KeepExperiment,
+ KeepDirty,
+ KeepUnique,
+ KeepUnverifiable,
+ KeepForeign,
+}
+
+/// Automatic reap only removes finished agent scratch checkouts that the
+/// keep gate has proved empty. Release/hotfix trees stay unless the caller
+/// has proved they are not in use (`in_use == false`) AND this is an
+/// explicit unused sweep (`explicit`). Session scratch (`worktree-*`) and
+/// experiment-pool trees are never an automatic reap target (#1124).
+pub fn reap_verdict(
+ is_main: bool,
+ locked: bool,
+ in_use: bool,
+ explicit: bool,
+ path: &str,
+ branch: &str,
+ keep: KeepReason,
+) -> ReapVerdict {
+ if is_main {
+ return ReapVerdict::KeepMain;
+ }
+ if locked || in_use {
+ return ReapVerdict::KeepLocked;
+ }
+ if is_experiment_tree(path, branch) {
+ return ReapVerdict::KeepExperiment;
+ }
+ if is_session_scratch(branch) {
+ return ReapVerdict::KeepSession;
+ }
+ if is_release_or_hotfix(branch) && !explicit {
+ return ReapVerdict::KeepRelease;
+ }
+ match keep {
+ KeepReason::Dirty => return ReapVerdict::KeepDirty,
+ KeepReason::UniqueCommits => return ReapVerdict::KeepUnique,
+ KeepReason::Unverifiable => return ReapVerdict::KeepUnverifiable,
+ KeepReason::Removed => {}
+ }
+ if is_release_or_hotfix(branch) {
+ // Explicit sweep may drop a clean, merged, unused release checkout.
+ return ReapVerdict::Remove;
+ }
+ if is_agent_scratch(branch) || explicit {
+ return ReapVerdict::Remove;
+ }
+ ReapVerdict::KeepForeign
+}
+
+/// A branch is deleted only after its worktree is gone, and only when the
+/// commits were landed or the user confirmed a force delete (#1121).
+pub fn branch_delete_allowed(worktree_exists: bool, merged_back: bool, confirmed: bool) -> bool {
+ !worktree_exists && (merged_back || confirmed)
+}
+
+pub fn validate_branch_name(name: &str) -> Result<()> {
+ let name = name.trim();
+ if name.is_empty() {
+ bail!("branch name is required");
+ }
+ if name.starts_with('-') || name.ends_with('/') || name.ends_with('.') {
+ bail!("invalid branch name");
+ }
+ if name.contains("..") || name.contains("@{") || name.contains(' ') {
+ bail!("invalid branch name");
+ }
+ if name
+ .chars()
+ .any(|ch| matches!(ch, '~' | '^' | ':' | '?' | '*' | '[' | '\\' | '\0'))
+ {
+ bail!("invalid branch name");
+ }
+ Ok(())
+}
+
+pub fn slug_branch(branch: &str) -> String {
+ let mut slug = String::new();
+ for ch in branch.chars() {
+ if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
+ slug.push(ch);
+ } else {
+ slug.push('-');
+ }
+ }
+ let slug = slug.trim_matches('-');
+ if slug.is_empty() {
+ "task".into()
+ } else {
+ slug.chars().take(48).collect()
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct WorktreeEntry {
+ pub path: String,
+ pub head: String,
+ pub branch: String,
+ pub locked: bool,
+ pub bare: bool,
+}
+
+pub fn parse_worktree_porcelain(text: &str) -> Vec<WorktreeEntry> {
+ let mut entries = Vec::new();
+ for block in text.split("\n\n") {
+ let mut entry = WorktreeEntry {
+ path: String::new(),
+ head: String::new(),
+ branch: String::new(),
+ locked: false,
+ bare: false,
+ };
+ for raw in block.lines() {
+ let line = raw.trim();
+ if let Some(path) = line.strip_prefix("worktree ") {
+ entry.path = path.to_string();
+ } else if let Some(head) = line.strip_prefix("HEAD ") {
+ entry.head = head.to_string();
+ } else if let Some(branch) = line.strip_prefix("branch ") {
+ entry.branch = branch.to_string();
+ } else if line == "locked" || line.starts_with("locked ") {
+ entry.locked = true;
+ } else if line == "bare" {
+ entry.bare = true;
+ }
+ }
+ if !entry.path.is_empty() {
+ entries.push(entry);
+ }
+ }
+ entries
+}
+
+pub fn contained_elsewhere(refs: &str, own_branch: &str) -> bool {
+ let own = short_branch(own_branch);
+ refs.lines().any(|raw| {
+ let reference = raw.trim().trim_start_matches(['*', '+']).trim();
+ !reference.is_empty() && short_branch(reference) != own && reference != own_branch
+ })
+}
+
+#[derive(Debug, Clone)]
+pub struct CreatedTaskWorktree {
+ pub path: PathBuf,
+ pub branch: String,
+ pub base_branch: String,
+ pub base_commit: String,
+}
+
+pub fn create_task_worktree(
+ source: &Path,
+ base_branch: Option<&str>,
+ branch: &str,
+) -> Result<CreatedTaskWorktree> {
+ validate_branch_name(branch)?;
+ let source = resolve_dir(source)?;
+ let main = main_worktree(&source).unwrap_or_else(|| source.clone());
+ let base_branch = match base_branch.map(str::trim).filter(|value| !value.is_empty()) {
+ Some(name) => name.to_string(),
+ None => current_branch(&source).unwrap_or_else(|| "HEAD".into()),
+ };
+ let base_ref = if base_branch == "HEAD" {
+ "HEAD".to_string()
+ } else {
+ base_branch.clone()
+ };
+ let base_commit = git_stdout(&source, &["rev-parse", &base_ref])
+ .context("could not read the base commit")?
+ .trim()
+ .to_string();
+ if base_commit.is_empty() {
+ bail!("could not read the base commit");
+ }
+ let dest = main
+ .join(".graff")
+ .join("worktrees")
+ .join(format!("task-{}", slug_branch(branch)));
+ if dest.exists() {
+ bail!("worktree path already exists: {}", dest.display());
+ }
+ if let Some(parent) = dest.parent() {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("failed to create {}", parent.display()))?;
+ }
+ let add = git(
+ &main,
+ &[
+ "worktree",
+ "add",
+ "-b",
+ branch,
+ dest.to_string_lossy().as_ref(),
+ &base_ref,
+ ],
+ )?;
+ if !add.status.success() {
+ bail!(
+ "git worktree add failed: {}",
+ stderr_text(&add).trim()
+ );
+ }
+ Ok(CreatedTaskWorktree {
+ path: dest,
+ branch: branch.to_string(),
+ base_branch,
+ base_commit,
+ })
+}
+
+#[derive(Debug, Clone)]
+pub struct Inspection {
+ pub keep: KeepReason,
+ pub checkout_bytes: u64,
+}
+
+pub fn inspect(path: &Path, base_commit: &str) -> Inspection {
+ let checkout_bytes = checkout_bytes(path);
+ let status = git(path, &["status", "--porcelain"]);
+ let head = git_stdout(path, &["rev-parse", "HEAD"])
+ .unwrap_or_default()
+ .trim()
+ .to_string();
+ let branch = git_stdout(path, &["rev-parse", "--abbrev-ref", "HEAD"])
+ .unwrap_or_default()
+ .trim()
+ .to_string();
+ let (status_ok, porcelain) = match status {
+ Ok(output) if output.status.success() => (true, String::from_utf8_lossy(&output.stdout).into_owned()),
+ _ => (false, String::new()),
+ };
+ let contained = git_stdout(
+ path,
+ &[
+ "branch",
+ "--all",
+ "--contains",
+ &head,
+ "--format=%(refname)",
+ ],
+ )
+ .map(|refs| contained_elsewhere(&refs, &branch))
+ .unwrap_or(false);
+ Inspection {
+ keep: keep_reason(status_ok, &porcelain, &head, base_commit, contained),
+ checkout_bytes,
+ }
+}
+
+pub fn remove_checkout(path: &Path, force: bool) -> Result<()> {
+ let repo = path;
+ let mut args = vec!["worktree", "remove"];
+ if force {
+ args.push("--force");
+ }
+ let path_string = path.to_string_lossy().into_owned();
+ args.push(&path_string);
+ // `worktree remove` must run from a checkout that is not the one being removed.
+ let main = main_worktree(path).unwrap_or_else(|| path.to_path_buf());
+ let cwd = if main == path {
+ path
+ } else {
+ &main
+ };
+ let output = git(cwd, &args)?;
+ if output.status.success() {
+ return Ok(());
+ }
+ // Fall back to the source repo if `path` itself was already unusable.
+ let _ = repo;
+ bail!("could not remove worktree: {}", stderr_text(&output).trim());
+}
+
+pub fn delete_branch(repo: &Path, branch: &str, force: bool) -> Result<()> {
+ let flag = if force { "-D" } else { "-d" };
+ let output = git(repo, &["branch", flag, branch])?;
+ if output.status.success() {
+ Ok(())
+ } else {
+ bail!("could not delete branch: {}", stderr_text(&output).trim())
+ }
+}
+
+/// Lands `branch` onto the base checkout as one commit. Refuses when the
+/// base checkout has uncommitted tracked work — a recovery reset would eat it.
+pub fn merge_back(base_checkout: &Path, branch: &str) -> Result<()> {
+ if tracked_dirty(base_checkout)? {
+ bail!("base checkout has uncommitted changes — commit or stash them before merge-back");
+ }
+ let merge = git(base_checkout, &["merge", "--squash", branch])?;
+ if !merge.status.success() {
+ let _ = git(base_checkout, &["reset", "--hard", "HEAD"]);
+ bail!(
+ "couldn't land {branch} — it overlaps changes already on the base. Base left clean, worktree intact."
+ );
+ }
+ let message = format!("land {branch}\n\nCo-Authored-By: Codegraff <[email protected]>");
+ let commit = git(base_checkout, &["commit", "-m", &message])?;
+ if !commit.status.success() {
+ let _ = git(base_checkout, &["reset", "--hard", "HEAD"]);
+ let detail = stderr_text(&commit);
+ if detail.contains("nothing to commit") || String::from_utf8_lossy(&commit.stdout).contains("nothing to commit")
+ {
+ bail!("nothing to land from {branch} — worktree left intact");
+ }
+ bail!("git commit failed — worktree left intact: {}", detail.trim());
+ }
+ Ok(())
+}
+
+pub fn update_from_base(worktree: &Path, base: &str) -> Result<()> {
+ if tracked_dirty(worktree)? {
+ bail!("workspace has uncommitted changes — commit or stash them before updating from {base}");
+ }
+ let output = git(worktree, &["merge", "--no-edit", base])?;
+ if output.status.success() {
+ Ok(())
+ } else {
+ let _ = git(worktree, &["merge", "--abort"]);
+ bail!(
+ "could not update from {base}: {}",
+ stderr_text(&output).trim()
+ );
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MergeProof {
+ Merged,
+ NotMerged,
+ Unknown,
+}
+
+pub fn proven_merged_local(repo: &Path, branch: &str, base: &str) -> MergeProof {
+ match git(repo, &["merge-base", "--is-ancestor", branch, base]) {
+ Ok(output) if output.status.success() => MergeProof::Merged,
+ Ok(output) if output.status.code() == Some(1) => MergeProof::NotMerged,
+ _ => MergeProof::Unknown,
+ }
+}
+
+/// `gh` is extra proof for squash merges, which are not ancestors of the base.
+/// A missing or timed-out `gh` does not count as "not merged".
+pub fn proven_merged(repo: &Path, branch: &str, base: &str) -> MergeProof {
+ match proven_merged_local(repo, branch, base) {
+ MergeProof::Merged => return MergeProof::Merged,
+ MergeProof::Unknown => return MergeProof::Unknown,
+ MergeProof::NotMerged => {}
+ }
+ match gh_merged_pr(repo, branch) {
+ Some(true) => MergeProof::Merged,
+ Some(false) => MergeProof::NotMerged,
+ None => MergeProof::NotMerged,
+ }
+}
+
+pub fn worktree_exists(path: &Path) -> bool {
+ path.join(".git").exists() || path.is_dir() && git(path, &["rev-parse", "--is-inside-work-tree"]).ok().is_some_and(|o| o.status.success())
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ScriptOutcome {
+ pub ok: bool,
+ pub output: String,
+}
+
+pub fn run_script(cwd: &Path, script: &str) -> ScriptOutcome {
+ let script = script.trim();
+ if script.is_empty() {
+ return ScriptOutcome {
+ ok: true,
+ output: String::new(),
+ };
+ }
+ let mut command = Command::new("sh");
+ command
+ .arg("-c")
+ .arg(script)
+ .current_dir(cwd)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ match command.output() {
+ Ok(output) => {
+ let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
+ let err = String::from_utf8_lossy(&output.stderr);
+ if !err.is_empty() {
+ if !text.is_empty() && !text.ends_with('\n') {
+ text.push('\n');
+ }
+ text.push_str(&err);
+ }
+ if text.len() > 16 * 1024 {
+ text.truncate(16 * 1024);
+ text.push_str("\n…");
+ }
+ ScriptOutcome {
+ ok: output.status.success(),
+ output: text,
+ }
+ }
+ Err(error) => ScriptOutcome {
+ ok: false,
+ output: format!("failed to run setup/run script: {error}"),
+ },
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ReviewDiff {
+ pub stat: String,
+ pub patch: String,
+}
+
+pub fn review_diff(worktree: &Path, base: &str) -> Result<ReviewDiff> {
+ let stat = git_stdout(worktree, &["diff", "--stat", &format!("{base}...HEAD")])
+ .unwrap_or_default();
+ let committed = git_stdout(worktree, &["diff", &format!("{base}...HEAD")]).unwrap_or_default();
+ let uncommitted = git_stdout(worktree, &["diff"]).unwrap_or_default();
+ let mut patch = String::new();
+ if !committed.trim().is_empty() {
+ patch.push_str(&committed);
+ }
+ if !uncommitted.trim().is_empty() {
+ if !patch.is_empty() && !patch.ends_with('\n') {
+ patch.push('\n');
+ }
+ patch.push_str(&uncommitted);
+ }
+ if patch.len() > 200_000 {
+ patch.truncate(200_000);
+ patch.push_str("\n… diff truncated\n");
+ }
+ Ok(ReviewDiff { stat, patch })
+}
+
+pub fn checkout_bytes(path: &Path) -> u64 {
+ let Ok(output) = Command::new("du")
+ .args(["-sk"])
+ .arg(path)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .output()
+ else {
+ return 0;
+ };
+ if !output.status.success() {
+ return 0;
+ }
+ let text = String::from_utf8_lossy(&output.stdout);
+ let kb = text.split_whitespace().next().unwrap_or("0");
+ kb.parse::<u64>().unwrap_or(0).saturating_mul(1024)
+}
+
+fn tracked_dirty(path: &Path) -> Result<bool> {
+ let output = git(path, &["status", "--porcelain"])?;
+ if !output.status.success() {
+ bail!("could not read git status");
+ }
+ let text = String::from_utf8_lossy(&output.stdout);
+ Ok(text.lines().any(|line| {
+ let line = line.trim_end();
+ line.len() >= 2 && !line.starts_with("??")
+ }))
+}
+
+fn current_branch(path: &Path) -> Option<String> {
+ let name = git_stdout(path, &["rev-parse", "--abbrev-ref", "HEAD"]).ok()?;
+ let name = name.trim();
+ if name.is_empty() || name == "HEAD" {
+ None
+ } else {
+ Some(name.to_string())
+ }
+}
+
+pub fn repo_root(path: &Path) -> PathBuf {
+ main_worktree(path).unwrap_or_else(|| path.to_path_buf())
+}
+
+fn main_worktree(path: &Path) -> Option<PathBuf> {
+ let common = git_stdout(path, &["rev-parse", "--git-common-dir"]).ok()?;
+ let common = PathBuf::from(common.trim());
+ let common = if common.is_absolute() {
+ common
+ } else {
+ path.join(common)
+ };
+ let main = common.parent()?;
+ if main.as_os_str().is_empty() {
+ return None;
+ }
+ Some(main.to_path_buf())
+}
+
+fn gh_merged_pr(repo: &Path, branch: &str) -> Option<bool> {
+ let mut command = Command::new("gh");
+ command
+ .args([
+ "pr",
+ "list",
+ "--head",
+ branch,
+ "--state",
+ "merged",
+ "--json",
+ "number",
+ "--limit",
+ "1",
+ ])
+ .current_dir(repo)
+ .env("GH_PROMPT_DISABLED", "1")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+ let text = run_timeout(&mut command, Duration::from_secs(3))?;
+ if text.trim().is_empty() || text.trim() == "[]" {
+ return Some(false);
+ }
+ Some(text.contains("\"number\""))
+}
+
+fn run_timeout(command: &mut Command, timeout: Duration) -> Option<String> {
+ let mut child = command.spawn().ok()?;
+ let started = Instant::now();
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => {
+ let mut text = String::new();
+ if let Some(mut stdout) = child.stdout.take() {
+ let _ = stdout.read_to_string(&mut text);
+ }
+ let _ = child.wait();
+ return Some(text);
+ }
+ Ok(None) if started.elapsed() > timeout => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return None;
+ }
+ Ok(None) => thread::sleep(Duration::from_millis(40)),
+ Err(_) => return None,
+ }
+ }
+}
+
+fn resolve_dir(path: &Path) -> Result<PathBuf> {
+ fs::canonicalize(path).with_context(|| format!("workspace not found: {}", path.display()))
+}
+
+fn git(cwd: &Path, args: &[&str]) -> Result<std::process::Output> {
+ Command::new("git")
+ .args(args)
+ .current_dir(cwd)
+ .stdin(Stdio::null())
+ .output()
+ .with_context(|| format!("failed to run git {}", args.join(" ")))
+}
+
+fn git_stdout(cwd: &Path, args: &[&str]) -> Result<String> {
+ let output = git(cwd, args)?;
+ if !output.status.success() {
+ bail!("{}", stderr_text(&output).trim());
+ }
+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+}
+
+fn stderr_text(output: &std::process::Output) -> String {
+ let mut text = String::from_utf8_lossy(&output.stderr).into_owned();
+ if text.trim().is_empty() {
+ text = String::from_utf8_lossy(&output.stdout).into_owned();
+ }
+ text
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn keep_reason_requires_proof_on_every_axis() {
+ assert_eq!(
+ keep_reason(true, "", "abc", "abc", false),
+ KeepReason::Removed
+ );
+ assert_eq!(
+ keep_reason(true, "", "def", "abc", true),
+ KeepReason::Removed
+ );
+ assert_eq!(
+ keep_reason(true, " M src/a.rs\n", "abc", "abc", true),
+ KeepReason::Dirty
+ );
+ assert_eq!(
+ keep_reason(true, "?? new.rs\n", "abc", "abc", true),
+ KeepReason::Dirty
+ );
+ assert_eq!(
+ keep_reason(true, "", "def", "abc", false),
+ KeepReason::UniqueCommits
+ );
+ assert_eq!(
+ keep_reason(false, "", "abc", "abc", true),
+ KeepReason::Unverifiable
+ );
+ assert_eq!(
+ keep_reason(true, "", "", "abc", true),
+ KeepReason::Unverifiable
+ );
+ }
+
+ #[test]
+ fn reap_keeps_main_release_session_and_dirty_agent_trees() {
+ assert_eq!(
+ reap_verdict(true, false, false, true, "/repo", "main", KeepReason::Removed),
+ ReapVerdict::KeepMain
+ );
+ assert_eq!(
+ reap_verdict(
+ false,
+ false,
+ true,
+ true,
+ "/repo/.graff/worktrees/rel",
+ "release/v1",
+ KeepReason::Removed
+ ),
+ ReapVerdict::KeepLocked
+ );
+ assert_eq!(
+ reap_verdict(
+ false,
+ false,
+ false,
+ false,
+ "/repo/.graff/worktrees/rel",
+ "hotfix/urgent",
+ KeepReason::Removed
+ ),
+ ReapVerdict::KeepRelease
+ );
+ assert_eq!(
+ reap_verdict(
+ false,
+ false,
+ false,
+ false,
+ "/repo/.graff/worktrees/session-1",
+ "worktree-session-1",
+ KeepReason::Removed
+ ),
+ ReapVerdict::KeepSession
+ );
+ assert_eq!(
+ reap_verdict(
+ false,
+ false,
+ false,
+ false,
+ "/repo/.graff/worktrees/agent-1",
+ "graff/agents/sa-1",
+ KeepReason::Dirty
+ ),
+ ReapVerdict::KeepDirty
+ );
+ assert_eq!(
+ reap_verdict(
+ false,
+ false,
+ false,
+ false,
+ "/repo/.graff/worktrees/agent-1",
+ "graff/agents/sa-1",
+ KeepReason::Removed
+ ),
+ ReapVerdict::Remove
+ );
+ assert_eq!(
+ reap_verdict(
+ false,
+ false,
+ false,
+ false,
+ "/repo/.worktrees/mine",
+ "feature/mine",
+ KeepReason::Removed
+ ),
+ ReapVerdict::KeepForeign
+ );
+ }
+
+ #[test]
+ fn branch_is_not_deleted_while_its_worktree_exists() {
+ assert!(!branch_delete_allowed(true, true, true));
+ assert!(!branch_delete_allowed(false, false, false));
+ assert!(branch_delete_allowed(false, true, false));
+ assert!(branch_delete_allowed(false, false, true));
+ }
+
+ #[test]
+ fn porcelain_parser_reads_locked_linked_trees() {
+ let entries = parse_worktree_porcelain(
+ "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\nworktree /repo/.graff/worktrees/a\nHEAD bbb\nbranch refs/heads/graff/agents/a\nlocked\n",
+ );
+ assert_eq!(entries.len(), 2);
+ assert_eq!(entries[1].branch, "refs/heads/graff/agents/a");
+ assert!(entries[1].locked);
+ assert!(!contained_elsewhere(
+ "refs/heads/graff/agents/a\n",
+ "refs/heads/graff/agents/a"
+ ));
+ assert!(contained_elsewhere(
+ "refs/heads/graff/agents/a\nrefs/heads/main\n",
+ "refs/heads/graff/agents/a"
+ ));
+ }
+
+ #[test]
+ fn create_refuses_to_clobber_and_merge_back_refuses_a_dirty_base() {
+ let root = std::env::temp_dir().join(format!(
+ "codegraff-task-wt-{}",
+ uuid_nonce()
+ ));
+ fs::create_dir_all(&root).unwrap();
+ git_ok(&root, &["init", "-b", "main"]);
+ git_ok(&root, &["config", "user.email", "[email protected]"]);
+ git_ok(&root, &["config", "user.name", "test"]);
+ fs::write(root.join("readme.txt"), "base\n").unwrap();
+ git_ok(&root, &["add", "readme.txt"]);
+ git_ok(&root, &["commit", "-m", "base"]);
+
+ let created = create_task_worktree(&root, Some("main"), "feature/task-one").unwrap();
+ assert!(created.path.join("readme.txt").is_file());
+ assert_eq!(created.base_branch, "main");
+ assert!(inspect(&created.path, &created.base_commit).keep == KeepReason::Removed);
+ update_from_base(&created.path, "main").unwrap();
+
+ fs::write(created.path.join("task.txt"), "work\n").unwrap();
+ assert_eq!(
+ inspect(&created.path, &created.base_commit).keep,
+ KeepReason::Dirty
+ );
+ let failed = run_script(&created.path, "echo hi && false");
+ assert!(!failed.ok);
+ assert!(failed.output.contains("hi"));
+
+ fs::write(root.join("readme.txt"), "dirty base\n").unwrap();
+ let merge_err = merge_back(&root, "feature/task-one").unwrap_err().to_string();
+ assert!(merge_err.contains("uncommitted"));
+ // The dirty base file is still the user's edit, not a reset.
+ assert_eq!(fs::read_to_string(root.join("readme.txt")).unwrap(), "dirty base\n");
+
+ git_ok(&root, &["checkout", "--", "readme.txt"]);
+ git_ok(&created.path, &["add", "task.txt"]);
+ git_ok(&created.path, &["commit", "-m", "task"]);
+ assert_eq!(
+ inspect(&created.path, &created.base_commit).keep,
+ KeepReason::UniqueCommits
+ );
+ merge_back(&root, "feature/task-one").unwrap();
+ assert_eq!(
+ proven_merged_local(&root, "feature/task-one", "main"),
+ MergeProof::NotMerged,
+ "squash merge is not an ancestor; the branch itself is the proof of landing"
+ );
+ assert!(fs::read_to_string(root.join("task.txt")).unwrap().contains("work"));
+
+ let review = review_diff(&created.path, "main").unwrap();
+ assert!(review.stat.contains("task.txt") || review.patch.contains("task"));
+
+ assert!(branch_delete_allowed(true, true, true) == false);
+ remove_checkout(&created.path, false).unwrap();
+ assert!(branch_delete_allowed(false, true, false));
+ // Squash land is not `git branch -d` merged; confirmation uses -D.
+ assert!(delete_branch(&root, "feature/task-one", false).is_err());
+ delete_branch(&root, "feature/task-one", true).unwrap();
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ fn uuid_nonce() -> String {
+ use std::time::{SystemTime, UNIX_EPOCH};
+ format!(
+ "{}-{}",
+ std::process::id(),
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ )
+ }
+
+ fn git_ok(cwd: &Path, args: &[&str]) {
+ let output = git(cwd, args).unwrap();
+ assert!(
+ output.status.success(),
+ "git {args:?} failed: {}",
+ stderr_text(&output)
+ );
+ }
+
+ #[test]
+ fn script_failure_is_visible() {
+ let root = std::env::temp_dir().join(format!("codegraff-task-script-{}", uuid_nonce()));
+ fs::create_dir_all(&root).unwrap();
+ let outcome = run_script(&root, "echo setup-failed >&2; exit 3");
+ assert!(!outcome.ok);
+ assert!(outcome.output.contains("setup-failed"));
+ let _ = fs::remove_dir_all(&root);
+ }
+}
diff --git a/gui/src/app/SessionProvider.tsx b/gui/src/app/SessionProvider.tsx
index d89c6039..a67246c1 100644
--- a/gui/src/app/SessionProvider.tsx
+++ b/gui/src/app/SessionProvider.tsx
@@ -5,6 +5,7 @@ import * as desktopClient from "../services/desktop/client";
import type {
ChatBinding,
HandoffChatInput,
+ TaskWorkspaceActionInput,
SessionSnapshot,
} from "../services/desktop/types/contracts";
import { extractBindingsFromLayoutJson } from "../components/workspace-board/layout";
@@ -315,6 +316,17 @@ export function SessionProvider({ children }: SessionProviderProps) {
desktopClient.pushGitBranch(workspacePath),
);
},
+ taskWorkspaceAction: async (input: TaskWorkspaceActionInput) => {
+ const snapshot = await desktopClient.taskWorkspaceAction(input);
+ applySessionSnapshot(snapshot);
+ syncBoardSelectionFromSnapshot(snapshot);
+ if (snapshot.activeWorkspacePath != null) {
+ ensureWorkspaceMeta(snapshot.activeWorkspacePath, {
+ forceRuntimeStatus: true,
+ });
+ }
+ return snapshot;
+ },
handoffChat: async (input: HandoffChatInput) => {
const originPromptDraftKey = getPromptDraftKey(
input.sourceWorkspacePath,
diff --git a/gui/src/app/types/sessionContext.ts b/gui/src/app/types/sessionContext.ts
index ea3e58e7..6b24a0f7 100644
--- a/gui/src/app/types/sessionContext.ts
+++ b/gui/src/app/types/sessionContext.ts
@@ -1,6 +1,7 @@
import type {
ChatBinding,
HandoffChatInput,
+ TaskWorkspaceActionInput,
SavedWorkspaceDetail,
SessionSnapshot,
} from "@/services/desktop/types/contracts";
@@ -31,6 +32,9 @@ export interface SessionActionsContextValue {
deleteSavedWorkspace: (workspaceId: string) => Promise<void>;
startNewChat: (workspacePath?: string) => Promise<SessionSnapshot | null>;
handoffChat: (input: HandoffChatInput) => Promise<SessionSnapshot | null>;
+ taskWorkspaceAction: (
+ input: TaskWorkspaceActionInput,
+ ) => Promise<SessionSnapshot>;
checkoutBranch: (branchName: string) => Promise<void>;
createBranch: (branchName: string) => Promise<void>;
commitChanges: (message: string) => Promise<void>;
diff --git a/gui/src/components/ProjectSidebar.tsx b/gui/src/components/ProjectSidebar.tsx
index 46620ccd..5df7263c 100644
--- a/gui/src/components/ProjectSidebar.tsx
+++ b/gui/src/components/ProjectSidebar.tsx
@@ -1,5 +1,7 @@
+import { useEffect, useRef, useState } from "react";
import {
FolderPlus,
+ GitBranch,
PanelsTopLeft,
PenSquare,
Plug2Icon,
@@ -14,6 +16,7 @@ import { useExpandedProjectPaths } from "../hooks/useExpandedProjectPaths";
import {
useSessionActions,
useSidebarSession,
+ useWorkspaceMeta,
} from "../hooks/useSession";
import { formatRelativeTimestamp } from "../utils/time";
import { handleWindowDragStart } from "../utils/window";
@@ -23,6 +26,12 @@ import { SidebarArchiveAction } from "./SidebarArchiveAction";
import { SidebarItemActionsMenu } from "./SidebarItemActionsMenu";
import { SidebarSettingsControl } from "./SidebarSettingsControl";
import { ProjectSidebarProject } from "./ProjectSidebarProject";
+import { TaskWorkspaceCard } from "./task-workspace/TaskWorkspaceCard";
+import {
+ TaskWorkspaceCreateDialog,
+ TaskWorkspaceFinishDialog,
+} from "./task-workspace/TaskWorkspaceDialogs";
+import { queueTaskRun } from "./task-workspace/taskRun";
import type { ProjectSidebarProps } from "./types/sidebar";
import { Button } from "./ui/Button";
import {
@@ -75,6 +84,7 @@ export function ProjectSidebar({
const {
archiveConversation,
archiveWorkspace,
+ taskWorkspaceAction,
deleteSavedWorkspace,
openWorkspacePicker,
openProject,
@@ -91,9 +101,41 @@ export function ProjectSidebar({
savedWorkspaces,
workspaces,
} = useSidebarSession();
+ const [createOpen, setCreateOpen] = useState(false);
+ const [finishPath, setFinishPath] = useState<string | null>(null);
+ const [taskBusy, setTaskBusy] = useState(false);
+ const [taskError, setTaskError] = useState<string | null>(null);
const projectWorkspaces = workspaces.filter(
(workspace) => workspace.kind === "project",
);
+ const taskWorkspaces = projectWorkspaces.filter(
+ (workspace) => workspace.task != null,
+ );
+ const activeMeta = useWorkspaceMeta(activeWorkspacePath);
+ const finishWorkspace = taskWorkspaces.find(
+ (workspace) => workspace.workspacePath === finishPath,
+ );
+
+ const syncedMerged = useRef(false);
+ useEffect(() => {
+ if (syncedMerged.current) {
+ return;
+ }
+ syncedMerged.current = true;
+ void taskWorkspaceAction({
+ action: "sync_merged",
+ sourceWorkspacePath: null,
+ workspacePath: null,
+ branchName: null,
+ baseBranch: null,
+ setupScript: null,
+ runScript: null,
+ teardownScript: null,
+ deleteBranch: false,
+ }).catch(() => {
+ // A missing gh login is not a reason to block the sidebar.
+ });
+ }, [taskWorkspaceAction]);
const managedChats = workspaces.filter(
(workspace) => workspace.kind === "managed_chat",
);
@@ -125,10 +167,38 @@ export function ProjectSidebar({
}
function handleArchiveWorkspace(workspacePath: string) {
+ const task = projectWorkspaces.find(
+ (workspace) => workspace.workspacePath === workspacePath,
+ )?.task;
+ if (task != null) {
+ setTaskError(null);
+ setFinishPath(workspacePath);
+ return;
+ }
collapseProject(workspacePath);
void archiveWorkspace(workspacePath);
}
+ async function runTaskAction(
+ input: Parameters<typeof taskWorkspaceAction>[0],
+ ) {
+ setTaskBusy(true);
+ setTaskError(null);
+ try {
+ const snapshot = await taskWorkspaceAction(input);
+ if (snapshot.uiError) {
+ setTaskError(snapshot.uiError);
+ } else {
+ setCreateOpen(false);
+ setFinishPath(null);
+ }
+ } catch (error) {
+ setTaskError(error instanceof Error ? error.message : "Task workspace action failed");
+ } finally {
+ setTaskBusy(false);
+ }
+ }
+
async function handleRenameProject(
workspacePath: string,
displayName?: string | null,
@@ -395,6 +465,19 @@ export function ProjectSidebar({
<SidebarGroupLabel className="h-full px-0 font-medium">
Projects
</SidebarGroupLabel>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label="New task workspace"
+ title="New task workspace"
+ onClick={() => {
+ setTaskError(null);
+ setCreateOpen(true);
+ }}
+ >
+ <GitBranch strokeWidth={2} className="size-3.5 shrink-0" />
+ </Button>
<Button
type="button"
variant="ghost"
@@ -409,6 +492,48 @@ export function ProjectSidebar({
</div>
<SidebarGroupContent>
+ {taskWorkspaces.length > 0 ? (
+ <div className="mb-2 grid gap-2 px-1">
+ {taskWorkspaces.map((project) =>
+ project.task ? (
+ <TaskWorkspaceCard
+ key={project.workspacePath}
+ name={project.workspaceName}
+ task={project.task}
+ busy={taskBusy}
+ onOpen={() => {
+ void openProject(project.workspacePath);
+ }}
+ onMerge={() => {
+ void runTaskAction({
+ action: "merge_back",
+ sourceWorkspacePath: null,
+ workspacePath: project.workspacePath,
+ branchName: null,
+ baseBranch: null,
+ setupScript: null,
+ runScript: null,
+ teardownScript: null,
+ deleteBranch: false,
+ });
+ }}
+ onArchive={() => {
+ setTaskError(null);
+ setFinishPath(project.workspacePath);
+ }}
+ onRun={() => {
+ if (!project.task?.runScript) {
+ return;
+ }
+ queueTaskRun(project.workspacePath, project.task.runScript);
+ void openProject(project.workspacePath);
+ handleStartNewChat(project.workspacePath);
+ }}
+ />
+ ) : null,
+ )}
+ </div>
+ ) : null}
{projectWorkspaces.length === 0 ? (
<p className="px-2 py-1 text-xs font-medium text-sidebar-foreground/60">
No projects yet
@@ -457,6 +582,62 @@ export function ProjectSidebar({
</div>
</div>
</div>
+ <TaskWorkspaceCreateDialog
+ open={createOpen}
+ sourcePath={activeWorkspacePath}
+ branches={activeMeta.runtimeStatus?.gitBranches ?? []}
+ busy={taskBusy}
+ error={taskError}
+ onOpenChange={setCreateOpen}
+ onSubmit={(input) => {
+ void runTaskAction(input);
+ }}
+ />
+ <TaskWorkspaceFinishDialog
+ open={finishPath != null}
+ branch={finishWorkspace?.task?.branch ?? null}
+ keepReason={finishWorkspace?.task?.keepReason ?? null}
+ busy={taskBusy}
+ error={taskError}
+ onOpenChange={(open) => {
+ if (!open) {
+ setFinishPath(null);
+ }
+ }}
+ onArchive={(deleteBranch, discard) => {
+ if (finishPath == null) {
+ return;
+ }
+ void runTaskAction({
+ action: discard ? "discard" : "archive",
+ sourceWorkspacePath: null,
+ workspacePath: finishPath,
+ branchName: null,
+ baseBranch: null,
+ setupScript: null,
+ runScript: null,
+ teardownScript: null,
+ deleteBranch,
+ });
+ }}
+ onKeep={() => setFinishPath(null)}
+ onUpdate={() => {
+ if (finishPath == null) {
+ return;
+ }
+ void runTaskAction({
+ action: "update_from_base",
+ sourceWorkspacePath: null,
+ workspacePath: finishPath,
+ branchName: null,
+ baseBranch: null,
+ setupScript: null,
+ runScript: null,
+ teardownScript: null,
+ deleteBranch: false,
+ });
+ }}
+ />
</Sidebar>
);
}
diff --git a/gui/src/components/task-workspace/TaskWorkspaceCard.tsx b/gui/src/components/task-workspace/TaskWorkspaceCard.tsx
new file mode 100644
index 00000000..f2bfe434
--- /dev/null
+++ b/gui/src/components/task-workspace/TaskWorkspaceCard.tsx
@@ -0,0 +1,78 @@
+import type { TaskWorkspaceSummary } from "@/services/desktop/types/contracts";
+
+import { Button } from "../ui/Button";
+
+export function formatCheckoutBytes(bytes: number): string {
+ if (!Number.isFinite(bytes) || bytes <= 0) {
+ return "size unavailable";
+ }
+ const units = ["B", "KB", "MB", "GB"];
+ let value = bytes;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ const shown = value >= 10 || unit === 0 ? value.toFixed(0) : value.toFixed(1);
+ return `${shown} ${units[unit]}`;
+}
+
+export function TaskWorkspaceCard({
+ name,
+ task,
+ busy,
+ onOpen,
+ onMerge,
+ onArchive,
+ onRun,
+}: {
+ name: string;
+ task: TaskWorkspaceSummary;
+ busy: boolean;
+ onOpen: () => void;
+ onMerge: () => void;
+ onArchive: () => void;
+ onRun: () => void;
+}) {
+ return (
+ <article className="grid gap-2 rounded-lg border border-sidebar-border bg-sidebar-accent/40 p-2">
+ <div className="min-w-0">
+ <p className="truncate text-sm font-medium">{name}</p>
+ <p className="truncate font-mono text-[11px] text-sidebar-foreground/70">
+ {task.branch}
+ <span className="text-sidebar-foreground/45"> · from {task.baseBranch}</span>
+ </p>
+ <p className="text-[11px] text-sidebar-foreground/60">
+ {formatCheckoutBytes(task.checkoutBytes)}
+ {task.mergedBack ? " · landed" : ""}
+ </p>
+ </div>
+ {task.keepReason ? (
+ <p className="text-[11px] text-amber-700 dark:text-amber-300">
+ Kept — {task.keepReason}
+ </p>
+ ) : null}
+ {task.setupError ? (
+ <p className="line-clamp-3 text-[11px] text-destructive">
+ Setup failed: {task.setupError}
+ </p>
+ ) : null}
+ <div className="flex flex-wrap gap-1">
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={onOpen}>
+ Open
+ </Button>
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={onMerge}>
+ Merge
+ </Button>
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={onArchive}>
+ Archive
+ </Button>
+ {task.runScript ? (
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={onRun}>
+ Run
+ </Button>
+ ) : null}
+ </div>
+ </article>
+ );
+}
diff --git a/gui/src/components/task-workspace/TaskWorkspaceDialogs.tsx b/gui/src/components/task-workspace/TaskWorkspaceDialogs.tsx
new file mode 100644
index 00000000..7c0c3e7b
--- /dev/null
+++ b/gui/src/components/task-workspace/TaskWorkspaceDialogs.tsx
@@ -0,0 +1,217 @@
+import { useState } from "react";
+
+import type { TaskWorkspaceActionInput } from "@/services/desktop/types/contracts";
+
+import { Button } from "../ui/Button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "../ui/Dialog";
+import { Input } from "../ui/Input";
+import { Label } from "../ui/Label";
+
+const EMPTY_ACTION: TaskWorkspaceActionInput = {
+ action: "create",
+ sourceWorkspacePath: null,
+ workspacePath: null,
+ branchName: null,
+ baseBranch: null,
+ setupScript: null,
+ runScript: null,
+ teardownScript: null,
+ deleteBranch: false,
+};
+
+export function TaskWorkspaceCreateDialog({
+ open,
+ sourcePath,
+ branches,
+ busy,
+ error,
+ onOpenChange,
+ onSubmit,
+}: {
+ open: boolean;
+ sourcePath: string | null;
+ branches: string[];
+ busy: boolean;
+ error: string | null;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (input: TaskWorkspaceActionInput) => void;
+}) {
+ const [branchName, setBranchName] = useState("");
+ const [baseBranch, setBaseBranch] = useState("");
+ const [setupScript, setSetupScript] = useState("");
+ const [runScript, setRunScript] = useState("");
+ const [teardownScript, setTeardownScript] = useState("");
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>New task workspace</DialogTitle>
+ <DialogDescription>
+ Checks out a fresh branch from the base into its own Git worktree.
+ Chats and terminals for this task stay on that checkout.
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ className="grid gap-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ onSubmit({
+ ...EMPTY_ACTION,
+ action: "create",
+ sourceWorkspacePath: sourcePath,
+ branchName: branchName.trim(),
+ baseBranch: baseBranch.trim() || null,
+ setupScript: setupScript.trim() || null,
+ runScript: runScript.trim() || null,
+ teardownScript: teardownScript.trim() || null,
+ });
+ }}
+ >
+ <div className="grid gap-1.5">
+ <Label htmlFor="task-branch">Branch</Label>
+ <Input
+ id="task-branch"
+ value={branchName}
+ placeholder="feature/my-task"
+ onChange={(event) => setBranchName(event.target.value)}
+ />
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="task-base">Base branch</Label>
+ <Input
+ id="task-base"
+ list="task-base-branches"
+ value={baseBranch}
+ placeholder={branches[0] ?? "main"}
+ onChange={(event) => setBaseBranch(event.target.value)}
+ />
+ <datalist id="task-base-branches">
+ {branches.map((branch) => (
+ <option key={branch} value={branch} />
+ ))}
+ </datalist>
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="task-setup">Setup script</Label>
+ <Input
+ id="task-setup"
+ value={setupScript}
+ placeholder="bun install"
+ onChange={(event) => setSetupScript(event.target.value)}
+ />
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="task-run">Run script</Label>
+ <Input
+ id="task-run"
+ value={runScript}
+ placeholder="bun run dev"
+ onChange={(event) => setRunScript(event.target.value)}
+ />
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="task-teardown">Teardown hook</Label>
+ <Input
+ id="task-teardown"
+ value={teardownScript}
+ placeholder="optional, runs on archive"
+ onChange={(event) => setTeardownScript(event.target.value)}
+ />
+ </div>
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ <DialogFooter>
+ <Button type="submit" disabled={busy || sourcePath == null || branchName.trim() === ""}>
+ Create worktree
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function TaskWorkspaceFinishDialog({
+ open,
+ branch,
+ keepReason,
+ busy,
+ error,
+ onOpenChange,
+ onArchive,
+ onKeep,
+ onUpdate,
+}: {
+ open: boolean;
+ branch: string | null;
+ keepReason: string | null;
+ busy: boolean;
+ error: string | null;
+ onOpenChange: (open: boolean) => void;
+ onArchive: (deleteBranch: boolean, discard: boolean) => void;
+ onKeep: () => void;
+ onUpdate: () => void;
+}) {
+ const [deleteBranch, setDeleteBranch] = useState(false);
+ const [discard, setDiscard] = useState(false);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>Finish workspace</DialogTitle>
+ <DialogDescription>
+ {branch
+ ? `${branch} stays until you archive it. An agent finishing a turn does not remove this checkout.`
+ : "Choose what to do with this checkout."}
+ </DialogDescription>
+ </DialogHeader>
+ {keepReason ? (
+ <p className="text-xs text-amber-700 dark:text-amber-300">
+ Kept — {keepReason}. Discard is explicit and deletes uncommitted work.
+ </p>
+ ) : null}
+ <label className="flex items-center gap-2 text-xs">
+ <input
+ type="checkbox"
+ checked={deleteBranch}
+ onChange={(event) => setDeleteBranch(event.target.checked)}
+ />
+ Delete the branch after the checkout is gone
+ </label>
+ <label className="flex items-center gap-2 text-xs">
+ <input
+ type="checkbox"
+ checked={discard}
+ onChange={(event) => setDiscard(event.target.checked)}
+ />
+ Discard uncommitted work
+ </label>
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ size="sm"
+ disabled={busy}
+ onClick={() => onArchive(deleteBranch, discard)}
+ >
+ Archive now
+ </Button>
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={onKeep}>
+ Keep for follow-up
+ </Button>
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={onUpdate}>
+ Update from main
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/gui/src/components/task-workspace/taskRun.ts b/gui/src/components/task-workspace/taskRun.ts
new file mode 100644
index 00000000..af389273
--- /dev/null
+++ b/gui/src/components/task-workspace/taskRun.ts
@@ -0,0 +1,33 @@
+const STORAGE_KEY = "graff.task-run";
+export const TASK_RUN_EVENT = "graff:task-run";
+
+export function queueTaskRun(workspacePath: string, command: string) {
+ sessionStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ workspacePath, command }),
+ );
+ window.dispatchEvent(new Event(TASK_RUN_EVENT));
+}
+
+export function takeTaskRun(
+ workspacePath: string,
+): { workspacePath: string; command: string } | null {
+ const raw = sessionStorage.getItem(STORAGE_KEY);
+ if (raw == null) {
+ return null;
+ }
+ try {
+ const parsed = JSON.parse(raw) as {
+ workspacePath?: string;
+ command?: string;
+ };
+ if (parsed.workspacePath !== workspacePath || !parsed.command) {
+ return null;
+ }
+ sessionStorage.removeItem(STORAGE_KEY);
+ return { workspacePath, command: parsed.command };
+ } catch {
+ sessionStorage.removeItem(STORAGE_KEY);
+ return null;
+ }
+}
diff --git a/gui/src/components/workspace-board/ChangesPane.tsx b/gui/src/components/workspace-board/ChangesPane.tsx
index 27e48aa0..2761d6ac 100644
--- a/gui/src/components/workspace-board/ChangesPane.tsx
+++ b/gui/src/components/workspace-board/ChangesPane.tsx
@@ -23,7 +23,8 @@ import { useConversationHeaderState } from "@/components/conversation-panel/hook
import { CommitChangesDialog } from "@/components/conversation-panel/CommitChangesDialog";
import { GithubHubCard, GithubHubMenu } from "@/components/conversation-panel/GithubHubMenu";
import { githubRepoUrls } from "@/components/conversation-panel/utils/githubIssues";
-import { openExternalUrl } from "@/services/desktop/client";
+import { openExternalUrl, taskWorkspaceReview } from "@/services/desktop/client";
+import { useSessionStore } from "@/hooks/useSession";
import {
getFileDiffDisplayName,
getFileDiffDisplayPath,
@@ -175,6 +176,38 @@ export function ChangesPane({
);
const view = useConversationView(binding);
const workspaceMeta = useWorkspaceMeta(params.workspacePath);
+ const task = useSessionStore(
+ (state) =>
+ state.workspaces.find(
+ (workspace) => workspace.workspacePath === params.workspacePath,
+ )?.task ?? null,
+ );
+ const [worktreeReview, setWorktreeReview] = useState<string | null>(null);
+ useEffect(() => {
+ if (task == null) {
+ setWorktreeReview(null);
+ return;
+ }
+ let cancelled = false;
+ void taskWorkspaceReview(params.workspacePath)
+ .then((review) => {
+ if (cancelled) {
+ return;
+ }
+ const body = [review.stat, review.patch].filter(Boolean).join("\n");
+ setWorktreeReview(review.error ?? (body || "Working tree matches its base."));
+ })
+ .catch((error: unknown) => {
+ if (!cancelled) {
+ setWorktreeReview(
+ error instanceof Error ? error.message : "Could not read the worktree diff",
+ );
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [params.workspacePath, task]);
const {
repoName,
branchName,
@@ -371,6 +404,12 @@ export function ChangesPane({
) : null}
</div>
+ {worktreeReview != null ? (
+ <pre className="max-h-64 overflow-auto border-b border-border px-4 py-2 font-mono text-[11px] whitespace-pre-wrap text-muted-foreground">
+ {worktreeReview}
+ </pre>
+ ) : null}
+
{changes.length === 0 ? (
<div className="flex flex-col gap-4 px-4 py-6">
{github != null && repoName != null ? (
diff --git a/gui/src/components/workspace-board/ChatTile.tsx b/gui/src/components/workspace-board/ChatTile.tsx
index ad06bfb7..ae3846ff 100644
--- a/gui/src/components/workspace-board/ChatTile.tsx
+++ b/gui/src/components/workspace-board/ChatTile.tsx
@@ -54,6 +54,7 @@ import {
type PaneResizeTween,
type ResizeAxis,
} from "./paneResizeAnimation";
+import { TASK_RUN_EVENT, takeTaskRun } from "../task-workspace/taskRun";
import { applySavedConversationLayout } from "./utils/savedLayout";
import "./chat-tile-dockview.css";
@@ -79,6 +80,19 @@ export function ChatTile({
const shellRef = useRef<HTMLElement | null>(null);
const paneTweenRef = useRef<PaneResizeTween | null>(null);
const innerApiRef = useRef<DockviewApi | null>(null);
+ useEffect(() => {
+ function openQueuedRun() {
+ const request = takeTaskRun(binding.workspacePath);
+ const api = innerApiRef.current;
+ if (request == null || api == null) {
+ return;
+ }
+ addTerminalTab(api, binding, request.command);
+ }
+ window.addEventListener(TASK_RUN_EVENT, openQueuedRun);
+ openQueuedRun();
+ return () => window.removeEventListener(TASK_RUN_EVENT, openQueuedRun);
+ }, [binding]);
const innerDisposablesRef = useRef<Array<{ dispose(): void }>>([]);
const fallbackToDefaultLayoutRef = useRef(false);
const draggedPanelRef = useRef<IDockviewPanel | null>(null);
diff --git a/gui/src/components/workspace-board/chatTileLayout.ts b/gui/src/components/workspace-board/chatTileLayout.ts
index 891270b3..cf384142 100644
--- a/gui/src/components/workspace-board/chatTileLayout.ts
+++ b/gui/src/components/workspace-board/chatTileLayout.ts
@@ -85,7 +85,11 @@ function generateTerminalKey(): string {
* (spanning beneath chat + side panes) with the stable key "1"; subsequent ones are
* added as sibling tabs in the same bottom group, each with its own PTY key.
*/
-export function addTerminalTab(api: DockviewApi, binding: ChatBinding): void {
+export function addTerminalTab(
+ api: DockviewApi,
+ binding: ChatBinding,
+ initialCommand?: string,
+): void {
if (api.getPanel(CHAT_PANE_ID) == null) {
buildDefaultChatTileLayout(api, binding);
}
@@ -109,6 +113,7 @@ export function addTerminalTab(api: DockviewApi, binding: ChatBinding): void {
kind: "terminal",
label: title,
terminalKey,
+ initialCommand,
},
// Keep every terminal tab mounted when inactive so switching tabs doesn't tear
// down its PTY (dockview's default `onlyWhenVisible` would unmount it).
diff --git a/gui/src/components/workspace-board/hooks/useTerminalSession.ts b/gui/src/components/workspace-board/hooks/useTerminalSession.ts
index 9a9df7e8..b33236aa 100644
--- a/gui/src/components/workspace-board/hooks/useTerminalSession.ts
+++ b/gui/src/components/workspace-board/hooks/useTerminalSession.ts
@@ -329,6 +329,13 @@ export function useTerminalSession(
openedRef.current = true;
setStatus(null);
+ const initialCommand = params.initialCommand?.trim();
+ if (initialCommand) {
+ await desktopClient.writeTerminal({
+ terminalId,
+ data: `${initialCommand}\n`,
+ });
+ }
const resolvedSize = normalizeTerminalSize(session.cols, session.rows);
syncedBackendSize = resolvedSize;
diff --git a/gui/src/components/workspace-board/types/layout.ts b/gui/src/components/workspace-board/types/layout.ts
index bb343184..2a249a36 100644
--- a/gui/src/components/workspace-board/types/layout.ts
+++ b/gui/src/components/workspace-board/types/layout.ts
@@ -10,9 +10,11 @@ export interface PlaceholderPaneParams extends ChatBinding {
// Per-tab key for terminal panes so multiple terminals each get a distinct PTY
// (persisted in the layout so sessions are stable across restore).
terminalKey?: string;
+ initialCommand?: string;
}
export type TerminalPaneParams = PlaceholderPaneParams & {
kind: "terminal";
terminalKey?: string;
+ initialCommand?: string;
};
diff --git a/gui/src/services/desktop/client.ts b/gui/src/services/desktop/client.ts
index 0357112e..e9b0486d 100644
--- a/gui/src/services/desktop/client.ts
+++ b/gui/src/services/desktop/client.ts
@@ -12,6 +12,8 @@ import { isQaMockMode, mockInvokeCommand } from "./clientQaMock";
import type {
AgentsPayload,
HandoffChatInput,
+ TaskWorkspaceActionInput,
+ TaskWorkspaceReview,
CheckoutGitBranchInput,
ChatBinding,
CloneRepositoryInput,
@@ -174,6 +176,18 @@ export function handoffChat(input: HandoffChatInput): Promise<SessionSnapshot> {
return invokeCommand("handoff_chat", { input });
}
+export function taskWorkspaceAction(
+ input: TaskWorkspaceActionInput,
+): Promise<SessionSnapshot> {
+ return invokeCommand("task_workspace_action", { input });
+}
+
+export function taskWorkspaceReview(
+ workspacePath: string,
+): Promise<TaskWorkspaceReview> {
+ return invokeCommand("task_workspace_review", { workspacePath });
+}
+
export function sendPrompt(input: SendPromptInput): Promise<SessionSnapshot> {
return invokeCommand("send_prompt", { input });
}
diff --git a/gui/src/services/desktop/types/contracts.generated.ts b/gui/src/services/desktop/types/contracts.generated.ts
index 93b0cc2d..0ec2f5ca 100644
--- a/gui/src/services/desktop/types/contracts.generated.ts
+++ b/gui/src/services/desktop/types/contracts.generated.ts
@@ -49,7 +49,9 @@ recap?: SessionRecap, followup: FollowupRequest | null, };
export type WorkspaceKind = "project" | "managed_chat";
-export type WorkspaceSession = { kind: WorkspaceKind, workspacePath: string, workspaceName: string, configured: boolean, configurationError: string | null, selectedConversationId: string | null, conversations: Array<ConversationSessionSummary>, };
+export type TaskWorkspaceSummary = { branch: string, baseBranch: string, baseCommit: string, checkoutBytes: number, keepReason: string | null, setupScript: string | null, runScript: string | null, teardownScript: string | null, setupError: string | null, runError: string | null, mergedBack: boolean, };
+
+export type WorkspaceSession = { kind: WorkspaceKind, workspacePath: string, workspaceName: string, configured: boolean, configurationError: string | null, selectedConversationId: string | null, conversations: Array<ConversationSessionSummary>, task?: TaskWorkspaceSummary, };
export type SavedWorkspaceSummary = { id: string, name: string, updatedAt: bigint, };
@@ -124,6 +126,12 @@ export type ChatHandoffTarget = "local" | "worktree";
export type HandoffChatInput = { sourceWorkspacePath: string, conversationId: string | null, target: ChatHandoffTarget, branchName: string | null, };
+export type TaskWorkspaceAction = "create" | "archive" | "discard" | "merge_back" | "update_from_base" | "sync_merged";
+
+export type TaskWorkspaceActionInput = { action: TaskWorkspaceAction, sourceWorkspacePath: string | null, workspacePath: string | null, branchName: string | null, baseBranch: string | null, setupScript: string | null, runScript: string | null, teardownScript: string | null, deleteBranch: boolean, };
+
+export type TaskWorkspaceReview = { workspacePath: string, branch: string, baseBranch: string, stat: string, patch: string, error: string | null, };
+
export type RuntimeStatus = { workspacePath: string | null, workspaceName: string | null, gitRepoName: string | null, gitBranchName: string | null, gitBranches: Array<string>, gitWorkspaceKind: GitWorkspaceKind | null, gitMainWorkspacePath: string | null, availableOpenTargets: Array<string>, configured: boolean, configurationError: string | null, };
export type GitWorkspaceKind = "local" | "worktree";
diff --git a/gui/src/services/desktop/types/contracts.ts b/gui/src/services/desktop/types/contracts.ts
index f2b7a4ff..1661a63d 100644
--- a/gui/src/services/desktop/types/contracts.ts
+++ b/gui/src/services/desktop/types/contracts.ts
@@ -25,6 +25,10 @@ export type {
FollowupResponse,
GitWorkspaceKind,
HandoffChatInput,
+ TaskWorkspaceAction,
+ TaskWorkspaceActionInput,
+ TaskWorkspaceReview,
+ TaskWorkspaceSummary,
McpImportInput,
McpServerActionInput,
McpServerSummary,