Skip to content

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

Python

Confirm tab close before stopping its ACP worker

Cursor Agentdec7cee4d417
diff --git a/apps/native/components/site/CloseConfirmDialog.tsx b/apps/native/components/site/CloseConfirmDialog.tsx
new file mode 100644
index 00000000..08787100
--- /dev/null
+++ b/apps/native/components/site/CloseConfirmDialog.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { useLayoutEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { IconCrossSmall } from "@/lib/icons";
+
+/* ─────────────────────────────────────────────────────────
+ * CLOSE CONFIRM DIALOG
+ * Closing a tab stops its `graff acp` worker: the agent process is
+ * retired and anything it was still running — background jobs,
+ * subagents — stops with it. Worth confirming once, instead of
+ * silently killing the chat under the user.
+ * ───────────────────────────────────────────────────────── */
+
+const BUTTON = "h-8 shrink-0 rounded-full px-3 text-[12.5px] font-medium transition-colors";
+
+type Props = {
+ /** Tabs about to close (a split tab closes its whole group). */
+ tabs: number;
+ /** How many of them own a live worker. The prompt only shows above zero. */
+ workers: number;
+ onCancel: () => void;
+ onConfirm: (dontAskAgain: boolean) => void;
+};
+
+export default function CloseConfirmDialog({ tabs, workers, onCancel, onConfirm }: Props) {
+ const panel = useRef<HTMLDivElement>(null);
+ const confirm = useRef<HTMLButtonElement>(null);
+ const [dontAskAgain, setDontAskAgain] = useState(false);
+ const cancel = useRef(onCancel);
+ cancel.current = onCancel;
+
+ useLayoutEffect(() => {
+ const dialog = panel.current!;
+ const previous = document.activeElement as HTMLElement | null;
+ // The portal is a direct body child. Inert background roots keep native
+ // and programmatic focus out of the chat behind the modal.
+ const background = Array.from(document.body.children)
+ .filter((element): element is HTMLElement => element instanceof HTMLElement && !element.contains(dialog))
+ .map((element) => ({ element, inert: element.inert }));
+ background.forEach(({ element }) => { element.inert = true; });
+ const controls = () => Array.from(dialog.querySelectorAll<HTMLElement>("button, input"))
+ .filter((element) => !(element as HTMLButtonElement).disabled && element.getClientRects().length > 0);
+ confirm.current?.focus({ preventScroll: true });
+ const keepFocus = (event: FocusEvent) => {
+ if (!dialog.contains(event.target as Node)) (controls()[0] ?? dialog).focus({ preventScroll: true });
+ };
+ const onKey = (event: KeyboardEvent) => {
+ if (event.isComposing) return;
+ if (event.key === "Escape") {
+ event.preventDefault(); event.stopPropagation(); cancel.current();
+ return;
+ }
+ if (event.key !== "Tab") return;
+ const items = controls(), first = items[0], last = items.at(-1);
+ if (!first || !last) return;
+ if (!dialog.contains(document.activeElement) || (event.shiftKey ? document.activeElement === first : document.activeElement === last)) {
+ event.preventDefault();
+ (event.shiftKey ? last : first).focus({ preventScroll: true });
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ document.addEventListener("focusin", keepFocus, true);
+ return () => {
+ document.removeEventListener("keydown", onKey);
+ document.removeEventListener("focusin", keepFocus, true);
+ background.forEach(({ element, inert }) => { element.inert = inert; });
+ if (previous?.isConnected) previous.focus({ preventScroll: true });
+ };
+ }, []);
+
+ const plural = tabs !== 1;
+ const title = plural ? `Close ${tabs} tabs` : "Close tab";
+ const stopLine = plural
+ ? `Closing these tabs stops ${workers === tabs ? `their ${workers === 1 ? "agent" : "agents"}` : `${workers} running ${workers === 1 ? "agent" : "agents"}`}.`
+ : "Closing this tab stops its agent.";
+
+ return createPortal(
+ <div
+ className="fixed inset-0 z-[60] flex items-center justify-center p-4"
+ style={{ background: "color-mix(in oklab, var(--ink) 22%, transparent)", animation: "fade-in 160ms ease both" }}
+ onPointerDown={(event) => {
+ if (event.target === event.currentTarget) onCancel();
+ }}
+ >
+ <div
+ ref={panel}
+ role="dialog"
+ tabIndex={-1}
+ aria-modal="true"
+ aria-label={title}
+ className="flex w-full max-w-[440px] flex-col overflow-hidden rounded-window bg-surface shadow-overlay"
+ style={{ animation: "pop-in 180ms cubic-bezier(0.23,1,0.32,1) both" }}
+ >
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-line px-4">
+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-ink">{title}</span>
+ <button
+ type="button"
+ aria-label="Close"
+ onClick={onCancel}
+ className="flex size-7 items-center justify-center rounded-full text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
+ >
+ <IconCrossSmall size={16} />
+ </button>
+ </div>
+
+ <div className="flex flex-col gap-2 px-4 py-4 text-[12.5px] leading-5 text-ink-2">
+ <p>{stopLine}</p>
+ <p className="text-ink-3">Anything still running — background jobs, subagents — stops with {plural ? "them" : "it"}.</p>
+ <label className="mt-1 flex cursor-pointer items-center gap-2 text-[12.5px] text-ink-2">
+ <input type="checkbox" checked={dontAskAgain} onChange={(event) => setDontAskAgain(event.target.checked)} />
+ Don&apos;t ask again
+ </label>
+ </div>
+
+ <div className="flex shrink-0 items-center justify-end gap-2 border-t border-line px-4 py-3">
+ <button type="button" onClick={onCancel} className={`${BUTTON} text-ink-2 hover:bg-hover hover:text-ink`}>
+ Cancel
+ </button>
+ <button
+ ref={confirm}
+ type="button"
+ onClick={() => onConfirm(dontAskAgain)}
+ className={`${BUTTON} bg-ink px-3.5 text-canvas hover:opacity-90`}
+ >
+ {title}
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index ef2aae72..98b49472 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -24,8 +24,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type PromptModel } from "@/components/primitives/PromptBar";
import SidebarNav from "@/components/primitives/SidebarNav";
import { type BrowserPin } from "@/lib/browser/annotations";
-import { browserClose } from "@/lib/browser-client";
import ChatColumn from "./ChatColumn";
+import CloseConfirmDialog from "@/components/site/CloseConfirmDialog";
import ModelSwitchDialog from "@/components/site/ModelSwitchDialog";
import {
AgentsPane, AppSettings, BrowserPane, ChangesPane, ConversationsPane, FilesPane,
@@ -38,14 +38,14 @@ import { useDesktopWorkspace } from "./useDesktopWorkspace";
import {
answer, cancel,
chatHandle,
- disposeSession,
type Health,
} from "@/lib/acp-client";
import { type AcpCommand } from "@/lib/acp";
import { useChatScroll } from "./useChatScroll";
import { enqueuePrompt } from "@/lib/prompt-queue";
import { usePromptQueue, steerOrInterrupt } from "./usePromptQueue";
-import { removeSession, type StoredSession } from "@/lib/sessions";
+import { useChatClose } from "./useChatClose";
+import { type StoredSession } from "@/lib/sessions";
import { loadHistory, mergeHistory } from "@/lib/prompt-history";
import {
basename,
@@ -147,8 +147,6 @@ export default function GraffHarness() {
const [pendingModel, setPendingModel] = useState<{ key: string; chatId: number } | null>(null);
const runningRef = useRef(new Set<number>());
const queueResumesRef = useRef(new Set<number>());
- // Closed tabs, oldest first, for the reopen shortcut.
- const closedRef = useRef<{ session: string | null; cwd?: string; resumable: boolean }[]>([]);
const chatThread = chats.find((c) => c.id === activeId) ?? chats[0];
// Split positions are independent of keyboard focus.
@@ -309,18 +307,6 @@ export default function GraffHarness() {
if (folder && folder !== activePathRef.current) activateWorkspace(folder);
});
- /** Bring back the tab that was closed last, resuming its graff session so
- * the conversation comes back with it. A tab that never got a message has
- * nothing saved, so it returns as a fresh one. */
- const reopenClosed = () => {
- const stack = closedRef.current;
- const last = stack[stack.length - 1];
- if (!last) return;
- closedRef.current = stack.slice(0, -1);
- if (last.session && last.resumable) void openStored(last.session, last.cwd);
- else newChat();
- };
-
/** Another chat beside the ones on screen, in the workspace the active
* chat is in. Up to four columns; past that they are too narrow to read. */
const addPane = (direction: "row" | "column" = splitDirection) => {
@@ -341,59 +327,16 @@ export default function GraffHarness() {
else addPane();
};
- const dropChat = (id: number) => {
- sessionsRef.current.delete(id);
- sessionNamesRef.current.delete(id);
- runningRef.current.delete(id);
- steerer.finish(id);
- setQueue(id, []);
- setSessionIds((current) => {
- const { [id]: _gone, ...rest } = current;
- return rest;
- });
- setBusyFor(id, false);
- const { [id]: _pins, ...remainingPins } = pinsRef.current;
- pinsRef.current = remainingPins; setPinsByChat(remainingPins);
- setCommands(current => { const { [id]: _commands, ...rest } = current; return rest; });
- setCancelError(current => { const { [id]: _error, ...rest } = current; return rest; });
- void disposeSession(handleOf(id));
- void browserClose(handleOf(id)).catch(() => undefined);
- };
-
- const closeChats = (ids: number[]) => {
- const visible = columnIds.filter(pane => !ids.includes(pane));
- groups.remove(ids); setZoomedPane(null);
- for (const id of ids) {
- const going = chatsRef.current.find(c => c.id === id);
- if (going) closedRef.current = [...closedRef.current.slice(-9), {
- session: going.session ?? null, cwd: going.cwd, resumable: going.messages.length > 0,
- }];
- dropChat(id);
- }
- const remaining = chatsRef.current.filter(c => !ids.includes(c.id));
- chatsRef.current = remaining; setChats(remaining);
- if (!remaining.length) { openChat(++chatIdRef.current); return; }
- if (ids.includes(activeId)) focusChat(visible[0] ?? remaining[remaining.length - 1].id);
- };
- const closeChat = (id: number) => closeChats([id]);
- const closeTab = (id: number) => closeChats(groups.groups.find(group => group.ids.includes(id))?.ids ?? [id]);
+ const { closeChat, closeTab, reopenClosed, dropStored, pendingClose, cancelPendingClose, confirmPendingClose } = useChatClose({
+ sessionsRef, sessionNamesRef, chatsRef, runningRef, chatIdRef, pinsRef, activePathRef, groups, columnIds, activeId,
+ handleOf, setBusyFor, setQueue, steerer, setSessionIds, setCommands, setCancelError, setPinsByChat, setZoomedPane,
+ setChats, setStored, openChat, focusChat, openStored, newChat, refreshStored,
+ });
const pickRecent = (id: string) => {
void openStored(id);
};
- /** Put a saved chat away, or remove it for good. Its tab closes with it,
- * and the row goes at once rather than after the next poll. */
- const dropStored = (name: string, archive: boolean) => {
- const cwd = activePathRef.current ?? undefined;
- const open = chatsRef.current.filter((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));
- if (open.length) closeChats(open.map(chat => chat.id));
- setStored((current) => current.filter((s) => s.name !== name));
- void removeSession(name, { root: cwd, archive })
- .catch(() => undefined)
- .then(() => refreshStored());
- };
-
const { switchWorkspace, addWorkspace, saveWorkspace, forgetWorkspace, newProjectChat, activateWorkspace } = workspaceActions({
workspacesRef, activePathRef, chatsRef, chatIdRef, activeId, root: health?.cwd,
setWorkspaces, setActivePath, setChats, setActiveId: focusChat, setFilesOpen, setDialog,
@@ -623,6 +566,14 @@ export default function GraffHarness() {
onConfirm={() => { const picked = pendingModel; setPendingModel(null); applyModel(picked.key, picked.chatId); }}
/>
)}
+ {pendingClose && (
+ <CloseConfirmDialog
+ tabs={pendingClose.ids.length}
+ workers={pendingClose.workers}
+ onCancel={cancelPendingClose}
+ onConfirm={confirmPendingClose}
+ />
+ )}
{dialog && (
<WorkspaceDialog
mode={dialog.mode}
diff --git a/apps/native/components/site/useChatClose.ts b/apps/native/components/site/useChatClose.ts
new file mode 100644
index 00000000..10b07cf3
--- /dev/null
+++ b/apps/native/components/site/useChatClose.ts
@@ -0,0 +1,136 @@
+"use client";
+import { useEffect, useRef, useState, type Dispatch, type MutableRefObject, type SetStateAction } from "react";
+import { disposeSession } from "@/lib/acp-client";
+import { browserClose } from "@/lib/browser-client";
+import { closeWorkerCount, readCloseDontAsk, shouldConfirmTabClose, writeCloseDontAsk } from "@/lib/close-confirm";
+import { removeSession, type StoredSession } from "@/lib/sessions";
+import type { AcpCommand } from "@/lib/acp";
+import type { BrowserPin } from "@/lib/browser/annotations";
+import type { QueuedPrompt } from "@/lib/prompt-queue";
+import type { Chat } from "./harness-types";
+
+type Ref<T> = MutableRefObject<T>;
+type Setter<T> = Dispatch<SetStateAction<T>>;
+type Props = {
+ sessionsRef: Ref<Map<number, string>>; sessionNamesRef: Ref<Map<number, string>>;
+ chatsRef: Ref<Chat[]>; runningRef: Ref<Set<number>>; chatIdRef: Ref<number>;
+ pinsRef: Ref<Record<number, BrowserPin[]>>; activePathRef: Ref<string | null>;
+ groups: { remove(ids: number[]): void; groups: { ids: number[] }[] };
+ columnIds: number[]; activeId: number;
+ handleOf(id: number): string; setBusyFor(id: number, on: boolean): void;
+ setQueue(chat: number, queue: QueuedPrompt[]): void;
+ steerer: { finish(id: number): void };
+ setSessionIds: Setter<Record<number, string>>; setCommands: Setter<Record<number, AcpCommand[]>>;
+ setCancelError: Setter<Record<number, string>>; setPinsByChat: Setter<Record<number, BrowserPin[]>>;
+ setZoomedPane: Setter<number | null>; setChats: Setter<Chat[]>; setStored: Setter<StoredSession[]>;
+ openChat(id: number): void; focusChat(id: number): void;
+ openStored(name: string, cwd?: string): void; newChat(): void;
+ refreshStored(): Promise<void>;
+};
+
+/** Tab close, and the reopen stack behind it. Closing a tab retires its
+ * `graff acp` worker (`dispose`), so the first close of a tab that owns
+ * one asks; "Don't ask again" remembers the choice forever. */
+export function useChatClose(props: Props) {
+ const { sessionsRef, sessionNamesRef, chatsRef, runningRef, chatIdRef, pinsRef, activePathRef } = props;
+ const { groups, columnIds, activeId, handleOf, setBusyFor, setQueue, steerer } = props;
+ const { setSessionIds, setCommands, setCancelError, setPinsByChat, setZoomedPane, setChats, setStored } = props;
+ const { openChat, focusChat, openStored, newChat, refreshStored } = props;
+ // Closed tabs, oldest first, for the reopen shortcut.
+ const closedRef = useRef<{ session: string | null; cwd?: string; resumable: boolean }[]>([]);
+ const [dontAskAgain, setDontAskAgain] = useState(false);
+ const [pendingClose, setPendingClose] = useState<{ ids: number[]; workers: number; after?: () => void } | null>(null);
+ useEffect(() => {
+ setDontAskAgain(readCloseDontAsk(window.localStorage));
+ }, []);
+
+ const dropChat = (id: number) => {
+ sessionsRef.current.delete(id);
+ sessionNamesRef.current.delete(id);
+ runningRef.current.delete(id);
+ steerer.finish(id);
+ setQueue(id, []);
+ setSessionIds((current) => {
+ const { [id]: _gone, ...rest } = current;
+ return rest;
+ });
+ setBusyFor(id, false);
+ const { [id]: _pins, ...remainingPins } = pinsRef.current;
+ pinsRef.current = remainingPins; setPinsByChat(remainingPins);
+ setCommands(current => { const { [id]: _commands, ...rest } = current; return rest; });
+ setCancelError(current => { const { [id]: _error, ...rest } = current; return rest; });
+ void disposeSession(handleOf(id));
+ void browserClose(handleOf(id)).catch(() => undefined);
+ };
+
+ const doCloseChats = (ids: number[]) => {
+ const visible = columnIds.filter(pane => !ids.includes(pane));
+ groups.remove(ids); setZoomedPane(null);
+ for (const id of ids) {
+ const going = chatsRef.current.find(c => c.id === id);
+ if (going) closedRef.current = [...closedRef.current.slice(-9), {
+ session: going.session ?? null, cwd: going.cwd, resumable: going.messages.length > 0,
+ }];
+ dropChat(id);
+ }
+ const remaining = chatsRef.current.filter(c => !ids.includes(c.id));
+ chatsRef.current = remaining; setChats(remaining);
+ if (!remaining.length) { openChat(++chatIdRef.current); return; }
+ if (ids.includes(activeId)) focusChat(visible[0] ?? remaining[remaining.length - 1].id);
+ };
+
+ const closeChats = (ids: number[], after?: () => void) => {
+ const workers = closeWorkerCount(ids, (id) => sessionsRef.current.has(id));
+ if (shouldConfirmTabClose({ dontAskAgain, closingWorkers: workers })) {
+ setPendingClose({ ids, workers, after });
+ return;
+ }
+ doCloseChats(ids);
+ after?.();
+ };
+ const closeChat = (id: number) => closeChats([id]);
+ const closeTab = (id: number) => closeChats(groups.groups.find(group => group.ids.includes(id))?.ids ?? [id]);
+
+ const cancelPendingClose = () => setPendingClose(null);
+ const confirmPendingClose = (dontAsk: boolean) => {
+ if (dontAsk) {
+ writeCloseDontAsk(window.localStorage, true);
+ setDontAskAgain(true);
+ }
+ const closing = pendingClose;
+ setPendingClose(null);
+ if (closing) {
+ doCloseChats(closing.ids);
+ closing.after?.();
+ }
+ };
+
+ /** Bring back the tab that was closed last, resuming its graff session so
+ * the conversation comes back with it. A tab that never got a message has
+ * nothing saved, so it returns as a fresh one. */
+ const reopenClosed = () => {
+ const stack = closedRef.current;
+ const last = stack[stack.length - 1];
+ if (!last) return;
+ closedRef.current = stack.slice(0, -1);
+ if (last.session && last.resumable) void openStored(last.session, last.cwd);
+ else newChat();
+ };
+
+ /** Put a saved chat away, or remove it for good. Its tab closes with it,
+ * and the row goes at once rather than after the next poll. */
+ const dropStored = (name: string, archive: boolean) => {
+ const cwd = activePathRef.current ?? undefined;
+ const open = chatsRef.current.filter((c) => c.session === name && (c.cwd ?? null) === (cwd ?? null));
+ const remove = () => {
+ setStored((current) => current.filter((s) => s.name !== name));
+ void removeSession(name, { root: cwd, archive })
+ .catch(() => undefined)
+ .then(() => refreshStored());
+ };
+ if (open.length) closeChats(open.map(chat => chat.id), remove);
+ else remove();
+ };
+
+ return { closeChats, closeChat, closeTab, reopenClosed, dropStored, pendingClose, cancelPendingClose, confirmPendingClose };
+}
diff --git a/apps/native/lib/close-confirm.test.ts b/apps/native/lib/close-confirm.test.ts
new file mode 100644
index 00000000..5e105202
--- /dev/null
+++ b/apps/native/lib/close-confirm.test.ts
@@ -0,0 +1,68 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { CLOSE_DONT_ASK_KEY, closeWorkerCount, parseCloseDontAsk, readCloseDontAsk, shouldConfirmTabClose, writeCloseDontAsk } from "./close-confirm.ts";
+
+function memoryStorage(entries: Record<string, string> = {}) {
+ const store = new Map(Object.entries(entries));
+ return {
+ getItem: (key: string) => (store.has(key) ? store.get(key)! : null),
+ setItem: (key: string, value: string) => { store.set(key, value); },
+ };
+}
+
+function throwingStorage() {
+ return {
+ getItem: (_key: string): string | null => { throw new Error("storage unavailable"); },
+ setItem: (_key: string, _value: string) => { throw new Error("storage unavailable"); },
+ };
+}
+
+test("the stored choice parses the true forms and nothing else", () => {
+ assert.equal(parseCloseDontAsk(true), true);
+ assert.equal(parseCloseDontAsk("true"), true);
+ assert.equal(parseCloseDontAsk("1"), true);
+ assert.equal(parseCloseDontAsk(false), false);
+ assert.equal(parseCloseDontAsk("false"), false);
+ assert.equal(parseCloseDontAsk("0"), false);
+ assert.equal(parseCloseDontAsk(null), false);
+ assert.equal(parseCloseDontAsk(undefined), false);
+ assert.equal(parseCloseDontAsk("yes"), false);
+});
+
+test("a fresh profile asks; a remembered choice never does", () => {
+ assert.equal(shouldConfirmTabClose({ dontAskAgain: false, closingWorkers: 1 }), true);
+ assert.equal(shouldConfirmTabClose({ dontAskAgain: false, closingWorkers: 3 }), true);
+ assert.equal(shouldConfirmTabClose({ dontAskAgain: true, closingWorkers: 1 }), false);
+ assert.equal(shouldConfirmTabClose({ dontAskAgain: true, closingWorkers: 3 }), false);
+});
+
+test("tabs without a worker close silently even while the prompt is armed", () => {
+ assert.equal(shouldConfirmTabClose({ dontAskAgain: false, closingWorkers: 0 }), false);
+ assert.equal(shouldConfirmTabClose({ dontAskAgain: true, closingWorkers: 0 }), false);
+});
+
+test("only tabs with a live worker count toward the prompt", () => {
+ const live = new Set([2, 5]);
+ assert.equal(closeWorkerCount([1], (id) => live.has(id)), 0);
+ assert.equal(closeWorkerCount([2], (id) => live.has(id)), 1);
+ assert.equal(closeWorkerCount([1, 2, 5], (id) => live.has(id)), 2);
+ assert.equal(closeWorkerCount([], (id) => live.has(id)), 0);
+});
+
+test("the choice round-trips through storage under its own key", () => {
+ const storage = memoryStorage();
+ assert.equal(readCloseDontAsk(storage), false);
+ writeCloseDontAsk(storage, true);
+ assert.equal(storage.getItem(CLOSE_DONT_ASK_KEY), "true");
+ assert.equal(readCloseDontAsk(storage), true);
+ writeCloseDontAsk(storage, false);
+ assert.equal(readCloseDontAsk(storage), false);
+});
+
+test("unavailable storage asks every time instead of throwing", () => {
+ assert.equal(readCloseDontAsk(throwingStorage()), false);
+ assert.equal(readCloseDontAsk(null), false);
+ assert.equal(readCloseDontAsk(undefined), false);
+ assert.doesNotThrow(() => writeCloseDontAsk(throwingStorage(), true));
+ assert.doesNotThrow(() => writeCloseDontAsk(null, true));
+});
diff --git a/apps/native/lib/close-confirm.ts b/apps/native/lib/close-confirm.ts
new file mode 100644
index 00000000..408e9864
--- /dev/null
+++ b/apps/native/lib/close-confirm.ts
@@ -0,0 +1,38 @@
+/** The tab-close confirmation: closing a tab stops its `graff acp` worker,
+ * so the first close asks. "Don't ask again" remembers the choice forever;
+ * a tab with no worker never asks because there is nothing to stop. */
+
+export const CLOSE_DONT_ASK_KEY = "graff.close.dont-ask";
+
+export function parseCloseDontAsk(value: unknown): boolean {
+ return value === true || value === "true" || value === "1";
+}
+
+export type CloseAskStorage = Pick<Storage, "getItem" | "setItem">;
+
+export function readCloseDontAsk(storage?: CloseAskStorage | null): boolean {
+ try {
+ return parseCloseDontAsk(storage?.getItem(CLOSE_DONT_ASK_KEY));
+ } catch {
+ return false;
+ }
+}
+
+export function writeCloseDontAsk(storage: CloseAskStorage | null | undefined, value: boolean): void {
+ try {
+ storage?.setItem(CLOSE_DONT_ASK_KEY, value ? "true" : "false");
+ } catch {
+ /* Optional storage; the prompt simply asks again next time. */
+ }
+}
+
+/** How many of the closing tabs own a live worker. Tabs that never
+ * bootstrapped an agent (a fresh desktop tab before its first prompt)
+ * close silently. */
+export function closeWorkerCount(ids: number[], hasWorker: (id: number) => boolean): number {
+ return ids.filter(hasWorker).length;
+}
+
+export function shouldConfirmTabClose(args: { dontAskAgain: boolean; closingWorkers: number }): boolean {
+ return !args.dontAskAgain && args.closingWorkers > 0;
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index 7a0a7e37..02811f13 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/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/prompt-queue-resume.test.ts lib/streaming-code.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.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 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/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/prompt-queue-resume.test.ts lib/streaming-code.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.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",
"electron:build": "bash electron/build.sh",
"test:electron": "bun test electron/policy.test.cjs",
"test:webauthn": "node scripts/test-webauthn.mjs",