Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): persist an autonomous reply once, under a core-owned id (#5933)\n\n`run_autonomous` (background sub-agent result delivery into the chat\nthread, autonomous task sessions) announced `chat_done` — which the\nfrontend persists as `sender: agent` — and then `task_session::append_final`\npersisted the same reply again as `sender: "assistant"`. The frontend maps\nany non-`agent` sender to a user-role message, so the reply rendered twice:\na right-side bubble carrying raw markdown plus the real answer below it.\n\n- the core persists first, as `agent:<run_id>` / `sender: agent` with\n `extraMetadata.requestId`, then emits one unsegmented `chat_done`\n (`deliver_response_single_bubble`)\n- `ConversationStore::append_message` is idempotent by message id\n- the frontend reuses `agent:<request_id>` for `client_id: "system"`\n turns so its own append collapses onto the core row\n- `threadApi` folds legacy `sender: "assistant"` rows onto `agent`\n

Shanudb509f156559
diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsx
index 0565d8879a..2e188b2eee 100644
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@ -218,6 +218,26 @@ function chatDoneExtraMetadata(event: ChatDoneEvent): Record<string, unknown> |
return Object.keys(meta).length > 0 ? meta : undefined;
}
+/**
+ * Message id for a reply the CORE already persisted before announcing it.
+ *
+ * Core-initiated turns (`client_id === 'system'`: autonomous task sessions and
+ * background sub-agent result delivery via `run_system_turn_on_thread`) write
+ * their own closing message — `task_session::append_final`, keyed
+ * `agent:<run_id>` — and only then emit `chat_done` / `chat_error` with that
+ * run id as `request_id`. Reusing the same id here makes our own
+ * `addInferenceResponse` append collapse onto the core's row (the conversation
+ * store is idempotent by message id) instead of persisting a second copy that
+ * rendered as a duplicate reply under the answer (#5933). Interactive turns
+ * keep their generated ids: nothing else has persisted them.
+ */
+function corePersistedMessageId(event: {
+ client_id?: string;
+ request_id?: string;
+}): string | undefined {
+ return event.client_id === 'system' && 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
@@ -1175,6 +1195,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
addInferenceResponse({
content: event.full_response,
threadId: event.thread_id,
+ messageId: corePersistedMessageId(event),
extraMetadata: chatDoneExtraMetadata(event),
})
).unwrap();
@@ -1210,6 +1231,7 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
addInferenceResponse({
content: event.full_response,
threadId: event.thread_id,
+ messageId: corePersistedMessageId(event),
extraMetadata: chatDoneExtraMetadata(event),
})
).unwrap();
@@ -1335,7 +1357,11 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
if (!(lastMsg?.sender === 'agent' && lastMsg?.content === errorContent)) {
void dispatch(
- addInferenceResponse({ content: errorContent, threadId: event.thread_id })
+ addInferenceResponse({
+ content: errorContent,
+ threadId: event.thread_id,
+ messageId: corePersistedMessageId(event),
+ })
);
}
diff --git a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
index 9044213625..a033128100 100644
--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
@@ -482,6 +482,75 @@ describe('ChatRuntimeProvider — dedupe, proactive resolution, mid-turn invaria
await waitFor(() => expect(mockRefetchSnapshot).toHaveBeenCalledTimes(1));
});
+ it('persists a core-initiated (system) turn under the id the core already wrote (#5933)', async () => {
+ const listeners = renderProvider();
+
+ act(() => {
+ listeners.onDone?.({
+ thread_id: 't-sys',
+ request_id: 'bgdeliver-1',
+ client_id: 'system',
+ full_response: 'Same two issues as before',
+ rounds_used: 1,
+ });
+ });
+
+ // The same `agent:<run_id>` id `task_session::append_final` used, so the
+ // core's idempotent store collapses this append onto its own row instead
+ // of keeping a second copy of the reply.
+ await waitFor(() =>
+ expect(threadApi.appendMessage).toHaveBeenCalledWith(
+ 't-sys',
+ expect.objectContaining({
+ id: 'agent:bgdeliver-1',
+ sender: 'agent',
+ content: 'Same two issues as before',
+ extraMetadata: expect.objectContaining({ requestId: 'bgdeliver-1' }),
+ })
+ )
+ );
+ });
+
+ it('persists a core-initiated (system) turn failure under the same core id', async () => {
+ const listeners = renderProvider();
+
+ act(() => {
+ listeners.onError?.({
+ thread_id: 't-sys-err',
+ request_id: 'bgdeliver-2',
+ client_id: 'system',
+ message: 'Run failed: boom',
+ error_type: 'inference',
+ round: null,
+ });
+ });
+
+ await waitFor(() =>
+ expect(threadApi.appendMessage).toHaveBeenCalledWith(
+ 't-sys-err',
+ expect.objectContaining({ id: 'agent:bgdeliver-2', sender: 'agent' })
+ )
+ );
+ });
+
+ it('keeps a generated id for an interactive chat_done (nothing else persisted it)', async () => {
+ const listeners = renderProvider();
+
+ act(() => {
+ listeners.onDone?.({
+ thread_id: 't-user',
+ request_id: 'r-user',
+ full_response: 'hi',
+ rounds_used: 1,
+ });
+ });
+
+ 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.sender).toBe('agent');
+ });
+
it('stores a parked plan review from the plan_review_request event', () => {
const listeners = renderProvider();
act(() => {
diff --git a/app/src/services/api/threadApi.test.ts b/app/src/services/api/threadApi.test.ts
index 67e8baeaa9..261fc40c0c 100644
--- a/app/src/services/api/threadApi.test.ts
+++ b/app/src/services/api/threadApi.test.ts
@@ -58,6 +58,65 @@ describe('threadApi', () => {
expect(result).toEqual(message);
});
+ it('folds the legacy `assistant` sender onto `agent` when listing messages (#5933)', async () => {
+ mockCallCoreRpc.mockResolvedValueOnce({
+ data: {
+ messages: [
+ {
+ id: 'user:1',
+ content: 'hi',
+ type: 'text',
+ extraMetadata: {},
+ sender: 'user',
+ createdAt: '2026-04-10T12:01:00Z',
+ },
+ {
+ // Written by an autonomous task run before the core switched its
+ // closing message to the `agent` vocabulary.
+ id: 'assistant:legacy',
+ content: 'done',
+ type: 'text',
+ extraMetadata: { scope: 'autonomous_task_result' },
+ sender: 'assistant',
+ createdAt: '2026-04-10T12:02:00Z',
+ },
+ ],
+ count: 2,
+ },
+ });
+
+ const { threadApi } = await import('./threadApi');
+ const result = await threadApi.getThreadMessages('default-thread');
+
+ expect(result.count).toBe(2);
+ expect(result.messages.map(m => m.sender)).toEqual(['user', 'agent']);
+ // Everything else on the row is untouched.
+ expect(result.messages[1]).toMatchObject({ id: 'assistant:legacy', content: 'done' });
+ });
+
+ it('folds the legacy `assistant` sender onto `agent` on append and update results', async () => {
+ const stored = {
+ id: 'agent:run-1',
+ content: 'done',
+ type: 'text',
+ extraMetadata: {},
+ sender: 'assistant',
+ createdAt: '2026-04-10T12:02:00Z',
+ };
+ mockCallCoreRpc.mockResolvedValueOnce({ data: stored });
+ mockCallCoreRpc.mockResolvedValueOnce({ data: stored });
+
+ const { threadApi } = await import('./threadApi');
+ const appended = await threadApi.appendMessage('default-thread', {
+ ...stored,
+ sender: 'agent',
+ });
+ const updated = await threadApi.updateMessage('default-thread', 'agent:run-1', {});
+
+ expect(appended.sender).toBe('agent');
+ expect(updated.sender).toBe('agent');
+ });
+
it('generates a thread title via threads RPC', async () => {
const thread = {
id: 'default-thread',
diff --git a/app/src/services/api/threadApi.ts b/app/src/services/api/threadApi.ts
index bf01d34bcf..a837bc3e03 100644
--- a/app/src/services/api/threadApi.ts
+++ b/app/src/services/api/threadApi.ts
@@ -46,6 +46,18 @@ function unwrapEnvelope<T>(response: Envelope<T> | T): T {
const generateTitleLog = debug('threadApi.generateTitleIfNeeded');
+/**
+ * The core's `sender` vocabulary is `user` | `agent`, but some core writers
+ * stored the assistant side as `assistant` (autonomous task sessions before
+ * #5933, channel-session mirrors). Fold that alias onto `agent` at the transport
+ * boundary so every `sender === 'agent'` check in the renderers — and the
+ * assistant-ui role mapping — treats such a row as the assistant instead of
+ * painting it as a user turn.
+ */
+function normalizeThreadMessage(message: ThreadMessage): ThreadMessage {
+ return (message.sender as string) === 'assistant' ? { ...message, sender: 'agent' } : message;
+}
+
export const threadApi = {
createNewThread: async (labels?: string[]): Promise<Thread> => {
const response = await callCoreRpc<Envelope<Thread>>({
@@ -67,7 +79,8 @@ export const threadApi = {
method: 'openhuman.threads_messages_list',
params: { thread_id: threadId },
});
- return unwrapEnvelope(response);
+ const data = unwrapEnvelope(response);
+ return { ...data, messages: data.messages.map(normalizeThreadMessage) };
},
appendMessage: async (threadId: string, message: ThreadMessage): Promise<ThreadMessage> => {
@@ -75,7 +88,7 @@ export const threadApi = {
method: 'openhuman.threads_message_append',
params: { thread_id: threadId, message },
});
- return unwrapEnvelope(response);
+ return normalizeThreadMessage(unwrapEnvelope(response));
},
generateTitleIfNeeded: async (threadId: string, assistantMessage?: string): Promise<Thread> => {
@@ -108,7 +121,7 @@ export const threadApi = {
method: 'openhuman.threads_message_update',
params: { thread_id: threadId, message_id: messageId, extra_metadata: extraMetadata },
});
- return unwrapEnvelope(response);
+ return normalizeThreadMessage(unwrapEnvelope(response));
},
deleteThread: async (threadId: string): Promise<ThreadDeleteData> => {
diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.ts
index 2a493d61c7..2249ff670f 100644
--- a/app/src/services/chatService.ts
+++ b/app/src/services/chatService.ts
@@ -89,6 +89,14 @@ export interface TurnUsageWire {
export interface ChatDoneEvent {
thread_id: string;
request_id?: string;
+ /**
+ * Socket.IO client that owns the turn. `"system"` marks a turn the core ran
+ * on its own behalf (autonomous task sessions, background sub-agent result
+ * delivery, cron/flow agents); such turns are broadcast to every client.
+ * Always on the wire (`WebChannelEvent.client_id`); declared here for the
+ * consumers that key off it.
+ */
+ client_id?: string;
/** Per-request monotonic ordering key stamped by the core progress bridge. */
seq?: number;
full_response: string;
@@ -165,6 +173,14 @@ export interface ChatInterimEvent {
export interface ChatErrorEvent {
thread_id: string;
request_id?: string;
+ /**
+ * Socket.IO client that owns the turn. `"system"` marks a turn the core ran
+ * on its own behalf (autonomous task sessions, background sub-agent result
+ * delivery, cron/flow agents); such turns are broadcast to every client.
+ * Always on the wire (`WebChannelEvent.client_id`); declared here for the
+ * consumers that key off it.
+ */
+ client_id?: string;
message: string;
error_type:
| 'network'
diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.md
index be0e613333..fd327d54ad 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`. 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 for system turns, so its usual `chat_done` append collapses onto the same row (the conversation store is idempotent by message id) 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.
### Spawn hierarchy and tiers
diff --git a/src/openhuman/agent/task_dispatcher/executor.rs b/src/openhuman/agent/task_dispatcher/executor.rs
index 368e76665e..ecbbf33ef3 100644
--- a/src/openhuman/agent/task_dispatcher/executor.rs
+++ b/src/openhuman/agent/task_dispatcher/executor.rs
@@ -241,27 +241,37 @@ pub(super) async fn run_autonomous(
}
.map_err(|e| format!("{e:#}"));
- // Emit the terminal chat event so a client viewing the session stops
- // "processing" and finalizes the assistant bubble — the SAME chat_done /
- // chat_error the web channel emits at the end of a normal turn. The
- // progress bridge only streams intermediate deltas; without this terminal
- // signal the live-streamed session spins forever. Broadcast as "system" so
- // any viewer of the thread receives it (frontend keys by thread_id).
+ // Close the run in its thread. Order matters (#5933): persist the closing
+ // message FIRST, announce the terminal event SECOND. A client viewing the
+ // thread persists whatever `chat_done` carries as well, under the same
+ // `agent:<run_id>` id (`ChatRuntimeProvider` mirrors `append_final`'s id
+ // for `client_id: "system"` turns), and the conversation store is
+ // idempotent by message id — so the second writer collapses onto the row
+ // that already exists instead of leaving the duplicate reply the issue
+ // reported. Persisting first makes the core's row the one that exists.
if let Some(thread_id) = session_thread_id.as_deref() {
+ // Persist the final response (or failure) as the closing agent message
+ // so a reopened session shows the outcome like a finished manual run —
+ // and so it is already there when any viewer reacts to the event below.
+ task_session::append_final(workspace_dir, thread_id, run_id, &result);
+
+ // Emit the terminal chat event so a client viewing the session stops
+ // "processing" and finalizes the assistant bubble — the SAME chat_done /
+ // chat_error the web channel emits at the end of a normal turn. The
+ // progress bridge only streams intermediate deltas; without this terminal
+ // signal the live-streamed session spins forever. Broadcast as "system" so
+ // any viewer of the thread receives it (frontend keys by thread_id).
match &result {
Ok(response) => {
- crate::openhuman::web_chat::presentation::deliver_response(
- "system",
- thread_id,
- run_id,
- response,
- prompt,
- &[],
- // Background/cron turns don't surface in the chat footer; their
- // token/cost spend is still captured by the global cost tracker.
- None,
- )
- .await;
+ // One bubble, never segmented: the reply was persisted as a
+ // single row above, and a segmented delivery would have a
+ // viewing client persist one row per segment beside it.
+ // Background/cron turns don't surface usage in the chat footer;
+ // their token/cost spend is still captured by the global cost
+ // tracker.
+ crate::openhuman::web_chat::presentation::deliver_response_single_bubble(
+ "system", thread_id, run_id, response, None,
+ );
}
Err(err) => {
crate::openhuman::web_chat::publish_web_channel_event(
@@ -277,9 +287,6 @@ pub(super) async fn run_autonomous(
);
}
}
- // Persist the final response as the closing assistant message so a
- // reopened session shows the outcome like a finished manual run.
- task_session::append_final(workspace_dir, thread_id, &result);
}
result
}
diff --git a/src/openhuman/agent/task_session.rs b/src/openhuman/agent/task_session.rs
index 80c5e06dde..032ff4d8a8 100644
--- a/src/openhuman/agent/task_session.rs
+++ b/src/openhuman/agent/task_session.rs
@@ -121,11 +121,21 @@ fn session_title(card: &TaskBoardCard) -> String {
}
/// Append the run's final response (or failure reason) to the session thread as
-/// the closing `assistant` message, so a reopened session shows the outcome.
+/// the closing `agent` message, so a reopened session shows the outcome.
/// No-op on an empty response. Best-effort: a store failure is logged only.
+///
+/// The row is keyed `agent:<run_id>` on purpose. A client viewing the thread
+/// persists the same reply again from the `chat_done` the run announces, and it
+/// reuses this id for `client_id: "system"` turns (`ChatRuntimeProvider`), so
+/// the conversation store's id idempotency collapses both writes onto one row
+/// instead of the duplicate reply #5933 reported. `sender` is `agent` — the
+/// vocabulary every renderer keys on; the former `assistant` painted this row
+/// as a USER bubble. `requestId` carries the run id so the reply anchors to its
+/// own process trail exactly like an interactive turn's answer.
pub(crate) fn append_final(
workspace_dir: PathBuf,
thread_id: &str,
+ run_id: &str,
outcome: &Result<String, String>,
) {
let (content, success) = match outcome {
@@ -139,11 +149,15 @@ pub(crate) fn append_final(
workspace_dir,
thread_id,
ConversationMessage {
- id: format!("assistant:{}", uuid::Uuid::new_v4()),
+ id: format!("agent:{run_id}"),
content,
message_type: "text".to_string(),
- extra_metadata: json!({ "scope": "autonomous_task_result", "success": success }),
- sender: "assistant".to_string(),
+ extra_metadata: json!({
+ "scope": "autonomous_task_result",
+ "success": success,
+ "requestId": run_id,
+ }),
+ sender: "agent".to_string(),
created_at: chrono::Utc::now().to_rfc3339(),
},
) {
diff --git a/src/openhuman/agent/task_session_tests.rs b/src/openhuman/agent/task_session_tests.rs
index a9f67c3aea..00528d09f0 100644
--- a/src/openhuman/agent/task_session_tests.rs
+++ b/src/openhuman/agent/task_session_tests.rs
@@ -59,22 +59,61 @@ fn creates_top_level_tasks_thread_and_seeds_prompt() {
}
#[test]
-fn append_final_writes_assistant_outcome() {
+fn append_final_writes_agent_outcome_keyed_by_run_id() {
let ws = temp_ws();
let id = create_session_thread(ws.clone(), &card("X"), "run-2", "prompt").expect("thread");
- append_final(ws.clone(), &id, &Ok("All done.".to_string()));
+ append_final(ws.clone(), &id, "run-2", &Ok("All done.".to_string()));
let msgs = conversations::get_messages(ws, &id).expect("messages");
let last = msgs.last().expect("has messages");
- assert_eq!(last.sender, "assistant");
+ // `agent` is the sender every renderer keys on; `assistant` used to land
+ // here and painted the closing reply as a USER bubble (#5933).
+ assert_eq!(last.sender, "agent");
assert_eq!(last.content, "All done.");
+ // Deterministic per run so a client that also persists the announced
+ // reply under `agent:<request_id>` collapses onto this row.
+ assert_eq!(last.id, "agent:run-2");
+ assert_eq!(last.extra_metadata["requestId"], "run-2");
+ assert_eq!(last.extra_metadata["success"], true);
+ assert_eq!(last.extra_metadata["scope"], "autonomous_task_result");
+}
+
+#[test]
+fn append_final_records_failure_as_unsuccessful_agent_message() {
+ let ws = temp_ws();
+ let id = create_session_thread(ws.clone(), &card("X"), "run-5", "prompt").expect("thread");
+ append_final(ws.clone(), &id, "run-5", &Err("boom".to_string()));
+
+ let msgs = conversations::get_messages(ws, &id).expect("messages");
+ let last = msgs.last().expect("has messages");
+ assert_eq!(last.sender, "agent");
+ assert_eq!(last.id, "agent:run-5");
+ assert_eq!(last.content, "Run failed: boom");
+ assert_eq!(last.extra_metadata["success"], false);
+}
+
+#[test]
+fn append_final_is_idempotent_per_run() {
+ // The core persists first, then a viewing client persists the announced
+ // reply under the same id — the store must keep exactly one row.
+ let ws = temp_ws();
+ let id = create_session_thread(ws.clone(), &card("X"), "run-4", "prompt").expect("thread");
+ append_final(ws.clone(), &id, "run-4", &Ok("All done.".to_string()));
+ append_final(ws.clone(), &id, "run-4", &Ok("All done.".to_string()));
+
+ let msgs = conversations::get_messages(ws, &id).expect("messages");
+ assert_eq!(
+ msgs.iter().filter(|m| m.sender == "agent").count(),
+ 1,
+ "a second append for the same run must not add a second closing message"
+ );
}
#[test]
fn append_final_skips_empty_response() {
let ws = temp_ws();
let id = create_session_thread(ws.clone(), &card("X"), "run-3", "prompt").expect("thread");
- append_final(ws.clone(), &id, &Ok(" ".to_string()));
+ append_final(ws.clone(), &id, "run-3", &Ok(" ".to_string()));
let msgs = conversations::get_messages(ws, &id).expect("messages");
assert_eq!(
diff --git a/src/openhuman/memory/conversations/store/store_ops.rs b/src/openhuman/memory/conversations/store/store_ops.rs
index 1189cb1d16..d657f75a8f 100644
--- a/src/openhuman/memory/conversations/store/store_ops.rs
+++ b/src/openhuman/memory/conversations/store/store_ops.rs
@@ -115,6 +115,15 @@ impl ConversationStore {
/// row, then a compact `MessageAppended` stat entry. Thread reads reconcile
/// that stat trail against the message file, repairing a crash between the
/// two appends.
+ ///
+ /// Idempotent by `message.id`: when the thread already holds a row with
+ /// that id, nothing is written (no message row, no stat bump, no index
+ /// insert) and the stored row is returned exactly as a fresh append would
+ /// return its input. Two writers can legitimately persist the same reply —
+ /// an autonomous run's `task_session::append_final` and the client that
+ /// also persists the `chat_done` it announced (#5933) — and a thread must
+ /// never carry two messages under one id (the frontend keys React and
+ /// assistant-ui resources by it).
pub fn append_message(
&self,
thread_id: &str,
@@ -125,6 +134,14 @@ impl ConversationStore {
return Err(format!("thread {} not found", thread_id));
}
let path = self.thread_messages_path(thread_id);
+ if path.exists() {
+ if let Some(existing) = read_jsonl::<ConversationMessage>(&path)?
+ .into_iter()
+ .find(|stored| stored.id == message.id)
+ {
+ return Ok(existing);
+ }
+ }
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("create conversation dir {}: {e}", parent.display()))?;
diff --git a/src/openhuman/memory/conversations/store/store_tests.rs b/src/openhuman/memory/conversations/store/store_tests.rs
index a47d879ffa..d00357271e 100644
--- a/src/openhuman/memory/conversations/store/store_tests.rs
+++ b/src/openhuman/memory/conversations/store/store_tests.rs
@@ -52,6 +52,54 @@ fn store_roundtrips_threads_and_messages() {
assert_eq!(messages[0].content, "hello");
}
+#[test]
+fn append_message_is_idempotent_by_message_id() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t".to_string(),
+ title: "Conversation".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+ let first = ConversationMessage {
+ id: "agent:run-1".to_string(),
+ content: "first".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "agent".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ };
+ store.append_message("t", first.clone()).expect("append");
+
+ // A second writer racing for the same id (the client persisting the
+ // `chat_done` an autonomous run already persisted itself — #5933).
+ let returned = store
+ .append_message(
+ "t",
+ ConversationMessage {
+ content: "second".to_string(),
+ created_at: "2026-04-10T12:02:00Z".to_string(),
+ ..first
+ },
+ )
+ .expect("append again");
+
+ // The stored row wins, and is what the second writer gets back.
+ assert_eq!(returned.content, "first");
+ assert_eq!(returned.created_at, "2026-04-10T12:01:00Z");
+ let messages = store.get_messages("t").expect("get messages");
+ assert_eq!(messages.len(), 1, "one id, one row");
+ assert_eq!(messages[0].content, "first");
+ // The no-op append did not bump the stat trail either.
+ let threads = store.list_threads().expect("list threads");
+ assert_eq!(threads[0].message_count, 1);
+ assert_eq!(threads[0].last_message_at, "2026-04-10T12:01:00Z");
+}
+
#[test]
fn get_messages_for_new_empty_thread_returns_empty_list() {
let (_temp, store) = make_store();
diff --git a/src/openhuman/web_chat/presentation.rs b/src/openhuman/web_chat/presentation.rs
index 44e14076cb..b0921856eb 100644
--- a/src/openhuman/web_chat/presentation.rs
+++ b/src/openhuman/web_chat/presentation.rs
@@ -76,46 +76,15 @@ pub(crate) async fn deliver_response(
if segments.len() <= 1 {
// Single bubble — emit chat_done directly.
- publish_web_channel_event(WebChannelEvent {
- event: "chat_done".to_string(),
- client_id: client_id.to_string(),
- thread_id: thread_id.to_string(),
- request_id: request_id.to_string(),
- full_response: Some(full_response.to_string()),
- message: None,
- error_type: None,
- error_source: None,
- error_retryable: None,
- error_retry_after_ms: None,
- error_provider: None,
- error_fallback_available: None,
- tool_name: None,
- skill_id: None,
- args: None,
- output: None,
- success: None,
- round: None,
+ publish_chat_done(
+ client_id,
+ thread_id,
+ request_id,
+ full_response,
reaction_emoji,
- segment_index: None,
- segment_total: None,
- delta: None,
- delta_kind: None,
- tool_call_id: None,
- failure: None,
- subagent: None,
- task_board: None,
- tool_display_label: None,
- tool_display_detail: None,
- citations: if citations.is_empty() {
- None
- } else {
- Some(serde_json::json!(citations))
- },
- usage: usage_payload,
- // Terminal delivery events are emitted outside the seq-stamping
- // progress bridge; leave `seq` unset (older clients ignore it).
- seq: None,
- });
+ citations,
+ usage_payload,
+ );
return;
}
@@ -213,6 +182,85 @@ pub(crate) async fn deliver_response(
});
}
+/// Deliver an agent response as exactly one `chat_done` bubble — no
+/// segmentation, no reaction — for turns the core runs on its own behalf
+/// (autonomous task sessions, background sub-agent result delivery).
+///
+/// Those turns persist their closing message themselves, as a single row,
+/// before announcing it (`task_session::append_final`). Splitting the reply
+/// into `chat_segment` bubbles would have a viewing client persist one row per
+/// segment beside that single row (#5933), so the conversational segmentation
+/// of [`deliver_response`] is deliberately not offered here.
+pub(crate) fn deliver_response_single_bubble(
+ client_id: &str,
+ thread_id: &str,
+ request_id: &str,
+ full_response: &str,
+ usage: Option<&LastTurnUsage>,
+) {
+ publish_chat_done(
+ client_id,
+ thread_id,
+ request_id,
+ full_response,
+ None,
+ &[],
+ usage_payload(usage),
+ );
+}
+
+/// Emit the terminal `chat_done` for an unsegmented reply.
+fn publish_chat_done(
+ client_id: &str,
+ thread_id: &str,
+ request_id: &str,
+ full_response: &str,
+ reaction_emoji: Option<String>,
+ citations: &[crate::openhuman::memory::agent::memory_loader::MemoryCitation],
+ usage_payload: Option<TurnUsagePayload>,
+) {
+ publish_web_channel_event(WebChannelEvent {
+ event: "chat_done".to_string(),
+ client_id: client_id.to_string(),
+ thread_id: thread_id.to_string(),
+ request_id: request_id.to_string(),
+ full_response: Some(full_response.to_string()),
+ message: None,
+ error_type: None,
+ error_source: None,
+ error_retryable: None,
+ error_retry_after_ms: None,
+ error_provider: None,
+ error_fallback_available: None,
+ tool_name: None,
+ skill_id: None,
+ args: None,
+ output: None,
+ success: None,
+ round: None,
+ reaction_emoji,
+ segment_index: None,
+ segment_total: None,
+ delta: None,
+ delta_kind: None,
+ tool_call_id: None,
+ failure: None,
+ subagent: None,
+ task_board: None,
+ tool_display_label: None,
+ tool_display_detail: None,
+ citations: if citations.is_empty() {
+ None
+ } else {
+ Some(serde_json::json!(citations))
+ },
+ usage: usage_payload,
+ // Terminal delivery events are emitted outside the seq-stamping
+ // progress bridge; leave `seq` unset (older clients ignore it).
+ seq: None,
+ });
+}
+
// ── Segmentation ─────────────────────────────────────────────────────────────
/// Decide whether and how to split a response into multiple chat bubbles.
diff --git a/src/openhuman/web_chat/presentation_tests.rs b/src/openhuman/web_chat/presentation_tests.rs
index cb04ff0ac7..270f6bd42f 100644
--- a/src/openhuman/web_chat/presentation_tests.rs
+++ b/src/openhuman/web_chat/presentation_tests.rs
@@ -270,3 +270,42 @@ fn segment_for_delivery_single_short_returns_one() {
let r = segment_for_delivery("Quick.");
assert_eq!(r.len(), 1);
}
+
+#[test]
+fn single_bubble_delivery_emits_one_unsegmented_chat_done_without_reaction() {
+ let mut rx = crate::openhuman::web_chat::subscribe_web_channel_events();
+ // Prose `deliver_response` WOULD split into several `chat_segment` bubbles
+ // (long, multi-paragraph, no fences) — the shape a background delivery turn
+ // produces. A core-persisted single row must be announced as one bubble.
+ let text = "Same three meetings as before, and nothing on the calendar moved since the last check.\n\n\
+ The product standup is still at noon and the design review still follows it at two.\n\n\
+ Nothing needs input from you right now, so I have not rescheduled anything on your behalf.";
+ assert!(
+ segment_for_delivery(text).len() > 1,
+ "fixture must be one the conversational path would segment"
+ );
+ let request_id = format!("single-bubble-{}", uuid::Uuid::new_v4());
+
+ deliver_response_single_bubble("system", "thread-1", &request_id, text, None);
+
+ // Other tests publish on the same process-global bus; keep only ours.
+ let mut mine = Vec::new();
+ loop {
+ match rx.try_recv() {
+ Ok(event) if event.request_id == request_id => mine.push(event),
+ Ok(_) => continue,
+ Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
+ Err(_) => break,
+ }
+ }
+ assert_eq!(mine.len(), 1, "exactly one terminal event, no chat_segment");
+ let done = &mine[0];
+ assert_eq!(done.event, "chat_done");
+ assert_eq!(done.client_id, "system");
+ assert_eq!(done.thread_id, "thread-1");
+ assert_eq!(done.full_response.as_deref(), Some(text));
+ assert_eq!(done.segment_total, None);
+ assert_eq!(done.segment_index, None);
+ assert_eq!(done.reaction_emoji, None);
+ assert!(done.usage.is_none());
+}