Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Keep chat operations alive across clients (#1644)
Ali Khokhard93631e75e7b
diff --git a/e2e/conftest.py b/e2e/conftest.pyindex 8cc8710d..4d811b8b 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -10,6 +10,7 @@ from pathlib import Pathimport pytestimport uvicorn+from playwright.sync_api import Pagefrom free_claude_code.api.app import create_appfrom free_claude_code.api.ports import ApiServices@@ -60,7 +61,6 @@ class _ModelListingProvider(BaseProvider):)self._model_infos = model_infosself._error = error- self._slow_used = Falseself._message_attempts: dict[str, int] = {}def preflight_messages(@@ -101,13 +101,12 @@ class _ModelListingProvider(BaseProvider):user_content = str(request.messages[-1].content) if request.messages else ""attempt = self._message_attempts.get(user_content, 0) + 1self._message_attempts[user_content] = attempt- slow = not self._slow_used and (- "[slow]" in user_content- or ("[slow-regenerate]" in user_content and attempt > 1)- or (summary and "[slow-compaction]" in user_content)+ slow = (+ ("[slow]" in user_content and attempt == 1)+ or ("[slow-regenerate]" in user_content and attempt == 2)+ or (summary and "[slow-compaction]" in user_content and attempt == 1))fragmented = "[fragmented]" in user_content- self._slow_used = self._slow_used or slowfailed_regeneration = "[fail-regenerate]" in user_content and attempt > 1if summary:text = "Earlier details retained."@@ -452,3 +451,14 @@ def admin_base_url(clear_settings_cache()if thread.is_alive():pytest.fail("Admin browser-test server did not stop")++[email protected](autouse=True)+def close_browser_connections_before_server_teardown(+ admin_base_url: str,+ page: Page,+) -> Iterator[None]:+ del admin_base_url+ yield+ if not page.is_closed():+ page.goto("about:blank")diff --git a/e2e/test_chat_sessions.py b/e2e/test_chat_sessions.pyindex 153a5877..db610585 100644--- a/e2e/test_chat_sessions.py+++ b/e2e/test_chat_sessions.py@@ -1,7 +1,7 @@import jsonimport re-from playwright.sync_api import Page, expect+from playwright.sync_api import Page, Request, expectdef _new_chat(page: Page, admin_base_url: str) -> None:@@ -221,7 +221,7 @@ def test_delayed_older_page_cannot_cross_into_another_chat(expect(page.locator(".assistant-message")).to_have_count(1)message.fill("A latest")page.get_by_role("button", name="Send").click()- expect(message).to_be_enabled()+ expect(page.locator(".assistant-message:not(.live-message)")).to_have_count(2)title = page.get_by_label("Chat title")title.fill("[delay-older-page] Chat A")with page.expect_response(@@ -400,15 +400,17 @@ def test_rejected_send_preserves_draft_after_stale_revision() -> None:_new_chat(page, admin_base_url)session_id = page.url.rsplit("/", 1)[-1]+ _hold_next_chat_operation(page, "send")+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("do not discard this draft")+ page.get_by_role("button", name="Send").click()+renamed = page.request.patch(f"{admin_base_url}/admin/api/chat/sessions/{session_id}",data={"expected_revision": 1, "title": "Changed elsewhere"},)assert renamed.ok-- message = page.get_by_role("textbox", name="Message", exact=True)- message.fill("do not discard this draft")- page.get_by_role("button", name="Send").click()+ page.evaluate("() => { window.__releaseHeldChatRequest(); }")expect(message).to_have_value("do not discard this draft")expect(page.locator("#chatNotice")).to_contain_text("changed in another tab")@@ -503,7 +505,7 @@ def test_chat_stop_then_retry_uses_one_operation_owner(expect(page.get_by_text("E2E answer")).to_be_visible()-def test_chat_opened_in_another_tab_recovers_when_operation_stops(+def test_chat_opened_in_another_tab_shares_live_operation_and_stop(page: Page,admin_base_url: str,) -> None:@@ -515,12 +517,247 @@ def test_chat_opened_in_another_tab_recovers_when_operation_stops(other = page.context.new_page()try:other.goto(page.url)- expect(other.locator("#chatComposerStatus")).to_contain_text(- "running in another tab"- )+ expect(other.get_by_text("E2E answer", exact=True)).to_be_visible()+ expect(other.get_by_role("button", name="Stop")).to_be_visible()+ other.get_by_role("button", name="Stop").click()+ expect(page.get_by_role("button", name="Retry")).to_be_visible()+ expect(other.get_by_role("button", name="Retry")).to_be_visible(timeout=3_000)+ finally:+ other.close()+++def test_refresh_keeps_one_live_operation_and_reconstructs_its_answer(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("[slow] survive refresh")+ message.press("Enter")+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()+ expect(page.get_by_role("button", name="Stop")).to_be_visible()++ page.reload()++ expect(page.get_by_text("[slow] survive refresh", exact=True)).to_have_count(1)+ expect(page.locator(".assistant-message")).to_have_count(1)+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()+ page.get_by_role("button", name="Stop").click()+ expect(page.get_by_role("button", name="Retry")).to_be_visible()+++def test_terminal_event_cannot_be_undone_by_an_older_detail_response(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ title = page.get_by_label("Chat title")+ title.fill("[delay-detail] stale operation snapshot")+ with page.expect_response(lambda response: response.request.method == "PATCH"):+ title.press("Enter")+ page.get_by_role("textbox", name="Message", exact=True).fill("[slow] finish once")+ page.get_by_role("button", name="Send").click()+ expect(page.get_by_role("button", name="Stop")).to_be_visible()++ other = page.context.new_page()+ try:+ with other.expect_request(+ lambda request: (+ request.method == "GET"+ and request.url.endswith(page.url.rsplit("/", 1)[-1])+ )+ ):+ other.goto(page.url, wait_until="commit")+ page.wait_for_timeout(150)page.get_by_role("button", name="Stop").click()expect(page.get_by_role("button", name="Retry")).to_be_visible()+expect(other.get_by_role("button", name="Retry")).to_be_visible(timeout=3_000)+ expect(other.get_by_role("button", name="Stop")).to_have_count(0)+ expect(other.locator("#chatComposerStatus")).not_to_have_text("Thinking…")+ finally:+ other.close()+++def test_two_sessions_run_concurrently_across_navigation(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ first_url = page.url+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("[slow] first active chat")+ message.press("Enter")+ expect(page.get_by_role("button", name="Stop")).to_be_visible()++ page.get_by_role("button", name="Chats", exact=False).click()+ page.get_by_role("button", name="New chat", exact=True).click()+ expect(page).to_have_url(re.compile(r"/admin/chat/[0-9a-f-]{36}$"))+ second_url = page.url+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("[slow] second active chat")+ message.press("Enter")+ expect(page.get_by_role("button", name="Stop")).to_be_visible()++ page.get_by_role("button", name="Chats", exact=False).click()+ expect(page.locator(".chat-session-status", has_text="Thinking…")).to_have_count(2)++ page.goto(first_url)+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()+ page.get_by_role("button", name="Stop").click()+ expect(page.get_by_role("button", name="Retry")).to_be_visible()++ page.goto(second_url)+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()+ page.get_by_role("button", name="Stop").click()+ expect(page.get_by_role("button", name="Retry")).to_be_visible()+++def test_library_card_tracks_background_operation_and_durable_summary(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ title = page.get_by_label("Chat title")+ title.fill("Library observer")+ with page.expect_response(lambda response: response.request.method == "PATCH"):+ title.press("Enter")+ other = page.context.new_page()+ try:+ other.goto(f"{admin_base_url}/admin/chat")+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("[slow] live library preview")+ message.press("Enter")++ card = other.locator(".chat-session-card", has_text="Library observer")+ expect(card).to_be_visible(timeout=3_000)+ expect(card.locator("p")).to_have_text("[slow] live library preview")+ expect(card.locator(".chat-session-status")).to_have_text("Thinking…")++ page.get_by_role("button", name="Stop").click()+ expect(page.get_by_role("button", name="Retry")).to_be_visible()+ expect(card.locator(".chat-session-status")).to_have_count(0, timeout=3_000)+ expect(card.locator("p")).to_have_text("[slow] live library preview")+ expect(card.locator("span").first).to_contain_text("just now")+ finally:+ other.close()+++def test_chat_operation_continues_while_providers_view_is_open(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ session_url = page.url+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("[slow] keep running outside chat")+ message.press("Enter")+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()++ page.get_by_role("button", name="Providers", exact=True).click()+ expect(page.locator("#pageTitle")).to_have_text("Providers")+ page.goto(session_url)++ expect(+ page.get_by_text("[slow] keep running outside chat", exact=True)+ ).to_have_count(1)+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()+ expect(page.get_by_role("button", name="Stop")).to_be_visible()+ page.get_by_role("button", name="Stop").click()+ expect(page.get_by_role("button", name="Retry")).to_be_visible()+++def test_event_feed_reconnect_preserves_transcript_and_draft(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("before reconnect")+ message.press("Enter")+ expect(page.get_by_role("button", name="Regenerate")).to_be_visible()+ message.fill("draft during reconnect")++ page.context.set_offline(True)+ expect(page.locator("#chatComposerStatus")).to_have_text("Reconnecting…")+ expect(page.get_by_text("E2E answer", exact=True)).to_be_visible()+ expect(message).to_have_value("draft during reconnect")+ expect(page.get_by_role("button", name="Send")).to_be_disabled()++ page.context.set_offline(False)+ expect(page.locator("#chatComposerStatus")).to_be_empty(timeout=10_000)+ expect(message).to_have_value("draft during reconnect")+ expect(page.get_by_role("button", name="Send")).to_be_enabled()+ expect(page.get_by_text("E2E answer", exact=True)).to_have_count(1)+++def test_drafts_are_session_scoped_and_private_to_each_tab(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ first_url = page.url+ message = page.get_by_role("textbox", name="Message", exact=True)+ message.fill("first private draft")+ page.reload()+ expect(message).to_have_value("first private draft")++ other = page.context.new_page()+ try:+ other.goto(first_url)+ expect(other.get_by_role("textbox", name="Message", exact=True)).to_be_empty()+ finally:+ other.close()++ page.get_by_role("button", name="Chats", exact=False).click()+ page.get_by_role("button", name="New chat", exact=True).click()+ page.get_by_role("textbox", name="Message", exact=True).fill("second private draft")+ page.goto(first_url)+ expect(page.get_by_role("textbox", name="Message", exact=True)).to_have_value(+ "first private draft"+ )+++def test_session_settings_sync_without_disturbing_another_tab_draft(+ page: Page,+ admin_base_url: str,+) -> None:+ _new_chat(page, admin_base_url)+ other = page.context.new_page()+ try:+ other.goto(page.url)+ other_patches: list[str] = []++ def remember_other_patch(request: Request) -> None:+ if request.method == "PATCH":+ other_patches.append(request.post_data or "")++ other.on("request", remember_other_patch)+ other_message = other.get_by_role("textbox", name="Message", exact=True)+ other_message.fill("private draft")+ other_title = other.get_by_label("Chat title")+ other_title.fill("Local title draft")++ title = page.get_by_label("Chat title")+ title.fill("Shared title")+ with page.expect_response(lambda response: response.request.method == "PATCH"):+ title.press("Enter")+ expect(other_title).to_have_value("Local title draft")+ other.wait_for_timeout(50)+ assert other_patches == []+ with other.expect_response(lambda response: response.request.method == "PATCH"):+ other_title.press("Enter")+ assert len(other_patches) == 1+ expect(title).to_have_value("Local title draft")++ _select_model(page, "open_router/vendor/model-b")+ expect(other.get_by_label("Selected model")).to_have_value(+ "open_router/vendor/model-b"+ )+ with page.expect_response(lambda response: response.request.method == "PATCH"):+ page.get_by_label("Thinking").select_option("high")+ expect(other.get_by_label("Thinking")).to_have_value("high")+ expect(other_message).to_have_value("private draft")finally:other.close()@@ -538,9 +775,8 @@ def test_active_chat_deleted_in_another_tab_returns_to_library(other = page.context.new_page()try:other.goto(session_url)- expect(other.locator("#chatComposerStatus")).to_contain_text(- "running in another tab"- )+ expect(other.get_by_text("E2E answer", exact=True)).to_be_visible()+ expect(other.get_by_role("button", name="Stop")).to_be_visible()other.on("dialog", lambda dialog: dialog.accept())other.get_by_role("button", name="Delete").click()expect(other).to_have_url(f"{admin_base_url}/admin/chat")@@ -606,12 +842,11 @@ def test_regeneration_is_visible_and_recovers_in_another_tab(other = page.context.new_page()try:other.goto(page.url)- expect(other.locator("#chatComposerStatus")).to_contain_text(- "running in another tab"- )+ expect(other.get_by_text("E2E answer", exact=True)).to_be_visible()+ expect(other.get_by_role("button", name="Stop")).to_be_visible()expect(other.get_by_label("Selected model")).to_be_disabled()- page.get_by_role("button", name="Stop").click()+ other.get_by_role("button", name="Stop").click()expect(other.get_by_label("Selected model")).to_be_enabled(timeout=3_000)expect(other.get_by_role("button", name="Regenerate")).to_be_visible()@@ -658,12 +893,11 @@ def test_manual_compaction_is_visible_and_recovers_in_another_tab(other = page.context.new_page()try:other.goto(page.url)- expect(other.locator("#chatComposerStatus")).to_contain_text(- "running in another tab"- )+ expect(other.locator("#chatComposerStatus")).to_have_text("Compacting…")+ expect(other.get_by_role("button", name="Stop")).to_be_visible()expect(other.get_by_label("Thinking")).to_be_disabled()- page.get_by_role("button", name="Stop").click()+ other.get_by_role("button", name="Stop").click()expect(other.get_by_label("Thinking")).to_be_enabled(timeout=3_000)finally:@@ -703,7 +937,12 @@ def test_long_transcript_keeps_composer_visible_and_preserves_reader_scroll_posipage.get_by_role("button", name="Send").click()expect(page.get_by_role("button", name="Stop")).to_be_visible()scroller = page.locator("#chatTranscript")- assert scroller.evaluate("node => node.scrollHeight > node.clientHeight")+ page.wait_for_function(+ """() => {+ const node = document.getElementById('chatTranscript');+ return node && node.scrollHeight > node.clientHeight;+ }"""+ )composer_is_fully_visible = message.evaluate("node => { const box = node.getBoundingClientRect(); ""return box.top >= 0 && box.bottom <= window.innerHeight; }"diff --git a/pyproject.toml b/pyproject.tomlindex b8fb803f..3d3dc17d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "5.18.11"+version = "5.19.0"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/api/admin_static/chat_sessions.css b/src/free_claude_code/api/admin_static/chat_sessions.cssindex 2e604010..fddca482 100644--- a/src/free_claude_code/api/admin_static/chat_sessions.css+++ b/src/free_claude_code/api/admin_static/chat_sessions.css@@ -112,6 +112,11 @@font-size: 12px;}+.chat-session-card .chat-session-status {+ color: var(--accent);+ font-weight: 700;+}+.chat-load-more {margin-top: 18px;}diff --git a/src/free_claude_code/api/admin_static/chat_sessions.js b/src/free_claude_code/api/admin_static/chat_sessions.jsindex 3258b12a..949194cc 100644--- a/src/free_claude_code/api/admin_static/chat_sessions.js+++ b/src/free_claude_code/api/admin_static/chat_sessions.js@@ -17,18 +17,49 @@libraryLoadMore: null,olderLoad: null,operation: null,+ activeOperations: new Map(),+ pendingCommands: new Map(),+ sessionSummaries: new Map(),+ sessionRevisions: new Map(),+ deletedSessions: new Set(),+ retiredTitleInputs: new WeakSet(),draft: "",draftSessionId: null,draftOperationId: null,+ draftSubmittedText: "",routeVersion: 0,estimateTimer: null,estimateVersion: 0,- foreignPollTimer: null,- serverOperationActive: false,- eventChannel: null,+ feed: null,+ feedStatus: "connecting",+ feedLastId: 0,+ feedSyncVersion: 0,+ eventBuffer: null,+ feedRestartTimer: null,modelComboboxes: new Set(),};+ const CHAT_EVENT_TYPES = [+ "session.created",+ "session.updated",+ "session.deleted",+ "preferences.updated",+ "operation.started",+ "turn.started",+ "segment.started",+ "segment.delta",+ "segment.completed",+ "compaction.started",+ "compaction.progress",+ "compaction.completed",+ "compaction.failed",+ "compaction.stopped",+ "turn.completed",+ "turn.failed",+ "turn.stopped",+ "operation.failed",+ ];+const root = () => document.getElementById("chatRoot");function node(tag, className = "", text = "") {@@ -56,16 +87,678 @@async function initialize(api) {if (state.initialized) return;state.api = api;- if (typeof window.BroadcastChannel === "function") {- state.eventChannel = new BroadcastChannel("fcc-chat-sessions");- state.eventChannel.addEventListener("message", handleCrossTabEvent);- }state.initialized = true;+ connectEventFeed();if (chatIsVisible()) {- await activate(window.location.pathname);+ renderLoading();+ }+ }++ function mutationsReady() {+ return state.feedStatus === "live";+ }++ function connectEventFeed() {+ window.clearTimeout(state.feedRestartTimer);+ state.feedRestartTimer = null;+ state.feed?.close();+ state.feedStatus = state.feedLastId ? "reconnecting" : "connecting";+ refreshFeedState();+ const feed = new EventSource("/admin/api/chat/events");+ state.feed = feed;+ feed.addEventListener("feed.ready", (event) => {+ if (state.feed === feed) void synchronizeFeed(event);+ });+ feed.addEventListener("feed.resync_required", () => {+ if (state.feed === feed) restartEventFeed();+ });+ CHAT_EVENT_TYPES.forEach((type) => {+ feed.addEventListener(type, (event) => {+ if (state.feed === feed) receiveChatEvent(type, event);+ });+ });+ feed.addEventListener("error", () => {+ if (state.feed !== feed) return;+ state.feedSyncVersion += 1;+ state.feedStatus = "reconnecting";+ refreshFeedState();+ if (!state.bootstrap) void refresh(window.location.pathname);+ });+ }++ function restartEventFeed() {+ state.feedSyncVersion += 1;+ state.feed?.close();+ state.feed = null;+ state.feedStatus = "reconnecting";+ refreshFeedState();+ window.clearTimeout(state.feedRestartTimer);+ state.feedRestartTimer = window.setTimeout(connectEventFeed, 250);+ }++ async function synchronizeFeed(event) {+ const cursor = Number.parseInt(event.lastEventId, 10);+ let snapshot;+ try {+ snapshot = JSON.parse(event.data);+ } catch {+ restartEventFeed();+ return;+ }+ if (+ !Number.isSafeInteger(cursor) ||+ cursor < 0 ||+ snapshot?.cursor !== cursor ||+ !Array.isArray(snapshot?.active_operations)+ ) {+ restartEventFeed();+ return;+ }+ const syncVersion = ++state.feedSyncVersion;+ state.feedLastId = cursor;+ state.feedStatus = "synchronizing";+ refreshFeedState();+ const snapshotOperationIds = installActiveSnapshot(snapshot.active_operations);+ if (!snapshotOperationIds) {+ restartEventFeed();+ return;+ }+ await withBufferedEvents(() => refresh(window.location.pathname));+ if (syncVersion !== state.feedSyncVersion) return;+ settlePendingAfterSnapshot(snapshotOperationIds);+ state.feedStatus = "live";+ refreshFeedState();+ }++ async function withBufferedEvents(loadSnapshot) {+ if (state.eventBuffer) {+ await loadSnapshot();+ return;+ }+ const buffer = [];+ state.eventBuffer = buffer;+ try {+ await loadSnapshot();+ } finally {+ if (state.eventBuffer !== buffer) return;+ state.eventBuffer = null;+ buffer.forEach(applyChatEvent);+ }+ }++ function receiveChatEvent(type, event) {+ let payload;+ const id = Number.parseInt(event.lastEventId, 10);+ try {+ payload = JSON.parse(event.data);+ } catch {+ restartEventFeed();+ return;+ }+ if (!Number.isSafeInteger(id) || id <= 0 || !payload) {+ restartEventFeed();+ return;+ }+ if (id <= state.feedLastId) return;+ if (id !== state.feedLastId + 1) {+ restartEventFeed();+ return;+ }+ state.feedLastId = id;+ const chatEvent = { type, id, payload };+ if (state.eventBuffer) {+ state.eventBuffer.push(chatEvent);+ } else {+ applyChatEvent(chatEvent);+ }+ }++ function applyChatEvent(event) {+ const { type, payload } = event;+ if (type === "session.created" || type === "session.updated") {+ applySessionSummary(payload);+ return;+ }+ if (type === "session.deleted") {+ applySessionDeletion(payload.session_id);+ return;+ }+ if (type === "preferences.updated") {+ applyPreferencesUpdate(payload);+ return;+ }+ applyOperationEvent(type, payload);+ }++ function applySessionSummary(payload) {+ const summary = sessionSummaryFromPayload(payload);+ const current = summary ? reduceSessionSummary(summary) : null;+ if (!current) return;+ upsertLibrarySummary(current);+ if (state.session?.id !== current.id) {+ if (!state.session && chatIsVisible()) renderLibraryItems();+ return;+ }+ if (current.revision < state.session.revision) return;+ const controlsChanged =+ state.session.title !== current.title ||+ state.session.model !== current.model ||+ state.session.reasoning !== current.reasoning;+ const titleEdit = captureTitleEdit();+ const selection = captureComposerSelection();+ state.session = {+ ...state.session,+ title: current.title,+ model: current.model,+ reasoning: current.reasoning,+ revision: current.revision,+ created_at: current.created_at,+ updated_at: current.updated_at,+ };+ if (controlsChanged) {+ renderSessionPreservingScroll(titleEdit);+ restoreComposerSelection(selection);+ }+ scheduleEstimate(true);+ }++ function sessionSummaryFromPayload(payload) {+ if (+ typeof payload.session_id !== "string" ||+ typeof payload.title !== "string" ||+ typeof payload.model !== "string" ||+ typeof payload.reasoning !== "string" ||+ !Number.isInteger(payload.revision) ||+ typeof payload.preview !== "string" ||+ !Number.isInteger(payload.created_at) ||+ !Number.isInteger(payload.updated_at)+ )+ return null;+ return {+ id: payload.session_id,+ title: payload.title,+ model: payload.model,+ reasoning: payload.reasoning,+ revision: payload.revision,+ preview: payload.preview,+ created_at: payload.created_at,+ updated_at: payload.updated_at,+ };+ }++ function reduceSessionSummary(summary) {+ if (state.deletedSessions.has(summary.id)) return null;+ const knownRevision = state.sessionRevisions.get(summary.id) || 0;+ if (summary.revision < knownRevision) return null;+ state.sessionRevisions.set(summary.id, summary.revision);+ state.sessionSummaries.set(summary.id, summary);+ return summary;+ }++ function upsertLibrarySummary(summary) {+ state.libraryItems = state.libraryItems.filter((item) => item.id !== summary.id);+ if (matchesLibraryQuery(summary)) state.libraryItems.push(summary);+ sortLibraryItems();+ }++ function matchesLibraryQuery(summary) {+ const query = state.libraryQuery.trim().toLocaleLowerCase();+ return !query || summary.title.toLocaleLowerCase().includes(query);+ }++ function sortLibraryItems() {+ state.libraryItems.sort(+ (left, right) =>+ right.updated_at - left.updated_at || right.id.localeCompare(left.id),+ );+ }++ function applySessionDeletion(sessionId) {+ if (typeof sessionId !== "string") return;+ state.deletedSessions.add(sessionId);+ state.sessionSummaries.delete(sessionId);+ state.sessionRevisions.delete(sessionId);+ const operation = state.activeOperations.get(sessionId);+ if (operation) cancelOperationRender(operation);+ state.activeOperations.delete(sessionId);+ const pending = state.pendingCommands.get(sessionId);+ if (pending) cancelOperationRender(pending);+ state.pendingCommands.delete(sessionId);+ removeDraft(sessionId);+ state.libraryItems = state.libraryItems.filter(+ (session) => session.id !== sessionId,+ );+ if (+ state.session?.id === sessionId ||+ routedSessionId(window.location.pathname) === sessionId+ ) {+ detachVisibleOperation();+ window.history.replaceState({}, "", "/admin/chat");+ void route(window.location.pathname);+ } else if (!state.session && chatIsVisible()) {+ renderLibraryItems();+ }+ }++ function applyPreferencesUpdate(payload) {+ if (!state.bootstrap || !Number.isInteger(payload.updated_at)) return;+ const current = state.bootstrap.preferences;+ if (current && payload.updated_at < current.updated_at) return;+ state.bootstrap.preferences = {+ system_prompt: payload.system_prompt,+ last_model: payload.last_model,+ last_reasoning: payload.last_reasoning,+ updated_at: payload.updated_at,+ };+ if (state.session) scheduleEstimate(true);+ }++ function createOperation(values) {+ const phase = values.phase || "generating";+ return {+ id: values.id,+ sessionId: values.sessionId,+ action: values.action,+ phase,+ segments: values.segments || [],+ sequence: values.sequence || 0,+ status: phase === "compacting" ? "Compacting…" : "Thinking…",+ userText: values.userText || "",+ accepted: Boolean(values.accepted),+ failureMessage: "",+ renderFrame: null,+ returnFocusToComposer: Boolean(values.returnFocusToComposer),+ commandPending: Boolean(values.commandPending),+ serverObserved: Boolean(values.serverObserved),+ ambiguousError: "",+ turnId: values.turnId || null,+ generationId: values.generationId || null,+ regeneration: Boolean(values.regeneration),+ actualModel: values.actualModel || null,+ };+ }++ function operationFromSnapshot(snapshot, existing = null) {+ const operation =+ existing && existing.id === snapshot.operation_id+ ? existing+ : createOperation({+ id: snapshot.operation_id,+ sessionId: snapshot.session_id,+ action: snapshot.kind,+ });+ if (snapshot.operation_sequence < operation.sequence) return operation;+ operation.action = snapshot.kind;+ operation.phase = snapshot.phase;+ operation.status =+ snapshot.phase === "compacting" ? "Compacting…" : "Thinking…";+ operation.userText = snapshot.submitted_text || "";+ operation.turnId = snapshot.turn_id;+ operation.generationId = snapshot.generation_id;+ operation.regeneration = Boolean(snapshot.regeneration);+ operation.actualModel = snapshot.actual_model;+ operation.segments = (snapshot.segments || []).map((segment) => ({+ kind: segment.kind,+ text: segment.text,+ pending: [],+ }));+ operation.sequence = snapshot.operation_sequence;+ operation.accepted = Boolean(snapshot.turn_id || snapshot.generation_id);+ operation.serverObserved = true;+ operation.commandPending = false;+ operation.ambiguousError = "";+ return operation;+ }++ function validOperationKind(value) {+ return ["send", "retry", "regenerate", "compact"].includes(value);+ }++ function validOperationSnapshot(snapshot) {+ return Boolean(+ snapshot &&+ typeof snapshot.session_id === "string" &&+ typeof snapshot.operation_id === "string" &&+ validOperationKind(snapshot.kind) &&+ ["generating", "compacting"].includes(snapshot.phase) &&+ Number.isInteger(snapshot.operation_sequence) &&+ Array.isArray(snapshot.segments),+ );+ }++ function installActiveSnapshot(snapshots) {+ const next = new Map();+ const operationIds = new Set();+ for (const snapshot of snapshots) {+ if (!validOperationSnapshot(snapshot) || next.has(snapshot.session_id)) {+ return null;+ }+ const current = state.activeOperations.get(snapshot.session_id);+ const pending = state.pendingCommands.get(snapshot.session_id);+ const reusable =+ current?.id === snapshot.operation_id+ ? current+ : pending?.id === snapshot.operation_id+ ? pending+ : null;+ const operation = operationFromSnapshot(snapshot, reusable);+ next.set(snapshot.session_id, operation);+ operationIds.add(snapshot.operation_id);+ if (pending?.id === snapshot.operation_id) {+ state.pendingCommands.delete(snapshot.session_id);+ }+ }+ state.activeOperations.forEach((operation, sessionId) => {+ if (next.get(sessionId) !== operation) cancelOperationRender(operation);+ });+ state.activeOperations = next;+ selectVisibleOperation();+ if (!state.session && chatIsVisible()) renderLibraryItems();+ return operationIds;+ }++ function settlePendingAfterSnapshot(operationIds) {+ if (!operationIds) {+ restartEventFeed();+ return;+ }+ [...state.pendingCommands.values()].forEach((pending) => {+ if (pending.commandPending || operationIds.has(pending.id)) return;+ if (pending.serverObserved) {+ clearPendingCommand(pending);+ } else if (pending.ambiguousError) {+ markCommandUncertain(pending);+ }+ });+ selectVisibleOperation();+ if (state.session) renderSessionPreservingScroll();+ }++ function selectVisibleOperation() {+ if (!state.session) {+ state.operation = null;+ return;+ }+ state.operation =+ state.activeOperations.get(state.session.id) ||+ state.pendingCommands.get(state.session.id) ||+ null;+ }++ function applyOperationEvent(type, payload) {+ if (+ typeof payload.session_id !== "string" ||+ typeof payload.operation_id !== "string" ||+ !validOperationKind(payload.kind) ||+ !Number.isInteger(payload.operation_sequence)+ )+ return;+ const active = state.activeOperations.get(payload.session_id);+ const pending = state.pendingCommands.get(payload.session_id);+ const matchingActive = active?.id === payload.operation_id ? active : null;+ const matchingPending = pending?.id === payload.operation_id ? pending : null;+ if (isTerminalEvent(type, payload.kind)) {+ if (+ matchingActive &&+ payload.operation_sequence <= matchingActive.sequence+ )+ return;+ if (matchingActive) matchingActive.sequence = payload.operation_sequence;+ if (matchingPending) matchingPending.serverObserved = true;+ void settleOperation(type, payload, matchingActive || matchingPending);+ return;+ }+ let operation = matchingActive || matchingPending;+ if (!operation) {+ operation = createOperation({+ id: payload.operation_id,+ sessionId: payload.session_id,+ action: payload.kind,+ });+ }+ if (payload.operation_sequence <= operation.sequence) return;+ if (active && active !== operation) cancelOperationRender(active);+ state.activeOperations.set(payload.session_id, operation);+ if (matchingPending) state.pendingCommands.delete(payload.session_id);+ operation.serverObserved = true;+ operation.commandPending = false;+ let structural = true;+ let restoreComposerFocus = false;+ if (type === "operation.started") {+ operation.action = payload.kind;+ operation.phase = payload.phase;+ operation.status =+ payload.phase === "compacting" ? "Compacting…" : "Thinking…";+ operation.userText = payload.submitted_text || "";+ } else if (type === "turn.started") {+ operation.accepted = true;+ operation.phase = "generating";+ operation.status = "Thinking…";+ operation.turnId = payload.turn_id;+ operation.generationId = payload.generation_id;+ operation.regeneration = Boolean(payload.regeneration);+ if (operation.action === "send") confirmSubmittedDraft(operation.id);+ restoreComposerFocus =+ operation.returnFocusToComposer && composerFocusIsUnclaimed();+ } else if (type === "segment.started") {+ operation.segments[payload.ordinal] = {+ kind: payload.segment_kind,+ text: "",+ pending: [],+ };+ } else if (type === "segment.delta") {+ const segment = operation.segments[payload.ordinal];+ if (segment) {+ if (state.operation === operation) {+ segment.pending.push(payload.delta);+ structural = false;+ scheduleLiveRender(operation);+ } else {+ segment.text += payload.delta;+ }+ }+ } else if (type === "compaction.started") {+ operation.phase = "compacting";+ operation.status = "Compacting…";+ } else if (type === "compaction.completed" && operation.action !== "compact") {+ operation.phase = "generating";+ operation.status = "Thinking…";+ }+ operation.sequence = payload.operation_sequence;+ if (state.session?.id === operation.sessionId) state.operation = operation;+ if (structural && state.operation === operation) {+ renderOperationStructure(operation);+ if (restoreComposerFocus) focusComposerAtEnd();+ } else if (!state.session && chatIsVisible()) {+ renderLibraryItems();+ }+ }++ function isTerminalEvent(type, kind) {+ return (+ [+ "turn.completed",+ "turn.failed",+ "turn.stopped",+ "compaction.failed",+ "compaction.stopped",+ "operation.failed",+ ].includes(type) ||+ (type === "compaction.completed" && kind === "compact")+ );+ }++ async function settleOperation(type, payload, operation) {+ const sessionId = payload.session_id;+ const operationId = payload.operation_id;+ if (operation) cancelOperationRender(operation);+ if (state.activeOperations.get(sessionId)?.id === operationId) {+ state.activeOperations.delete(sessionId);+ }+ if (state.pendingCommands.get(sessionId)?.id === operationId) {+ state.pendingCommands.delete(sessionId);+ }+ if (state.session?.id !== sessionId) {+ if (!state.session && chatIsVisible()) renderLibraryItems();+ return;+ }+ selectVisibleOperation();+ if (type === "operation.failed") {+ if (payload.kind === "send") rejectSubmittedDraft(operationId);+ renderSessionPreservingScroll();+ setNotice(payload.message || "Chat operation failed.", "error");+ return;+ }+ await reloadSession();+ if (type === "compaction.failed") {+ setNotice(payload.message || "Compaction failed.", "error");+ }+ }++ function refreshFeedState() {+ if (state.session) refreshComposerState();+ const newChat = document.querySelector('[data-testid="chat-new"]');+ if (newChat) newChat.disabled = !mutationsReady();+ }++ function focusComposerAtEnd() {+ const textarea = document.getElementById("chatComposer");+ restoreComposerSelection(+ textarea+ ? {+ start: textarea.value.length,+ end: textarea.value.length,+ direction: "none",+ }+ : null,+ );+ }++ function draftKey(sessionId) {+ return `fcc.chat.draft.${sessionId}`;+ }++ function loadDraft(sessionId) {+ state.draftSessionId = sessionId;+ state.draft = "";+ state.draftOperationId = null;+ state.draftSubmittedText = "";+ try {+ const stored = JSON.parse(sessionStorage.getItem(draftKey(sessionId)) || "null");+ if (!stored || typeof stored !== "object") return;+ if (typeof stored.text === "string") state.draft = stored.text;+ if (typeof stored.operationId === "string") {+ state.draftOperationId = stored.operationId;+ }+ if (typeof stored.submittedText === "string") {+ state.draftSubmittedText = stored.submittedText;+ }+ } catch {+ // In-memory draft state remains usable when browser storage is unavailable.+ }+ }++ function saveDraft() {+ if (!state.draftSessionId) return;+ try {+ if (!state.draft && !state.draftOperationId) {+ sessionStorage.removeItem(draftKey(state.draftSessionId));+ return;+ }+ sessionStorage.setItem(+ draftKey(state.draftSessionId),+ JSON.stringify({+ text: state.draft,+ operationId: state.draftOperationId,+ submittedText: state.draftSubmittedText,+ }),+ );+ } catch {+ // In-memory draft state remains usable when browser storage is unavailable.+ }+ }++ function removeDraft(sessionId) {+ try {+ sessionStorage.removeItem(draftKey(sessionId));+ } catch {+ // Deletion remains correct even when browser storage is unavailable.+ }+ if (state.draftSessionId === sessionId) {+ state.draft = "";+ state.draftSessionId = null;+ state.draftOperationId = null;+ state.draftSubmittedText = "";+ }+ }++ function confirmSubmittedDraft(operationId) {+ if (state.draftOperationId !== operationId) return;+ if (state.draft === state.draftSubmittedText) state.draft = "";+ state.draftOperationId = null;+ state.draftSubmittedText = "";+ saveDraft();+ const textarea = document.getElementById("chatComposer");+ if (textarea) textarea.value = state.draft;+ }++ function rejectSubmittedDraft(operationId) {+ if (state.draftOperationId !== operationId) return;+ if (!state.draft) state.draft = state.draftSubmittedText;+ state.draftOperationId = null;+ state.draftSubmittedText = "";+ saveDraft();+ }++ function rejectCommand(operation, message) {+ cancelOperationRender(operation);+ if (state.pendingCommands.get(operation.sessionId) === operation) {+ state.pendingCommands.delete(operation.sessionId);+ }+ if (operation.action === "send") rejectSubmittedDraft(operation.id);+ if (state.operation === operation) {+ selectVisibleOperation();+ renderSessionPreservingScroll();+ setNotice(message, "error");}}+ function clearPendingCommand(operation) {+ if (state.pendingCommands.get(operation.sessionId) === operation) {+ state.pendingCommands.delete(operation.sessionId);+ }+ if (+ operation.action === "send" &&+ state.turns.some((turn) => turn.operation_id === operation.id)+ ) {+ confirmSubmittedDraft(operation.id);+ }+ cancelOperationRender(operation);+ }++ function markCommandUncertain(operation) {+ clearPendingCommand(operation);+ if (state.operation !== operation) return;+ selectVisibleOperation();+ renderSessionPreservingScroll();+ setNotice(+ "The connection was lost before FCC could confirm this command. Check the chat before trying it again.",+ "error",+ );+ }++ function reconcileAmbiguousCommand(operation) {+ if (state.pendingCommands.get(operation.sessionId) !== operation) return;+ restartEventFeed();+ }++ function detachVisibleOperation() {+ if (!state.operation) return;+ cancelOperationRender(state.operation);+ commitPendingDeltas(state.operation);+ state.operation = null;+ }+async function refresh(path = window.location.pathname) {if (!state.initialized) return;const requestVersion = ++state.bootstrapRequestVersion;@@ -92,10 +785,9 @@renderLoading();return;}- stopForeignOperationPoll();state.routeVersion += 1;renderLoading();- await refresh(path);+ await withBufferedEvents(() => refresh(path));}function chatIsVisible() {@@ -104,7 +796,6 @@}async function route(path) {- stopForeignOperationPoll();const version = ++state.routeVersion;const sessionId = routedSessionId(path);if (!sessionId) {@@ -139,9 +830,8 @@}async function showLibrary(version) {- cancelLocalStream();+ detachVisibleOperation();state.session = null;- state.serverOperationActive = false;if (!state.bootstrap?.available) {renderUnavailable();return;@@ -160,6 +850,7 @@);const newButton = button("New chat", "primary-button", createSession);newButton.dataset.testid = "chat-new";+ newButton.disabled = !mutationsReady();header.append(copy, newButton);const search = node("input", "chat-search");@@ -220,9 +911,16 @@try {const page = await state.api(`/admin/api/chat/sessions?${params}`);if (!isCurrent()) return;- state.libraryItems = reset- ? page.sessions- : [...state.libraryItems, ...page.sessions];+ const merged = new Map(+ state.libraryItems.map((session) => [session.id, session]),+ );+ page.sessions.forEach((session) => {+ if (state.deletedSessions.has(session.id)) return;+ const current = reduceSessionSummary(session);+ if (current && matchesLibraryQuery(current)) merged.set(current.id, current);+ });+ state.libraryItems = [...merged.values()].filter(matchesLibraryQuery);+ sortLibraryItems();state.libraryCursor = page.next_cursor;renderLibraryItems();} catch (error) {@@ -255,6 +953,16 @@const preview = node("p", "", session.preview || "No messages yet");const meta = node("span", "", `${session.model} · ${relativeTime(session.updated_at)}`);item.append(heading, preview, meta);+ const active = state.activeOperations.get(session.id);+ if (active) {+ item.appendChild(+ node(+ "span",+ "chat-session-status",+ active.action === "compact" ? "Compacting…" : "Thinking…",+ ),+ );+ }list.appendChild(item);});const more = document.getElementById("chatLoadMore");@@ -265,6 +973,7 @@}async function createSession() {+ if (!mutationsReady()) return;setNotice("Creating chat…");try {const session = await state.api("/admin/api/chat/sessions", {@@ -282,17 +991,33 @@route(window.location.pathname);}- async function showSession(id, version) {+ async function showSession(id, version, freshnessRetry = false) {if (!state.bootstrap?.available) {renderUnavailable();return;}- renderLoading();+ const refreshingVisibleSession =+ state.session?.id === id && Boolean(document.getElementById("chatTranscript"));+ if (!refreshingVisibleSession) renderLoading();try {const detail = await state.api(`/admin/api/chat/sessions/${id}`);if (version !== state.routeVersion) return;- applyDetail(detail);- renderSession();+ const titleEdit = refreshingVisibleSession ? captureTitleEdit() : null;+ const composerSelection = refreshingVisibleSession+ ? captureComposerSelection()+ : null;+ if (!applyDetail(detail)) {+ if (!freshnessRetry && !state.deletedSessions.has(id)) {+ await showSession(id, version, true);+ }+ return;+ }+ if (refreshingVisibleSession) {+ renderSessionPreservingScroll(titleEdit);+ restoreComposerSelection(composerSelection);+ } else {+ renderSession();+ }} catch (error) {if (version !== state.routeVersion) return;const empty = node("section", "chat-empty");@@ -306,31 +1031,43 @@}function applyDetail(detail) {- invalidateEstimate();- if (state.draftSessionId !== detail.session.id) {- state.draft = "";- state.draftSessionId = detail.session.id;- state.draftOperationId = null;- } else if (- state.draftOperationId &&- detail.turns.some((turn) => turn.operation_id === state.draftOperationId)+ const sessionId = detail.session.id;+ const knownRevision = state.sessionRevisions.get(sessionId) || 0;+ if (+ state.deletedSessions.has(sessionId) ||+ detail.session.revision < knownRevision ||+ (state.session?.id === sessionId &&+ detail.session.revision < state.session.revision)) {- state.draft = "";- state.draftOperationId = null;+ return false;}+ state.sessionRevisions.set(sessionId, detail.session.revision);+ invalidateEstimate();+ if (state.draftSessionId !== sessionId) {+ loadDraft(sessionId);+ }+ const pendingTurn =+ state.draftOperationId &&+ detail.turns.find((turn) => turn.operation_id === state.draftOperationId);+ if (pendingTurn) confirmSubmittedDraft(state.draftOperationId);state.session = detail.session;state.turns = detail.turns;state.nextBefore = detail.next_before;state.compaction = detail.compaction;state.context = detail.context;state.contextError = detail.context_error || "";- state.serverOperationActive = Boolean(detail.active_operation);+ selectVisibleOperation();if (state.draft && !state.operation) scheduleEstimate(true);+ return true;}function renderSession({ followLatest = true, scrollTop = 0 } = {}) {const session = state.session;if (!session) return;+ const previousTitle = document.querySelector(".chat-title");+ if (previousTitle instanceof HTMLInputElement) {+ state.retiredTitleInputs.add(previousTitle);+ }state.modelComboboxes.clear();const shell = node("div", "chat-session-shell");const header = renderSessionHeader(session);@@ -350,15 +1087,15 @@} else {scroller.scrollTop = scrollTop;}- syncForeignOperationPoll();}- function renderSessionPreservingScroll() {+ function renderSessionPreservingScroll(titleEdit = captureTitleEdit()) {const scroller = document.getElementById("chatTranscript");renderSession({followLatest: !scroller || nearBottom(scroller),scrollTop: scroller?.scrollTop || 0,});+ restoreTitleEdit(titleEdit);}function renderSessionHeader(session) {@@ -369,7 +1106,14 @@title.value = session.title;title.maxLength = 200;title.setAttribute("aria-label", "Chat title");- title.addEventListener("change", () => updateSession({ title: title.value }));+ title.addEventListener("blur", () => {+ if (+ title.isConnected &&+ !state.retiredTitleInputs.has(title) &&+ title.value !== state.session?.title+ )+ void updateSession({ title: title.value });+ });title.addEventListener("keydown", (event) => {if (event.key === "Enter") title.blur();});@@ -478,6 +1222,8 @@textarea.addEventListener("input", () => {state.draft = textarea.value;state.draftOperationId = null;+ state.draftSubmittedText = "";+ saveDraft();refreshComposerState();scheduleEstimate();});@@ -532,9 +1278,36 @@textarea.setSelectionRange(start, end, selection.direction);}+ function captureTitleEdit() {+ const input = document.querySelector(".chat-title");+ if (+ !(input instanceof HTMLInputElement) ||+ document.activeElement !== input ||+ input.value === state.session?.title+ )+ return null;+ return {+ value: input.value,+ start: input.selectionStart,+ end: input.selectionEnd,+ direction: input.selectionDirection,+ };+ }++ function restoreTitleEdit(edit) {+ const input = document.querySelector(".chat-title");+ if (!(input instanceof HTMLInputElement) || !edit) return;+ input.value = edit.value;+ input.focus({ preventScroll: true });+ const start = Math.min(edit.start ?? edit.value.length, edit.value.length);+ const end = Math.min(edit.end ?? edit.value.length, edit.value.length);+ input.setSelectionRange(start, end, edit.direction || "none");+ }+function renderTranscript() {const scroller = document.getElementById("chatTranscript");if (!scroller) return;+ if (state.operation) commitPendingDeltas(state.operation);scroller.replaceChildren();if (state.nextBefore) {scroller.appendChild(@@ -551,8 +1324,10 @@state.turns.forEach((turn, index) => {scroller.appendChild(renderUserMessage(turn));const replacingLatest =- index === state.turns.length - 1 &&- ["retry", "regenerate"].includes(state.operation?.action);+ turn.id === state.operation?.turnId ||+ (index === state.turns.length - 1 &&+ !state.operation?.turnId &&+ ["retry", "regenerate"].includes(state.operation?.action));if (!replacingLatest) scroller.appendChild(renderAssistantMessage(turn));if (state.compaction &&@@ -562,7 +1337,14 @@dividerRendered = true;}});- if (state.operation?.action === "send" && state.operation.userText) {+ const operationHasTurn = state.turns.some(+ (turn) => turn.operation_id === state.operation?.id,+ );+ if (+ state.operation?.action === "send" &&+ state.operation.userText &&+ !operationHasTurn+ ) {const pending = node("article", "chat-message user-message");pending.append(node("div", "chat-message-label", "You"),@@ -723,7 +1505,7 @@}async function updateSession(changes) {- if (!state.session) return;+ if (!state.session || !mutationsReady()) return;if (state.operation && (changes.model || changes.reasoning)) return;const sessionId = state.session.id;const expectedRevision = state.session.revision;@@ -742,10 +1524,12 @@if (routeVersion !== state.routeVersion ||state.session?.id !== sessionId ||- state.session.revision !== expectedRevision+ state.session.revision !== expectedRevision ||+ state.deletedSessions.has(sessionId))return;state.session = session;+ state.sessionRevisions.set(session.id, session.revision);renderSessionPreservingScroll();scheduleEstimate(true);} catch (error) {@@ -757,7 +1541,7 @@}async function deleteSession() {- if (!state.session) return;+ if (!state.session || !mutationsReady()) return;if (!window.confirm(`Permanently delete “${state.session.title}”?`)) return;const sessionId = state.session.id;try {@@ -765,7 +1549,6 @@method: "DELETE",body: JSON.stringify({ expected_revision: state.session.revision }),});- state.eventChannel?.postMessage({ type: "session.deleted", sessionId });goLibrary();} catch (error) {setNotice(error.message, "error");@@ -773,27 +1556,13 @@}function goLibrary() {- cancelLocalStream();+ detachVisibleOperation();window.history.pushState({}, "", "/admin/chat");route(window.location.pathname);}- function handleCrossTabEvent(event) {- const message = event.data;- if (- !message ||- message.type !== "session.deleted" ||- typeof message.sessionId !== "string" ||- (state.session?.id !== message.sessionId &&- routedSessionId(window.location.pathname) !== message.sessionId)- )- return;- cancelLocalStream();- window.history.replaceState({}, "", "/admin/chat");- route(window.location.pathname);- }-function editSystemPrompt() {+ if (!mutationsReady()) return;const current = state.bootstrap.preferences?.system_prompt || "";const dialog = document.createElement("dialog");dialog.className = "chat-prompt-dialog";@@ -915,14 +1684,10 @@function sendBlockReason() {if (!state.session) return "Chat unavailable";+ if (!mutationsReady()) return "Reconnecting…";if (state.operation) return "A chat operation is already running";const latest = state.turns[state.turns.length - 1];- if (- state.serverOperationActive ||- latest?.generation?.status === "running"- ) {- return "This chat is running in another tab";- }+ if (latest?.generation?.status === "running") return "This chat is running";const option = modelOption(state.session.model);if (!option) return "Choose an available model";if (option.supports_reasoning === false && state.session.reasoning !== "off") {@@ -951,9 +1716,7 @@const blocked = sendBlockReason();const latest = state.turns[state.turns.length - 1];const busy = Boolean(- state.operation ||- state.serverOperationActive ||- latest?.generation?.status === "running",+ state.operation || latest?.generation?.status === "running",);send.disabled = Boolean(blocked) || !textarea.value.trim();send.hidden = Boolean(state.operation);@@ -970,7 +1733,12 @@".chat-controls button, .chat-controls input, .chat-controls select",).forEach((control) => {- control.disabled = busy;+ control.disabled = busy || !mutationsReady();+ });+ document+ .querySelectorAll(".chat-header-row .danger-button, .chat-title")+ .forEach((control) => {+ control.disabled = !mutationsReady();});if (compact) {compact.disabled = busy || !state.context?.can_compact;@@ -997,194 +1765,64 @@}async function runOperation(action, extra) {- if (!state.session || state.operation) return;+ if (!state.session || state.operation || !mutationsReady()) return;invalidateEstimate();- let failure = null;const activeElementId = document.activeElement?.id;- const operation = {+ const operation = createOperation({id: crypto.randomUUID(),sessionId: state.session.id,action,- controller: new AbortController(),- segments: [],- sequence: 0,- status: action === "compact" ? "Compacting…" : "Thinking…",+ phase: action === "compact" ? "compacting" : "generating",userText: extra.text || "",- accepted: false,- failureMessage: "",- renderFrame: null,returnFocusToComposer:action === "send" &&(activeElementId === "chatComposer" || activeElementId === "chatSend"),- };+ commandPending: true,+ });if (action === "send") {state.draftOperationId = operation.id;+ state.draftSubmittedText = operation.userText;+ saveDraft();}+ state.pendingCommands.set(operation.sessionId, operation);state.operation = operation;renderSessionPreservingScroll();try {- const response = await fetch(+ const acknowledgement = await state.api(`/admin/api/chat/sessions/${operation.sessionId}/${action}`,{method: "POST",- headers: { "Content-Type": "application/json" },body: JSON.stringify({expected_revision: state.session.revision,operation_id: operation.id,...extra,}),- cache: "no-store",- signal: operation.controller.signal,},);- if (!response.ok) throw await responseError(response);- if (!response.body) throw new Error("The browser could not open the chat stream.");- await consumeEvents(response.body, operation);- if (operation.failureMessage) {- failure = new Error(operation.failureMessage);- }- } catch (error) {- if (action === "send" && !operation.accepted) {- state.draft = operation.userText;- state.draftSessionId = operation.sessionId;- state.draftOperationId = operation.id;- }- if (error.name !== "AbortError") failure = error;- } finally {- cancelOperationRender(operation);- const composerSelection =- captureComposerSelection() ||- (operation.returnFocusToComposer && composerFocusIsUnclaimed()- ? {- start: state.draft.length,- end: state.draft.length,- direction: "none",- }- : null);- if (state.operation === operation) state.operation = null;- if (state.session?.id === operation.sessionId) await reloadSession();- restoreComposerSelection(composerSelection);- const persistedFailure = state.turns[state.turns.length - 1]?.generation;- const failureIsInline =- operation.failureMessage &&- persistedFailure?.status === "failed" &&- persistedFailure.error_message === operation.failureMessage;- if (failure && !failureIsInline) setNotice(failure.message, "error");- }- }-- async function consumeEvents(body, operation) {- const reader = body.getReader();- const decoder = new TextDecoder();- const frameParts = [];- let boundaryTail = "";- try {- while (true) {- const { done, value } = await reader.read();- const chunk = decoder.decode(value || new Uint8Array(), { stream: !done });- const probe = boundaryTail + chunk;- const boundary = /\r?\n\r?\n/g;- const prefixLength = boundaryTail.length;- let chunkStart = 0;- for (const match of probe.matchAll(boundary)) {- const chunkEnd = match.index + match[0].length - prefixLength;- frameParts.push(chunk.slice(chunkStart, chunkEnd));- applyStreamFrame(frameParts.join(""), operation);- frameParts.length = 0;- chunkStart = chunkEnd;- }- const remainder = chunk.slice(chunkStart);- if (remainder) frameParts.push(remainder);- boundaryTail = chunkStart- ? remainder.slice(-3)- : (boundaryTail + chunk).slice(-3);- if (done) {- const finalFrame = frameParts.join("");- if (finalFrame.trim()) applyStreamFrame(finalFrame, operation);- return;- }- }- } finally {- reader.releaseLock();- }- }-- function applyStreamFrame(frame, operation) {- if (state.operation !== operation) return;- let event = "message";- let sequence = 0;- let payload = null;- frame.split(/\r?\n/).forEach((line) => {- if (line.startsWith("event:")) event = line.slice(6).trim();- if (line.startsWith("id:")) sequence = Number.parseInt(line.slice(3), 10);- if (line.startsWith("data:")) payload = JSON.parse(line.slice(5).trim());- });- if (!payload || payload.operation_id !== operation.id) return;- if (!Number.isFinite(sequence) || sequence <= operation.sequence) return;- if (- state.session?.id === operation.sessionId &&- Number.isInteger(payload.revision)- ) {- state.session.revision = payload.revision;- }- let liveDelta = false;- let restoreComposerFocus = false;- if (event === "turn.started") {- operation.accepted = true;if (- operation.action === "send" &&- state.draftOperationId === operation.id+ acknowledgement.session_id !== operation.sessionId ||+ acknowledgement.operation_id !== operation.id ||+ acknowledgement.kind !== action) {- state.draft = "";- state.draftSessionId = operation.sessionId;- state.draftOperationId = null;- const textarea = document.getElementById("chatComposer");- if (textarea) textarea.value = "";+ throw new Error("The server returned an invalid operation acknowledgement.");}- restoreComposerFocus =- operation.returnFocusToComposer && composerFocusIsUnclaimed();- } else if (event === "segment.started") {- operation.segments[payload.ordinal] = {- kind: payload.kind,- text: "",- pending: [],- };- } else if (event === "segment.delta") {- const segment = operation.segments[payload.ordinal];- if (segment) {- segment.pending.push(payload.delta);- liveDelta = true;+ operation.commandPending = false;+ operation.serverObserved = true;+ } catch (error) {+ operation.commandPending = false;+ const active = state.activeOperations.get(operation.sessionId);+ const pending = state.pendingCommands.get(operation.sessionId);+ if (+ active?.id === operation.id ||+ (pending !== operation && operation.serverObserved)+ )+ return;+ if (error.status) {+ rejectCommand(operation, error.message);+ return;}- } else if (event === "compaction.completed") {- operation.status = "Compacted";- } else if (event === "compaction.failed") {- operation.failureMessage = payload.message || "Compaction failed";- operation.status = operation.failureMessage;- } else if (event === "compaction.stopped") {- operation.status = "Stopped";- } else if (event === "turn.failed") {- operation.failureMessage = payload.message || "Generation failed";- operation.status = operation.failureMessage;- } else if (event === "turn.stopped") {- operation.status = "Stopped";- }- operation.sequence = sequence;- if (liveDelta) {- scheduleLiveRender(operation);- return;- }- renderOperationStructure(operation);- if (restoreComposerFocus) {- const textarea = document.getElementById("chatComposer");- restoreComposerSelection(- textarea- ? {- start: textarea.value.length,- end: textarea.value.length,- direction: "none",- }- : null,- );+ operation.ambiguousError = error.message;+ reconcileAmbiguousCommand(operation);}}@@ -1244,33 +1882,33 @@operation.status = "Stopping…";renderOperationStructure(operation);try {- await state.api(`/admin/api/chat/sessions/${operation.sessionId}/stop`, {- method: "POST",- body: JSON.stringify({ operation_id: operation.id }),- });+ const result = await state.api(+ `/admin/api/chat/sessions/${operation.sessionId}/stop`,+ {+ method: "POST",+ body: JSON.stringify({ operation_id: operation.id }),+ },+ );+ if (!result.stopped) restartEventFeed();} catch (error) {setNotice(error.message, "error");}}- function cancelLocalStream() {- if (!state.operation) return;- cancelOperationRender(state.operation);- state.operation.controller.abort();- state.operation = null;- }-async function reloadSession() {const id = state.session?.id;if (!id) return;+ const selection = captureComposerSelection();try {const detail = await state.api(`/admin/api/chat/sessions/${id}`);if (state.session?.id !== id) return;- applyDetail(detail);- renderSessionPreservingScroll();+ const titleEdit = captureTitleEdit();+ if (!applyDetail(detail)) return;+ renderSessionPreservingScroll(titleEdit);+ restoreComposerSelection(selection);} catch (error) {if (error.status === 404 && state.session?.id === id) {- cancelLocalStream();+ detachVisibleOperation();window.history.replaceState({}, "", "/admin/chat");await route(window.location.pathname);return;@@ -1279,42 +1917,6 @@}}- function stopForeignOperationPoll() {- window.clearTimeout(state.foreignPollTimer);- state.foreignPollTimer = null;- }-- function syncForeignOperationPoll() {- stopForeignOperationPoll();- const latest = state.turns[state.turns.length - 1];- const chatView = root()?.closest(".admin-view");- if (- !state.session ||- state.operation ||- (!state.serverOperationActive &&- latest?.generation?.status !== "running") ||- chatView?.hidden- ) {- return;- }- const sessionId = state.session.id;- state.foreignPollTimer = window.setTimeout(async () => {- state.foreignPollTimer = null;- if (state.session?.id !== sessionId || state.operation) return;- await reloadSession();- syncForeignOperationPoll();- }, 750);- }-- async function responseError(response) {- try {- const payload = await response.json();- return new Error(payload.detail || `${response.status} ${response.statusText}`);- } catch {- return new Error(`${response.status} ${response.statusText}`);- }- }-function nearBottom(scroller) {return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80;}@@ -1349,6 +1951,17 @@window.ChatSessions = { initialize, activate, refresh };+ window.addEventListener("offline", () => {+ if (!state.initialized) return;+ state.feedSyncVersion += 1;+ state.feedStatus = "reconnecting";+ refreshFeedState();+ });++ window.addEventListener("online", () => {+ if (state.initialized && state.feedStatus !== "live") restartEventFeed();+ });+document.addEventListener("pointerdown", (event) => {state.modelComboboxes.forEach((combobox) => {if (combobox.isOpen && !combobox.element.contains(event.target)) {diff --git a/src/free_claude_code/api/chat_routes.py b/src/free_claude_code/api/chat_routes.pyindex 899fbdad..0e3e67a0 100644--- a/src/free_claude_code/api/chat_routes.py+++ b/src/free_claude_code/api/chat_routes.py@@ -1,24 +1,26 @@"""Loopback-only HTTP adapter for local Chat Sessions."""import base64-import jsonimport uuidfrom collections.abc import AsyncIteratorfrom fastapi import APIRouter, Depends, Query, Request+from fastapi.sse import EventSourceResponse, ServerSentEventfrom pydantic import BaseModel, Fieldfrom free_claude_code.application.chat import (+ ChatActiveOperation,ChatApplicationPort,ChatCompaction,ChatContextEstimate,+ ChatEventOverflowError,ChatModelOption,- ChatOperationStream,+ ChatOperationAcknowledgement,ChatPreferences,+ ChatPublishedEvent,ChatReasoning,ChatSession,ChatSessionSummary,- ChatStreamEvent,ChatTurn,ChatUnavailableError,ChatValidationError,@@ -30,7 +32,6 @@ from .admin_security import require_loopback_adminfrom .chat_markdown import render_chat_markdownfrom .dependencies import get_servicesfrom .ports import ApiServices-from .response_streams import ManagedStreamingResponserouter = APIRouter()@@ -93,6 +94,38 @@ async def chat_bootstrap(return payload[email protected]("/admin/api/chat/events", response_class=EventSourceResponse)+async def chat_events(+ request: Request,+ services: ApiServices = Depends(get_services),+) -> AsyncIterator[ServerSentEvent]:+ require_loopback_admin(request)+ subscription, active_operations = await _chat(services).subscribe()+ try:+ yield ServerSentEvent(+ event="feed.ready",+ id=str(subscription.cursor),+ retry=1_000,+ data={+ "cursor": subscription.cursor,+ "active_operations": [+ _active_operation_payload(active) for active in active_operations+ ],+ },+ )+ try:+ async for event in subscription:+ yield _sse_event(event)+ except ChatEventOverflowError as exc:+ yield ServerSentEvent(+ event="feed.resync_required",+ id=str(exc.cursor),+ data={"cursor": exc.cursor},+ )+ finally:+ await subscription.aclose()++@router.get("/admin/api/chat/sessions")async def list_chat_sessions(request: Request,@@ -139,7 +172,6 @@ async def get_chat_session(_estimate_payload(detail.context) if detail.context is not None else None),"context_error": detail.context_error,- "active_operation": detail.active_operation,}@@ -211,7 +243,7 @@ async def estimate_chat_context(return _estimate_payload(estimate)[email protected]("/admin/api/chat/sessions/{session_id}/send")[email protected]("/admin/api/chat/sessions/{session_id}/send", status_code=202)async def send_chat_message(session_id: str,payload: ChatSendPayload,@@ -219,16 +251,16 @@ async def send_chat_message(services: ApiServices = Depends(get_services),):require_loopback_admin(request)- stream = await _chat(services).send(+ acknowledgement = await _chat(services).send(session_id,expected_revision=payload.expected_revision,operation_id=payload.operation_id,text=payload.text,)- return _stream_response(stream)+ return _operation_acknowledgement_payload(acknowledgement)[email protected]("/admin/api/chat/sessions/{session_id}/retry")[email protected]("/admin/api/chat/sessions/{session_id}/retry", status_code=202)async def retry_chat_message(session_id: str,payload: ChatOperationPayload,@@ -236,15 +268,15 @@ async def retry_chat_message(services: ApiServices = Depends(get_services),):require_loopback_admin(request)- stream = await _chat(services).retry(+ acknowledgement = await _chat(services).retry(session_id,expected_revision=payload.expected_revision,operation_id=payload.operation_id,)- return _stream_response(stream)+ return _operation_acknowledgement_payload(acknowledgement)[email protected]("/admin/api/chat/sessions/{session_id}/regenerate")[email protected]("/admin/api/chat/sessions/{session_id}/regenerate", status_code=202)async def regenerate_chat_message(session_id: str,payload: ChatOperationPayload,@@ -252,15 +284,15 @@ async def regenerate_chat_message(services: ApiServices = Depends(get_services),):require_loopback_admin(request)- stream = await _chat(services).regenerate(+ acknowledgement = await _chat(services).regenerate(session_id,expected_revision=payload.expected_revision,operation_id=payload.operation_id,)- return _stream_response(stream)+ return _operation_acknowledgement_payload(acknowledgement)[email protected]("/admin/api/chat/sessions/{session_id}/compact")[email protected]("/admin/api/chat/sessions/{session_id}/compact", status_code=202)async def compact_chat_session(session_id: str,payload: ChatOperationPayload,@@ -268,12 +300,12 @@ async def compact_chat_session(services: ApiServices = Depends(get_services),):require_loopback_admin(request)- stream = await _chat(services).compact(+ acknowledgement = await _chat(services).compact(session_id,expected_revision=payload.expected_revision,operation_id=payload.operation_id,)- return _stream_response(stream)+ return _operation_acknowledgement_payload(acknowledgement)@router.post("/admin/api/chat/sessions/{session_id}/stop")@@ -325,32 +357,22 @@ def _chat(services: ApiServices) -> ChatApplicationPort:return services.chat-def _stream_response(stream: ChatOperationStream) -> ManagedStreamingResponse:- response = ManagedStreamingResponse(- _stream_events(stream),- media_type="text/event-stream",- headers={- "Cache-Control": "no-store",- "Connection": "keep-alive",- "X-Accel-Buffering": "no",- "X-Content-Type-Options": "nosniff",- },+def _sse_event(event: ChatPublishedEvent) -> ServerSentEvent:+ return ServerSentEvent(+ event=event.event,+ id=str(event.id),+ data=event.data,)- response.bind_release(stream.aclose)- return response-async def _stream_events(stream: ChatOperationStream) -> AsyncIterator[str]:- try:- async for event in stream:- yield _sse_event(event)- finally:- await stream.aclose()---def _sse_event(event: ChatStreamEvent) -> str:- data = json.dumps(event.data, ensure_ascii=False, separators=(",", ":"))- return f"id: {event.sequence}\nevent: {event.event}\ndata: {data}\n\n"+def _operation_acknowledgement_payload(+ acknowledgement: ChatOperationAcknowledgement,+) -> JsonObject:+ return {+ "session_id": acknowledgement.session_id,+ "operation_id": acknowledgement.operation_id,+ "kind": acknowledgement.kind.value,+ }def _encode_cursor(cursor: tuple[int, str] | None) -> str | None:@@ -437,6 +459,33 @@ def _session_summary_payload(session: ChatSessionSummary) -> JsonObject:}+def _active_operation_payload(+ active: ChatActiveOperation | None,+) -> JsonObject | None:+ if active is None:+ return None+ return {+ "session_id": active.session_id,+ "operation_id": active.operation_id,+ "kind": active.kind.value,+ "phase": active.phase.value,+ "operation_sequence": active.operation_sequence,+ "submitted_text": active.submitted_text,+ "turn_id": active.turn_id,+ "generation_id": active.generation_id,+ "regeneration": active.regeneration,+ "actual_model": active.actual_model,+ "segments": [+ {+ "ordinal": segment.ordinal,+ "kind": segment.kind.value,+ "text": segment.text,+ }+ for segment in active.segments+ ],+ }++def _turn_payload(turn: ChatTurn) -> JsonObject:generation = turn.generationreturn {diff --git a/src/free_claude_code/api/request_lifetime.py b/src/free_claude_code/api/request_lifetime.pyindex a2dc4b42..91771a6a 100644--- a/src/free_claude_code/api/request_lifetime.py+++ b/src/free_claude_code/api/request_lifetime.py@@ -5,7 +5,6 @@ import asynciofrom starlette.types import ASGIApp, Message, Receive, Scope, Send_INFERENCE_PATHS = frozenset({"/v1/messages", "/v1/responses"})-_CHAT_STREAM_ACTIONS = frozenset({"send", "retry", "regenerate", "compact"})class InferenceRequestLifetimeMiddleware:@@ -82,19 +81,7 @@ def _owns_inference_lifetime(scope: Scope) -> bool:return (scope["type"] == "http"and scope.get("method") == "POST"- and (path in _INFERENCE_PATHS or _is_chat_stream_path(path))- )---def _is_chat_stream_path(path: object) -> bool:- if not isinstance(path, str):- return False- parts = path.split("/")- return (- len(parts) == 7- and parts[1:5] == ["admin", "api", "chat", "sessions"]- and bool(parts[5])- and parts[6] in _CHAT_STREAM_ACTIONS+ and path in _INFERENCE_PATHS)diff --git a/src/free_claude_code/application/chat/__init__.py b/src/free_claude_code/application/chat/__init__.pyindex 2f294206..184ef44f 100644--- a/src/free_claude_code/application/chat/__init__.py+++ b/src/free_claude_code/application/chat/__init__.py@@ -2,21 +2,26 @@from .models import (DEFAULT_CHAT_SYSTEM_PROMPT,+ ChatActiveOperation,ChatCompaction,ChatConflictError,ChatContextEstimate,ChatError,+ ChatEventOverflowError,ChatGeneration,ChatModelOption,ChatNotFoundError,+ ChatOperationAcknowledgement,+ ChatOperationKind,+ ChatOperationPhase,ChatPreferences,+ ChatPublishedEvent,ChatReasoning,ChatSegment,ChatSession,ChatSessionDetail,ChatSessionPage,ChatSessionSummary,- ChatStreamEvent,ChatTranscript,ChatTurn,ChatUnavailableError,@@ -24,21 +29,27 @@ from .models import (GenerationStatus,SegmentKind,)-from .ports import ChatApplicationPort, ChatOperationStream, ChatStorePort+from .ports import ChatApplicationPort, ChatEventSubscriptionPort, ChatStorePortfrom .service import ChatService__all__ = ["DEFAULT_CHAT_SYSTEM_PROMPT",+ "ChatActiveOperation","ChatApplicationPort","ChatCompaction","ChatConflictError","ChatContextEstimate","ChatError",+ "ChatEventOverflowError",+ "ChatEventSubscriptionPort","ChatGeneration","ChatModelOption","ChatNotFoundError",- "ChatOperationStream",+ "ChatOperationAcknowledgement",+ "ChatOperationKind",+ "ChatOperationPhase","ChatPreferences",+ "ChatPublishedEvent","ChatReasoning","ChatSegment","ChatService",@@ -47,7 +58,6 @@ __all__ = ["ChatSessionPage","ChatSessionSummary","ChatStorePort",- "ChatStreamEvent","ChatTranscript","ChatTurn","ChatUnavailableError",diff --git a/src/free_claude_code/application/chat/events.py b/src/free_claude_code/application/chat/events.pynew file mode 100644index 00000000..c2c5c27c--- /dev/null+++ b/src/free_claude_code/application/chat/events.py@@ -0,0 +1,117 @@+"""Bounded in-process fan-out for observable Chat state changes."""++import asyncio+from collections.abc import AsyncIterator++from free_claude_code.core.json_types import JsonObject++from .models import ChatEventOverflowError, ChatPublishedEvent++_DEFAULT_QUEUE_SIZE = 128+++class _Closed:+ pass+++_CLOSED = _Closed()+++class _Overflow:+ def __init__(self, cursor: int) -> None:+ self.cursor = cursor+++type _QueueItem = ChatPublishedEvent | _Overflow | _Closed+++class ChatEventSubscription:+ """One observer's independent view of the process-local Chat feed."""++ def __init__(+ self,+ publisher: ChatEventPublisher,+ *,+ cursor: int,+ queue_size: int,+ ) -> None:+ self._publisher = publisher+ self._queue: asyncio.Queue[_QueueItem] = asyncio.Queue(maxsize=queue_size)+ self.cursor = cursor+ self._closed = False++ def __aiter__(self) -> AsyncIterator[ChatPublishedEvent]:+ return self._events()++ async def _events(self) -> AsyncIterator[ChatPublishedEvent]:+ while True:+ item = await self._queue.get()+ if item is _CLOSED:+ return+ if isinstance(item, _Overflow):+ raise ChatEventOverflowError(item.cursor)+ if isinstance(item, ChatPublishedEvent):+ yield item++ async def aclose(self) -> None:+ if self._closed:+ return+ self._closed = True+ self._publisher.unsubscribe(self)+ self.signal(_CLOSED)++ def signal(self, item: _QueueItem) -> None:+ while True:+ try:+ self._queue.get_nowait()+ except asyncio.QueueEmpty:+ break+ self._queue.put_nowait(item)+++class ChatEventPublisher:+ """Publish without allowing one observer to backpressure Chat work."""++ def __init__(self, *, queue_size: int = _DEFAULT_QUEUE_SIZE) -> None:+ if queue_size <= 0:+ raise ValueError("Chat event queue size must be positive.")+ self._queue_size = queue_size+ self._sequence = 0+ self._subscriptions: set[ChatEventSubscription] = set()+ self._closed = False++ def subscribe(self) -> ChatEventSubscription:+ if self._closed:+ raise RuntimeError("Chat event publisher is closed.")+ subscription = ChatEventSubscription(+ self,+ cursor=self._sequence,+ queue_size=self._queue_size,+ )+ self._subscriptions.add(subscription)+ return subscription++ def publish(self, event: str, data: JsonObject) -> ChatPublishedEvent:+ if self._closed:+ raise RuntimeError("Chat event publisher is closed.")+ self._sequence += 1+ published = ChatPublishedEvent(event=event, id=self._sequence, data={**data})+ for subscription in tuple(self._subscriptions):+ try:+ subscription._queue.put_nowait(published)+ except asyncio.QueueFull:+ self._subscriptions.discard(subscription)+ subscription.signal(_Overflow(self._sequence))+ return published++ def unsubscribe(self, subscription: ChatEventSubscription) -> None:+ self._subscriptions.discard(subscription)++ def close(self) -> None:+ if self._closed:+ return+ self._closed = True+ subscriptions = tuple(self._subscriptions)+ self._subscriptions.clear()+ for subscription in subscriptions:+ subscription.signal(_CLOSED)diff --git a/src/free_claude_code/application/chat/models.py b/src/free_claude_code/application/chat/models.pyindex 670a7ed0..b4ea5af9 100644--- a/src/free_claude_code/application/chat/models.py+++ b/src/free_claude_code/application/chat/models.py@@ -48,6 +48,22 @@ class SegmentKind(StrEnum):TEXT = "text"+class ChatOperationKind(StrEnum):+ """Long-running Chat commands owned by the application."""++ SEND = "send"+ RETRY = "retry"+ REGENERATE = "regenerate"+ COMPACT = "compact"+++class ChatOperationPhase(StrEnum):+ """Current work phase exposed to Chat observers."""++ GENERATING = "generating"+ COMPACTING = "compacting"++@dataclass(frozen=True, slots=True)class ChatPreferences:system_prompt: str@@ -159,6 +175,28 @@ class ChatContextEstimate:can_compact: bool+@dataclass(frozen=True, slots=True)+class ChatOperationAcknowledgement:+ session_id: str+ operation_id: str+ kind: ChatOperationKind+++@dataclass(frozen=True, slots=True)+class ChatActiveOperation:+ session_id: str+ operation_id: str+ kind: ChatOperationKind+ phase: ChatOperationPhase+ operation_sequence: int+ submitted_text: str | None+ turn_id: str | None+ generation_id: str | None+ regeneration: bool+ actual_model: str | None+ segments: tuple[ChatSegment, ...]++@dataclass(frozen=True, slots=True)class ChatSessionDetail:session: ChatSession@@ -167,13 +205,12 @@ class ChatSessionDetail:compaction: ChatCompaction | Nonecontext: ChatContextEstimate | Nonecontext_error: str | None- active_operation: bool@dataclass(frozen=True, slots=True)-class ChatStreamEvent:+class ChatPublishedEvent:event: str- sequence: int+ id: intdata: JsonObject@@ -195,3 +232,11 @@ class ChatConflictError(ChatError):class ChatValidationError(ChatError):"""The requested Chat operation cannot be executed as supplied."""+++class ChatEventOverflowError(ChatError):+ """One slow Chat observer must reconnect from a fresh snapshot."""++ def __init__(self, cursor: int) -> None:+ super().__init__("Chat event subscription overflowed.")+ self.cursor = cursordiff --git a/src/free_claude_code/application/chat/ports.py b/src/free_claude_code/application/chat/ports.pyindex c8a8e0aa..b5777732 100644--- a/src/free_claude_code/application/chat/ports.py+++ b/src/free_claude_code/application/chat/ports.py@@ -4,17 +4,20 @@ from collections.abc import AsyncIteratorfrom typing import Protocolfrom .models import (+ ChatActiveOperation,ChatCompaction,ChatContextEstimate,ChatGeneration,ChatModelOption,+ ChatOperationAcknowledgement,ChatPreferences,+ ChatPublishedEvent,ChatReasoning,ChatSegment,ChatSession,ChatSessionDetail,ChatSessionPage,- ChatStreamEvent,+ ChatSessionSummary,ChatTranscript,ChatTurn,GenerationStatus,@@ -44,6 +47,8 @@ class ChatStorePort(Protocol):limit: int,) -> ChatSessionPage: ...+ async def get_session_summary(self, session_id: str) -> ChatSessionSummary: ...+async def get_session(self, session_id: str) -> ChatSession: ...async def update_session(@@ -155,12 +160,12 @@ class ChatStorePort(Protocol):) -> ChatCompaction: ...-class ChatOperationStream(Protocol):- """One initiating browser's event stream and cancellation boundary."""+class ChatEventSubscriptionPort(Protocol):+ """Read-only process-local Chat event subscription."""- operation_id: str+ cursor: int- def __aiter__(self) -> AsyncIterator[ChatStreamEvent]: ...+ def __aiter__(self) -> AsyncIterator[ChatPublishedEvent]: ...async def aclose(self) -> None: ...@@ -172,6 +177,10 @@ class ChatApplicationPort(Protocol):def models(self) -> tuple[ChatModelOption, ...]: ...+ async def subscribe(+ self,+ ) -> tuple[ChatEventSubscriptionPort, tuple[ChatActiveOperation, ...]]: ...+async def preferences(self) -> ChatPreferences: ...async def save_system_prompt(self, value: str) -> ChatPreferences: ...@@ -223,7 +232,7 @@ class ChatApplicationPort(Protocol):expected_revision: int,operation_id: str,text: str,- ) -> ChatOperationStream: ...+ ) -> ChatOperationAcknowledgement: ...async def retry(self,@@ -231,7 +240,7 @@ class ChatApplicationPort(Protocol):*,expected_revision: int,operation_id: str,- ) -> ChatOperationStream: ...+ ) -> ChatOperationAcknowledgement: ...async def regenerate(self,@@ -239,7 +248,7 @@ class ChatApplicationPort(Protocol):*,expected_revision: int,operation_id: str,- ) -> ChatOperationStream: ...+ ) -> ChatOperationAcknowledgement: ...async def compact(self,@@ -247,6 +256,6 @@ class ChatApplicationPort(Protocol):*,expected_revision: int,operation_id: str,- ) -> ChatOperationStream: ...+ ) -> ChatOperationAcknowledgement: ...async def stop(self, session_id: str, *, operation_id: str) -> bool: ...diff --git a/src/free_claude_code/application/chat/service.py b/src/free_claude_code/application/chat/service.pyindex 96fae374..867433b1 100644--- a/src/free_claude_code/application/chat/service.py+++ b/src/free_claude_code/application/chat/service.py@@ -1,11 +1,10 @@"""Application lifecycle and commands for durable local Chat Sessions."""import asyncio-import contextlibimport sysimport timeimport uuid-from collections.abc import AsyncIterator, Awaitable, Callable+from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, field, replacefrom enum import StrEnum@@ -30,19 +29,24 @@ from .context import (PreparedChatRequest,compaction_target_tokens,)+from .events import ChatEventPublisherfrom .models import (DEFAULT_CHAT_SYSTEM_PROMPT,+ ChatActiveOperation,ChatCompaction,ChatConflictError,ChatContextEstimate,ChatModelOption,+ ChatOperationAcknowledgement,+ ChatOperationKind,+ ChatOperationPhase,ChatPreferences,ChatReasoning,ChatSegment,ChatSession,ChatSessionDetail,ChatSessionPage,- ChatStreamEvent,+ ChatSessionSummary,ChatTranscript,ChatTurn,ChatUnavailableError,@@ -50,9 +54,8 @@ from .models import (GenerationStatus,SegmentKind,)-from .ports import ChatOperationStream, ChatStorePort+from .ports import ChatEventSubscriptionPort, ChatStorePort-_EVENT_QUEUE_SIZE = 128_PERSIST_INTERVAL_SECONDS = 0.25_PERSIST_CHARACTER_THRESHOLD = 4_096_TURN_PAGE_LIMIT = 50@@ -62,19 +65,24 @@ _STORAGE_RESTART_MESSAGE = ()-class _OperationKind(StrEnum):- SEND = "send"- RETRY = "retry"- REGENERATE = "regenerate"- COMPACT = "compact"--class _CancellationReason(StrEnum):STOPPED = "stopped"INTERRUPTED = "interrupted"DELETED = "deleted"+class _OperationLifecycle(StrEnum):+ RUNNING = "running"+ SETTLING = "settling"+++@dataclass(frozen=True, slots=True)+class _TerminalEvent:+ event: str+ data: JsonObject+ publish_summary: bool++class _TerminalPersistenceError(ChatUnavailableError):"""A bounded terminal write failed and requires startup repair."""@@ -83,49 +91,20 @@ class _TerminalPersistenceError(ChatUnavailableError):class _ActiveOperation:session_id: stroperation_id: str- kind: _OperationKind- queue: asyncio.Queue[ChatStreamEvent | None] = field(- default_factory=lambda: asyncio.Queue(maxsize=_EVENT_QUEUE_SIZE)- )- task: asyncio.Task[None] | None = None+ kind: ChatOperationKind+ phase: ChatOperationPhase+ submitted_text: str | None = None+ work_task: asyncio.Task[None] | None = None+ supervisor_task: asyncio.Task[None] | None = None+ lifecycle: _OperationLifecycle = _OperationLifecycle.RUNNINGcancellation_reason: _CancellationReason | None = None+ turn_id: str | None = Nonegeneration_id: str | None = Noneregeneration: bool = Falsesegments: list[ChatSegment] = field(default_factory=list)event_sequence: int = 0actual_model: str | None = None- terminal_emitted: bool = False---class _OperationStream:- """Initiating browser view of one application-owned operation."""-- def __init__(self, service: ChatService, active: _ActiveOperation) -> None:- self._service = service- self._active = active- self.operation_id = active.operation_id- self._closed = False-- def __aiter__(self) -> AsyncIterator[ChatStreamEvent]:- return self._events()-- async def _events(self) -> AsyncIterator[ChatStreamEvent]:- while True:- event = await self._active.queue.get()- if event is None:- return- yield event-- async def aclose(self) -> None:- if self._closed:- return- self._closed = True- task = self._active.task- if task is not None and not task.done():- await self._service._cancel_active(- self._active,- reason=_CancellationReason.STOPPED,- )+ terminal_event: _TerminalEvent | None = Noneclass ChatService:@@ -135,6 +114,7 @@ class ChatService:self._runtime = runtimeself._store = storeself._context = ChatContextBuilder(runtime)+ self._events = ChatEventPublisher()self._active: dict[str, _ActiveOperation] = {}self._deleting: set[str] = set()self._active_lock = asyncio.Lock()@@ -173,10 +153,12 @@ class ChatService:self._cancel_active(operation,reason=_CancellationReason.INTERRUPTED,+ wait_if_settling=True,)for operation in active))+ self._events.close()await self._store.close()self._started = Falseself._unavailable_message = "Chat Sessions is stopped."@@ -187,17 +169,34 @@ class ChatService:def models(self) -> tuple[ChatModelOption, ...]:return self._context.models()+ async def subscribe(+ self,+ ) -> tuple[ChatEventSubscriptionPort, tuple[ChatActiveOperation, ...]]:+ self._require_available()+ subscription = self._events.subscribe()+ try:+ async with self._active_lock:+ active = tuple(_active_snapshot(item) for item in self._active.values())+ except BaseException:+ await subscription.aclose()+ raise+ return subscription, active+async def preferences(self) -> ChatPreferences:self._require_available()return await self._store.load_preferences()async def save_system_prompt(self, value: str) -> ChatPreferences:self._require_available()- return await self._store.save_system_prompt(value)+ preferences = await self._store.save_system_prompt(value)+ self._publish_preferences(preferences)+ return preferencesasync def reset_system_prompt(self) -> ChatPreferences:self._require_available()- return await self._store.save_system_prompt(DEFAULT_CHAT_SYSTEM_PROMPT)+ preferences = await self._store.save_system_prompt(DEFAULT_CHAT_SYSTEM_PROMPT)+ self._publish_preferences(preferences)+ return preferencesasync def create_session(self) -> ChatSession:self._require_available()@@ -219,11 +218,13 @@ class ChatService:reasoning = preferences.last_reasoningif available[model].supports_reasoning is False:reasoning = ChatReasoning.OFF- return await self._store.create_session(+ session = await self._store.create_session(session_id=str(uuid.uuid4()),model=model,reasoning=reasoning,)+ await self._publish_session_summary(session.id, event="session.created")+ return sessionasync def list_sessions(self,@@ -246,32 +247,29 @@ class ChatService:async def get_detail(self, session_id: str) -> ChatSessionDetail:self._require_available()session_id = _canonical_uuid(session_id, "session")- async with self._active_lock:- active_operation = session_id in self._active- transcript = await self._store.get_transcript(session_id)- prompt = (await self._store.load_preferences()).system_prompt- context: ChatContextEstimate | None- context_error: str | None = None- try:- context = self._context.prepare(- transcript,- system_prompt=prompt,- ).estimate- except ChatValidationError as exc:- context = None- context_error = str(exc)- has_more = len(transcript.turns) > _TURN_PAGE_LIMIT- turns = transcript.turns[-_TURN_PAGE_LIMIT:]- next_before = turns[0].sequence if has_more and turns else None- return ChatSessionDetail(- session=transcript.session,- turns=turns,- next_before=next_before,- compaction=transcript.compaction,- context=context,- context_error=context_error,- active_operation=active_operation,- )+ transcript = await self._store.get_transcript(session_id)+ prompt = (await self._store.load_preferences()).system_prompt+ context: ChatContextEstimate | None+ context_error: str | None = None+ try:+ context = self._context.prepare(+ transcript,+ system_prompt=prompt,+ ).estimate+ except ChatValidationError as exc:+ context = None+ context_error = str(exc)+ has_more = len(transcript.turns) > _TURN_PAGE_LIMIT+ turns = transcript.turns[-_TURN_PAGE_LIMIT:]+ next_before = turns[0].sequence if has_more and turns else None+ return ChatSessionDetail(+ session=transcript.session,+ turns=turns,+ next_before=next_before,+ compaction=transcript.compaction,+ context=context,+ context_error=context_error,+ )async def update_session(self,@@ -301,13 +299,15 @@ class ChatService:raise ChatConflictError("Model and thinking cannot change while this chat is running.")- return await self._store.update_session(+ session = await self._store.update_session(session_id,expected_revision=expected_revision,title=title,model=model,reasoning=reasoning,)+ await self._publish_session_summary(session.id)+ return sessionasync def delete_session(self, session_id: str, *, expected_revision: int) -> None:self._require_available()@@ -320,13 +320,31 @@ class ChatService:try:current = await self._store.get_session(session_id)_expect_revision(current, expected_revision)- if active is not None:- await self._cancel_active(active, reason=_CancellationReason.DELETED)- current = await self._store.get_session(session_id)- await self._store.delete_session(- session_id,- expected_revision=current.revision,++ async def finish_deletion() -> None:+ settled = current+ if active is not None:+ await self._cancel_active(+ active,+ reason=_CancellationReason.DELETED,+ wait_if_settling=True,+ )+ settled = await self._store.get_session(session_id)+ await self._store.delete_session(+ session_id,+ expected_revision=settled.revision,+ )+ self._events.publish("session.deleted", {"session_id": session_id})++ deletion_task = asyncio.create_task(+ finish_deletion(),+ name=f"fcc-chat-delete-{session_id}",)+ _result, cancellation = await _await_task_despite_cancellation(+ deletion_task+ )+ if cancellation is not None:+ raise cancellationfinally:async with self._active_lock:self._deleting.discard(session_id)@@ -366,7 +384,7 @@ class ChatService:expected_revision: int,operation_id: str,text: str,- ) -> ChatOperationStream:+ ) -> ChatOperationAcknowledgement:self._require_available()session_id = _canonical_uuid(session_id, "session")operation_id = _canonical_uuid(operation_id, "operation")@@ -379,7 +397,8 @@ class ChatService:return await self._start_operation(session_id,operation_id=operation_id,- kind=_OperationKind.SEND,+ kind=ChatOperationKind.SEND,+ submitted_text=text,action=lambda active: self._run_send(active,expected_revision=expected_revision,@@ -393,7 +412,7 @@ class ChatService:*,expected_revision: int,operation_id: str,- ) -> ChatOperationStream:+ ) -> ChatOperationAcknowledgement:self._require_available()session_id = _canonical_uuid(session_id, "session")operation_id = _canonical_uuid(operation_id, "operation")@@ -415,7 +434,7 @@ class ChatService:return await self._start_operation(session_id,operation_id=operation_id,- kind=_OperationKind.RETRY,+ kind=ChatOperationKind.RETRY,action=lambda active: self._run_retry(active,expected_revision=expected_revision,@@ -428,7 +447,7 @@ class ChatService:*,expected_revision: int,operation_id: str,- ) -> ChatOperationStream:+ ) -> ChatOperationAcknowledgement:self._require_available()session_id = _canonical_uuid(session_id, "session")operation_id = _canonical_uuid(operation_id, "operation")@@ -446,7 +465,7 @@ class ChatService:return await self._start_operation(session_id,operation_id=operation_id,- kind=_OperationKind.REGENERATE,+ kind=ChatOperationKind.REGENERATE,action=lambda active: self._run_regenerate(active,expected_revision=expected_revision,@@ -459,7 +478,7 @@ class ChatService:*,expected_revision: int,operation_id: str,- ) -> ChatOperationStream:+ ) -> ChatOperationAcknowledgement:self._require_available()session_id = _canonical_uuid(session_id, "session")operation_id = _canonical_uuid(operation_id, "operation")@@ -472,7 +491,7 @@ class ChatService:return await self._start_operation(session_id,operation_id=operation_id,- kind=_OperationKind.COMPACT,+ kind=ChatOperationKind.COMPACT,action=lambda active: self._run_manual_compaction(active,expected_revision=expected_revision,@@ -485,21 +504,25 @@ class ChatService:operation_id = _canonical_uuid(operation_id, "operation")async with self._active_lock:active = self._active.get(session_id)- if active is None:- return False- if active.operation_id != operation_id:- raise ChatConflictError("That operation is no longer active.")- await self._cancel_active(active, reason=_CancellationReason.STOPPED)- return True+ if active is None:+ return False+ if active.operation_id != operation_id:+ raise ChatConflictError("That operation is no longer active.")+ return await self._cancel_active(+ active,+ reason=_CancellationReason.STOPPED,+ wait_if_settling=False,+ )async def _start_operation(self,session_id: str,*,operation_id: str,- kind: _OperationKind,+ kind: ChatOperationKind,+ submitted_text: str | None = None,action: Callable[[_ActiveOperation], Awaitable[None]],- ) -> _OperationStream:+ ) -> ChatOperationAcknowledgement:async with self._active_lock:if not self._accepting:raise ChatUnavailableError("Chat Sessions is shutting down.")@@ -511,39 +534,66 @@ class ChatService:session_id=session_id,operation_id=operation_id,kind=kind,+ phase=(+ ChatOperationPhase.COMPACTING+ if kind is ChatOperationKind.COMPACT+ else ChatOperationPhase.GENERATING+ ),+ submitted_text=submitted_text,)++ async def run_work() -> None:+ await action(active)+self._active[session_id] = active- active.task = asyncio.create_task(- self._run_active(active, action),+ active.work_task = asyncio.create_task(+ run_work(),+ name=f"fcc-chat-{kind.value}-{operation_id}-work",+ )+ active.supervisor_task = asyncio.create_task(+ self._run_active(active),name=f"fcc-chat-{kind.value}-{operation_id}",)- return _OperationStream(self, active)+ self._emit(+ active,+ "operation.started",+ {+ "kind": kind.value,+ "phase": active.phase.value,+ "submitted_text": submitted_text,+ },+ )+ return ChatOperationAcknowledgement(+ session_id=session_id,+ operation_id=operation_id,+ kind=kind,+ )async def _run_active(self,active: _ActiveOperation,- action: Callable[[_ActiveOperation], Awaitable[None]],) -> None:+ work_task = active.work_task+ if work_task is None:+ raise RuntimeError("Chat operation work was not initialized.")try:- await action(active)+ await work_taskexcept asyncio.CancelledError:- settlement = asyncio.create_task(- self._handle_cancelled(active),- name=f"fcc-chat-settle-cancelled-{active.operation_id}",+ await self._claim_settlement(+ active,+ reason=active.cancellation_reason or _CancellationReason.STOPPED,)- await _await_task_despite_cancellation(settlement)+ await self._handle_cancelled(active)except Exception as exc:- settlement = asyncio.create_task(- self._handle_failure(active, exc),- name=f"fcc-chat-settle-failed-{active.operation_id}",- )- await _await_task_despite_cancellation(settlement)+ await self._claim_settlement(active)+ if active.cancellation_reason is not None:+ await self._handle_cancelled(active)+ else:+ await self._handle_failure(active, exc)finally:- release_task = asyncio.create_task(- self._release_active(active),- name=f"fcc-chat-release-{active.operation_id}",- )- await _await_task_despite_cancellation(release_task)+ publish_summary = await self._release_active(active)+ if publish_summary:+ await self._publish_session_summary(active.session_id)async def _run_send(self,@@ -598,7 +648,9 @@ class ChatService:effective_output_limit=prepared.routed.request.max_tokens or 1,),)- await self._emit(+ active.turn_id = turn_id+ await self._publish_session_summary(active.session_id)+ self._emit(active,"turn.started",{@@ -664,7 +716,9 @@ class ChatService:effective_output_limit=prepared.routed.request.max_tokens or 1,),)- await self._emit(+ active.turn_id = latest.id+ await self._publish_session_summary(active.session_id)+ self._emit(active,"turn.started",{@@ -732,7 +786,9 @@ class ChatService:effective_output_limit=prepared.routed.request.max_tokens or 1,),)- await self._emit(+ active.turn_id = latest.id+ await self._publish_session_summary(active.session_id)+ self._emit(active,"turn.started",{@@ -858,6 +914,9 @@ class ChatService:if not saw_message_stop:raise ChatValidationError("The provider stream ended before completing.")+ if not await self._claim_settlement(active):+ raise asyncio.CancelledError+async def commit_completion() -> ChatSession:await self._flush_terminal_segments(active)if active.regeneration:@@ -876,12 +935,8 @@ class ChatService:error_message=None,)- commit_task = asyncio.create_task(- commit_completion(),- name=f"fcc-chat-generation-commit-{generation_id}",- )- session, _cancellation = await _await_task_despite_cancellation(commit_task)- self._emit_terminal_nowait(+ session = await commit_completion()+ self._stage_terminal(active,"turn.completed",{@@ -889,6 +944,7 @@ class ChatService:"revision": session.revision,"actual_model": active.actual_model,},+ publish_summary=True,)async def _handle_sse_event(@@ -933,10 +989,10 @@ class ChatService:ordinal = len(active.segments)active.segments.append(ChatSegment(ordinal=ordinal, kind=kind, text=""))block_segments[index] = ordinal- await self._emit(+ self._emit(active,"segment.started",- {"ordinal": ordinal, "kind": kind.value},+ {"ordinal": ordinal, "segment_kind": kind.value},)eager_key = "thinking" if kind is SegmentKind.THINKING else "text"eager = _optional_string(block.get(eager_key)) or ""@@ -972,7 +1028,7 @@ class ChatService:ordinal = block_segments.pop(index, None)if ordinal is not None:await self._flush_segments(active)- await self._emit(active, "segment.completed", {"ordinal": ordinal})+ self._emit(active, "segment.completed", {"ordinal": ordinal})return 0, False, Noneif payload_type == "message_delta":delta = data.get("delta")@@ -989,10 +1045,14 @@ class ChatService:) -> None:current = active.segments[ordinal]active.segments[ordinal] = replace(current, text=f"{current.text}{delta}")- await self._emit(+ self._emit(active,"segment.delta",- {"ordinal": ordinal, "kind": current.kind.value, "delta": delta},+ {+ "ordinal": ordinal,+ "segment_kind": current.kind.value,+ "delta": delta,+ },)async def _flush_segments(self, active: _ActiveOperation) -> None:@@ -1024,7 +1084,8 @@ class ChatService:raise ChatValidationError("There is not enough older conversation to compact.")- await self._emit(active, "compaction.started", {})+ active.phase = ChatOperationPhase.COMPACTING+ self._emit(active, "compaction.started", {"phase": active.phase.value})option = builder.model(transcript.session.model)output_tokens = builder.summary_output_tokens(option)retain_count = min(4, len(remaining) - 1)@@ -1095,21 +1156,37 @@ class ChatService:),)- commit_task = asyncio.create_task(- commit_compaction(),- name=f"fcc-chat-compaction-commit-{transcript.session.id}",- )- compaction, cancellation = await _await_task_despite_cancellation(commit_task)+ cancellation: asyncio.CancelledError | None = None+ if active.kind is ChatOperationKind.COMPACT:+ if not await self._claim_settlement(active):+ raise asyncio.CancelledError+ compaction = await commit_compaction()+ else:+ commit_task = asyncio.create_task(+ commit_compaction(),+ name=f"fcc-chat-compaction-commit-{transcript.session.id}",+ )+ compaction, cancellation = await _await_task_despite_cancellation(+ commit_task+ )completion: JsonObject = {"covered_through_sequence": covered,"revision": transcript.session.revision + 1,}- if active.kind is _OperationKind.COMPACT:- self._emit_terminal_nowait(active, "compaction.completed", completion)+ if active.kind is ChatOperationKind.COMPACT:+ self._stage_terminal(+ active,+ "compaction.completed",+ completion,+ publish_summary=True,+ )else:- self._emit_nowait(active, "compaction.completed", completion)+ active.phase = ChatOperationPhase.GENERATING+ completion["phase"] = active.phase.value+ self._emit(active, "compaction.completed", completion)if cancellation is not None:raise cancellation+ await self._publish_session_summary(active.session_id)return compactionasync def _summarize_turns(@@ -1222,7 +1299,7 @@ class ChatService:raise ChatValidationError("The provider did not identify the compaction model.")- await self._emit(+ self._emit(active,"compaction.progress",{"covered_exchange_count": 1},@@ -1231,6 +1308,8 @@ class ChatService:async def _handle_cancelled(self, active: _ActiveOperation) -> None:reason = active.cancellation_reason or _CancellationReason.STOPPED+ terminal_data: JsonObject = {"reason": reason.value}+ publish_summary = Falseif active.generation_id is not None:try:if active.regeneration:@@ -1242,13 +1321,15 @@ class ChatService:if reason is _CancellationReason.INTERRUPTEDelse GenerationStatus.STOPPED)- await self._finish_generation(+ session = await self._finish_generation(active.generation_id,status=status,stop_reason=reason.value,error_code=None,error_message=None,)+ terminal_data["revision"] = session.revision+ publish_summary = Trueexcept Exception as exc:if reason is _CancellationReason.INTERRUPTED:logger.warning(@@ -1262,7 +1343,7 @@ class ChatService:self._disable_after_terminal_write_failure(active, exc)if reason is _CancellationReason.DELETED:raise- self._emit_terminal_nowait(+ self._stage_terminal(active,"turn.failed",{@@ -1275,20 +1356,29 @@ class ChatService:returnevent = ("compaction.stopped"- if active.kind is _OperationKind.COMPACT+ if active.kind is ChatOperationKind.COMPACTelse "turn.stopped")- self._emit_terminal_nowait(active, event, {"reason": reason.value})+ self._stage_terminal(+ active,+ event,+ terminal_data,+ publish_summary=publish_summary,+ )async def _handle_failure(self, active: _ActiveOperation, exc: Exception) -> None:if isinstance(exc, _TerminalPersistenceError):self._disable_after_terminal_write_failure(active, exc)event = ("compaction.failed"- if active.kind is _OperationKind.COMPACT- else "turn.failed"+ if active.kind is ChatOperationKind.COMPACT+ else (+ "turn.failed"+ if active.generation_id is not None+ else "operation.failed"+ ))- self._emit_terminal_nowait(+ self._stage_terminal(active,event,{@@ -1315,11 +1405,13 @@ class ChatService:active.operation_id,type(exc).__name__,)+ terminal_data: JsonObject = {"code": code, "message": message}+ publish_summary = Falseif active.generation_id is not None:try:await self._flush_terminal_segments(active)if active.regeneration:- await self._finish_regeneration(+ session = await self._finish_regeneration(active.generation_id,status=GenerationStatus.FAILED,stop_reason=None,@@ -1327,13 +1419,15 @@ class ChatService:error_message=message,)else:- await self._finish_generation(+ session = await self._finish_generation(active.generation_id,status=GenerationStatus.FAILED,stop_reason=None,error_code=code,error_message=message,)+ terminal_data["revision"] = session.revision+ publish_summary = Trueexcept Exception as persistence_exc:self._disable_after_terminal_write_failure(active,@@ -1341,12 +1435,20 @@ class ChatService:)code = "chat_storage_unavailable"message = _STORAGE_RESTART_MESSAGE+ terminal_data = {"code": code, "message": message}event = ("compaction.failed"- if active.kind is _OperationKind.COMPACT+ if active.kind is ChatOperationKind.COMPACTelse "turn.failed"+ if active.generation_id is not None+ else "operation.failed"+ )+ self._stage_terminal(+ active,+ event,+ terminal_data,+ publish_summary=publish_summary,)- self._emit_terminal_nowait(active, event, {"code": code, "message": message})async def _flush_terminal_segments(self, active: _ActiveOperation) -> None:await self._retry_terminal_persistence(@@ -1436,80 +1538,90 @@ class ChatService:type(exc).__name__,)- async def _emit(- self, active: _ActiveOperation, event: str, data: JsonObject- ) -> None:+ def _emit(self, active: _ActiveOperation, event: str, data: JsonObject) -> None:active.event_sequence += 1payload: JsonObject = {"session_id": active.session_id,"operation_id": active.operation_id,+ "kind": active.kind.value,+ "operation_sequence": active.event_sequence,**data,}- await active.queue.put(- ChatStreamEvent(- event=event,- sequence=active.event_sequence,- data=payload,- )- )+ self._events.publish(event, payload)- def _emit_terminal_nowait(- self, active: _ActiveOperation, event: str, data: JsonObject+ def _stage_terminal(+ self,+ active: _ActiveOperation,+ event: str,+ data: JsonObject,+ *,+ publish_summary: bool = False,) -> None:- if active.terminal_emitted:+ if active.terminal_event is not None:return- self._emit_nowait(active, event, data)- active.terminal_emitted = True-- def _emit_nowait(- self, active: _ActiveOperation, event: str, data: JsonObject- ) -> None:- active.event_sequence += 1- payload: JsonObject = {- "session_id": active.session_id,- "operation_id": active.operation_id,- **data,- }- _make_queue_room(active.queue)- active.queue.put_nowait(- ChatStreamEvent(- event=event,- sequence=active.event_sequence,- data=payload,- )+ active.terminal_event = _TerminalEvent(+ event=event,+ data={**data},+ publish_summary=publish_summary,)+ async def _claim_settlement(+ self,+ active: _ActiveOperation,+ *,+ reason: _CancellationReason | None = None,+ ) -> bool:+ async with self._active_lock:+ if self._active.get(active.session_id) is not active:+ return False+ if active.lifecycle is _OperationLifecycle.SETTLING:+ return False+ active.lifecycle = _OperationLifecycle.SETTLING+ active.cancellation_reason = reason+ return True+async def _cancel_active(self,active: _ActiveOperation,*,reason: _CancellationReason,- ) -> None:- task = active.task- if task is None or task.done():- return- if active.cancellation_reason is None:- active.cancellation_reason = reason- task.cancel()- cancellation: asyncio.CancelledError | None = None- try:- _result, cancellation = await _await_task_despite_cancellation(task)- except asyncio.CancelledError:- current = asyncio.current_task()- if current is not None and current.cancelling():- raise- finally:- await self._release_active(active)- if cancellation is not None:- raise cancellation+ wait_if_settling: bool,+ ) -> bool:+ async with self._active_lock:+ if self._active.get(active.session_id) is not active:+ return False+ accepted = False+ if active.lifecycle is _OperationLifecycle.RUNNING:+ active.lifecycle = _OperationLifecycle.SETTLING+ active.cancellation_reason = reason+ accepted = True+ work_task = active.work_task+ if work_task is not None and not work_task.done():+ work_task.cancel()+ elif (+ reason is _CancellationReason.STOPPED+ and active.cancellation_reason is _CancellationReason.STOPPED+ ):+ accepted = True+ supervisor_task = active.supervisor_task+ if supervisor_task is not None and (accepted or wait_if_settling):+ cancellation = await _wait_task_despite_cancellation(supervisor_task)+ supervisor_task.result()+ if cancellation is not None:+ raise cancellation+ return accepted- async def _release_active(self, active: _ActiveOperation) -> None:+ async def _release_active(self, active: _ActiveOperation) -> bool:+ publish_summary = Falseasync with self._active_lock:if self._active.get(active.session_id) is not active:- return+ return Falseself._active.pop(active.session_id, None)- _make_queue_room(active.queue)- active.queue.put_nowait(None)+ terminal = active.terminal_event+ if terminal is not None:+ self._emit(active, terminal.event, terminal.data)+ publish_summary = terminal.publish_summary+ return publish_summarydef _require_available(self) -> None:if not self._started or not self._accepting:@@ -1517,6 +1629,34 @@ class ChatService:self._unavailable_message or "Chat Sessions is unavailable.")+ def _publish_preferences(self, preferences: ChatPreferences) -> None:+ self._events.publish(+ "preferences.updated",+ {+ "system_prompt": preferences.system_prompt,+ "last_model": preferences.last_model,+ "last_reasoning": preferences.last_reasoning.value,+ "updated_at": preferences.updated_at,+ },+ )++ async def _publish_session_summary(+ self,+ session_id: str,+ *,+ event: str = "session.updated",+ ) -> None:+ try:+ summary = await self._store.get_session_summary(session_id)+ self._events.publish(event, _session_summary_event_data(summary))+ except Exception as exc:+ logger.warning(+ "Could not publish Chat session summary: session_id={} exc_type={}",+ session_id,+ type(exc).__name__,+ )+ return+async def _commit_generation_start(active: _ActiveOperation,@@ -1638,7 +1778,30 @@ def _optional_string(value: object) -> str | None:return value if isinstance(value, str) else None-def _make_queue_room(queue: asyncio.Queue[ChatStreamEvent | None]) -> None:- if queue.full():- with contextlib.suppress(asyncio.QueueEmpty):- queue.get_nowait()+def _active_snapshot(active: _ActiveOperation) -> ChatActiveOperation:+ return ChatActiveOperation(+ session_id=active.session_id,+ operation_id=active.operation_id,+ kind=active.kind,+ phase=active.phase,+ operation_sequence=active.event_sequence,+ submitted_text=active.submitted_text,+ turn_id=active.turn_id,+ generation_id=active.generation_id,+ regeneration=active.regeneration,+ actual_model=active.actual_model,+ segments=tuple(active.segments),+ )+++def _session_summary_event_data(session: ChatSessionSummary) -> JsonObject:+ return {+ "session_id": session.id,+ "title": session.title,+ "model": session.model,+ "reasoning": session.reasoning.value,+ "revision": session.revision,+ "preview": session.preview[:240],+ "created_at": session.created_at,+ "updated_at": session.updated_at,+ }diff --git a/src/free_claude_code/runtime/chat_sqlite.py b/src/free_claude_code/runtime/chat_sqlite.pyindex 4935880b..630da8fd 100644--- a/src/free_claude_code/runtime/chat_sqlite.py+++ b/src/free_claude_code/runtime/chat_sqlite.py@@ -35,6 +35,15 @@ T = TypeVar("T")_SCHEMA_VERSION = 1_BUSY_TIMEOUT_MS = 5_000_NEW_CHAT_TITLE = "New chat"+_SESSION_SUMMARY_SELECT = """+ SELECT s.*,+ COALESCE((+ SELECT t.user_text FROM chat_turns AS t+ WHERE t.session_id = s.id+ ORDER BY t.sequence DESC LIMIT 1+ ), '') AS preview+ FROM chat_sessions AS s+"""class SQLiteChatStore:@@ -149,13 +158,7 @@ class SQLiteChatStore:where = f"WHERE {' AND '.join(clauses)}" if clauses else ""rows = connection.execute(f"""- SELECT s.*,- COALESCE((- SELECT t.user_text FROM chat_turns AS t- WHERE t.session_id = s.id- ORDER BY t.sequence DESC LIMIT 1- ), '') AS preview- FROM chat_sessions AS s+ {_SESSION_SUMMARY_SELECT}{where}ORDER BY s.updated_at DESC, s.id DESCLIMIT ?@@ -173,6 +176,18 @@ class SQLiteChatStore:return await self._run(operation)+ async def get_session_summary(self, session_id: str) -> ChatSessionSummary:+ def operation(connection: sqlite3.Connection) -> ChatSessionSummary:+ row = connection.execute(+ f"{_SESSION_SUMMARY_SELECT} WHERE s.id = ?",+ (session_id,),+ ).fetchone()+ if row is None:+ raise ChatNotFoundError("Chat session not found.")+ return _session_summary_from_row(row)++ return await self._run(operation)+async def get_session(self, session_id: str) -> ChatSession:return await self._run(lambda connection: self._get_session(connection, session_id)diff --git a/tests/api/test_chat_routes.py b/tests/api/test_chat_routes.pyindex 8e0a7c00..2458b48d 100644--- a/tests/api/test_chat_routes.py+++ b/tests/api/test_chat_routes.py@@ -1,26 +1,26 @@-import asyncioimport base64-from collections.abc import AsyncIteratorfrom dataclasses import replace-from typing import castimport pytestfrom fastapi.testclient import TestClient-from starlette.types import Message, Scope-from free_claude_code.api.chat_routes import _stream_responsefrom free_claude_code.application.chat import (+ ChatActiveOperation,ChatCompaction,ChatContextEstimate,+ ChatEventOverflowError,ChatModelOption,+ ChatOperationAcknowledgement,+ ChatOperationKind,+ ChatOperationPhase,ChatPreferences,+ ChatPublishedEvent,ChatReasoning,ChatSegment,ChatSession,ChatSessionDetail,ChatSessionPage,ChatSessionSummary,- ChatStreamEvent,ChatTurn,ChatValidationError,GenerationStatus,@@ -34,26 +34,40 @@ SESSION_ID = "29e3b8fd-8744-4377-b8cf-4c9d48daf962"OPERATION_ID = "7cd43d62-c1aa-42f8-9963-6c0811c0dfaf"-class StubStream:- operation_id = OPERATION_ID+class StubSubscription:+ cursor = 4def __init__(self) -> None:self.closed = False- def __aiter__(self) -> AsyncIterator[ChatStreamEvent]:+ def __aiter__(self):return self._events()- async def _events(self) -> AsyncIterator[ChatStreamEvent]:- yield ChatStreamEvent(+ async def _events(self):+ yield ChatPublishedEvent(event="turn.completed",- sequence=1,- data={"operation_id": OPERATION_ID, "session_id": SESSION_ID},+ id=5,+ data={+ "operation_id": OPERATION_ID,+ "session_id": SESSION_ID,+ "kind": "send",+ "operation_sequence": 3,+ },)async def aclose(self) -> None:self.closed = True+class OverflowSubscription(StubSubscription):+ cursor = 7++ async def _events(self):+ if False:+ yield+ raise ChatEventOverflowError(9)++class StubChat:def __init__(self) -> None:self.session = ChatSession(@@ -94,9 +108,9 @@ class StubChat:last_reasoning=self.session.reasoning,updated_at=1,)- self.last_stream: StubStream | None = None+ self.last_subscription: StubSubscription | None = Noneself.deleted = False- self.active_operation = False+ self.active_operation: ChatActiveOperation | None = Nonedef availability(self) -> tuple[bool, str | None]:return True, None@@ -114,6 +128,13 @@ class StubChat:),)+ async def subscribe(+ self,+ ) -> tuple[StubSubscription, tuple[ChatActiveOperation, ...]]:+ self.last_subscription = StubSubscription()+ active = (self.active_operation,) if self.active_operation is not None else ()+ return self.last_subscription, active+async def preferences(self) -> ChatPreferences:return self.preferences_value@@ -148,7 +169,6 @@ class StubChat:compaction=compaction,context=context,context_error=context_error,- active_operation=self.active_operation,)async def list_sessions(@@ -227,15 +247,18 @@ class StubChat:expected_revision: int,operation_id: str,text: str,- ) -> StubStream:+ ) -> ChatOperationAcknowledgement:assert (session_id, expected_revision, operation_id, text) == (SESSION_ID,self.session.revision,OPERATION_ID,"hello",)- self.last_stream = StubStream()- return self.last_stream+ return ChatOperationAcknowledgement(+ session_id=session_id,+ operation_id=operation_id,+ kind=ChatOperationKind.SEND,+ )async def retry(self,@@ -243,9 +266,13 @@ class StubChat:*,expected_revision: int,operation_id: str,- ) -> StubStream:- del session_id, expected_revision, operation_id- return StubStream()+ ) -> ChatOperationAcknowledgement:+ del expected_revision+ return ChatOperationAcknowledgement(+ session_id=session_id,+ operation_id=operation_id,+ kind=ChatOperationKind.RETRY,+ )async def regenerate(self,@@ -253,9 +280,13 @@ class StubChat:*,expected_revision: int,operation_id: str,- ) -> StubStream:- del session_id, expected_revision, operation_id- return StubStream()+ ) -> ChatOperationAcknowledgement:+ del expected_revision+ return ChatOperationAcknowledgement(+ session_id=session_id,+ operation_id=operation_id,+ kind=ChatOperationKind.REGENERATE,+ )async def compact(self,@@ -263,9 +294,13 @@ class StubChat:*,expected_revision: int,operation_id: str,- ) -> StubStream:- del session_id, expected_revision, operation_id- return StubStream()+ ) -> ChatOperationAcknowledgement:+ del expected_revision+ return ChatOperationAcknowledgement(+ session_id=session_id,+ operation_id=operation_id,+ kind=ChatOperationKind.COMPACT,+ )async def stop(self, session_id: str, *, operation_id: str) -> bool:return (session_id, operation_id) == (SESSION_ID, OPERATION_ID)@@ -280,6 +315,18 @@ class UnestimatableChat(StubChat):)+class OverflowChat(StubChat):+ async def subscribe(+ self,+ ) -> tuple[OverflowSubscription, tuple[ChatActiveOperation, ...]]:+ subscription = OverflowSubscription()+ self.last_subscription = subscription+ return subscription, ()++ async def stop(self, session_id: str, *, operation_id: str) -> bool:+ raise AssertionError((session_id, operation_id))++def _client(chat: StubChat | None = None) -> TestClient:return TestClient(create_test_app(chat=chat),@@ -299,11 +346,24 @@ def test_chat_deep_links_serve_the_versioned_admin_shell():def test_chat_bootstrap_and_detail_project_rich_models_and_safe_markdown():chat = StubChat()- chat.active_operation = True+ chat.active_operation = ChatActiveOperation(+ session_id=SESSION_ID,+ operation_id=OPERATION_ID,+ kind=ChatOperationKind.SEND,+ phase=ChatOperationPhase.GENERATING,+ operation_sequence=2,+ submitted_text="next",+ turn_id="turn-next",+ generation_id="generation-next",+ regeneration=False,+ actual_model="groq/model",+ segments=(ChatSegment(0, SegmentKind.TEXT, "live"),),+ )client = _client(chat)bootstrap = client.get("/admin/api/chat/bootstrap").json()detail = client.get(f"/admin/api/chat/sessions/{SESSION_ID}").json()+ feed = client.get("/admin/api/chat/events")assert bootstrap["models"][0]["supports_reasoning"] is Trueassert bootstrap["models"][0]["input_modalities"] == ["text"]@@ -313,7 +373,8 @@ def test_chat_bootstrap_and_detail_project_rich_models_and_safe_markdown():assert "<script>" not in segment["html"]assert detail["turns"][0]["generation"]["actual_model"] == ("open_router/fallback")assert detail["turns"][0]["operation_id"] == "operation"- assert detail["active_operation"] is True+ assert "active_operation" not in detail+ assert '"submitted_text": "next"' in feed.textdef test_chat_detail_stays_readable_when_context_controls_need_repair():@@ -354,7 +415,7 @@ def test_chat_crud_and_prompt_routes_use_application_port():assert chat.deleted is True-def test_chat_stream_serializes_events_and_closes_operation():+def test_chat_long_operation_acknowledges_without_owning_its_event_stream():chat = StubChat()response = _client(chat).post(f"/admin/api/chat/sessions/{SESSION_ID}/send",@@ -365,50 +426,46 @@ def test_chat_stream_serializes_events_and_closes_operation():},)+ assert response.status_code == 202+ assert response.json() == {+ "session_id": SESSION_ID,+ "operation_id": OPERATION_ID,+ "kind": "send",+ }+ assert chat.last_subscription is None+++def test_chat_event_feed_starts_at_snapshot_barrier_and_closes_subscription():+ chat = StubChat()++ response = _client(chat).get("/admin/api/chat/events")+assert response.status_code == 200+ assert response.headers["content-type"].startswith("text/event-stream")+ assert response.headers["cache-control"] == "no-store"+ assert response.headers["x-accel-buffering"] == "no"+ assert "event: feed.ready" in response.text+ assert "id: 4" in response.text+ assert 'data: {"cursor": 4, "active_operations": []}' in response.textassert "event: turn.completed" in response.text- assert "id: 1" in response.text- assert chat.last_stream is not None and chat.last_stream.closed is True---async def test_chat_stream_closes_when_cancelled_before_body_iteration():- stream = StubStream()- response = _stream_response(stream)- response_started = asyncio.Event()-- async def receive() -> Message:- await asyncio.Event().wait()- raise AssertionError("unreachable")-- async def send(message: Message) -> None:- assert message["type"] == "http.response.start"- response_started.set()- await asyncio.Event().wait()-- scope = cast(- Scope,- {- "type": "http",- "asgi": {"version": "3.0", "spec_version": "2.4"},- "http_version": "1.1",- "method": "POST",- "scheme": "http",- "path": f"/admin/api/chat/sessions/{SESSION_ID}/send",- "raw_path": b"/admin/api/chat/sessions/send",- "query_string": b"",- "headers": [],- "client": ("127.0.0.1", 50000),- "server": ("127.0.0.1", 8000),- },- )- response_task = asyncio.create_task(response(scope, receive, send))- await asyncio.wait_for(response_started.wait(), timeout=1)- response_task.cancel()+ assert "id: 5" in response.text+ assert chat.last_subscription is not None+ assert chat.last_subscription.closed is True+- with pytest.raises(asyncio.CancelledError):- await response_task- assert stream.closed is True+def test_chat_event_feed_overflow_requests_resync_without_stopping_work():+ chat = OverflowChat()++ response = _client(chat).get("/admin/api/chat/events")++ assert response.status_code == 200+ assert "event: feed.ready" in response.text+ assert "id: 7" in response.text+ assert "event: feed.resync_required" in response.text+ assert "id: 9" in response.text+ assert 'data: {"cursor": 9}' in response.text+ assert chat.last_subscription is not None+ assert chat.last_subscription.closed is Truedef test_chat_routes_apply_loopback_and_origin_protection():diff --git a/tests/api/test_request_lifetime.py b/tests/api/test_request_lifetime.pyindex 339be379..514cf8ef 100644--- a/tests/api/test_request_lifetime.py+++ b/tests/api/test_request_lifetime.py@@ -60,6 +60,7 @@ async def _unused_send(_message: Message) -> None:[_http_scope("/health"),_http_scope("/v1/messages", method="OPTIONS"),+ _http_scope("/admin/api/chat/sessions/session/send"),_http_scope("/admin/api/chat/sessions/session/stop"),cast(Scope, {"type": "lifespan", "asgi": {"version": "3.0"}}),],@@ -98,7 +99,6 @@ async def test_non_inference_scopes_delegate_with_original_callables(["/v1/messages","/v1/responses",- "/admin/api/chat/sessions/session/send",],)async def test_request_body_frames_are_relayed_once_in_order(path: str) -> None:diff --git a/tests/application/test_chat_events.py b/tests/application/test_chat_events.pynew file mode 100644index 00000000..a41ae74b--- /dev/null+++ b/tests/application/test_chat_events.py@@ -0,0 +1,72 @@+import asyncio++import pytest++from free_claude_code.application.chat import ChatEventOverflowError+from free_claude_code.application.chat.events import ChatEventPublisher+++async def test_subscribers_receive_the_same_ordered_events_independently() -> None:+ publisher = ChatEventPublisher(queue_size=4)+ first = publisher.subscribe()+ second = publisher.subscribe()+ first_events = first.__aiter__()+ second_events = second.__aiter__()++ publisher.publish("session.created", {"session_id": "one"})+ publisher.publish("session.updated", {"session_id": "one", "revision": 2})++ assert [await anext(first_events), await anext(first_events)] == [+ await anext(second_events),+ await anext(second_events),+ ]++ await first.aclose()+ publisher.publish("session.deleted", {"session_id": "one"})++ with pytest.raises(StopAsyncIteration):+ await anext(first_events)+ assert (await anext(second_events)).event == "session.deleted"++ await second.aclose()+++async def test_slow_subscriber_overflow_does_not_block_a_healthy_subscriber() -> None:+ publisher = ChatEventPublisher(queue_size=2)+ slow = publisher.subscribe()+ healthy = publisher.subscribe()+ slow_events = slow.__aiter__()+ healthy_events = healthy.__aiter__()++ for revision in range(1, 4):+ published = publisher.publish(+ "session.updated",+ {"session_id": "one", "revision": revision},+ )+ assert await asyncio.wait_for(anext(healthy_events), timeout=1) == published++ with pytest.raises(ChatEventOverflowError) as raised:+ await asyncio.wait_for(anext(slow_events), timeout=1)+ assert raised.value.cursor == 3++ publisher.publish("session.deleted", {"session_id": "one"})+ assert (await anext(healthy_events)).event == "session.deleted"++ await slow.aclose()+ await healthy.aclose()+++async def test_publisher_close_releases_every_waiting_subscription() -> None:+ publisher = ChatEventPublisher()+ first = publisher.subscribe().__aiter__()+ second = publisher.subscribe().__aiter__()++ publisher.close()++ with pytest.raises(StopAsyncIteration):+ await asyncio.wait_for(anext(first), timeout=1)+ with pytest.raises(StopAsyncIteration):+ await asyncio.wait_for(anext(second), timeout=1)diff --git a/tests/application/test_chat_service.py b/tests/application/test_chat_service.pyindex 4d187970..5eb65e6d 100644--- a/tests/application/test_chat_service.py+++ b/tests/application/test_chat_service.py@@ -1,13 +1,17 @@import asyncioimport sqlite3-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Awaitable, Callable+from dataclasses import dataclassfrom pathlib import Pathimport pytestfrom free_claude_code.application.chat import (ChatConflictError,+ ChatEventSubscriptionPort,ChatNotFoundError,+ ChatOperationAcknowledgement,+ ChatOperationKind,ChatService,ChatUnavailableError,GenerationStatus,@@ -280,9 +284,60 @@ async def _service(return service, runtime, store-async def _drain(stream) -> list[str]:- events = [event.event async for event in stream]- await stream.aclose()+_TURN_TERMINAL_EVENTS = frozenset(+ {"turn.completed", "turn.failed", "turn.stopped", "operation.failed"}+)+_COMPACTION_TERMINAL_EVENTS = frozenset(+ {+ "compaction.completed",+ "compaction.failed",+ "compaction.stopped",+ "operation.failed",+ }+)+++@dataclass(slots=True)+class _ObservedOperation:+ acknowledgement: ChatOperationAcknowledgement+ subscription: ChatEventSubscriptionPort++ async def aclose(self) -> None:+ await self.subscription.aclose()+++async def _observe_call[**P](+ service: ChatService,+ command: Callable[P, Awaitable[ChatOperationAcknowledgement]],+ *args: P.args,+ **kwargs: P.kwargs,+) -> _ObservedOperation:+ subscription, _active = await service.subscribe()+ try:+ acknowledgement = await command(*args, **kwargs)+ except BaseException:+ await subscription.aclose()+ raise+ return _ObservedOperation(acknowledgement, subscription)+++async def _drain(operation: _ObservedOperation) -> list[str]:+ events: list[str] = []+ terminal_events = (+ _COMPACTION_TERMINAL_EVENTS+ if operation.acknowledgement.kind is ChatOperationKind.COMPACT+ else _TURN_TERMINAL_EVENTS+ )+ try:+ async for event in operation.subscription:+ if event.data.get("operation_id") != operation.acknowledgement.operation_id:+ continue+ assert event.data["kind"] == operation.acknowledgement.kind.value+ events.append(event.event)+ if event.event in terminal_events:+ break+ finally:+ await operation.aclose()return events@@ -292,7 +347,9 @@ async def test_send_streams_and_persists_interleaved_segments(tmp_path: Path):service, runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="b21677f0-aa9a-4acb-b197-64d3dbd56536",@@ -334,7 +391,9 @@ async def test_completion_persistence_exhaustion_never_downgrades_to_failed(return await original_finish_generation(*args, **kwargs)monkeypatch.setattr(store, "finish_generation", unavailable_completion)- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="f69c7c4d-9a46-40f0-b6ad-7f288a2c2dd7",@@ -362,7 +421,9 @@ async def test_regeneration_retries_an_ambiguous_terminal_commit(service, _runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- initial = await service.send(+ initial = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="e8476211-c6a1-45c4-a463-b7d92bfcc7d8",@@ -388,7 +449,9 @@ async def test_regeneration_retries_an_ambiguous_terminal_commit("finish_regeneration",ambiguous_finish_regeneration,)- replacement = await service.regenerate(+ replacement = await _observe_call(+ service,+ service.regenerate,session.id,expected_revision=before.session.revision,operation_id="8a99c4a9-e4f5-4ebd-a8c9-982a9227a557",@@ -413,7 +476,9 @@ async def test_failed_regeneration_replaces_original_with_failed_generation(service, _runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- initial = await service.send(+ initial = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="01355e92-06c4-4820-b80a-fc8e0dff2553",@@ -458,7 +523,9 @@ async def test_failed_regeneration_replaces_original_with_failed_generation()monkeypatch.setattr(provider, "stream_messages", failing_stream)- replacement = await service.regenerate(+ replacement = await _observe_call(+ service,+ service.regenerate,session.id,expected_revision=before.session.revision,operation_id="810b8d15-adab-4df6-9084-3189ca534d09",@@ -483,7 +550,9 @@ async def test_stopped_regeneration_retries_an_ambiguous_discard(service, _runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- initial = await service.send(+ initial = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="14e14878-842d-425a-952c-4e9f105760c0",@@ -516,7 +585,9 @@ async def test_stopped_regeneration_retries_an_ambiguous_discard()provider.started.clear()provider.block_after_delta = True- replacement = await service.regenerate(+ replacement = await _observe_call(+ service,+ service.regenerate,session.id,expected_revision=before.session.revision,operation_id="19cbb991-38ff-4cd2-a20e-f94783f78003",@@ -540,23 +611,39 @@ async def test_stopped_regeneration_retries_an_ambiguous_discard(@pytest.mark.asyncio-async def test_closing_initiating_stream_cancels_and_persists_partial_answer(+async def test_closing_subscription_does_not_cancel_active_operation(tmp_path: Path,):provider = FakeChatProvider(block_after_delta=True)service, runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="9781df8c-aa92-422e-97d9-e9ea7f542b89",text="hello",)- collector = asyncio.create_task(_drain(stream))await asyncio.wait_for(provider.started.wait(), timeout=1)await stream.aclose()- events = await asyncio.wait_for(collector, timeout=1)++ assert runtime.leases[0].released == 0+ assert provider.closed == 0++ replacement_subscription, active_operations = await service.subscribe()+ assert [active.operation_id for active in active_operations] == [+ stream.acknowledgement.operation_id+ ]+ replacement_observer = _ObservedOperation(+ stream.acknowledgement, replacement_subscription+ )+ assert await service.stop(+ session.id,+ operation_id=stream.acknowledgement.operation_id,+ )+ events = await asyncio.wait_for(_drain(replacement_observer), timeout=1)generation = (await store.get_transcript(session.id)).turns[0].generationassert events[-1] == "turn.stopped"@@ -578,7 +665,9 @@ async def test_stop_retries_transient_terminal_persistence_failure(try:session = await service.create_session()operation_id = "3a1c071f-f558-4be3-a072-f9af230352ec"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -604,10 +693,14 @@ async def test_stop_retries_transient_terminal_persistence_failure(transcript = await store.get_transcript(session.id)assert attempts == 2assert transcript.turns[-1].generation.status is GenerationStatus.STOPPED- assert (await service.get_detail(session.id)).active_operation is False+ snapshot_subscription, active_operations = await service.subscribe()+ await snapshot_subscription.aclose()+ assert active_operations == ()provider.block_after_delta = False- replacement = await service.send(+ replacement = await _observe_call(+ service,+ service.send,session.id,expected_revision=transcript.session.revision,operation_id="f5190fdb-ce16-402d-a5a2-1633ba0cae55",@@ -628,7 +721,9 @@ async def test_stop_retries_transient_terminal_segment_flush(try:session = await service.create_session()operation_id = "242841f6-d826-48b5-9ed7-bf073b17840e"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -671,7 +766,9 @@ async def test_terminal_persistence_failure_disables_chat_instead_of_lying(try:session = await service.create_session()operation_id = "f744570e-0ec6-4f70-b74d-19de6bc60547"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -719,7 +816,9 @@ async def test_immediate_stop_before_operation_task_starts_releases_owner(try:session = await service.create_session()operation_id = "2029b65e-f4d9-4b80-8c6a-563a32fb8b8f"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -727,9 +826,11 @@ async def test_immediate_stop_before_operation_task_starts_releases_owner()assert await service.stop(session.id, operation_id=operation_id) is True- assert await _drain(stream) == []+ assert (await _drain(stream))[-1] == "turn.stopped"- replacement = await service.send(+ replacement = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="4b50506e-92bf-46ba-aa35-333dc0946e14",@@ -756,7 +857,9 @@ async def test_ambiguous_generation_start_adopts_the_committed_owner(raise ChatUnavailableError("Chat commit result was unavailable.")monkeypatch.setattr(store, "begin_send", ambiguous_begin_send)- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="cc47acc3-d7c2-46d0-a1b6-fe2acda191e4",@@ -779,7 +882,7 @@ async def test_ambiguous_generation_start_adopts_the_committed_owner(@pytest.mark.asyncio-async def test_disconnect_cannot_interrupt_failure_terminalization(+async def test_disconnect_does_not_interrupt_failure_terminalization(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,):@@ -838,7 +941,9 @@ async def test_disconnect_cannot_interrupt_failure_terminalization()session = await service.create_session()operation_id = "63523531-024d-47f2-a0ce-ff7104d4e3af"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -846,13 +951,14 @@ async def test_disconnect_cannot_interrupt_failure_terminalization()await asyncio.wait_for(entered_flush.wait(), timeout=1)- close_task = asyncio.create_task(stream.aclose())- await asyncio.sleep(0.05)- assert not close_task.done()+ await stream.aclose()+ replacement_subscription, _active = await service.subscribe()+ replacement_observer = _ObservedOperation(+ stream.acknowledgement, replacement_subscription+ )release_flush.set()- await asyncio.wait_for(close_task, timeout=1)- assert (await _drain(stream))[-1] == "turn.failed"+ assert (await _drain(replacement_observer))[-1] == "turn.failed"generation = (await store.get_transcript(session.id)).turns[0].generationassert generation.status is GenerationStatus.FAILEDassert await service.stop(session.id, operation_id=operation_id) is False@@ -868,7 +974,9 @@ async def test_second_operation_on_same_session_is_rejected(tmp_path: Path):service, _runtime, _store = await _service(tmp_path, provider)try:session = await service.create_session()- first = await service.send(+ first = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="3e363fbc-25ee-414e-a954-02d11990497f",@@ -877,7 +985,9 @@ async def test_second_operation_on_same_session_is_rejected(tmp_path: Path):await asyncio.wait_for(provider.started.wait(), timeout=1)running = await service.get_session(session.id)with pytest.raises(ChatConflictError, match="active operation"):- await service.send(+ await _observe_call(+ service,+ service.send,session.id,expected_revision=running.revision,operation_id="223ad9ac-e830-42ec-b73d-b1cbd81511c4",@@ -888,6 +998,61 @@ async def test_second_operation_on_same_session_is_rejected(tmp_path: Path):await service.close()+async def test_durable_mutations_publish_once_and_stale_mutation_publishes_nothing(+ tmp_path: Path,+):+ service, _runtime, _store = await _service(tmp_path, FakeChatProvider())+ subscription, active_operations = await service.subscribe()+ assert active_operations == ()+ events = subscription.__aiter__()+ try:+ session = await service.create_session()+ created = await anext(events)++ with pytest.raises(ChatConflictError, match="another tab"):+ await service.update_session(+ session.id,+ expected_revision=session.revision + 10,+ title="Stale title",+ model=None,+ reasoning=None,+ )++ updated = await service.update_session(+ session.id,+ expected_revision=session.revision,+ title="Durable title",+ model=None,+ reasoning=None,+ )+ update_event = await anext(events)+ preferences = await service.save_system_prompt("Shared prompt")+ preferences_event = await anext(events)+ await service.delete_session(+ session.id,+ expected_revision=updated.revision,+ )+ deleted = await anext(events)++ assert [+ (created.id, created.event),+ (update_event.id, update_event.event),+ (preferences_event.id, preferences_event.event),+ (deleted.id, deleted.event),+ ] == [+ (1, "session.created"),+ (2, "session.updated"),+ (3, "preferences.updated"),+ (4, "session.deleted"),+ ]+ assert update_event.data["revision"] == updated.revision+ assert preferences_event.data["updated_at"] == preferences.updated_at+ finally:+ await subscription.aclose()+ await service.close()++@pytest.mark.asyncioasync def test_delete_validates_stale_revision_before_cancelling_active_send(tmp_path: Path,@@ -897,7 +1062,9 @@ async def test_delete_validates_stale_revision_before_cancelling_active_send(try:session = await service.create_session()operation_id = "3b4390e2-bbd0-499a-94c5-d7813b1d5f75"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -928,7 +1095,9 @@ async def test_delete_active_send_finishes_generation_before_removing_session(service, _runtime, _store = await _service(tmp_path, provider)try:session = await service.create_session()- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="0162e7e5-aabd-4ffb-ae50-ed864825ec71",@@ -956,7 +1125,9 @@ async def test_cancellation_waits_for_generation_start_commit_before_cleanup(blocker: sqlite3.Connection | None = Nonetry:session = await service.create_session()- initial_stream = await service.send(+ initial_stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="7f4c7a3f-c06e-42c3-9887-f748dc5aa518",@@ -982,7 +1153,9 @@ async def test_cancellation_waits_for_generation_start_commit_before_cleanup(blocker.execute("BEGIN IMMEDIATE")current = await service.get_session(session.id)- retry_stream = await service.retry(+ retry_stream = await _observe_call(+ service,+ service.retry,session.id,expected_revision=current.revision,operation_id="38dcb3e5-04b7-4ecf-bc8b-7c72550839b0",@@ -990,13 +1163,19 @@ async def test_cancellation_waits_for_generation_start_commit_before_cleanup(await asyncio.wait_for(entered.wait(), timeout=1)await asyncio.sleep(0.05)- close_task = asyncio.create_task(retry_stream.aclose())+ stop_task = asyncio.create_task(+ service.stop(+ session.id,+ operation_id=retry_stream.acknowledgement.operation_id,+ )+ )await asyncio.sleep(0.05)- waited_for_commit = not close_task.done()+ waited_for_commit = not stop_task.done()blocker.commit()blocker.close()blocker = None- await asyncio.wait_for(close_task, timeout=1)+ assert await asyncio.wait_for(stop_task, timeout=1) is True+ assert (await _drain(retry_stream))[-1] == "turn.stopped"generation = (await store.get_transcript(session.id)).turns[-1].generationassert waited_for_commit@@ -1019,7 +1198,9 @@ async def test_repeated_cancellation_waits_for_terminal_cleanup(try:session = await service.create_session()operation_id = "f02c0da7-1ec9-4433-bef3-dc760753e451"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1043,20 +1224,23 @@ async def test_repeated_cancellation_waits_for_terminal_cleanup(blocker.execute("PRAGMA journal_mode = WAL")blocker.execute("BEGIN IMMEDIATE")- close_task = asyncio.create_task(stream.aclose())+ first_stop_task = asyncio.create_task(+ service.stop(session.id, operation_id=operation_id)+ )await asyncio.wait_for(entered_cleanup.wait(), timeout=1)- stop_task = asyncio.create_task(+ second_stop_task = asyncio.create_task(service.stop(session.id, operation_id=operation_id))await asyncio.sleep(0.05)- assert not close_task.done()- assert not stop_task.done()+ assert not first_stop_task.done()+ assert not second_stop_task.done()blocker.commit()blocker.close()blocker = None- await asyncio.wait_for(close_task, timeout=1)- assert await asyncio.wait_for(stop_task, timeout=1) is True+ assert await asyncio.wait_for(first_stop_task, timeout=1) is True+ assert await asyncio.wait_for(second_stop_task, timeout=1) is True+ assert (await _drain(stream))[-1] == "turn.stopped"generation = (await store.get_transcript(session.id)).turns[0].generationassert generation.status is GenerationStatus.STOPPED@@ -1088,7 +1272,9 @@ async def test_stop_at_generation_commit_preserves_completed_result(monkeypatch.setattr(store, "finish_generation", observed_finish_generation)session = await service.create_session()operation_id = "03ba5dce-bd47-452c-a878-229d4df65944"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1099,11 +1285,9 @@ async def test_stop_at_generation_commit_preserves_completed_result(stop_task = asyncio.create_task(service.stop(session.id, operation_id=operation_id))- await asyncio.sleep(0.05)- assert not stop_task.done()+ assert await asyncio.wait_for(stop_task, timeout=1) is Falserelease_commit.set()- assert await asyncio.wait_for(stop_task, timeout=1) is Trueevents = await _drain(stream)generation = (await store.get_transcript(session.id)).turns[0].generationassert events[-1] == "turn.completed"@@ -1112,6 +1296,390 @@ async def test_stop_at_generation_commit_preserves_completed_result(await service.close()+async def test_snapshot_never_advertises_unpublished_terminal_sequence(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ service, _runtime, _store = await _service(tmp_path, FakeChatProvider())+ release_terminal = asyncio.Event()+ late_subscription: ChatEventSubscriptionPort | None = None+ fresh_subscription: ChatEventSubscriptionPort | None = None+ try:+ entered_terminal = asyncio.Event()+ original_release_active = service._release_active++ async def observed_release_active(active):+ entered_terminal.set()+ await release_terminal.wait()+ return await original_release_active(active)++ monkeypatch.setattr(service, "_release_active", observed_release_active)+ session = await service.create_session()+ operation_id = "025295bc-d2f5-4208-9dab-ed507471fb33"+ stream = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=session.revision,+ operation_id=operation_id,+ text="publish this terminal event",+ )+ await asyncio.wait_for(entered_terminal.wait(), timeout=1)++ late_subscription, active = await service.subscribe()+ assert len(active) == 1+ assert active[0].operation_id == operation_id+ snapshot_sequence = active[0].operation_sequence++ release_terminal.set()+ late_events = late_subscription.__aiter__()+ terminal = await asyncio.wait_for(anext(late_events), timeout=1)+ assert terminal.event == "turn.completed"+ assert terminal.data["operation_sequence"] == snapshot_sequence + 1+ assert (await _drain(stream))[-1] == "turn.completed"++ fresh_subscription, current_active = await service.subscribe()+ assert current_active == ()+ finally:+ release_terminal.set()+ if late_subscription is not None:+ await late_subscription.aclose()+ if fresh_subscription is not None:+ await fresh_subscription.aclose()+ await service.close()+++async def test_stop_after_completed_regeneration_cannot_discard_result(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ service, _runtime, store = await _service(tmp_path, FakeChatProvider())+ release_terminal = asyncio.Event()+ try:+ session = await service.create_session()+ initial = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=session.revision,+ operation_id="25362cff-95ae-4051-9d15-36317753eb29",+ text="replace this answer",+ )+ await _drain(initial)+ before = await store.get_transcript(session.id)++ entered_terminal = asyncio.Event()+ original_release_active = service._release_active++ async def observed_release_active(active):+ entered_terminal.set()+ await release_terminal.wait()+ return await original_release_active(active)++ discarded = 0+ original_discard_generation = store.discard_generation++ async def observed_discard_generation(*args, **kwargs):+ nonlocal discarded+ discarded += 1+ return await original_discard_generation(*args, **kwargs)++ monkeypatch.setattr(service, "_release_active", observed_release_active)+ monkeypatch.setattr(store, "discard_generation", observed_discard_generation)+ operation_id = "a2f69564-3eb5-4805-8578-2be42d710e5a"+ replacement = await _observe_call(+ service,+ service.regenerate,+ session.id,+ expected_revision=before.session.revision,+ operation_id=operation_id,+ )+ await asyncio.wait_for(entered_terminal.wait(), timeout=1)++ assert await service.stop(session.id, operation_id=operation_id) is False+ release_terminal.set()+ assert (await _drain(replacement))[-1] == "turn.completed"++ after = await store.get_transcript(session.id)+ assert discarded == 0+ assert after.turns[-1].generation.status is GenerationStatus.COMPLETED+ assert service.availability()[0] is True+ finally:+ release_terminal.set()+ await service.close()+++async def test_delete_waits_for_terminal_settlement_before_removing_session(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ service, _runtime, store = await _service(tmp_path, FakeChatProvider())+ release_commit = asyncio.Event()+ try:+ entered_commit = asyncio.Event()+ original_finish_generation = store.finish_generation++ async def observed_finish_generation(*args, **kwargs):+ entered_commit.set()+ await release_commit.wait()+ return await original_finish_generation(*args, **kwargs)++ monkeypatch.setattr(store, "finish_generation", observed_finish_generation)+ session = await service.create_session()+ stream = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=session.revision,+ operation_id="77a5fc8a-6043-49f9-a291-b0545bd47ed8",+ text="finish before deletion",+ )+ await asyncio.wait_for(entered_commit.wait(), timeout=1)+ running = await service.get_session(session.id)++ delete_task = asyncio.create_task(+ service.delete_session(session.id, expected_revision=running.revision)+ )+ await asyncio.sleep(0.05)+ assert not delete_task.done()+ release_commit.set()+ await asyncio.wait_for(delete_task, timeout=1)++ with pytest.raises(ChatNotFoundError):+ await service.get_session(session.id)+ await stream.aclose()+ finally:+ release_commit.set()+ await service.close()+++async def test_cancelled_delete_request_still_finishes_accepted_deletion(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ provider = FakeChatProvider(block_after_delta=True)+ service, _runtime, store = await _service(tmp_path, provider)+ release_settlement = asyncio.Event()+ subscription: ChatEventSubscriptionPort | None = None+ try:+ entered_settlement = asyncio.Event()+ original_finish_generation = store.finish_generation++ async def observed_finish_generation(*args, **kwargs):+ entered_settlement.set()+ await release_settlement.wait()+ return await original_finish_generation(*args, **kwargs)++ monkeypatch.setattr(store, "finish_generation", observed_finish_generation)+ session = await service.create_session()+ subscription, _active = await service.subscribe()+ operation_id = "cd352568-fefd-4324-8062-9dadc4efbba6"+ await service.send(+ session.id,+ expected_revision=session.revision,+ operation_id=operation_id,+ text="delete this chat",+ )+ await asyncio.wait_for(provider.started.wait(), timeout=1)+ running = await service.get_session(session.id)++ request_task = asyncio.create_task(+ service.delete_session(session.id, expected_revision=running.revision)+ )+ await asyncio.wait_for(entered_settlement.wait(), timeout=1)+ request_task.cancel()+ await asyncio.sleep(0.05)+ assert not request_task.done()++ release_settlement.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(request_task, timeout=1)+ with pytest.raises(ChatNotFoundError):+ await service.get_session(session.id)++ events = subscription.__aiter__()+ while True:+ event = await asyncio.wait_for(anext(events), timeout=1)+ if event.event == "session.deleted":+ break+ fresh_subscription, active = await service.subscribe()+ try:+ assert active == ()+ finally:+ await fresh_subscription.aclose()+ finally:+ release_settlement.set()+ if subscription is not None:+ await subscription.aclose()+ await service.close()+++async def test_close_waits_for_terminal_settlement(tmp_path: Path, monkeypatch):+ service, _runtime, store = await _service(tmp_path, FakeChatProvider())+ release_commit = asyncio.Event()+ service_closed = False+ reopened: SQLiteChatStore | None = None+ try:+ entered_commit = asyncio.Event()+ original_finish_generation = store.finish_generation++ async def observed_finish_generation(*args, **kwargs):+ entered_commit.set()+ await release_commit.wait()+ return await original_finish_generation(*args, **kwargs)++ monkeypatch.setattr(store, "finish_generation", observed_finish_generation)+ session = await service.create_session()+ stream = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=session.revision,+ operation_id="aa6d0128-de80-43ff-ab8c-aa1f7c4bf5ba",+ text="finish before shutdown",+ )+ await asyncio.wait_for(entered_commit.wait(), timeout=1)++ close_task = asyncio.create_task(service.close())+ await asyncio.sleep(0.05)+ assert not close_task.done()+ release_commit.set()+ await asyncio.wait_for(close_task, timeout=1)+ service_closed = True+ await stream.aclose()++ reopened = SQLiteChatStore(tmp_path / "chat.db", tmp_path / "chat.lock")+ await reopened.start()+ transcript = await reopened.get_transcript(session.id)+ assert transcript.turns[-1].generation.status is GenerationStatus.COMPLETED+ finally:+ release_commit.set()+ if reopened is not None:+ await reopened.close()+ if not service_closed:+ await service.close()+++async def test_cancelled_stop_waiter_does_not_cancel_supervisor(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ provider = FakeChatProvider(block_after_delta=True)+ service, _runtime, store = await _service(tmp_path, provider)+ release_settlement = asyncio.Event()+ try:+ entered_settlement = asyncio.Event()+ original_finish_generation = store.finish_generation++ async def observed_finish_generation(*args, **kwargs):+ entered_settlement.set()+ await release_settlement.wait()+ return await original_finish_generation(*args, **kwargs)++ monkeypatch.setattr(store, "finish_generation", observed_finish_generation)+ session = await service.create_session()+ operation_id = "13d97a77-aef0-4f2c-8415-1525ab70c427"+ stream = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=session.revision,+ operation_id=operation_id,+ text="stop independently of this request",+ )+ await asyncio.wait_for(provider.started.wait(), timeout=1)++ stop_task = asyncio.create_task(+ service.stop(session.id, operation_id=operation_id)+ )+ await asyncio.wait_for(entered_settlement.wait(), timeout=1)+ stop_task.cancel()+ await asyncio.sleep(0.05)+ assert not stop_task.done()++ release_settlement.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(stop_task, timeout=1)+ assert (await _drain(stream))[-1] == "turn.stopped"+ transcript = await store.get_transcript(session.id)+ assert transcript.turns[-1].generation.status is GenerationStatus.STOPPED+ finally:+ release_settlement.set()+ await service.close()+++async def test_terminal_event_precedes_best_effort_summary(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ service, _runtime, store = await _service(tmp_path, FakeChatProvider())+ release_summary = asyncio.Event()+ fresh_subscription: ChatEventSubscriptionPort | None = None+ try:+ entered_summary = asyncio.Event()+ blocked_summary = False+ original_get_session_summary = store.get_session_summary++ async def observed_get_session_summary(session_id: str):+ nonlocal blocked_summary+ transcript = await store.get_transcript(session_id)+ completed = bool(+ transcript.turns+ and transcript.turns[-1].generation.status is GenerationStatus.COMPLETED+ )+ if completed and not blocked_summary:+ blocked_summary = True+ entered_summary.set()+ await release_summary.wait()+ raise ChatUnavailableError("Summary read failed.")+ return await original_get_session_summary(session_id)++ monkeypatch.setattr(+ store,+ "get_session_summary",+ observed_get_session_summary,+ )+ session = await service.create_session()+ stream = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=session.revision,+ operation_id="526be960-a16f-4d83-8f02-d51568003b60",+ text="publish before the summary",+ )++ assert (await _drain(stream))[-1] == "turn.completed"+ await asyncio.wait_for(entered_summary.wait(), timeout=1)+ fresh_subscription, active = await service.subscribe()+ assert active == ()++ current = await service.get_session(session.id)+ next_stream = await _observe_call(+ service,+ service.send,+ session.id,+ expected_revision=current.revision,+ operation_id="ee7985a6-adf8-454f-9785-53d13c4eef8d",+ text="start while the old summary waits",+ )+ release_summary.set()+ assert (await _drain(next_stream))[-1] == "turn.completed"+ assert service.availability()[0] is True+ finally:+ release_summary.set()+ if fresh_subscription is not None:+ await fresh_subscription.aclose()+ await service.close()++@pytest.mark.asyncioasync def test_detail_snapshot_keeps_operation_owner_visible_through_completion(tmp_path: Path,@@ -1135,7 +1703,9 @@ async def test_detail_snapshot_keeps_operation_owner_visible_through_completion(monkeypatch.setattr(store, "finish_generation", observed_finish_generation)session = await service.create_session()- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="9e34cdcb-3d56-44f2-8921-a5d43cb0ed20",@@ -1161,7 +1731,7 @@ async def test_detail_snapshot_keeps_operation_owner_visible_through_completion(detail = await asyncio.wait_for(detail_task, timeout=1)await _drain(stream)- assert detail.active_operation is True+ assert not hasattr(detail, "active_operation")assert detail.session.revision > session.revisionfinally:release_commit.set()@@ -1170,7 +1740,7 @@ async def test_detail_snapshot_keeps_operation_owner_visible_through_completion(@pytest.mark.asyncio-async def test_cancellation_while_release_waits_cannot_strand_operation_owner(+async def test_terminal_event_releases_owner_while_an_older_detail_read_waits(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,):@@ -1190,7 +1760,9 @@ async def test_cancellation_while_release_waits_cannot_strand_operation_owner(monkeypatch.setattr(store, "finish_generation", observed_finish_generation)session = await service.create_session()operation_id = "7f4dcfd1-bc69-4df1-9737-f434d357133a"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1211,20 +1783,20 @@ async def test_cancellation_while_release_waits_cannot_strand_operation_owner(await asyncio.wait_for(entered_snapshot.wait(), timeout=1)release_commit.set()- events = stream.__aiter__()- while (- await asyncio.wait_for(anext(events), timeout=1)- ).event != "turn.completed":- pass-- close_task = asyncio.create_task(stream.aclose())- await asyncio.sleep(0)+ assert (await asyncio.wait_for(_drain(stream), timeout=1))[-1] == (+ "turn.completed"+ )release_snapshot.set()- await asyncio.wait_for(detail_task, timeout=1)- await asyncio.wait_for(close_task, timeout=1)+ older_detail = await asyncio.wait_for(detail_task, timeout=1)+ assert not hasattr(older_detail, "active_operation")++ current_detail = await service.get_detail(session.id)+ assert not hasattr(current_detail, "active_operation")current = await service.get_session(session.id)- next_stream = await service.send(+ next_stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=current.revision,operation_id="87f5dd83-ee78-48d8-82f5-b65cd91034fc",@@ -1245,7 +1817,9 @@ async def test_disconnect_after_durable_completion_cannot_downgrade_status(service, _runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="80354cee-d3b1-4760-963f-9cc7a1558ffc",@@ -1289,7 +1863,9 @@ async def test_stop_during_compaction_commit_waits_and_reports_completion("35d15a22-88e4-476f-aec2-9c0cdfb5cb87",)):- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1311,7 +1887,9 @@ async def test_stop_during_compaction_commit_waits_and_reports_completion(blocker.execute("BEGIN IMMEDIATE")operation_id = "b15f0721-acd3-482f-812d-28d2d3cc568b"- compact = await service.compact(+ compact = await _observe_call(+ service,+ service.compact,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1320,13 +1898,11 @@ async def test_stop_during_compaction_commit_waits_and_reports_completion(stop_task = asyncio.create_task(service.stop(session.id, operation_id=operation_id))- await asyncio.sleep(0.05)- assert not stop_task.done()+ assert await asyncio.wait_for(stop_task, timeout=1) is Falseblocker.commit()blocker.close()blocker = None- assert await asyncio.wait_for(stop_task, timeout=1) is Trueevents = await _drain(compact)transcript = await store.get_transcript(session.id)@@ -1353,7 +1929,9 @@ async def test_compaction_retries_an_ambiguous_commit_once(("110ce497-5d5f-4659-b2c7-7ae4bf362900", "first"),("64de0c33-c956-4ac2-b172-9f9fc5caf13b", "second"),):- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1375,7 +1953,9 @@ async def test_compaction_retries_an_ambiguous_commit_once(return resultmonkeypatch.setattr(store, "upsert_compaction", ambiguous_upsert_compaction)- compact = await service.compact(+ compact = await _observe_call(+ service,+ service.compact,session.id,expected_revision=session.revision,operation_id="861cba8a-fca4-47eb-84cb-de1a7059714c",@@ -1399,7 +1979,9 @@ async def test_manual_compaction_keeps_full_transcript_and_adds_checkpoint(service, _runtime, store = await _service(tmp_path, provider)try:session = await service.create_session()- first = await service.send(+ first = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="e90f819b-a835-4c1f-80d7-6e7c17c429a7",@@ -1407,7 +1989,9 @@ async def test_manual_compaction_keeps_full_transcript_and_adds_checkpoint()await _drain(first)session = await service.get_session(session.id)- second = await service.send(+ second = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="8de64c2a-34c8-4b30-a880-37d3678c62de",@@ -1415,7 +1999,9 @@ async def test_manual_compaction_keeps_full_transcript_and_adds_checkpoint()await _drain(second)session = await service.get_session(session.id)- compact = await service.compact(+ compact = await _observe_call(+ service,+ service.compact,session.id,expected_revision=session.revision,operation_id="b5c9bc6f-3b74-4218-bac5-17b6813f443a",@@ -1442,7 +2028,9 @@ async def test_manual_compaction_rejects_incomplete_summary_stream(tmp_path: Pat("560c7a0f-c074-489b-8b90-e7e031577716", "first"),("d77427c1-8417-4ab5-a380-94860c778db8", "second"),):- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1451,7 +2039,9 @@ async def test_manual_compaction_rejects_incomplete_summary_stream(tmp_path: Patawait _drain(stream)session = await service.get_session(session.id)- compact = await service.compact(+ compact = await _observe_call(+ service,+ service.compact,session.id,expected_revision=session.revision,operation_id="8895d9ae-c896-4af2-be44-d6328e1da736",@@ -1481,7 +2071,9 @@ async def test_send_auto_compacts_without_removing_original_turns(tmp_path: Path"3a4f8108-2cf4-45c1-b412-56a8551e7f8b",)for operation_id in operation_ids:- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1490,7 +2082,9 @@ async def test_send_auto_compacts_without_removing_original_turns(tmp_path: Pathawait _drain(stream)session = await service.get_session(session.id)- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id="195faf19-ea0a-4633-ad81-a09734f5e17c",@@ -1527,7 +2121,9 @@ async def test_stop_during_auto_compaction_commit_keeps_checkpoint_without_new_t"79cd9bd9-df33-4ed4-8a5c-5e34770a30f7","71ac3c34-7be1-4c26-b69e-f6f7193fa353",):- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,@@ -1549,7 +2145,9 @@ async def test_stop_during_auto_compaction_commit_keeps_checkpoint_without_new_tblocker.execute("BEGIN IMMEDIATE")operation_id = "443b12d9-8989-4bb5-a609-c9c2c0e2ecf5"- stream = await service.send(+ stream = await _observe_call(+ service,+ service.send,session.id,expected_revision=session.revision,operation_id=operation_id,diff --git a/tests/runtime/test_chat_sqlite.py b/tests/runtime/test_chat_sqlite.pyindex 120d466b..e49c589a 100644--- a/tests/runtime/test_chat_sqlite.py+++ b/tests/runtime/test_chat_sqlite.py@@ -52,6 +52,7 @@ async def test_store_creates_schema_preferences_and_searchable_sessions(tmp_pathpage = await store.list_sessions(query="CAFÉ", cursor=None, limit=25)assert [session.id for session in page.sessions] == [renamed.id]+ assert await store.get_session_summary(renamed.id) == page.sessions[0]assert (await store.load_preferences()).last_model == second.modelfinally:await store.close()diff --git a/uv.lock b/uv.lockindex d8480b83..d9e2030a 100644--- a/uv.lock+++ b/uv.lock@@ -598,7 +598,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "5.18.11"+version = "5.19.0"source = { editable = "." }dependencies = [{ name = "aiohttp" },