The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): store a delivered reply before announcing it
Shanu77a47dbd0b09
diff --git a/.claude/memory.md b/.claude/memory.mdindex 185673b018..57427175af 100644--- a/.claude/memory.md+++ b/.claude/memory.md@@ -4,6 +4,8 @@ Quick reference for anyone starting with Claude on this project. Updated by the## Fixes & Gotchas+- **Who persists a chat reply (issue #6034)** — the core writes an unsegmented reply to the conversation store under `agent:<request_id>` **before** it publishes `chat_done` (`web_chat::presentation::deliver_response` → `web_chat::reply_persistence`), and the frontend's `addInferenceResponse` reuses that id so the store's idempotency collapses the two writes onto one row. Before this the frontend was the *only* persister of an interactive reply, so a failed `threads_message_append`, a socket reconnect (which issues a new `client_id`, leaving only the `thread:<id>` room as a route) or a webview reload lost the answer from screen and disk while the agent's session history still held it. Two rules follow: any new `chat_done` append site must pass `deliveredReplyMessageId(event)` or the thread gets two copies of one answer (#5933 again), and a **segmented** delivery is the exception — the client owns one row per segment there, so the core stores nothing and the ids stay generated.+- **`deliver_response` does not segment any more** — `presentation.rs` sets `let segments = [full_response.to_string()]` unconditionally, so the multi-segment branch (and every `chat_segment` event) is dead on the interactive path; the segmentation helpers survive for channel callers and tests. Read that binding before reasoning about `segment_total`, which is never set in practice today.- **macOS close button does not dismiss window (issue #2049)** — `WebviewWindow::hide()` routes through CEF's `WindowMessage::Hide` → `cef::Window::hide()` which does NOT propagate to the visible NSWindow frame. Fix: use `AppHandle::hide()` which calls `[NSApp hide:]` via `set_application_visibility(false)`. This is macOS-only (`#[cfg(target_os = "macos")]`); the `CloseRequested` handlers are in `app/src-tauri/src/lib.rs` (grep `WindowEvent::CloseRequested` — line numbers drift). PR #2118.- **ServiceBlockingGate CORS errors** — The gate calls `openhumanServiceStatus()` and `openhumanAgentServerStatus()` at startup. These used `callCoreRpc()` which falls back to raw `fetch()` when socket isn't connected yet, causing CORS errors. Fix: route through `invoke('core_rpc_relay')` instead (Tauri IPC, no CORS).- **Socket not connected at startup** — `SocketProvider` only connects when a Redux `auth.token` is set. At fresh launch (no token), socket is null, so any `callCoreRpc()` call falls back to `fetch()`. Always use `invoke('core_rpc_relay')` for local sidecar RPC calls.diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsxindex 65d0d82d3d..0ec2b40321 100644--- a/app/src/providers/ChatRuntimeProvider.tsx+++ b/app/src/providers/ChatRuntimeProvider.tsx@@ -28,6 +28,7 @@ import {segmentText,subscribeChatEvents,} from '../services/chatService';+import { socketService } from '../services/socketService';import { store } from '../store';import {appendSubagentStreamDelta,@@ -74,6 +75,7 @@ import {clearThreadInferenceActive,createNewThread,generateThreadTitleIfNeeded,+ loadThreadMessages,setActiveThread,setSelectedThread,} from '../store/threadSlice';@@ -238,6 +240,28 @@ function corePersistedMessageId(event: {return event.client_id === 'system' && event.request_id ? `agent:${event.request_id}` : undefined;}+/**+ * Message id for a delivered reply, shared with the core.+ *+ * Since #6034 the core stores an unsegmented reply before it announces it, on+ * every surface that carries a workspace — interactive turns and forked lanes,+ * not just the core-initiated ones {@link corePersistedMessageId} covers. Both+ * writers therefore derive the id from the same `request_id`, which is what+ * makes our append collapse onto the core's row rather than add a second copy+ * of the answer (#5933).+ *+ * A segmented `chat_done` is excluded on purpose: the core leaves those rows to+ * us (one per segment), so there is nothing to collapse onto and a shared id+ * would make several segments fight over one row.+ */+function deliveredReplyMessageId(event: {+ request_id?: string;+ segment_total?: number | null;+}): string | undefined {+ if (event.segment_total) return undefined;+ return event.request_id ? `agent:${event.request_id}` : undefined;+}+/*** Map a `chat_done` event's holistic usage onto the `recordChatTurnUsage`* payload. Prefers the structured `usage` object (tokens + cost + context window@@ -310,6 +334,9 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {// (#4273, AC3). Single instance for the provider's lifetime; observability// only — it never gates or cancels a turn.const skillLatencyRef = useRef(createSkillToolChainLatencyTracker());+ // Threads that had a turn in flight when the socket dropped, held across the+ // gap so the reconnect can rejoin their rooms and re-read them (#6034).+ const interruptedThreadsRef = useRef<Set<string>>(new Set());useEffect(() => {toolTimelineRef.current = toolTimelineByThread;@@ -474,6 +501,55 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {}};+ /**+ * Put a delivered reply back on screen after our own append failed.+ *+ * Since #6034 the core stores an unsegmented reply before it announces it,+ * so a failed `threads_message_append` is almost always a lost *render*+ * rather than a lost answer: re-reading the thread brings the core's row+ * into the cache and the reply appears without the user re-asking.+ *+ * The residual case — neither writer stored it — is reported at error+ * level rather than through the dev-only debug channel. It cannot be+ * surfaced as an in-thread message, because writing one needs the same+ * append that just failed.+ */+ const recoverDeliveredReply = async (event: ChatDoneEvent, cause: unknown) => {+ const expectedId = deliveredReplyMessageId(event);+ try {+ await dispatch(loadThreadMessages(event.thread_id)).unwrap();+ } catch (refetchError) {+ console.error(+ '[chat-runtime] a delivered reply could not be appended or re-read; it may be missing from this thread',+ {+ threadId: event.thread_id,+ requestId: event.request_id,+ appendError: cause instanceof Error ? cause.message : String(cause),+ refetchError:+ refetchError instanceof Error ? refetchError.message : String(refetchError),+ }+ );+ return;+ }+ const recovered = expectedId+ ? (store.getState().thread.messagesByThreadId[event.thread_id] ?? []).some(+ m => m.id === expectedId+ )+ : false;+ if (recovered) {+ rtLog('chat_done_recovered_from_store', {+ thread: event.thread_id,+ request: event.request_id,+ });+ return;+ }+ console.error('[chat-runtime] a delivered reply is absent from the thread after a refetch', {+ threadId: event.thread_id,+ requestId: event.request_id,+ appendError: cause instanceof Error ? cause.message : String(cause),+ });+ };+const finishChatDoneTurn = async (event: ChatDoneEvent, path: string) => {rtLog('refresh_usage_counter', {thread: event.thread_id,@@ -1148,6 +1224,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {addInferenceResponse({content: event.full_response,threadId: event.thread_id,+ messageId: deliveredReplyMessageId(event),extraMetadata: chatDoneExtraMetadata(event),})).unwrap();@@ -1163,6 +1240,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {request: event.request_id,error: error instanceof Error ? error.message : String(error),});+ await recoverDeliveredReply(event, error);}})();}@@ -1195,7 +1273,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {addInferenceResponse({content: event.full_response,threadId: event.thread_id,- messageId: corePersistedMessageId(event),+ messageId: deliveredReplyMessageId(event),extraMetadata: chatDoneExtraMetadata(event),})).unwrap();@@ -1211,6 +1289,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {request: event.request_id,error: error instanceof Error ? error.message : String(error),});+ await recoverDeliveredReply(event, error);}await finishChatDoneTurn(event, 'proactive');})();@@ -1446,6 +1525,13 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {const threadIds = Object.keys(lifecycles);const activeThreadIds = Object.keys(state.thread.activeThreadIds);if (threadIds.length === 0 && activeThreadIds.length === 0) return;+ // Remember what was in flight BEFORE the markers are cleared below. The+ // reconnect handler in `socketService` re-subscribes from+ // `activeThreadIds`, which this effect is about to empty — so without this+ // snapshot the new socket rejoins only the selected thread's room, and a+ // turn finishing on any other thread announces itself to a `client_id`+ // that no longer exists (#6034).+ interruptedThreadsRef.current = new Set([...threadIds, ...activeThreadIds]);// Abandon any in-flight tool-chain latency windows: a disconnect tears down// these turns without an onDone/onError, so without this the next tool call// on a reused thread would attribute stale elapsed/tool counts (#4288).@@ -1471,6 +1557,28 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {}}, [socketStatus, dispatch]);+ // Heal the threads a disconnect orphaned, once the socket is back.+ //+ // Two things are wrong at this moment and neither fixes itself. The new+ // socket has a new `client_id`, so the only route left to an in-flight turn+ // is its `thread:<id>` room — and the reconnect handler rejoined just the+ // selected thread. And a turn that finished while we were away announced its+ // `chat_done` to nobody: the reply is on disk (the core stores it before+ // announcing it) but nothing re-reads the thread while the user stays put.+ // Re-subscribe and re-read, so a reply that landed during the gap appears+ // instead of looking lost until the thread is reselected (#6034).+ useEffect(() => {+ if (socketStatus !== 'connected') return;+ const interrupted = interruptedThreadsRef.current;+ if (interrupted.size === 0) return;+ interruptedThreadsRef.current = new Set();+ rtLog('socket_reconnect_heal', { threads: interrupted.size });+ for (const threadId of interrupted) {+ socketService.subscribeThread(threadId);+ void dispatch(loadThreadMessages(threadId));+ }+ }, [socketStatus, dispatch]);+// assistant-ui's runtime is mounted here, INSIDE the subscription provider,// so it sits above every chat surface and below the Redux store this file// already feeds. It is additive: it publishes the runtime context withoutdiff --git a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsxindex 4e90adde69..48e976e1ff 100644--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as chatService from '../../services/chatService';import { threadApi } from '../../services/api/threadApi';+import { socketService } from '../../services/socketService';import { store } from '../../store';import {clearAllChatRuntime,@@ -15,7 +16,12 @@ import {setPendingPlanReviewForThread,} from '../../store/chatRuntimeSlice';import { setStatusForUser } from '../../store/socketSlice';-import { clearAllThreads, loadThreads, setSelectedThread } from '../../store/threadSlice';+import {+ clearAllThreads,+ loadThreads,+ setActiveThread,+ setSelectedThread,+} from '../../store/threadSlice';import ChatRuntimeProvider from '../ChatRuntimeProvider';import { clearAllProactiveThreadPins } from '../proactiveThreadPins';@@ -39,6 +45,8 @@ vi.mock('../../services/api/threadApi', () => ({},}));+vi.mock('../../services/socketService', () => ({ socketService: { subscribeThread: vi.fn() } }));+vi.mock('../../hooks/usageRefresh', () => ({ requestUsageRefresh: vi.fn() }));const mockRefetchSnapshot = vi.fn();@@ -605,7 +613,7 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invariaexpect(threadApi.appendMessage).toHaveBeenCalledTimes(1);});- it('keeps a generated id for an interactive chat_done (nothing else persisted it)', async () => {+ it('mirrors the core id on an interactive chat_done so the two writers collapse (#6034)', async () => {const listeners = renderProvider();act(() => {@@ -617,12 +625,75 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invaria});});+ // The core stores an unsegmented reply before announcing it, so this+ // append must carry the same `agent:<request_id>` id — otherwise the+ // thread ends up with the core's row AND ours, which is #5933 again.await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));const [, persisted] = vi.mocked(threadApi.appendMessage).mock.calls[0];- expect(persisted.id).not.toBe('agent:r-user');+ expect(persisted.id).toBe('agent:r-user');expect(persisted.sender).toBe('agent');});+ it('keeps a generated id for a segmented chat_done (the core left those rows to us)', async () => {+ const listeners = renderProvider();++ act(() => {+ listeners.onDone?.({+ thread_id: 't-seg',+ request_id: 'r-seg',+ full_response: 'one two',+ segment_total: 2,+ rounds_used: 1,+ });+ });++ // Segments are the client's rows to write, several of them under one+ // request id, so a shared deterministic id would make them collapse onto+ // each other and lose all but the first.+ await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalledTimes(1));+ const [, persisted] = vi.mocked(threadApi.appendMessage).mock.calls[0];+ expect(persisted.id).not.toBe('agent:r-seg');+ });++ it('re-reads the thread when the append fails, so the core row still renders (#6034)', async () => {+ vi.mocked(threadApi.appendMessage).mockRejectedValueOnce(new Error('rpc timeout'));+ vi.mocked(threadApi.getThreadMessages).mockResolvedValueOnce({+ messages: [+ {+ id: 'agent:r-lost',+ content: 'the answer the core stored',+ type: 'text',+ sender: 'agent',+ createdAt: new Date().toISOString(),+ extraMetadata: {},+ },+ ],+ } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);++ const listeners = renderProvider();++ act(() => {+ listeners.onDone?.({+ thread_id: 't-lost',+ request_id: 'r-lost',+ full_response: 'the answer the core stored',+ rounds_used: 1,+ });+ });++ // The failed append used to end the story with a debug log and no+ // assistant row. Re-reading the thread is what brings the core's copy+ // into the cache without the user having to ask again.+ await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-lost'));+ await waitFor(() =>+ expect(+ (store.getState().thread.messagesByThreadId['t-lost'] ?? []).some(+ m => m.id === 'agent:r-lost'+ )+ ).toBe(true)+ );+ });+it('stores a parked plan review from the plan_review_request event', () => {const listeners = renderProvider();act(() => {@@ -1074,6 +1145,57 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invaria});});+ describe('socket reconnect recovery (#6034)', () => {+ it('rejoins the rooms of interrupted threads and re-reads them once the socket returns', async () => {+ vi.mocked(threadApi.getThreadMessages).mockResolvedValue({+ messages: [],+ } as unknown as Awaited<ReturnType<typeof threadApi.getThreadMessages>>);++ renderProvider();++ // A turn is in flight on a thread the user is not looking at.+ act(() => {+ store.dispatch(setActiveThread('t-away'));+ });+ vi.mocked(threadApi.getThreadMessages).mockClear();+ vi.mocked(socketService.subscribeThread).mockClear();++ // The socket drops. The provider clears every active marker so the+ // composer unlocks, which is also what erases the list the reconnect+ // handler would have re-subscribed from.+ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));+ });+ expect(store.getState().thread.activeThreadIds).toEqual({});++ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));+ });++ // Rejoin the room, so a turn still running can still reach us under the+ // new client_id, and re-read the thread, so a turn that finished during+ // the gap is not invisible until the thread is reselected.+ await waitFor(() => expect(socketService.subscribeThread).toHaveBeenCalledWith('t-away'));+ await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('t-away'));+ });++ it('does nothing on a connect with no interrupted threads', async () => {+ renderProvider();+ vi.mocked(socketService.subscribeThread).mockClear();++ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));+ });+ act(() => {+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'connected' }));+ });++ // A blip with nothing in flight must not re-read every thread the user+ // has ever opened.+ expect(socketService.subscribeThread).not.toHaveBeenCalled();+ });+ });+describe('mid-turn streaming invariants', () => {it('reconciles missing segment events from chat_done.full_response', async () => {const listeners = renderProvider();diff --git a/app/src/services/socketService.ts b/app/src/services/socketService.tsindex 06673892f4..eb376450fa 100644--- a/app/src/services/socketService.ts+++ b/app/src/services/socketService.ts@@ -475,6 +475,25 @@ class SocketService {}}+ /**+ * Join one thread's event room.+ *+ * The reconnect handler re-subscribes from `activeThreadIds`, which the chat+ * runtime clears when the socket drops — so a turn left in flight on a thread+ * the user had navigated away from has no room to be delivered into once a new+ * `client_id` is issued, and its `chat_done` reaches nobody. `ChatRuntimeProvider`+ * calls this for the threads it remembers across that gap (#6034).+ *+ * Emitting the room join directly rather than through {@link emit} keeps a+ * disconnected call quiet: re-subscription is what the `connect` handler+ * already does, so a warning here would only be noise.+ */+ subscribeThread(threadId: string): void {+ if (!threadId || !this.socket?.connected) return;+ socketLog('Subscribing to thread room', { threadId });+ this.socket.emit('thread:subscribe', { thread_id: threadId });+ }+/*** Listen to an event from the server*/diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 902b1f0021..e3f19ccbcc 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -191,6 +191,7 @@ Canonical mapping of every product feature to its test source(s). Drives gap-fil| 4.2.8 | Composer attachments (image / video / document; drag-drop + paste) | VU | `app/src/lib/attachments.test.ts`, `app/src/components/chat/__tests__/ChatComposer.test.tsx`, `app/src/pages/__tests__/Conversations.attachments.test.tsx` | 🟡 | Attach affordance gated on the resolved vision tier (images/video need vision; documents flow on any model); video is sampled into still frames client-side and forwarded through the existing `[IMAGE:]` vision path; drag-drop + clipboard-paste reuse the picker ingest. VU covers MIME/kind/limits/marker building + drag-drop + paste; real video decode and the frames→vision round-trip are manual-smoke only (jsdom has no video codec). WD E2E is a follow-up || 4.2.9 | Share cards ("Look what my agent did" post to X / LinkedIn) | VU | `app/src/features/share/shareContent.test.ts`, `app/src/features/share/shareTargets.test.ts`, `app/src/features/share/shareCaption.test.ts`, `app/src/features/share/shareCard.test.ts`, `app/src/features/share/ShareMessageButton.test.tsx`, `app/src/features/share/ShareCardModal.test.tsx` | ✅ | Hover Share button under completed agent messages opens a Canvas 2D branded card; LLM-drafted headline/caption via `inference_agent_chat_simple` with deterministic offline fallback; X/LinkedIn intent URLs + copy/save PNG; secrets/paths/emails redacted before render. MVP wires only the completed-task trigger; workflow-run + Human-tab triggers are follow-ups. WD E2E deferred |+| 4.2.10 | Durable agent reply (core stores it before announcing `chat_done`) | RU+VU | `src/openhuman/web_chat/reply_persistence_tests.rs`, `src/openhuman/web_chat/presentation_tests.rs`, `app/src/providers/__tests__/ChatRuntimeProvider.test.tsx` | ✅ | `deliver_response` persists an unsegmented reply under `agent:<request_id>` before publishing the terminal event, so a dropped socket, a failed `threads_message_append` or a reloaded webview costs a repaint rather than the answer; the client's append collapses onto that row by id. RU covers the write, its idempotency, the empty-reply and missing-thread paths, and that delivery still announces when the store refuses. VU covers the mirrored id, the segmented exception, the refetch that recovers a failed append, and the reconnect that rejoins orphaned thread rooms. WD E2E (kill the append mid-turn) is a follow-up |### 4.3 Tool Invocationdiff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.mdindex 78a27cc951..86842db435 100644--- a/gitbooks/developing/architecture/agent-harness.md+++ b/gitbooks/developing/architecture/agent-harness.md@@ -288,7 +288,7 @@ The child run itself still uses the same runner:`wait_subagent` and `steer_subagent` accept either the durable `subagent_session_id` or the transient `task_id`; durable ids are preferred across turns. `list_subagents` shows reusable children for the current parent thread, and `close_subagent` marks a worker non-reusable and cancels it if it is still running. Inline blocking is explicit via `blocking: true`; it is no longer the default.-The synthesized archetype delegations (`delegate_*`, `build_workflow`, and the other `delegate_name` tools) follow the same contract: they route through the durable async path by default, returning an `[async_subagent_ref]` (with `subagent_session_id` + `task_id`) immediately, and the finished result is inserted into the parent chat as a new system turn via `background_completions`/`background_delivery`. That delivery turn (`task_dispatcher::run_system_turn_on_thread`, the same runner autonomous task sessions use) persists its own closing message — `sender: "agent"`, id `agent:<run_id>`, `extraMetadata.requestId = run_id` — **before** it emits `chat_done` as `client_id: "system"`; the frontend reuses that id for system turns, so its usual `chat_done` append collapses onto the same row (the conversation store is idempotent for these deterministic `agent:`-prefixed ids; every other id is UUID-fresh and keeps the constant-time append path) instead of persisting the delivered result a second time (#5933). They fall back to inline blocking automatically when there is no parent agent turn or no chat thread to deliver into (cron/CLI), or when `blocking: true` is passed. Cross-turn continuity comes from three pieces: the per-turn `[active_subagents]` roster merges the live in-memory registry with the durable `subagent_sessions` store (so a cold-booted orchestrator still sees earlier workers); `continue_subagent` falls back from pause checkpoints to the durable store, resuming an idle worker with its persisted history; and a `workflow_proposal` payload found in a finished child's history is persisted as a parent-thread message (`extraMetadata.scope = "workflow_proposal"`) that the frontend rehydrates into the proposal card on thread load.+The synthesized archetype delegations (`delegate_*`, `build_workflow`, and the other `delegate_name` tools) follow the same contract: they route through the durable async path by default, returning an `[async_subagent_ref]` (with `subagent_session_id` + `task_id`) immediately, and the finished result is inserted into the parent chat as a new system turn via `background_completions`/`background_delivery`. That delivery turn (`task_dispatcher::run_system_turn_on_thread`, the same runner autonomous task sessions use) persists its own closing message — `sender: "agent"`, id `agent:<run_id>`, `extraMetadata.requestId = run_id` — **before** it emits `chat_done` as `client_id: "system"`; the frontend reuses that id, so its usual `chat_done` append collapses onto the same row (the conversation store is idempotent for these deterministic `agent:`-prefixed ids; every other id is UUID-fresh and keeps the constant-time append path) instead of persisting the delivered result a second time (#5933). **Interactive turns follow the same contract since #6034**: `web_chat::presentation::deliver_response` stores the reply under `agent:<request_id>` before publishing `chat_done`, so an answer the core produced exists on disk whether or not a client is there to receive the announcement — a dropped socket, a failed append or a reloaded webview costs a repaint, not the reply. The exception is a segmented delivery, where the client owns one row per segment and the core stores none; the frontend keeps generated ids there for exactly that reason. They fall back to inline blocking automatically when there is no parent agent turn or no chat thread to deliver into (cron/CLI), or when `blocking: true` is passed. Cross-turn continuity comes from three pieces: the per-turn `[active_subagents]` roster merges the live in-memory registry with the durable `subagent_sessions` store (so a cold-booted orchestrator still sees earlier workers); `continue_subagent` falls back from pause checkpoints to the durable store, resuming an idle worker with its persisted history; and a `workflow_proposal` payload found in a finished child's history is persisted as a parent-thread message (`extraMetadata.scope = "workflow_proposal"`) that the frontend rehydrates into the proposal card on thread load.### Spawn hierarchy and tiersdiff --git a/src/openhuman/flows/ops_part_10.rs b/src/openhuman/flows/ops_part_10.rsindex 0921e89a56..7baf4b3202 100644--- a/src/openhuman/flows/ops_part_10.rs+++ b/src/openhuman/flows/ops_part_10.rs@@ -23,6 +23,10 @@ async fn finalize_flow_stream(// Builder/scout turns don't surface in the chat footer; their// token/cost spend is still captured by the global cost tracker.None,+ // No workspace in scope on this path, so the viewing client+ // stays the only persister of a flow turn's reply — unchanged+ // from before #6034, which covered the chat surfaces.+ None,).await;}diff --git a/src/openhuman/web_chat/mod.rs b/src/openhuman/web_chat/mod.rsindex b751915362..7e140267ff 100644--- a/src/openhuman/web_chat/mod.rs+++ b/src/openhuman/web_chat/mod.rs@@ -4,6 +4,7 @@ mod ops;// standalone `presentation` provider — it is the web channel's delivery formatter).pub mod presentation;mod progress_bridge;+mod reply_persistence;mod run_task;mod schemas;mod session;diff --git a/src/openhuman/web_chat/ops_part_02.rs b/src/openhuman/web_chat/ops_part_02.rsindex cc9fb96179..cf06c85501 100644--- a/src/openhuman/web_chat/ops_part_02.rs+++ b/src/openhuman/web_chat/ops_part_02.rs@@ -385,6 +385,9 @@ pub async fn start_chat(&user_message,&chat_result.citations,chat_result.usage.as_ref(),+ // The workspace the turn ran in, so the reply is stored+ // there before it is announced (#6034).+ Some(chat_result.workspace_dir.as_path()),).await;}diff --git a/src/openhuman/web_chat/ops_part_03.rs b/src/openhuman/web_chat/ops_part_03.rsindex 0b659db093..38abaa1d7d 100644--- a/src/openhuman/web_chat/ops_part_03.rs+++ b/src/openhuman/web_chat/ops_part_03.rs@@ -68,6 +68,9 @@ async fn spawn_parallel_turn(&user_message,&chat_result.citations,chat_result.usage.as_ref(),+ // The workspace the turn ran in, so the reply is stored+ // there before it is announced (#6034).+ Some(chat_result.workspace_dir.as_path()),).await;}diff --git a/src/openhuman/web_chat/presentation.rs b/src/openhuman/web_chat/presentation.rsindex b0921856eb..e05c2a68fc 100644--- a/src/openhuman/web_chat/presentation.rs+++ b/src/openhuman/web_chat/presentation.rs@@ -50,6 +50,12 @@ fn usage_payload(usage: Option<&LastTurnUsage>) -> Option<TurnUsagePayload> {/// paragraphs into `chat_segment` messages duplicates tool/reasoning parts and/// turns one answer into several bubbles, so this path always emits exactly one/// `chat_done` with the model's original text.+///+/// `workspace_dir` is where the reply is stored **before** it is announced, so a+/// client that never receives the `chat_done` — or receives it and fails to+/// append — is not the difference between the answer existing and not existing+/// (#6034). Pass `None` from a caller that has no workspace in scope; delivery+/// then behaves exactly as it did when the renderer was the only writer.pub(crate) async fn deliver_response(client_id: &str,thread_id: &str,@@ -58,6 +64,7 @@ pub(crate) async fn deliver_response(user_message: &str,citations: &[crate::openhuman::memory::agent::memory_loader::MemoryCitation],usage: Option<&LastTurnUsage>,+ workspace_dir: Option<&std::path::Path>,) {let usage_payload = usage_payload(usage);@@ -75,6 +82,50 @@ pub(crate) async fn deliver_response(let reaction_emoji = reaction_handle.await.unwrap_or(None);if segments.len() <= 1 {+ // Store the answer before announcing it. Ordering is the whole point:+ // once the row is on disk, a `chat_done` that is never delivered, never+ // painted, or never persisted by the client costs the user a repaint,+ // not the reply (#6034). Only this single-bubble branch persists — the+ // segmented branch below hands the client one row per segment to write,+ // and a full-text row beside those would read as a duplicate answer.+ if let Some(dir) = workspace_dir {+ // The store appends under a process-wide lock and fsyncs, and its+ // existence check folds the whole threads log (#5156) — blocking+ // work that has no business holding a runtime worker while a turn+ // is settling. Hand it to the blocking pool and await the handle,+ // which keeps the ordering this whole change rests on.+ let (dir, thread, request, reply) = (+ dir.to_path_buf(),+ thread_id.to_string(),+ request_id.to_string(),+ full_response.to_string(),+ );+ let persisted = tokio::task::spawn_blocking(move || {+ super::reply_persistence::persist_delivered_reply(&dir, &thread, &request, &reply)+ })+ .await;+ match persisted {+ Ok(Ok(stored)) => {+ if stored {+ log::debug!(+ "[web-channel] persisted reply before announcing it thread_id={thread_id} request_id={request_id}"+ );+ }+ }+ // Deliberately non-fatal: announce anyway. The client's own+ // append still persists the reply in the common case, and a+ // storage failure must not also cost the user the delivery.+ Ok(Err(err)) => log::warn!(+ "[web-channel] could not persist reply before announcing it \+ thread_id={thread_id} request_id={request_id} error={err}"+ ),+ Err(err) => log::warn!(+ "[web-channel] reply persistence task did not run \+ thread_id={thread_id} request_id={request_id} error={err}"+ ),+ }+ }+// Single bubble — emit chat_done directly.publish_chat_done(client_id,diff --git a/src/openhuman/web_chat/presentation_test_support_tests.rs b/src/openhuman/web_chat/presentation_test_support_tests.rsindex aee2b717ce..6c45ac43af 100644--- a/src/openhuman/web_chat/presentation_test_support_tests.rs+++ b/src/openhuman/web_chat/presentation_test_support_tests.rs@@ -19,6 +19,29 @@ pub async fn deliver_response_for_test(full_response: &str,user_message: &str,citations: &[MemoryCitation],+) {+ deliver_response_in_workspace_for_test(+ client_id,+ thread_id,+ request_id,+ full_response,+ user_message,+ citations,+ None,+ )+ .await;+}++/// `deliver_response` with an explicit workspace, so a test can assert the+/// reply reached disk before the turn was announced (#6034).+pub async fn deliver_response_in_workspace_for_test(+ client_id: &str,+ thread_id: &str,+ request_id: &str,+ full_response: &str,+ user_message: &str,+ citations: &[MemoryCitation],+ workspace_dir: Option<&std::path::Path>,) {super::deliver_response(client_id,@@ -28,6 +51,7 @@ pub async fn deliver_response_for_test(user_message,citations,None,+ workspace_dir,).await;}diff --git a/src/openhuman/web_chat/presentation_tests.rs b/src/openhuman/web_chat/presentation_tests.rsindex 270f6bd42f..7cc7761e59 100644--- a/src/openhuman/web_chat/presentation_tests.rs+++ b/src/openhuman/web_chat/presentation_tests.rs@@ -309,3 +309,93 @@ fn single_bubble_delivery_emits_one_unsegmented_chat_done_without_reaction() {assert_eq!(done.reaction_emoji, None);assert!(done.usage.is_none());}++// ── Delivery persists before it announces (#6034) ───────────────────────++#[tokio::test]+async fn delivery_stores_the_reply_before_announcing_it() {+ use crate::openhuman::memory::conversations::{self, CreateConversationThread};++ let ws = std::env::temp_dir().join(format!("deliver-persist-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&ws).unwrap();+ conversations::ensure_thread(+ ws.clone(),+ CreateConversationThread {+ id: "t-deliver".to_string(),+ title: "Chat".to_string(),+ created_at: chrono::Utc::now().to_rfc3339(),+ parent_thread_id: None,+ labels: None,+ personality_id: None,+ },+ )+ .expect("thread created");++ test_support::deliver_response_in_workspace_for_test(+ "client-1",+ "t-deliver",+ "req-deliver",+ "Here is the summary you asked for.",+ "summarise this",+ &[],+ Some(ws.as_path()),+ )+ .await;++ // `deliver_response` returns only after the terminal event is published, so+ // a row present here proves the write happened no later than the announce.+ // A client that never receives that event, or fails to append it, no longer+ // decides whether the reply exists.+ let messages = conversations::get_messages(ws.clone(), "t-deliver").expect("messages");+ assert_eq!(messages.len(), 1, "delivery must leave exactly one row");+ assert_eq!(messages[0].id, "agent:req-deliver");+ assert_eq!(messages[0].content, "Here is the summary you asked for.");+ assert_eq!(messages[0].sender, "agent");+}++#[tokio::test]+async fn delivery_still_announces_when_the_reply_cannot_be_stored() {+ // The thread does not exist, so the store refuses the write. Delivery must+ // continue regardless: a storage failure that also swallowed the+ // announcement would turn a recoverable problem into a dead turn, and the+ // client's own append is still a working fallback.+ let ws = std::env::temp_dir().join(format!("deliver-nothread-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&ws).unwrap();++ test_support::deliver_response_in_workspace_for_test(+ "client-3",+ "absent-thread",+ "req-absent",+ "an answer with nowhere to go",+ "hi",+ &[],+ Some(ws.as_path()),+ )+ .await;++ // `get_messages` answers `Ok(vec![])` for a thread it has never seen — only+ // `append_message` refuses one — so absence is what proves the write was+ // rejected and swallowed rather than silently creating a thread.+ let messages =+ crate::openhuman::memory::conversations::get_messages(ws.clone(), "absent-thread")+ .expect("reading an unknown thread is not an error");+ assert!(+ messages.is_empty(),+ "the thread was never created, so nothing should have been written"+ );+}++#[tokio::test]+async fn delivery_without_a_workspace_persists_nothing() {+ // Callers with no workspace in scope (the flows stream finalizer) keep the+ // pre-#6034 behaviour: the viewing client stays the only persister.+ test_support::deliver_response_for_test(+ "client-2",+ "t-none",+ "req-none",+ "nothing to store",+ "hi",+ &[],+ )+ .await;+}diff --git a/src/openhuman/web_chat/reply_persistence.rs b/src/openhuman/web_chat/reply_persistence.rsnew file mode 100644index 0000000000..59675abb45--- /dev/null+++ b/src/openhuman/web_chat/reply_persistence.rs@@ -0,0 +1,73 @@+//! Durable storage for the reply a web-channel turn is about to announce.+//!+//! An interactive turn's answer used to reach disk only if the viewing client+//! persisted the `chat_done` it received. That made the renderer the single+//! writer of a reply the core had already produced: one failed+//! `threads_message_append`, one socket reconnect that moved the client to a new+//! `client_id`, or one webview reload during a long turn, and the answer was+//! gone from the thread while the agent's own session history still held it+//! (#6034).+//!+//! Core-initiated turns never had that exposure — `task_session::append_final`+//! writes their closing row *before* the run announces it, and the client's+//! append collapses onto that row because both derive the same deterministic id+//! (#5933). This module gives interactive turns the same guarantee, so a reply+//! survives whatever the renderer was doing at the moment it was delivered.+//!+//! The id is [`run_reply_message_id`] over the turn's `request_id`, which is+//! what makes the second write a no-op rather than a duplicate bubble: the+//! conversation store is idempotent for exactly this id shape.++use std::path::Path;++use serde_json::json;++use crate::openhuman::memory::conversations::{self, run_reply_message_id, ConversationMessage};++/// Metadata scope stamped on a reply persisted by the web-channel delivery path.+///+/// Distinguishes it from `autonomous_task_result` (the same shape written by+/// `task_session::append_final`) when reading a thread back.+const REPLY_SCOPE: &str = "web_chat_reply";++/// Persist a delivered reply under the id the announcing client will reuse.+///+/// Returns `Ok(false)` when there was nothing to store (an empty or+/// whitespace-only response — the same guard `task_session::append_final`+/// applies), `Ok(true)` when the row is on disk, and `Err` when the store+/// refused the write (most commonly a thread that does not exist yet).+///+/// Callers must treat an `Err` as non-fatal and announce the reply anyway: the+/// client's own append is still a working fallback, and losing the delivery on+/// top of losing the row would turn a storage problem into a visibly dead turn.+pub(crate) fn persist_delivered_reply(+ workspace_dir: &Path,+ thread_id: &str,+ request_id: &str,+ full_response: &str,+) -> Result<bool, String> {+ let content = full_response.trim();+ if content.is_empty() {+ return Ok(false);+ }+ conversations::append_message(+ workspace_dir.to_path_buf(),+ thread_id,+ ConversationMessage {+ id: run_reply_message_id(request_id),+ content: content.to_string(),+ message_type: "text".to_string(),+ extra_metadata: json!({+ "scope": REPLY_SCOPE,+ "requestId": request_id,+ }),+ sender: "agent".to_string(),+ created_at: chrono::Utc::now().to_rfc3339(),+ },+ )?;+ Ok(true)+}++#[cfg(test)]+#[path = "reply_persistence_tests.rs"]+mod tests;diff --git a/src/openhuman/web_chat/reply_persistence_tests.rs b/src/openhuman/web_chat/reply_persistence_tests.rsnew file mode 100644index 0000000000..28336a3ce5--- /dev/null+++ b/src/openhuman/web_chat/reply_persistence_tests.rs@@ -0,0 +1,93 @@+use std::path::PathBuf;++use super::persist_delivered_reply;+use crate::openhuman::memory::conversations::{self, CreateConversationThread};++fn temp_ws() -> PathBuf {+ let dir = std::env::temp_dir().join(format!("web-chat-reply-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++fn seed_thread(ws: &PathBuf, thread_id: &str) {+ conversations::ensure_thread(+ ws.clone(),+ CreateConversationThread {+ id: thread_id.to_string(),+ title: "Chat".to_string(),+ created_at: chrono::Utc::now().to_rfc3339(),+ parent_thread_id: None,+ labels: None,+ personality_id: None,+ },+ )+ .expect("thread created");+}++#[test]+fn persists_the_reply_under_the_id_the_client_will_reuse() {+ let ws = temp_ws();+ seed_thread(&ws, "t-1");++ let stored = persist_delivered_reply(&ws, "t-1", "req-1", "Done, the draft is updated.")+ .expect("append succeeds");+ assert!(stored, "a non-empty reply must report that it was stored");++ let messages = conversations::get_messages(ws.clone(), "t-1").expect("messages");+ assert_eq!(messages.len(), 1);+ // The id is what makes the client's own append collapse onto this row+ // instead of adding a duplicate bubble (#5933 / #6034).+ assert_eq!(messages[0].id, "agent:req-1");+ assert_eq!(messages[0].sender, "agent");+ assert_eq!(messages[0].content, "Done, the draft is updated.");+ assert_eq!(messages[0].extra_metadata["scope"], "web_chat_reply");+ assert_eq!(messages[0].extra_metadata["requestId"], "req-1");+}++#[test]+fn a_second_write_of_the_same_turn_does_not_add_a_row() {+ let ws = temp_ws();+ seed_thread(&ws, "t-2");++ persist_delivered_reply(&ws, "t-2", "req-2", "First").expect("first append");+ // The client persists the same reply from the `chat_done` it received. The+ // store's idempotency for deterministic ids is what keeps the thread at one+ // row; assert the second write here so a change to the id shape (which+ // would silently opt out of that lookup) fails loudly.+ persist_delivered_reply(&ws, "t-2", "req-2", "First").expect("second append");++ let messages = conversations::get_messages(ws.clone(), "t-2").expect("messages");+ assert_eq!(messages.len(), 1, "one turn must never leave two rows");+}++#[test]+fn an_empty_reply_is_not_stored() {+ let ws = temp_ws();+ seed_thread(&ws, "t-3");++ let stored = persist_delivered_reply(&ws, "t-3", "req-3", " \n ").expect("no error");+ assert!(!stored, "an empty reply reports that nothing was stored");+ assert!(conversations::get_messages(ws.clone(), "t-3")+ .expect("messages")+ .is_empty());+}++#[test]+fn content_is_trimmed_the_way_the_autonomous_path_trims_it() {+ let ws = temp_ws();+ seed_thread(&ws, "t-4");++ persist_delivered_reply(&ws, "t-4", "req-4", " padded reply\n").expect("append");++ let messages = conversations::get_messages(ws.clone(), "t-4").expect("messages");+ assert_eq!(messages[0].content, "padded reply");+}++#[test]+fn a_missing_thread_is_reported_rather_than_silently_dropped() {+ let ws = temp_ws();++ let err = persist_delivered_reply(&ws, "nope", "req-5", "text")+ .expect_err("a missing thread must not look like a successful store");+ assert!(err.contains("nope"), "error names the thread: {err}");+}diff --git a/src/openhuman/web_chat/run_task.rs b/src/openhuman/web_chat/run_task.rsindex 03f3b11ceb..75886ead75 100644--- a/src/openhuman/web_chat/run_task.rs+++ b/src/openhuman/web_chat/run_task.rs@@ -276,6 +276,7 @@ pub(crate) async fn run_chat_task(full_response: response,citations,usage,+ workspace_dir: config.workspace_dir.clone(),})}Err(err) => {@@ -306,6 +307,7 @@ pub(crate) async fn run_chat_task(full_response: inference_budget_exceeded_user_message().to_string(),citations: Vec::new(),usage: None,+ workspace_dir: config.workspace_dir.clone(),})}BudgetCorrelation::UpgradeEmptyToBudget => {@@ -324,6 +326,7 @@ pub(crate) async fn run_chat_task(full_response: inference_budget_exceeded_user_message().to_string(),citations: Vec::new(),usage: None,+ workspace_dir: config.workspace_dir.clone(),})}BudgetCorrelation::PassThrough => Err(err_message),diff --git a/src/openhuman/web_chat/run_task_tests.rs b/src/openhuman/web_chat/run_task_tests.rsindex 8d15aee0b4..685767aa6c 100644--- a/src/openhuman/web_chat/run_task_tests.rs+++ b/src/openhuman/web_chat/run_task_tests.rs@@ -5,6 +5,7 @@ fn ok() -> Result<WebChatTaskResult, String> {full_response: "hello".to_string(),citations: Vec::new(),usage: None,+ workspace_dir: std::path::PathBuf::from("/tmp/ws"),})}diff --git a/src/openhuman/web_chat/types.rs b/src/openhuman/web_chat/types.rsindex 7301d34b68..77c672ddff 100644--- a/src/openhuman/web_chat/types.rs+++ b/src/openhuman/web_chat/types.rs@@ -74,6 +74,14 @@ pub(super) struct WebChatTaskResult {/// forwarded to the frontend on `chat_done`. `None` for synthetic results/// (e.g. budget-exhausted placeholders) that never ran a real turn.pub(super) usage: Option<crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage>,+ /// The workspace this turn actually ran in, carried to delivery so the+ /// reply is stored there before it is announced (#6034).+ ///+ /// Taken from the config the turn resolved rather than re-read at delivery+ /// time: a sign-out or account switch moves `workspace_dir`, and a reply+ /// re-resolved afterwards would be filed under whoever is signed in when+ /// the turn happens to finish.+ pub(super) workspace_dir: std::path::PathBuf,}/// Per-request metadata carried alongside a chat send. Currently used by the