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): preserve session drafts across navigation (#1325)

Call Whiteda10a846783a
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index 1cd1c0afc..893400e28 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -2167,29 +2167,39 @@ def retire_for_archive(conn: Connection, session_id: str) -> dict[str, Any]:
def set_draft(conn: Connection, session_id: str, text: str | None) -> bool:
- now = utc_now_iso()
+ # A clear is a real draft revision too: retaining its timestamp prevents an
+ # offline client based on the previous revision from recreating text that a
+ # successful send already cleared. Microseconds keep rapid edits distinct.
+ now = turn_now_iso()
result = conn.execute(
update(agent_sessions)
.where(agent_sessions.c.id == session_id)
.values(
composer_draft_text=text if text and text.strip() else None,
- composer_draft_updated_at=now if text and text.strip() else None,
+ composer_draft_updated_at=now,
updated_at=now,
)
)
return result.rowcount == 1
-def get_draft(conn: Connection, session_id: str) -> dict[str, Any] | None:
+def get_draft_state(conn: Connection, session_id: str) -> dict[str, Any] | None:
row = conn.execute(
select(
agent_sessions.c.composer_draft_text,
agent_sessions.c.composer_draft_updated_at,
).where(agent_sessions.c.id == session_id)
).first()
- if row is None or not row[0]:
+ if row is None:
+ return None
+ return {"text": str(row[0] or ""), "updated_at": row[1]}
+
+
+def get_draft(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ state = get_draft_state(conn, session_id)
+ if state is None or not state["text"]:
return None
- return {"text": str(row[0]), "updated_at": row[1]}
+ return state
def pending_control_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 42732f132..580ec2c14 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -1968,6 +1968,9 @@ def test_draft_upsert_get_and_clear(isolated_state):
assert message_deliveries.set_draft(conn, "ses_d", " ") is True
with engine.connect() as conn:
assert message_deliveries.get_draft(conn, "ses_d") is None
+ cleared = message_deliveries.get_draft_state(conn, "ses_d")
+ assert cleared["text"] == ""
+ assert cleared["updated_at"] is not None
# clear_draft is idempotent.
with engine.begin() as conn:
@@ -1976,6 +1979,7 @@ def test_draft_upsert_get_and_clear(isolated_state):
message_deliveries.set_draft(conn, "ses_d", None)
with engine.connect() as conn:
assert message_deliveries.get_draft(conn, "ses_d") is None
+ assert message_deliveries.get_draft_state(conn, "ses_d")["updated_at"] is not None
def test_inbox_ignores_draft_and_queued_delivery_activity(isolated_state):
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 2a15edd46..c299392b0 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -219,6 +219,11 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
):
client = app.test_client()
headers = csrf_headers(client)
+ saved_draft = client.put(
+ f"/api/sessions/{session_id}/draft",
+ json={"text": "draft before send", "expected_updated_at": None},
+ headers=headers,
+ ).get_json()["draft"]
response = client.post(
f"/api/sessions/{session_id}/messages",
json={"text": "no stream", "author_id": "remote:spoofed"},
@@ -231,6 +236,9 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
assert payload["metadata"]["_web_push_user_key"] == "remote:user-a"
assert payload["metadata"]["_memory_cli_admitted"] is False
assert payload["text"] == "no stream"
+ assert payload["draft_advanced"] is True
+ assert payload["draft"]["text"] == ""
+ assert payload["draft"]["updated_at"] not in (None, saved_draft["updated_at"])
# The turn was kicked off fire-and-forget with the session + text.
dispatch_mock.assert_awaited_once()
sent = dispatch_mock.await_args.args[0]
@@ -266,6 +274,9 @@ def test_workbench_side_actions_are_not_marked_as_ordinary_memory_input(
assert response.status_code == 201
assert dispatch.await_args.args[0]["is_ordinary_text"] is False
+ assert response.get_json()["draft_advanced"] is (
+ "quick_reply_for" not in payload.get("metadata", {})
+ )
@@ -1172,6 +1183,7 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
assert [message["type"] for message in body["messages"]] == ["user", "result"]
assert body["queued"][0]["text"] == "follow-up"
assert body["draft"]["text"] == "draft text"
+ assert body["draft"]["updated_at"] is not None
assert body["turn_state"]["in_flight"] is True
assert body["turn_state"]["foreground"] == "running"
assert body["turn_state"]["pending_input_count"] == 1
@@ -1179,6 +1191,119 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
assert body["turn_state"]["connection"] == "connected"
+def test_session_draft_compare_and_set_protects_newer_writes_and_clears(
+ isolated_state,
+ tmp_path,
+):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ headers = csrf_headers(client)
+ path = f"/api/sessions/{session_id}/draft"
+
+ created = client.put(
+ path,
+ json={"text": "first", "expected_updated_at": None},
+ headers=headers,
+ )
+ assert created.status_code == 200
+ created_draft = created.get_json()["draft"]
+ assert created_draft["text"] == "first"
+ first_revision = created_draft["updated_at"]
+ assert first_revision is not None
+
+ fetched = client.get(path)
+ assert fetched.status_code == 200
+ assert fetched.get_json() == created_draft
+
+ stale = client.put(
+ path,
+ json={"text": "stale", "expected_updated_at": None},
+ headers=headers,
+ )
+ assert stale.status_code == 409
+ assert stale.get_json() == {
+ "ok": False,
+ "code": "draft_conflict",
+ "draft": created_draft,
+ }
+
+ revisionless = client.put(
+ path,
+ json={"text": "legacy overwrite"},
+ headers=headers,
+ )
+ assert revisionless.status_code == 409
+ assert revisionless.get_json() == {
+ "ok": False,
+ "code": "draft_conflict",
+ "draft": created_draft,
+ }
+
+ updated = client.put(
+ path,
+ json={"text": "second", "expected_updated_at": first_revision},
+ headers=headers,
+ )
+ assert updated.status_code == 200
+ updated_draft = updated.get_json()["draft"]
+ assert updated_draft["text"] == "second"
+ second_revision = updated_draft["updated_at"]
+ assert second_revision not in (None, first_revision)
+
+ cleared = client.put(
+ path,
+ json={"text": "", "expected_updated_at": second_revision},
+ headers=headers,
+ )
+ assert cleared.status_code == 200
+ cleared_draft = cleared.get_json()["draft"]
+ assert cleared_draft["text"] == ""
+ assert cleared_draft["updated_at"] not in (None, second_revision)
+
+ resurrect = client.put(
+ path,
+ json={"text": "resurrected", "expected_updated_at": second_revision},
+ headers=headers,
+ )
+ assert resurrect.status_code == 409
+ assert resurrect.get_json()["draft"] == cleared_draft
+
+
+def test_session_draft_reserves_writer_before_cas_reads(isolated_state, tmp_path):
+ from core.services import sessions as sessions_service
+ from storage.agent_session_rows import reserve_write_lock as real_reserve_write_lock
+ from vibe.ui_server import app
+
+ real_get_session = sessions_service.get_session
+ _, session_id = _make_session(tmp_path)
+ client = app.test_client()
+ headers = csrf_headers(client)
+ calls = []
+
+ def reserve_write_lock(conn):
+ calls.append("write_lock")
+ return real_reserve_write_lock(conn)
+
+ def get_session(conn, target_session_id):
+ calls.append("session_read")
+ return real_get_session(conn, target_session_id)
+
+ with (
+ patch("storage.agent_session_rows.reserve_write_lock", reserve_write_lock),
+ patch("core.services.sessions.get_session", get_session),
+ ):
+ response = client.put(
+ f"/api/sessions/{session_id}/draft",
+ json={"text": "serialized", "expected_updated_at": None},
+ headers=headers,
+ )
+
+ assert response.status_code == 200
+ assert calls[:2] == ["write_lock", "session_read"]
+
+
def test_queue_row_send_now_passes_the_exact_delivery_id(isolated_state, tmp_path):
from vibe.ui_server import app
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 13aa4d89e..307f776a0 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -813,7 +813,8 @@ export const ChatPage: React.FC = () => {
// subscription, including the ones issued by components this page owns rather
// than by the page itself. ``sendMessage`` is the exception by construction: it
// uses a raw ``apiFetch`` so it can read ``queued``/``already_answered`` off a
- // non-2xx-aware response, so it calls the same converger directly.
+ // non-2xx-aware response, so it reports the terminal state back through the
+ // ApiContext converger explicitly.
useEffect(() => api.onSessionArchived(convergeSessionArchived), [api, convergeSessionArchived]);
useEffect(() => {
@@ -967,12 +968,12 @@ export const ChatPage: React.FC = () => {
}
}, [api, sessionId, scheduleActivityRefresh]);
- // Persist the composer's unsent text server-side (debounced) so it survives a
- // reload / device switch. The send path clears it server-side; this only
- // saves while typing.
+ // Cache every edit synchronously so navigation, a tab close, or a disconnected
+ // network cannot lose it. Cloud persistence remains debounced and serialized.
const onDraftChange = useCallback(
(text: string) => {
if (!sessionId) return;
+ api.cacheSessionDraft(sessionId, text);
// Tag the pending save with THIS session so the timer (and the
// session-change flush) save to the right session even if the user has
// since navigated away.
@@ -1176,7 +1177,7 @@ export const ChatPage: React.FC = () => {
setWorking(false);
setRuntimeState(emptyRuntimeState());
setQueue([]);
- setInitialDraft(null);
+ setInitialDraft(sessionId ? api.getCachedSessionDraft(sessionId) : null);
// Clear all Agent Activity state so the previous session's groups / live buffer
// never leak into the new chat (refresh re-reads the toggle + summary).
setActivityGroups([]);
@@ -1197,7 +1198,7 @@ export const ChatPage: React.FC = () => {
window.clearTimeout(graceResyncRef.current);
graceResyncRef.current = null;
}
- }, [sessionId]);
+ }, [api, sessionId]);
// Persistent per-session subscription: append every transcript-visible
// ``message.new`` for THIS session for as long as the page is open. An agent
@@ -1455,42 +1456,62 @@ export const ChatPage: React.FC = () => {
body: JSON.stringify(requestBody),
});
const body = await response.json().catch(() => null);
+ if (isSessionArchivedConflict(response.status, body)) {
+ // Archive is terminal. Clear the original session's draft even when
+ // this response settles after navigation, and do not return false:
+ // false tells Composer to restore a retryable submission.
+ api.convergeSessionArchived(sessionId);
+ if (sessionId === sessionIdRef.current) {
+ setWorking(false);
+ setError(t('chat.archived.sendBlocked'));
+ }
+ return;
+ }
+ if (!response.ok) {
+ // A reserved ordinary message may already have cleared the server
+ // draft. Start recovery for its original session before any page
+ // staleness decision; the old Composer will then persist its restore
+ // even if navigation unmounted it. Quick replies never advance drafts.
+ if (!metadata?.quick_reply_for && body?.draft_advanced !== false) {
+ void api.recoverSessionDraftAfterRejectedSend(sessionId);
+ }
+ if (sessionId === sessionIdRef.current) {
+ void syncTurnStateRef.current?.();
+ setWorking(false);
+ // Routes answer either the flat ``{"error": "<sentence>"}`` or the shared
+ // CODED shape (``{"error": {code, message}, code, message}``) — the
+ // runtime-owned session's ``403 reserved_session`` is the latter, and
+ // ``String(body.error)`` renders that object as literal "[object Object]".
+ const parsed = body ? selectApiErrorFields(body, `HTTP ${response.status}`) : null;
+ setError(
+ parsed
+ ? parsed.code
+ ? t(`errors.${parsed.code}`, { defaultValue: parsed.fallback })
+ : parsed.fallback
+ : body?.detail
+ ? String(body.detail)
+ : `HTTP ${response.status}`,
+ );
+ }
+ return false;
+ }
+ // Reserving an accepted message advances the server draft to a blank
+ // revision. Apply that exact causal revision before handling this chat's
+ // UI response, so text typed while the POST was in flight is rebased and
+ // synced even if the user has already navigated to another session.
+ if (
+ response.ok
+ && body?.draft_advanced === true
+ && body?.draft
+ && typeof body.draft === 'object'
+ ) {
+ void api.reconcileSessionDraftAfterSend(sessionId, body.draft);
+ }
// If the user switched chats while this POST was in flight, the response
// belongs to the previous session — don't append it / mutate working /
// error on the chat they moved to (Codex P2). The turn still ran for the
// original session; its rows live there.
if (sessionId !== sessionIdRef.current) return;
- if (isSessionArchivedConflict(response.status, body)) {
- // Archive is terminal, so this is not a retryable failure — it is state
- // this tab missed. Raw ``apiFetch`` never reaches ``handleApiError``, so
- // the shared subscription can't see this one: call the same converger
- // directly. Only the turn state and the message are send-specific.
- setWorking(false);
- setError(t('chat.archived.sendBlocked'));
- convergeSessionArchived(sessionId);
- return false;
- }
- if (!response.ok) {
- setWorking(false);
- // Routes answer either the flat ``{"error": "<sentence>"}`` or the shared
- // CODED shape (``{"error": {code, message}, code, message}``) — the
- // runtime-owned session's ``403 reserved_session`` is the latter, and
- // ``String(body.error)`` renders that object as literal "[object Object]".
- // This is a raw ``apiFetch``, so ``handleApiError`` never runs; reuse its own
- // selector instead of re-deriving the precedence, and localize by code the
- // same way, so a coded refusal reads as a sentence here too. ``detail`` is
- // only FastAPI's own validation shape.
- const parsed = body ? selectApiErrorFields(body, `HTTP ${response.status}`) : null;
- throw new Error(
- parsed
- ? parsed.code
- ? t(`errors.${parsed.code}`, { defaultValue: parsed.fallback })
- : parsed.fallback
- : body?.detail
- ? String(body.detail)
- : `HTTP ${response.status}`,
- );
- }
if (body?.already_answered) {
// A duplicate quick-reply the backend already had (stale tab / missed
// event): no turn started HERE. Reconcile authoritatively rather than
@@ -1524,19 +1545,23 @@ export const ChatPage: React.FC = () => {
}
}
} catch (err) {
+ if (!metadata?.quick_reply_for) {
+ void api.recoverSessionDraftAfterRejectedSend(sessionId);
+ }
if (sessionId === sessionIdRef.current) {
// The request may have raced a turn owned by another tab or source.
// Reconcile rather than clearing that turn's Stop state optimistically.
void syncTurnStateRef.current?.();
setWorking(false);
setError(errorMessage(err) ?? String(err));
- // Signal the composer the send didn't start so it restores the text +
- // uploaded chips — the user can retry without re-uploading (Codex r5).
- return false;
}
+ // Recovery belongs to the original session, while UI mutation is gated
+ // above. Returning false also lets an unmounted old Composer persist its
+ // submitted text after navigation.
+ return false;
}
},
- [sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages, convergeSessionArchived, t],
+ [sessionId, api, appendMessage, refreshQueue, markWorking, reloadLatestMessages, t],
);
// @ mention source: all enabled Agents, filtered client-side (the set is small
diff --git a/ui/src/components/workbench/Composer.attachmentRetry.test.tsx b/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
index 72a679da1..0f64e06d6 100644
--- a/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
+++ b/ui/src/components/workbench/Composer.attachmentRetry.test.tsx
@@ -107,3 +107,52 @@ describe('Composer attachment retry', () => {
expect(uploadWorkbenchAttachment).toHaveBeenCalledTimes(1);
});
});
+
+describe('Composer draft retry', () => {
+ it('re-caches optimistically cleared text when a send cannot start', async () => {
+ const onDraftChange = vi.fn();
+ render(providers(
+ <Composer
+ onSend={async () => false}
+ onDraftChange={onDraftChange}
+ />,
+ ));
+
+ const textbox = screen.getByRole('textbox') as HTMLTextAreaElement;
+ fireEvent.change(textbox, { target: { value: 'keep this' } });
+ fireEvent.click(screen.getByLabelText(en.chat.compose.send));
+
+ await waitFor(() => expect(textbox.value).toBe('keep this'));
+ expect(onDraftChange.mock.calls.map(([text]) => text)).toEqual([
+ 'keep this',
+ '',
+ 'keep this',
+ ]);
+ });
+
+ it('persists rejected text after navigation unmounts the old composer', async () => {
+ let rejectSend!: () => void;
+ const onDraftChange = vi.fn();
+ const view = render(providers(
+ <Composer
+ onSend={() => new Promise<boolean>((resolve) => {
+ rejectSend = () => resolve(false);
+ })}
+ onDraftChange={onDraftChange}
+ />,
+ ));
+
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'survive navigation' } });
+ fireEvent.click(screen.getByLabelText(en.chat.compose.send));
+ await waitFor(() => expect(onDraftChange).toHaveBeenLastCalledWith(''));
+
+ view.unmount();
+ await act(async () => rejectSend());
+
+ expect(onDraftChange.mock.calls.map(([text]) => text)).toEqual([
+ 'survive navigation',
+ '',
+ 'survive navigation',
+ ]);
+ });
+});
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index b45cecbd6..ea0fea34a 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -1200,6 +1200,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const voiceDiscardAvailable = recording || voiceRetainedSession !== null;
const update = (next: string) => {
+ valueRef.current = next;
setValue(next);
onDraftChange?.(next);
};
@@ -1213,6 +1214,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
pendingRef.current = true;
// Clear optimistically so the box can't be re-submitted and a slow send can't
// wipe text typed in the meantime.
+ valueRef.current = '';
setValue('');
setHasText(false);
onDraftChange?.('');
@@ -1225,14 +1227,27 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// restore the prompt + attachments for retry — unless the user typed anew.
const started = await onSend(submitted, sent, useMentions ? sentRefs : undefined);
if (started === false) {
- setValue((cur) => (cur ? cur : submitted));
- setAttachments((cur) => (cur.length ? cur : sent));
- if (useMentions && !valueRef.current.trim()) {
+ if (!unmountedRef.current) {
+ setAttachments((cur) => (cur.length ? cur : sent));
+ }
+ if (!valueRef.current.trim()) {
// Only restore when the user hasn't started a new draft during the
- // in-flight send (mirrors the textarea path's keep-new-typing guard).
- // Chips re-resolve when re-picked; the content is never lost.
- referencesRef.current = sentRefs;
- mentionRef.current?.setText(submitted);
+ // in-flight send. Persist the restored text as a draft too: the
+ // optimistic blank was already cached before onSend rejected it. The
+ // callback still runs after navigation unmounts this Composer, because
+ // the original session's local draft must survive even though its UI
+ // state no longer exists.
+ valueRef.current = submitted;
+ if (!unmountedRef.current) {
+ setValue(submitted);
+ setHasText(Boolean(submitted));
+ if (useMentions) {
+ // Chips re-resolve when re-picked; the content is never lost.
+ referencesRef.current = sentRefs;
+ mentionRef.current?.setText(submitted);
+ }
+ }
+ onDraftChange?.(submitted);
}
}
} finally {
diff --git a/ui/src/context/ApiContext.sessionDraftRetry.test.tsx b/ui/src/context/ApiContext.sessionDraftRetry.test.tsx
new file mode 100644
index 000000000..360b6f668
--- /dev/null
+++ b/ui/src/context/ApiContext.sessionDraftRetry.test.tsx
@@ -0,0 +1,307 @@
+/* @vitest-environment jsdom */
+
+import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+const showToast = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/apiFetch', () => ({ apiFetch }));
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast }) }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { SessionDraftLocalCache } from '../lib/sessionDraftLocalCache';
+import { ApiProvider, useApi } from './ApiContext';
+
+let capturedApi: ReturnType<typeof useApi> | null = null;
+
+const CaptureApi = () => {
+ const api = useApi();
+ useEffect(() => {
+ capturedApi = api;
+ }, [api]);
+ return null;
+};
+
+beforeEach(() => {
+ window.localStorage.clear();
+ apiFetch.mockReset();
+ showToast.mockReset();
+ capturedApi = null;
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ window.localStorage.clear();
+});
+
+describe('ApiProvider session draft reconnect', () => {
+ it('syncs restored dirty drafts when a visible provider mounts', async () => {
+ const cache = new SessionDraftLocalCache(window.localStorage);
+ cache.writeDirty('session-a', 'restored A', 'rev-a');
+ apiFetch.mockImplementation(async (_path: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body)) as { text: string };
+ return new Response(JSON.stringify({
+ ok: true,
+ draft: { text: body.text, updated_at: 'synced-a' },
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ render(<ApiProvider><div /></ApiProvider>);
+
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1));
+ expect(apiFetch.mock.calls[0]?.[0]).toBe('/api/sessions/session-a/draft');
+ expect(cache.read('session-a')?.dirty).toBe(false);
+ });
+
+ it('syncs dirty drafts for every session when the browser comes online', async () => {
+ const cache = new SessionDraftLocalCache(window.localStorage);
+ cache.writeDirty('session-a', 'offline A', 'rev-a');
+ cache.writeDirty('session-b', 'offline B', 'rev-b');
+ cache.writeClean('session-c', 'already synced', 'rev-c');
+ apiFetch.mockImplementation(async (_path: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body)) as {
+ text: string;
+ expected_updated_at: string | null;
+ };
+ return new Response(JSON.stringify({
+ ok: true,
+ draft: {
+ text: body.text,
+ updated_at: `synced-${body.expected_updated_at}`,
+ },
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ render(<ApiProvider><div /></ApiProvider>);
+ act(() => window.dispatchEvent(new Event('online')));
+
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2));
+ const writes = apiFetch.mock.calls.map(([path, init]) => ({
+ path,
+ body: JSON.parse(String(init?.body)),
+ }));
+ expect(writes).toEqual(expect.arrayContaining([
+ {
+ path: '/api/sessions/session-a/draft',
+ body: { text: 'offline A', expected_updated_at: 'rev-a' },
+ },
+ {
+ path: '/api/sessions/session-b/draft',
+ body: { text: 'offline B', expected_updated_at: 'rev-b' },
+ },
+ ]));
+ expect(cache.read('session-a')?.dirty).toBe(false);
+ expect(cache.read('session-b')?.dirty).toBe(false);
+ expect(cache.read('session-c')).toMatchObject({ text: 'already synced', dirty: false });
+ });
+
+ it('bounds a stalled write and releases its reconciled successor', async () => {
+ vi.useFakeTimers();
+ let putCount = 0;
+ apiFetch.mockImplementation(async (path: string, init?: RequestInit) => {
+ if (init?.method === 'PUT' && ++putCount === 1) {
+ return new Promise<Response>((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () => {
+ reject(new DOMException('aborted', 'AbortError'));
+ }, { once: true });
+ });
+ }
+ if (!init?.method) {
+ return new Response(JSON.stringify({ text: '', updated_at: null }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+ const body = JSON.parse(String(init.body)) as { text: string };
+ return new Response(JSON.stringify({
+ ok: true,
+ draft: { text: body.text, updated_at: 'second-revision' },
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ capturedApi!.cacheSessionDraft('session-a', 'first');
+ const first = capturedApi!.setSessionDraft('session-a', 'first');
+ await Promise.resolve();
+ capturedApi!.cacheSessionDraft('session-a', 'second');
+ const second = capturedApi!.setSessionDraft('session-a', 'second');
+
+ await vi.advanceTimersByTimeAsync(12_000);
+ await expect(first).resolves.toMatchObject({ ok: false });
+ await expect(second).resolves.toMatchObject({ ok: true });
+ const writes = apiFetch.mock.calls
+ .filter(([, init]) => init?.method === 'PUT')
+ .map(([, init]) => JSON.parse(String(init?.body)));
+ expect(writes).toEqual([
+ { text: 'first', expected_updated_at: null },
+ { text: 'second', expected_updated_at: null },
+ ]);
+ });
+
+ it('rebases a successor when its timed-out predecessor commits after reconciliation', async () => {
+ vi.useFakeTimers();
+ const writes: Array<{ text: string; expected_updated_at: string | null }> = [];
+ apiFetch.mockImplementation(async (_path: string, init?: RequestInit) => {
+ if (!init?.method) {
+ return Response.json({ text: '', updated_at: null });
+ }
+ const body = JSON.parse(String(init.body)) as {
+ text: string;
+ expected_updated_at: string | null;
+ };
+ writes.push(body);
+ if (writes.length === 1) {
+ return new Promise<Response>((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () => {
+ reject(new DOMException('aborted', 'AbortError'));
+ }, { once: true });
+ });
+ }
+ if (writes.length === 2) {
+ return Response.json({
+ ok: false,
+ code: 'draft_conflict',
+ draft: { text: 'first', updated_at: 'late-first-revision' },
+ }, { status: 409 });
+ }
+ return Response.json({
+ ok: true,
+ draft: { text: body.text, updated_at: 'second-revision' },
+ });
+ });
+
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ capturedApi!.cacheSessionDraft('session-a', 'first');
+ const first = capturedApi!.setSessionDraft('session-a', 'first');
+ await Promise.resolve();
+ capturedApi!.cacheSessionDraft('session-a', 'second');
+ const second = capturedApi!.setSessionDraft('session-a', 'second');
+
+ await vi.advanceTimersByTimeAsync(12_000);
+ await expect(first).resolves.toMatchObject({ ok: false });
+ await expect(second).resolves.toMatchObject({ ok: true });
+ expect(writes).toEqual([
+ { text: 'first', expected_updated_at: null },
+ { text: 'second', expected_updated_at: null },
+ { text: 'second', expected_updated_at: 'late-first-revision' },
+ ]);
+ expect(new SessionDraftLocalCache(window.localStorage).read('session-a')).toMatchObject({
+ text: 'second',
+ serverUpdatedAt: 'second-revision',
+ dirty: false,
+ });
+ });
+
+ it('rebases and retries text restored after a rejected send', async () => {
+ let resolveDraft!: (response: Response) => void;
+ const draft = new Promise<Response>((resolve) => { resolveDraft = resolve; });
+ apiFetch.mockImplementation(async (_path: string, init?: RequestInit) => {
+ if (!init?.method) return draft;
+ const body = JSON.parse(String(init.body)) as { text: string };
+ return new Response(JSON.stringify({
+ ok: true,
+ draft: { text: body.text, updated_at: 'restored-revision' },
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ capturedApi!.cacheSessionDraft('session-a', 'submitted');
+ capturedApi!.cacheSessionDraft('session-a', '');
+ const recovery = capturedApi!.recoverSessionDraftAfterRejectedSend('session-a');
+ capturedApi!.cacheSessionDraft('session-a', 'submitted');
+ resolveDraft(new Response(JSON.stringify({ text: '', updated_at: 'clear-revision' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }));
+ await recovery;
+
+ const write = apiFetch.mock.calls.find(([, init]) => init?.method === 'PUT');
+ expect(JSON.parse(String(write?.[1]?.body))).toEqual({
+ text: 'submitted',
+ expected_updated_at: 'clear-revision',
+ });
+ });
+
+ it('rebases text typed while an accepted send advances the draft revision', async () => {
+ let resolveStaleWrite!: (response: Response) => void;
+ const staleWrite = new Promise<Response>((resolve) => { resolveStaleWrite = resolve; });
+ let putCount = 0;
+ apiFetch.mockImplementation(async (_path: string, init?: RequestInit) => {
+ if (++putCount === 1) return staleWrite;
+ const body = JSON.parse(String(init?.body)) as { text: string };
+ return new Response(JSON.stringify({
+ ok: true,
+ draft: { text: body.text, updated_at: 'next-revision' },
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ });
+
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ capturedApi!.cacheSessionDraft('session-a', 'submitted');
+ capturedApi!.cacheSessionDraft('session-a', '');
+ capturedApi!.cacheSessionDraft('session-a', 'next prompt');
+ const stale = capturedApi!.setSessionDraft('session-a', 'next prompt');
+ await Promise.resolve();
+
+ await capturedApi!.reconcileSessionDraftAfterSend('session-a', {
+ text: '',
+ updated_at: 'clear-revision',
+ });
+ resolveStaleWrite(new Response(JSON.stringify({
+ ok: true,
+ draft: { text: 'next prompt', updated_at: 'stale-write-revision' },
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }));
+ await stale;
+
+ const writes = apiFetch.mock.calls.map(([, init]) => JSON.parse(String(init?.body)));
+ expect(writes).toEqual([
+ { text: 'next prompt', expected_updated_at: null },
+ { text: 'next prompt', expected_updated_at: 'clear-revision' },
+ ]);
+ const cache = new SessionDraftLocalCache(window.localStorage);
+ expect(cache.read('session-a')).toMatchObject({
+ text: 'next prompt',
+ serverUpdatedAt: 'next-revision',
+ dirty: false,
+ });
+ });
+
+ it('clears and announces an archived session reported by a raw request path', () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ capturedApi!.cacheSessionDraft('session-a', 'must be reclaimed');
+ const archived = vi.fn();
+ capturedApi!.onSessionArchived(archived);
+
+ act(() => capturedApi!.convergeSessionArchived('session-a'));
+
+ expect(archived).toHaveBeenCalledWith('session-a');
+ expect(new SessionDraftLocalCache(window.localStorage).read('session-a')).toBeNull();
+ expect(capturedApi!.getCachedSessionDraft('session-a')).toBeNull();
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 1b7520796..24db38abd 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -12,6 +12,12 @@ import {
} from '../lib/workbenchEventConnection';
import type { DockDoc } from './dockDoc';
import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';
+import {
+ SessionDraftPersistence,
+ type SessionDraftSaveResult,
+ type SessionDraftServerState,
+ type SessionDraftWrite,
+} from '../lib/sessionDraftPersistence';
// The workbench Dock API response shape ({ ok, dock }); the Dock document type
// itself lives with the DockProvider that owns reconciliation.
@@ -672,6 +678,9 @@ export type ApiContextType = {
getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
archiveSession: (sessionId: string) => Promise<WorkbenchSession>;
+ /** Apply the terminal archived state for raw request paths that intentionally
+ * bypass the shared JSON error handler. */
+ convergeSessionArchived: (sessionId: string) => void;
/** Subscribe to "the server just refused a write because that session is
* archived". Fires for EVERY request whose error body carries
* ``session_archived``, whatever the verb — the messages POST, the sessions
@@ -715,8 +724,15 @@ export type ApiContextType = {
removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;
sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
getTurnState: (sessionId: string, options?: { handleError?: boolean }) => Promise<SessionRuntimeState>;
+ getCachedSessionDraft: (sessionId: string) => string | null;
+ cacheSessionDraft: (sessionId: string, text: string) => void;
getSessionDraft: (sessionId: string) => Promise<{ text: string }>;
setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;
+ reconcileSessionDraftAfterSend: (
+ sessionId: string,
+ draft: { text: string; updated_at: string | null },
+ ) => Promise<void>;
+ recoverSessionDraftAfterRejectedSend: (sessionId: string) => Promise<void>;
listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; onlySession?: string; cache?: boolean; handleError?: boolean }) => Promise<InboxFeedResult>;
connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
listVibeAgents: (params?: {
@@ -1247,10 +1263,23 @@ export type WorkbenchSessionBootstrap = {
next_after_id: string | null;
next_before_id?: string | null;
queued: WorkbenchMessage[];
- draft: { text: string };
+ draft: { text: string; updated_at: string | null };
turn_state: SessionRuntimeState;
};
+function sessionDraftServerState(payload: unknown): SessionDraftServerState {
+ const draft = payload && typeof payload === 'object'
+ ? payload as { text?: unknown; updated_at?: unknown }
+ : {};
+ return {
+ text: typeof draft.text === 'string' ? draft.text : '',
+ updatedAt: typeof draft.updated_at === 'string' ? draft.updated_at : null,
+ };
+}
+
+const SESSION_DRAFT_WRITE_TIMEOUT_MS = 12_000;
+const SESSION_DRAFT_RECONCILE_TIMEOUT_MS = 5_000;
+
// One row of the per-session ("Slack-like") inbox feed from ``GET /api/inbox``.
// Aggregated per session at query time: ``preview_text`` is the session's latest
// agent ``result`` (aligned with the avibe chat, which only shows results),
@@ -2323,8 +2352,21 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const eventConnectionStateRef = useRef<WorkbenchEventConnectionState>('reconnecting');
const eventReconnectLoopRef = useRef<WorkbenchEventReconnectLoop | null>(null);
const wakeWorkbenchEventsRef = useRef<() => void>(() => {});
+ const syncSessionDraftsRef = useRef<() => void>(() => {});
const stopWorkbenchEventsRef = useRef<() => void>(() => {});
const sessionArchivedHandlersRef = useRef(new Set<(sessionId: string) => void>());
+ const sessionDraftPersistence = useMemo(() => new SessionDraftPersistence(), []);
+
+ const convergeSessionArchived = (sessionId: string) => {
+ sessionDraftPersistence.clearSession(sessionId);
+ for (const handler of Array.from(sessionArchivedHandlersRef.current)) {
+ try {
+ handler(sessionId);
+ } catch (err) {
+ console.error('[API] session-archived subscriber failed', err);
+ }
+ }
+ };
const handleApiError = async (res: Response, path: string) => {
let errorMessage = `Request failed: ${path} (${res.status})`;
@@ -2364,13 +2406,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
// must never change whether/what this handler throws.
const archivedSessionId = archivedConflictSessionId(errorCode, path);
if (archivedSessionId) {
- for (const handler of Array.from(sessionArchivedHandlersRef.current)) {
- try {
- handler(archivedSessionId);
- } catch (err) {
- console.error('[API] session-archived subscriber failed', err);
- }
- }
+ convergeSessionArchived(archivedSessionId);
}
throw new ApiError(errorMessage, res.status, errorCode);
@@ -2556,6 +2592,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (!envelope) return;
if (envelope.data.session_id) {
clearSessionReadCache(envelope.data.session_id);
+ if (envelope.data.event === 'archived') {
+ sessionDraftPersistence.clearSession(envelope.data.session_id);
+ }
} else {
clearReadCacheMatching((path) => path.startsWith('/api/inbox') || path.startsWith('/api/sessions'));
}
@@ -2706,11 +2745,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
useEffect(() => {
const wakeIfVisible = () => {
- if (document.visibilityState === 'visible') wakeWorkbenchEventsRef.current();
+ if (document.visibilityState !== 'visible') return;
+ wakeWorkbenchEventsRef.current();
+ syncSessionDraftsRef.current();
};
document.addEventListener('visibilitychange', wakeIfVisible);
window.addEventListener('online', wakeIfVisible);
window.addEventListener('focus', wakeIfVisible);
+ if (document.visibilityState === 'visible') syncSessionDraftsRef.current();
return () => {
document.removeEventListener('visibilitychange', wakeIfVisible);
window.removeEventListener('online', wakeIfVisible);
@@ -2736,6 +2778,95 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return { res, payloadJson };
};
+ const readSessionDraftServer = async (
+ sessionId: string,
+ timeoutMs = SESSION_DRAFT_RECONCILE_TIMEOUT_MS,
+ ): Promise<SessionDraftServerState | null> => {
+ const controller = new AbortController();
+ const timeout = window.setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await apiFetch(
+ `/api/sessions/${encodeURIComponent(sessionId)}/draft`,
+ { signal: controller.signal },
+ );
+ if (!res.ok) return null;
+ return sessionDraftServerState(await res.json().catch(() => null));
+ } catch {
+ return null;
+ } finally {
+ window.clearTimeout(timeout);
+ }
+ };
+
+ const writeSessionDraft = async (
+ sessionId: string,
+ draft: SessionDraftWrite,
+ ): Promise<SessionDraftSaveResult> => {
+ const controller = new AbortController();
+ let timedOut = false;
+ const timeout = window.setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, SESSION_DRAFT_WRITE_TIMEOUT_MS);
+ try {
+ const { res, payloadJson } = await requestJson(
+ `/api/sessions/${encodeURIComponent(sessionId)}/draft`,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ text: draft.text,
+ expected_updated_at: draft.expectedUpdatedAt,
+ }),
+ signal: controller.signal,
+ },
+ `/api/sessions/${sessionId}/draft`,
+ { handleError: false },
+ );
+ const hasServerDraft = payloadJson?.draft && typeof payloadJson.draft === 'object';
+ const server = sessionDraftServerState(payloadJson?.draft);
+ if (res.status === 409 && payloadJson?.code === 'draft_conflict') {
+ return { ok: false, conflict: true, server };
+ }
+ return res.ok
+ ? { ok: true, ...(hasServerDraft ? { server } : {}) }
+ : { ok: false };
+ } catch (error) {
+ if (!timedOut) throw error;
+ // The request may have committed before its response stalled. Reconcile
+ // once before releasing queued successors so they inherit the actual
+ // cloud revision instead of manufacturing a conflict from uncertainty.
+ const server = await readSessionDraftServer(sessionId);
+ if (!server) return { ok: false };
+ if (server.text === draft.text) return { ok: true, server };
+ return server.updatedAt !== draft.expectedUpdatedAt
+ ? { ok: false, conflict: true, server }
+ : {
+ ok: false,
+ server,
+ // The abort only stops waiting for the response; the synchronous
+ // server transaction may still commit. If the queued successor
+ // conflicts specifically with this text, rebase and retry once.
+ retryConflictIfServerText: draft.text,
+ };
+ } finally {
+ window.clearTimeout(timeout);
+ }
+ };
+ const rebaseAndRetrySessionDraft = async (
+ sessionId: string,
+ server: SessionDraftServerState,
+ ): Promise<void> => {
+ sessionDraftPersistence.rebase(sessionId, server);
+ await sessionDraftPersistence.retry(
+ sessionId,
+ (draft) => writeSessionDraft(sessionId, draft),
+ );
+ };
+ syncSessionDraftsRef.current = () => {
+ void sessionDraftPersistence.retryAll(writeSessionDraft);
+ };
+
const postJson = async (path: string, payload: any, opts?: { handleError?: boolean }) => {
const { payloadJson } = await requestJson(
path,
@@ -3128,8 +3259,28 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
session: res.ok && payload && typeof payload.id === 'string' ? payload : null,
};
},
- getSessionBootstrap: (sessionId) =>
- getJson(`/api/sessions/${encodeURIComponent(sessionId)}/bootstrap`),
+ getSessionBootstrap: async (sessionId) => {
+ const read = sessionDraftPersistence.beginRead(sessionId);
+ try {
+ const payload = await getJson(`/api/sessions/${encodeURIComponent(sessionId)}/bootstrap`);
+ if (payload?.session?.status === 'archived') {
+ sessionDraftPersistence.clearSession(sessionId);
+ return payload;
+ }
+ const server = sessionDraftServerState(payload?.draft);
+ const text = sessionDraftPersistence.reconcileRead(sessionId, read, server);
+ void sessionDraftPersistence.retry(
+ sessionId,
+ (draft) => writeSessionDraft(sessionId, draft),
+ );
+ return text === server.text
+ ? payload
+ : { ...payload, draft: { ...(payload.draft ?? {}), text } };
+ } catch (error) {
+ sessionDraftPersistence.releaseRead(sessionId, read);
+ throw error;
+ }
+ },
updateSession: async (sessionId, payload) => {
const { payloadJson } = await requestJson(`/api/sessions/${encodeURIComponent(sessionId)}`, {
method: 'PATCH',
@@ -3138,7 +3289,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}, `PATCH /api/sessions/${sessionId}`);
return payloadJson;
},
- archiveSession: (sessionId) => deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ archiveSession: async (sessionId) => {
+ const payload = await deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}`);
+ sessionDraftPersistence.clearSession(sessionId);
+ return payload;
+ },
+ convergeSessionArchived,
onSessionArchived,
getArchivePreview: (sessionId) =>
getJson(`/api/sessions/${encodeURIComponent(sessionId)}/archive-preview`),
@@ -3227,14 +3383,40 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
return res.json();
},
- getSessionDraft: (sessionId) => getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`),
- setSessionDraft: async (sessionId, text) => {
- const { res, payloadJson } = await requestJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text }),
- }, `/api/sessions/${sessionId}/draft`, { handleError: false });
- return res.ok ? payloadJson : { ok: false };
+ getCachedSessionDraft: (sessionId) => sessionDraftPersistence.peek(sessionId),
+ cacheSessionDraft: (sessionId, text) => sessionDraftPersistence.cache(sessionId, text),
+ getSessionDraft: async (sessionId) => {
+ const read = sessionDraftPersistence.beginRead(sessionId);
+ try {
+ const payload = await getJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`);
+ const server = sessionDraftServerState(payload);
+ const text = sessionDraftPersistence.reconcileRead(sessionId, read, server);
+ void sessionDraftPersistence.retry(
+ sessionId,
+ (draft) => writeSessionDraft(sessionId, draft),
+ );
+ return { text };
+ } catch (error) {
+ sessionDraftPersistence.releaseRead(sessionId, read);
+ throw error;
+ }
+ },
+ setSessionDraft: (sessionId, text) => sessionDraftPersistence.save(
+ sessionId,
+ text,
+ (draft) => writeSessionDraft(sessionId, draft),
+ ),
+ reconcileSessionDraftAfterSend: (sessionId, draft) => (
+ rebaseAndRetrySessionDraft(sessionId, sessionDraftServerState(draft))
+ ),
+ recoverSessionDraftAfterRejectedSend: async (sessionId) => {
+ // The message reservation clears the cloud draft before dispatch. A
+ // rejected/unknown dispatch therefore needs an authoritative revision
+ // before the composer's optimistic text restoration is replayed.
+ sessionDraftPersistence.markRejectedSend(sessionId);
+ const server = await readSessionDraftServer(sessionId);
+ if (!server) return;
+ await rebaseAndRetrySessionDraft(sessionId, server);
},
listInbox: (params) => {
const search = new URLSearchParams();
@@ -3527,7 +3709,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getAuthSession: () => getJson('/api/session'),
signOut: () => postJson('/auth/logout', {}),
// eslint-disable-next-line react-hooks/exhaustive-deps
- }), [showToast, t]);
+ }), [sessionDraftPersistence, showToast, t]);
return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;
};
diff --git a/ui/src/lib/sessionDraftLocalCache.test.ts b/ui/src/lib/sessionDraftLocalCache.test.ts
new file mode 100644
index 000000000..7dbe9a678
--- /dev/null
+++ b/ui/src/lib/sessionDraftLocalCache.test.ts
@@ -0,0 +1,217 @@
+import { describe, expect, it } from 'vitest';
+import {
+ SESSION_DRAFT_INVALIDATION_PREFIX,
+ SESSION_DRAFT_MUTATION_PREFIX,
+ SESSION_DRAFT_STORAGE_PREFIX,
+ SessionDraftLocalCache,
+} from './sessionDraftLocalCache';
+
+class MemoryStorage {
+ readonly values = new Map<string, string>();
+
+ get length(): number {
+ return this.values.size;
+ }
+
+ key(index: number): string | null {
+ return [...this.values.keys()][index] ?? null;
+ }
+
+ getItem(key: string): string | null {
+ return this.values.get(key) ?? null;
+ }
+
+ setItem(key: string, value: string): void {
+ this.values.set(key, value);
+ }
+
+ removeItem(key: string): void {
+ this.values.delete(key);
+ }
+}
+
+describe('SessionDraftLocalCache', () => {
+ it('stores dirty and clean versioned records per session', () => {
+ const storage = new MemoryStorage();
+ let sequence = 0;
+ const cache = new SessionDraftLocalCache(
+ storage,
+ () => `id-${++sequence}`,
+ () => 100 + sequence,
+ );
+
+ const dirty = cache.writeDirty('session/a', 'typing', 'server-1');
+ expect(cache.read('session/a')).toEqual({
+ version: 1,
+ text: 'typing',
+ serverUpdatedAt: 'server-1',
+ dirty: true,
+ mutationId: 'id-1',
+ savedAt: 101,
+ });
+ expect([...storage.values.keys()]).toEqual([
+ `${SESSION_DRAFT_MUTATION_PREFIX}session%2Fa:id-1`,
+ ]);
+
+ cache.acknowledge('session/a', dirty.mutationId, 'typing', 'server-2');
+ expect(cache.read('session/a')).toMatchObject({
+ text: 'typing',
+ serverUpdatedAt: 'server-2',
+ dirty: false,
+ mutationId: 'id-1',
+ });
+ expect([...storage.values.keys()]).toEqual([
+ `${SESSION_DRAFT_STORAGE_PREFIX}session%2Fa`,
+ ]);
+ });
+
+ it('removes an empty clean draft and ignores stale acknowledgements or rebases', () => {
+ const storage = new MemoryStorage();
+ const cache = new SessionDraftLocalCache(storage, () => 'current', () => 1);
+ cache.writeDirty('session-a', 'text', null);
+
+ cache.rebaseDirty('session-a', 'stale', 'server-1');
+ expect(cache.read('session-a')?.serverUpdatedAt).toBeNull();
+ cache.acknowledge('session-a', 'stale', 'old text', 'server-1');
+ expect(cache.read('session-a')).toMatchObject({ text: 'text', dirty: true });
+
+ cache.acknowledge('session-a', 'current', 'text', 'server-1');
+ expect(cache.read('session-a')).toMatchObject({
+ text: 'text',
+ dirty: false,
+ mutationId: 'current',
+ serverUpdatedAt: 'server-1',
+ });
+
+ cache.writeClean('session-a', '', 'server-2');
+ expect(cache.read('session-a')).toBeNull();
+ });
+
+ it('enumerates only dirty session records for reconnect replay', () => {
+ const storage = new MemoryStorage();
+ let sequence = 0;
+ const cache = new SessionDraftLocalCache(storage, () => `id-${++sequence}`, () => sequence);
+ cache.writeDirty('session/a', 'offline A', 'server-1');
+ storage.setItem(`${SESSION_DRAFT_STORAGE_PREFIX}broken`, '{not-json');
+ cache.writeClean('session-b', 'synced B', 'server-2');
+ cache.writeDirty('session-c', 'offline C', null);
+
+ expect(cache.dirtySessionIds()).toEqual(['session/a', 'session-c']);
+ expect(storage.getItem(`${SESSION_DRAFT_STORAGE_PREFIX}broken`)).toBeNull();
+ });
+
+ it('acknowledges one tab without replacing another tab mutation', () => {
+ const storage = new MemoryStorage();
+ const first = new SessionDraftLocalCache(storage, () => 'tab-a', () => 1);
+ const second = new SessionDraftLocalCache(storage, () => 'tab-b', () => 2);
+
+ first.writeDirty('session-a', 'from tab A', null);
+ const removeItem = storage.removeItem.bind(storage);
+ storage.removeItem = (key) => {
+ if (key === `${SESSION_DRAFT_MUTATION_PREFIX}session-a:tab-a`) {
+ second.writeDirty('session-a', 'from tab B', null);
+ }
+ removeItem(key);
+ };
+ first.acknowledge('session-a', 'tab-a', 'from tab A', 'rev-a');
+
+ expect(second.read('session-a')).toMatchObject({
+ text: 'from tab B',
+ dirty: true,
+ mutationId: 'tab-b',
+ });
+ expect(storage.getItem(
+ `${SESSION_DRAFT_MUTATION_PREFIX}session-a:tab-b`,
+ )).not.toBeNull();
+ first.writeClean('session-a', '', 'clear-revision');
+ expect(second.read('session-a')).toMatchObject({
+ text: 'from tab B',
+ dirty: true,
+ mutationId: 'tab-b',
+ });
+ });
+
+ it('retires mutations older than the acknowledged reload winner', () => {
+ const storage = new MemoryStorage();
+ let sequence = 0;
+ const writer = new SessionDraftLocalCache(
+ storage,
+ () => `mutation-${++sequence}`,
+ () => sequence,
+ );
+ const older = writer.writeDirty('session-a', 'older text', 'rev-0');
+ const winner = writer.writeDirty('session-a', 'selected text', 'rev-0');
+ const restored = new SessionDraftLocalCache(storage, () => 'unused', () => 10);
+
+ expect(restored.read('session-a')?.mutationId).toBe(winner.mutationId);
+ restored.acknowledge('session-a', winner.mutationId, winner.text, 'rev-1');
+
+ expect(storage.getItem(
+ `${SESSION_DRAFT_MUTATION_PREFIX}session-a:${older.mutationId}`,
+ )).toBeNull();
+ expect(restored.dirtySessionIds()).toEqual([]);
+ expect(restored.read('session-a')).toMatchObject({
+ text: 'selected text',
+ serverUpdatedAt: 'rev-1',
+ dirty: false,
+ });
+ });
+
+ it('persists archive invalidation across cache instances', () => {
+ const storage = new MemoryStorage();
+ const first = new SessionDraftLocalCache(storage, () => 'archive-1', () => 1);
+ const second = new SessionDraftLocalCache(storage, () => 'unused', () => 2);
+
+ expect(first.readInvalidation('session/a')).toBeNull();
+ expect(first.invalidate('session/a')).toBe('archive-1');
+ expect(second.readInvalidation('session/a')).toBe('archive-1');
+ expect(storage.getItem(
+ `${SESSION_DRAFT_INVALIDATION_PREFIX}session%2Fa`,
+ )).toBe('archive-1');
+ });
+
+ it('keeps a newer in-memory invalidation when storage retains an older token', () => {
+ const storage = new MemoryStorage();
+ let sequence = 0;
+ let blockWrites = false;
+ const setItem = storage.setItem.bind(storage);
+ storage.setItem = (key, value) => {
+ if (blockWrites) throw new Error('read only');
+ setItem(key, value);
+ };
+ const cache = new SessionDraftLocalCache(
+ storage,
+ () => `archive-${++sequence}`,
+ () => sequence,
+ );
+
+ expect(cache.invalidate('session-a')).toBe('archive-1');
+ blockWrites = true;
+ expect(cache.invalidate('session-a')).toBe('archive-2');
+ expect(storage.getItem(
+ `${SESSION_DRAFT_INVALIDATION_PREFIX}session-a`,
+ )).toBe('archive-1');
+ expect(cache.readInvalidation('session-a')).toBe('archive-2');
+ });
+
+ it('discards malformed data and tolerates blocked storage', () => {
+ const storage = new MemoryStorage();
+ storage.setItem(`${SESSION_DRAFT_STORAGE_PREFIX}broken`, '{not-json');
+ const cache = new SessionDraftLocalCache(storage);
+
+ expect(cache.read('broken')).toBeNull();
+ expect(storage.values.size).toBe(0);
+
+ const blocked = {
+ getItem: () => { throw new Error('blocked'); },
+ setItem: () => { throw new Error('full'); },
+ removeItem: () => { throw new Error('blocked'); },
+ };
+ const fallback = new SessionDraftLocalCache(blocked, () => 'id', () => 1);
+ expect(() => fallback.writeDirty('session-a', 'text', null)).not.toThrow();
+ expect(fallback.read('session-a')).toBeNull();
+ expect(() => fallback.clear('session-a')).not.toThrow();
+ expect(fallback.invalidate('session-a')).toBe('id');
+ expect(fallback.readInvalidation('session-a')).toBe('id');
+ });
+});
diff --git a/ui/src/lib/sessionDraftLocalCache.ts b/ui/src/lib/sessionDraftLocalCache.ts
new file mode 100644
index 000000000..c319a0341
--- /dev/null
+++ b/ui/src/lib/sessionDraftLocalCache.ts
@@ -0,0 +1,434 @@
+export type SessionDraftCacheRecord = {
+ version: 1;
+ text: string;
+ serverUpdatedAt: string | null;
+ dirty: boolean;
+ mutationId: string;
+ savedAt: number;
+ rebaseOnConflict?: boolean;
+ rebaseOnConflictServerText?: string;
+};
+
+type DraftStorage = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
+ & Partial<Pick<Storage, 'key' | 'length'>>;
+type CreateId = () => string;
+type Now = () => number;
+
+export const SESSION_DRAFT_STORAGE_PREFIX = 'avibe.session-draft.v1.';
+export const SESSION_DRAFT_MUTATION_PREFIX = 'avibe.session-draft-mutation.v1.';
+export const SESSION_DRAFT_INVALIDATION_PREFIX = 'avibe.session-draft-invalidation.v1.';
+
+function browserStorage(storage?: DraftStorage): DraftStorage | undefined {
+ try {
+ return storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);
+ } catch {
+ return undefined;
+ }
+}
+
+function defaultId(): string {
+ return globalThis.crypto?.randomUUID?.()
+ ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+}
+
+function parseRecord(raw: string | null): SessionDraftCacheRecord | null {
+ if (!raw) return null;
+ try {
+ const value = JSON.parse(raw) as Partial<SessionDraftCacheRecord>;
+ if (
+ value.version !== 1
+ || typeof value.text !== 'string'
+ || (value.serverUpdatedAt !== null && typeof value.serverUpdatedAt !== 'string')
+ || typeof value.dirty !== 'boolean'
+ || typeof value.mutationId !== 'string'
+ || !value.mutationId
+ || typeof value.savedAt !== 'number'
+ || !Number.isFinite(value.savedAt)
+ || (value.rebaseOnConflict !== undefined && typeof value.rebaseOnConflict !== 'boolean')
+ || (
+ value.rebaseOnConflictServerText !== undefined
+ && (
+ typeof value.rebaseOnConflictServerText !== 'string'
+ || value.rebaseOnConflict !== true
+ )
+ )
+ ) {
+ return null;
+ }
+ return value as SessionDraftCacheRecord;
+ } catch {
+ return null;
+ }
+}
+
+export class SessionDraftLocalCache {
+ private readonly storage?: DraftStorage;
+ private readonly createId: CreateId;
+ private readonly now: Now;
+ private readonly memoryInvalidations = new Map<string, { token: string; persisted: boolean }>();
+
+ constructor(
+ storage?: DraftStorage,
+ createId: CreateId = defaultId,
+ now: Now = Date.now,
+ ) {
+ this.storage = storage;
+ this.createId = createId;
+ this.now = now;
+ }
+
+ read(sessionId: string): SessionDraftCacheRecord | null {
+ const target = browserStorage(this.storage);
+ if (!target) return null;
+ try {
+ const dirty = this.readDirtyMutations(target, sessionId);
+ const stored = this.readRecord(target, this.key(sessionId));
+ if (stored?.dirty) dirty.push(stored); // Legacy single-record cache.
+ if (dirty.length) {
+ return dirty.reduce((latest, record) => (
+ this.compareMutationOrder(record, latest) > 0
+ ? record
+ : latest
+ ));
+ }
+ return stored;
+ } catch {
+ return null;
+ }
+ }
+
+ readInvalidation(sessionId: string): string | null {
+ const memory = this.memoryInvalidations.get(sessionId);
+ // A failed write leaves an older token readable in storage. The newer
+ // process-local token must win until it can be persisted.
+ if (memory && !memory.persisted) return memory.token;
+ const target = browserStorage(this.storage);
+ if (!target) return memory?.token ?? null;
+ try {
+ const stored = target.getItem(this.invalidationKey(sessionId));
+ return stored || memory?.token || null;
+ } catch {
+ return memory?.token ?? null;
+ }
+ }
+
+ invalidate(sessionId: string): string {
+ const token = this.createId();
+ let persisted = false;
+ try {
+ const target = browserStorage(this.storage);
+ target?.setItem(this.invalidationKey(sessionId), token);
+ persisted = Boolean(target);
+ } catch {
+ // Recorded below so this token remains newer than stale stored state.
+ }
+ this.memoryInvalidations.set(sessionId, { token, persisted });
+ return token;
+ }
+
+ dirtySessionIds(): string[] {
+ const target = browserStorage(this.storage);
+ if (!target || typeof target.length !== 'number' || typeof target.key !== 'function') return [];
+ const sessionIds = new Set<string>();
+ try {
+ const keys = this.keys(target);
+ for (const key of keys) {
+ if (key.startsWith(SESSION_DRAFT_MUTATION_PREFIX)) {
+ const separator = key.indexOf(':', SESSION_DRAFT_MUTATION_PREFIX.length);
+ if (separator < 0) continue;
+ const record = this.readRecord(target, key);
+ if (!record?.dirty) continue;
+ try {
+ sessionIds.add(decodeURIComponent(key.slice(
+ SESSION_DRAFT_MUTATION_PREFIX.length,
+ separator,
+ )));
+ } catch {
+ // Ignore malformed keys that were not written by this cache.
+ }
+ continue;
+ }
+ if (!key.startsWith(SESSION_DRAFT_STORAGE_PREFIX)) continue;
+ const record = this.readRecord(target, key);
+ if (!record?.dirty) continue;
+ try {
+ sessionIds.add(decodeURIComponent(key.slice(SESSION_DRAFT_STORAGE_PREFIX.length)));
+ } catch {
+ // Ignore malformed keys that were not written by this cache.
+ }
+ }
+ } catch {
+ return [];
+ }
+ return [...sessionIds];
+ }
+
+ writeDirty(
+ sessionId: string,
+ text: string,
+ serverUpdatedAt: string | null,
+ previousMutationId?: string,
+ rebaseOnConflict = false,
+ rebaseOnConflictServerText?: string,
+ ): SessionDraftCacheRecord {
+ const record: SessionDraftCacheRecord = {
+ version: 1,
+ text,
+ serverUpdatedAt,
+ dirty: true,
+ mutationId: this.createId(),
+ savedAt: this.now(),
+ ...(rebaseOnConflict ? { rebaseOnConflict: true } : {}),
+ ...(rebaseOnConflict && rebaseOnConflictServerText !== undefined
+ ? { rebaseOnConflictServerText }
+ : {}),
+ };
+ try {
+ const target = browserStorage(this.storage);
+ target?.setItem(this.mutationKey(sessionId, record.mutationId), JSON.stringify(record));
+ if (target && previousMutationId) {
+ target.removeItem(this.mutationKey(sessionId, previousMutationId));
+ }
+ } catch {
+ // The in-memory persistence layer still protects this tab when storage is unavailable.
+ }
+ return record;
+ }
+
+ writeClean(sessionId: string, text: string, serverUpdatedAt: string | null): SessionDraftCacheRecord | null {
+ if (!text) {
+ try {
+ browserStorage(this.storage)?.removeItem(this.key(sessionId));
+ } catch {
+ // Concurrent dirty mutations use separate keys and remain recoverable.
+ }
+ return null;
+ }
+ return this.write(sessionId, {
+ version: 1,
+ text,
+ serverUpdatedAt,
+ dirty: false,
+ mutationId: this.createId(),
+ savedAt: this.now(),
+ });
+ }
+
+ rebaseDirty(
+ sessionId: string,
+ mutationId: string,
+ serverUpdatedAt: string | null,
+ rebaseOnConflict = false,
+ rebaseOnConflictServerText?: string,
+ ): void {
+ const target = browserStorage(this.storage);
+ if (!target) return;
+ try {
+ const mutationKey = this.mutationKey(sessionId, mutationId);
+ const mutation = this.readRecord(target, mutationKey);
+ if (mutation?.dirty && mutation.mutationId === mutationId) {
+ target.setItem(mutationKey, JSON.stringify({
+ ...mutation,
+ serverUpdatedAt,
+ rebaseOnConflict: rebaseOnConflict || undefined,
+ rebaseOnConflictServerText: rebaseOnConflict
+ ? rebaseOnConflictServerText
+ : undefined,
+ }));
+ return;
+ }
+ // Compatibility with dirty records created before mutations used
+ // independent keys.
+ const legacy = this.readRecord(target, this.key(sessionId));
+ if (!legacy?.dirty || legacy.mutationId !== mutationId) return;
+ target.setItem(this.key(sessionId), JSON.stringify({
+ ...legacy,
+ serverUpdatedAt,
+ rebaseOnConflict: rebaseOnConflict || undefined,
+ rebaseOnConflictServerText: rebaseOnConflict
+ ? rebaseOnConflictServerText
+ : undefined,
+ }));
+ } catch {
+ // Best-effort cache metadata; the live in-memory entry remains authoritative.
+ }
+ }
+
+ markRebaseOnConflict(
+ sessionId: string,
+ mutationId: string,
+ serverText?: string,
+ ): void {
+ const target = browserStorage(this.storage);
+ if (!target) return;
+ try {
+ const mutationKey = this.mutationKey(sessionId, mutationId);
+ const mutation = this.readRecord(target, mutationKey);
+ if (mutation?.dirty && mutation.mutationId === mutationId) {
+ target.setItem(mutationKey, JSON.stringify({
+ ...mutation,
+ rebaseOnConflict: true,
+ rebaseOnConflictServerText: serverText,
+ }));
+ return;
+ }
+ const legacy = this.readRecord(target, this.key(sessionId));
+ if (!legacy?.dirty || legacy.mutationId !== mutationId) return;
+ target.setItem(this.key(sessionId), JSON.stringify({
+ ...legacy,
+ rebaseOnConflict: true,
+ rebaseOnConflictServerText: serverText,
+ }));
+ } catch {
+ // The live entry still carries the recovery marker in this tab.
+ }
+ }
+
+ acknowledge(
+ sessionId: string,
+ mutationId: string,
+ text: string,
+ serverUpdatedAt: string | null,
+ ): void {
+ const target = browserStorage(this.storage);
+ if (!target) return;
+ try {
+ const mutationKey = this.mutationKey(sessionId, mutationId);
+ const mutation = this.readRecord(target, mutationKey);
+ if (mutation?.dirty && mutation.mutationId === mutationId) {
+ // Dirty mutations use independent keys, so acknowledging this tab can
+ // never replace another tab's concurrently-written text.
+ // A reload replays the newest stored mutation. Once that winner reaches
+ // the cloud, every mutation at or before its ordering frontier is stale;
+ // otherwise the next reload would reveal and replay an older hidden key.
+ // Retire older keys first so a partial storage failure leaves the winner
+ // available for an idempotent retry instead of exposing an older draft.
+ this.retireMutationsBefore(target, sessionId, mutation);
+ target.removeItem(mutationKey);
+ if (!text) {
+ target.removeItem(this.key(sessionId));
+ return;
+ }
+ this.write(sessionId, {
+ ...mutation,
+ text,
+ serverUpdatedAt,
+ dirty: false,
+ savedAt: this.now(),
+ rebaseOnConflict: undefined,
+ rebaseOnConflictServerText: undefined,
+ });
+ return;
+ }
+
+ // Compatibility with the former single-record cache. New mutations never
+ // use this path, so current tabs retain atomic cross-tab ownership.
+ const legacy = this.readRecord(target, this.key(sessionId));
+ if (!legacy || legacy.mutationId !== mutationId) return;
+ if (!text) {
+ target.removeItem(this.key(sessionId));
+ return;
+ }
+ this.write(sessionId, {
+ ...legacy,
+ text,
+ serverUpdatedAt,
+ dirty: false,
+ savedAt: this.now(),
+ rebaseOnConflict: undefined,
+ rebaseOnConflictServerText: undefined,
+ });
+ } catch {
+ // The cloud acknowledgement succeeded; a blocked cache is non-fatal.
+ }
+ }
+
+ clear(sessionId: string): void {
+ try {
+ const target = browserStorage(this.storage);
+ if (!target) return;
+ target.removeItem(this.key(sessionId));
+ for (const key of this.keys(target)) {
+ if (key.startsWith(this.mutationPrefix(sessionId))) target.removeItem(key);
+ }
+ } catch {
+ // Draft caching is best-effort when storage is blocked or full.
+ }
+ }
+
+ private write(sessionId: string, record: SessionDraftCacheRecord): SessionDraftCacheRecord {
+ try {
+ browserStorage(this.storage)?.setItem(this.key(sessionId), JSON.stringify(record));
+ } catch {
+ // The in-memory persistence layer still protects this tab when storage is unavailable.
+ }
+ return record;
+ }
+
+ private key(sessionId: string): string {
+ return `${SESSION_DRAFT_STORAGE_PREFIX}${encodeURIComponent(sessionId)}`;
+ }
+
+ private mutationPrefix(sessionId: string): string {
+ return `${SESSION_DRAFT_MUTATION_PREFIX}${encodeURIComponent(sessionId)}:`;
+ }
+
+ private mutationKey(sessionId: string, mutationId: string): string {
+ return `${this.mutationPrefix(sessionId)}${encodeURIComponent(mutationId)}`;
+ }
+
+ private invalidationKey(sessionId: string): string {
+ return `${SESSION_DRAFT_INVALIDATION_PREFIX}${encodeURIComponent(sessionId)}`;
+ }
+
+ private keys(target: DraftStorage): string[] {
+ if (typeof target.length !== 'number' || typeof target.key !== 'function') return [];
+ return Array.from({ length: target.length }, (_, index) => target.key!(index))
+ .filter((key): key is string => Boolean(key));
+ }
+
+ private readRecord(target: DraftStorage, key: string): SessionDraftCacheRecord | null {
+ const raw = target.getItem(key);
+ const record = parseRecord(raw);
+ if (raw && !record) target.removeItem(key);
+ return record;
+ }
+
+ private readDirtyMutations(
+ target: DraftStorage,
+ sessionId: string,
+ ): SessionDraftCacheRecord[] {
+ const prefix = this.mutationPrefix(sessionId);
+ return this.keys(target)
+ .filter((key) => key.startsWith(prefix))
+ .map((key) => this.readRecord(target, key))
+ .filter((record): record is SessionDraftCacheRecord => Boolean(record?.dirty));
+ }
+
+ private compareMutationOrder(
+ left: SessionDraftCacheRecord,
+ right: SessionDraftCacheRecord,
+ ): number {
+ if (left.savedAt !== right.savedAt) return left.savedAt - right.savedAt;
+ if (left.mutationId === right.mutationId) return 0;
+ return left.mutationId > right.mutationId ? 1 : -1;
+ }
+
+ private retireMutationsBefore(
+ target: DraftStorage,
+ sessionId: string,
+ acknowledged: SessionDraftCacheRecord,
+ ): void {
+ const prefix = this.mutationPrefix(sessionId);
+ for (const key of this.keys(target)) {
+ if (!key.startsWith(prefix)) continue;
+ const record = this.readRecord(target, key);
+ if (
+ record?.dirty
+ && this.compareMutationOrder(record, acknowledged) < 0
+ ) {
+ target.removeItem(key);
+ }
+ }
+ }
+}
diff --git a/ui/src/lib/sessionDraftPersistence.test.ts b/ui/src/lib/sessionDraftPersistence.test.ts
new file mode 100644
index 000000000..8316b2fb7
--- /dev/null
+++ b/ui/src/lib/sessionDraftPersistence.test.ts
@@ -0,0 +1,601 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ SESSION_DRAFT_MUTATION_PREFIX,
+ SessionDraftLocalCache,
+} from './sessionDraftLocalCache';
+import {
+ SessionDraftPersistence,
+ type SessionDraftSaveResult,
+ type SessionDraftWrite,
+} from './sessionDraftPersistence';
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((next) => {
+ resolve = next;
+ });
+ return { promise, resolve };
+};
+
+class MemoryStorage {
+ readonly values = new Map<string, string>();
+
+ get length(): number {
+ return this.values.size;
+ }
+
+ key(index: number): string | null {
+ return [...this.values.keys()][index] ?? null;
+ }
+
+ getItem(key: string): string | null {
+ return this.values.get(key) ?? null;
+ }
+
+ setItem(key: string, value: string): void {
+ this.values.set(key, value);
+ }
+
+ removeItem(key: string): void {
+ this.values.delete(key);
+ }
+}
+
+const localCache = (storage = new MemoryStorage()) => {
+ let sequence = 0;
+ return new SessionDraftLocalCache(
+ storage,
+ () => `mutation-${++sequence}`,
+ () => sequence,
+ );
+};
+
+describe('SessionDraftPersistence', () => {
+ it('serializes one session and rebases a newer edit onto the successful cloud revision', async () => {
+ const cache = localCache();
+ const persistence = new SessionDraftPersistence(cache);
+ const first = deferred<SessionDraftSaveResult>();
+ const calls: SessionDraftWrite[] = [];
+
+ persistence.save('session-a', 'first', async (draft) => {
+ calls.push(draft);
+ return first.promise;
+ });
+ await Promise.resolve();
+ persistence.cache('session-a', 'second');
+ const second = persistence.save('session-a', 'second', async (draft) => {
+ calls.push(draft);
+ return { ok: true, server: { text: draft.text, updatedAt: 'rev-2' } };
+ });
+
+ expect(calls).toEqual([{ text: 'first', expectedUpdatedAt: null }]);
+ first.resolve({ ok: true, server: { text: 'first', updatedAt: 'rev-1' } });
+ await second;
+
+ expect(calls).toEqual([
+ { text: 'first', expectedUpdatedAt: null },
+ { text: 'second', expectedUpdatedAt: 'rev-1' },
+ ]);
+ expect(cache.read('session-a')).toMatchObject({
+ text: 'second',
+ serverUpdatedAt: 'rev-2',
+ dirty: false,
+ });
+ expect(persistence.revision('session-a')).toBe(0);
+ });
+
+ it('does not block writes for different sessions', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const first = deferred<SessionDraftSaveResult>();
+ const calls: string[] = [];
+
+ persistence.save('session-a', 'first', async () => {
+ calls.push('a');
+ return first.promise;
+ });
+ await persistence.save('session-b', 'other', async () => {
+ calls.push('b');
+ return { ok: true, server: { text: 'other', updatedAt: 'rev-b' } };
+ });
+
+ expect(calls).toEqual(['a', 'b']);
+ first.resolve({ ok: true, server: { text: 'first', updatedAt: 'rev-a' } });
+ });
+
+ it('does not let a slow acknowledgement overwrite another tab local mutation', async () => {
+ const storage = new MemoryStorage();
+ const firstCache = new SessionDraftLocalCache(storage, () => 'tab-a', () => 1);
+ const secondCache = new SessionDraftLocalCache(storage, () => 'tab-b', () => 2);
+ const first = new SessionDraftPersistence(firstCache);
+ const slow = deferred<SessionDraftSaveResult>();
+
+ const save = first.save('session-a', 'from tab A', async () => slow.promise);
+ secondCache.writeDirty('session-a', 'from tab B', null);
+ slow.resolve({ ok: true, server: { text: 'from tab A', updatedAt: 'rev-1' } });
+ await save;
+
+ expect(secondCache.read('session-a')).toMatchObject({
+ text: 'from tab B',
+ dirty: true,
+ mutationId: 'tab-b',
+ });
+ });
+
+ it('keeps each live tab dirty mutation authoritative until it is acknowledged', async () => {
+ const storage = new MemoryStorage();
+ const firstCache = new SessionDraftLocalCache(storage, () => 'tab-a', () => 1);
+ const secondCache = new SessionDraftLocalCache(storage, () => 'tab-b', () => 2);
+ const first = new SessionDraftPersistence(firstCache);
+ await first.save('session-a', 'from tab A', async () => ({ ok: false }));
+ secondCache.writeDirty('session-a', 'from tab B', null);
+ const writes: SessionDraftWrite[] = [];
+
+ await first.retryAll(async (_sessionId, draft) => {
+ writes.push(draft);
+ return { ok: true, server: { text: draft.text, updatedAt: 'rev-1' } };
+ });
+
+ expect(writes).toEqual([{ text: 'from tab A', expectedUpdatedAt: null }]);
+ expect(secondCache.read('session-a')).toMatchObject({
+ text: 'from tab B',
+ dirty: true,
+ mutationId: 'tab-b',
+ });
+ });
+
+ it('does not delete an adopted mutation when this tab starts editing', () => {
+ const storage = new MemoryStorage();
+ const firstCache = new SessionDraftLocalCache(storage, () => 'tab-a', () => 1);
+ const secondCache = new SessionDraftLocalCache(storage, () => 'tab-b', () => 2);
+ secondCache.writeDirty('session-a', 'from tab B', null);
+ const first = new SessionDraftPersistence(firstCache);
+
+ first.beginRead('session-a');
+ first.cache('session-a', 'from tab A');
+
+ expect(storage.getItem(
+ `${SESSION_DRAFT_MUTATION_PREFIX}session-a:tab-b`,
+ )).not.toBeNull();
+ expect(storage.getItem(
+ `${SESSION_DRAFT_MUTATION_PREFIX}session-a:tab-a`,
+ )).not.toBeNull();
+ });
+
+ it('keeps local text when a read starts during a pending write', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const first = deferred<SessionDraftSaveResult>();
+ persistence.save('session-a', 'draft', async () => first.promise);
+
+ const read = persistence.beginRead('session-a');
+ expect(persistence.reconcileRead('session-a', read, { text: '', updatedAt: null })).toBe('draft');
+ first.resolve({ ok: true, server: { text: 'draft', updatedAt: 'rev-1' } });
+ await Promise.resolve();
+ });
+
+ it('retains a successful revision until an older read reconciles', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const read = persistence.beginRead('session-a');
+ await persistence.save('session-a', 'newer', async () => ({
+ ok: true,
+ server: { text: 'newer', updatedAt: 'rev-2' },
+ }));
+
+ expect(persistence.reconcileRead(
+ 'session-a',
+ read,
+ { text: 'old', updatedAt: 'rev-1' },
+ )).toBe('newer');
+ expect(persistence.revision('session-a')).toBe(0);
+ });
+
+ it('keeps the saved revision when a newer read settles before an older read', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const olderRead = persistence.beginRead('session-a');
+ await persistence.save('session-a', 'newer', async () => ({
+ ok: true,
+ server: { text: 'newer', updatedAt: 'rev-2' },
+ }));
+ const newerRead = persistence.beginRead('session-a');
+
+ expect(persistence.reconcileRead(
+ 'session-a',
+ newerRead,
+ { text: 'newer', updatedAt: 'rev-2' },
+ )).toBe('newer');
+ expect(persistence.revision('session-a')).toBe(1);
+ expect(persistence.reconcileRead(
+ 'session-a',
+ olderRead,
+ { text: 'old', updatedAt: 'rev-1' },
+ )).toBe('newer');
+ expect(persistence.revision('session-a')).toBe(0);
+ });
+
+ it('recovers a failed write from local storage in a new persistence instance', async () => {
+ const storage = new MemoryStorage();
+ const first = new SessionDraftPersistence(localCache(storage));
+ await first.save('session-a', 'offline text', async () => ({ ok: false }));
+
+ const restored = new SessionDraftPersistence(localCache(storage));
+ expect(restored.peek('session-a')).toBe('offline text');
+ const read = restored.beginRead('session-a');
+ expect(restored.reconcileRead(
+ 'session-a',
+ read,
+ { text: '', updatedAt: null },
+ )).toBe('offline text');
+ const write = vi.fn(async (draft: SessionDraftWrite) => ({
+ ok: true,
+ server: { text: draft.text, updatedAt: 'rev-1' },
+ }));
+ await restored.retry('session-a', write);
+ expect(write).toHaveBeenCalledWith({
+ text: 'offline text',
+ expectedUpdatedAt: null,
+ });
+ });
+
+ it('retries every dirty session discovered after a reload', async () => {
+ const storage = new MemoryStorage();
+ const cache = localCache(storage);
+ cache.writeDirty('session-a', 'offline A', 'rev-a');
+ cache.writeDirty('session-b', 'offline B', 'rev-b');
+ cache.writeClean('session-c', 'synced C', 'rev-c');
+ const persistence = new SessionDraftPersistence(cache);
+ const calls: Array<{ sessionId: string; draft: SessionDraftWrite }> = [];
+
+ await persistence.retryAll(async (sessionId, draft) => {
+ calls.push({ sessionId, draft });
+ return {
+ ok: true,
+ server: { text: draft.text, updatedAt: `synced-${sessionId}` },
+ };
+ });
+
+ expect(calls).toEqual([
+ {
+ sessionId: 'session-a',
+ draft: { text: 'offline A', expectedUpdatedAt: 'rev-a' },
+ },
+ {
+ sessionId: 'session-b',
+ draft: { text: 'offline B', expectedUpdatedAt: 'rev-b' },
+ },
+ ]);
+ expect(cache.read('session-a')?.dirty).toBe(false);
+ expect(cache.read('session-b')?.dirty).toBe(false);
+ expect(cache.read('session-c')).toMatchObject({ text: 'synced C', dirty: false });
+ });
+
+ it('lets an authoritative newer cloud revision replace a clean local copy', async () => {
+ const storage = new MemoryStorage();
+ const first = new SessionDraftPersistence(localCache(storage));
+ await first.save('session-a', 'synced', async () => ({
+ ok: true,
+ server: { text: 'synced', updatedAt: 'rev-1' },
+ }));
+
+ const restored = new SessionDraftPersistence(localCache(storage));
+ expect(restored.peek('session-a')).toBe('synced');
+ const read = restored.beginRead('session-a');
+ expect(restored.reconcileRead(
+ 'session-a',
+ read,
+ { text: 'other device', updatedAt: 'rev-2' },
+ )).toBe('other device');
+ expect(restored.peek('session-a')).toBe('other device');
+ });
+
+ it('preserves a conflicted draft and resumes syncing after the user edits it', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const firstRead = persistence.beginRead('session-a');
+ persistence.reconcileRead('session-a', firstRead, { text: 'cloud', updatedAt: 'rev-1' });
+ persistence.cache('session-a', 'local edit');
+
+ const racingRead = persistence.beginRead('session-a');
+ expect(persistence.reconcileRead(
+ 'session-a',
+ racingRead,
+ { text: 'other device', updatedAt: 'rev-2' },
+ )).toBe('local edit');
+
+ const write = vi.fn(async () => ({ ok: true }));
+ await expect(persistence.retry('session-a', write)).resolves.toMatchObject({
+ ok: false,
+ conflict: true,
+ });
+ expect(write).not.toHaveBeenCalled();
+ expect(persistence.peek('session-a')).toBe('local edit');
+
+ persistence.cache('session-a', 'local edit resolved');
+ await expect(persistence.save('session-a', 'local edit resolved', write)).resolves.toMatchObject({
+ ok: true,
+ });
+ expect(write).toHaveBeenCalledWith({
+ text: 'local edit resolved',
+ expectedUpdatedAt: 'rev-2',
+ });
+ });
+
+ it('rebases the next edit onto the server revision returned by a write conflict', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const conflict = vi.fn(async (): Promise<SessionDraftSaveResult> => ({
+ ok: false,
+ conflict: true,
+ server: { text: 'other device', updatedAt: 'rev-2' },
+ }));
+
+ await expect(persistence.save('session-a', 'local edit', conflict)).resolves.toMatchObject({
+ ok: false,
+ conflict: true,
+ });
+ await persistence.save('session-a', 'local edit', conflict);
+ expect(conflict).toHaveBeenCalledTimes(1);
+
+ const resolved = vi.fn(async (draft: SessionDraftWrite): Promise<SessionDraftSaveResult> => ({
+ ok: true,
+ server: { text: draft.text, updatedAt: 'rev-3' },
+ }));
+ persistence.cache('session-a', 'local edit resolved');
+ await persistence.save('session-a', 'local edit resolved', resolved);
+ expect(resolved).toHaveBeenCalledWith({
+ text: 'local edit resolved',
+ expectedUpdatedAt: 'rev-2',
+ });
+ });
+
+ it('rebases a newer edit made before the previous write conflict returns', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const first = deferred<SessionDraftSaveResult>();
+ const firstSave = persistence.save('session-a', 'before send', async () => first.promise);
+ await Promise.resolve();
+
+ persistence.cache('session-a', 'typed after send');
+ const successor = vi.fn(async (draft: SessionDraftWrite): Promise<SessionDraftSaveResult> => ({
+ ok: true,
+ server: { text: draft.text, updatedAt: 'rev-3' },
+ }));
+ const secondSave = persistence.save('session-a', 'typed after send', successor);
+ first.resolve({
+ ok: false,
+ conflict: true,
+ server: { text: '', updatedAt: 'clear-revision' },
+ });
+
+ await expect(firstSave).resolves.toMatchObject({ ok: false, conflict: true });
+ await expect(secondSave).resolves.toMatchObject({ ok: true });
+ expect(successor).toHaveBeenCalledWith({
+ text: 'typed after send',
+ expectedUpdatedAt: 'clear-revision',
+ });
+ });
+
+ it('rebases a successor from the authoritative state after an uncertain write', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const first = deferred<SessionDraftSaveResult>();
+ const firstSave = persistence.save('session-a', 'first', async () => first.promise);
+ await Promise.resolve();
+
+ persistence.cache('session-a', 'second');
+ const successor = vi.fn(async (draft: SessionDraftWrite): Promise<SessionDraftSaveResult> => ({
+ ok: true,
+ server: { text: draft.text, updatedAt: 'rev-2' },
+ }));
+ const secondSave = persistence.save('session-a', 'second', successor);
+ first.resolve({
+ ok: false,
+ server: { text: '', updatedAt: 'reconciled-revision' },
+ });
+
+ await expect(firstSave).resolves.toMatchObject({ ok: false });
+ await expect(secondSave).resolves.toMatchObject({ ok: true });
+ expect(successor).toHaveBeenCalledWith({
+ text: 'second',
+ expectedUpdatedAt: 'reconciled-revision',
+ });
+ });
+
+ it('does not overwrite an unrelated conflict after an uncertain write', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ const first = deferred<SessionDraftSaveResult>();
+ const firstSave = persistence.save('session-a', 'first', async () => first.promise);
+ await Promise.resolve();
+
+ persistence.cache('session-a', 'second');
+ const successor = vi.fn(async (): Promise<SessionDraftSaveResult> => ({
+ ok: false,
+ conflict: true,
+ server: { text: 'other device', updatedAt: 'other-revision' },
+ }));
+ const secondSave = persistence.save('session-a', 'second', successor);
+ first.resolve({
+ ok: false,
+ server: { text: '', updatedAt: 'reconciled-revision' },
+ retryConflictIfServerText: 'first',
+ });
+
+ await expect(firstSave).resolves.toMatchObject({ ok: false });
+ await expect(secondSave).resolves.toMatchObject({ ok: false, conflict: true });
+ expect(successor).toHaveBeenCalledTimes(1);
+ expect(persistence.peek('session-a')).toBe('second');
+ });
+
+ it('carries timeout uncertainty into an edit made after reconciliation', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ await persistence.save('session-a', 'first', async () => ({
+ ok: false,
+ server: { text: '', updatedAt: 'reconciled-revision' },
+ retryConflictIfServerText: 'first',
+ }));
+
+ persistence.cache('session-a', 'second');
+ const writes: SessionDraftWrite[] = [];
+ const result = await persistence.save('session-a', 'second', async (draft) => {
+ writes.push(draft);
+ if (writes.length === 1) {
+ return {
+ ok: false,
+ conflict: true,
+ server: { text: 'first', updatedAt: 'late-first-revision' },
+ };
+ }
+ return {
+ ok: true,
+ server: { text: draft.text, updatedAt: 'second-revision' },
+ };
+ });
+
+ expect(result).toMatchObject({ ok: true });
+ expect(writes).toEqual([
+ { text: 'second', expectedUpdatedAt: 'reconciled-revision' },
+ { text: 'second', expectedUpdatedAt: 'late-first-revision' },
+ ]);
+ });
+
+ it('restores the bounded timeout recovery marker after reload', async () => {
+ const storage = new MemoryStorage();
+ const cache = localCache(storage);
+ cache.writeDirty('session-a', 'second', 'reconciled-revision', undefined, true, 'first');
+ const restored = new SessionDraftPersistence(localCache(storage));
+ const writes: SessionDraftWrite[] = [];
+
+ const result = await restored.retry('session-a', async (draft) => {
+ writes.push(draft);
+ if (writes.length === 1) {
+ return {
+ ok: false,
+ conflict: true,
+ server: { text: 'first', updatedAt: 'late-first-revision' },
+ };
+ }
+ return {
+ ok: true,
+ server: { text: draft.text, updatedAt: 'second-revision' },
+ };
+ });
+
+ expect(result).toMatchObject({ ok: true });
+ expect(writes).toEqual([
+ { text: 'second', expectedUpdatedAt: 'reconciled-revision' },
+ { text: 'second', expectedUpdatedAt: 'late-first-revision' },
+ ]);
+ expect(cache.read('session-a')).toMatchObject({
+ text: 'second',
+ serverUpdatedAt: 'second-revision',
+ dirty: false,
+ });
+ });
+
+ it('rebases and retries a rejected-send restoration without another edit', async () => {
+ const persistence = new SessionDraftPersistence(localCache());
+ persistence.cache('session-a', 'submitted');
+ persistence.cache('session-a', '');
+ persistence.cache('session-a', 'submitted');
+
+ persistence.rebase('session-a', { text: '', updatedAt: 'clear-revision' });
+ const write = vi.fn(async (draft: SessionDraftWrite): Promise<SessionDraftSaveResult> => ({
+ ok: true,
+ server: { text: draft.text, updatedAt: 'restored-revision' },
+ }));
+ await persistence.retry('session-a', write);
+
+ expect(write).toHaveBeenCalledWith({
+ text: 'submitted',
+ expectedUpdatedAt: 'clear-revision',
+ });
+ });
+
+ it('persists rejected-send recovery and retries its first conflict after reload', async () => {
+ const storage = new MemoryStorage();
+ const first = new SessionDraftPersistence(localCache(storage));
+ first.cache('session-a', 'submitted');
+ first.markRejectedSend('session-a');
+
+ const restored = new SessionDraftPersistence(localCache(storage));
+ const writes: SessionDraftWrite[] = [];
+ const result = await restored.retry('session-a', async (draft) => {
+ writes.push(draft);
+ if (writes.length === 1) {
+ return {
+ ok: false,
+ conflict: true,
+ server: { text: '', updatedAt: 'clear-revision' },
+ };
+ }
+ return {
+ ok: true,
+ server: { text: draft.text, updatedAt: 'restored-revision' },
+ };
+ });
+
+ expect(result).toMatchObject({ ok: true });
+ expect(writes).toEqual([
+ { text: 'submitted', expectedUpdatedAt: null },
+ { text: 'submitted', expectedUpdatedAt: 'clear-revision' },
+ ]);
+ });
+
+ it('treats a same-text conflict as convergence and cleans the local record', async () => {
+ const cache = localCache();
+ const persistence = new SessionDraftPersistence(cache);
+
+ const result = await persistence.save('session-a', '', async () => ({
+ ok: false,
+ conflict: true,
+ server: { text: '', updatedAt: 'clear-revision' },
+ }));
+
+ expect(result).toMatchObject({ ok: true });
+ expect(cache.read('session-a')).toBeNull();
+ expect(persistence.revision('session-a')).toBe(0);
+ });
+
+ it('removes persistent and in-memory state when a session is archived', async () => {
+ const cache = localCache();
+ const persistence = new SessionDraftPersistence(cache);
+ await persistence.save('session-a', 'draft', async () => ({ ok: false }));
+
+ persistence.clearSession('session-a');
+
+ expect(cache.read('session-a')).toBeNull();
+ expect(persistence.revision('session-a')).toBe(0);
+ expect(persistence.beginRead('session-a').pending).toBe(false);
+ });
+
+ it('discards a read response captured before the session was archived', () => {
+ const cache = localCache();
+ const persistence = new SessionDraftPersistence(cache);
+ const read = persistence.beginRead('session-a');
+
+ persistence.clearSession('session-a');
+ expect(persistence.reconcileRead(
+ 'session-a',
+ read,
+ { text: 'stale pre-archive draft', updatedAt: 'old-revision' },
+ )).toBe('');
+ expect(cache.read('session-a')).toBeNull();
+ });
+
+ it('discards a pre-archive read when another tab invalidates the session', () => {
+ const storage = new MemoryStorage();
+ const first = new SessionDraftPersistence(new SessionDraftLocalCache(
+ storage,
+ () => 'tab-a',
+ () => 1,
+ ));
+ const second = new SessionDraftPersistence(new SessionDraftLocalCache(
+ storage,
+ () => 'tab-b-archive',
+ () => 2,
+ ));
+ const read = first.beginRead('session-a');
+
+ second.clearSession('session-a');
+ expect(first.reconcileRead(
+ 'session-a',
+ read,
+ { text: 'stale pre-archive draft', updatedAt: 'old-revision' },
+ )).toBe('');
+ expect(first.peek('session-a')).toBeNull();
+ });
+});
diff --git a/ui/src/lib/sessionDraftPersistence.ts b/ui/src/lib/sessionDraftPersistence.ts
new file mode 100644
index 000000000..1df7efdb4
--- /dev/null
+++ b/ui/src/lib/sessionDraftPersistence.ts
@@ -0,0 +1,524 @@
+import { SessionDraftLocalCache } from './sessionDraftLocalCache';
+
+export type SessionDraftServerState = {
+ text: string;
+ updatedAt: string | null;
+};
+
+export type SessionDraftWrite = {
+ text: string;
+ expectedUpdatedAt: string | null;
+};
+
+export type SessionDraftSaveResult = {
+ ok: boolean;
+ conflict?: boolean;
+ server?: SessionDraftServerState;
+ /** Retry one successor conflict only when the server contains this timed-out
+ * predecessor, never when an unrelated device wrote instead. */
+ retryConflictIfServerText?: string;
+};
+
+export type SessionDraftRead = {
+ revision: number;
+ pending: boolean;
+ generation: string | null;
+};
+
+type DraftEntry = {
+ revision: number;
+ text: string;
+ localId: string;
+ baseUpdatedAt: string | null;
+ pending: Promise<SessionDraftSaveResult> | null;
+ pendingRevision: number | null;
+ dirty: boolean;
+ conflict: boolean;
+ localOwned: boolean;
+ rebaseOnConflict: boolean;
+ rebaseOnConflictServerText?: string;
+ serverEpoch: number;
+};
+
+type DraftSave = (draft: SessionDraftWrite) => Promise<SessionDraftSaveResult>;
+type SessionDraftSave = (
+ sessionId: string,
+ draft: SessionDraftWrite,
+) => Promise<SessionDraftSaveResult>;
+
+/**
+ * Keeps the latest draft available synchronously, serializes cloud writes per
+ * session, and reconciles reads against the server revision each local edit was
+ * based on. A real version conflict preserves the local text without silently
+ * overwriting the other device's newer cloud draft.
+ */
+export class SessionDraftPersistence {
+ private readonly entries = new Map<string, DraftEntry>();
+ private readonly activeReads = new Map<string, Set<SessionDraftRead>>();
+ private readonly serverVersions = new Map<string, string | null>();
+ private readonly invalidations = new Map<string, string | null>();
+ private readonly localCache: SessionDraftLocalCache;
+
+ constructor(localCache = new SessionDraftLocalCache()) {
+ this.localCache = localCache;
+ }
+
+ cache(sessionId: string, text: string): void {
+ this.observeInvalidation(sessionId);
+ const current = this.entries.get(sessionId);
+ const cached = this.localCache.read(sessionId);
+ const resolvesConflict = Boolean(current?.conflict && current.text !== text);
+ const baseUpdatedAt = resolvesConflict && this.serverVersions.has(sessionId)
+ ? this.serverVersions.get(sessionId)!
+ : current?.baseUpdatedAt
+ ?? cached?.serverUpdatedAt
+ ?? this.serverVersions.get(sessionId)
+ ?? null;
+ const local = this.localCache.writeDirty(
+ sessionId,
+ text,
+ baseUpdatedAt,
+ current?.localOwned ? current.localId : undefined,
+ current?.rebaseOnConflict ?? false,
+ current?.rebaseOnConflictServerText,
+ );
+ this.entries.set(sessionId, {
+ revision: (current?.revision ?? 0) + 1,
+ text,
+ localId: local.mutationId,
+ baseUpdatedAt,
+ pending: current?.pending ?? null,
+ pendingRevision: current?.pendingRevision ?? null,
+ dirty: true,
+ // A new keystroke after a conflict is explicit user intent. Rebase that
+ // edit onto the revision returned by the conflict and resume CAS writes.
+ conflict: resolvesConflict ? false : current?.conflict ?? false,
+ localOwned: true,
+ rebaseOnConflict: current?.rebaseOnConflict ?? false,
+ rebaseOnConflictServerText: current?.rebaseOnConflictServerText,
+ serverEpoch: current?.serverEpoch ?? 0,
+ });
+ }
+
+ peek(sessionId: string): string | null {
+ this.observeInvalidation(sessionId);
+ const current = this.entries.get(sessionId);
+ if (current?.dirty) return current.text;
+ return this.localCache.read(sessionId)?.text ?? null;
+ }
+
+ save(sessionId: string, text: string, write: DraftSave): Promise<SessionDraftSaveResult> {
+ this.observeInvalidation(sessionId);
+ let current = this.entries.get(sessionId);
+ if (!current || current.text !== text || !current.dirty) {
+ this.cache(sessionId, text);
+ current = this.entries.get(sessionId)!;
+ }
+ return this.startSync(sessionId, current, write);
+ }
+
+ retry(sessionId: string, write: DraftSave): Promise<SessionDraftSaveResult> {
+ const current = this.hydrateDirty(sessionId);
+ if (!current) return Promise.resolve({ ok: true });
+ return this.startSync(sessionId, current, write);
+ }
+
+ retryAll(write: SessionDraftSave): Promise<SessionDraftSaveResult[]> {
+ const sessionIds = new Set(this.localCache.dirtySessionIds());
+ for (const [sessionId, entry] of this.entries) {
+ if (entry.dirty) sessionIds.add(sessionId);
+ }
+ return Promise.all(
+ [...sessionIds].map((sessionId) => this.retry(
+ sessionId,
+ (draft) => write(sessionId, draft),
+ )),
+ );
+ }
+
+ beginRead(sessionId: string): SessionDraftRead {
+ const current = this.hydrateDirty(sessionId);
+ const read: SessionDraftRead = {
+ revision: current?.revision ?? 0,
+ pending: Boolean(current?.pending),
+ generation: this.localCache.readInvalidation(sessionId),
+ };
+ const reads = this.activeReads.get(sessionId) ?? new Set<SessionDraftRead>();
+ reads.add(read);
+ this.activeReads.set(sessionId, reads);
+ return read;
+ }
+
+ releaseRead(sessionId: string, read: SessionDraftRead): void {
+ this.finishRead(sessionId, read);
+ this.cleanupSuccessfulEntry(sessionId);
+ }
+
+ revision(sessionId: string): number {
+ return this.entries.get(sessionId)?.revision ?? 0;
+ }
+
+ reconcileRead(
+ sessionId: string,
+ read: SessionDraftRead,
+ server: SessionDraftServerState,
+ ): string {
+ this.finishRead(sessionId, read);
+ const invalidation = this.localCache.readInvalidation(sessionId);
+ if (read.generation !== invalidation) {
+ this.discardInvalidatedSession(sessionId, invalidation);
+ return '';
+ }
+ this.invalidations.set(sessionId, invalidation);
+ const current = this.entries.get(sessionId);
+
+ // A write that finished after this read started is newer than the read's
+ // response even though both have server revisions. Preserve that result
+ // until every racing read has reconciled.
+ if (current && (read.pending || current.revision > read.revision || current.pending)) {
+ this.cleanupSuccessfulEntry(sessionId);
+ return current.text;
+ }
+
+ const cached = this.localCache.read(sessionId);
+ const dirty = current?.dirty ? current : cached?.dirty ? this.hydrateDirty(sessionId) : null;
+ if (dirty) {
+ if (dirty.text === server.text) {
+ this.acceptServer(sessionId, server, dirty.localId);
+ return server.text;
+ }
+
+ this.serverVersions.set(sessionId, server.updatedAt);
+ if (dirty.baseUpdatedAt !== server.updatedAt) {
+ dirty.conflict = true;
+ }
+ return dirty.text;
+ }
+
+ if (current && this.hasOlderRead(sessionId, current.revision)) {
+ // A read that began after this successful write may settle before a read
+ // from the older revision. Keep one retained value as a read barrier so
+ // every older response returns the newest value instead of deleting the
+ // only stale-response guard.
+ this.localCache.acknowledge(
+ sessionId,
+ current.localId,
+ server.text,
+ server.updatedAt,
+ );
+ current.text = server.text;
+ current.baseUpdatedAt = server.updatedAt;
+ this.serverVersions.set(sessionId, server.updatedAt);
+ return current.text;
+ }
+
+ this.acceptServer(sessionId, server);
+ this.cleanupSuccessfulEntry(sessionId);
+ return server.text;
+ }
+
+ clearSession(sessionId: string): void {
+ const invalidation = this.localCache.invalidate(sessionId);
+ this.invalidations.set(sessionId, invalidation);
+ this.entries.delete(sessionId);
+ this.activeReads.delete(sessionId);
+ this.serverVersions.delete(sessionId);
+ this.localCache.clear(sessionId);
+ }
+
+ rebase(sessionId: string, server: SessionDraftServerState): void {
+ this.serverVersions.set(sessionId, server.updatedAt);
+ const current = this.hydrateDirty(sessionId);
+ if (!current) return;
+ current.baseUpdatedAt = server.updatedAt;
+ current.conflict = false;
+ current.rebaseOnConflict = false;
+ current.rebaseOnConflictServerText = undefined;
+ current.serverEpoch += 1;
+ // The external revision is causally newer than every write already in
+ // flight. Detach that promise chain; its eventual result is ignored by the
+ // epoch guard below, while retry() starts from this exact server revision.
+ current.pending = null;
+ current.pendingRevision = null;
+ this.localCache.rebaseDirty(sessionId, current.localId, server.updatedAt, false);
+ }
+
+ markRejectedSend(sessionId: string): void {
+ const current = this.hydrateDirty(sessionId);
+ if (!current) return;
+ current.rebaseOnConflict = true;
+ current.rebaseOnConflictServerText = undefined;
+ this.localCache.markRebaseOnConflict(sessionId, current.localId);
+ }
+
+ private startSync(
+ sessionId: string,
+ entry: DraftEntry,
+ write: DraftSave,
+ ): Promise<SessionDraftSaveResult> {
+ if (entry.conflict) return Promise.resolve({ ok: false, conflict: true });
+ if (entry.pending && entry.pendingRevision === entry.revision) return entry.pending;
+
+ const predecessor = entry.pending;
+ const revision = entry.revision;
+ const serverEpoch = entry.serverEpoch;
+ const text = entry.text;
+ const pending = (async (): Promise<SessionDraftSaveResult> => {
+ const predecessorResult: SessionDraftSaveResult | undefined = await predecessor?.catch(
+ (): SessionDraftSaveResult => ({ ok: false }),
+ );
+ const beforeWrite = this.entries.get(sessionId);
+ if (!beforeWrite || beforeWrite.revision !== revision) return { ok: true };
+ if (beforeWrite.serverEpoch !== serverEpoch) return { ok: false };
+ if (predecessorResult?.server) {
+ beforeWrite.baseUpdatedAt = predecessorResult.server.updatedAt;
+ beforeWrite.conflict = false;
+ beforeWrite.rebaseOnConflict = (
+ predecessorResult.retryConflictIfServerText !== undefined
+ );
+ beforeWrite.rebaseOnConflictServerText = (
+ predecessorResult.retryConflictIfServerText
+ );
+ this.localCache.rebaseDirty(
+ sessionId,
+ beforeWrite.localId,
+ predecessorResult.server.updatedAt,
+ beforeWrite.rebaseOnConflict,
+ beforeWrite.rebaseOnConflictServerText,
+ );
+ }
+ if (predecessorResult?.conflict && !predecessorResult.server) {
+ beforeWrite.pending = null;
+ beforeWrite.pendingRevision = null;
+ beforeWrite.conflict = true;
+ return { ok: false, conflict: true };
+ }
+ if (beforeWrite.conflict) {
+ beforeWrite.pending = null;
+ beforeWrite.pendingRevision = null;
+ beforeWrite.conflict = true;
+ return { ok: false, conflict: true };
+ }
+
+ let result: SessionDraftSaveResult;
+ try {
+ result = await write({ text, expectedUpdatedAt: beforeWrite.baseUpdatedAt });
+ } catch {
+ result = { ok: false };
+ }
+
+ // The cloud may already contain this exact text because another write
+ // (notably the send transaction clearing a draft) won the race. That is
+ // convergence, not a user-visible conflict.
+ if (result.conflict && result.server?.text === text) {
+ result = { ok: true, server: result.server };
+ }
+ const shouldRetryRecoveredConflict = Boolean(
+ result.conflict
+ && result.server
+ && beforeWrite.revision === revision
+ && beforeWrite.serverEpoch === serverEpoch
+ && this.matchesConflictRecovery(beforeWrite, result)
+ );
+ this.applyWriteResult(sessionId, revision, serverEpoch, result);
+ if (shouldRetryRecoveredConflict) {
+ const retry = this.entries.get(sessionId);
+ if (retry?.dirty && !retry.conflict && !retry.pending) {
+ return this.startSync(sessionId, retry, write);
+ }
+ }
+ return result;
+ })();
+
+ entry.pending = pending;
+ entry.pendingRevision = revision;
+ return pending;
+ }
+
+ private applyWriteResult(
+ sessionId: string,
+ revision: number,
+ serverEpoch: number,
+ result: SessionDraftSaveResult,
+ ): void {
+ const current = this.entries.get(sessionId);
+ if (!current || current.serverEpoch !== serverEpoch) return;
+
+ if (result.ok) {
+ const server = result.server ?? {
+ text: current.text,
+ updatedAt: current.baseUpdatedAt,
+ };
+ this.serverVersions.set(sessionId, server.updatedAt);
+ if (current.revision === revision) {
+ current.pending = null;
+ current.pendingRevision = null;
+ current.dirty = false;
+ current.conflict = false;
+ current.rebaseOnConflict = false;
+ current.rebaseOnConflictServerText = undefined;
+ current.baseUpdatedAt = server.updatedAt;
+ this.localCache.acknowledge(
+ sessionId,
+ current.localId,
+ server.text,
+ server.updatedAt,
+ );
+ this.cleanupSuccessfulEntry(sessionId);
+ } else if (current.dirty && !current.conflict) {
+ // A newer edit was made while this request was in flight. Advance only
+ // that exact local mutation's cloud base before its serialized write.
+ current.baseUpdatedAt = server.updatedAt;
+ this.localCache.rebaseDirty(sessionId, current.localId, server.updatedAt);
+ }
+ return;
+ }
+
+ if (current.revision === revision) {
+ current.pending = null;
+ current.pendingRevision = null;
+ }
+ if (result.retryConflictIfServerText !== undefined && result.server) {
+ // No successor has to exist yet. Preserve this uncertainty on the current
+ // mutation so a later edit or a reload can recognize the timed-out write
+ // if it eventually commits and becomes the next conflict response.
+ current.baseUpdatedAt = result.server.updatedAt;
+ current.rebaseOnConflict = true;
+ current.rebaseOnConflictServerText = result.retryConflictIfServerText;
+ this.localCache.rebaseDirty(
+ sessionId,
+ current.localId,
+ result.server.updatedAt,
+ true,
+ result.retryConflictIfServerText,
+ );
+ }
+ if (result.conflict) {
+ if (result.server) this.serverVersions.set(sessionId, result.server.updatedAt);
+ if (current.revision !== revision && result.server) {
+ current.baseUpdatedAt = result.server.updatedAt;
+ current.conflict = false;
+ current.rebaseOnConflict = false;
+ current.rebaseOnConflictServerText = undefined;
+ this.localCache.rebaseDirty(sessionId, current.localId, result.server.updatedAt, false);
+ } else if (
+ this.matchesConflictRecovery(current, result)
+ && result.server
+ ) {
+ current.baseUpdatedAt = result.server.updatedAt;
+ current.conflict = false;
+ current.rebaseOnConflict = false;
+ current.rebaseOnConflictServerText = undefined;
+ this.localCache.rebaseDirty(sessionId, current.localId, result.server.updatedAt, false);
+ } else {
+ current.conflict = true;
+ current.rebaseOnConflict = false;
+ current.rebaseOnConflictServerText = undefined;
+ this.localCache.rebaseDirty(
+ sessionId,
+ current.localId,
+ current.baseUpdatedAt,
+ false,
+ );
+ }
+ }
+ }
+
+ private matchesConflictRecovery(
+ entry: DraftEntry,
+ result: SessionDraftSaveResult,
+ ): boolean {
+ return Boolean(
+ entry.rebaseOnConflict
+ && result.server
+ && (
+ entry.rebaseOnConflictServerText === undefined
+ || result.server.text === entry.rebaseOnConflictServerText
+ )
+ );
+ }
+
+ private hydrateDirty(sessionId: string): DraftEntry | null {
+ this.observeInvalidation(sessionId);
+ const current = this.entries.get(sessionId);
+ const cached = this.localCache.read(sessionId);
+ // A live tab owns its unsynced mutation. Shared localStorage is recovery
+ // state for reloads and inactive tabs, not permission for one tab to replace
+ // another tab's composer while navigating.
+ if (current?.dirty) return current;
+ if (current && (!cached || cached.mutationId === current.localId)) return current;
+ if (current && cached && !cached.dirty) {
+ if (current.pending) return current;
+ this.entries.delete(sessionId);
+ return null;
+ }
+ if (!cached?.dirty) return null;
+ const hydrated: DraftEntry = {
+ revision: (current?.revision ?? 0) + 1,
+ text: cached.text,
+ localId: cached.mutationId,
+ baseUpdatedAt: cached.serverUpdatedAt,
+ pending: current?.pending ?? null,
+ pendingRevision: current?.pendingRevision ?? null,
+ dirty: true,
+ conflict: false,
+ localOwned: false,
+ rebaseOnConflict: cached.rebaseOnConflict ?? false,
+ rebaseOnConflictServerText: cached.rebaseOnConflictServerText,
+ serverEpoch: current?.serverEpoch ?? 0,
+ };
+ this.entries.set(sessionId, hydrated);
+ return hydrated;
+ }
+
+ private acceptServer(
+ sessionId: string,
+ server: SessionDraftServerState,
+ mutationId?: string,
+ ): void {
+ this.serverVersions.set(sessionId, server.updatedAt);
+ this.entries.delete(sessionId);
+ if (mutationId) {
+ this.localCache.acknowledge(sessionId, mutationId, server.text, server.updatedAt);
+ } else {
+ this.localCache.writeClean(sessionId, server.text, server.updatedAt);
+ }
+ }
+
+ private observeInvalidation(sessionId: string): void {
+ const invalidation = this.localCache.readInvalidation(sessionId);
+ if (!this.invalidations.has(sessionId)) {
+ this.invalidations.set(sessionId, invalidation);
+ return;
+ }
+ if (this.invalidations.get(sessionId) === invalidation) return;
+ this.discardInvalidatedSession(sessionId, invalidation);
+ }
+
+ private discardInvalidatedSession(sessionId: string, invalidation: string | null): void {
+ this.invalidations.set(sessionId, invalidation);
+ this.entries.delete(sessionId);
+ this.activeReads.delete(sessionId);
+ this.serverVersions.delete(sessionId);
+ this.localCache.clear(sessionId);
+ }
+
+ private finishRead(sessionId: string, read: SessionDraftRead): void {
+ const reads = this.activeReads.get(sessionId);
+ if (!reads) return;
+ reads.delete(read);
+ if (!reads.size) this.activeReads.delete(sessionId);
+ }
+
+ private cleanupSuccessfulEntry(sessionId: string): void {
+ const current = this.entries.get(sessionId);
+ if (current && !current.pending && !current.dirty && !this.activeReads.has(sessionId)) {
+ this.entries.delete(sessionId);
+ }
+ }
+
+ private hasOlderRead(sessionId: string, revision: number): boolean {
+ const reads = this.activeReads.get(sessionId);
+ return Boolean(reads && [...reads].some((read) => read.revision < revision));
+ }
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3f6e7fdd3..545733c3b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6805,7 +6805,7 @@ async def sessions_bootstrap(session_id: str):
from storage import message_deliveries
queued = message_deliveries.list_queued(conn, session_id)
- draft = message_deliveries.get_draft(conn, session_id)
+ draft = message_deliveries.get_draft_state(conn, session_id)
try:
agents_payload = vibe_api.get_vibe_agents(include_disabled=False, include_archived=True)
@@ -6849,7 +6849,7 @@ async def sessions_bootstrap(session_id: str):
"next_after_id": messages_result.get("next_after_id"),
"next_before_id": messages_result.get("next_before_id"),
"queued": queued,
- "draft": {"text": (draft or {}).get("text") or ""},
+ "draft": _session_draft_payload(draft),
"turn_state": turn_state,
}
)
@@ -8633,8 +8633,12 @@ async def sessions_messages_create(session_id: str):
)
if not quick_reply_for:
message_deliveries.set_draft(conn, session_id, None)
+ draft = message_deliveries.get_draft_state(conn, session_id)
workbench_sessions_service.touch_session(conn, session_id)
- return message_deliveries.delivery_payload(row)
+ result = message_deliveries.delivery_payload(row)
+ result["draft"] = _session_draft_payload(draft)
+ result["draft_advanced"] = not bool(quick_reply_for)
+ return result
# Reserve the row FIRST (pending), then decide by the dispatch outcome.
message = _persist_user_row()
@@ -8682,6 +8686,8 @@ async def sessions_messages_create(session_id: str):
if current is None:
return dict(message)
payload = message_deliveries.delivery_payload(current)
+ payload["draft"] = message["draft"]
+ payload["draft_advanced"] = message["draft_advanced"]
if current["state"] == "queued":
payload["type"] = "queued"
payload["queued"] = True
@@ -8764,7 +8770,14 @@ async def sessions_messages_create(session_id: str):
"dispatch_error": "dispatch_pending",
}
), 502
- return jsonify({**accepted, **body}), 201
+ return jsonify(
+ {
+ **accepted,
+ **body,
+ "draft": message["draft"],
+ "draft_advanced": message["draft_advanced"],
+ }
+ ), 201
return jsonify({**current, **body}), 202
current = _retire_unclaimed_delivery(f"internal_dispatch_rejected_{status}")
return jsonify(
@@ -8919,6 +8932,13 @@ async def sessions_queue_send_now(session_id: str, message_id: str):
return jsonify(body), status
+def _session_draft_payload(draft: dict | None) -> dict:
+ return {
+ "text": (draft or {}).get("text") or "",
+ "updated_at": (draft or {}).get("updated_at"),
+ }
+
+
@app.route("/api/sessions/<session_id>/draft", methods=["GET"])
def sessions_draft_get(session_id: str):
"""The session's saved unsent compose text (restored on open / device switch)."""
@@ -8926,8 +8946,8 @@ def sessions_draft_get(session_id: str):
engine = _projects_engine()
with engine.connect() as conn:
- draft = message_deliveries.get_draft(conn, session_id)
- return jsonify({"text": (draft or {}).get("text") or ""})
+ draft = message_deliveries.get_draft_state(conn, session_id)
+ return jsonify(_session_draft_payload(draft))
@app.route("/api/sessions/<session_id>/draft", methods=["PUT"])
@@ -8935,26 +8955,50 @@ def sessions_draft_set(session_id: str):
"""Upsert the session's draft (debounced from the composer). Blank clears it."""
from core.services import sessions as workbench_sessions_service
from storage import message_deliveries
+ from storage.agent_session_rows import reserve_write_lock
payload = request.json or {}
text = payload.get("text")
+ expected_supplied = "expected_updated_at" in payload
+ expected_updated_at = payload.get("expected_updated_at")
+ if expected_supplied and expected_updated_at is not None and not isinstance(expected_updated_at, str):
+ return jsonify({"ok": False, "code": "invalid_expected_updated_at"}), 400
engine = _projects_engine()
try:
with engine.begin() as conn:
+ # The version read and its update are one CAS decision. Reserving
+ # SQLite's writer slot before either read prevents a concurrent
+ # commit from turning this transaction's snapshot into BUSY_SNAPSHOT.
+ reserve_write_lock(conn)
session = workbench_sessions_service.get_session(conn, session_id)
# Archive is terminal: drop a late/debounced draft save (e.g. the
# composer flushing as it unmounts right after archive) so it can't
# recreate a draft on a session whose drafts were just reclaimed.
if session.get("status") == "archived":
- return jsonify({"ok": True})
+ current = message_deliveries.get_draft_state(conn, session_id)
+ return jsonify({"ok": True, "draft": _session_draft_payload(current)})
+ current = message_deliveries.get_draft_state(conn, session_id)
+ current_updated_at = (current or {}).get("updated_at")
+ if (
+ (not expected_supplied and current_updated_at is not None)
+ or (expected_supplied and current_updated_at != expected_updated_at)
+ ):
+ return jsonify(
+ {
+ "ok": False,
+ "code": "draft_conflict",
+ "draft": _session_draft_payload(current),
+ }
+ ), 409
message_deliveries.set_draft(
conn,
session_id,
text if isinstance(text, str) else None,
)
+ saved = message_deliveries.get_draft_state(conn, session_id)
except LookupError as err:
return jsonify({"error": str(err)}), 404
- return jsonify({"ok": True})
+ return jsonify({"ok": True, "draft": _session_draft_payload(saved)})
@app.route("/api/events", methods=["GET"])