Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): apply model/effort picks optimistically (#1572)

Call White8a1ea7b2760d
diff --git a/ui/src/components/workbench/AgentRoutePicker.test.tsx b/ui/src/components/workbench/AgentRoutePicker.test.tsx
new file mode 100644
index 000000000..f1b731970
--- /dev/null
+++ b/ui/src/components/workbench/AgentRoutePicker.test.tsx
@@ -0,0 +1,192 @@
+/* @vitest-environment jsdom */
+
+import { useState } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router-dom';
+
+import type { VibeAgentBrief } from '../../context/ApiContext';
+import { AgentRoutePicker } from './AgentRoutePicker';
+import type { AgentRoutePatch, AgentRouteValue } from './AgentRoutePicker';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('../../context/ApiContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../context/ApiContext')>()),
+ useApi: () => ({}),
+}));
+
+// The model column is fetched per backend; serve it synchronously so the test is
+// about the route state, not about the catalog request.
+vi.mock('../../lib/backendModels', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../lib/backendModels')>()),
+ loadBackendModelsWithRefresh: (
+ _api: unknown,
+ _backend: string,
+ onLoaded: (payload: {
+ models: string[];
+ modelLabels: Record<string, string>;
+ reasoningOptions: Record<string, { value: string; label: string }[]>;
+ catalogRefreshPending: boolean;
+ }) => void,
+ ) => {
+ onLoaded({
+ models: ['sonnet', 'opus'],
+ modelLabels: {},
+ reasoningOptions: {},
+ catalogRefreshPending: false,
+ });
+ return () => {};
+ },
+}));
+
+const agent = (over: Partial<VibeAgentBrief> = {}): VibeAgentBrief =>
+ ({
+ id: 'agt-claude',
+ name: 'claude',
+ display_name: 'claude',
+ description: null,
+ backend: 'claude',
+ model: 'sonnet',
+ reasoning_effort: null,
+ enabled: true,
+ archived: false,
+ archived_at: null,
+ source: 'builtin',
+ updated_at: '2026-08-19T00:00:00Z',
+ ...over,
+ }) as VibeAgentBrief;
+
+const AGENTS = [agent(), agent({ id: 'agt-codex', name: 'codex', display_name: 'codex', backend: 'codex', model: 'gpt' })];
+
+const CLAUDE_ROUTE: AgentRouteValue = {
+ agent_name: 'claude',
+ agent_id: 'agt-claude',
+ agent_backend: 'claude',
+ agent_variant: 'claude',
+ model: 'sonnet',
+ reasoning_effort: 'low',
+};
+
+// The picker holds no selection of its own, so its highlight is whatever the
+// owner passes back as `value`. This stands in for an owner whose write is
+// async: the pick lands in local state within the click and `saving` stays on
+// until the test releases it — exactly what the two workbench owners now do.
+const OptimisticOwner: React.FC<{
+ initial?: AgentRouteValue;
+ isDefaultRoute?: boolean;
+ defaultRoute?: AgentRouteValue;
+ defaultLabel?: string;
+ onWrite: (patch: AgentRoutePatch) => void;
+}> = ({ initial = CLAUDE_ROUTE, isDefaultRoute, defaultRoute, defaultLabel, onWrite }) => {
+ const [route, setRoute] = useState<AgentRouteValue>(initial);
+ const [saving, setSaving] = useState(false);
+ return (
+ <MemoryRouter>
+ <AgentRoutePicker
+ value={route}
+ agents={AGENTS}
+ saving={saving}
+ isDefaultRoute={isDefaultRoute}
+ defaultRoute={defaultRoute}
+ defaultLabel={defaultLabel}
+ onChange={(patch) => {
+ setRoute((prev) => ({ ...prev, ...patch }));
+ setSaving(true);
+ onWrite(patch);
+ }}
+ />
+ </MemoryRouter>
+ );
+};
+
+// The highlight IS the checkmark in this menu: the active row carries the cyan
+// wash from `RouteItem`.
+const highlighted = (label: string) => {
+ const item = screen.getByRole('button', { name: label });
+ return item.className.includes('bg-cyan/[0.10]');
+};
+
+const openMenu = async (user: ReturnType<typeof userEvent.setup>) => {
+ await user.click(screen.getByRole('button', { name: /claude/ }));
+ await screen.findByText('chat.picker.model');
+};
+
+describe('AgentRoutePicker', () => {
+ afterEach(cleanup);
+
+ it('highlights the pick while the owner write is still in flight', async () => {
+ const user = userEvent.setup();
+ const onWrite = vi.fn();
+ render(<OptimisticOwner onWrite={onWrite} />);
+ await openMenu(user);
+ expect(highlighted('sonnet')).toBe(true);
+
+ await user.click(screen.getByRole('button', { name: 'opus' }));
+
+ // The write has not resolved — nothing here ever resolves it — and the
+ // highlight has already moved.
+ expect(onWrite).toHaveBeenCalledExactlyOnceWith({ model: 'opus' });
+ expect(highlighted('opus')).toBe(true);
+ expect(highlighted('sonnet')).toBe(false);
+ });
+
+ it('keeps the menu clickable while a write is in flight, so the next pick is not lost', async () => {
+ const user = userEvent.setup();
+ const onWrite = vi.fn();
+ render(<OptimisticOwner onWrite={onWrite} />);
+ await openMenu(user);
+
+ await user.click(screen.getByRole('button', { name: 'opus' }));
+ const effort = screen.getByRole('button', { name: 'chat.picker.effortOptions.high' });
+ // A disabled row would fire no click at all, which is how the previous
+ // greyed-out panel dropped the effort a user picked right after a model.
+ expect((effort as HTMLButtonElement).disabled).toBe(false);
+ await user.click(effort);
+
+ expect(onWrite).toHaveBeenNthCalledWith(2, { reasoning_effort: 'high' });
+ expect(highlighted('opus')).toBe(true);
+ expect(highlighted('chat.picker.effortOptions.high')).toBe(true);
+ });
+
+ it('shows the in-flight indicator on the trigger instead of greying the panel', async () => {
+ const user = userEvent.setup();
+ render(<OptimisticOwner onWrite={vi.fn()} />);
+ expect(screen.queryByLabelText('common.saving')).toBeNull();
+
+ await openMenu(user);
+ await user.click(screen.getByRole('button', { name: 'opus' }));
+
+ expect(screen.getByLabelText('common.saving')).toBeTruthy();
+ });
+
+ it('pins the whole inherited route when a model is picked on a default route', async () => {
+ const user = userEvent.setup();
+ const onWrite = vi.fn();
+ render(
+ <OptimisticOwner
+ initial={{}}
+ isDefaultRoute
+ defaultRoute={CLAUDE_ROUTE}
+ defaultLabel="default"
+ onWrite={onWrite}
+ />,
+ );
+ await openMenu(user);
+
+ await user.click(screen.getByRole('button', { name: 'opus' }));
+
+ // A bare {model} would leave the owner storing a model against no Agent.
+ expect(onWrite).toHaveBeenCalledExactlyOnceWith({
+ agent_name: 'claude',
+ agent_id: 'agt-claude',
+ agent_backend: 'claude',
+ agent_variant: 'claude',
+ model: 'opus',
+ reasoning_effort: 'low',
+ });
+ });
+});
diff --git a/ui/src/components/workbench/AgentRoutePicker.tsx b/ui/src/components/workbench/AgentRoutePicker.tsx
index 0dd55b1ea..af93f76a8 100644
--- a/ui/src/components/workbench/AgentRoutePicker.tsx
+++ b/ui/src/components/workbench/AgentRoutePicker.tsx
@@ -32,7 +32,11 @@ export interface AgentRoutePatch extends AgentRouteValue {
interface AgentRoutePickerProps {
value: AgentRouteValue;
agents: VibeAgentBrief[];
- onChange: (patch: AgentRoutePatch) => void | Promise<void>;
+ /** Applied by the OWNER, synchronously. An owner whose write is async applies
+ * the pick to its own state first and persists behind it (see `saving`) —
+ * the picker holds no selection of its own, so anything it waits for is a
+ * highlight the user watches lag behind their click. */
+ onChange: (patch: AgentRoutePatch) => void;
/** Optional backend allow-list for existing sessions whose backend is pinned. */
allowedBackends?: string[];
/** Trigger label when no agent is selected — the create flow shows "默认 · …". */
@@ -41,6 +45,10 @@ interface AgentRoutePickerProps {
defaultRoute?: AgentRouteValue;
/** True when the displayed route is inherited, not persisted on this session/project yet. */
isDefaultRoute?: boolean;
+ /** An owner-side write is in flight — shown as a spinner on the trigger. The
+ * menu stays live: the local state already moved, so further picks queue
+ * behind it instead of being locked out until the request lands. */
+ saving?: boolean;
disabled?: boolean;
align?: 'start' | 'end';
/** Override the trigger width (chat caps at 62%; the create surfaces go full width). */
@@ -74,6 +82,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
defaultLabel,
defaultRoute,
isDefaultRoute,
+ saving,
disabled,
align = 'end',
triggerClassName,
@@ -92,7 +101,6 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
>({});
const loadedModelBackendsRef = useRef<Set<string>>(new Set());
const [loadingModels, setLoadingModels] = useState(false);
- const [patching, setPatching] = useState(false);
// Free-text filter for the model column — long backends (OpenCode) list dozens.
const [modelQuery, setModelQuery] = useState('');
@@ -103,39 +111,38 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
? agents.find((agent) => agent.name === displayValue.agent_name) || null
: null;
- // Serialize patches: an agent pick carries its default model/effort, so if it
- // resolves AFTER a later model/effort pick the later choice would be rolled
- // back. One patch at a time, items disabled while it's in flight.
+ // Emit the pick straight to the owner: an owner with an async write applies it
+ // locally and queues the request, so ordering is settled where the state lives
+ // (an Agent pick carries that Agent's default model/effort, and an earlier
+ // request landing last would undo a newer model pick). Blocking here would
+ // only delay the highlight — and lock out the very next click.
const applyPatch = useCallback(
- async (changes: AgentRoutePatch) => {
- if (patching) return;
- setPatching(true);
- try {
- const patchPinsDisplayedDefault =
- routeIsDefault &&
- Boolean(displayValue.agent_name || displayValue.agent_backend) &&
- !('agent_name' in changes) &&
- !('agent_backend' in changes) &&
- !('agent_id' in changes) &&
- !('agent_variant' in changes);
- await onChange(
- patchPinsDisplayedDefault
- ? {
- agent_name: displayValue.agent_name ?? null,
- agent_id: displayValue.agent_id ?? null,
- agent_backend: displayedAgent?.backend ?? displayValue.agent_backend ?? null,
- agent_variant: displayValue.agent_variant ?? displayedAgent?.backend ?? displayValue.agent_backend ?? null,
- model: displayValue.model ?? null,
- reasoning_effort: displayValue.reasoning_effort ?? null,
- ...changes,
- }
- : changes,
- );
- } finally {
- setPatching(false);
- }
+ (changes: AgentRoutePatch) => {
+ // Picking a model/effort on an INHERITED route must persist the whole
+ // displayed route, not just the changed field: otherwise the owner stores
+ // a bare model against no Agent at all.
+ const patchPinsDisplayedDefault =
+ routeIsDefault &&
+ Boolean(displayValue.agent_name || displayValue.agent_backend) &&
+ !('agent_name' in changes) &&
+ !('agent_backend' in changes) &&
+ !('agent_id' in changes) &&
+ !('agent_variant' in changes);
+ onChange(
+ patchPinsDisplayedDefault
+ ? {
+ agent_name: displayValue.agent_name ?? null,
+ agent_id: displayValue.agent_id ?? null,
+ agent_backend: displayedAgent?.backend ?? displayValue.agent_backend ?? null,
+ agent_variant: displayValue.agent_variant ?? displayedAgent?.backend ?? displayValue.agent_backend ?? null,
+ model: displayValue.model ?? null,
+ reasoning_effort: displayValue.reasoning_effort ?? null,
+ ...changes,
+ }
+ : changes,
+ );
},
- [displayValue, displayedAgent, patching, onChange, routeIsDefault],
+ [displayValue, displayedAgent, onChange, routeIsDefault],
);
const backend = displayValue.agent_backend || displayedAgent?.backend || '';
@@ -290,7 +297,14 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
</span>
</>
)}
- <ChevronDown className="ml-auto size-3 shrink-0 text-muted" />
+ {/* In-flight feedback replaces the chevron rather than greying the menu:
+ the pick is already applied, so the user is watching a save, not
+ waiting for their click to take effect. */}
+ {saving ? (
+ <Loader2 className="ml-auto size-3 shrink-0 animate-spin text-muted" aria-label={t('common.saving')} />
+ ) : (
+ <ChevronDown className="ml-auto size-3 shrink-0 text-muted" />
+ )}
</Button>
</PopoverTrigger>
<PopoverContent align={align} className="z-50 max-h-[70vh] w-[680px] max-w-[92vw] overflow-y-auto p-0">
@@ -305,9 +319,8 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
{defaultLabel && (
<RouteItem
active={routeIsDefault}
- disabled={patching}
onClick={() =>
- void applyPatch({
+ applyPatch({
agent_name: null,
agent_id: null,
agent_backend: null,
@@ -331,9 +344,8 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
<RouteItem
key={agent.id}
active={!routeIsDefault && agent.name === currentAgent}
- disabled={patching}
onClick={() =>
- void applyPatch({
+ applyPatch({
agent_name: agent.name,
agent_id: agent.id,
agent_backend: agent.backend,
@@ -400,7 +412,6 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
<RouteItem
key={model}
active={model === currentModel}
- disabled={patching}
onClick={() => {
const patch: AgentRoutePatch = { model };
// Switching to a model whose effort set no longer includes
@@ -409,7 +420,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
if (!isEffortSupported(backend, model, currentEffort, backendReasoning)) {
patch.reasoning_effort = null;
}
- void applyPatch(patch);
+ applyPatch(patch);
}}
>
{/* Full id always visible (wraps instead of truncating); the
@@ -429,8 +440,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
<RouteItem
key={opt}
active={opt === currentEffort}
- disabled={patching}
- onClick={() => void applyPatch({ reasoning_effort: opt })}
+ onClick={() => applyPatch({ reasoning_effort: opt })}
>
<span className="flex-1 capitalize">
{t(`chat.picker.effortOptions.${opt}`, { defaultValue: opt })}
@@ -456,15 +466,13 @@ const RouteColumn: React.FC<{ title: string; children: React.ReactNode }> = ({ t
const RouteItem: React.FC<{
active: boolean;
onClick: () => void;
- disabled?: boolean;
children: React.ReactNode;
-}> = ({ active, onClick, disabled, children }) => (
+}> = ({ active, onClick, children }) => (
<Button
type="button"
variant="ghost"
size="sm"
onClick={onClick}
- disabled={disabled}
className={clsx(
'h-auto w-full justify-start gap-2 rounded px-2 py-1.5 text-left text-[12px] font-normal',
active ? 'bg-cyan/[0.10] text-cyan-ink hover:bg-cyan/[0.10] hover:text-cyan-ink' : 'text-foreground hover:bg-foreground/[0.04]',
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 40f89c815..eff04f585 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -97,8 +97,16 @@ import {
type SessionReadOnlyReason,
} from './sessionArchived';
import {
+ bySessionWriteGroup,
+ commitSessionRowWrite,
createSessionRowRefreshGate,
+ recordSessionRowWrite,
+ releaseSessionRowWrite,
sessionRowWithBootstrapFallback,
+ sessionWriteStandsAlone,
+ useChatSessionRow,
+ type SessionRowRefreshGate,
+ type SessionWriteGroup,
} from './sessionRowRefresh';
import { chatSessionViewState } from './chatSessionViewState';
import { InstallHint } from '../InstallHint';
@@ -116,6 +124,7 @@ import { VaultApprovalFloat, VaultChatRequests } from '../ui/vault-chat-requests
import { VaultProvisionDialogProvider, VaultRequestCard } from '../ui/vault-request-card';
import { StatusPill } from '../visual';
import { usePendingVaultRequests } from '../../lib/usePendingVaultRequests';
+import { useCoalescedWrite } from '../../lib/useCoalescedWrite';
import { hasInAppBackEntry } from '../../lib/navigationHistory';
import { Composer, type ComposerAttachment, type ComposerHandle, type ComposerProps } from './Composer';
import type { MentionReference } from '../../lib/mentions';
@@ -188,6 +197,19 @@ const OLDER_TRIGGER_BAND_PX = 120;
// row's hint so the shortcut is discoverable instead of folklore.
const ARCHIVE_SHORTCUT_LABEL = archiveSessionShortcutLabel();
+// One session write. The header applies an edit optimistically, so the request
+// that follows carries the chat it was made for: it is recorded under that
+// session's id (the URL may already be on another chat by the time it flushes)
+// and carries that chat's read-ordering gate, which is replaced on navigation.
+// It also carries which of the row's field groups it belongs to, because the
+// optimistic record it commits against is per group — the writer key alone says
+// that to the writer, not to the sender it hands the payload to.
+type SessionPatchWrite = {
+ changes: Partial<WorkbenchSession>;
+ gate: SessionRowRefreshGate;
+ group: SessionWriteGroup;
+};
+
// Mirrors design.pen kxEkn — the inline header replaces the old "Session
// settings" dialog. Title is click-to-edit; the cyan-bordered pill on the
// right opens a single popover that drives agent / model / effort all at
@@ -255,7 +277,12 @@ export const ChatPage: React.FC = () => {
// Loaded session (null while bootstrapping — ChatPage renders a loader until
// it's set). Lifted above the composer bridge + show-page logic that gate on it.
- const [session, setSession] = useState<WorkbenchSession | null>(null);
+ // Two ways to move it, by provenance: ``installFromServer`` for anything the
+ // server sent (an open write is re-applied on top of it), ``applyLocal`` for
+ // this document's own optimistic state. The raw setter is deliberately out of
+ // scope — see ``useChatSessionRow``.
+ const { session, installFromServer: installServerSession, applyLocal: applyLocalSession } =
+ useChatSessionRow<WorkbenchSession>();
const sessionRowRefreshGateRef = useRef(createSessionRowRefreshGate());
// Archive is terminal: an archived transcript stays fully readable (search's
// "include archived" opt-in links straight here) but every mutation is refused
@@ -859,7 +886,7 @@ export const ChatPage: React.FC = () => {
// cached a stale row; reusing it inside the read cache's TTL is exactly
// what the callers are trying to escape.
const row = await api.getSession(id, { cache: false });
- setSession((prev) =>
+ installServerSession((prev) =>
isCurrent() && row.id === sessionIdRef.current ? row : prev,
);
} catch {
@@ -872,7 +899,141 @@ export const ChatPage: React.FC = () => {
}
};
await read(true);
- }, [api]);
+ }, [api, installServerSession]);
+
+ // Persistence for the header's optimistic edits.
+ const sendSessionPatch = useCallback(
+ async ({ changes, gate, group }: SessionPatchWrite, patchedId: string): Promise<boolean> => {
+ const finishPatch = gate.beginMutation();
+ try {
+ await api.updateSession(patchedId, changes as any);
+ // Do not install the PATCH response: it is only a mutation snapshot and
+ // can be older than another committed write. The authoritative refresh
+ // on settle is guarded by session id and runs after every active write.
+ //
+ // The server now holds these fields, so the rollback target moves PAST
+ // them: a burst commits in parts (the Agent pick lands, the effort pick
+ // folded in behind it is refused), and reverting to where the burst started
+ // would undo a change the server took. Only the fields this request
+ // carried — the rest of the target is still the pre-burst row.
+ commitSessionRowWrite<WorkbenchSession>(patchedId, changes, group);
+ return true;
+ } catch (err) {
+ if (patchedId !== sessionIdRef.current) return false;
+ // The archive itself has already converged through the shared
+ // ``onSessionArchived`` subscription (the title editor and route picker are
+ // gone by the next render, so this PATCH cannot be re-issued). Only the
+ // wording is per-verb: the global ``errors.session_archived`` copy that
+ // ``handleApiError`` resolved is Show-Page-worded, which is wrong for a
+ // rename or a re-route.
+ setError(isSessionArchivedError(err) ? t('chat.archived.editBlocked') : (errorMessage(err) ?? String(err)));
+ return false;
+ } finally {
+ finishPatch();
+ }
+ },
+ [api, t],
+ );
+
+ // Within ONE group the clicks made while a request is in flight are transit
+ // rather than intent, so they fold into a single follow-up PATCH: an effort
+ // clicked behind an Agent switch was composed against that switch, so if the
+ // request fails the follow-up goes with it and the re-read below shows what the
+ // server actually holds — a half-applied route is worse than a visible
+ // rollback. A merged payload that ends up carrying the whole route depended on
+ // nothing, and ``sessionWriteStandsAlone`` is what keeps it from being dropped
+ // for a failure that says nothing about it. Across groups nothing folds, because
+ // they no longer share a writer at all. The newest gate wins: it belongs to the
+ // mount that is on screen now and whose reads the reconcile below has to fence.
+ const mergeSessionPatch = useCallback(
+ (prev: SessionPatchWrite, next: SessionPatchWrite): SessionPatchWrite => ({
+ changes: { ...prev.changes, ...next.changes },
+ gate: next.gate,
+ group: next.group,
+ }),
+ [],
+ );
+
+ // Once per burst, not once per write. On success the read is what makes the
+ // optimistic row authoritative again, and it is returned rather than fired and
+ // forgotten, so the session counts as saving until it has reconciled. Only for
+ // the open chat: a burst for a session the user has navigated away from has
+ // nothing on screen to reconcile, and ``refreshSessionRow`` reads whatever IS
+ // open.
+ const settleSessionPatch = useCallback(
+ (patchedId: string, committed: boolean, group: SessionWriteGroup) => {
+ // Ends this group's open write — including its overlay, so the re-read below
+ // is what those fields show from here on — and hands back what a rejection
+ // must restore. Per group: the OTHER group's request stands or falls on its
+ // own, so releasing both here would drop an overlay nobody has answered.
+ const base = releaseSessionRowWrite<WorkbenchSession>(patchedId, group);
+ if (patchedId !== sessionIdRef.current) return;
+ if (committed) return refreshSessionRow();
+ // A rejected burst lives only in this row, and the re-read is best-effort
+ // BY CONTRACT — it swallows its own failure — so it cannot be the rollback:
+ // an offline tab would keep showing a title or route the server refused,
+ // with the saving indicator already gone. Restore the values the burst
+ // replaced instead, and only for the fields it changed: putting the whole
+ // pre-burst row back would also undo what arrived meanwhile over SSE (a
+ // status flip that made the chat read-only, say), or what the sibling group
+ // is still writing — neither of which this burst touched.
+ if (base) {
+ sessionRowRefreshGateRef.current.invalidate();
+ applyLocalSession((prev) => (prev && prev.id === patchedId ? { ...prev, ...base } : prev));
+ }
+ // Converge anyway, unawaited: the restored values are the ones this tab
+ // last saw, and only a read can show a field someone else moved. The row on
+ // screen is already correct, so nothing waits for it.
+ void refreshSessionRow();
+ },
+ [refreshSessionRow, applyLocalSession],
+ );
+
+ // One writer per field group, not one per row. A writer serializes and
+ // coalesces per key and ENDS the burst on failure, so its key must name exactly
+ // the fields that share a fate — see ``bySessionWriteGroup``. Sharing one key
+ // let a refused rename drop a route pick that had never been sent, and revert
+ // it. They share the sender: the request is the same PATCH either way, and the
+ // server writes only the columns it was given.
+ // Whether a refused request takes the write behind it down with it is decided by
+ // the group that owns those fields, from the two payloads' relation — never
+ // assumed for the key as a whole (a model click behind a refused model click
+ // overwrites the very field that failed).
+ const patchStandsAlone = useCallback(
+ (pending: SessionPatchWrite, refused: SessionPatchWrite) =>
+ sessionWriteStandsAlone(pending.group, pending.changes, refused.changes),
+ [],
+ );
+
+ const { write: writeRoutePatch, isSaving: isRoutePatchSaving } = useCoalescedWrite<SessionPatchWrite>(
+ 'session-route',
+ sendSessionPatch,
+ {
+ merge: mergeSessionPatch,
+ standsAlone: patchStandsAlone,
+ onSettled: useCallback(
+ (patchedId: string, committed: boolean) => settleSessionPatch(patchedId, committed, 'route'),
+ [settleSessionPatch],
+ ),
+ },
+ );
+ const { write: writeMetaPatch, isSaving: isMetaPatchSaving } = useCoalescedWrite<SessionPatchWrite>(
+ 'session-meta',
+ sendSessionPatch,
+ {
+ merge: mergeSessionPatch,
+ standsAlone: patchStandsAlone,
+ onSettled: useCallback(
+ (patchedId: string, committed: boolean) => settleSessionPatch(patchedId, committed, 'meta'),
+ [settleSessionPatch],
+ ),
+ },
+ );
+ const sessionPatchWriters = useMemo(
+ () => ({ route: writeRoutePatch, meta: writeMetaPatch }) as Record<SessionWriteGroup, typeof writeRoutePatch>,
+ [writeRoutePatch, writeMetaPatch],
+ );
+
// ── Converging on a terminal archive this tab missed ────────────────────────
//
// A backgrounded / offline tab can miss the archive SSE for a session that
@@ -899,10 +1060,10 @@ export const ChatPage: React.FC = () => {
setShowPageBusy(false);
writeChatViewMode(archivedSessionId, 'chat');
sessionRowRefreshGateRef.current.invalidate();
- setSession((prev) => markSessionArchived(prev, archivedSessionId));
+ installServerSession((prev) => markSessionArchived(prev, archivedSessionId));
void refreshSessionRow();
},
- [refreshSessionRow],
+ [refreshSessionRow, installServerSession],
);
// Every write that goes through the shared JSON helpers (updateSession,
@@ -1196,16 +1357,20 @@ export const ChatPage: React.FC = () => {
// Drop a response if the user switched chats or a newer bootstrap for
// this route began while it was in flight.
if (!requestIsCurrent()) return;
+ // A write still in flight for this session outranks the row the bootstrap
+ // answers with: opening this chat again is not a reason to show the route the
+ // user has already clicked past. ``installServerSession`` re-applies it.
+ const bootstrapRow = bootstrap.session;
if (bootstrapIsCurrent()) {
- setSession(bootstrap.session);
+ installServerSession(bootstrapRow);
} else {
// A newer turn-end/activity read won the row race. Preserve its row if
// it landed, but keep this successful bootstrap as the fallback while a
// cold-page recovery is pending or if both bounded attempts fail.
- setSession((current) => sessionRowWithBootstrapFallback(
+ installServerSession((current) => sessionRowWithBootstrapFallback(
current,
sessionId,
- bootstrap.session,
+ bootstrapRow,
));
void refreshSessionRow();
}
@@ -1265,7 +1430,7 @@ export const ChatPage: React.FC = () => {
// of its own loading state into a premature not-found / error view.
if (requestIsCurrent()) setLoading(false);
}
- }, [api, sessionId, markWorking, scheduleActivityRefresh, refreshSessionRow, beginTranscriptSnapshotRead]);
+ }, [api, sessionId, markWorking, scheduleActivityRefresh, refreshSessionRow, beginTranscriptSnapshotRead, installServerSession]);
// Clear per-session state the instant the session changes (React Router swaps
// only :sessionId, reusing this instance), before the new session's
@@ -1282,7 +1447,7 @@ export const ChatPage: React.FC = () => {
// finishes, and a rename / agent change would patch() the STALE session.id
// while the URL is already on the new chat (Codex P2). Nulling it shows the
// loading state until refresh() resolves the new session.
- setSession(null);
+ applyLocalSession(null);
setSessionCanChat(false);
setMessages([]);
setHydratedTranscriptSessionId(null);
@@ -1330,7 +1495,7 @@ export const ChatPage: React.FC = () => {
window.clearTimeout(graceResyncRef.current);
graceResyncRef.current = null;
}
- }, [api, sessionId]);
+ }, [api, sessionId, applyLocalSession]);
// Persistent per-session subscription: append every transcript-visible
// ``message.new`` for THIS session for as long as the page is open. An agent
@@ -1446,7 +1611,7 @@ export const ChatPage: React.FC = () => {
if (!Object.prototype.hasOwnProperty.call(data, 'title')) return;
const nextTitle = data.title ?? null;
sessionRowRefreshGateRef.current.invalidate();
- setSession((prev) => {
+ installServerSession((prev) => {
if (!prev || prev.id !== data.session_id || prev.title === nextTitle) return prev;
return { ...prev, title: nextTitle };
});
@@ -1474,7 +1639,7 @@ export const ChatPage: React.FC = () => {
setSessionCanChat(false);
void api.getSession(currentSessionId, { cache: false })
.then((nextSession) => {
- setSession(nextSession);
+ installServerSession(nextSession);
void refresh();
})
.catch(() => goBack());
@@ -1490,7 +1655,7 @@ export const ChatPage: React.FC = () => {
},
});
return disconnect;
- }, [api, sessionId, appendMessage, reconcile, refresh, refreshQueue, syncTurnState, refreshSessionRow, markWorking, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive, probeShowPageAccess]);
+ }, [api, sessionId, appendMessage, reconcile, refresh, refreshQueue, syncTurnState, refreshSessionRow, markWorking, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive, probeShowPageAccess, installServerSession]);
// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the
// SSE feed can be suspended without a clean reconnect, dropping the reply.
@@ -1597,6 +1762,13 @@ export const ChatPage: React.FC = () => {
// so the locked/highlighted state can be derived on reload.
...(metadata ? { metadata } : {}),
};
+ // This POST does not wait for the header's route writes, so a prompt sent
+ // in the same breath as a model pick can be admitted on the route the row
+ // still holds. The client cannot close that window: routing a turn and
+ // sending it are separate requests (``POST /messages`` accepts text,
+ // content and metadata only), so gating the send would trade the gap for
+ // the very latency this optimistic path removes — a slow PATCH would make
+ // Enter feel dead. Atomic admission belongs to the server.
const response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -1708,7 +1880,16 @@ export const ChatPage: React.FC = () => {
return false;
}
},
- [sessionId, api, appendMessage, refreshQueue, markWorking, reloadLatestMessages, t, writable],
+ [
+ sessionId,
+ api,
+ appendMessage,
+ refreshQueue,
+ markWorking,
+ reloadLatestMessages,
+ t,
+ writable,
+ ],
);
// @ mention source: all enabled Agents, filtered client-side (the set is small
@@ -2164,31 +2345,44 @@ export const ChatPage: React.FC = () => {
void sendMessage(initialMessage);
}, [location.state, location.pathname, loading, session, sessionId, navigate, sendMessage]);
+ // Scoped to the open chat: a write still draining for a session the user has
+ // left must not spin the header of the one they are looking at. Either group
+ // counts — the header shows ONE saving indicator, and the user is owed it for
+ // whichever field they just edited.
+ const openSessionId = session?.id ?? '';
+ const patchSaving = isRoutePatchSaving(openSessionId) || isMetaPatchSaving(openSessionId);
+
+ // A route or title edit lands on the local row within the click and is
+ // persisted behind it. The picker highlight and the title are CONTROLLED by
+ // ``session``, so anything this waits for is lag the user reads as a frozen UI
+ // (the reason the picker no longer greys itself out either).
const patch = useCallback(
- async (changes: Partial<WorkbenchSession>) => {
+ (changes: Partial<WorkbenchSession>) => {
if (!session) return;
const patchedId = session.id;
- const finishPatch = sessionRowRefreshGateRef.current.beginMutation();
- try {
- await api.updateSession(session.id, changes as any);
- // Do not install the PATCH response: it is only a mutation snapshot and
- // can be older than another committed write. The authoritative refresh
- // in finally is guarded by session id and runs after every active write.
- } catch (err) {
- if (patchedId !== sessionIdRef.current) return;
- // The archive itself has already converged through the shared
- // ``onSessionArchived`` subscription (the title editor and route picker are
- // gone by the next render, so this PATCH cannot be re-issued). Only the
- // wording is per-verb: the global ``errors.session_archived`` copy that
- // ``handleApiError`` resolved is Show-Page-worded, which is wrong for a
- // rename or a re-route.
- setError(isSessionArchivedError(err) ? t('chat.archived.editBlocked') : (errorMessage(err) ?? String(err)));
- } finally {
- finishPatch();
- if (patchedId === sessionIdRef.current) void refreshSessionRow();
+ // ``invalidate`` stops a row read that is ALREADY in flight from
+ // re-installing the pre-patch row on top of the optimistic one.
+ const gate = sessionRowRefreshGateRef.current;
+ gate.invalidate();
+ applyLocalSession((prev) => (prev && prev.id === patchedId ? { ...prev, ...changes } : prev));
+ // The row moves as one; the REQUESTS do not. Fields that overwrite each
+ // other belong in one serialized, coalescing, fails-together burst — fields
+ // that don't must not be tied to one, so the edit is split into the
+ // independent writes it actually is (today: at most a route and a title).
+ for (const [group, groupChanges] of bySessionWriteGroup(changes)) {
+ // Both the id and the gate travel with the write: a patch waiting to flush
+ // belongs to the chat that was open when it was clicked, and the gate is
+ // per-session (replaced on navigation), so it must never fence the new
+ // chat's reads.
+ const opened = sessionPatchWriters[group](patchedId, { changes: groupChanges, gate, group });
+ // Record the write against the row it is replacing: what a rejection restores,
+ // and what every row arriving from the server has to yield to until this write
+ // is answered. ``write`` reports which call OPENED the burst, which is the one
+ // that starts the record over.
+ recordSessionRowWrite(session, groupChanges, opened, group);
}
},
- [api, session, t, refreshSessionRow],
+ [session, applyLocalSession, sessionPatchWriters],
);
// Session-level actions share the sidebar/mobile row model. A read-only or
@@ -2214,7 +2408,7 @@ export const ChatPage: React.FC = () => {
onSessionPatched: (changes, sessionId) => {
if (sessionId !== sessionIdRef.current) return;
sessionRowRefreshGateRef.current.invalidate();
- setSession((prev) => (prev && prev.id === sessionId ? { ...prev, ...changes } : prev));
+ installServerSession((prev) => (prev && prev.id === sessionId ? { ...prev, ...changes } : prev));
// Pin updates only carry the changed sidebar field. A successful PATCH can
// race a turn-end row read, so re-read the complete durable projection to
// keep any newly materialized route in the header.
@@ -2437,6 +2631,7 @@ export const ChatPage: React.FC = () => {
agents={agents}
defaultAgentName={defaultAgentName}
onPatch={patch}
+ patchSaving={patchSaving}
onBack={goBack}
working={working}
showPageMode={showPageActive}
@@ -3013,7 +3208,10 @@ interface ChatHeaderBarProps {
session: WorkbenchSession;
agents: VibeAgentBrief[];
defaultAgentName: string | null;
- onPatch: (changes: Partial<WorkbenchSession>) => Promise<void>;
+ // Applies to the local row first, then persists — never awaited by the header.
+ onPatch: (changes: Partial<WorkbenchSession>) => void;
+ /** A queued ``onPatch`` write is still in flight. */
+ patchSaving?: boolean;
onBack: () => void;
working: boolean;
// The EFFECTIVE mode (ChatPage passes ``showPageActive``): whether the page is
@@ -3048,7 +3246,7 @@ interface ChatHeaderBarProps {
// which renders the header alone rather than mounting the whole page. Note the
// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the
// read-only rendering is reachable without an ApiProvider.
-export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, showPageAccess = null, canOpenShowPage = true, canManageShowPage = true, canManageInstance = false, sessionActions, titleFieldRef }) => {
+export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, patchSaving, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, showPageAccess = null, canOpenShowPage = true, canManageShowPage = true, canManageInstance = false, sessionActions, titleFieldRef }) => {
const { t } = useTranslation();
const readOnly = !writable;
const sessionReadOnly = readOnlyReason !== null;
@@ -3149,6 +3347,7 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
value={session}
agents={agents}
onChange={onPatch}
+ saving={patchSaving}
disabled={pickerDisabled}
allowedBackends={pinnedBackend ? [pinnedBackend] : undefined}
defaultLabel={
diff --git a/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx b/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
new file mode 100644
index 000000000..de32a7d11
--- /dev/null
+++ b/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
@@ -0,0 +1,766 @@
+/** @vitest-environment jsdom */
+
+// The header's route edits apply within the click and persist behind them, which
+// is the point of the optimistic path. These tests pin what that means at the two
+// boundaries where it is observable — what reached the network, in which order
+// (Enter is never held behind an in-flight route PATCH, the resulting admission
+// gap being the server's to close; the picks made during one PATCH reach the row
+// as a single merged follow-up) — and what the user is left looking at when the
+// server refuses the burst.
+
+import { useEffect } from 'react';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
+
+import type { AgentRoutePatch } from './AgentRoutePicker';
+
+const mocks = vi.hoisted(() => ({
+ api: {
+ connectWorkbenchEvents: vi.fn(),
+ getCachedSessionDraft: vi.fn(),
+ getSession: vi.fn(),
+ getSessionBootstrap: vi.fn(),
+ getTurnState: vi.fn(),
+ getWorkbenchPrefs: vi.fn(),
+ listSessionMessages: vi.fn(),
+ listSessionQueue: vi.fn(),
+ onSessionArchived: vi.fn(),
+ updateSession: vi.fn(),
+ cancelSession: vi.fn(),
+ recoverSessionDraftAfterRejectedSend: vi.fn(),
+ reconcileSessionDraftAfterSend: vi.fn(),
+ convergeSessionArchived: vi.fn(),
+ },
+ apiFetch: vi.fn(),
+ // The live subscription's handlers, so a test can deliver the server's own
+ // events — the arrival point that has no request to be ordered against.
+ events: null as null | {
+ onSessionActivity?: (data: { session_id: string; event: string; title?: string | null }) => void;
+ },
+ // Captured from the mocked leaf components: the route pick and the send are
+ // both props ChatPage hands down, so driving them needs no DOM choreography.
+ onPatch: null as null | ((patch: AgentRoutePatch) => void),
+ onSend: null as null | ((text: string) => void | Promise<unknown>),
+ onStop: null as null | (() => void | Promise<unknown>),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('../../lib/apiFetch', () => ({
+ apiFetch: (...args: unknown[]) => mocks.apiFetch(...args),
+}));
+
+vi.mock('../../context/ApiContext', () => ({
+ useApi: () => mocks.api,
+}));
+
+vi.mock('../../context/ToastContext', () => ({
+ useToast: () => ({ showToast: vi.fn() }),
+}));
+
+vi.mock('../../context/WorkbenchInboxContext', () => ({
+ useWorkbenchInbox: () => ({ unreadBySession: {}, markRead: vi.fn() }),
+}));
+
+vi.mock('../../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({
+ capabilities: {
+ can_chat: true,
+ can_manage_instance: false,
+ can_use_show_pages: false,
+ can_use_vault_secrets: false,
+ },
+ }),
+}));
+
+vi.mock('../../context/ComposerBridgeContext', () => ({
+ useRegisterComposerTarget: vi.fn(),
+}));
+
+vi.mock('../../context/WindowManagerContext', () => ({
+ useWindowManager: () => ({ focusedId: null, focusCanvas: vi.fn() }),
+}));
+
+vi.mock('../../lib/useIsDesktop', () => ({
+ isDesktopViewport: () => false,
+ useIsDesktop: () => false,
+}));
+
+vi.mock('../../lib/useIosKeyboardInset', () => ({
+ useIosKeyboardInset: vi.fn(),
+}));
+
+vi.mock('../../lib/useFileDrop', () => ({
+ useFileDrop: () => ({ dragging: false, handlers: {} }),
+}));
+
+vi.mock('../../lib/usePendingVaultRequests', () => ({
+ usePendingVaultRequests: () => ({ requests: [], refresh: vi.fn() }),
+}));
+
+vi.mock('./useSessionActions', () => ({
+ useSessionActions: () => ({
+ actions: [],
+ archiveDialog: null,
+ requestArchive: vi.fn(),
+ canArchive: false,
+ }),
+}));
+
+vi.mock('./useShowPageAnnotation', () => ({
+ useShowPageAnnotation: () => ({
+ state: { enabled: false, mode: 'smart' },
+ setIframe: vi.fn(),
+ handleIframeLoad: vi.fn(),
+ enable: vi.fn(),
+ disable: vi.fn(),
+ setMode: vi.fn(),
+ }),
+}));
+
+vi.mock('./Composer', () => ({
+ Composer: ({
+ onSend,
+ onStop,
+ }: {
+ onSend: (text: string) => void | Promise<unknown>;
+ onStop: () => void | Promise<unknown>;
+ }) => {
+ mocks.onSend = onSend;
+ mocks.onStop = onStop;
+ return null;
+ },
+}));
+
+vi.mock('./AgentRoutePicker', () => ({
+ AgentRoutePicker: ({
+ onChange,
+ value,
+ saving,
+ }: {
+ onChange: (patch: AgentRoutePatch) => void;
+ value: { agent_name?: string | null; model?: string | null; reasoning_effort?: string | null } | null;
+ saving?: boolean;
+ }) => {
+ mocks.onPatch = onChange;
+ // The picker holds no selection of its own — the highlight IS this value — so
+ // rendering it is how a test reads what the user is looking at.
+ return (
+ <div
+ data-testid="route"
+ data-agent={value?.agent_name ?? ''}
+ data-model={value?.model ?? ''}
+ data-effort={value?.reasoning_effort ?? ''}
+ data-saving={saving ? 'yes' : 'no'}
+ />
+ );
+ },
+}));
+
+import { ChatPage } from './ChatPage';
+import { resetCoalescedWrites } from '../../lib/useCoalescedWrite';
+import { resetOpenSessionRowWrites } from './sessionRowRefresh';
+
+const SESSION_ID = 'session-route';
+const OTHER_SESSION_ID = 'session-other';
+
+type Deferred<T> = {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+ reject: (reason: unknown) => void;
+};
+
+const deferred = <T,>(): Deferred<T> => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+};
+
+const idleTurnState = {
+ foreground: 'idle',
+ native_turn_started: false,
+ pending_input_count: 0,
+ background_activities: [],
+ pending_activity_output_count: 0,
+ connection: 'connected',
+};
+
+const sessionRow = {
+ id: SESSION_ID,
+ title: 'Route ordering',
+ agent_name: 'claude',
+ agent_backend: 'claude',
+ model: 'sonnet',
+ reasoning_effort: null,
+};
+
+// A second chat, for the cases about two rows being edited at once. Same route on
+// purpose: only the id distinguishes whose rollback is whose.
+const otherRow = { ...sessionRow, id: OTHER_SESSION_ID, title: 'The other chat' };
+
+const rowsById: Record<string, typeof sessionRow> = {
+ [SESSION_ID]: sessionRow,
+ [OTHER_SESSION_ID]: otherRow,
+};
+
+// Switching chats keeps ChatPage mounted (same route, new param) — which is why a
+// burst opened on the chat the user has left can still settle into this component.
+let navigate: ((to: string) => void) | null = null;
+
+function NavProbe() {
+ const to = useNavigate();
+ useEffect(() => {
+ navigate = to;
+ }, [to]);
+ return null;
+}
+
+function settle() {
+ return act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+function messagePosts() {
+ return mocks.apiFetch.mock.calls.filter(([url]) => String(url).includes('/messages'));
+}
+
+// What the header's picker is showing right now.
+function shownRoute() {
+ return screen.getByTestId('route').dataset;
+}
+
+// The title is click-to-edit, so what the user is looking at is the label of the
+// button it collapses to. The real field is driven here rather than synthesized:
+// a rename and a route pick come from two different controls, which is the whole
+// point of the cases below.
+function renameFrom(current: string, next: string) {
+ act(() => {
+ fireEvent.click(screen.getByRole('button', { name: current }));
+ });
+ const input = screen.getByPlaceholderText('chat.titlePlaceholder');
+ act(() => {
+ fireEvent.change(input, { target: { value: next } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ });
+}
+
+async function mountChat() {
+ render(
+ <MemoryRouter initialEntries={[`/chat/${SESSION_ID}`]}>
+ <NavProbe />
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await settle();
+ // The live header only renders once the row is loaded, and the picker is where
+ // a route pick comes from.
+ if (!mocks.onPatch || !mocks.onSend || !mocks.onStop) {
+ throw new Error('ChatPage did not mount its header/composer');
+ }
+}
+
+describe('the chat row under an optimistic write', () => {
+ beforeEach(() => {
+ for (const name of ['ResizeObserver', 'IntersectionObserver']) {
+ vi.stubGlobal(
+ name,
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ }
+ mocks.onPatch = null;
+ mocks.onSend = null;
+ mocks.onStop = null;
+ mocks.events = null;
+ navigate = null;
+ vi.clearAllMocks();
+ // The writer's store and the record of what an open write is holding are both
+ // module state (a session row outlives the page that edits it), so each case
+ // starts from an empty one.
+ resetCoalescedWrites();
+ resetOpenSessionRowWrites();
+
+ mocks.api.connectWorkbenchEvents.mockImplementation((handlers: unknown) => {
+ mocks.events = handlers as typeof mocks.events;
+ return () => {};
+ });
+ mocks.api.getCachedSessionDraft.mockReturnValue(null);
+ mocks.api.getSession.mockImplementation(async (id: string) => rowsById[id] ?? sessionRow);
+ mocks.api.getSessionBootstrap.mockImplementation(async (id: string) => ({
+ session: rowsById[id] ?? sessionRow,
+ capabilities: { can_chat: true },
+ agents: [],
+ default_agent_name: null,
+ config: { ui: {} },
+ messages: [],
+ next_before_id: null,
+ turn_state: idleTurnState,
+ queued: [],
+ draft: { text: '' },
+ }));
+ mocks.api.getTurnState.mockResolvedValue(idleTurnState);
+ mocks.api.getWorkbenchPrefs.mockResolvedValue({});
+ mocks.api.listSessionMessages.mockResolvedValue({ messages: [] });
+ mocks.api.listSessionQueue.mockResolvedValue([]);
+ mocks.api.onSessionArchived.mockReturnValue(() => {});
+ // A turn started; no transcript row to graft in this harness.
+ mocks.apiFetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
+ });
+
+ afterEach(() => {
+ cleanup();
+ resetCoalescedWrites();
+ resetOpenSessionRowWrites();
+ vi.unstubAllGlobals();
+ });
+
+ it('sends without waiting for the route write to land', async () => {
+ const patchGate = deferred<unknown>();
+ mocks.api.updateSession.mockReturnValue(patchGate.promise);
+ await mountChat();
+
+ act(() => mocks.onPatch!({ model: 'opus' }));
+ expect(mocks.api.updateSession).toHaveBeenCalledWith(SESSION_ID, { model: 'opus' });
+
+ act(() => {
+ void mocks.onSend!('run it on opus');
+ });
+ await settle();
+ // Enter stays live: the POST goes out while the PATCH is still deciding. That
+ // leaves a real gap — the turn can be admitted on the route the row still
+ // holds while the header already shows the new one — and the client cannot
+ // close it, because routing a turn and sending it are separate requests
+ // (``POST /messages`` accepts text, content and metadata only). Gating the
+ // send would trade the gap for the very latency this path removes. Atomic
+ // admission belongs to the server.
+ expect(messagePosts()).toHaveLength(1);
+ expect(String(messagePosts()[0][0])).toContain(`/api/sessions/${SESSION_ID}/messages`);
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ patchGate.resolve({ ...sessionRow, model: 'opus' });
+ await patchGate.promise;
+ });
+ await settle();
+ // And the send did not disturb the write: one PATCH for the pick, one row
+ // re-read on settle.
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('folds the picks made during a route write into a single follow-up PATCH', async () => {
+ const gates = [deferred<unknown>(), deferred<unknown>()];
+ let call = 0;
+ mocks.api.updateSession.mockImplementation(() => gates[call++].promise);
+ await mountChat();
+
+ act(() => {
+ mocks.onPatch!({ agent_name: 'codex', agent_variant: 'codex', model: 'gpt-5' });
+ mocks.onPatch!({ reasoning_effort: 'high' });
+ mocks.onPatch!({ model: 'gpt-5-codex' });
+ });
+ // One request per row: a second PATCH beside this one could land first and
+ // undo it.
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(1);
+ expect(mocks.api.updateSession).toHaveBeenCalledWith(SESSION_ID, {
+ agent_name: 'codex',
+ agent_variant: 'codex',
+ model: 'gpt-5',
+ });
+
+ await act(async () => {
+ gates[0].resolve({ ...sessionRow, agent_name: 'codex', model: 'gpt-5' });
+ await gates[0].promise;
+ });
+ await settle();
+ // Two picks, ONE follow-up PATCH carrying the union of their fields: they are
+ // independent fields of one row, so neither takes the other hostage and
+ // neither is dropped as "superseded".
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, {
+ reasoning_effort: 'high',
+ model: 'gpt-5-codex',
+ });
+
+ await act(async () => {
+ gates[1].resolve({
+ ...sessionRow,
+ agent_name: 'codex',
+ model: 'gpt-5-codex',
+ reasoning_effort: 'high',
+ });
+ await gates[1].promise;
+ });
+ await settle();
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ });
+
+ it('puts the row back when the write is refused and the re-read fails', async () => {
+ const patchGate = deferred<unknown>();
+ mocks.api.updateSession.mockReturnValue(patchGate.promise);
+ // The tab is offline for reads too — the case that decides whether the
+ // rollback may be delegated to the re-read.
+ mocks.api.getSession.mockRejectedValue(new Error('offline'));
+ await mountChat();
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'sonnet', effort: '' });
+
+ act(() => {
+ mocks.onPatch!({ agent_name: 'codex', agent_variant: 'codex', model: 'gpt-5' });
+ mocks.onPatch!({ reasoning_effort: 'high' });
+ });
+ // Both picks are on screen at once, ahead of the single request carrying the
+ // first of them.
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', effort: 'high', saving: 'yes' });
+
+ await act(async () => {
+ patchGate.reject(new Error('nope'));
+ await patchGate.promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The whole burst goes back to what the row held before it — the pick that
+ // was refused AND the one dropped behind it, since neither is on the server.
+ // ``refreshSessionRow`` is best-effort by contract (it swallows its own
+ // failure), so a rollback delegated to it would leave this tab showing a
+ // route the server refused with the indicator already gone.
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'sonnet', effort: '', saving: 'no' });
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('sends the pick waiting behind a refused write when it carries the whole route', async () => {
+ const gates = [deferred<unknown>(), deferred<unknown>()];
+ let call = 0;
+ mocks.api.updateSession.mockImplementation(() => gates[call++].promise);
+ await mountChat();
+
+ // An effort click, then an Agent pick behind it while that request is still
+ // deciding. The picker emits an Agent pick as the WHOLE route — the Agent, its
+ // default model, its default effort — so it names every field it depends on.
+ act(() => {
+ mocks.onPatch!({ reasoning_effort: 'high' });
+ mocks.onPatch!({
+ agent_name: 'codex',
+ agent_id: 'ag_codex',
+ agent_backend: 'codex',
+ agent_variant: 'codex',
+ model: 'gpt-5',
+ reasoning_effort: 'medium',
+ });
+ });
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', effort: 'medium', saving: 'yes' });
+
+ await act(async () => {
+ gates[0].reject(new Error('nope'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The refusal says nothing about the pick behind it: that pick replaces every
+ // field the refused one carried, so it is coherent against the route the server
+ // kept. Dropping it would revert the header to an Agent the user has moved off,
+ // for a failure that never touched the Agent.
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, {
+ agent_name: 'codex',
+ agent_id: 'ag_codex',
+ agent_backend: 'codex',
+ agent_variant: 'codex',
+ model: 'gpt-5',
+ reasoning_effort: 'medium',
+ });
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', effort: 'medium', saving: 'yes' });
+
+ const committedRow = { ...sessionRow, agent_name: 'codex', model: 'gpt-5', reasoning_effort: 'medium' };
+ mocks.api.getSession.mockResolvedValue(committedRow);
+ await act(async () => {
+ gates[1].resolve(committedRow);
+ await gates[1].promise;
+ });
+ await settle();
+
+ // One burst, one settle: the send that ENDED it committed, so nothing reverts.
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', effort: 'medium', saving: 'no' });
+ });
+
+ it('sends a second model pick behind a refused one, because it overwrites the field that was refused', async () => {
+ const gates = [deferred<unknown>(), deferred<unknown>()];
+ let call = 0;
+ mocks.api.updateSession.mockImplementation(() => gates[call++].promise);
+ await mountChat();
+
+ // Two model clicks on a session that already has an explicit Agent. The picker
+ // emits each as ``{model}`` ALONE — there is no default to pin — so neither
+ // payload carries the whole route, and counting fields would call the second
+ // one dependent on the first.
+ act(() => {
+ mocks.onPatch!({ model: 'gpt-5' });
+ mocks.onPatch!({ model: 'gpt-5-codex' });
+ });
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'gpt-5-codex', saving: 'yes' });
+
+ await act(async () => {
+ gates[0].reject(new Error('nope'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // What decides it is the RELATION: the pending patch restates every field the
+ // refused one tried to write, so the refusal says nothing about it. The user's
+ // newest model choice must reach the server, not be discarded because the
+ // choice it replaced failed.
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, { model: 'gpt-5-codex' });
+
+ const committedRow = { ...sessionRow, model: 'gpt-5-codex' };
+ mocks.api.getSession.mockResolvedValue(committedRow);
+ await act(async () => {
+ gates[1].resolve(committedRow);
+ await gates[1].promise;
+ });
+ await settle();
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'gpt-5-codex', saving: 'no' });
+ });
+
+ it('keeps the fields a partly committed burst persisted, reverting only the refused ones', async () => {
+ const gates = [deferred<unknown>(), deferred<unknown>()];
+ let call = 0;
+ mocks.api.updateSession.mockImplementation(() => gates[call++].promise);
+ await mountChat();
+
+ act(() => {
+ mocks.onPatch!({ agent_name: 'codex', agent_variant: 'codex', model: 'gpt-5' });
+ mocks.onPatch!({ reasoning_effort: 'high' });
+ });
+ await act(async () => {
+ gates[0].resolve({ ...sessionRow, agent_name: 'codex', model: 'gpt-5' });
+ await gates[0].promise;
+ });
+ await settle();
+ // The Agent switch is on the server; the effort follows it in one request.
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, { reasoning_effort: 'high' });
+
+ // Offline for reads too, so the local revert is the only thing acting.
+ mocks.api.getSession.mockRejectedValue(new Error('offline'));
+ await act(async () => {
+ gates[1].reject(new Error('nope'));
+ await gates[1].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // Only the effort goes back. This burst committed in PARTS, and reverting to
+ // the row it started from would undo an Agent switch the server is holding —
+ // leaving the header showing a route that exists nowhere.
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', effort: '', saving: 'no' });
+ });
+
+ it('keeps a pick the server has not answered on the row the user comes back to', async () => {
+ const patchGate = deferred<unknown>();
+ mocks.api.updateSession.mockReturnValue(patchGate.promise);
+ await mountChat();
+
+ act(() => mocks.onPatch!({ agent_name: 'codex', agent_variant: 'codex', model: 'gpt-5' }));
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5' });
+
+ // Away and back while that PATCH is still deciding. The chat reloads, and the
+ // row it loads is the one the server still holds — legitimately, since the write
+ // has not answered.
+ await act(async () => {
+ navigate!(`/chat/${OTHER_SESSION_ID}`);
+ });
+ await settle();
+ await act(async () => {
+ navigate!(`/chat/${SESSION_ID}`);
+ });
+ await settle();
+
+ // The pick is still what the user is looking at. The read that reopened this
+ // chat is older than the write in flight, and the per-session read fence was
+ // replaced by the navigation, so the record of the open write is what defends it.
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', saving: 'yes' });
+
+ // Which is what makes the next click safe: the picker emits an effort change as
+ // ``{reasoning_effort}`` alone, so composing it against the reopened row would
+ // fold an effort chosen for claude in behind the switch to codex — and persist
+ // it on top of that switch.
+ act(() => mocks.onPatch!({ reasoning_effort: 'high' }));
+ expect(shownRoute()).toMatchObject({ agent: 'codex', model: 'gpt-5', effort: 'high' });
+
+ await act(async () => {
+ patchGate.resolve({ ...sessionRow, agent_name: 'codex', model: 'gpt-5' });
+ await patchGate.promise;
+ });
+ await settle();
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, { reasoning_effort: 'high' });
+ // And the defence ends with the write. This harness's row read still answers
+ // with the route the chat started on, so the settle re-read is visible: an
+ // overlay left standing would pin a pick nothing is writing any more.
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'sonnet', effort: '', saving: 'no' });
+ });
+
+ it('sends a route pick made behind a rename as its own request, and keeps it when the rename is refused', async () => {
+ const gates: Deferred<unknown>[] = [];
+ mocks.api.updateSession.mockImplementation(() => {
+ const gate = deferred<unknown>();
+ gates.push(gate);
+ return gate.promise;
+ });
+ await mountChat();
+
+ renameFrom('Route ordering', 'Renamed');
+ expect(mocks.api.updateSession).toHaveBeenCalledWith(SESSION_ID, { title: 'Renamed' });
+
+ // Two requests, not one merged patch and not one waiting behind the other.
+ // The title and the route overwrite nothing of each other's, and the server
+ // writes only the columns each PATCH names.
+ act(() => mocks.onPatch!({ model: 'opus' }));
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, { model: 'opus' });
+
+ // Offline for reads, so only the local rollback is acting.
+ mocks.api.getSession.mockRejectedValue(new Error('offline'));
+ await act(async () => {
+ gates[0].reject(new Error('nope'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The rename goes back. The pick does not: it is a different write, still in
+ // flight, and nothing about it was refused. While the two shared one writer
+ // key, this rejection ENDED that key's burst — which dropped the pick before
+ // it was ever sent AND reverted it on screen.
+ expect(screen.getByRole('button', { name: 'Route ordering' })).toBeTruthy();
+ expect(shownRoute()).toMatchObject({ model: 'opus', saving: 'yes' });
+
+ await act(async () => {
+ gates[1].resolve({ ...sessionRow, model: 'opus' });
+ await gates[1].promise;
+ });
+ await settle();
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(shownRoute()).toMatchObject({ model: 'opus', saving: 'no' });
+ });
+
+ it('keeps a rename made behind a route pick when the pick is refused', async () => {
+ const gates: Deferred<unknown>[] = [];
+ mocks.api.updateSession.mockImplementation(() => {
+ const gate = deferred<unknown>();
+ gates.push(gate);
+ return gate.promise;
+ });
+ await mountChat();
+
+ act(() => mocks.onPatch!({ agent_name: 'codex', agent_variant: 'codex', model: 'gpt-5' }));
+ renameFrom('Route ordering', 'Renamed');
+ expect(mocks.api.updateSession).toHaveBeenCalledTimes(2);
+ expect(mocks.api.updateSession).toHaveBeenLastCalledWith(SESSION_ID, { title: 'Renamed' });
+
+ mocks.api.getSession.mockRejectedValue(new Error('offline'));
+ await act(async () => {
+ gates[0].reject(new Error('nope'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The route reverts and the rename stays — including its request, which the
+ // refusal has no claim over. The indicator is still on, because the header
+ // shows one for the row and the row is still being written.
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'sonnet', saving: 'yes' });
+ expect(screen.getByRole('button', { name: 'Renamed' })).toBeTruthy();
+
+ await act(async () => {
+ gates[1].resolve({ ...sessionRow, title: 'Renamed' });
+ await gates[1].promise;
+ });
+ await settle();
+ expect(screen.getByRole('button', { name: 'Renamed' })).toBeTruthy();
+ expect(shownRoute()).toMatchObject({ saving: 'no' });
+ });
+
+ it('keeps a pending rename when a session event carries the title the server still holds', async () => {
+ const patchGate = deferred<unknown>();
+ mocks.api.updateSession.mockReturnValue(patchGate.promise);
+ await mountChat();
+
+ renameFrom('Route ordering', 'Renamed');
+ expect(mocks.api.updateSession).toHaveBeenCalledWith(SESSION_ID, { title: 'Renamed' });
+
+ // The rename broadcast for THIS row, carrying the title as the server still
+ // holds it. An event has no request of its own, so no read fence orders it
+ // against the write — which is why the defence cannot live in the fence.
+ await act(async () => {
+ mocks.events!.onSessionActivity!({ session_id: SESSION_ID, event: 'updated', title: 'Route ordering' });
+ });
+ await settle();
+ // Installing it would not just flicker: it re-seeds the header's editor from
+ // the prop, so a user still typing loses what they typed.
+ expect(screen.getByRole('button', { name: 'Renamed' })).toBeTruthy();
+
+ await act(async () => {
+ patchGate.resolve({ ...sessionRow, title: 'Renamed' });
+ await patchGate.promise;
+ });
+ await settle();
+ // And the defence ends with the write: this harness's row read still answers
+ // with the stored title, so an overlay left standing would be visible here.
+ expect(screen.getByRole('button', { name: 'Route ordering' })).toBeTruthy();
+ });
+
+ it('keeps each chat rollback to itself when two rows have a write in flight', async () => {
+ const gates = new Map<string, Deferred<unknown>>();
+ mocks.api.updateSession.mockImplementation((id: string) => {
+ const gate = deferred<unknown>();
+ gates.set(id, gate);
+ return gate.promise;
+ });
+ await mountChat();
+
+ // A pick on the first chat, left in flight.
+ act(() => mocks.onPatch!({ model: 'opus' }));
+ expect(gates.has(SESSION_ID)).toBe(true);
+
+ // The user switches chats while it is still deciding. ChatPage stays mounted,
+ // so both bursts are live in the same component.
+ await act(async () => {
+ navigate!(`/chat/${OTHER_SESSION_ID}`);
+ });
+ await settle();
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'sonnet' });
+
+ act(() => mocks.onPatch!({ model: 'haiku' }));
+ expect(shownRoute()).toMatchObject({ model: 'haiku', saving: 'yes' });
+ expect(gates.has(OTHER_SESSION_ID)).toBe(true);
+
+ mocks.api.getSession.mockRejectedValue(new Error('offline'));
+ // The FIRST chat's write fails. Its row is not on screen, so there is nothing
+ // to revert there — but its settle must not take the open chat's rollback with
+ // it. One slot for both would do exactly that, and the failure below would then
+ // leave a refused model on screen with the indicator already gone.
+ await act(async () => {
+ gates.get(SESSION_ID)!.reject(new Error('nope'));
+ await gates.get(SESSION_ID)!.promise.catch(() => undefined);
+ });
+ await settle();
+ expect(shownRoute()).toMatchObject({ model: 'haiku', saving: 'yes' });
+
+ await act(async () => {
+ gates.get(OTHER_SESSION_ID)!.reject(new Error('nope'));
+ await gates.get(OTHER_SESSION_ID)!.promise.catch(() => undefined);
+ });
+ await settle();
+ expect(shownRoute()).toMatchObject({ agent: 'claude', model: 'sonnet', saving: 'no' });
+ });
+});
diff --git a/ui/src/components/workbench/ProjectSettingsDialog.tsx b/ui/src/components/workbench/ProjectSettingsDialog.tsx
index 6036f8483..fa1f45e3c 100644
--- a/ui/src/components/workbench/ProjectSettingsDialog.tsx
+++ b/ui/src/components/workbench/ProjectSettingsDialog.tsx
@@ -29,7 +29,7 @@ export const ProjectSettingsDialog: React.FC<{
}> = ({ project, open, onClose }) => {
const { t } = useTranslation();
const api = useApi();
- const { setProjectDefaultAgent } = useWorkbenchProjectsActions();
+ const { setProjectDefaultAgent, isSavingDefaultAgent } = useWorkbenchProjectsActions();
const { capabilities } = useInstanceAuthorization();
const canManageProjects = capabilities.can_manage_projects;
const canEditAgentsMd = canManageProjects;
@@ -58,7 +58,7 @@ export const ProjectSettingsDialog: React.FC<{
// current default, so the picker reflects a save as soon as it lands.
const current = project.default_agent ?? null;
- const handleRouteChange = async (patch: AgentRoutePatch) => {
+ const handleRouteChange = (patch: AgentRoutePatch) => {
// The picker emits partial patches (a model-only pick is just {model}), so
// merge onto the stored default and persist the full 5-field route. A field
// PRESENT in the patch wins (incl. an explicit null that clears it); an
@@ -72,11 +72,11 @@ export const ProjectSettingsDialog: React.FC<{
reasoning_effort:
'reasoning_effort' in patch ? patch.reasoning_effort ?? null : current?.reasoning_effort ?? null,
};
- try {
- await setProjectDefaultAgent(project.id, merged, current?.agent_id ?? null);
- } catch {
- // apiFetch already surfaced the error toast; keep the dialog open.
- }
+ // Applied to the shared cache within the click (which re-renders `current`
+ // here), persisted behind it: nothing to await, nothing to catch. The
+ // compare-and-set token is the provider's business — `current` is the
+ // optimistic route, which is exactly what it must not expect.
+ setProjectDefaultAgent(project.id, merged);
};
return (
@@ -114,6 +114,7 @@ export const ProjectSettingsDialog: React.FC<{
value={current ?? {}}
agents={agents}
onChange={handleRouteChange}
+ saving={isSavingDefaultAgent(project.id)}
defaultLabel={t('projectSettings.defaultAgent.followGlobal')}
align="start"
modal
diff --git a/ui/src/components/workbench/sessionRowRefresh.ts b/ui/src/components/workbench/sessionRowRefresh.ts
index 6921513ae..7f28b90b2 100644
--- a/ui/src/components/workbench/sessionRowRefresh.ts
+++ b/ui/src/components/workbench/sessionRowRefresh.ts
@@ -1,3 +1,7 @@
+import { useCallback, useState } from 'react';
+
+import { overwritesRefusedFields } from '../../lib/useCoalescedWrite';
+
// Orders best-effort Session-row reads against every newer local observation.
// Reads wait for in-flight mutations to settle; a push event or mutation then
// invalidates every read that began before that newer state was observed.
@@ -13,6 +17,203 @@ export const sessionRowWithBootstrapFallback = <T extends { id: string }>(
bootstrap: T,
): T => (current?.id === routeSessionId ? current : bootstrap);
+// ── Which of a row's fields share a fate ────────────────────────────────────
+//
+// The writer serializes per key, coalesces per key, and a failure ENDS the burst
+// for that key — so a key must name exactly the fields that overwrite each other,
+// and nothing more. A route pick carries the Agent's default model and effort, so
+// those fields are one group: an effort clicked behind an Agent switch was
+// composed against it, and dropping it when the switch is refused is what keeps
+// the row coherent. The title is composed against none of them. While it shared
+// the route's key, a refused title discarded a route pick that had never been
+// sent — and reverted it — which is the opposite of that rule, not an instance of
+// it. Groups are derived from the fields, never chosen by a caller, so a field
+// added to the row lands in a group by construction.
+const ROUTE_FIELDS: ReadonlySet<string> = new Set([
+ 'agent_id',
+ 'agent_name',
+ 'agent_backend',
+ 'agent_variant',
+ 'model',
+ 'reasoning_effort',
+]);
+
+export type SessionWriteGroup = 'route' | 'meta';
+
+/** Splits one edit into the independent writes it actually is. */
+export const bySessionWriteGroup = <T extends object>(
+ changes: T,
+): Array<[SessionWriteGroup, T]> => {
+ const groups = new Map<SessionWriteGroup, T>();
+ for (const [field, value] of Object.entries(changes)) {
+ const group: SessionWriteGroup = ROUTE_FIELDS.has(field) ? 'route' : 'meta';
+ const bucket = groups.get(group) ?? ({} as T);
+ (bucket as Record<string, unknown>)[field] = value;
+ groups.set(group, bucket);
+ }
+ return [...groups.entries()];
+};
+
+/** Whether a write may still be sent after an earlier request for its OWN group
+ * was refused — i.e. whether it was composed against a field that request was
+ * moving, or overwrites whatever it moved.
+ *
+ * Route fields are chosen against each other: a model belongs to an Agent, an
+ * effort to a model. So the question is not how MANY fields a pick carries but
+ * whether it restates the ones that were refused — the relation
+ * ``overwritesRefusedFields`` answers. `{reasoning_effort}` behind a refused
+ * AGENT switch was composed against an Agent the row never took, and applying it
+ * would persist a combination nobody picked; `{model}` behind a refused `{model}`
+ * replaces the exact field that failed, against an Agent nothing has moved, and
+ * dropping it would throw away the user's newest click. Counting fields could not
+ * tell those apart — which is why the group only says WHETHER its fields are
+ * chosen against each other, and the relation says the rest. Nothing in `meta`
+ * is chosen against another field, so nothing there can be composed against a
+ * refusal. */
+export const sessionWriteStandsAlone = (
+ group: SessionWriteGroup,
+ pending: object,
+ refused: object,
+): boolean => (group === 'route' ? overwritesRefusedFields(pending, refused) : true);
+
+// ── What a row's OPEN writes are holding, keyed by session id and group ─────
+//
+// The gate below orders reads against writes within one chat's lifetime: it is
+// replaced whenever the route's session changes, so it cannot speak for a write
+// that outlives the chat that issued it. Leaving a chat and coming back is
+// exactly that — the writer's queue is module state, so the request is still in
+// flight, while the returning chat opens a fresh gate and its bootstrap
+// legitimately installs the row as the server still holds it. The pick would
+// vanish from the picker mid-write, and the next click would be composed against
+// what replaced it: the picker emits an effort change as ``{reasoning_effort}``
+// alone, so the follow-up PATCH would persist an effort chosen for the Agent the
+// open write is switching away from.
+//
+// An open write's record therefore lives at module scope too, and holds both
+// halves of a row's optimistic state:
+//
+// overlay — the fields this document has applied and the server has not
+// answered yet. Re-applied on top of every row that ARRIVES from the server,
+// so no read can show a field an open write has already moved.
+// base — where a REJECTED write puts those fields back: the values the row held
+// before it, advanced past every field the write has since committed, because
+// a burst commits in PARTS and reverting past a committed field would undo a
+// change the server is holding.
+//
+// Records are per session id AND per group, never one slot: renaming one chat
+// while another's route write is in flight is two open writes, and so is renaming
+// THIS chat while its own route write is in flight — each group's request stands
+// or falls on its own, so one slot would let whichever settles first release the
+// other's overlay and revert its fields.
+type OpenRowWrite = { overlay: Record<string, unknown>; base: Record<string, unknown> };
+
+const openRowWrites = new Map<string, Map<SessionWriteGroup, OpenRowWrite>>();
+
+/** Records what a write changes, against the row it is changing. ``opened`` is the
+ * writer's answer to "did this call start the burst" — the one moment at which
+ * the row still holds the values a rejection has to put back. */
+export const recordSessionRowWrite = <T extends { id: string }>(
+ row: T,
+ changes: Partial<T>,
+ opened: boolean,
+ group: SessionWriteGroup,
+): void => {
+ const groups = openRowWrites.get(row.id) ?? new Map<SessionWriteGroup, OpenRowWrite>();
+ const open = (opened ? undefined : groups.get(group)) ?? { overlay: {}, base: {} };
+ for (const field of Object.keys(changes)) {
+ // A field already recorded keeps the value it has — the pre-burst one, or the
+ // newer one a committed request in this same burst moved it to. The picks
+ // folded in behind that request were composed against optimistic state.
+ if (!(field in open.base)) open.base[field] = (row as Record<string, unknown>)[field];
+ }
+ Object.assign(open.overlay, changes);
+ groups.set(group, open);
+ openRowWrites.set(row.id, groups);
+};
+
+/** Moves the rollback target PAST the fields a request has just committed. */
+export const commitSessionRowWrite = <T extends { id: string }>(
+ sessionId: string,
+ changes: Partial<T>,
+ group: SessionWriteGroup,
+): void => {
+ const open = openRowWrites.get(sessionId)?.get(group);
+ if (open) Object.assign(open.base, changes);
+};
+
+/** Ends one group's write and hands back what a rejection must restore. */
+export const releaseSessionRowWrite = <T extends { id: string }>(
+ sessionId: string,
+ group: SessionWriteGroup,
+): Partial<T> | undefined => {
+ const groups = openRowWrites.get(sessionId);
+ const open = groups?.get(group);
+ groups?.delete(group);
+ if (groups && groups.size === 0) openRowWrites.delete(sessionId);
+ return open?.base as Partial<T> | undefined;
+};
+
+/** The row as the user has to keep seeing it: the server's, with every open
+ * write's fields still on top. Deliberately NOT exported — the hook below is the
+ * only way a server-sourced row reaches the state, so no arrival point can
+ * forget this. */
+const withOpenSessionRowWrites = <T extends { id: string }>(row: T): T => {
+ const groups = openRowWrites.get(row.id);
+ if (!groups) return row;
+ let merged = row;
+ // Groups hold disjoint fields, so the order they are applied in cannot matter.
+ for (const open of groups.values()) merged = { ...merged, ...(open.overlay as Partial<T>) };
+ return merged;
+};
+
+/** Drops every record. For tests (module state outlives a render root) and for a
+ * hard document reset; never part of a normal write path. */
+export const resetOpenSessionRowWrites = (): void => {
+ openRowWrites.clear();
+};
+
+// ── The loaded chat row: one state slot, two provenances ────────────────────
+//
+// Reads and events keep arriving for a row this document is mid-way through
+// writing, and every one of them carries the row as the server holds it — which
+// is, correctly, the state before the write. Applying it would not just flicker:
+// the picker composes its next payload from what it displays and emits an effort
+// change as ``{reasoning_effort}`` alone, so a pick made against a row that had
+// jumped back would persist an effort chosen for the Agent the open write is
+// leaving. And a title event landing under an open title write re-seeds the
+// header's editor while the user is still typing in it.
+//
+// So provenance is not a detail a call site may leave implicit. This hook owns
+// the slot and hands out exactly two ways to move it — the raw setter is not in
+// scope for the component — so a new arrival point cannot silently become an
+// exception:
+//
+// installFromServer — a row or field set as the SERVER has it: bootstrap, row
+// re-read, SSE activity, authorization change, an archive 409, a committed
+// sibling mutation. Open writes are re-applied on top.
+// applyLocal — this document's OWN state: the optimistic edit, its rollback,
+// and clearing the row on navigation. These are the SOURCE of the overlay,
+// so they never yield to it.
+export type SessionRowUpdate<T> = T | null | ((prev: T | null) => T | null);
+
+const resolveRowUpdate = <T,>(update: SessionRowUpdate<T>, prev: T | null): T | null =>
+ typeof update === 'function' ? (update as (p: T | null) => T | null)(prev) : update;
+
+export const useChatSessionRow = <T extends { id: string }>() => {
+ const [session, setRow] = useState<T | null>(null);
+ const installFromServer = useCallback((update: SessionRowUpdate<T>) => {
+ setRow((prev) => {
+ const row = resolveRowUpdate(update, prev);
+ return row ? withOpenSessionRowWrites(row) : row;
+ });
+ }, []);
+ const applyLocal = useCallback(
+ (update: SessionRowUpdate<T>) => setRow((prev) => resolveRowUpdate(update, prev)),
+ [],
+ );
+ return { session, installFromServer, applyLocal };
+};
+
export const createSessionRowRefreshGate = (): SessionRowRefreshGate => {
let generation = 0;
let activeMutations = 0;
diff --git a/ui/src/context/WorkbenchProjectDefaultAgent.test.tsx b/ui/src/context/WorkbenchProjectDefaultAgent.test.tsx
new file mode 100644
index 000000000..ee0ad4c7f
--- /dev/null
+++ b/ui/src/context/WorkbenchProjectDefaultAgent.test.tsx
@@ -0,0 +1,920 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, render } from '@testing-library/react';
+import { useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkbenchProjectsProvider } from './WorkbenchProjectsProvider';
+import { useWorkbenchProjectsTree } from './WorkbenchProjectsContext';
+import type { ProjectDefaultAgent, WorkbenchEventHandlers } from './ApiContext';
+import { resetCoalescedWrites } from '../lib/useCoalescedWrite';
+
+type Deferred<T> = {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+ reject: (reason: unknown) => void;
+};
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<T>((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ });
+ return { promise, resolve, reject };
+}
+
+function settle() {
+ return act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+const project = {
+ id: 'proj_a',
+ scope_id: 'scope_a',
+ display_name: 'Project A',
+ folder_path: '/tmp/project-a',
+ created_at: '2026-08-19T00:00:00Z',
+ last_active_at: null,
+ archived: false,
+ default_agent: null,
+};
+
+const route = (over: Partial<ProjectDefaultAgent> = {}): ProjectDefaultAgent => ({
+ agent_backend: null,
+ agent_id: 'agt_claude',
+ agent_name: 'claude',
+ agent_variant: 'claude',
+ model: 'sonnet',
+ reasoning_effort: null,
+ ...over,
+});
+
+// What the shared JSON helpers throw for a ``409 {"code": "project_agent_conflict"}``:
+// an Error carrying the machine code. The code is the whole point — it is what says
+// the failure was about our compare-and-set token and not about the pick — so a
+// generic failure in these tests is a plain `Error`.
+const conflict = () =>
+ Object.assign(new Error('Project default agent changed'), { code: 'project_agent_conflict' });
+
+type UpdateCall = { projectId: string; payload: Record<string, unknown> };
+
+type FakeApi = {
+ getWorkbenchProjectsBootstrap?: (params?: { cache?: boolean }) => Promise<unknown>;
+ updateProject?: (projectId: string, payload: Record<string, unknown>) => Promise<unknown>;
+ connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
+};
+
+const apiRef = { current: null as FakeApi | null };
+
+vi.mock('./ApiContext', async () => {
+ const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');
+ return { ...actual, useApi: () => apiRef.current };
+});
+
+// The provider's own message surface, for the one refusal that never reaches the
+// network and so has no ``apiFetch`` toast of its own. Keyed rather than rendered:
+// the assertion is about which fact the user is told, not about a translation.
+const toasts: string[] = [];
+
+vi.mock('./ToastContext', () => ({
+ useToast: () => ({ showToast: (message: string) => toasts.push(message) }),
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const connectWorkbenchEvents = () => vi.fn(() => vi.fn());
+
+// Records every PATCH and hands back a gate per call, so a write waiting behind
+// the request in flight can be observed as "not sent yet" rather than merely
+// "not resolved yet".
+function gatedUpdateProject(calls: UpdateCall[], gates: Deferred<unknown>[]) {
+ return vi.fn((projectId: string, payload: Record<string, unknown>) => {
+ calls.push({ projectId, payload });
+ const gate = deferred<unknown>();
+ gates.push(gate);
+ return gate.promise;
+ });
+}
+
+function renderTree() {
+ let tree: ReturnType<typeof useWorkbenchProjectsTree> | null = null;
+ const Probe = () => {
+ const value = useWorkbenchProjectsTree();
+ useEffect(() => {
+ tree = value;
+ }, [value]);
+ return null;
+ };
+ render(
+ <WorkbenchProjectsProvider>
+ <Probe />
+ </WorkbenchProjectsProvider>,
+ );
+ return () => tree;
+}
+
+describe('project default Agent route', () => {
+ beforeEach(() => {
+ apiRef.current = null;
+ toasts.length = 0;
+ // The writer's store is module state (a resource outlives the view that edits
+ // it), so each case starts from an empty one.
+ resetCoalescedWrites();
+ });
+
+ afterEach(() => {
+ cleanup();
+ apiRef.current = null;
+ resetCoalescedWrites();
+ vi.restoreAllMocks();
+ });
+
+ it('caches the pick before the request lands, and folds picks made during it into one follow-up', async () => {
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({ projects: [project], sessions: {} }),
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ // The picker's highlight is this cache, so it has to be current already.
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(true);
+ expect(calls).toHaveLength(1);
+ // The project held no route, and the compare-and-set token says what the
+ // SERVER was last confirmed to hold — never what this cache now shows.
+ expect(calls[0].payload).toMatchObject({ expected_agent_id: null, model: 'sonnet' });
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'haiku' }));
+ });
+ expect(tree()!.projects?.[0].default_agent).toEqual(route({ model: 'haiku' }));
+ // Still one request: a route is a whole-snapshot payload, so an earlier one
+ // landing last would undo the newer pick.
+ expect(calls).toHaveLength(1);
+
+ await act(async () => {
+ gates[0].resolve({ ...project, default_agent: route() });
+ await gates[0].promise;
+ });
+ // Two picks, ONE follow-up request: the pick in between was transit, not
+ // intent. Its token is the route the server has just confirmed.
+ expect(calls).toHaveLength(2);
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: 'agt_claude', model: 'haiku' });
+ // The first write's response is already outdated — installing it would drag
+ // the row back to the model the user has clicked past.
+ expect(tree()!.projects?.[0].default_agent).toEqual(route({ model: 'haiku' }));
+
+ await act(async () => {
+ gates[1].resolve({
+ ...project,
+ display_name: 'Renamed by the server',
+ default_agent: route({ model: 'haiku' }),
+ });
+ await gates[1].promise;
+ });
+ await settle();
+ // The last write's response is the truth about the ROUTE it wrote. Its copy of
+ // every other field is only as fresh as the moment the server handled this
+ // request, so the rest of the row is left as the cache holds it.
+ expect(tree()!.projects?.[0]).toEqual({ ...project, default_agent: route({ model: 'haiku' }) });
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ });
+
+ it('keeps a name a rename committed while the route write was in flight', async () => {
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({ projects: [project], sessions: {} }),
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ // A rename issued while the route PATCH is still deciding. It is not serialized
+ // against that write — they are different fields of one row — so both are live.
+ act(() => {
+ void tree()!.renameProject(project.id, 'Renamed by the user');
+ });
+ expect(calls).toHaveLength(2);
+
+ await act(async () => {
+ // The rename commits first, and its response carries the route as the server
+ // held it BEFORE the pick — which the commit path drops on the floor.
+ gates[1].resolve({ ...project, display_name: 'Renamed by the user', default_agent: null });
+ await gates[1].promise;
+ });
+ await settle();
+ expect(tree()!.projects?.[0]).toMatchObject({
+ display_name: 'Renamed by the user',
+ default_agent: route(),
+ });
+
+ await act(async () => {
+ // And the route response carries the name as the server held it before the
+ // rename. Symmetry is the whole point: neither response may install the row
+ // it saw, because nothing re-reads the tree after a write that succeeded.
+ gates[0].resolve({ ...project, default_agent: route({ agent_backend: 'claude' }) });
+ await gates[0].promise;
+ });
+ await settle();
+
+ expect(tree()!.projects?.[0]).toEqual({
+ ...project,
+ display_name: 'Renamed by the user',
+ default_agent: route({ agent_backend: 'claude' }),
+ });
+ });
+
+ it('takes the route the server derived once the pick is no longer superseded', async () => {
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({ projects: [project], sessions: {} }),
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ // The picker composes a route with NO backend — only the server knows which
+ // backend an Agent belongs to — so the optimistic route is knowingly partial.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ agent_backend: null }));
+ });
+ expect(tree()!.projects?.[0].default_agent).toEqual(route({ agent_backend: null }));
+
+ await act(async () => {
+ gates[0].resolve({ ...project, default_agent: route({ agent_backend: 'claude' }) });
+ await gates[0].promise;
+ });
+ await settle();
+
+ // Nothing is left for the optimistic route to protect once this pick is the
+ // newest one, so the response's route is installed as it stands. Keeping the
+ // overlay up would hold a backend-less route in the cache until an unrelated
+ // refresh — and a picker that has lost the Agent list could no longer tell
+ // which model or effort options to offer.
+ expect(tree()!.projects?.[0].default_agent).toEqual(route({ agent_backend: 'claude' }));
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ });
+
+ it('reverts a partly committed burst to what the server took, not to where the burst started', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const stuck = deferred<unknown>();
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [{ ...project, default_agent: route() }], sessions: {} })
+ // Left unanswered on purpose: the local revert is the only thing acting.
+ .mockReturnValueOnce(stuck.promise);
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ const codex = route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex', model: 'gpt-5' });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, codex);
+ });
+ // A second pick while that request is in flight — the effort for the Agent the
+ // first pick switched to.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, { ...codex, reasoning_effort: 'high' });
+ });
+ expect(calls).toHaveLength(1);
+
+ await act(async () => {
+ gates[0].resolve({ ...project, default_agent: { ...codex, agent_backend: 'codex' } });
+ await gates[0].promise;
+ });
+ await settle();
+ // The Agent switch is on the server now; the effort follows it in one request.
+ expect(calls).toHaveLength(2);
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: 'agt_codex', reasoning_effort: 'high' });
+
+ await act(async () => {
+ gates[1].reject(new Error('boom'));
+ await gates[1].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // Only the effort goes back. This burst committed in PARTS, so reverting to
+ // the route it started from would undo an Agent switch the server is holding —
+ // a rollback that invents a state nobody is in. The target is the last
+ // CONFIRMED route, which is also why the backend the server derived survives.
+ expect(tree()!.projects?.[0].default_agent).toEqual({ ...codex, agent_backend: 'codex' });
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+
+ // And the next pick expects that same confirmed route, so it is not born into
+ // a deterministic conflict.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, { ...codex, model: 'gpt-5-codex' });
+ });
+ expect(calls).toHaveLength(3);
+ expect(calls[2].payload).toMatchObject({ expected_agent_id: 'agt_codex', model: 'gpt-5-codex' });
+ });
+
+ it('sends the pick waiting behind a rejected write, because a project route stands on its own', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: {} })
+ .mockResolvedValueOnce({ projects: [project], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ expect(calls).toHaveLength(1);
+
+ await act(async () => {
+ gates[0].reject(new Error('boom'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The waiting pick is a COMPLETE route with its own send-time token: it was
+ // never composed against the route the server just refused, so the refusal
+ // says nothing about it. It is also the user's newest choice, so it goes out
+ // rather than being dropped — and it expects what the server confirmed
+ // (nothing yet), not the route that was refused.
+ expect(calls).toHaveLength(2);
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: null, model: 'opus' });
+ // The burst is still going, so nothing has been rolled back and nothing re-read.
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(1);
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(true);
+
+ await act(async () => {
+ gates[1].resolve({ ...project, default_agent: route({ agent_backend: 'claude', model: 'opus' }) });
+ });
+ await settle();
+
+ // It landed, so the burst ends committed: the cache shows what the server took
+ // and there is nothing to revert to.
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(1);
+ expect(tree()!.projects?.[0].default_agent).toMatchObject({ agent_backend: 'claude', model: 'opus' });
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ });
+
+ it('ends the burst when the refusal invalidates the token the next send would derive', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const stored = { ...project, default_agent: route() };
+ // Another surface moved the route since our last read — which is what makes our
+ // token stale, and what only a re-read can report.
+ const moved = { ...project, default_agent: route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex' }) };
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [stored], sessions: {} })
+ .mockResolvedValueOnce({ projects: [moved], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'haiku' }));
+ });
+ expect(calls).toHaveLength(1);
+ expect(calls[0].payload).toMatchObject({ expected_agent_id: 'agt_claude', model: 'opus' });
+
+ await act(async () => {
+ gates[0].reject(conflict());
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The waiting pick carries a whole route, so by its own fields it stands alone —
+ // but the send would derive its compare-and-set token from a confirmation this
+ // very failure contradicted, so it is a guaranteed second conflict and a second
+ // toast for a pick that never had a chance. The burst ends instead. We do NOT
+ // adopt the conflict's current agent and retry: that would overwrite whoever
+ // moved the route with a pick made before the user could know about it.
+ expect(calls).toHaveLength(1);
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenNthCalledWith(2, { cache: false });
+ expect(tree()!.projects?.[0].default_agent).toEqual(moved.default_agent);
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ });
+
+ it('lets a pick stand alone again once a read has answered the conflict', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const stored = { ...project, default_agent: route() };
+ const moved = { ...project, default_agent: route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex' }) };
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [stored], sessions: {} })
+ .mockResolvedValueOnce({ projects: [moved], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ await act(async () => {
+ gates[0].reject(conflict());
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+ expect(tree()!.projects?.[0].default_agent).toEqual(moved.default_agent);
+
+ // The doubt was about that one confirmation, and the read has replaced it. So a
+ // later burst is back to the normal rule: a whole-route pick waiting behind a
+ // refused request goes out, because nothing it depends on was invalidated.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'haiku' }));
+ });
+ await act(async () => {
+ gates[1].reject(new Error('boom'));
+ await gates[1].promise.catch(() => undefined);
+ });
+ await settle();
+
+ expect(calls).toHaveLength(3);
+ expect(calls[2].payload).toMatchObject({ expected_agent_id: 'agt_codex', model: 'haiku' });
+
+ await act(async () => {
+ gates[2].resolve({ ...moved, default_agent: route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex', agent_backend: 'codex', model: 'haiku' }) });
+ await gates[2].promise;
+ });
+ await settle();
+ // Committed on the send that ended the burst, and no second rollback read.
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);
+ expect(tree()!.projects?.[0].default_agent).toMatchObject({ agent_backend: 'codex', model: 'haiku' });
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ });
+
+ it('refuses a pick made after the conflicted burst ended, until a read has answered it', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const stored = { ...project, default_agent: route() };
+ const moved = { ...project, default_agent: route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex' }) };
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [stored], sessions: {} })
+ // The read that would answer the conflict fails, so nothing has replaced the
+ // confirmation the server contradicted. This is the state that separates the
+ // rule from the writer's admission of a WAITING patch: the burst is over.
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce({ projects: [moved], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ await act(async () => {
+ gates[0].reject(conflict());
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+ expect(calls).toHaveLength(1);
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+
+ // A brand-new burst, with no pending patch anywhere for the writer to judge. It
+ // would derive its token from the confirmation the 409 contradicted, so it is a
+ // guaranteed second conflict: refused at the send, where the token comes from,
+ // and the user is told the same fact the 409 carries rather than watching the
+ // click revert for no stated reason.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'haiku' }));
+ });
+ await settle();
+ expect(calls).toHaveLength(1);
+ expect(toasts).toEqual(['errors.project_agent_conflict']);
+ // Refused is not stuck: the rollback puts the confirmed route back and asks
+ // again, and THAT read is what lifts the doubt.
+ expect(tree()!.projects?.[0].default_agent).toEqual(moved.default_agent);
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex', model: 'haiku' }));
+ });
+ await settle();
+ expect(calls).toHaveLength(2);
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: 'agt_codex', model: 'haiku' });
+ expect(toasts).toEqual(['errors.project_agent_conflict']);
+ });
+
+ it('reverts the whole burst when the pick that stood alone is refused too', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: {} })
+ .mockResolvedValueOnce({ projects: [project], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+
+ await act(async () => {
+ gates[0].reject(new Error('boom'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+ await act(async () => {
+ gates[1].reject(new Error('boom'));
+ await gates[1].promise.catch(() => undefined);
+ });
+ await settle();
+
+ expect(calls).toHaveLength(2);
+ // Continuing past the first failure must not fragment the reconcile: the burst
+ // settles ONCE, on the outcome of the send that ended it, and reverts to the
+ // last route the server confirmed — which is still no route at all.
+ expect(tree()!.projects?.[0].default_agent).toBeNull();
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenNthCalledWith(2, { cache: false });
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+
+ // And the extra request has not poisoned the next pick's token.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ expect(calls).toHaveLength(3);
+ expect(calls[2].payload).toMatchObject({ expected_agent_id: null, model: 'opus' });
+ });
+
+ it('does not let a rename response revert the route or poison the next write', async () => {
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({ projects: [project], sessions: {} }),
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ // A rename and a route pick are separate requests on the same row, and the
+ // rename answers LAST — carrying the row as it was before the pick.
+ act(() => {
+ void tree()!.renameProject(project.id, 'Renamed');
+ });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ expect(calls[0].payload).toEqual({ display_name: 'Renamed' });
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: null, model: 'sonnet' });
+
+ await act(async () => {
+ gates[1].resolve({ ...project, default_agent: route() });
+ await gates[1].promise;
+ });
+ await settle();
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+
+ await act(async () => {
+ gates[0].resolve({ ...project, display_name: 'Renamed', default_agent: null });
+ await gates[0].promise;
+ });
+ await settle();
+ // Only the field the rename changed is taken. Installing its snapshot whole
+ // would revert the route the user just set...
+ expect(tree()!.projects?.[0].display_name).toBe('Renamed');
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+
+ // ...and recording it as confirmed would hand the next pick a token naming a
+ // route the server has already replaced — a deterministic conflict.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ expect(calls[2].payload).toMatchObject({ expected_agent_id: 'agt_claude', model: 'opus' });
+ });
+
+ it('rolls a rejected pick back by re-reading the server, and retries against that route', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const serverTruth = {
+ ...project,
+ default_agent: route({ agent_id: 'agt_codex', agent_name: 'codex', agent_variant: 'codex' }),
+ };
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: {} })
+ .mockResolvedValueOnce({ projects: [serverTruth], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+
+ await act(async () => {
+ gates[0].reject(conflict());
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The pick lived only in this cache, so the rollback is a re-read — which
+ // here reveals the route another surface had set meanwhile.
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenNthCalledWith(2, { cache: false });
+ expect(tree()!.projects?.[0].default_agent).toEqual(serverTruth.default_agent);
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ // A read confirms a route too: the next write expects what that read found.
+ expect(calls).toHaveLength(2);
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: 'agt_codex', model: 'opus' });
+ });
+
+ it('keeps each project on its own writer, so one failing project cannot hold another up', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const other = { ...project, id: 'proj_b', scope_id: 'scope_b', display_name: 'Project B' };
+ const otherSaved = { ...other, default_agent: route({ model: 'sonnet' }) };
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project, other], sessions: {} })
+ // The rollback re-read is a whole-tree read: by then the server HAS taken
+ // Project B's write, so its row comes back with B's route, not the pre-pick one.
+ .mockResolvedValueOnce({ projects: [{ ...project, default_agent: null }, otherSaved], sessions: {} });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ tree()!.setProjectDefaultAgent(other.id, route({ model: 'sonnet' }));
+ });
+ // Two requests, not one: Project B has nothing to overwrite in Project A, so
+ // it goes out immediately instead of waiting behind A's request.
+ expect(calls.map((c) => c.projectId)).toEqual([project.id, other.id]);
+
+ await act(async () => {
+ gates[1].resolve(otherSaved);
+ await gates[1].promise;
+ });
+ await settle();
+ // B settles on its own: no rollback read, and no waiting on A.
+ expect(tree()!.isSavingDefaultAgent(other.id)).toBe(false);
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ gates[0].reject(new Error('boom'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // A's refused request does not take the pick behind it down — a project route
+ // stands on its own — so A sends a third request. It is still A's writer alone:
+ // B settled long ago and is not touched again.
+ expect(calls.map((c) => c.projectId)).toEqual([project.id, other.id, project.id]);
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(true);
+ expect(tree()!.isSavingDefaultAgent(other.id)).toBe(false);
+
+ await act(async () => {
+ gates[2].reject(new Error('boom'));
+ await gates[2].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // Now A's burst is over and rolls back to the server route, while B's pick
+ // survives a failure it had no part in.
+ expect(tree()!.projects?.[0].default_agent).toBeNull();
+ expect(tree()!.projects?.[1].default_agent).toEqual(route({ model: 'sonnet' }));
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ });
+
+ it('caches a cleared route as no default at all', async () => {
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({
+ projects: [{ ...project, default_agent: route() }],
+ sessions: {},
+ }),
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ const cleared = route({ agent_id: null, agent_name: null, agent_variant: null, model: null });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, cleared);
+ });
+
+ // An all-null route means "follow the global default", which the server
+ // reports as no route at all — consumers read `default_agent?.agent_name`.
+ expect(tree()!.projects?.[0].default_agent).toBeNull();
+ expect(calls[0].payload).toMatchObject({
+ agent_id: null,
+ agent_name: null,
+ model: null,
+ // The bootstrap is a confirmation: clearing expects the route it reported.
+ expected_agent_id: 'agt_claude',
+ });
+ });
+
+ it('keeps a projects read that was already in flight from undoing the pick', async () => {
+ const stale = deferred<unknown>();
+ const neverSettles = deferred<unknown>();
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: {} })
+ .mockReturnValueOnce(stale.promise)
+ .mockReturnValueOnce(neverSettles.promise);
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ void tree()!.refreshProjects();
+ });
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+
+ await act(async () => {
+ stale.resolve({ projects: [project], sessions: {} });
+ await stale.promise;
+ });
+
+ // That read began before the pick, so its snapshot is the pre-pick route.
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+ });
+
+ it('keeps a read that starts after the pick from undoing it, while still installing the rest of that snapshot', async () => {
+ const later = deferred<unknown>();
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: {} })
+ .mockReturnValueOnce(later.promise)
+ .mockResolvedValueOnce({
+ projects: [{ ...project, default_agent: route({ model: 'opus' }) }],
+ sessions: {},
+ });
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route());
+ });
+ // A read issued AFTER the pick: its stamp is legitimately current, so the
+ // ordering fence cannot refuse it — yet the server had not committed the
+ // PATCH when it was answered.
+ act(() => {
+ void tree()!.refreshProjects();
+ });
+ await act(async () => {
+ later.resolve({
+ projects: [{ ...project, display_name: 'Renamed elsewhere', default_agent: null }],
+ sessions: {},
+ });
+ await later.promise;
+ });
+ await settle();
+
+ // The pick outranks the incoming row, and only on that one field: this
+ // snapshot is otherwise the newest truth there is, so discarding it whole
+ // would drop a rename the user is entitled to see.
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+ expect(tree()!.projects?.[0].display_name).toBe('Renamed elsewhere');
+
+ await act(async () => {
+ gates[0].resolve({ ...project, display_name: 'Renamed elsewhere', default_agent: route() });
+ await gates[0].promise;
+ });
+ await settle();
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+
+ // And the precedence is not sticky: once the write has settled there is no
+ // pick to protect, so a later read is free to move the route again — which is
+ // how another surface's change reaches this one.
+ await act(async () => {
+ await tree()!.refreshProjects();
+ });
+ await settle();
+ expect(tree()!.projects?.[0].default_agent).toEqual(route({ model: 'opus' }));
+ });
+
+ it('reverts a rejected burst to the route it replaced, without waiting for a re-read', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const stuck = deferred<unknown>();
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [{ ...project, default_agent: route() }], sessions: {} })
+ .mockReturnValueOnce(stuck.promise);
+ const calls: UpdateCall[] = [];
+ const gates: Deferred<unknown>[] = [];
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ updateProject: gatedUpdateProject(calls, gates),
+ connectWorkbenchEvents: connectWorkbenchEvents(),
+ };
+ const tree = renderTree();
+ await settle();
+
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'opus' }));
+ });
+ expect(tree()!.projects?.[0].default_agent).toEqual(route({ model: 'opus' }));
+
+ await act(async () => {
+ gates[0].reject(new Error('boom'));
+ await gates[0].promise.catch(() => undefined);
+ });
+ await settle();
+
+ // The rollback is local and complete on its own: the pick lived only in this
+ // cache, so putting back the route it replaced needs no network. The re-read
+ // below may only be QUEUED — ``fetchProjects`` records a trailing intent when
+ // one is already in flight — so a rollback that waited for it would clear the
+ // indicator while leaving the refused route on screen.
+ expect(tree()!.projects?.[0].default_agent).toEqual(route());
+ expect(tree()!.isSavingDefaultAgent(project.id)).toBe(false);
+ // Still asked, unawaited: a compare-and-set conflict means someone else moved
+ // the route, and only a read can say to what.
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenNthCalledWith(2, { cache: false });
+
+ // The revert restores what the server CONFIRMED, so the next pick's token is
+ // coherent with it even though that read has not answered.
+ act(() => {
+ tree()!.setProjectDefaultAgent(project.id, route({ model: 'haiku' }));
+ });
+ expect(calls).toHaveLength(2);
+ expect(calls[1].payload).toMatchObject({ expected_agent_id: 'agt_claude', model: 'haiku' });
+ });
+});
diff --git a/ui/src/context/WorkbenchProjectsContext.ts b/ui/src/context/WorkbenchProjectsContext.ts
index 3bf241e9b..8dc10fefb 100644
--- a/ui/src/context/WorkbenchProjectsContext.ts
+++ b/ui/src/context/WorkbenchProjectsContext.ts
@@ -43,15 +43,21 @@ export interface WorkbenchProjectsActions {
* i.e. no project-bound scope) forks with `null` and simply has no row to place. */
forkSession: (projectId: string | null, sessionId: string) => Promise<WorkbenchSession | null>;
renameProject: (projectId: string, name: string) => Promise<void>;
- /** Persist the project's default Agent route (Project Settings) and patch the
- * shared cache so the sidebar + Projects page reflect it. Pass an all-null
- * route to clear the default back to the global default. Throws on failure
- * (the apiFetch layer already surfaced a toast) so the dialog can react. */
- setProjectDefaultAgent: (
- projectId: string,
- route: ProjectDefaultAgent,
- expectedAgentId: string | null,
- ) => Promise<void>;
+ /** Set the project's default Agent route (Project Settings): patches the shared
+ * cache FIRST, so the sidebar + Projects page + the picker's own highlight move
+ * within the click, then persists behind it. Pass an all-null route to clear
+ * the default back to the global default. Never throws and never resolves — a
+ * pick made while the last one is in flight replaces it, a failure is already
+ * toasted by the apiFetch layer, and the cache is reconciled from the server on
+ * settle. The route's compare-and-set token is NOT a parameter: only the writer
+ * knows which route the server last confirmed, and a caller reading it off this
+ * optimistic cache would expect a route the server may have refused. */
+ setProjectDefaultAgent: (projectId: string, route: ProjectDefaultAgent) => void;
+ /** Whether this project's default Agent is mid-write — from the pick until the
+ * server route is reconciled. Per project: the writes are partitioned per
+ * project too, so one project's slow save neither blocks nor spins another's
+ * picker. */
+ isSavingDefaultAgent: (projectId: string) => boolean;
archiveProject: (projectId: string) => Promise<void>;
/** Throws on failure so the row's inline editor can fall back; patches title on success. */
renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 2f6a4b299..aefc55bf1 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -1,7 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
import { useApi } from './ApiContext';
+import { useToast } from './ToastContext';
import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, WorkbenchSessionCreate } from './ApiContext';
import {
WorkbenchProjectsContext,
@@ -10,6 +12,7 @@ import {
} from './WorkbenchProjectsContext';
import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';
import { orderProjectSessions } from '../lib/sessionPinning';
+import { overwritesRefusedFields, useCoalescedWrite } from '../lib/useCoalescedWrite';
import { errorMessage } from '@/lib/errorMessage';
import { useConsumerActivation } from '@/lib/useConsumerActivation';
import {
@@ -35,6 +38,32 @@ const EMPTY_SESSIONS: ProjectSessionsState = {
error: false,
};
+// What a commit learned about a project's route straight from the server. Only
+// the route, because that is all a confirmation is for: it is the compare-and-set
+// token the next write must expect to find, so a whole row would invite a caller
+// to pass one it has not actually had confirmed.
+type ProjectRouteConfirmation = { id: string; default_agent?: ProjectDefaultAgent | null };
+
+// What a route pick means for the cached row: an all-null route is the user
+// CLEARING the default, which the row carries as no default agent at all. One
+// helper because two places have to agree — the optimistic write and the overlay
+// that defends it against incoming rows.
+const appliedRoute = (route: ProjectDefaultAgent): ProjectDefaultAgent | null => {
+ const cleared = !(
+ route.agent_id || route.agent_name || route.agent_variant || route.model || route.reasoning_effort
+ );
+ return cleared ? null : route;
+};
+
+// The one rejection that is evidence about our compare-and-set token rather than
+// about the pick: the server compared `expected_agent_id` against the project's
+// current agent and they differed, so whatever we had confirmed is no longer what
+// is stored. Duck-typed on ``code`` like ``isSessionArchivedError`` — the shared
+// JSON helpers already parsed the 409 body into an ``ApiError`` carrying it — so a
+// plain ``Error`` from a network failure is correctly not a conflict.
+const isProjectAgentConflictError = (err: unknown): boolean =>
+ (err as { code?: unknown } | null | undefined)?.code === 'project_agent_conflict';
+
// Scan every project's loaded rows for a session id and apply `patch`; returns a
// new state only when something actually changed (so unrelated consumers don't
// re-render). Used for both the status-dot and title SSE patches — keyed on
@@ -105,6 +134,10 @@ const REORDER_ACTIVITY_EVENTS = new Set(['created', 'user_message', 'show_event'
// WorkbenchInboxContext (both consumers read it directly).
export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const api = useApi();
+ const { t } = useTranslation();
+ // The write paths here report their own failures through ``apiFetch``; this is
+ // for the one refusal that never reaches the network (see ``sendProjectRoute``).
+ const { showToast } = useToast();
// The tree is workbench-only data behind an app-level provider. Nothing under
// /admin renders a project, so nothing there should pay for the bootstrap —
// neither on load nor on an SSE reconnect.
@@ -146,6 +179,39 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const treeInitialFetched = useRef(false);
const fetchProjectsPendingRef = useRef<{ cache?: boolean } | null>(null);
const projectTreePendingRef = useRef(false);
+ // The newest default-Agent pick per project, so an earlier write's response can
+ // be recognised as already outdated by the time it arrives.
+ const latestProjectRouteRef = useRef(new Map<string, ProjectDefaultAgent>());
+ // The route each project was last CONFIRMED to hold by the server. It cannot be
+ // read off the list below, because that list also carries picks the server has
+ // not accepted yet. Two things read it, and both need the same value:
+ //
+ // - the compare-and-set token a route write must expect — expecting a pick the
+ // server refused is what turns one rejected write into a deterministic
+ // ``project_agent_conflict`` on the retry;
+ // - where a REJECTED burst puts the row back. That is this ref rather than a
+ // per-burst snapshot because a burst can commit in PARTS: the Agent pick can
+ // land and the effort pick folded in behind it can fail, and rolling back to
+ // where the burst started would then undo a change the server is holding.
+ // Every commit and every read advances this ref, so "the last state the
+ // server confirmed" needs no bookkeeping of its own.
+ const confirmedProjectRouteRef = useRef(new Map<string, ProjectDefaultAgent | null>());
+ // The projects whose confirmation the server has CONTRADICTED: a
+ // ``project_agent_conflict`` is the one failure that says the entry above is
+ // wrong, because the token it produced is exactly what the server compared. The
+ // route it still holds is unknown until a read answers, so the entry stays (it is
+ // also the rollback target, and inventing a route to display would be worse than
+ // showing a stale one for a moment) and the doubt is recorded beside it.
+ //
+ // While a project is in here, ``sendProjectRoute`` refuses to write it at all —
+ // read at the one place the token is DERIVED, so it holds for a brand-new burst
+ // and not only for a patch already waiting. The alternatives are both wrong
+ // rather than merely worse: sending the contradicted token is a request we know
+ // the server will refuse, and re-deriving the token from what the conflict (or a
+ // fresh read) says is stored turns compare-and-set into last-writer-wins, which
+ // is the lost update the token exists to prevent. Cleared wherever the
+ // confirmation is re-established — one place, below.
+ const contradictedProjectRouteRef = useRef(new Set<string>());
const fetchProjectsRunnerRef = useRef<(options?: { cache?: boolean }) => void>(() => {});
const projectTreeRunnerRef = useRef<() => void>(() => {});
@@ -155,20 +221,95 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// their request and discard the response, and why asking beforehand would have
// dropped the window a just-created project needs. A read cannot decline a request
// on an answer it can only trust afterwards.
+ //
+ // ``confirmed`` names the rows THIS commit takes from the server, which is also
+ // where the compare-and-set token for a route write comes from. Declared per
+ // commit rather than inferred from the list, because a commit can install a
+ // server row into a list that still holds another project's optimistic pick —
+ // and recording that pick as confirmed is exactly the mistake the token exists
+ // to prevent. Omitting it records nothing, so the cost of a future commit
+ // forgetting is a stale token (one loud conflict, then a re-read) rather than a
+ // wrong one.
const commitProjects = useCallback(
(
next:
| WorkbenchProject[]
| null
| ((prev: WorkbenchProject[] | null) => WorkbenchProject[] | null),
+ options?: { confirmed?: ProjectRouteConfirmation[] | null },
) => {
- const resolved = typeof next === 'function' ? next(projectsRef.current) : next;
+ const requested = typeof next === 'function' ? next(projectsRef.current) : next;
+ // ── The in-flight pick outranks every incoming row ────────────────────
+ // A read that STARTS after a pick still answers with what the server held
+ // before the PATCH committed, and its read stamp is legitimately current —
+ // so the ordering fence cannot refuse it and the highlight would jump back
+ // to the old Agent until the PATCH response arrives. The same is true of
+ // any other producer of a row (a rename response, a find-or-create upsert,
+ // a reconnect reconcile). Applied HERE rather than at each of them: the
+ // callers are what keeps growing, the property is one. `confirmed` below is
+ // deliberately untouched — a read still records what the server actually
+ // holds, which is exactly the compare-and-set token the next write needs.
+ const inFlight = latestProjectRouteRef.current;
+ const resolved =
+ requested && inFlight.size
+ ? requested.map((project) =>
+ inFlight.has(project.id)
+ ? { ...project, default_agent: appliedRoute(inFlight.get(project.id)!) }
+ : project,
+ )
+ : requested;
projectsRef.current = resolved;
+ if (options && 'confirmed' in options) {
+ const confirmed = confirmedProjectRouteRef.current;
+ const contradicted = contradictedProjectRouteRef.current;
+ // Whatever the server just told us about a project's route replaces our
+ // doubt about it, so the two move together: this is the only place either
+ // is written, which is what keeps "contradicted" from outliving the read
+ // that answers it.
+ if (options.confirmed === null) {
+ confirmed.clear();
+ contradicted.clear();
+ } else {
+ for (const project of options.confirmed ?? []) {
+ confirmed.set(project.id, project.default_agent ?? null);
+ contradicted.delete(project.id);
+ }
+ }
+ }
setProjects(resolved);
},
[],
);
+ // ── A mutation commits the fields it wrote, never the row it saw ─────────────
+ // Every project mutation answers with a snapshot of the row as that request
+ // found it, so its authority is scoped to the fields that request changed: a
+ // rename's copy of the route can be older than a pick still in flight, and a
+ // route response's copy of the name can be older than a rename that has already
+ // committed. Installing either whole reinstates state the server has since
+ // replaced, with no read scheduled to correct it. Mutations therefore hand over
+ // FIELDS — and pass ``fields: null`` when their answer has been superseded and
+ // only its confirmation is still worth keeping.
+ //
+ // ``confirmedRoute`` is the route the server just said it holds, which is where
+ // the next write's compare-and-set token comes from. Passed explicitly rather
+ // than read out of ``fields``, because an optimistic pick writes that same field
+ // with a value the server has not accepted yet.
+ const commitProjectFields = useCallback(
+ (
+ projectId: string,
+ fields: Partial<WorkbenchProject> | null,
+ options?: { confirmedRoute: ProjectDefaultAgent | null },
+ ) => {
+ commitProjects(
+ (prev) =>
+ prev && fields ? prev.map((p) => (p.id === projectId ? { ...p, ...fields } : p)) : prev,
+ options ? { confirmed: [{ id: projectId, default_agent: options.confirmedRoute }] } : undefined,
+ );
+ },
+ [commitProjects],
+ );
+
// ── One question, asked immediately before every read request ────────────────
// Every read this provider owns commits into a cache, and two things can make
// that commit impossible or pointless before the response even arrives. There may
@@ -265,7 +406,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const applyProjectsSnapshot = useCallback((nextProjects: WorkbenchProject[]) => {
const accessibleIds = new Set(nextProjects.map((project) => project.id));
- commitProjects(nextProjects);
+ commitProjects(nextProjects, { confirmed: nextProjects });
setSessions((prev) =>
Object.fromEntries(
Object.entries(prev).filter(([projectId]) => accessibleIds.has(projectId)),
@@ -306,7 +447,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
...[...cachedProjectIds].map((projectId) => `project:${projectId}`),
...[...sessionProjectRef.current.keys()].map((sessionId) => `project-session:${sessionId}`),
]);
- commitProjects(null);
+ commitProjects(null, { confirmed: null });
sessionsRef.current = {};
expandedRef.current = new Set();
sessionProjectRef.current.clear();
@@ -1012,12 +1153,17 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
try {
const updated = await api.updateProject(projectId, { display_name: name });
acceptProjectsMutation();
- commitProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
+ // Only the field this request changed (see ``commitProjectFields``), and no
+ // confirmation: a rename is not route truth, and recording its copy of the
+ // route would hand the compare-and-set token a route the server may have
+ // replaced since — making the user's next pick a deterministic
+ // ``project_agent_conflict``.
+ commitProjectFields(projectId, { display_name: updated.display_name });
} catch (err) {
console.error('[workbench] rename project failed', err);
}
},
- [acceptProjectsMutation, api, commitProjects],
+ [acceptProjectsMutation, api, commitProjectFields],
);
const forkSession = useCallback(
@@ -1061,23 +1207,135 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
[acceptSessionMutation, api, fetchSessions],
);
+ const sendProjectRoute = useCallback(
+ async (route: ProjectDefaultAgent, projectId: string): Promise<boolean> => {
+ // The compare-and-set token is derived HERE, at send time, from the last
+ // route the server confirmed — never from the cache, which is showing the
+ // pick this very request is trying to install. That is what keeps a
+ // rejected pick from poisoning the next one: expecting the route the server
+ // refused would make every retry a deterministic conflict.
+ //
+ // And if that confirmation has been contradicted, no token can be derived at
+ // all, so the write does not go out: the server has told us our token is
+ // wrong, and it is the only party that can say what the right one is. Refused
+ // here rather than at the writer's admission of a waiting patch, because this
+ // is the single line every project-route write passes through — a pick made
+ // after the burst ended reaches exactly the same answer. The user is told the
+ // same thing the 409 says, since a click that silently reverts is the lag this
+ // whole path exists to remove; the toast layer collapses the repeat when this
+ // is the same incident's second pick.
+ if (contradictedProjectRouteRef.current.has(projectId)) {
+ showToast(t('errors.project_agent_conflict'), 'error');
+ return false;
+ }
+ const expectedAgentId = confirmedProjectRouteRef.current.get(projectId)?.agent_id ?? null;
+ try {
+ // Always send the full 5-field route: a complete set is coherent whether
+ // the user picked an agent (all set) or cleared it (all null → default
+ // dropped).
+ const updated = await api.updateProject(projectId, {
+ agent_id: route.agent_id,
+ expected_agent_id: expectedAgentId,
+ agent_name: route.agent_name,
+ agent_variant: route.agent_variant,
+ model: route.model,
+ reasoning_effort: route.reasoning_effort,
+ });
+ acceptProjectsMutation();
+ // Only the newest pick's response is still the truth: a pick made while
+ // this request was in flight is already on screen, and installing this
+ // answer would drag the row back to the route the user clicked past — the
+ // lag this optimistic path exists to remove. The response is still
+ // recorded as confirmed, because the server did take it: that is what the
+ // follow-up write must expect to find.
+ const superseded = route !== latestProjectRouteRef.current.get(projectId);
+ // The route the server derived — the picker composes a pick with no backend,
+ // because only the server knows which backend an Agent belongs to.
+ const serverRoute = updated.default_agent ?? null;
+ // Nothing is left for the overlay to protect once THIS pick is the newest
+ // one, and leaving it up would re-apply the backend-less optimistic route on
+ // top of the route the server derived: the cache would keep a route the
+ // server never sent until an unrelated refresh, and a picker that has lost
+ // the Agent list could no longer tell which model or effort options to offer.
+ if (!superseded) latestProjectRouteRef.current.delete(projectId);
+ commitProjectFields(projectId, superseded ? null : { default_agent: serverRoute }, {
+ confirmedRoute: serverRoute,
+ });
+ return true;
+ } catch (err) {
+ // A conflict is the server saying the token above was wrong, so it is the
+ // one failure that invalidates the confirmation the NEXT send would derive
+ // its token from. Record the doubt where the confirmation lives; nothing
+ // built on it stands on its own until a read answers.
+ if (isProjectAgentConflictError(err)) contradictedProjectRouteRef.current.add(projectId);
+ // apiFetch already surfaced the toast; the settle re-read below is what
+ // puts the optimistic row back to what the server actually holds.
+ console.error('[workbench] set project default agent failed', err);
+ return false;
+ }
+ },
+ [acceptProjectsMutation, api, commitProjectFields, showToast, t],
+ );
+
+ const { write: writeProjectRoute, isSaving: isSavingDefaultAgent } = useCoalescedWrite<ProjectDefaultAgent>(
+ 'project-route',
+ sendProjectRoute,
+ {
+ // Asked as the relation it is, not asserted for this owner: a pick overwrites
+ // every field the refused one wrote, because ``sendProjectRoute`` composes the
+ // full 5-field route either way — so a refusal says nothing about the pick
+ // waiting behind it, and dropping it would discard the user's newest choice
+ // for nothing. Should a route payload ever narrow to the field the user
+ // touched (as the session picker's does), the same answer covers it without
+ // this line changing. The one precondition a pick does NOT carry — the
+ // compare-and-set token — is enforced where it is derived, above.
+ standsAlone: overwritesRefusedFields,
+ onSettled: useCallback(
+ (projectId: string, committed: boolean) => {
+ latestProjectRouteRef.current.delete(projectId);
+ if (committed) return;
+ // A rejected pick lives only in this cache, so the rollback is local:
+ // put back the last route the server CONFIRMED. Synchronous and complete
+ // on its own — the previous revision awaited a whole-tree re-read
+ // instead, which is a read this provider may only be able to QUEUE
+ // (``fetchProjects`` records a trailing intent when one is already in
+ // flight), so the refused route stayed on screen after the indicator had
+ // gone. The confirmation, not a snapshot of where the burst started: a
+ // burst that committed its Agent pick and then had an effort pick refused
+ // must keep the Agent the server took.
+ const confirmed = confirmedProjectRouteRef.current;
+ if (confirmed.has(projectId)) {
+ commitProjectFields(projectId, { default_agent: confirmed.get(projectId) ?? null });
+ }
+ // Still re-read, unawaited: the confirmation is what the server told THIS
+ // document, and a compare-and-set conflict means someone else has moved
+ // the route since — only a read can say to what. The revert above is
+ // already on screen, so nothing waits for it, and a pick made meanwhile
+ // fences it through ``acceptProjectsMutation``.
+ void fetchProjects({ cache: false });
+ },
+ [commitProjectFields, fetchProjects],
+ ),
+ },
+ );
+
const setProjectDefaultAgent = useCallback(
- async (projectId: string, route: ProjectDefaultAgent, expectedAgentId: string | null) => {
- // Always send the full 5-field route: a complete set is coherent whether
- // the user picked an agent (all set) or cleared it (all null → default
- // dropped). Let failures propagate — apiFetch already toasted.
- const updated = await api.updateProject(projectId, {
- agent_id: route.agent_id,
- expected_agent_id: expectedAgentId,
- agent_name: route.agent_name,
- agent_variant: route.agent_variant,
- model: route.model,
- reasoning_effort: route.reasoning_effort,
- });
+ (projectId: string, route: ProjectDefaultAgent) => {
+ // The picker highlight is CONTROLLED by this cache, so the pick lands here
+ // within the click and the request follows behind it. `acceptProjectsMutation`
+ // stops a projects read that is already in flight from re-installing the
+ // pre-pick route on top of it.
acceptProjectsMutation();
- commitProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
+ latestProjectRouteRef.current.set(projectId, route);
+ // Through the commit path, not ``setProjects``: the ref it keeps in step is
+ // what every read and reconcile of this cache addresses, so an optimistic row
+ // written past it would be invisible to them and lost on the next commit.
+ commitProjectFields(projectId, { default_agent: appliedRoute(route) });
+ // Nothing to record for a rollback: the settle above restores the last
+ // CONFIRMED route, which every commit and read already maintains.
+ writeProjectRoute(projectId, route);
},
- [acceptProjectsMutation, api, commitProjects],
+ [acceptProjectsMutation, commitProjectFields, writeProjectRoute],
);
const archiveProject = useCallback(
@@ -1162,7 +1420,15 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
acceptProjectsMutation();
// create_project is find-or-create by path: opening a tracked folder returns
// the existing project, refreshed. Drop any stale copy, hoist to top, expand.
- commitProjects((prev) => (prev ? [project, ...prev.filter((p) => p.id !== project.id)] : [project]));
+ // The route this snapshot carries can be older than a pick still in flight;
+ // defending that is ``commitProjects``' job now, not this call site's. Only
+ // the CONFIRMATION stays here: this is a mutation response, so it may not
+ // record a token for a route whose write has not answered yet.
+ const routeInFlight = latestProjectRouteRef.current.has(project.id);
+ commitProjects(
+ (prev) => (prev ? [project, ...prev.filter((p) => p.id !== project.id)] : [project]),
+ routeInFlight ? undefined : { confirmed: [project] },
+ );
setExpanded((prev) => {
const next = new Set(prev);
next.add(project.id);
@@ -1222,6 +1488,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
forkSession,
renameProject,
setProjectDefaultAgent,
+ isSavingDefaultAgent,
archiveProject,
renameSession,
setSessionPinned,
@@ -1244,6 +1511,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
forkSession,
renameProject,
setProjectDefaultAgent,
+ isSavingDefaultAgent,
archiveProject,
renameSession,
setSessionPinned,
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 1f4f56919..d8a57cf9f 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -99,6 +99,11 @@ vi.mock('./ApiContext', async () => {
return { ...actual, useApi: () => apiRef.current };
});
+// The provider reports its one never-sent refusal through the toast surface, which
+// this tree does not mount. Nothing here asserts that copy — a no-op keeps the
+// dependency from throwing.
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast: () => {} }) }));
+
function settle() {
return act(async () => {
await Promise.resolve();
diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsx
index 5195e62dd..411065833 100644
--- a/ui/src/context/shellBootstrapDemand.test.tsx
+++ b/ui/src/context/shellBootstrapDemand.test.tsx
@@ -101,6 +101,11 @@ vi.mock('./ApiContext', async () => {
return { ...actual, useApi: () => apiRef.current };
});
+// The provider reports its one never-sent refusal through the toast surface, which
+// this tree does not mount. Nothing here asserts that copy — a no-op keeps the
+// dependency from throwing.
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast: () => {} }) }));
+
function settle() {
return act(async () => {
await Promise.resolve();
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index f9658114e..2e66fe48f 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1667,6 +1667,7 @@
"icon_write_failed": "Couldn't save the icon. Please try again.",
"project_no_folder": "This project has no local folder configured.",
"project_not_found": "Project not found.",
+ "project_agent_conflict": "The project's Agent changed elsewhere. Reloading it — apply your change again.",
"remote_access_host_mismatch": "This address can't open the Avibe control panel. Open it from your https://<your-slug>.avibe.bot link, or http://127.0.0.1:5123 on the machine running Avibe.",
"remote_access_config_unavailable": "Avibe couldn't read its configuration. Check that the service is healthy and try again.",
"remote_access_public_url_invalid": "Remote access is misconfigured (the public URL is invalid). Re-pair this device or fix the remote-access settings.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 49f8a0b24..c79c27bb8 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1667,6 +1667,7 @@
"icon_write_failed": "无法保存图标,请重试。",
"project_no_folder": "这个项目没有配置本地文件夹。",
"project_not_found": "找不到这个项目。",
+ "project_agent_conflict": "该项目的 Agent 已在别处变更,正在重新加载,请再次修改。",
"remote_access_host_mismatch": "这个地址无法打开 Avibe 控制台。请用你的 https://<你的子域>.avibe.bot 链接打开,或在运行 Avibe 的机器上访问 http://127.0.0.1:5123。",
"remote_access_config_unavailable": "Avibe 无法读取配置。请确认服务运行正常后重试。",
"remote_access_public_url_invalid": "远程访问配置有误(公网地址无效)。请重新配对此设备或修正远程访问设置。",
diff --git a/ui/src/lib/useCoalescedWrite.test.tsx b/ui/src/lib/useCoalescedWrite.test.tsx
new file mode 100644
index 000000000..26a1e9af6
--- /dev/null
+++ b/ui/src/lib/useCoalescedWrite.test.tsx
@@ -0,0 +1,691 @@
+// @vitest-environment jsdom
+
+import { useEffect, useLayoutEffect } from 'react';
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resetCoalescedWrites, useCoalescedWrite } from './useCoalescedWrite';
+
+type Deferred = {
+ promise: Promise<boolean>;
+ resolve: (value: boolean) => void;
+ reject: (reason: unknown) => void;
+};
+
+function deferred(): Deferred {
+ let resolve!: (value: boolean) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<boolean>((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ });
+ return { promise, resolve, reject };
+}
+
+function settle() {
+ return act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+// Records what reached the network as `<key>:<patch>` and hands back a gate per
+// call, so a write can be observed as "not sent yet" rather than merely "not
+// resolved yet".
+function gatedSend(started: string[], pending: Map<string, Deferred>) {
+ return vi.fn(async (patch: string, key: string) => {
+ const label = `${key}:${patch}`;
+ started.push(label);
+ const gate = deferred();
+ pending.set(label, gate);
+ return gate.promise;
+ });
+}
+
+// Merges string patches as `a+b`, standing in for the session row's field union.
+const joinMerge = (prev: string, next: string) => `${prev}+${next}`;
+
+describe('useCoalescedWrite', () => {
+ // The store is module state on purpose (it outlives the component); each case
+ // starts from an empty one.
+ beforeEach(resetCoalescedWrites);
+ afterEach(cleanup);
+
+ it('keeps one request per resource in flight and folds the clicks made during it into one follow-up', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const { result } = renderHook(() => useCoalescedWrite<string>('t', send, { merge: joinMerge }));
+
+ act(() => {
+ result.current.write('s1', 'first');
+ result.current.write('s1', 'second');
+ result.current.write('s1', 'third');
+ });
+ await settle();
+ // Nothing about the later clicks may reach the network while the first
+ // request is still deciding what the server holds.
+ expect(started).toEqual(['s1:first']);
+
+ await act(async () => {
+ pending.get('s1:first')!.resolve(true);
+ await pending.get('s1:first')!.promise;
+ });
+ await settle();
+ // Two clicks, one follow-up request: the intermediate state was transit.
+ expect(started).toEqual(['s1:first', 's1:second+third']);
+ });
+
+ it('does not make one resource wait behind another', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const { result } = renderHook(() => useCoalescedWrite<string>('t', send));
+
+ act(() => {
+ result.current.write('s1', 'a');
+ result.current.write('s2', 'b');
+ });
+ await settle();
+ expect(started).toEqual(['s1:a', 's2:b']);
+ expect(result.current.isSaving('s1')).toBe(true);
+ expect(result.current.isSaving('s2')).toBe(true);
+ });
+
+ it('does not let two owners of the same resource race after a remount', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const first = renderHook(() => useCoalescedWrite<string>('t', send, { merge: joinMerge }));
+
+ act(() => {
+ first.result.current.write('s1', 'from-first-mount');
+ });
+ await settle();
+ expect(started).toEqual(['s1:from-first-mount']);
+
+ // The user navigates away mid-request and comes back: a hook-local queue
+ // would start a second request beside the first and let the older one commit
+ // last.
+ first.unmount();
+ const second = renderHook(() => useCoalescedWrite<string>('t', send, { merge: joinMerge }));
+ expect(second.result.current.isSaving('s1')).toBe(true);
+ act(() => {
+ second.result.current.write('s1', 'from-second-mount');
+ });
+ await settle();
+ expect(started).toEqual(['s1:from-first-mount']);
+
+ await act(async () => {
+ pending.get('s1:from-first-mount')!.resolve(true);
+ await pending.get('s1:from-first-mount')!.promise;
+ });
+ await settle();
+ expect(started).toEqual(['s1:from-first-mount', 's1:from-second-mount']);
+ second.unmount();
+ });
+
+ it('hands the burst to the owner that is on screen when it settles', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const settled: string[] = [];
+ const mount = (tag: string) =>
+ renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ onSettled: (key, committed) => {
+ settled.push(`${tag}:${key}:${committed}`);
+ },
+ }),
+ );
+
+ const first = mount('gone');
+ act(() => {
+ first.result.current.write('s1', 'route');
+ });
+ await settle();
+ first.unmount();
+ const second = mount('live');
+ await settle();
+
+ await act(async () => {
+ pending.get('s1:route')!.resolve(true);
+ await pending.get('s1:route')!.promise;
+ });
+ await settle();
+ // The answer lands on the screen that is there when it arrives. Reconciling
+ // into the unmounted page would leave the live one showing an optimistic
+ // route nobody ever converged — and no `setState` there could fix it.
+ expect(settled).toEqual(['live:s1:true']);
+ // Handing the burst over is not a reason to re-send it.
+ expect(started).toEqual(['s1:route']);
+ expect(second.result.current.isSaving('s1')).toBe(false);
+ second.unmount();
+ });
+
+ it('claims the scope in the commit, so an answer landing before passive effects still finds the live owner', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const settled: string[] = [];
+ // Whether the replacement page's own passive effects had run by the time the
+ // answer was handled — recorded WITH the settlement, so a React that stopped
+ // leaving this window open fails the case instead of passing it vacuously.
+ let passiveEffectsRan = false;
+ const record = (tag: string) => (key: string, committed: boolean) => {
+ settled.push(`${tag}:${key}:${committed}:${passiveEffectsRan ? 'late' : 'in-window'}`);
+ };
+ const Live = () => {
+ useCoalescedWrite<string>('t', send, { onSettled: record('live') });
+ // Answers the request from inside the commit that puts this page on screen.
+ // Both markers are declared AFTER the hook, so each runs behind whatever the
+ // hook registered in its own phase.
+ useLayoutEffect(() => {
+ pending.get('s1:route')!.resolve(true);
+ }, []);
+ useEffect(() => {
+ passiveEffectsRan = true;
+ }, []);
+ return null;
+ };
+
+ const gone = renderHook(() => useCoalescedWrite<string>('t', send, { onSettled: record('gone') }));
+ act(() => {
+ gone.result.current.write('s1', 'route');
+ });
+ await settle();
+ gone.unmount();
+
+ // React runs passive effects in a LATER task than the commit, so a
+ // replacement page is on screen for a while with none of them run yet. `act`
+ // and `flushSync` both close that window by flushing them before they return,
+ // and this case is about what happens inside it — so it drives React directly.
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ const actEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
+ const wasActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = false;
+ try {
+ root.render(<Live />);
+ // Let the scheduler commit the mount, hand the answer to whoever owns the
+ // scope by then, and finally run the queued passive effects.
+ while (!settled.length) await new Promise((r) => setTimeout(r, 0));
+ // Being rendered is what makes a page the live owner. Answering into the
+ // page it replaced releases the optimistic overlay through a dead component
+ // — the row the user is looking at keeps whatever it was showing, and no
+ // settlement is left to converge it.
+ expect(settled).toEqual(['live:s1:true:in-window']);
+ expect(started).toEqual(['s1:route']);
+ } finally {
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = wasActEnvironment;
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
+ }
+ });
+
+ it('reports which write opened the burst', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const opened: boolean[] = [];
+ const { result } = renderHook(() => useCoalescedWrite<string>('t', send, { merge: joinMerge }));
+
+ act(() => {
+ opened.push(result.current.write('s1', 'a'));
+ opened.push(result.current.write('s1', 'b'));
+ opened.push(result.current.write('s2', 'c'));
+ });
+ await settle();
+ // The opening write is the one moment at which the state the burst replaces
+ // is still what the owner holds, so an owner that must revert a rejected
+ // burst captures its base here and accumulates into it afterwards. Per
+ // resource, not per click: `s2` opens its own burst.
+ expect(opened).toEqual([true, false, true]);
+
+ await act(async () => {
+ pending.get('s2:c')!.resolve(true);
+ await pending.get('s2:c')!.promise;
+ });
+ await settle();
+ act(() => {
+ opened.push(result.current.write('s2', 'd'));
+ });
+ await settle();
+ // Settled means the base is spent: the next click opens a fresh burst and
+ // captures the state the server confirmed.
+ expect(opened).toEqual([true, false, true, true]);
+ });
+
+ it('drops what is waiting when the request in flight fails', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const settled: Array<[string, boolean]> = [];
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ merge: joinMerge,
+ onSettled: (key, committed) => {
+ settled.push([key, committed]);
+ },
+ }),
+ );
+
+ act(() => {
+ result.current.write('s1', 'title');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'route');
+ });
+
+ // The write in flight is rejected. What was clicked behind it was composed
+ // against the state that request was installing — the state the server has
+ // just refused — so sending it now would persist a combination nobody picked.
+ // This owner declares no `standsAlone`, which is the conservative default: the
+ // failure ends the burst, and the owner's reconcile takes the whole burst back.
+ await act(async () => {
+ pending.get('s1:title')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+ expect(started).toEqual(['s1:title']);
+ // One settle per burst, reporting the burst's outcome.
+ expect(settled).toEqual([['s1', false]]);
+ expect(result.current.isSaving('s1')).toBe(false);
+ });
+
+ // A payload that carries its whole resource was composed against nothing, so a
+ // refusal says nothing about it: it is the user's newest intent and still
+ // coherent. Dropping it would lose a click to protect against a mismatch that
+ // cannot happen — while the burst's shape is unchanged, because `committed`
+ // already means "the outcome of the last send".
+ const standsAloneWhenWhole = (patch: string) => patch.startsWith('whole');
+
+ it('sends what is waiting past a failure when that patch stands on its own', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const settled: Array<[string, boolean]> = [];
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ merge: joinMerge,
+ standsAlone: standsAloneWhenWhole,
+ onSettled: (key, committed) => {
+ settled.push([key, committed]);
+ },
+ }),
+ );
+
+ act(() => {
+ result.current.write('s1', 'partial');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'whole');
+ });
+
+ await act(async () => {
+ pending.get('s1:partial')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+ // Sent, not dropped — and nothing has settled yet, because the burst is still
+ // going: the resource is still mid-write.
+ expect(started).toEqual(['s1:partial', 's1:whole']);
+ expect(settled).toEqual([]);
+ expect(result.current.isSaving('s1')).toBe(true);
+
+ await act(async () => {
+ pending.get('s1:whole')!.resolve(true);
+ await Promise.resolve();
+ });
+ await settle();
+ // One settle for the burst, reporting the send that ended it: the server holds
+ // the user's newest pick, so the owner converges instead of reverting.
+ expect(settled).toEqual([['s1', true]]);
+ expect(result.current.isSaving('s1')).toBe(false);
+ });
+
+ it('ends the burst as refused when the patch that stood alone is refused too', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const settled: Array<[string, boolean]> = [];
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ merge: joinMerge,
+ standsAlone: standsAloneWhenWhole,
+ onSettled: (key, committed) => {
+ settled.push([key, committed]);
+ },
+ }),
+ );
+
+ act(() => {
+ result.current.write('s1', 'whole-a');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'whole-b');
+ });
+
+ await act(async () => {
+ pending.get('s1:whole-a')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+ await act(async () => {
+ pending.get('s1:whole-b')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+
+ expect(started).toEqual(['s1:whole-a', 's1:whole-b']);
+ // Still ONE settle for the burst, still reporting the last send — continuing
+ // past a failure must not turn one burst into two reconciles, or the owner
+ // would revert, re-read, and revert again.
+ expect(settled).toEqual([['s1', false]]);
+ expect(result.current.isSaving('s1')).toBe(false);
+ });
+
+ it('asks with both payloads, so the same pending patch can be answered either way', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const asked: Array<[string, string]> = [];
+ // The identical pending payload, behind two different refusals: whether it
+ // stands alone is a property of the PAIR, so an owner that is told only what
+ // waits cannot answer at all.
+ const standsAlone = (patch: string, refused: string) => {
+ asked.push([patch, refused]);
+ return refused === 'same-field';
+ };
+ const { result } = renderHook(() => useCoalescedWrite<string>('t', send, { merge: joinMerge, standsAlone }));
+
+ act(() => {
+ result.current.write('s1', 'same-field');
+ result.current.write('s2', 'wider');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'b');
+ result.current.write('s2', 'b');
+ });
+
+ await act(async () => {
+ pending.get('s1:same-field')!.resolve(false);
+ pending.get('s2:wider')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+
+ expect(asked).toEqual([
+ ['b', 'same-field'],
+ ['b', 'wider'],
+ ]);
+ expect(started).toEqual(['s1:same-field', 's2:wider', 's1:b']);
+ });
+
+ it('asks about the MOST RECENT send, so a burst that fails twice compares against the right one', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const asked: Array<[string, string]> = [];
+ const standsAlone = (patch: string, refused: string) => {
+ asked.push([patch, refused]);
+ return true;
+ };
+ const { result } = renderHook(() => useCoalescedWrite<string>('t', send, { merge: joinMerge, standsAlone }));
+
+ act(() => {
+ result.current.write('s1', 'a');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'b');
+ });
+ await act(async () => {
+ pending.get('s1:a')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'c');
+ });
+ await act(async () => {
+ pending.get('s1:b')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+
+ // ``c`` is weighed against ``b``, never against ``a``: the first failure is
+ // already accounted for by the payload the second one sent, and comparing
+ // against a patch two sends back would answer a question nobody asked.
+ expect(asked).toEqual([
+ ['b', 'a'],
+ ['c', 'b'],
+ ]);
+ expect(started).toEqual(['s1:a', 's1:b', 's1:c']);
+ });
+
+ it('treats a throw as a failed write', async () => {
+ const started: string[] = [];
+ const boom = deferred();
+ const send = vi.fn(async (patch: string, key: string) => {
+ started.push(`${key}:${patch}`);
+ if (patch === 'boom') return boom.promise;
+ return true;
+ });
+ const settled: Array<[string, boolean]> = [];
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ onSettled: (key, committed) => {
+ settled.push([key, committed]);
+ },
+ }),
+ );
+
+ act(() => {
+ result.current.write('s1', 'boom');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'after');
+ });
+ await act(async () => {
+ boom.reject(new Error('network'));
+ await boom.promise.catch(() => undefined);
+ });
+ await settle();
+ // A throw counts as a failure, so it ends the burst the same way a `false`
+ // does — including the patch that was waiting behind it.
+ expect(started).toEqual(['s1:boom']);
+ expect(settled).toEqual([['s1', false]]);
+ expect(result.current.isSaving('s1')).toBe(false);
+ });
+
+ it('reports a burst that committed in parts as uncommitted, leaving the extent to the owner', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const settled: Array<[string, boolean]> = [];
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ merge: joinMerge,
+ onSettled: (key, committed) => {
+ settled.push([key, committed]);
+ },
+ }),
+ );
+
+ act(() => {
+ result.current.write('s1', 'agent');
+ });
+ await settle();
+ act(() => {
+ result.current.write('s1', 'effort');
+ });
+ await act(async () => {
+ pending.get('s1:agent')!.resolve(true);
+ await pending.get('s1:agent')!.promise;
+ });
+ await settle();
+ expect(started).toEqual(['s1:agent', 's1:effort']);
+
+ await act(async () => {
+ pending.get('s1:effort')!.resolve(false);
+ await pending.get('s1:effort')!.promise;
+ });
+ await settle();
+
+ // A burst can commit in PARTS: the first request landed, the patch folded in
+ // behind it was refused. There is still ONE settle, and `committed` reports
+ // the burst's outcome — false, because the state the owner is showing is not
+ // the state the server holds.
+ //
+ // What it deliberately does NOT say is how much of the burst survived. The
+ // writer never sees the payloads' fields (they are the owner's shape, merged
+ // by the owner's `merge`), so only the owner can know that the Agent pick is
+ // on the server and the effort pick is not. An owner that reverts to where its
+ // burst STARTED would undo the committed part; the owners here advance their
+ // rollback target on each successful send instead.
+ expect(settled).toEqual([['s1', false]]);
+ expect(result.current.isSaving('s1')).toBe(false);
+ });
+
+ it('stays mid-write until the reconcile finishes and folds a pick made during it into the same writer', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const reconcile = deferred();
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ onSettled: () => reconcile.promise.then(() => undefined),
+ }),
+ );
+
+ act(() => {
+ result.current.write('p1', 'route');
+ });
+ await settle();
+ await act(async () => {
+ pending.get('p1:route')!.resolve(true);
+ await Promise.resolve();
+ });
+ await settle();
+ // The authoritative re-read is in flight: the project is still mid-write, so
+ // the picker keeps its indicator and nothing starts a fresh burst against
+ // state the read is still rewriting.
+ expect(result.current.isSaving('p1')).toBe(true);
+
+ act(() => {
+ result.current.write('p1', 'next');
+ });
+ await settle();
+ expect(started).toEqual(['p1:route']);
+
+ await act(async () => {
+ reconcile.resolve(true);
+ await reconcile.promise;
+ });
+ await settle();
+ // A pick made during a SUCCESSFUL burst's reconcile is still live intent: it
+ // was composed against a route the server took, so it goes out.
+ expect(started).toEqual(['p1:route', 'p1:next']);
+ expect(result.current.isSaving('p1')).toBe(true);
+
+ await act(async () => {
+ pending.get('p1:next')!.resolve(true);
+ await pending.get('p1:next')!.promise;
+ });
+ await settle();
+ expect(result.current.isSaving('p1')).toBe(false);
+ });
+
+ it('drops a pick made while a failed burst is rolling back', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const rollback = deferred();
+ const { result } = renderHook(() =>
+ useCoalescedWrite<string>('t', send, {
+ onSettled: () => rollback.promise.then(() => undefined),
+ }),
+ );
+
+ act(() => {
+ result.current.write('p1', 'route');
+ });
+ await settle();
+ await act(async () => {
+ pending.get('p1:route')!.resolve(false);
+ await Promise.resolve();
+ });
+ await settle();
+ // The rollback read is in flight, so the row on screen is still the one the
+ // server refused.
+ expect(result.current.isSaving('p1')).toBe(true);
+
+ act(() => {
+ result.current.write('p1', 'during-rollback');
+ });
+ await act(async () => {
+ rollback.resolve(true);
+ await rollback.promise;
+ });
+ await settle();
+ // This pick was composed against the refused row, so it goes back with it.
+ // The rollback lands whole and the user picks again from what the server
+ // actually holds.
+ expect(started).toEqual(['p1:route']);
+ expect(result.current.isSaving('p1')).toBe(false);
+ });
+
+ it('keeps two scopes writing the same id apart', async () => {
+ const started: string[] = [];
+ const pending = new Map<string, Deferred>();
+ const send = gatedSend(started, pending);
+ const rows = renderHook(() => useCoalescedWrite<string>('rows', send));
+ const routes = renderHook(() => useCoalescedWrite<string>('routes', send));
+
+ act(() => {
+ rows.result.current.write('x', 'row');
+ routes.result.current.write('x', 'route');
+ });
+ await settle();
+ expect(started).toEqual(['x:row', 'x:route']);
+ expect(rows.result.current.isSaving('x')).toBe(true);
+ expect(routes.result.current.isSaving('x')).toBe(true);
+
+ await act(async () => {
+ pending.get('x:row')!.resolve(true);
+ await pending.get('x:row')!.promise;
+ });
+ await settle();
+ expect(rows.result.current.isSaving('x')).toBe(false);
+ expect(routes.result.current.isSaving('x')).toBe(true);
+ });
+
+ it('uses the newest send closure', async () => {
+ const calls: string[] = [];
+ const { result, rerender } = renderHook(
+ ({ tag }: { tag: string }) =>
+ useCoalescedWrite<string>('t', async (patch: string) => {
+ calls.push(`${tag}:${patch}`);
+ return true;
+ }),
+ { initialProps: { tag: 'first' } },
+ );
+
+ rerender({ tag: 'second' });
+ act(() => {
+ result.current.write('s1', 'a');
+ });
+ await settle();
+ expect(calls).toEqual(['second:a']);
+ });
+});
diff --git a/ui/src/lib/useCoalescedWrite.ts b/ui/src/lib/useCoalescedWrite.ts
new file mode 100644
index 000000000..9752667f4
--- /dev/null
+++ b/ui/src/lib/useCoalescedWrite.ts
@@ -0,0 +1,300 @@
+import { useCallback, useLayoutEffect, useMemo, useSyncExternalStore } from 'react';
+
+import { useLatestRef } from './useLatestRef';
+
+/** The surface a scope's writes belong to: one live view, whichever is mounted. */
+type Owner = {
+ send: (patch: unknown, key: string) => Promise<boolean>;
+ merge: (prev: unknown, next: unknown) => unknown;
+ standsAlone: (pending: unknown, refused: unknown) => boolean;
+ onSettled: ((key: string, committed: boolean) => void | Promise<void>) | undefined;
+};
+
+/** One resource's writer: at most one request in flight, at most one patch waiting. */
+type Entry = {
+ /** The write not yet sent, already merged with everything clicked before it. */
+ pending: { patch: unknown } | undefined;
+ /** Who serves this burst — refreshed from `owners`, never fixed at creation. */
+ owner: Owner;
+};
+
+// MODULE scope on purpose: a resource outlives the view that edits it. ChatPage
+// unmounts when the user opens Inbox, so a hook-local queue would let the next
+// visit to the same chat fire a second PATCH beside the first and let the older
+// one commit last. Keys are namespaced per scope, so two owners writing
+// different resource kinds cannot collide on an id.
+const entries = new Map<string, Entry>();
+// A scope names ONE owning surface, and the burst is served by whichever mount
+// of it is up now. A burst outlives its view — the user navigates away
+// mid-request and comes back — and the answer has to land on the screen that is
+// there when it arrives: reconciling into an unmounted page leaves the live one
+// showing state nobody converged. Registered on mount and deliberately never
+// removed on unmount, because a request in flight still needs a `send`; the next
+// mount replaces it.
+const owners = new Map<string, Owner>();
+const listeners = new Set<() => void>();
+// A snapshot of which resources are mid-write, rebuilt only when that set
+// changes: `useSyncExternalStore` requires a stable reference between changes,
+// and the identity is what re-renders consumers reading it through a memoized
+// context value.
+let savingSnapshot: ReadonlySet<string> = new Set<string>();
+
+const publish = () => {
+ savingSnapshot = new Set(entries.keys());
+ listeners.forEach((listener) => listener());
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+const getSavingSnapshot = () => savingSnapshot;
+
+/** Drops every writer. For tests (module state outlives a render root) and for a
+ * hard document reset; never part of a normal write path. */
+export const resetCoalescedWrites = () => {
+ entries.clear();
+ owners.clear();
+ publish();
+};
+
+const drain = async (scope: string, scopedKey: string, key: string) => {
+ let committed = true;
+ // The patch of the request in flight, kept so that a failure can be put to the
+ // owner as the RELATION it is: what is waiting, against what was refused.
+ // Always the most recent send, because that is the one whose refusal the next
+ // decision is about — a burst can fail twice, and the first failure is already
+ // accounted for by the payload the second one sent. Read only after a send
+ // failed, which is why it needs no initial value.
+ let refused: unknown;
+ for (;;) {
+ const entry = entries.get(scopedKey);
+ if (!entry) break;
+ // Re-read the owner on every step, never captured at burst start: each
+ // request and the settle after it belong to the view that is mounted when
+ // they happen.
+ entry.owner = owners.get(scope) ?? entry.owner;
+ // A failure ends the burst UNLESS what waits stands on its own — which is a
+ // relation between the two payloads, not a property of either, so the owner is
+ // asked with both. Only the owner can answer it at all: the writer never
+ // inspects a payload's fields. The default answer is the safe one. See the
+ // block below the send.
+ const next =
+ entry.pending && (committed || entry.owner.standsAlone(entry.pending.patch, refused))
+ ? entry.pending
+ : undefined;
+ if (next) {
+ entry.pending = undefined;
+ refused = next.patch;
+ try {
+ committed = await entry.owner.send(next.patch, key);
+ } catch {
+ committed = false;
+ }
+ continue;
+ }
+ // Nothing more goes out in this burst — either nothing is waiting, or a send
+ // failed and what waits was COMPOSED AGAINST a field that request was
+ // installing and the server did not take. The picker emits an effort click as
+ // `{reasoning_effort}` alone, so sending that behind a refused AGENT switch
+ // would apply it to a route that never existed — an effort chosen for the
+ // Agent the failed write was installing, landing on the Agent the row still
+ // holds. Dropping it is what makes the rollback whole: the reconcile below
+ // reverts the burst together, so the user sees the row the server holds
+ // instead of a combination nobody picked.
+ //
+ // What waits may instead OVERWRITE every field that was refused — a second
+ // model click replacing the first, or a whole-route pick behind a partial one.
+ // Then the refusal says nothing about it: the fields it does not carry are
+ // fields that request never moved, so it is the user's newest intent and still
+ // coherent. Those keep the burst going above, and `committed` then reports
+ // whichever send ended it.
+ entry.pending = undefined;
+ // Reconcile BEFORE releasing the key, so a pick made during a rollback read
+ // coalesces into this writer instead of starting a fresh burst against state
+ // the read is still rewriting.
+ try {
+ await entry.owner.onSettled?.(key, committed);
+ } catch {
+ // Reconciliation is the owner's business; it reports its own failures.
+ }
+ // A pick made during a successful burst's reconcile is still live intent. One
+ // made during a FAILED burst's rollback was composed against the state being
+ // rolled back, so it goes the same way as the rest.
+ if (committed && entry.pending) continue;
+ entry.pending = undefined;
+ entries.delete(scopedKey);
+ publish();
+ break;
+ }
+};
+
+/**
+ * The standard answer to `standsAlone` for payloads whose fields are chosen
+ * against each other: a pending patch stands on its own exactly when it
+ * OVERWRITES every field the refused request tried to write.
+ *
+ * That is the whole condition, and it has no free parameter to get wrong. The
+ * fields the pending patch carries, it decides itself. The fields it does not
+ * carry are — by containment — fields the refused request never touched either,
+ * so the values the user composed this pick against are the values the server
+ * still holds. Fail containment and the reverse holds: the refused request moved
+ * a field this patch depends on and does not restate, so the field is on screen
+ * with a value the server never took.
+ *
+ * Field PRESENCE, never a shape a caller claims: a payload that grows a field or
+ * narrows to one gets the right answer without anyone remembering to update this.
+ */
+export const overwritesRefusedFields = (pending: object, refused: object): boolean =>
+ Object.keys(refused).every((field) => field in pending);
+
+export type CoalescedWrite<P> = {
+ /**
+ * Record one write for `key`: sent now when that key is idle, else merged into
+ * the patch waiting behind the request in flight.
+ *
+ * Returns whether this write OPENED a burst. That is the one moment at which
+ * the state the burst is about to replace is still what the owner holds, so an
+ * owner that has to revert a rejected burst captures its base on `true` and
+ * accumulates into it on `false`.
+ */
+ write: (key: string, patch: P) => boolean;
+ /** True from the first write for `key` until that key has been reconciled. */
+ isSaving: (key: string) => boolean;
+};
+
+/**
+ * Persists the writes behind an optimistic surface, so the UI can move on the
+ * click without letting two requests for the same resource race.
+ *
+ * The owner applies the change to its own state and hands the payload to
+ * `write`; the network catches up behind it. One request per resource is in
+ * flight at a time, because these payloads overwrite each other's fields — an
+ * Agent pick carries that Agent's default model and effort, a project route is a
+ * whole 5-field snapshot — and an earlier request landing last would undo the
+ * newer pick.
+ *
+ * What is waiting is COALESCED rather than queued: the clicks a user makes while
+ * a request is in flight are transit, not intent, so `merge` folds them into one
+ * payload and only the result is sent. Serializing, coalescing and ending a burst
+ * are all per KEY, so a key is a claim that its payloads overwrite each other:
+ * fields that are composed against nothing in common belong to different keys, or
+ * a refused write for one would discard a write for the other (the session row
+ * splits its route from its title for exactly this reason).
+ *
+ * `send` reports its own failure (banner / toast) and returns false; a throw
+ * counts as false too. A failure ends the burst and drops what was waiting, which
+ * was composed against the state the server just refused — unless the owner's
+ * `standsAlone` says that payload overwrites what the refused one was writing, in
+ * which case the refusal says nothing about it and the burst goes on (see
+ * `drain`). `onSettled` then runs once per burst, for the owner to reconcile its
+ * optimistic state with the server (a re-read, or a revert), and the resource
+ * stays `isSaving` until that reconciliation finishes.
+ *
+ * A precondition the SENDER derives rather than the payload carrying it — a
+ * compare-and-set token read from the last confirmed state, say — is not this
+ * hook's business and must not be smuggled into `standsAlone`. It is enforced
+ * where it is derived, which is the only place that covers a NEW burst as well as
+ * a pending patch.
+ *
+ * `committed` is the outcome of the burst's LAST send, not a claim that nothing
+ * was persisted: a burst commits in parts when one request lands and the patch
+ * folded in behind it is refused. How much survived is the owner's to know — the
+ * writer never inspects a payload's fields — so an owner that reverts a rejected
+ * burst must advance its rollback target as each send commits, or it will undo a
+ * change the server is holding.
+ *
+ * A burst is served by the LIVE owner of its scope, not by the mount that opened
+ * it: navigating away mid-request and back hands the remaining request and the
+ * settle to the view that is on screen when they happen. A scope therefore names
+ * one owning surface. "Live" is decided at the moment the answer arrives — the
+ * entry re-reads the registry per step — and a mount claims the scope in its
+ * COMMIT, so being on screen and owning the writes cannot come apart in between.
+ */
+export function useCoalescedWrite<P>(
+ /** Namespace for the keys, so two owners writing different resource kinds never share an entry. */
+ scope: string,
+ send: (patch: P, key: string) => Promise<boolean>,
+ options?: {
+ /** Fold a new patch into the one already waiting. Defaults to "the newer one wins", which is right for whole-snapshot payloads. */
+ merge?: (prev: P, next: P) => P;
+ /**
+ * Whether the payload waiting behind a REFUSED request may still be sent: true
+ * when nothing it depends on was invalidated by that refusal, so it is
+ * coherent whatever the server just did. Defaults to false — a partial patch
+ * applied to state the server kept would persist a combination nobody picked,
+ * and that is the failure worth being conservative about.
+ *
+ * Answered by the OWNER, because the writer never inspects a payload's fields,
+ * and asked with BOTH payloads, because independence is a relation between
+ * them: the same `{model}` click stands alone behind another model click and
+ * does not behind an Agent switch. `overwritesRefusedFields` is that answer for
+ * every payload whose fields are chosen against each other.
+ *
+ * Deliberately not told WHICH resource: the relation is the same for every key
+ * a scope writes. A precondition that does differ per resource belongs to `send`,
+ * which is given the key — see the note above.
+ */
+ standsAlone?: (pending: P, refused: P) => boolean;
+ onSettled?: (key: string, committed: boolean) => void | Promise<void>;
+ },
+): CoalescedWrite<P> {
+ const savingKeys = useSyncExternalStore(subscribe, getSavingSnapshot, getSavingSnapshot);
+ const sendRef = useLatestRef(send);
+ const mergeRef = useLatestRef(options?.merge);
+ const standsAloneRef = useLatestRef(options?.standsAlone);
+ const settledRef = useLatestRef(options?.onSettled);
+
+ // One owner object per mount, whose methods read THIS mount's newest closures.
+ // The refs are stable, so it is built once and its identity is what the
+ // registration below hands over.
+ const owner = useMemo<Owner>(
+ () => ({
+ send: (patch, key) => sendRef.current(patch as P, key),
+ merge: (prev, next) => (mergeRef.current ? mergeRef.current(prev as P, next as P) : next),
+ standsAlone: (pending, refused) => standsAloneRef.current?.(pending as P, refused as P) ?? false,
+ onSettled: (key, committed) => settledRef.current?.(key, committed),
+ }),
+ [sendRef, mergeRef, standsAloneRef, settledRef],
+ );
+
+ // Claimed in the COMMIT, so "on screen" and "owns the scope" are one event.
+ // React schedules passive effects after paint, so a passive claim would leave a
+ // window in which a mount is already rendered while an answer arriving in it is
+ // still routed to the page it replaced — reconciling through a dead component,
+ // with no live settlement left to correct what the new one is showing.
+ useLayoutEffect(() => {
+ owners.set(scope, owner);
+ }, [scope, owner]);
+
+ const write = useCallback(
+ (key: string, patch: P): boolean => {
+ const scopedKey = `${scope}:${key}`;
+ const existing = entries.get(scopedKey);
+ if (existing) {
+ // The mount that is writing is by definition the one on screen, so it
+ // takes the burst over — including its `merge`.
+ existing.owner = owner;
+ existing.pending = {
+ patch: existing.pending ? owner.merge(existing.pending.patch, patch) : patch,
+ };
+ return false;
+ }
+ entries.set(scopedKey, { pending: { patch }, owner });
+ publish();
+ // Entered synchronously, so the first request is in flight within the click
+ // that recorded it: owners open their read-ordering fence inside `send`,
+ // and it must not miss a read that starts a microtask later.
+ void drain(scope, scopedKey, key);
+ return true;
+ },
+ [scope, owner],
+ );
+
+ const isSaving = useCallback((key: string) => savingKeys.has(`${scope}:${key}`), [savingKeys, scope]);
+
+ return { write, isSaving };
+}