Skip to content

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

Python

Fix composer attach hang and model pick snap-back

Cursor Agentc5a28c7dd241
diff --git a/apps/native/components/primitives/ComposerMenu.tsx b/apps/native/components/primitives/ComposerMenu.tsx
index f75526f5..afcecaf0 100644
--- a/apps/native/components/primitives/ComposerMenu.tsx
+++ b/apps/native/components/primitives/ComposerMenu.tsx
@@ -1,6 +1,7 @@
"use client";
import { useLayoutEffect, useRef, useState, type RefObject } from "react";
import { createPortal } from "react-dom";
+import { attachRowKeepsUserActivation } from "@/lib/attachments";
import { Icon, GLYPHS, BRANDS, SOURCES } from "./prompt-demo";
type Row = { key: string; name: string; desc: string };
type Props = {
@@ -43,7 +44,7 @@ export default function ComposerMenu({ anchor, panel, id, menu, rows, query, act
const mark = source ? source.brand ? BRANDS[source.brand] : <Icon size={15}>{GLYPHS[source.glyph ?? "clip"]}</Icon>
: row.key.startsWith("file:") ? <Icon size={15}>{GLYPHS.file}</Icon> : null;
return <button key={row.key} id={`${id}-${i}`} type="button" role="option" aria-selected={i === active} title={`${row.name} — ${row.desc}`}
- onPointerDown={event => { event.preventDefault(); onPick(row); }} onPointerMove={() => {
+ onPointerDown={event => { if (!attachRowKeepsUserActivation(row.key)) event.preventDefault(); onPick(row); }} onPointerMove={() => {
if (active !== i) setActive(i);
if (!engaged) setEngaged(true);
}}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index ef2aae72..187d94b3 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -17,7 +17,8 @@ import HarnessChrome from "./HarnessChrome";
import ChatSplitLayout from "./ChatSplitLayout";
import { sidebarRecents } from "./harness-sidebar";
import { newPageToken, newSessionName, type Chat, type Msg } from "./harness-types";
-import { liveComposerKey } from "@/lib/composer-model";
+import { modelDisplayName, paneComposerKey } from "@/lib/composer-model";
+import { createModelSwitcher } from "./harness-model";
import { useBrowserVisibility } from "./useBrowserVisibility";
import { useReferenceNavigation } from "./useReferenceNavigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -145,6 +146,7 @@ export default function GraffHarness() {
const [cancelError, setCancelError] = useState<Record<number, string>>({});
// A model pick awaiting confirmation: switching respawns the tab's agent.
const [pendingModel, setPendingModel] = useState<{ key: string; chatId: number } | null>(null);
+ const pendingPickRef = useRef<{ 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.
@@ -177,7 +179,8 @@ export default function GraffHarness() {
};
const { adoptCatalog, requireSession, refreshStored, projectsReady } = useHarnessSessions({
- sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal
+ sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal,
+ pendingPick: () => pendingPickRef.current ?? pendingModel,
});
const { openPath, openReference } = useReferenceNavigation({
@@ -203,24 +206,11 @@ export default function GraffHarness() {
openChanges();
}, [filesOpen, fileRequest, openChanges]);
- /** Respawn this tab's agent on `key` and reload its conversation: the
- * `--resume` target carries the history across, so the switch keeps the chat
- * instead of starting it over. New tabs inherit the pick. */
- const applyModel = (key: string, chatId: number) => {
- void requireSession(chatId, true, key)
- .catch(error => setCancelError(current => ({ ...current, [chatId]: error instanceof Error ? error.message : "Could not switch model" })));
- };
-
- const changeModel = (key: string, forChat?: number) => {
- const chatId = forChat ?? chatThread.id;
- // A tab with a conversation (or a turn in flight) has state to reload, so
- // confirm the restart first; an empty tab has nothing to carry over.
- const chat = chatsRef.current.find(c => c.id === chatId);
- if ((chat?.messages.length ?? 0) > 0 || runningRef.current.has(chatId)) setPendingModel({ key, chatId });
- else applyModel(key, chatId);
- };
-
- const modelLabel = (key: string | null | undefined) => models.find(m => m.key === key)?.name ?? key ?? "the current model";
+ const { changeModel, cancelPending, confirmPending } = createModelSwitcher({
+ chatsRef, runningRef, pendingPickRef, activeChatId: () => chatThread.id,
+ requireSession, setChatModel, setCancelError, setPendingModel,
+ });
+ const modelLabel = (key: string | null | undefined) => modelDisplayName(models, key);
const runPrompt = createPromptRunner({ onStarted: started, onCompleted: completed,
runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, adoptCatalog, refreshStored, takeQueuedPrompt, setCancelError
@@ -465,7 +455,7 @@ export default function GraffHarness() {
chatsRef.current = next; setChats(next);
}}
prompt={{ demo: false, models, commands: commands[thread.id] ?? catalogCommands,
- root: cwdOf(thread), modelKey: liveComposerKey(thread.model, model, sessionsRef.current.has(thread.id)),
+ root: cwdOf(thread), modelKey: paneComposerKey(thread.model, model, sessionsRef.current.has(thread.id), pendingModel, thread.id),
onModelChange: key => changeModel(key, thread.id), onSend: text => void send(text, thread.id),
onSetting: text => settings.change(thread.id, text),
onSteerQueued: () => steerOrInterrupt(queuesRef.current[thread.id]?.[0], runningRef.current.has(thread.id), id => steerQueued(thread.id, id), () => {
@@ -619,8 +609,8 @@ export default function GraffHarness() {
<ModelSwitchDialog
from={modelLabel(chatsRef.current.find(c => c.id === pendingModel.chatId)?.model ?? model)}
to={modelLabel(pendingModel.key)}
- onCancel={() => setPendingModel(null)}
- onConfirm={() => { const picked = pendingModel; setPendingModel(null); applyModel(picked.key, picked.chatId); }}
+ onCancel={cancelPending}
+ onConfirm={() => confirmPending(pendingModel)}
/>
)}
{dialog && (
diff --git a/apps/native/components/site/ModelSwitchDialog.tsx b/apps/native/components/site/ModelSwitchDialog.tsx
index d6dd2dc2..10050213 100644
--- a/apps/native/components/site/ModelSwitchDialog.tsx
+++ b/apps/native/components/site/ModelSwitchDialog.tsx
@@ -72,7 +72,7 @@ export default function ModelSwitchDialog({ from, to, onCancel, onConfirm }: Pro
return createPortal(
<div
- className="fixed inset-0 z-[60] flex items-center justify-center p-4"
+ className="fixed inset-0 z-[300] 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();
diff --git a/apps/native/components/site/harness-model.ts b/apps/native/components/site/harness-model.ts
new file mode 100644
index 00000000..71659f48
--- /dev/null
+++ b/apps/native/components/site/harness-model.ts
@@ -0,0 +1,54 @@
+import type { Dispatch, MutableRefObject, SetStateAction } from "react";
+import { shouldConfirmModelSwitch } from "@/lib/composer-model";
+import type { Chat } from "./harness-types";
+
+export type PendingModel = { key: string; chatId: number };
+
+/** Respawn and confirm stay out of GraffHarness so the shell does not grow. */
+export function createModelSwitcher(opts: {
+ chatsRef: MutableRefObject<Chat[]>;
+ runningRef: MutableRefObject<Set<number>>;
+ pendingPickRef: MutableRefObject<PendingModel | null>;
+ activeChatId(): number;
+ requireSession(id: number, reset?: boolean, key?: string): Promise<string>;
+ setChatModel(id: number, key: string): void;
+ setCancelError: Dispatch<SetStateAction<Record<number, string>>>;
+ setPendingModel: Dispatch<SetStateAction<PendingModel | null>>;
+}) {
+ const lock = (pick: PendingModel | null) => {
+ opts.pendingPickRef.current = pick;
+ };
+ const applyModel = (key: string, chatId: number) => {
+ lock({ key, chatId });
+ opts.setChatModel(chatId, key);
+ void opts.requireSession(chatId, true, key)
+ .catch((error) => opts.setCancelError((current) => ({
+ ...current,
+ [chatId]: error instanceof Error ? error.message : "Could not switch model",
+ })))
+ .finally(() => {
+ if (opts.pendingPickRef.current?.chatId === chatId && opts.pendingPickRef.current.key === key) {
+ lock(null);
+ }
+ });
+ };
+ const changeModel = (key: string, forChat?: number) => {
+ const chatId = forChat ?? opts.activeChatId();
+ const chat = opts.chatsRef.current.find((c) => c.id === chatId);
+ lock({ key, chatId });
+ if (shouldConfirmModelSwitch(chat?.messages.length ?? 0, opts.runningRef.current.has(chatId))) {
+ opts.setPendingModel({ key, chatId });
+ return;
+ }
+ applyModel(key, chatId);
+ };
+ const cancelPending = () => {
+ lock(null);
+ opts.setPendingModel(null);
+ };
+ const confirmPending = (picked: PendingModel) => {
+ opts.setPendingModel(null);
+ applyModel(picked.key, picked.chatId);
+ };
+ return { applyModel, changeModel, cancelPending, confirmPending };
+}
diff --git a/apps/native/components/site/idle-peer-turns.ts b/apps/native/components/site/idle-peer-turns.ts
index 6e048890..b4c483e6 100644
--- a/apps/native/components/site/idle-peer-turns.ts
+++ b/apps/native/components/site/idle-peer-turns.ts
@@ -1,8 +1,11 @@
import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
import { idleUpdates, type ChatHandle } from "@/lib/acp-client";
+import { holdWhileIdle, waitWhile } from "@/lib/idle-http";
import type { Chat } from "./harness-types";
-/** Paint unsolicited ACP session/update while a tab is idle (#1007). */
+/** Paint unsolicited ACP session/update while a tab is idle (#1007).
+ * The idle HTTP stream is dropped for the duration of a prompt turn so
+ * attach and other POSTs can use the origin's connection slots (#1068). */
export async function pumpIdlePeerTurns(opts: {
chatId: number;
handle: ChatHandle;
@@ -12,34 +15,45 @@ export async function pumpIdlePeerTurns(opts: {
setChats(update: (current: Chat[]) => Chat[]): void;
}): Promise<void> {
let asstId: number | undefined;
- try {
- for await (const update of idleUpdates(opts.handle, opts.sessionId, opts.signal)) {
- if (opts.running() || opts.signal.aborted) continue;
- opts.setChats(current => current.map(chat => {
- if (chat.id !== opts.chatId) return chat;
- const existing = asstId != null
- ? chat.messages.find(message => message.role === "assistant" && message.id === asstId)
- : undefined;
- let messages = chat.messages;
- let id = asstId;
- let turn: AssistantTurn = existing && existing.role === "assistant" ? existing.turn : emptyTurn();
- if (!existing) {
- id = Date.now();
- asstId = id;
- messages = [...chat.messages, { id, role: "assistant", turn }];
- }
- turn = applyAcpUpdate(turn, update);
- if (update.sessionUpdate === "gui_turn_end") {
- turn = finishAcpTurn(turn);
- asstId = undefined;
- }
- return {
- ...chat,
- messages: messages.map(message => message.role === "assistant" && message.id === id ? { ...message, turn } : message),
- };
- }));
- }
- } catch {
+ const paint = (update: Parameters<typeof applyAcpUpdate>[1]) => {
+ if (opts.running() || opts.signal.aborted) return;
+ opts.setChats(current => current.map(chat => {
+ if (chat.id !== opts.chatId) return chat;
+ const existing = asstId != null
+ ? chat.messages.find(message => message.role === "assistant" && message.id === asstId)
+ : undefined;
+ let messages = chat.messages;
+ let id = asstId;
+ let turn: AssistantTurn = existing && existing.role === "assistant" ? existing.turn : emptyTurn();
+ if (!existing) {
+ id = Date.now();
+ asstId = id;
+ messages = [...chat.messages, { id, role: "assistant", turn }];
+ }
+ turn = applyAcpUpdate(turn, update);
+ if (update.sessionUpdate === "gui_turn_end") {
+ turn = finishAcpTurn(turn);
+ asstId = undefined;
+ }
+ return {
+ ...chat,
+ messages: messages.map(message => message.role === "assistant" && message.id === id ? { ...message, turn } : message),
+ };
+ }));
+ };
+
+ while (!opts.signal.aborted) {
+ await waitWhile(() => opts.running(), opts.signal);
if (opts.signal.aborted) return;
+ const result = await holdWhileIdle({
+ signal: opts.signal,
+ busy: opts.running,
+ open: async (signal) => {
+ for await (const update of idleUpdates(opts.handle, opts.sessionId, signal)) {
+ paint(update);
+ }
+ },
+ });
+ if (result !== "paused") return;
}
}
diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.ts
index 4310781a..a523b068 100644
--- a/apps/native/components/site/useHarnessSessions.ts
+++ b/apps/native/components/site/useHarnessSessions.ts
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, type MutableRefObject, type Dispatch, type SetStateAction } from "react";
import { bindMcpAppChat, checkHealth, disposePage, ensureSession, fetchModels, type Health } from "@/lib/acp-client";
-import { sameModels } from "@/lib/composer-model";
+import { catalogMayWriteChatModel, catalogMayWriteGlobalKey, sameModels } from "@/lib/composer-model";
import { pumpIdlePeerTurns } from "./idle-peer-turns";
import type { AcpCommand } from "@/lib/acp";
import type { PromptModel } from "@/components/primitives/PromptBar";
@@ -20,10 +20,13 @@ type Props = {
setSessionIds: Setter<Record<number, string>>; setHealth: Setter<Health | null>;
setWorkspaces: Setter<Workspace[]>; setActivePath: Setter<string | null>;
setChats: Setter<Chat[]>; setStored: Setter<StoredSession[]>; setStoredTotal: Setter<number>;
+ pendingPick(): { key: string; chatId: number } | null;
};
const SIDEBAR_PAGE = 12;
-export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal}: Props) {
+export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal, pendingPick}: Props) {
const [projectsReady, setProjectsReady] = useState(false);
+ const pendingRef = useRef(pendingPick);
+ pendingRef.current = pendingPick;
const idleCtl = useRef(new Map<number, AbortController>());
const watchIdle = (chatId: number, sessionId: string) => {
idleCtl.current.get(chatId)?.abort();
@@ -43,9 +46,10 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
if (available?.length) { setCatalogCommands(available); setCommands(old => ({ ...old, [chatId]: available })); }
if (current && handle) {
const chat = chatsRef.current.find((c) => c.id === chatId);
- if (chat?.model !== current) setChatModel(chatId, current);
- setModelKey((key) => (key === current ? key : current));
- } else if (current) {
+ if (catalogMayWriteChatModel(chatId, pendingRef.current()) && chat?.model !== current) {
+ setChatModel(chatId, current);
+ }
+ } else if (current && catalogMayWriteGlobalKey(false)) {
setModelKey((key) => key ?? current);
}
} catch {
diff --git a/apps/native/lib/attachments.test.ts b/apps/native/lib/attachments.test.ts
index 6e34a3eb..9c3cc046 100644
--- a/apps/native/lib/attachments.test.ts
+++ b/apps/native/lib/attachments.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { filesFrom, isImageFile, liftAttachmentMarkers, marker, markerName, splitImageMarkers, withAttachmentMarkers, type Attachment } from "./attachments.ts";
+import { attachRowKeepsUserActivation, filesFrom, isImageFile, liftAttachmentMarkers, marker, markerName, splitImageMarkers, uploadAttachment, withAttachmentMarkers, type Attachment } from "./attachments.ts";
const shot: Attachment = { id: "/tmp/a/shot.png", name: "shot.png", path: "/tmp/a/shot.png" };
const notes: Attachment = { id: "/tmp/a/notes.md", name: "notes.md", path: "/tmp/a/notes.md" };
@@ -82,3 +82,24 @@ test("a paste carrying only text yields nothing, so the composer lets it through
assert.deepEqual(filesFrom(textOnly), []);
assert.deepEqual(filesFrom(null), []);
});
+
+test("the attach row keeps the pointer gesture so the file dialog can open", () => {
+ assert.equal(attachRowKeepsUserActivation("attach"), true);
+ assert.equal(attachRowKeepsUserActivation("file:notes.md"), false);
+});
+
+test("uploadAttachment times out instead of hanging the composer", async () => {
+ const file = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (_url: unknown, init?: { signal?: AbortSignal }) => {
+ await new Promise((_, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason ?? new DOMException("aborted", "AbortError")), { once: true });
+ });
+ throw new Error("unreachable");
+ }) as typeof fetch;
+ try {
+ await assert.rejects(() => uploadAttachment(file, 20), /timed out/);
+ } finally {
+ globalThis.fetch = original;
+ }
+});
diff --git a/apps/native/lib/attachments.ts b/apps/native/lib/attachments.ts
index f8d4cb31..cecf1ef6 100644
--- a/apps/native/lib/attachments.ts
+++ b/apps/native/lib/attachments.ts
@@ -45,11 +45,31 @@ export function filesFrom(data: DataTransfer | null | undefined): File[] {
return out;
}
+/** File-picker rows must keep the user gesture; preventDefault drops it. */
+export function attachRowKeepsUserActivation(rowKey: string): boolean {
+ return rowKey === "attach";
+}
+
+/** Generous: a large paste should finish, but a hung HTTP/1.1 slot must not. */
+export const ATTACH_TIMEOUT_MS = 30_000;
+
+function attachFailure(err: unknown): Error {
+ if (err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError")) {
+ return new Error("Adding the file timed out. Try again.");
+ }
+ return err instanceof Error ? err : new Error(String(err));
+}
+
/** Write one file to the harness-readable temp directory and describe it. */
-export async function uploadAttachment(file: File): Promise<Attachment> {
+export async function uploadAttachment(file: File, timeoutMs = ATTACH_TIMEOUT_MS): Promise<Attachment> {
const body = new FormData();
body.append("file", file);
- const res = await fetch("/api/attach", { method: "POST", body });
+ let res: Response;
+ try {
+ res = await fetch("/api/attach", { method: "POST", body, signal: AbortSignal.timeout(timeoutMs) });
+ } catch (err) {
+ throw attachFailure(err);
+ }
const json = (await res.json()) as { path?: string; name?: string; error?: string };
if (!res.ok || !json.path) throw new Error(json.error ?? `attach failed (${res.status})`);
return {
diff --git a/apps/native/lib/composer-model.test.ts b/apps/native/lib/composer-model.test.ts
index 0d3d2505..55accbef 100644
--- a/apps/native/lib/composer-model.test.ts
+++ b/apps/native/lib/composer-model.test.ts
@@ -4,7 +4,17 @@ import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { modelChoices } from "./acp-client";
-import { liveComposerKey, pillFromAcp, resolveComposerModel, sameModels } from "./composer-model";
+import {
+ catalogMayWriteChatModel,
+ catalogMayWriteGlobalKey,
+ liveComposerKey,
+ modelDisplayName,
+ paneComposerKey,
+ pillFromAcp,
+ resolveComposerModel,
+ sameModels,
+ shouldConfirmModelSwitch,
+} from "./composer-model";
test("the pill keeps an unknown live key instead of catalog[0]", () => {
const decoy = { key: "catalog-zero", name: "catalog-zero" };
@@ -19,6 +29,27 @@ test("a tab with an agent does not inherit another chat's global pick", () => {
expect(liveComposerKey(undefined, "catalog-zero", false)).toBe("catalog-zero");
});
+test("a pending pick owns the pane pill until the new agent answers", () => {
+ expect(paneComposerKey("glm-5.3-flash", "glm-5.3-flash", true, { chatId: 2, key: "grok-4.6" }, 2)).toBe("grok-4.6");
+ expect(paneComposerKey("glm-5.3-flash", "glm-5.3-flash", true, { chatId: 2, key: "grok-4.6" }, 1)).toBe("glm-5.3-flash");
+});
+
+test("catalog refresh does not overwrite a pending pick or the global inherit", () => {
+ expect(catalogMayWriteChatModel(2, { chatId: 2 })).toBe(false);
+ expect(catalogMayWriteChatModel(1, { chatId: 2 })).toBe(true);
+ expect(catalogMayWriteChatModel(1, null)).toBe(true);
+ expect(catalogMayWriteGlobalKey(true)).toBe(false);
+ expect(catalogMayWriteGlobalKey(false)).toBe(true);
+});
+
+test("a chat with history or a running turn confirms before respawn", () => {
+ expect(shouldConfirmModelSwitch(1, false)).toBe(true);
+ expect(shouldConfirmModelSwitch(0, true)).toBe(true);
+ expect(shouldConfirmModelSwitch(0, false)).toBe(false);
+ expect(modelDisplayName([{ key: "a", name: "Alpha" }], "a")).toBe("Alpha");
+ expect(modelDisplayName([], null)).toBe("the current model");
+});
+
test("sameModels ignores a new array of the same rows", () => {
const row = { key: "running-live", name: "running-live" };
expect(sameModels([row], [{ ...row }])).toBe(true);
diff --git a/apps/native/lib/composer-model.ts b/apps/native/lib/composer-model.ts
index 4721fedb..2582236b 100644
--- a/apps/native/lib/composer-model.ts
+++ b/apps/native/lib/composer-model.ts
@@ -17,6 +17,39 @@ export function liveComposerKey(
return globalModel ?? undefined;
}
+/** A confirmed or in-flight pick owns the pill until the new agent answers. */
+export function paneComposerKey(
+ threadModel: string | undefined,
+ globalModel: string | null | undefined,
+ hasAgent: boolean,
+ pending?: { chatId: number; key: string } | null,
+ chatId?: number,
+): string | undefined {
+ if (pending && chatId === pending.chatId) return pending.key;
+ return liveComposerKey(threadModel, globalModel, hasAgent);
+}
+
+/** Catalog refresh must not overwrite the chat the user is switching. */
+export function catalogMayWriteChatModel(
+ chatId: number,
+ pending?: { chatId: number } | null,
+): boolean {
+ return pending?.chatId !== chatId;
+}
+
+/** An existing agent's `current` is that chat's model, not the global inherit. */
+export function catalogMayWriteGlobalKey(hasAgent: boolean): boolean {
+ return !hasAgent;
+}
+
+export function shouldConfirmModelSwitch(messageCount: number, running: boolean): boolean {
+ return messageCount > 0 || running;
+}
+
+export function modelDisplayName(models: { key: string; name: string }[], key: string | null | undefined): string {
+ return models.find((m) => m.key === key)?.name ?? key ?? "the current model";
+}
+
/** Pill after a `graff/models` reply. `current` is the agent; the catalog only prettifies it. */
export function pillFromAcp(
models: ModelChoice[],
diff --git a/apps/native/lib/idle-http.test.ts b/apps/native/lib/idle-http.test.ts
new file mode 100644
index 00000000..72c3bc88
--- /dev/null
+++ b/apps/native/lib/idle-http.test.ts
@@ -0,0 +1,53 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { holdWhileIdle, waitWhile } from "./idle-http.ts";
+
+test("waitWhile returns immediately when idle", async () => {
+ const ac = new AbortController();
+ await waitWhile(() => false, ac.signal);
+ assert.equal(ac.signal.aborted, false);
+});
+
+test("waitWhile yields once busy clears", async () => {
+ const ac = new AbortController();
+ let busy = true;
+ const waited = waitWhile(() => busy, ac.signal, 10);
+ setTimeout(() => {
+ busy = false;
+ }, 25);
+ await waited;
+ assert.equal(busy, false);
+});
+
+test("holdWhileIdle aborts the open stream when a turn starts", async () => {
+ const ac = new AbortController();
+ let busy = false;
+ let opened = 0;
+ let aborted = false;
+ const held = holdWhileIdle({
+ signal: ac.signal,
+ busy: () => busy,
+ pollMs: 10,
+ open: (signal) => new Promise((_, reject) => {
+ opened += 1;
+ signal.addEventListener("abort", () => {
+ aborted = true;
+ reject(new DOMException("aborted", "AbortError"));
+ }, { once: true });
+ }),
+ });
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ assert.equal(opened, 1);
+ busy = true;
+ assert.equal(await held, "paused");
+ assert.equal(aborted, true);
+});
+
+test("holdWhileIdle reports ended when the stream finishes while idle", async () => {
+ const ac = new AbortController();
+ assert.equal(await holdWhileIdle({
+ signal: ac.signal,
+ busy: () => false,
+ open: async () => {},
+ }), "ended");
+});
diff --git a/apps/native/lib/idle-http.ts b/apps/native/lib/idle-http.ts
new file mode 100644
index 00000000..54abb81d
--- /dev/null
+++ b/apps/native/lib/idle-http.ts
@@ -0,0 +1,52 @@
+/** Long-lived idle fetches must yield the HTTP/1.1 slot when a turn starts.
+ * Chromium caps six connections per origin; a split of prompt streams plus
+ * idle SSE saturates it and `/api/attach` never starts (#1068). */
+
+export type IdleHoldResult = "paused" | "ended" | "aborted";
+
+export function waitWhile(busy: () => boolean, signal: AbortSignal, stepMs = 50): Promise<void> {
+ return new Promise((resolve) => {
+ if (!busy() || signal.aborted) {
+ resolve();
+ return;
+ }
+ const tick = () => {
+ if (!busy() || signal.aborted) {
+ clearInterval(id);
+ signal.removeEventListener("abort", stop);
+ resolve();
+ }
+ };
+ const stop = () => tick();
+ const id = setInterval(tick, stepMs);
+ signal.addEventListener("abort", stop, { once: true });
+ });
+}
+
+/** Run `open` until it ends, the caller aborts, or `busy` becomes true. */
+export async function holdWhileIdle(opts: {
+ signal: AbortSignal;
+ busy(): boolean;
+ open(signal: AbortSignal): Promise<void>;
+ pollMs?: number;
+}): Promise<IdleHoldResult> {
+ if (opts.signal.aborted) return "aborted";
+ if (opts.busy()) return "paused";
+ const hold = new AbortController();
+ const stop = () => hold.abort();
+ opts.signal.addEventListener("abort", stop, { once: true });
+ const poll = setInterval(() => {
+ if (opts.busy()) hold.abort();
+ }, opts.pollMs ?? 50);
+ try {
+ await opts.open(hold.signal);
+ } catch {
+ /* caller maps abort / stream errors to the result below */
+ } finally {
+ clearInterval(poll);
+ opts.signal.removeEventListener("abort", stop);
+ }
+ if (opts.signal.aborted) return "aborted";
+ if (opts.busy() || hold.signal.aborted) return "paused";
+ return "ended";
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index 7a0a7e37..0f43179a 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/idle-http.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",
"electron:build": "bash electron/build.sh",
"test:electron": "bun test electron/policy.test.cjs",
"test:webauthn": "node scripts/test-webauthn.mjs",