π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent-runtime): push UIChatMessage snapshot at gateway step boundaries (#15152)
Arvin Xu930344ae237d
diff --git a/.agents/skills/local-testing/references/agent-gateway.md b/.agents/skills/local-testing/references/agent-gateway.mdnew file mode 100644index 00000000000..de30fa23622--- /dev/null+++ b/.agents/skills/local-testing/references/agent-gateway.md@@ -0,0 +1,93 @@+# LobeHub gateway streaming + tab-switch test harness++Captures store + DOM state at 200ms intervals so we can prove or disprove+claims like "εε tab εζΆζ―εε°δΊεΎζ©δ»₯ε". Built for gateway-mode chat but+works for any LobeHub streaming session.++## Files++`scripts/agent-gateway/`++| File | Role |+| --------------- | ---------------------------------------------------------------- |+| `probe.js` | Injects a 200ms sampler + `__PROBE_EVENT` marker + `__switchTab` |+| `probe-dump.js` | Stops the sampler and returns `{events, samples}` as JSON string |+| `tab-switch.js` | Runs N round-trip switches between two tabs, marks each step |+| `analyze.mjs` | Node post-processor: timeline + regression detection |++## Standard workflow++```bash+# 1. Start Electron with CDP+./.agents/skills/local-testing/scripts/electron-dev.sh start++# 2. Navigate to a chat, switch runtime to Cloud Sandbox (gateway mode)++# 3. Install the probe + helpers+agent-browser --cdp 9222 eval --stdin \+ < .agents/skills/local-testing/scripts/agent-gateway/probe.js++# 4. Send a tool-call message β manually or via type+press+agent-browser --cdp 9222 eval "window.__PROBE_EVENT('SENT')"++# 5. Run the multi-switch driver (auto-picks active tab as BACK and the+# rightmost inactive tab as AWAY β edit ROUND_TRIPS / DWELL_MS in the+# file if you want different timing)+agent-browser --cdp 9222 eval --stdin \+ < .agents/skills/local-testing/scripts/agent-gateway/tab-switch.js++# 6. Wait for streaming to finish, then dump+agent-browser --cdp 9222 eval --stdin \+ < .agents/skills/local-testing/scripts/agent-gateway/probe-dump.js \+ > /tmp/probe.json++# 7. Analyze+node .agents/skills/local-testing/scripts/agent-gateway/analyze.mjs /tmp/probe.json+```++The analyzer prints three sections: EVENTS, TIMELINE, REGRESSIONS. If+REGRESSIONS is non-empty it means content/reasoning/childN dropped on the+same topic β the symptom users describe.++## What the probe tracks (and why)++`chat.messagesMap` only stores the top-level `assistantGroup` shell. The+actual streamed content, reasoning, and tool calls live in+`assistantGroup.children: AssistantContentBlock[]`. Any probe that only+reads `m.content` / `m.reasoning` will see zeros throughout streaming and+miss everything that matters. probe.js walks both levels and sums:++- `cT` total content length+- `rT` total reasoning length+- `toolT` total tool-call count+- `childN` number of content blocks++Plus DOM-side signals (`domLen`, search/crawl indicator counts) so you can+tell store-side regressions apart from render-side regressions.++## Gotchas++- **Optimistic new-topic state.** Before the first chunk lands, messages+ live under the `<scope>_new` key with `tmp_*` ids and no `topicId` field.+ probe.js falls back to those when `activeTopicId` is null.+- **Reasoning resets to 0 are not bugs.** When the assistant finishes+ thinking and starts tool-use or text, the streaming reasoning buffer+ empties and the finalised reasoning gets sealed into a completed block.+ Filter these out manually if needed.+- **DOM length jitters by a handful of chars** because counters like "(10)"+ in tool-call labels change as results arrive. analyze.mjs only flags+ `domLen` drops greater than 100 chars to ignore that noise.+- **Never identify tabs by innerText.** The active tab's text embeds a+ ` Β· <agent name>` suffix, so a search like `'LobeHub Growth'` matches the+ active tab when the active agent happens to be LobeHub Growth β and you+ end up clicking the tab you're already on. probe.js uses the stable+ `data-contextmenu-trigger` attribute (a React `useId()` value that's set+ per-tab and survives focus changes) plus `data-active="true"` to mark+ the active one. Helpers exposed:+ `__listTabs()` / `__clickTabByKey(key)` / `__clickTabByIndex(i)` /+ `__activeTabKey()`.+- **`tab-switch.js` fires-and-forgets.** The IIFE kicks off an async loop+ and returns immediately so the agent-browser CLI eval doesn't blow past+ its default 25 s timeout. Wait on the `SWITCH_LOOP_DONE` event marker+ before dumping. Re-running while a loop is in flight is refused β the+ chaotic data from overlapping runs is not worth debugging.diff --git a/.agents/skills/local-testing/scripts/agent-gateway/analyze.mjs b/.agents/skills/local-testing/scripts/agent-gateway/analyze.mjsnew file mode 100755index 00000000000..84e2c11e9a6--- /dev/null+++ b/.agents/skills/local-testing/scripts/agent-gateway/analyze.mjs@@ -0,0 +1,119 @@+#!/usr/bin/env node+// Analyze a probe dump captured by probe.js + probe-dump.js.+//+// node analyze.mjs /tmp/probe.json+//+// Prints:+// 1. EVENTS β user-action markers with their relative timestamps+// 2. TIMELINE β periodic samples (~1 per second + event-adjacent samples)+// showing every interesting field; columns:+// t(ms) | runOps | msgN | childN | content | reasoning | tools | domLen | search | crawl | topic | event+// 3. REGRESSIONS β every place a tracked counter *dropped* on the same+// topic between adjacent samples. A "true" UI rollback shows up as a+// drop in content/reasoning/tools/childN/domLen without a topic change.+//+// Whitelisted transitions (not flagged):+// - topic change β all drops expected (focus moved away)+// - reasoning length 0 after content starts β reasoning gets sealed into a+// completed sub-block; the parent's running reasoning resets to ''.+// - msgN drop when topic transitions from `_new` placeholder to a real id.++import fs from 'node:fs';++const file = process.argv[2];+if (!file) {+ console.error('usage: node analyze.mjs <probe.json>');+ process.exit(1);+}++const raw = JSON.parse(fs.readFileSync(file, 'utf8'));+// probe-dump.js wraps the payload in JSON.stringify so agent-browser returns+// it as a single quoted string. Unwrap.+const data = typeof raw === 'string' ? JSON.parse(raw) : raw;+const { events, samples } = data;++const fmt = {+ pad(v, n) {+ return String(v).padStart(n);+ },+};++console.log('=== EVENTS ===');+for (const e of events) console.log(` t=${fmt.pad(e.t, 7)} ${e.name}`);++console.log(+ '\n=== TIMELINE (~1s cadence, plus event-adjacent samples) ===\n' ++ ' t(ms) runOps msgN childN content reasoning tools domLen search crawl topic event',+);++let lastSampledAt = -1e9;+const eventBuckets = events.map((e) => e.t);+for (let i = 0; i < samples.length; i++) {+ const s = samples[i];+ const nearEvent = eventBuckets.some((et) => Math.abs(et - s.t) < 110);+ if (!nearEvent && s.t - lastSampledAt < 1000) continue;+ lastSampledAt = s.t;++ const ev = events.find((e) => Math.abs(e.t - s.t) < 110);+ const evMarker = ev ? ` β ${ev.name}` : '';+ const topicSuffix = s.topicId ? s.topicId.slice(-6) : '(none)';+ const search = s.ind?.search ?? 0;+ const crawl = s.ind?.crawl ?? 0;+ console.log(+ ` ${fmt.pad(s.t, 6)} ` ++ `${fmt.pad(s.runOps, 6)} ` ++ `${fmt.pad(s.msgN, 4)} ` ++ `${fmt.pad(s.childN ?? 0, 5)} ` ++ `${fmt.pad(s.cT ?? 0, 8)} ` ++ `${fmt.pad(s.rT ?? 0, 9)} ` ++ `${fmt.pad(s.toolT ?? 0, 5)} ` ++ `${fmt.pad(s.domLen ?? 0, 7)} ` ++ `${fmt.pad(search, 6)} ` ++ `${fmt.pad(crawl, 5)} ` ++ `${topicSuffix.padEnd(8)}${evMarker}`,+ );+}++console.log('\n=== REGRESSIONS (same topic, value dropped) ===');+const regressions = [];+for (let i = 1; i < samples.length; i++) {+ const prev = samples[i - 1];+ const cur = samples[i];+ if (!cur.topicId || prev.topicId !== cur.topicId) continue;++ const drops = [];+ if (cur.msgN < prev.msgN) drops.push(`msgN: ${prev.msgN}β${cur.msgN}`);+ if ((cur.childN ?? 0) < (prev.childN ?? 0)) drops.push(`childN: ${prev.childN}β${cur.childN}`);+ if ((cur.cT ?? 0) < (prev.cT ?? 0)) drops.push(`content: ${prev.cT}β${cur.cT}`);+ if ((cur.rT ?? 0) < (prev.rT ?? 0)) drops.push(`reasoning: ${prev.rT}β${cur.rT}`);+ if ((cur.toolT ?? 0) < (prev.toolT ?? 0)) drops.push(`tools: ${prev.toolT}β${cur.toolT}`);+ // domLen jitters by a few chars from counter labels β only flag big drops.+ if ((cur.domLen ?? 0) < (prev.domLen ?? 0) - 100) {+ drops.push(`domLen: ${prev.domLen}β${cur.domLen}`);+ }+ if (drops.length === 0) continue;++ const nearbyEv = events.filter((e) => Math.abs(e.t - cur.t) < 600).map((e) => e.name);+ regressions.push({ t: cur.t, topic: cur.topicId.slice(-6), drops, nearbyEv });+}++if (regressions.length === 0) {+ console.log(' (none)');+} else {+ for (const r of regressions) {+ const evStr = r.nearbyEv.length ? ` near:[${r.nearbyEv.join(',')}]` : '';+ console.log(` t=${fmt.pad(r.t, 7)} topic=${r.topic} ${r.drops.join(' | ')}${evStr}`);+ }+}++console.log(`\n=== SUMMARY ===`);+console.log(` samples: ${samples.length}`);+console.log(` events: ${events.length}`);+console.log(` regressions: ${regressions.length}`);+if (samples.length) {+ const last = samples.at(-1);+ console.log(+ ` final: msgN=${last.msgN} childN=${last.childN ?? 0} content=${last.cT ?? 0} ` ++ `reasoning=${last.rT ?? 0} tools=${last.toolT ?? 0} runOps=${last.runOps}`,+ );+}diff --git a/.agents/skills/local-testing/scripts/agent-gateway/probe-dump.js b/.agents/skills/local-testing/scripts/agent-gateway/probe-dump.jsnew file mode 100644index 00000000000..355c67147eb--- /dev/null+++ b/.agents/skills/local-testing/scripts/agent-gateway/probe-dump.js@@ -0,0 +1,17 @@+// Stop the probe and serialize collected data.+//+// agent-browser --cdp 9222 eval --stdin < probe-dump.js > /tmp/probe.json+//+// The whole thing is wrapped in a JSON.stringify so agent-browser returns it+// as a single quoted string β the analyzer double-parses to handle that.++(function () {+ if (window.__PROBE_TIMER) {+ clearInterval(window.__PROBE_TIMER);+ window.__PROBE_TIMER = null;+ }+ return JSON.stringify({+ events: window.__PROBE_EVENTS || [],+ samples: window.__PROBE_SAMPLES || [],+ });+})();diff --git a/.agents/skills/local-testing/scripts/agent-gateway/probe.js b/.agents/skills/local-testing/scripts/agent-gateway/probe.jsnew file mode 100644index 00000000000..2fb1aa74800--- /dev/null+++ b/.agents/skills/local-testing/scripts/agent-gateway/probe.js@@ -0,0 +1,204 @@+// LobeHub chat streaming time-series probe.+//+// Inject into the renderer (via agent-browser eval) to record store + DOM+// snapshots every 200ms during a streaming session. Designed to surface+// "UI rolled back to an earlier state" symptoms β especially around+// gateway-mode tab switches that happen while the assistant is still writing.+//+// Usage:+// agent-browser --cdp 9222 eval --stdin < probe.js+// # ...do test interactions, call window.__PROBE_EVENT('LABEL') to mark moments...+// agent-browser --cdp 9222 eval --stdin < probe-dump.js > /tmp/probe.json+// node analyze.mjs /tmp/probe.json+//+// What it captures per sample:+// - activeTopicId+// - msgN: top-level messages in chat.messagesMap for this topic+// - childN: total assistantGroup.children blocks across all msgs (THIS is+// where streaming content actually lives β top-level assistantGroup stays empty)+// - cT / rT / toolT: totals across messages AND their children+// (content, reasoning, tool-call count)+// - perMsg: per-message breakdown so regressions can be located precisely+// - runOps: number of running operations (execServerAgentRuntime etc.)+// - domLen: total innerText length of the rendered chat list area+// - ind: visible UI indicators (Search pages, Crawled pages, Deeply Thought, Sending)+//+// Event markers: window.__PROBE_EVENT('NAME') records {t, name} into+// __PROBE_EVENTS, used by the analyzer to align state changes with+// user-driven actions (SENT, AWAY_1, BACK_1, ...).++(function () {+ if (window.__PROBE_TIMER) clearInterval(window.__PROBE_TIMER);+ window.__PROBE_SAMPLES = [];+ window.__PROBE_EVENTS = [];+ const t0 = Date.now();++ function snapshot() {+ try {+ const chat = window.__LOBE_STORES.chat();+ const topicId = chat.activeTopicId;+ const idTail = topicId ? topicId.replace('tpc_', '') : null;+ const keys = Object.keys(chat.messagesMap || {});++ // Collect messages for the active topic. Before a topic is committed,+ // optimistic messages live under the `<agentScope>_new` key β fall+ // back to those when no topic is active yet.+ let msgs = [];+ if (idTail) {+ keys.forEach((k) => {+ if (k.includes(idTail)) msgs = msgs.concat(chat.messagesMap[k] || []);+ });+ } else {+ keys+ .filter((k) => k.endsWith('_new'))+ .forEach((k) => {+ msgs = msgs.concat(chat.messagesMap[k] || []);+ });+ }++ // Walk top-level + assistantGroup.children. children carry the actual+ // streamed content / reasoning / tool calls; the parent assistantGroup+ // remains a placeholder (cLen=0, rLen=0) for its whole lifetime.+ let totalContent = 0;+ let totalReason = 0;+ let totalTools = 0;+ let childCount = 0;+ const perMsg = msgs.map((m) => {+ const cLen = (m.content || '').length;+ const rLen = ((m.reasoning && m.reasoning.content) || '').length;+ const tools = (m.tools || []).length;+ totalContent += cLen;+ totalReason += rLen;+ totalTools += tools;++ const children = m.children || [];+ let chC = 0;+ let chR = 0;+ let chT = 0;+ children.forEach((c) => {+ chC += (c.content || '').length;+ chR += ((c.reasoning && c.reasoning.content) || '').length;+ chT += (c.tools || []).length;+ });+ totalContent += chC;+ totalReason += chR;+ totalTools += chT;+ childCount += children.length;++ return {+ id: (m.id || '').slice(-8),+ role: m.role,+ cLen,+ rLen,+ tools,+ chCount: children.length,+ chC,+ chR,+ chT,+ };+ });++ const ops = Object.values(chat.operations || {});+ const runningOps = ops.filter((o) => o.status === 'running');++ // DOM probe: total rendered text in the chat scroll area (proxy for+ // "how much is actually visible to the user").+ const convScroll =+ document.querySelector(+ '[data-chat-list], [class*="ChatList"], [class*="ConversationList"]',+ ) ||+ document.querySelector('main [class*="scroll"]') ||+ document.querySelector('main');+ const domTxt = convScroll ? convScroll.innerText || '' : '';++ const bodyTxt = document.body.innerText || '';+ const searchMatches = (bodyTxt.match(/Search pages?:|Searched the web/g) || []).length;+ const crawlMatches = (bodyTxt.match(/Crawl(ed|ing) pages?/g) || []).length;++ window.__PROBE_SAMPLES.push({+ t: Date.now() - t0,+ topicId,+ msgN: msgs.length,+ childN: childCount,+ cT: totalContent,+ rT: totalReason,+ toolT: totalTools,+ perMsg,+ runOps: runningOps.length,+ runOpTypes: runningOps.map((o) => o.type),+ domLen: domTxt.length,+ ind: {+ search: searchMatches,+ crawl: crawlMatches,+ sending: bodyTxt.includes('Sending message'),+ deeplyThinking: bodyTxt.includes('Deeply Thinking'),+ deeplyThought: bodyTxt.includes('Deeply Thought'),+ },+ });+ } catch (e) {+ window.__PROBE_SAMPLES.push({ t: Date.now() - t0, err: e.message });+ }+ }++ snapshot();+ window.__PROBE_TIMER = setInterval(snapshot, 200);+ window.__PROBE_EVENT = function (name) {+ window.__PROBE_EVENTS.push({ t: Date.now() - t0, name });+ };++ // Tab-switch helpers installed alongside the probe.+ //+ // The Electron tab bar mounts each tab as a div with data-insp-path+ // ending in `TabItem.tsx:...`. The active tab is marked with+ // data-active="true". DO NOT search by innerText β the active tab's text+ // includes a ` Β· <agent name>` suffix that produces false matches when+ // your search string happens to overlap with the agent name.+ function listTabs() {+ return Array.from(+ document.querySelectorAll('[data-insp-path*="TabItem.tsx"][data-contextmenu-trigger]'),+ ).filter((t) => t.getBoundingClientRect().top < 30);+ }+ function tabKey(el) {+ // Stable for the tab's lifetime; survives focus changes.+ return el.getAttribute('data-contextmenu-trigger');+ }+ function findActiveTab() {+ return listTabs().find((t) => t.getAttribute('data-active') === 'true') || null;+ }++ // Click by stable key captured earlier (preferred for round-trips).+ window.__clickTabByKey = function (key) {+ const tab = listTabs().find((t) => tabKey(t) === key);+ if (!tab) return 'not found: key=' + key;+ if (tab.getAttribute('data-active') === 'true') return 'already active: ' + key;+ tab.click();+ return 'clicked key=' + key;+ };++ // Click by index in the tab strip (0-based, left-to-right).+ window.__clickTabByIndex = function (i) {+ const tabs = listTabs();+ if (i < 0 || i >= tabs.length) return 'index out of range: ' + i + '/' + tabs.length;+ const t = tabs[i];+ if (t.getAttribute('data-active') === 'true') return 'already active: i=' + i;+ t.click();+ return 'clicked i=' + i + ' key=' + tabKey(t);+ };++ // Snapshot all tabs in order: [{key, active, title (first 60 chars of innerText)}]+ window.__listTabs = function () {+ return listTabs().map((t, i) => ({+ i,+ key: tabKey(t),+ active: t.getAttribute('data-active') === 'true',+ title: (t.innerText || '').slice(0, 60),+ }));+ };++ window.__activeTabKey = function () {+ const a = findActiveTab();+ return a ? tabKey(a) : null;+ };++ return 'probe installed';+})();diff --git a/.agents/skills/local-testing/scripts/agent-gateway/tab-switch.js b/.agents/skills/local-testing/scripts/agent-gateway/tab-switch.jsnew file mode 100644index 00000000000..54cd0d2c73f--- /dev/null+++ b/.agents/skills/local-testing/scripts/agent-gateway/tab-switch.js@@ -0,0 +1,72 @@+// Run N round-trip tab switches with event markers timed against the probe.+//+// agent-browser --cdp 9222 eval --stdin < tab-switch.js+//+// Captures the currently-active tab as the BACK target and the rightmost+// inactive tab as the AWAY target. Both are addressed by their stable+// data-contextmenu-trigger key (NOT by visible title β the active tab's+// innerText embeds a ` Β· <agent name>` suffix that breaks text matching).+//+// Fires the loop in the background and returns immediately so the+// agent-browser eval doesn't have to await the full ROUND_TRIPS Γ DWELL_MS+// duration. Wait on the `SWITCH_LOOP_DONE` event before dumping.+//+// Refuses to launch if a previous loop is still in flight.+//+// Requires probe.js to have been installed first (provides+// window.__PROBE_EVENT / __listTabs / __clickTabByKey / __activeTabKey).++(function () {+ const ROUND_TRIPS = 4;+ const DWELL_MS = 10_000;++ if (!window.__PROBE_EVENT || !window.__listTabs || !window.__clickTabByKey) {+ return 'probe not installed β eval probe.js first';+ }+ if (window.__SWITCH_LOOP_RUNNING) {+ return 'switch loop already running β wait for SWITCH_LOOP_DONE first';+ }++ const tabs = window.__listTabs();+ const activeTab = tabs.find((t) => t.active);+ if (!activeTab) return 'no active tab β abort';++ // Pick the first inactive tab as AWAY target. With multiple inactive tabs+ // you'll usually want the one that's stable across the test β feel free+ // to swap to tabs[tabs.length-1] if you want the rightmost.+ const inactives = tabs.filter((t) => !t.active);+ if (inactives.length === 0) return 'no inactive tab to switch to β abort';+ const awayTab = inactives.at(-1); // rightmost inactive++ const BACK_KEY = activeTab.key;+ const AWAY_KEY = awayTab.key;++ window.__SWITCH_LOOP_RUNNING = true;+ window.__PROBE_EVENT('SWITCH_LOOP_CONFIG:back=' + BACK_KEY + ',away=' + AWAY_KEY);++ (async function () {+ function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+ }++ try {+ window.__PROBE_EVENT('SWITCH_LOOP_START');+ for (let i = 1; i <= ROUND_TRIPS; i++) {+ window.__PROBE_EVENT('AWAY_' + i);+ const awayResult = window.__clickTabByKey(AWAY_KEY);+ window.__PROBE_EVENT('AWAY_' + i + '_RES:' + awayResult.slice(0, 50));+ await sleep(DWELL_MS);++ window.__PROBE_EVENT('BACK_' + i);+ const backResult = window.__clickTabByKey(BACK_KEY);+ window.__PROBE_EVENT('BACK_' + i + '_RES:' + backResult.slice(0, 50));+ await sleep(DWELL_MS);+ }+ window.__PROBE_EVENT('SWITCH_LOOP_DONE');+ } finally {+ window.__SWITCH_LOOP_RUNNING = false;+ }+ })();++ return 'switch loop kicked off (BACK=' + BACK_KEY + ', AWAY=' + AWAY_KEY + ')';+})();diff --git a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex 34f122e3358..c9972a6e170 100644--- a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -1,4 +1,5 @@import { type AgentState } from '@lobechat/agent-runtime';+import { type UIChatMessage } from '@lobechat/types';import debug from 'debug';import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';@@ -43,6 +44,17 @@ export interface AgentRuntimeCoordinatorOptions {* Defaults to automatic selection based on Redis availability*/streamEventManager?: IStreamEventManager;+ /**+ * Resolve the canonical UIChatMessage[] snapshot for a terminal-state+ * agent run, attached to `agent_runtime_end` events so the client can+ * use the pushed payload as Source of Truth instead of refetching from+ * DB.+ *+ * Optional: when omitted (e.g. tests, embedded usage without DB access)+ * the coordinator falls back to publishing without `uiMessages` and the+ * client behaves as before.+ */+ uiMessagesResolver?: (state: AgentState) => Promise<UIChatMessage[] | undefined>;}/**@@ -59,10 +71,12 @@ export interface AgentRuntimeCoordinatorOptions {export class AgentRuntimeCoordinator {private stateManager: IAgentStateManager;private streamEventManager: IStreamEventManager;+ private uiMessagesResolver?: (state: AgentState) => Promise<UIChatMessage[] | undefined>;constructor(options?: AgentRuntimeCoordinatorOptions) {this.stateManager = options?.stateManager ?? createAgentStateManager();this.streamEventManager = options?.streamEventManager ?? createStreamEventManager();+ this.uiMessagesResolver = options?.uiMessagesResolver;}/**@@ -94,6 +108,22 @@ export class AgentRuntimeCoordinator {}}+ /**+ * Invoke the optional uiMessagesResolver and shield callers from its+ * failures β stream-event publishing must never fail the surrounding+ * save. Errors are logged and surfaced to the client as a missing field,+ * which falls back to the legacy refresh path.+ */+ private async resolveUiMessages(state: AgentState): Promise<UIChatMessage[] | undefined> {+ if (!this.uiMessagesResolver) return undefined;+ try {+ return await this.uiMessagesResolver(state);+ } catch (error) {+ console.error('Failed to resolve uiMessages for agent_runtime_end:', error);+ return undefined;+ }+ }+/*** Save Agent state and handle corresponding events*/@@ -106,12 +136,13 @@ export class AgentRuntimeCoordinator {// Send a terminal event once the operation first enters a terminal state.if (hasEnteredStreamEndState(previousState?.status, state.status)) {- await this.streamEventManager.publishAgentRuntimeEnd(+ await this.streamEventManager.publishAgentRuntimeEnd({+ finalState: state,operationId,- state.stepCount ?? previousState?.stepCount ?? 0,- state,- state.status,- );+ reason: state.status,+ stepIndex: state.stepCount ?? previousState?.stepCount ?? 0,+ uiMessages: await this.resolveUiMessages(state),+ });log('[%s] Agent runtime reached terminal state: %s', operationId, state.status);}} catch (error) {@@ -133,12 +164,14 @@ export class AgentRuntimeCoordinator {// This ensures agent_runtime_end is sent after all step events.if (hasEnteredStreamEndState(previousState?.status, stepResult.newState.status)) {- await this.streamEventManager.publishAgentRuntimeEnd(+ await this.streamEventManager.publishAgentRuntimeEnd({+ finalState: stepResult.newState,operationId,- stepResult.newState.stepCount ?? stepResult.stepIndex ?? previousState?.stepCount ?? 0,- stepResult.newState,- stepResult.newState.status,- );+ reason: stepResult.newState.status,+ stepIndex:+ stepResult.newState.stepCount ?? stepResult.stepIndex ?? previousState?.stepCount ?? 0,+ uiMessages: await this.resolveUiMessages(stepResult.newState),+ });log('[%s] Agent runtime reached terminal state after step result: %s',operationId,diff --git a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts b/src/server/modules/AgentRuntime/GatewayStreamNotifier.tsindex 944122776f8..85fe2657017 100644--- a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -7,7 +7,7 @@ import {type StreamChunkData,type StreamEvent,} from './StreamEventManager';-import type { IStreamEventManager } from './types';+import type { IStreamEventManager, PublishAgentRuntimeEndParams } from './types';const log = debug('lobe-server:agent-runtime:gateway-notifier');@@ -78,26 +78,25 @@ export class GatewayStreamNotifier implements IStreamEventManager {return result;}- async publishAgentRuntimeEnd(- operationId: string,- stepIndex: number,- finalState: any,- reason?: string,- reasonDetail?: string,- ): Promise<string> {- const result = await this.inner.publishAgentRuntimeEnd(- operationId,- stepIndex,- finalState,- reason,- reasonDetail,- );+ async publishAgentRuntimeEnd(params: PublishAgentRuntimeEndParams): Promise<string> {+ const { operationId, stepIndex, finalState, reason, reasonDetail, uiMessages } = params;+ const result = await this.inner.publishAgentRuntimeEnd(params);const effectiveReasonDetail = reasonDetail || getDefaultReasonDetail(finalState, reason);const errorType = finalState?.error?.type || finalState?.error?.errorType;this.pushEvent(operationId, {- data: { errorType, finalState, reason, reasonDetail: effectiveReasonDetail },+ // Forward `uiMessages` to the gateway push channel so terminal-state+ // clients consuming /push-event get the canonical UIChatMessage[]+ // snapshot β the final step has no later step_start to carry a fresh+ // snapshot, so dropping it here would break the SoT contract.+ data: {+ errorType,+ finalState,+ reason,+ reasonDetail: effectiveReasonDetail,+ ...(uiMessages !== undefined && { uiMessages }),+ },operationId,stepIndex,timestamp: Date.now(),diff --git a/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts b/src/server/modules/AgentRuntime/InMemoryStreamEventManager.tsindex 894db9c50e0..199d9e8aed8 100644--- a/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts+++ b/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts@@ -1,7 +1,7 @@import debug from 'debug';import { type StreamChunkData, type StreamEvent } from './StreamEventManager';-import { type IStreamEventManager } from './types';+import { type IStreamEventManager, type PublishAgentRuntimeEndParams } from './types';const log = debug('lobe-server:agent-runtime:in-memory-stream-event-manager');@@ -97,13 +97,14 @@ export class InMemoryStreamEventManager implements IStreamEventManager {});}- async publishAgentRuntimeEnd(- operationId: string,- stepIndex: number,- finalState: any,- reason?: string,- reasonDetail?: string,- ): Promise<string> {+ async publishAgentRuntimeEnd({+ operationId,+ stepIndex,+ finalState,+ reason,+ reasonDetail,+ uiMessages,+ }: PublishAgentRuntimeEndParams): Promise<string> {return this.publishStreamEvent(operationId, {data: {finalState,@@ -111,6 +112,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {phase: 'execution_complete',reason: reason || 'completed',reasonDetail: reasonDetail || getDefaultReasonDetail(finalState, reason),+ ...(uiMessages !== undefined && { uiMessages }),},stepIndex,type: 'agent_runtime_end',diff --git a/src/server/modules/AgentRuntime/StreamEventManager.ts b/src/server/modules/AgentRuntime/StreamEventManager.tsindex 1152ae17797..4cdd07a696d 100644--- a/src/server/modules/AgentRuntime/StreamEventManager.ts+++ b/src/server/modules/AgentRuntime/StreamEventManager.ts@@ -4,6 +4,7 @@ import debug from 'debug';import { type Redis } from 'ioredis';import { getAgentRuntimeRedisClient } from './redis';+import { type PublishAgentRuntimeEndParams } from './types';const log = debug('lobe-server:agent-runtime:stream-event-manager');const timing = debug('lobe-server:agent-runtime:timing');@@ -182,13 +183,14 @@ export class StreamEventManager {/*** Publish Agent runtime end event*/- async publishAgentRuntimeEnd(- operationId: string,- stepIndex: number,- finalState: any,- reason?: string,- reasonDetail?: string,- ): Promise<string> {+ async publishAgentRuntimeEnd({+ operationId,+ stepIndex,+ finalState,+ reason,+ reasonDetail,+ uiMessages,+ }: PublishAgentRuntimeEndParams): Promise<string> {return this.publishStreamEvent(operationId, {data: {finalState,@@ -196,6 +198,7 @@ export class StreamEventManager {phase: 'execution_complete',reason: reason || 'completed',reasonDetail: reasonDetail || getDefaultReasonDetail(finalState, reason),+ ...(uiMessages !== undefined && { uiMessages }),},stepIndex,type: 'agent_runtime_end',diff --git a/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.tsindex 99fb707c3bf..a7d0fd81df1 100644--- a/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts@@ -95,12 +95,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveAgentState(operationId, newState as any);expect(mockStateManager.saveAgentState).toHaveBeenCalledWith(operationId, newState);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,operationId,- newState.stepCount,- newState,- 'done',- );+ reason: 'done',+ stepIndex: newState.stepCount,+ uiMessages: undefined,+ });});it('should publish end event when status changes to error', async () => {@@ -112,12 +113,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveAgentState(operationId, newState as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,operationId,- newState.stepCount,- newState,- 'error',- );+ reason: 'error',+ stepIndex: newState.stepCount,+ uiMessages: undefined,+ });});it('should fallback to previous stepCount when terminal state is missing stepCount', async () => {@@ -129,12 +131,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveAgentState(operationId, newState as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,operationId,- previousState.stepCount,- newState,- 'error',- );+ reason: 'error',+ stepIndex: previousState.stepCount,+ uiMessages: undefined,+ });});it('should publish end event when status changes to interrupted', async () => {@@ -146,12 +149,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveAgentState(operationId, newState as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,operationId,- newState.stepCount,- newState,- 'interrupted',- );+ reason: 'interrupted',+ stepIndex: newState.stepCount,+ uiMessages: undefined,+ });});it('should publish end event when status changes to waiting_for_human so the client releases its loading state', async () => {@@ -163,12 +167,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveAgentState(operationId, newState as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,operationId,- newState.stepCount,- newState,- 'waiting_for_human',- );+ reason: 'waiting_for_human',+ stepIndex: newState.stepCount,+ uiMessages: undefined,+ });});it('should not publish end event when status was already done', async () => {@@ -214,12 +219,13 @@ describe('AgentRuntimeCoordinator', () => {expect(mockStateManager.loadAgentState).toHaveBeenCalledWith(operationId);expect(mockStateManager.saveStepResult).toHaveBeenCalledWith(operationId, stepResult);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,operationId,- 5,- stepResult.newState,- 'done',- );+ reason: 'done',+ stepIndex: 5,+ uiMessages: undefined,+ });});it('should publish end event when status becomes error', async () => {@@ -234,12 +240,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveStepResult(operationId, stepResult as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,operationId,- 5,- stepResult.newState,- 'error',- );+ reason: 'error',+ stepIndex: 5,+ uiMessages: undefined,+ });});it('should fallback to stepResult.stepIndex when terminal step result state is missing stepCount', async () => {@@ -254,12 +261,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveStepResult(operationId, stepResult as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,operationId,- stepResult.stepIndex,- stepResult.newState,- 'error',- );+ reason: 'error',+ stepIndex: stepResult.stepIndex,+ uiMessages: undefined,+ });});it('should publish end event when status becomes waiting_for_human (paused awaiting approval)', async () => {@@ -274,12 +282,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveStepResult(operationId, stepResult as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,operationId,- 4,- stepResult.newState,- 'waiting_for_human',- );+ reason: 'waiting_for_human',+ stepIndex: 4,+ uiMessages: undefined,+ });});it('should publish end event when status becomes interrupted', async () => {@@ -294,12 +303,13 @@ describe('AgentRuntimeCoordinator', () => {await coordinator.saveStepResult(operationId, stepResult as any);- expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,operationId,- 5,- stepResult.newState,- 'interrupted',- );+ reason: 'interrupted',+ stepIndex: 5,+ uiMessages: undefined,+ });});it('should not publish end event when status is not done', async () => {@@ -395,4 +405,105 @@ describe('AgentRuntimeCoordinator', () => {expect(result).toBe(expectedHistory);});});++ // Terminal events should carry the canonical UIChatMessage[] snapshot+ // when a resolver is wired so the client can use the pushed payload as+ // Source of Truth instead of refetching from DB.+ describe('uiMessagesResolver on agent_runtime_end', () => {+ it('passes resolver result through saveAgentState terminal publish', async () => {+ const uiMessages = [{ id: 'msg_1', role: 'user' }] as any[];+ const resolver = vi.fn().mockResolvedValue(uiMessages);+ const coordinatorWithResolver = new AgentRuntimeCoordinator({+ stateManager: mockStateManager,+ streamEventManager: mockStreamManager,+ uiMessagesResolver: resolver,+ });++ const previousState = { status: 'running', stepCount: 3 };+ const newState = { status: 'done', stepCount: 5 };+ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinatorWithResolver.saveAgentState('op-1', newState as any);++ expect(resolver).toHaveBeenCalledWith(newState);+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,+ operationId: 'op-1',+ reason: 'done',+ stepIndex: 5,+ uiMessages,+ });+ });++ it('passes resolver result through saveStepResult terminal publish', async () => {+ const uiMessages = [{ id: 'msg_a', role: 'assistantGroup' }] as any[];+ const resolver = vi.fn().mockResolvedValue(uiMessages);+ const coordinatorWithResolver = new AgentRuntimeCoordinator({+ stateManager: mockStateManager,+ streamEventManager: mockStreamManager,+ uiMessagesResolver: resolver,+ });++ const stepResult = {+ executionTime: 100,+ newState: { status: 'done', stepCount: 4 },+ stepIndex: 4,+ };+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 3 });++ await coordinatorWithResolver.saveStepResult('op-2', stepResult as any);++ expect(resolver).toHaveBeenCalledWith(stepResult.newState);+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,+ operationId: 'op-2',+ reason: 'done',+ stepIndex: 4,+ uiMessages,+ });+ });++ it('publishes with uiMessages=undefined when resolver rejects (must never fail the surrounding save)', async () => {+ const resolver = vi.fn().mockRejectedValue(new Error('db down'));+ const coordinatorWithResolver = new AgentRuntimeCoordinator({+ stateManager: mockStateManager,+ streamEventManager: mockStreamManager,+ uiMessagesResolver: resolver,+ });++ const previousState = { status: 'running', stepCount: 3 };+ const newState = { status: 'error', stepCount: 5 };+ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinatorWithResolver.saveAgentState('op-3', newState as any);++ expect(resolver).toHaveBeenCalled();+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,+ operationId: 'op-3',+ reason: 'error',+ stepIndex: 5,+ uiMessages: undefined,+ });+ });++ it('publishes with uiMessages=undefined when no resolver is wired (default constructor)', async () => {+ // The default `coordinator` from the outer beforeEach is constructed+ // without a resolver β proves the field is genuinely optional and+ // legacy call sites stay unaffected.+ const previousState = { status: 'running', stepCount: 3 };+ const newState = { status: 'done', stepCount: 5 };+ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinator.saveAgentState('op-4', newState as any);++ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,+ operationId: 'op-4',+ reason: 'done',+ stepIndex: 5,+ uiMessages: undefined,+ });+ });+ });});diff --git a/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex 6c0d9fe9c7a..b54d1f74c26 100644--- a/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -131,21 +131,27 @@ describe('GatewayStreamNotifier', () => {it('delegates to inner and returns its result', async () => {const finalState = { status: 'done' };- const result = await notifier.publishAgentRuntimeEnd('op-1', 2, finalState, 'completed');+ const params = {+ finalState,+ operationId: 'op-1',+ reason: 'completed',+ stepIndex: 2,+ };+ const result = await notifier.publishAgentRuntimeEnd(params);expect(result).toBe('publishAgentRuntimeEnd-result');expect(inner.calls.publishAgentRuntimeEnd).toHaveLength(1);- expect(inner.calls.publishAgentRuntimeEnd[0]).toEqual([- 'op-1',- 2,- finalState,- 'completed',- undefined,- ]);+ expect(inner.calls.publishAgentRuntimeEnd[0]).toEqual([params]);});it('calls gateway push-event endpoint only (no update-status)', async () => {- await notifier.publishAgentRuntimeEnd('op-1', 2, {}, 'completed', 'All done');+ await notifier.publishAgentRuntimeEnd({+ finalState: {},+ operationId: 'op-1',+ reason: 'completed',+ reasonDetail: 'All done',+ stepIndex: 2,+ });await new Promise((r) => setTimeout(r, 50));@@ -163,7 +169,12 @@ describe('GatewayStreamNotifier', () => {},};- await notifier.publishAgentRuntimeEnd('op-1', 0, finalState, 'error');+ await notifier.publishAgentRuntimeEnd({+ finalState,+ operationId: 'op-1',+ reason: 'error',+ stepIndex: 0,+ });await new Promise((r) => setTimeout(r, 50));const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));@@ -176,7 +187,13 @@ describe('GatewayStreamNotifier', () => {error: { message: 'Some error' },};- await notifier.publishAgentRuntimeEnd('op-1', 0, finalState, 'error', 'Custom detail');+ await notifier.publishAgentRuntimeEnd({+ finalState,+ operationId: 'op-1',+ reason: 'error',+ reasonDetail: 'Custom detail',+ stepIndex: 0,+ });await new Promise((r) => setTimeout(r, 50));const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));@@ -189,7 +206,12 @@ describe('GatewayStreamNotifier', () => {error: { message: 'Budget exceeded', type: 'InsufficientBudgetForModel' },};- await notifier.publishAgentRuntimeEnd('op-1', 0, finalState, 'error');+ await notifier.publishAgentRuntimeEnd({+ finalState,+ operationId: 'op-1',+ reason: 'error',+ stepIndex: 0,+ });await new Promise((r) => setTimeout(r, 50));const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));@@ -205,7 +227,12 @@ describe('GatewayStreamNotifier', () => {},};- await notifier.publishAgentRuntimeEnd('op-1', 0, finalState, 'error');+ await notifier.publishAgentRuntimeEnd({+ finalState,+ operationId: 'op-1',+ reason: 'error',+ stepIndex: 0,+ });await new Promise((r) => setTimeout(r, 50));const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));@@ -214,13 +241,49 @@ describe('GatewayStreamNotifier', () => {});it('errorType is undefined when no error in finalState', async () => {- await notifier.publishAgentRuntimeEnd('op-1', 0, { status: 'done' }, 'completed');+ await notifier.publishAgentRuntimeEnd({+ finalState: { status: 'done' },+ operationId: 'op-1',+ reason: 'completed',+ stepIndex: 0,+ });await new Promise((r) => setTimeout(r, 50));const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));const body = JSON.parse(pushCall![1].body);expect(body.event.data.errorType).toBeUndefined();});++ it('forwards uiMessages to the gateway push payload when provided', async () => {+ const uiMessages = [{ id: 'msg_z', role: 'assistantGroup' }] as any;++ await notifier.publishAgentRuntimeEnd({+ finalState: { status: 'done' },+ operationId: 'op-1',+ reason: 'completed',+ stepIndex: 4,+ uiMessages,+ });+ await new Promise((r) => setTimeout(r, 50));++ const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));+ const body = JSON.parse(pushCall![1].body);+ expect(body.event.data.uiMessages).toEqual(uiMessages);+ });++ it('omits uiMessages from the gateway push payload when not provided', async () => {+ await notifier.publishAgentRuntimeEnd({+ finalState: { status: 'done' },+ operationId: 'op-1',+ reason: 'completed',+ stepIndex: 4,+ });+ await new Promise((r) => setTimeout(r, 50));++ const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));+ const body = JSON.parse(pushCall![1].body);+ expect(body.event.data).not.toHaveProperty('uiMessages');+ });});// βββ Read/subscribe methods: must delegate directly to inner βββ@@ -306,7 +369,12 @@ describe('GatewayStreamNotifier', () => {() => new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 10)),);- const result = await notifier.publishAgentRuntimeEnd('op-1', 0, {}, 'completed');+ const result = await notifier.publishAgentRuntimeEnd({+ finalState: {},+ operationId: 'op-1',+ reason: 'completed',+ stepIndex: 0,+ });expect(result).toBe('publishAgentRuntimeEnd-result');expect(inner.calls.publishAgentRuntimeEnd).toHaveLength(1);diff --git a/src/server/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts b/src/server/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.tsindex ef7a8c316c3..bdb7fcfd954 100644--- a/src/server/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts@@ -157,4 +157,46 @@ describe('InMemoryStreamEventManager', () => {expect(manager.getAllEvents('op-1')).toHaveLength(0);});});++ // agent_runtime_end optionally carries the canonical UIChatMessage[]+ // snapshot so the client can use the pushed payload as Source of Truth+ // instead of refetching from DB.+ describe('publishAgentRuntimeEnd uiMessages', () => {+ it('includes uiMessages in event data when provided', async () => {+ const uiMessages = [+ { id: 'msg_u', role: 'user' },+ { id: 'msg_a', role: 'assistantGroup' },+ ] as any[];+ const finalState = { status: 'done', stepCount: 3 };++ await manager.publishAgentRuntimeEnd({+ finalState,+ operationId: 'op-1',+ reason: 'done',+ stepIndex: 3,+ uiMessages,+ });++ const events = manager.getAllEvents('op-1');+ expect(events).toHaveLength(1);+ expect(events[0].type).toBe('agent_runtime_end');+ expect(events[0].data.uiMessages).toEqual(uiMessages);+ expect(events[0].data.finalState).toEqual(finalState);+ });++ it('omits uiMessages when not provided (legacy callers stay unaffected)', async () => {+ const finalState = { status: 'done', stepCount: 3 };++ await manager.publishAgentRuntimeEnd({+ finalState,+ operationId: 'op-1',+ reason: 'done',+ stepIndex: 3,+ });++ const events = manager.getAllEvents('op-1');+ expect(events[0].data).not.toHaveProperty('uiMessages');+ expect(events[0].data.finalState).toEqual(finalState);+ });+ });});diff --git a/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.tsindex 03e4ac3215e..d46ccf938b0 100644--- a/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts@@ -75,7 +75,11 @@ describe('StreamEventManager', () => {mockRedis.xadd.mockResolvedValue('event-id-456');- const result = await streamManager.publishAgentRuntimeEnd(operationId, stepIndex, finalState);+ const result = await streamManager.publishAgentRuntimeEnd({+ finalState,+ operationId,+ stepIndex,+ });expect(result).toBe('event-id-456');expect(mockRedis.xadd).toHaveBeenCalledWith(@@ -103,6 +107,50 @@ describe('StreamEventManager', () => {);});+ // agent_runtime_end optionally carries the canonical UIChatMessage[]+ // snapshot so the client can use the pushed payload as Source of Truth+ // instead of refetching from DB.+ it('should include uiMessages in serialized data when provided', async () => {+ const operationId = 'test-operation-id';+ const stepIndex = 5;+ const finalState = { status: 'done', stepCount: 5 };+ const uiMessages = [{ id: 'msg_a', role: 'assistantGroup' }] as any;++ mockRedis.xadd.mockResolvedValue('event-id-ui');++ await streamManager.publishAgentRuntimeEnd({+ finalState,+ operationId,+ reason: 'done',+ stepIndex,+ uiMessages,+ });++ // Find the serialized `data` argument inline so this test stays robust+ // if other positional args shift around.+ const dataArg = mockRedis.xadd.mock.calls[0]?.find(+ (a: any) => typeof a === 'string' && a.startsWith('{'),+ );+ const parsed = JSON.parse(dataArg);+ expect(parsed.uiMessages).toEqual(uiMessages);+ expect(parsed.finalState).toEqual(finalState);+ });++ it('should omit uiMessages from serialized data when not provided', async () => {+ const operationId = 'test-operation-id';+ const finalState = { status: 'done', stepCount: 3 };++ mockRedis.xadd.mockResolvedValue('event-id-noui');++ await streamManager.publishAgentRuntimeEnd({ finalState, operationId, stepIndex: 3 });++ const dataArg = mockRedis.xadd.mock.calls[0]?.find(+ (a: any) => typeof a === 'string' && a.startsWith('{'),+ );+ const parsed = JSON.parse(dataArg);+ expect(parsed).not.toHaveProperty('uiMessages');+ });+it('should accept custom reason and reasonDetail', async () => {const operationId = 'test-operation-id';const stepIndex = 3;@@ -112,13 +160,13 @@ describe('StreamEventManager', () => {mockRedis.xadd.mockResolvedValue('event-id-789');- await streamManager.publishAgentRuntimeEnd(- operationId,- stepIndex,+ await streamManager.publishAgentRuntimeEnd({finalState,+ operationId,reason,reasonDetail,- );+ stepIndex,+ });expect(mockRedis.xadd).toHaveBeenCalledWith(expect.any(String),@@ -158,7 +206,12 @@ describe('StreamEventManager', () => {mockRedis.xadd.mockResolvedValue('event-id-790');- await streamManager.publishAgentRuntimeEnd(operationId, stepIndex, finalState, 'error');+ await streamManager.publishAgentRuntimeEnd({+ finalState,+ operationId,+ reason: 'error',+ stepIndex,+ });expect(mockRedis.xadd).toHaveBeenCalledWith(expect.any(String),diff --git a/src/server/modules/AgentRuntime/types.ts b/src/server/modules/AgentRuntime/types.tsindex 18902e11f72..ca971abbdb0 100644--- a/src/server/modules/AgentRuntime/types.ts+++ b/src/server/modules/AgentRuntime/types.ts@@ -1,9 +1,24 @@import type { ToolExecuteData } from '@lobechat/agent-gateway-client';import { type AgentState } from '@lobechat/agent-runtime';+import { type UIChatMessage } from '@lobechat/types';import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';import { type StreamChunkData, type StreamEvent } from './StreamEventManager';+export interface PublishAgentRuntimeEndParams {+ finalState: any;+ operationId: string;+ reason?: string;+ reasonDetail?: string;+ stepIndex: number;+ /**+ * Canonical UIChatMessage[] snapshot of the topic at terminal-state time.+ * When present, the client uses this directly as Source of Truth instead+ * of refetching from DB.+ */+ uiMessages?: UIChatMessage[];+}+/*** Agent State Manager Interface* Abstract interface for state persistence, supports Redis and in-memory implementations@@ -114,15 +129,14 @@ export interface IStreamEventManager {getStreamHistory: (operationId: string, count?: number) => Promise<StreamEvent[]>;/**- * Publish Agent runtime end event+ * Publish Agent runtime end event.+ *+ * `uiMessages` is the canonical UIChatMessage[] snapshot of the topic at+ * terminal-state time so the client can use the pushed payload as Source+ * of Truth instead of refetching from DB. Optional: callers without DB+ * access may omit it and the client falls back to its existing behaviour.*/- publishAgentRuntimeEnd: (- operationId: string,- stepIndex: number,- finalState: any,- reason?: string,- reasonDetail?: string,- ) => Promise<string>;+ publishAgentRuntimeEnd: (params: PublishAgentRuntimeEndParams) => Promise<string>;/*** Publish Agent runtime initialization eventdiff --git a/src/server/routers/lambda/agentNotify.ts b/src/server/routers/lambda/agentNotify.tsindex fa2e27dbfce..de0ec31e083 100644--- a/src/server/routers/lambda/agentNotify.ts+++ b/src/server/routers/lambda/agentNotify.ts@@ -132,13 +132,13 @@ export const agentNotifyRouter = router({const stream = getStreamManager();if (done) {// Signal task completion β frontend gateway WS subscription closes.- await stream.publishAgentRuntimeEnd(- remoteOperationId,- 0,- { reason: 'success' },- 'success',- 'Remote hetero agent task completed',- );+ await stream.publishAgentRuntimeEnd({+ finalState: { reason: 'success' },+ operationId: remoteOperationId,+ reason: 'success',+ reasonDetail: 'Remote hetero agent task completed',+ stepIndex: 0,+ });} else {// Lightweight invalidation β frontend calls fetchAndReplaceMessages.await stream.publishStreamEvent(remoteOperationId, {diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.tsindex f1b696d8682..28a2913dc0c 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts@@ -1478,4 +1478,55 @@ describe('AgentRuntimeService', () => {expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();});});++ // Stream events at step / operation boundaries should carry the canonical+ // UIChatMessage[] snapshot so the client can use the pushed payload as+ // Source of Truth instead of refetching from DB.+ describe('queryUiMessages', () => {+ const stubMessageService = (svc: any, queryMessages: ReturnType<typeof vi.fn>) => {+ svc.messageServiceInstance = { queryMessages };+ };++ it('returns messageService.queryMessages result when agentId + topicId are present', async () => {+ const stubMessages = [{ id: 'msg_x', role: 'user' }];+ const queryMessages = vi.fn().mockResolvedValue(stubMessages);+ stubMessageService(service, queryMessages);++ const result = await service.queryUiMessages({+ metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages).toHaveBeenCalledWith({ agentId: 'agt_1', topicId: 'tpc_1' });+ expect(result).toEqual(stubMessages);+ });++ it('returns undefined when agentId or topicId is missing (skips empty-array push)', async () => {+ const queryMessages = vi.fn();+ stubMessageService(service, queryMessages);++ const noAgent = await service.queryUiMessages({+ metadata: { topicId: 'tpc_1' },+ } as any);+ const noTopic = await service.queryUiMessages({+ metadata: { agentId: 'agt_1' },+ } as any);+ const noMeta = await service.queryUiMessages({} as any);++ expect(noAgent).toBeUndefined();+ expect(noTopic).toBeUndefined();+ expect(noMeta).toBeUndefined();+ expect(queryMessages).not.toHaveBeenCalled();+ });++ it('returns undefined and never throws when DB query fails (stream events must not fail the step)', async () => {+ const queryMessages = vi.fn().mockRejectedValue(new Error('db down'));+ stubMessageService(service, queryMessages);++ const result = await service.queryUiMessages({+ metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(result).toBeUndefined();+ });+ });});diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 765f151586a..2f288f92caa 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -13,6 +13,7 @@ import {ChatErrorType,type ChatMessageError,type ExecSubAgentTaskParams,+ type UIChatMessage,} from '@lobechat/types';import debug from 'debug';import urlJoin from 'url-join';@@ -30,6 +31,7 @@ import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';import { mcpService } from '@/server/services/mcp';+import { MessageService } from '@/server/services/message';import { QueueService } from '@/server/services/queue';import { LocalQueueServiceImpl } from '@/server/services/queue/impls';import { ToolExecutionService } from '@/server/services/toolExecution';@@ -182,6 +184,17 @@ export class AgentRuntimeService {private serverDB: LobeChatDatabase;private userId: string;private messageModel: MessageModel;+ // Lazily constructed because MessageService instantiates a FileService+ // which eagerly creates the S3 client and throws when S3 env vars are+ // missing β eager construction would break every test that builds an+ // AgentRuntimeService without mocking the file backend.+ private messageServiceInstance?: MessageService;+ private get messageService(): MessageService {+ if (!this.messageServiceInstance) {+ this.messageServiceInstance = new MessageService(this.serverDB, this.userId);+ }+ return this.messageServiceInstance;+ }constructor(db: LobeChatDatabase, userId: string, options?: AgentRuntimeServiceOptions) {// Use factory function to auto-select Redis or InMemory implementation@@ -192,6 +205,10 @@ export class AgentRuntimeService {this.coordinator = new AgentRuntimeCoordinator({...options?.coordinatorOptions,streamEventManager: this.streamManager,+ // Provide the canonical UIChatMessage[] for terminal-state events so+ // the client can use the pushed payload directly instead of refetching+ // from DB. Falls back gracefully when topicId isn't set.+ uiMessagesResolver: (state) => this.queryUiMessages(state),});this.queueService =options?.queueService === null ? null : (options?.queueService ?? new QueueService());@@ -474,6 +491,31 @@ export class AgentRuntimeService {}}+ /**+ * Query the canonical UIChatMessage[] snapshot for the active topic β the+ * same shape the `message.getMessages` trpc lambda returns to the client.+ * Attached to step_start / agent_runtime_end stream events so the client+ * can use the pushed payload directly instead of refetching from DB.+ *+ * Returns undefined when the topic isn't known yet (e.g. very early in+ * bootstrap before the topic row has been committed) so callers can skip+ * the `uiMessages` field entirely instead of pushing an empty array.+ */+ async queryUiMessages(agentState: AgentState): Promise<UIChatMessage[] | undefined> {+ const agentId: string | undefined = agentState?.metadata?.agentId;+ const topicId: string | undefined = agentState?.metadata?.topicId;+ if (!agentId || !topicId) return undefined;++ try {+ return await this.messageService.queryMessages({ agentId, topicId });+ } catch (error) {+ // Stream events must never fail the step. If the DB hiccups, fall back+ // to letting the client refresh as before.+ console.error('[queryUiMessages] Failed to load uiMessages snapshot: %O', error);+ return undefined;+ }+ }+/*** Execute Agent step*/@@ -515,20 +557,27 @@ export class AgentRuntimeService {try {log('[%s][%d] Start step executing...', operationId, stepIndex);- // Publish step start event- await this.streamManager.publishStreamEvent(operationId, {- data: {},- stepIndex,- type: 'step_start',- });-- // Get operation state and metadata+ // Load agent state BEFORE publishing step_start so we can attach the+ // canonical UIChatMessage snapshot to the event payload. step_start+ // fires after the previous step's DB writes are awaited durable, so+ // the snapshot query here reflects strongly-consistent state β that's+ // the contract that lets the client treat the pushed uiMessages as+ // the source of truth instead of doing its own refetch.const agentState = await this.coordinator.loadAgentState(operationId);if (!agentState) {throw new Error(`Agent state not found for operation ${operationId}`);}+ const stepStartUiMessages = await this.queryUiMessages(agentState);+ await this.streamManager.publishStreamEvent(operationId, {+ data: {+ ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),+ },+ stepIndex,+ type: 'step_start',+ });+agentState.metadata = {...agentState.metadata,externalRetryCount,diff --git a/src/server/services/agentRuntime/__tests__/executeStep.test.ts b/src/server/services/agentRuntime/__tests__/executeStep.test.tsindex 8497b3bced6..8cae6e8883d 100644--- a/src/server/services/agentRuntime/__tests__/executeStep.test.ts+++ b/src/server/services/agentRuntime/__tests__/executeStep.test.ts@@ -898,3 +898,82 @@ describe('AgentRuntimeService.executeStep - error-path snapshot finalize ()', ()dispatchSpy.mockRestore();});});++// step_start event should carry the canonical UIChatMessage[] so the+// client can use the pushed payload as Source of Truth.+describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () => {+ const createService = () => {+ return new AgentRuntimeService({} as any, 'user-1', { queueService: null });+ };++ it('attaches uiMessages to step_start data when topic context is known', async () => {+ const service = createService();+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;++ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);+ // Force early-exit path so we don't need to mock the entire runtime+ // execution surface β terminal-state short-circuits right after+ // step_start publishes.+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ status: 'done',+ stepCount: 3,+ lastModified: new Date().toISOString(),+ metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ });+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);++ // Inject a uiMessages-returning messageService β the runtime queries+ // through MessageService (not the bare messageModel) so that file URLs+ // go through FileService postProcessUrl.+ const stubMessages = [{ id: 'msg_1', role: 'user' }];+ (service as any).messageServiceInstance = {+ queryMessages: vi.fn().mockResolvedValue(stubMessages),+ };++ await service.executeStep({+ operationId: 'op-uimsg',+ stepIndex: 5,+ context: { phase: 'user_input' } as any,+ });++ // First publish call is step_start; assert its payload carries uiMessages.+ const stepStartCall = streamManager.publishStreamEvent.mock.calls.find(+ ([, evt]: any) => evt?.type === 'step_start',+ );+ expect(stepStartCall).toBeDefined();+ expect(stepStartCall[1].data.uiMessages).toEqual(stubMessages);+ });++ it('omits uiMessages from step_start data when topic context is unknown', async () => {+ const service = createService();+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;++ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ status: 'done',+ stepCount: 3,+ lastModified: new Date().toISOString(),+ metadata: {}, // no agentId/topicId+ });+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);++ const queryMock = vi.fn();+ (service as any).messageServiceInstance = { queryMessages: queryMock };++ await service.executeStep({+ operationId: 'op-noctx',+ stepIndex: 5,+ context: { phase: 'user_input' } as any,+ });++ const stepStartCall = streamManager.publishStreamEvent.mock.calls.find(+ ([, evt]: any) => evt?.type === 'step_start',+ );+ expect(stepStartCall).toBeDefined();+ expect(stepStartCall[1].data).not.toHaveProperty('uiMessages');+ // Did not even attempt the DB query when context is missing.+ expect(queryMock).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/agentRuntime/__tests__/executeSync.test.ts b/src/server/services/agentRuntime/__tests__/executeSync.test.tsindex 6da3f108fa7..046fe3247d5 100644--- a/src/server/services/agentRuntime/__tests__/executeSync.test.ts+++ b/src/server/services/agentRuntime/__tests__/executeSync.test.ts@@ -256,7 +256,11 @@ describe('AgentRuntimeService.executeSync', () => {// Publish event after a small delaysetTimeout(async () => {- await streamEventManager.publishAgentRuntimeEnd(operationId, 1, { status: 'done' });+ await streamEventManager.publishAgentRuntimeEnd({+ finalState: { status: 'done' },+ operationId,+ stepIndex: 1,+ });}, 10);const event = await streamEventManager.waitForEvent(operationId, 'agent_runtime_end', 1000);diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex ff633474f0d..b92b709790c 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -873,7 +873,13 @@ export class AiAgentService {if (!result.success) {log('execAgent: remote hetero dispatch failed: %s', result.error);await streamManager- .publishAgentRuntimeEnd(operationId, 0, { error: result.error }, 'error', result.error)+ .publishAgentRuntimeEnd({+ finalState: { error: result.error },+ operationId,+ reason: 'error',+ reasonDetail: result.error,+ stepIndex: 0,+ }).catch(() => {});await this.messageModel.update(assistantMsg.id, {content: '',diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.tsindex f6d180774a6..8eea9537b4f 100644--- a/src/server/services/message/index.ts+++ b/src/server/services/message/index.ts@@ -2,6 +2,7 @@ import { type LobeChatDatabase } from '@lobechat/database';import { CompressionRepository } from '@lobechat/database';import {type CreateMessageParams,+ type QueryMessageParams,type UIChatMessage,type UpdateMessageParams,} from '@lobechat/types';@@ -111,6 +112,18 @@ export class MessageService {return { messages, success: true };}+ /**+ * Fetch the canonical message list for an agent / topic scope, using the+ * standard UIChatMessage shape (file URLs resolved through FileService).+ *+ * Mirrors the read path exposed by the `message.getMessages` trpc lambda+ * so server-internal callers (e.g. agent runtime stream events) can push+ * the same payload the client would otherwise fetch.+ */+ async queryMessages(params: QueryMessageParams): Promise<UIChatMessage[]> {+ return this.messageModel.query(params, this.getQueryOptions());+ }+/*** Create a new message and return the complete message list* Pattern: create + query