Skip to content

🀯 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.

✨ feat(server): serve tool results as render-facing view models on the v2 read path (#19666)

Arvin Xue13ad4173326
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index a64afa3f83a..8567432eb23 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -64,6 +64,8 @@ the next free number of that prefix.
- **L-S20** Read the managed containers' host ports from `docker ps` and pass `DB_PORT`/`REDIS_PORT` to every `init-dev-env.sh` subcommand; `auth_failed` on migrate is a port mismatch.
- **L-S21** In a worktree, invoke scripts by absolute path and prove the SPA's identity (Vite pid cwd, changed module from the Vite origin) before trusting any gate or evidence.
- **L-S22** A per-account cap that a round consumes (artifact deployments) is cleared for the account the surface actually authenticates as, and re-cleared between rounds.
+- **L-S23** A hand-built `node_modules` symlink farm runs unit tests but cannot start the dev server; clone a working checkout's `node_modules` instead of a fresh install, which this lockfile-less repo resolves against a moving registry.
+- **L-S24** Read the dev server's URL from its own log, and treat "ready" as any status but `000` β€” `/` answers `302` to `/signin` when signed out.
## Entries
@@ -569,3 +571,38 @@ authenticates as the seeded runtime user, still held three.
the `user_id` on the seeded API key row) and clear the cap for _that_ id before
and between rounds. A quota error mid-round is an environment fact until the
account has been checked; do not debug it as product behaviour.
+
+### L-S23 β€” Substituting a symlink farm for an install in a fresh worktree
+
+`since 2026-09-18` Β· `holds-while: pnpm-workspace.yaml sets lockfile: false, and Turbopack resolves next/package.json from the workspace root it detects`
+
+**Trap:** a new worktree has no `node_modules`, and a farm of symlinks into a
+working checkout is quick and makes `vitest` and `tsgo` pass β€” so the tree looks
+ready. The dev server then dies on `Could not find the Next.js package
+(next/package.json)`, every route 500s, and the visible errors point elsewhere
+(`Failed to resolve import "anser"` from a package-level dependency the farm
+never linked). Falling back to `pnpm install` can fail outright: this repo
+commits no lockfile, so a fresh resolve hits whatever the registry holds today
+(seen: `No matching version found for @aws-sdk/[email protected]`).
+
+**Rule:** for anything that boots the app, copy a working checkout's
+`node_modules` β€” `cp -Rc` (APFS clonefile) takes \~100s and almost no disk for
+6.8 GB. Copy the per-package `node_modules` too (\~100 of them; the root tree
+alone leaves package-level deps unresolved), then symlink any workspace package
+the branch adds into `node_modules/@lobechat/`. The `@lobechat/*` links inside
+are relative and resolve to the worktree's own `packages/`, which is what keeps
+the code under test in the path. A farm is fine for unit tests only.
+
+### L-S24 β€” Waiting for a readiness code the server never returns
+
+`since 2026-09-18` Β· `holds-while: the dev script allocates a free port per run and the app redirects unauthenticated root requests`
+
+**Trap:** polling a remembered port (3010) for HTTP `200`. The script allocates a
+port per run and prints it (`πŸ” Next server URL: http://localhost:<port>/`, plus
+a separate Vite port in the Debug Proxy line); and the app answers `/` with
+`302` to `/signin` until the surface is authenticated. Both mistakes read as
+"the server never came up" while it has been serving for minutes.
+
+**Rule:** take both URLs from the log, never from memory or a default. Probe with
+PROJECT.md's predicate as written β€” any code but `000` β€” and confirm health by
+following the redirect, not by demanding `200` at the root.
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 4532bcfc202..6ff94917cf6 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -40,6 +40,8 @@ const hasEnteredStreamEndState = (
};
export interface AgentRuntimeCoordinatorOptions {
+ /** Whether terminal reconciliation is delivered by protocol-v2 message patches. */
+ messagePatchModeResolver?: (state: AgentState) => Promise<boolean>;
/**
* Custom state manager implementation
* Defaults to automatic selection based on Redis availability
@@ -75,11 +77,13 @@ export interface AgentRuntimeCoordinatorOptions {
* Supports dependency injection, allowing custom implementations to be passed in
*/
export class AgentRuntimeCoordinator {
+ private messagePatchModeResolver?: (state: AgentState) => Promise<boolean>;
private stateManager: IAgentStateManager;
private streamEventManager: IStreamEventManager;
private uiMessagesResolver?: (state: AgentState) => Promise<UIChatMessage[] | undefined>;
constructor(options?: AgentRuntimeCoordinatorOptions) {
+ this.messagePatchModeResolver = options?.messagePatchModeResolver;
this.stateManager = options?.stateManager ?? createAgentStateManager();
this.streamEventManager = options?.streamEventManager ?? createStreamEventManager();
this.uiMessagesResolver = options?.uiMessagesResolver;
@@ -150,6 +154,16 @@ export class AgentRuntimeCoordinator {
}
}
+ private async resolveMessagePatchMode(state: AgentState): Promise<boolean> {
+ if (!this.messagePatchModeResolver) return false;
+ try {
+ return await this.messagePatchModeResolver(state);
+ } catch (error) {
+ console.error('Failed to resolve message patch mode:', error);
+ return false;
+ }
+ }
+
private async publishVisibleOutputEnd(
operationId: string,
state: AgentState,
@@ -182,11 +196,13 @@ export class AgentRuntimeCoordinator {
// Send a terminal event once the operation first enters a terminal state.
if (hasEnteredStreamEndState(previousState?.status, state.status)) {
const stepIndex = state.stepCount ?? previousState?.stepCount ?? 0;
+ const messagePatchMode = await this.resolveMessagePatchMode(state);
if (!hasVisibleOutputEndPublished(state)) {
await this.publishVisibleOutputEnd(operationId, state, stepIndex);
}
await this.streamEventManager.publishAgentRuntimeEnd({
finalState: state,
+ ...(messagePatchMode && { messagePatchMode: true, messageRevision: stepIndex + 1 }),
operationId,
reason: state.status,
stepIndex,
@@ -218,11 +234,13 @@ export class AgentRuntimeCoordinator {
// but suppress visible_output_end once the operation marker exists.
const stepIndex =
stepResult.stepIndex ?? stepResult.newState.stepCount ?? previousState?.stepCount ?? 0;
+ const messagePatchMode = await this.resolveMessagePatchMode(stepResult.newState);
if (!hasVisibleOutputEndPublished(stepResult.newState)) {
await this.publishVisibleOutputEnd(operationId, stepResult.newState, stepIndex);
}
await this.streamEventManager.publishAgentRuntimeEnd({
finalState: stepResult.newState,
+ ...(messagePatchMode && { messagePatchMode: true, messageRevision: stepIndex + 1 }),
operationId,
reason: stepResult.newState.status,
stepIndex,
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index d2cf17c8206..905d7c32c39 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -155,10 +155,11 @@ export class GatewayStreamNotifier implements IStreamEventManager {
): Promise<string> {
const result = await this.inner.publishStreamEvent(operationId, event);
const gatewayEvent = { ...event, operationId, timestamp: Date.now() };
- if (event.type === 'stream_end') {
+ if (event.type === 'stream_end' || event.type === 'message_patch') {
// `visible_output_end` may be published immediately after `stream_end`.
- // Await the Gateway push for this boundary so the client applies
- // stream_end.finalContent before closing visible loading/reasoning.
+ // Await ordering boundaries so the client applies stream_end.finalContent
+ // before visible_output_end, and its canonical message patch before the
+ // following step_start / agent_runtime_end revision check.
await this.pushEvent(operationId, gatewayEvent);
} else {
void this.pushEvent(operationId, gatewayEvent);
@@ -235,10 +236,10 @@ export class GatewayStreamNotifier implements IStreamEventManager {
}
void this.pushEvent(operationId, {
- // Share-visitor runs must not receive the creator's raw operation
- // metadata (agentConfig / system prompt, modelRuntimeConfig, userId,
- // workspaceId) over their WS channel β€” see `buildPublicInitEventData`.
- data: isShareInit ? buildPublicInitEventData(initialState) : initialState,
+ // Every run, not just share visitors: nothing on the other end reads this
+ // event's data, while the raw `initialState` is the whole `AgentState` β€”
+ // the LLM context plus the tool-set maps. See `buildPublicInitEventData`.
+ data: buildPublicInitEventData(initialState),
operationId,
stepIndex: 0,
timestamp: Date.now(),
@@ -249,7 +250,16 @@ export class GatewayStreamNotifier implements IStreamEventManager {
}
async publishAgentRuntimeEnd(params: PublishAgentRuntimeEndParams): Promise<string> {
- const { operationId, stepIndex, finalState, reason, reasonDetail, uiMessages } = params;
+ const {
+ operationId,
+ stepIndex,
+ finalState,
+ messagePatchMode,
+ messageRevision,
+ reason,
+ reasonDetail,
+ uiMessages,
+ } = params;
const result = await this.inner.publishAgentRuntimeEnd(params);
const endRedaction = resolveRedactionFromState(finalState);
@@ -289,7 +299,8 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// snapshot, so dropping it here would break the SoT contract.
const endEventData = {
errorType,
- finalState,
+ ...(!messagePatchMode && { finalState }),
+ ...(messagePatchMode && { messagePatchMode: true, messageRevision }),
reason,
reasonDetail: effectiveReasonDetail,
...(uiMessages !== undefined && { uiMessages }),
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
index 9f40761e9a8..9378d931c7c 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
@@ -110,6 +110,8 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
operationId,
stepIndex,
finalState,
+ messagePatchMode,
+ messageRevision,
reason,
reasonDetail,
uiMessages,
@@ -117,7 +119,8 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
// Strip happens centrally inside `publishStreamEvent`.
return this.publishStreamEvent(operationId, {
data: {
- finalState,
+ ...(!messagePatchMode && { finalState }),
+ ...(messagePatchMode && { messagePatchMode: true, messageRevision }),
operationId,
phase: 'execution_complete',
reason: reason || 'completed',
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
index 1067f361de8..329eeff12da 100644
--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
@@ -273,6 +273,8 @@ export class StreamEventManager {
operationId,
stepIndex,
finalState,
+ messagePatchMode,
+ messageRevision,
reason,
reasonDetail,
uiMessages,
@@ -283,7 +285,8 @@ export class StreamEventManager {
// so the error message remains available.
return this.publishStreamEvent(operationId, {
data: {
- finalState,
+ ...(!messagePatchMode && { finalState }),
+ ...(messagePatchMode && { messagePatchMode: true, messageRevision }),
operationId,
phase: 'execution_complete',
reason: reason || 'completed',
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index ecbc31f1394..51f714fb577 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -672,6 +672,33 @@ describe('AgentRuntimeCoordinator', () => {
});
});
+ it('marks a protocol-v2 patched terminal event with its expected revision', async () => {
+ const coordinatorWithResolver = new AgentRuntimeCoordinator({
+ messagePatchModeResolver: vi.fn().mockResolvedValue(true),
+ stateManager: mockStateManager,
+ streamEventManager: mockStreamManager,
+ uiMessagesResolver: vi.fn().mockResolvedValue(undefined),
+ });
+ const stepResult = {
+ executionTime: 100,
+ newState: { status: 'done', stepCount: 4 },
+ stepIndex: 4,
+ };
+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 3 });
+
+ await coordinatorWithResolver.saveStepResult('op-patch', stepResult as any);
+
+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
+ finalState: stepResult.newState,
+ messagePatchMode: true,
+ messageRevision: 5,
+ operationId: 'op-patch',
+ reason: 'done',
+ stepIndex: 4,
+ uiMessages: undefined,
+ });
+ });
+
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({
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 52e8b3b6568..15df657764e 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -150,6 +150,31 @@ describe('GatewayStreamNotifier', () => {
expect(inner.calls.publishAgentRuntimeInit[0]).toEqual(['op-1', initialState]);
});
+ it('pushes only the status, never the whole AgentState', async () => {
+ // Nothing on the other end reads this event's data, while the raw state
+ // carries the LLM context and every enabled tool's manifest.
+ await notifier.publishAgentRuntimeInit('op-1', {
+ agentConfig: { systemRole: 'secret prompt' },
+ messages: [{ content: 'x'.repeat(50_000), role: 'user' }],
+ status: 'running',
+ toolManifestMap: { big: 'manifest' },
+ userId: 'user-1',
+ });
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const push = mockFetch.mock.calls.find((c: any[]) =>
+ String(c[0]).endsWith('/api/operations/push-event'),
+ );
+ const pushed = JSON.parse(push![1].body);
+ const initEvent = (pushed.events ?? [pushed.event ?? pushed]).find(
+ (e: any) => e?.type === 'agent_runtime_init' || e?.event?.type === 'agent_runtime_init',
+ );
+ const data = (initEvent?.data ?? initEvent?.event?.data) as Record<string, unknown>;
+
+ expect(data).toEqual({ status: 'running' });
+ });
+
it('calls gateway init and push-event endpoints', async () => {
await notifier.publishAgentRuntimeInit('op-1', { userId: 'user-1' });
@@ -489,6 +514,28 @@ describe('GatewayStreamNotifier', () => {
const body = JSON.parse(pushCall![1].body);
expect(body.event.data).not.toHaveProperty('uiMessages');
});
+
+ it('sends only terminal metadata after a protocol-v2 message patch', async () => {
+ await notifier.publishAgentRuntimeEnd({
+ finalState: { messages: ['large'], status: 'done', world: { private: true } },
+ messagePatchMode: true,
+ messageRevision: 5,
+ 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).toMatchObject({
+ messagePatchMode: true,
+ messageRevision: 5,
+ reason: 'completed',
+ });
+ expect(body.event.data).not.toHaveProperty('finalState');
+ expect(body.event.data).not.toHaveProperty('uiMessages');
+ });
});
// ─── Read/subscribe methods: must delegate directly to inner ───
diff --git a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
index d5cafbebd98..63aa5edd03a 100644
--- a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
+++ b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
@@ -69,11 +69,17 @@ export const resolveRedactionFromState = (state: any): GatewayVisitorRedaction =
};
/**
- * Public `agent_runtime_init` DTO pushed to the Gateway for shared-agent
- * visitor runs. The full operation metadata must never cross the WS boundary to
- * the visitor. The client doesn't render anything from this event today β€”
- * `runAgent.ts`'s `agent_runtime_init` case only logs it β€” so `status` is the
- * only field forwarded.
+ * The `agent_runtime_init` DTO pushed to the Gateway.
+ *
+ * Applied to EVERY run, not just shared-agent visitors. No consumer reads this
+ * event's data: the web handler logs it and breaks, the CLI prints a fixed
+ * line, and the gateway transport does not handle the type at all. What the raw
+ * `initialState` would otherwise carry is the entire `AgentState` β€” the LLM
+ * context in `messages` plus the tool-set maps that `stripStateForStream`
+ * already treats as the size problem on `finalState`, and for a visitor the
+ * creator's `agentConfig` / system prompt on top.
+ *
+ * `status` is kept because it is the one field the shape has ever needed.
*/
export const buildPublicInitEventData = (initialState: any): { status?: unknown } => ({
status: initialState?.status,
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 187c5e93fed..ec76d9e60a7 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -7,6 +7,10 @@ import { type StreamChunkData, type StreamEvent } from './StreamEventManager';
export interface PublishAgentRuntimeEndParams {
finalState: any;
+ /** Protocol-v2 native run: terminal reconciliation arrived as message_patch. */
+ messagePatchMode?: boolean;
+ /** Last message patch revision the client must have applied before settling. */
+ messageRevision?: number;
operationId: string;
reason?: string;
reasonDetail?: string;
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
index 01364652b5c..8c5162a7fec 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
@@ -45,7 +45,14 @@ vi.mock('@/server/services/aiChat', () => ({
}),
}));
-const buildEvent = (type: AgentStreamEvent['type'], stepIndex: number): AgentStreamEvent => ({
+type HeterogeneousAgentStreamEvent = Omit<AgentStreamEvent, 'type'> & {
+ type: Exclude<AgentStreamEvent['type'], 'message_patch'>;
+};
+
+const buildEvent = (
+ type: HeterogeneousAgentStreamEvent['type'],
+ stepIndex: number,
+): HeterogeneousAgentStreamEvent => ({
data: {},
operationId: 'op-1',
stepIndex,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 0f6d632fe2b..6278a760a2c 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -28,6 +28,7 @@ import {
assertCanUseCreateMessageTargets,
assertCanUseMessageTargets,
assertCanUseTopicTargets,
+ assertCanViewMessageTargets,
} from './_helpers/conversationResourceGuard';
import { projectSharedTopicMessages } from './_helpers/projectSharedTopicMessages';
import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';
@@ -393,6 +394,22 @@ export const messageRouter = router({
return ctx.topicDoctorRepo.repair(input);
}),
+ /**
+ * Raw tool payload for one message, fetched on demand when the projected
+ * read path dropped it (`UIChatMessage.payloadOmitted`).
+ */
+ getToolResultPayload: messageProcedure
+ .input(z.object({ messageId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ // A message id is a locator, not an authorization. In a workspace the
+ // model reads are workspace-scoped, so without this a member who kept an
+ // id could pull tool output from a conversation they cannot open β€” the
+ // same guard `getMessages` applies before returning the list.
+ await assertCanViewMessageTargets(guardCtx(ctx), [input.messageId]);
+
+ return ctx.messageService.getToolResultPayload(input.messageId);
+ }),
+
getHeatmaps: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.getHeatmaps();
}),
@@ -482,9 +499,14 @@ export const messageRouter = router({
const messageModel = new MessageModel(ctx.serverDB, ctx.userId, wsId);
const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);
- return messageModel.query(queryParams, {
+ const messages = await messageModel.query(queryParams, {
postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
});
+
+ // This branch reads through its own `MessageModel` (different query
+ // options than `MessageService.queryMessages`), so it applies the tool
+ // view-model step explicitly rather than inheriting it.
+ return new MessageService(ctx.serverDB, ctx.userId, wsId).projectToolPayloads(messages);
}),
rankModels: messageProcedure.query(async ({ ctx }) => {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index f657fa75d77..7da7b74e6af 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -2125,21 +2125,31 @@ describe('AgentRuntimeService', () => {
expect(result).toEqual(stubMessages);
});
- it('opts the snapshot into agent-share visitor rows', async () => {
- // Regression: `MessageModel.query()` hides share-visitor messages by
- // default. A visitor run executes under the creator's identity, so
- // without the opt-in the terminal snapshot for the visitor's topic is
- // `[]` and the client replaces the conversation it just streamed with
- // nothing.
- const queryMessages = vi.fn().mockResolvedValue([]);
- stubMessageService(service, queryMessages);
-
- await service.queryUiMessages({
- origin: { agentId: 'agt_1', topicId: 'tpc_1' },
- } as any);
-
- expect(queryMessages).toHaveBeenCalledWith(expect.anything(), { allowShareVisitor: true });
- });
+ it.each([
+ { skipToolProjection: false, visitorUserId: undefined },
+ { skipToolProjection: true, visitorUserId: 'visitor_1' },
+ ])(
+ 'includes visitor rows with skipToolProjection=$skipToolProjection',
+ async ({ skipToolProjection, visitorUserId }) => {
+ // Regression: `MessageModel.query()` hides share-visitor messages by
+ // default. A visitor run executes under the creator's identity, so
+ // without the opt-in the terminal snapshot for the visitor's topic is
+ // `[]` and the client replaces the conversation it just streamed with
+ // nothing.
+ const queryMessages = vi.fn().mockResolvedValue([]);
+ stubMessageService(service, queryMessages);
+
+ await service.queryUiMessages({
+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },
+ principal: visitorUserId ? { actor: { shareVisitor: { visitorUserId } } } : undefined,
+ } as any);
+
+ expect(queryMessages).toHaveBeenCalledWith(expect.anything(), {
+ allowShareVisitor: true,
+ skipToolProjection,
+ });
+ },
+ );
it('scopes the snapshot to the run thread when the operation is a subtopic run', async () => {
// Regression: without `threadId` the snapshot is the topic's MAIN
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 1c3754180e4..7718f0678e7 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -52,6 +52,7 @@ import {
} from '@/business/server/agent-run/agentInterventionIdentity';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
+import { UserModel } from '@/database/models/user';
import { type LobeChatDatabase } from '@/database/type';
import { appEnv } from '@/envs/app';
import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntime';
@@ -87,6 +88,7 @@ import {
import { logToolCallPc } from './formalObservation';
import { type AgentHook, hookDispatcher } from './hooks';
import { HumanInterventionHandler } from './HumanInterventionHandler';
+import { buildMessagePatch } from './messagePatch';
import { OperationTraceRecorder } from './OperationTraceRecorder';
import { createDefaultSnapshotStore } from './snapshotStore';
import { buildStepPresentation, formatTokenCount } from './stepPresentation';
@@ -382,6 +384,8 @@ export interface AgentRuntimeServiceOptions {
* circular import.
*/
delegate?: AgentRuntimeDelegate;
+ /** Lightweight protocol capability seam; primarily injectable in tests. */
+ gatewayMuxEnabledResolver?: () => Promise<boolean>;
/**
* Opt IN to agent-share visitor rows for the models this service owns.
* Reserved for share-runtime entry points that drive a visitor turn under
@@ -436,6 +440,8 @@ export class AgentRuntimeService {
private coordinator: AgentRuntimeCoordinator;
private delegate: AgentRuntimeDelegate;
private humanIntervention: HumanInterventionHandler;
+ private gatewayMuxEnabled?: Promise<boolean>;
+ private gatewayMuxEnabledResolver: () => Promise<boolean>;
private streamManager: IStreamEventManager;
private queueService: QueueService | null;
private traceRecorder: OperationTraceRecorder;
@@ -466,6 +472,12 @@ export class AgentRuntimeService {
}
constructor(db: LobeChatDatabase, userId: string, options?: AgentRuntimeServiceOptions) {
+ this.gatewayMuxEnabledResolver =
+ options?.gatewayMuxEnabledResolver ??
+ (() =>
+ new UserModel(db, userId)
+ .getUserPreference()
+ .then((preference) => preference?.lab?.enableGatewayMux === true));
// Use factory function to auto-select Redis or InMemory implementation
this.streamManager =
options?.streamEventManager ??
@@ -473,11 +485,13 @@ export class AgentRuntimeService {
createStreamEventManager();
this.coordinator = new AgentRuntimeCoordinator({
...options?.coordinatorOptions,
+ messagePatchModeResolver: (state) => this.usesGatewayMessagePatch(state),
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),
+ uiMessagesResolver: async (state) =>
+ (await this.usesGatewayMessagePatch(state)) ? undefined : this.queryUiMessages(state),
});
this.queueService =
options?.queueService === null ? null : (options?.queueService ?? new QueueService());
@@ -1316,7 +1330,15 @@ export class AgentRuntimeService {
// terminal Source of Truth β€” wiping the conversation the run just
// produced. Visitor-facing redaction of the pushed snapshot happens in
// `GatewayStreamNotifier`.
- { allowShareVisitor: true },
+ //
+ // A visitor snapshot additionally keeps its tool payloads whole: this
+ // query runs as the CREATOR, but the recovery RPC runs as the VISITOR
+ // against ownership-scoped reads that cannot see a creator-owned row,
+ // so a projected snapshot could never be filled back in.
+ {
+ allowShareVisitor: true,
+ skipToolProjection: !!agentState?.principal?.actor?.shareVisitor?.visitorUserId,
+ },
);
} catch (error) {
// Stream events must never fail the step. If the DB hiccups, fall back
@@ -1326,6 +1348,16 @@ export class AgentRuntimeService {
}
}
+ /** Native harness + Gateway mux is the only producer of message patches. */
+ private async usesGatewayMessagePatch(agentState: AgentState): Promise<boolean> {
+ if (agentState.principal?.actor?.shareVisitor) return false;
+ this.gatewayMuxEnabled ??= this.gatewayMuxEnabledResolver().catch((error) => {
+ console.error('[AgentRuntimeService] failed to read gateway mux preference: %O', error);
+ return false;
+ });
+ return this.gatewayMuxEnabled;
+ }
+
/**
* Execute Agent step
*/
@@ -1650,11 +1682,12 @@ export class AgentRuntimeService {
};
}
+ const gatewayMessagePatchEnabled = await this.usesGatewayMessagePatch(agentState);
const stepStartUiMessages = await this.queryUiMessages(agentState, { skipWorks: true });
await this.streamManager.publishStreamEvent(operationId, {
- data: {
- ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),
- },
+ data: gatewayMessagePatchEnabled
+ ? { messageRevision: stepIndex }
+ : { ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }) },
stepIndex,
type: 'step_start',
});
@@ -2114,6 +2147,24 @@ export class AgentRuntimeService {
}
}
+ // Protocol v2 native runs reconcile only what this step changed. The
+ // full before/after lists stay server-side; the wire sees a bounded
+ // patch. Publish before saveStepResult because a terminal save emits
+ // agent_runtime_end immediately, and the client must apply the patch
+ // before completing the run.
+ if (gatewayMessagePatchEnabled && stepStartUiMessages) {
+ const settledUiMessages = await this.queryUiMessages(stepResult.newState, {
+ skipWorks: shouldContinue,
+ });
+ if (settledUiMessages) {
+ await this.streamManager.publishStreamEvent(operationId, {
+ data: buildMessagePatch(stepStartUiMessages, settledUiMessages, stepIndex + 1),
+ stepIndex,
+ type: 'message_patch',
+ });
+ }
+ }
+
// Save state, coordinator will handle event sending automatically
await this.coordinator.saveStepResult(operationId, {
...stepResult,
@@ -3687,6 +3738,11 @@ export class AgentRuntimeService {
postProcessUrl = undefined;
}
+ // MODEL, not `messageService.queryMessages`: this read feeds the LLM
+ // context and must keep every tool result whole. The service read path may
+ // reduce tool payloads to render-facing view models (see
+ // `@lobechat/tool-view-model`), which would silently strip the results the
+ // model is supposed to remember.
return this.messageModel.query(
{
agentId: state.origin?.agentId,
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index f4c706bb72e..098cde61d23 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -1722,6 +1722,38 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =
// Did not even attempt the DB query when context is missing.
expect(queryMock).not.toHaveBeenCalled();
});
+
+ it('sends only the expected revision for a Gateway mux native run', async () => {
+ const service = new AgentRuntimeService({} as any, 'user-1', {
+ gatewayMuxEnabledResolver: async () => true,
+ queueService: null,
+ });
+ const coordinator = (service as any).coordinator;
+ const streamManager = (service as any).streamManager;
+
+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({
+ lastModified: new Date().toISOString(),
+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },
+ status: 'done',
+ stepCount: 3,
+ });
+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);
+ (service as any).messageServiceInstance = {
+ queryMessages: vi.fn().mockResolvedValue([{ id: 'large-history', role: 'user' }]),
+ };
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-patch',
+ stepIndex: 5,
+ });
+
+ const stepStartCall = streamManager.publishStreamEvent.mock.calls.find(
+ ([, evt]: any) => evt?.type === 'step_start',
+ );
+ expect(stepStartCall[1].data).toEqual({ messageRevision: 5 });
+ });
});
describe('AgentRuntimeService.executeStep - pre-snapshot file-Work registration', () => {
diff --git a/apps/server/src/services/agentRuntime/messagePatch.test.ts b/apps/server/src/services/agentRuntime/messagePatch.test.ts
new file mode 100644
index 00000000000..c71efecbc50
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/messagePatch.test.ts
@@ -0,0 +1,42 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildMessagePatch } from './messagePatch';
+
+const message = (id: string, content: string): UIChatMessage =>
+ ({ content, createdAt: 1, id, role: 'assistant', updatedAt: 1 }) as UIChatMessage;
+
+describe('buildMessagePatch', () => {
+ it('emits only changed and appended rows with canonical anchors', () => {
+ const before = [message('a', 'same'), message('b', 'old')];
+ const after = [message('a', 'same'), message('b', 'new'), message('c', 'created')];
+
+ expect(buildMessagePatch(before, after, 4)).toEqual({
+ deletes: [],
+ revision: 4,
+ upserts: [
+ { afterId: 'a', message: after[1] },
+ { afterId: 'b', message: after[2] },
+ ],
+ });
+ });
+
+ it('emits deleted top-level envelopes', () => {
+ expect(
+ buildMessagePatch([message('a', 'a'), message('b', 'b')], [message('b', 'b')], 2),
+ ).toEqual({
+ deletes: ['a'],
+ revision: 2,
+ upserts: [],
+ });
+ });
+
+ it('treats a changed nested envelope as one atomic upsert', () => {
+ const before = [{ ...message('group', ''), compressedMessages: [message('a', 'old')] }];
+ const after = [{ ...message('group', ''), compressedMessages: [message('a', 'new')] }];
+
+ expect(buildMessagePatch(before, after, 1).upserts).toEqual([
+ { afterId: null, message: after[0] },
+ ]);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/messagePatch.ts b/apps/server/src/services/agentRuntime/messagePatch.ts
new file mode 100644
index 00000000000..ca955d2b6f5
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/messagePatch.ts
@@ -0,0 +1,34 @@
+import type { MessagePatchData } from '@lobechat/agent-gateway-client';
+import type { UIChatMessage } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+
+/**
+ * Diff two canonical top-level message lists for one native runtime step.
+ * Nested compression/member structures remain atomic: if a nested row changes,
+ * its top-level envelope is upserted as one unit so the client never has to
+ * reproduce server-side conversation-flow grouping rules.
+ */
+export const buildMessagePatch = (
+ before: UIChatMessage[],
+ after: UIChatMessage[],
+ revision: number,
+): MessagePatchData => {
+ const beforeById = new Map(before.map((message) => [message.id, message]));
+ const afterIds = new Set(after.map((message) => message.id));
+
+ return {
+ deletes: before.filter((message) => !afterIds.has(message.id)).map((message) => message.id),
+ revision,
+ upserts: after.flatMap((message, index) => {
+ const previous = beforeById.get(message.id);
+ if (previous && isEqual(previous, message)) return [];
+
+ return [
+ {
+ afterId: index === 0 ? null : after[index - 1].id,
+ message,
+ },
+ ];
+ }),
+ };
+};
diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.ts
index 34132e72251..4178c416fff 100644
--- a/apps/server/src/services/message/__tests__/index.test.ts
+++ b/apps/server/src/services/message/__tests__/index.test.ts
@@ -1,19 +1,32 @@
import { type LobeChatDatabase } from '@lobechat/database';
+import type * as ToolViewModelModule from '@lobechat/tool-view-model';
+import { projectToolViewModels } from '@lobechat/tool-view-model';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MessageModel } from '@/database/models/message';
+import { UserModel } from '@/database/models/user';
import { FileService } from '@/server/services/file';
import { MessageService } from '../index';
vi.mock('@/database/models/message');
+vi.mock('@/database/models/user');
vi.mock('@/server/services/file');
+// Spy on the real projector pipeline rather than stubbing it: the assertion
+// that matters is that the UI read path runs it at all, and that with an empty
+// registry it is still a pass-through.
+vi.mock('@lobechat/tool-view-model', async (importOriginal) => {
+ const actual = await importOriginal<typeof ToolViewModelModule>();
+ return { ...actual, projectToolViewModels: vi.fn(actual.projectToolViewModels) };
+});
+
describe('MessageService', () => {
let messageService: MessageService;
let mockDB: LobeChatDatabase;
let mockMessageModel: MessageModel;
let mockFileService: FileService;
+ let mockUserModel: UserModel;
const userId = 'test-user-id';
beforeEach(() => {
@@ -37,6 +50,11 @@ describe('MessageService', () => {
}),
} as any;
+ // Mux cohort by default; the off case is asserted explicitly below.
+ mockUserModel = {
+ getUserPreference: vi.fn().mockResolvedValue({ lab: { enableGatewayMux: true } }),
+ } as any;
+
// Mock constructors
vi.mocked(MessageModel).mockImplementation(function () {
return mockMessageModel;
@@ -44,10 +62,89 @@ describe('MessageService', () => {
vi.mocked(FileService).mockImplementation(function () {
return mockFileService;
});
+ vi.mocked(UserModel).mockImplementation(function () {
+ return mockUserModel;
+ });
messageService = new MessageService(mockDB, userId);
});
+ describe('queryMessages', () => {
+ const toolRow = {
+ content: 'RAW BODY',
+ id: 'tool-1',
+ plugin: { apiName: 'crawlSinglePage', arguments: '{}', identifier: 'lobe-web-browsing' },
+ pluginState: { results: [] },
+ role: 'tool',
+ } as any;
+
+ it('runs the UI read path through the tool view-model projector', async () => {
+ vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
+
+ const [projected] = await messageService.queryMessages({ topicId: 'topic-1' });
+
+ expect(projectToolViewModels).toHaveBeenCalledWith([toolRow]);
+ expect(projected.content).toBe('');
+ expect(projected.contentLength).toBe('RAW BODY'.length);
+ expect(projected.payloadOmitted).toBe('detail');
+ });
+
+ it('keeps the whole payload for a user who is not on the mux', async () => {
+ // Off the mux a run can execute in the browser against this very list, so
+ // projecting here would quietly drop tool results from the LLM context.
+ vi.mocked(mockUserModel.getUserPreference).mockResolvedValue({ lab: {} } as any);
+ vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
+
+ const result = await messageService.queryMessages({ topicId: 'topic-1' });
+
+ expect(result).toEqual([toolRow]);
+ });
+
+ it('keeps the whole payload when the preference read fails', async () => {
+ vi.mocked(mockUserModel.getUserPreference).mockRejectedValue(new Error('db down'));
+ vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const result = await messageService.queryMessages({ topicId: 'topic-1' });
+
+ expect(result).toEqual([toolRow]);
+ error.mockRestore();
+ });
+
+ it('reads the lab preference once, not once per step', async () => {
+ vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
+
+ await messageService.queryMessages({ topicId: 'topic-1' });
+ await messageService.queryMessages({ topicId: 'topic-1' });
+ await messageService.queryMessages({ topicId: 'topic-1' });
+
+ expect(mockUserModel.getUserPreference).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a share-visitor snapshot whole, since only the creator could fetch it back', async () => {
+ vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
+
+ const result = await messageService.queryMessages(
+ { topicId: 'topic-1' },
+ { allowShareVisitor: true, skipToolProjection: true },
+ );
+
+ expect(result).toEqual([toolRow]);
+ });
+
+ it('leaves a tool without a projector exactly as stored', async () => {
+ const unprojected = {
+ ...toolRow,
+ plugin: { apiName: 'noSuchApi', arguments: '{}', identifier: 'some-mcp-server' },
+ };
+ vi.mocked(mockMessageModel.query).mockResolvedValue([unprojected]);
+
+ const result = await messageService.queryMessages({ topicId: 'topic-1' });
+
+ expect(result).toEqual([unprojected]);
+ });
+ });
+
describe('removeMessage', () => {
it('should delete message and return { success: true } when no sessionId/topicId provided', async () => {
const messageId = 'msg-1';
diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.ts
index 2255c58397c..33a13c34543 100644
--- a/apps/server/src/services/message/index.ts
+++ b/apps/server/src/services/message/index.ts
@@ -1,5 +1,6 @@
import { type LobeChatDatabase } from '@lobechat/database';
import { CompressionRepository } from '@lobechat/database';
+import { projectToolViewModels } from '@lobechat/tool-view-model';
import {
type CreateMessageParams,
type HeterogeneousToolStateSnapshot,
@@ -10,6 +11,7 @@ import {
import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
import { MessageModel } from '@/database/models/message';
+import { UserModel } from '@/database/models/user';
import { FileService } from '../file';
@@ -94,11 +96,43 @@ export class MessageService {
private messageModel: MessageModel;
private fileService: FileService;
private compressionRepository: CompressionRepository;
+ private userModel: UserModel;
+ private toolProjectionEnabled?: Promise<boolean>;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.messageModel = new MessageModel(db, userId, workspaceId);
this.fileService = new FileService(db, userId, workspaceId);
this.compressionRepository = new CompressionRepository(db, userId, workspaceId);
+ this.userModel = new UserModel(db, userId);
+ }
+
+ /**
+ * Whether this user's reads hand back projected tool payloads.
+ *
+ * Gated on the `gatewayMux` lab opt-in, because that is exactly the cohort for
+ * which the browser never assembles an LLM context itself. Off the mux, a run
+ * can execute client-side against `dbMessagesMap`, so the read path IS the
+ * model path there and a projected tool result would silently disappear from
+ * the model's context.
+ *
+ * Memoized per service instance: a gateway run calls `queryMessages` once per
+ * step, and a lab preference cannot change mid-run. Fails to `false`, which
+ * keeps today's whole payload β€” never the direction that loses data.
+ *
+ * Turning the lab OFF does not invalidate message lists the client already
+ * cached in their projected form. Deliberately not handled: the mux is on its
+ * way to being the only runtime, at which point the gate goes away entirely.
+ */
+ private isToolProjectionEnabled(): Promise<boolean> {
+ this.toolProjectionEnabled ??= this.userModel
+ .getUserPreference()
+ .then((preference) => preference?.lab?.enableGatewayMux === true)
+ .catch((error) => {
+ console.error('[MessageService] failed to read lab preference: %O', error);
+ return false;
+ });
+
+ return this.toolProjectionEnabled;
}
/**
@@ -173,12 +207,58 @@ export class MessageService {
* authorized may opt in.
*/
allowShareVisitor?: boolean;
+ /**
+ * Keep the stored tool payloads whole. Set for a shared-agent visitor's
+ * snapshot: it is produced under the CREATOR's identity, but the recovery
+ * RPC runs as the VISITOR against ownership-scoped reads, which cannot see
+ * a creator-owned row β€” a projected snapshot would be unrecoverable.
+ */
+ skipToolProjection?: boolean;
},
): Promise<UIChatMessage[]> {
- return this.messageModel.query(params, {
+ const messages = await this.messageModel.query(params, {
...this.getQueryOptions(),
...(options?.allowShareVisitor && { allowShareVisitor: true }),
});
+
+ return options?.skipToolProjection ? messages : this.projectToolPayloads(messages);
+ }
+
+ /**
+ * Reduce tool payloads to render-facing view models, for the mux cohort only.
+ *
+ * Public because `message.getMessages` reads through its own `MessageModel`
+ * rather than {@link queryMessages} β€” it passes different query options β€” so
+ * the router applies this step itself. Both UI reads must go through here;
+ * only the shared-topic branch stays unprojected, since an anonymous visitor
+ * has no authenticated way to fetch the stored payload back.
+ */
+ async projectToolPayloads(messages: UIChatMessage[]): Promise<UIChatMessage[]> {
+ return (await this.isToolProjectionEnabled()) ? projectToolViewModels(messages) : messages;
+ }
+
+ /**
+ * The stored tool payload behind a projected message.
+ *
+ * The UI read path hands back a view model (see `@lobechat/tool-view-model`),
+ * which is all the inline card renders. Surfaces that show the real thing β€”
+ * the crawl detail portal, the raw/debug viewer β€” call this when the message
+ * they hold is flagged `payloadOmitted`.
+ *
+ * Ownership is enforced by the two model reads, so a foreign message id
+ * resolves to `undefined` rather than another user's tool output.
+ */
+ async getToolResultPayload(
+ messageId: string,
+ ): Promise<{ content: string; pluginState?: unknown } | undefined> {
+ const [message, plugin] = await Promise.all([
+ this.messageModel.findById(messageId),
+ this.messageModel.findMessagePlugin(messageId),
+ ]);
+
+ if (!message) return undefined;
+
+ return { content: message.content ?? '', pluginState: plugin?.state };
}
/**
diff --git a/package.json b/package.json
index deb41828f47..0da821cdb58 100644
--- a/package.json
+++ b/package.json
@@ -308,6 +308,7 @@
"@lobechat/shared-tool-ui": "workspace:*",
"@lobechat/ssrf-safe-fetch": "workspace:*",
"@lobechat/tool-runtime": "workspace:*",
+ "@lobechat/tool-view-model": "workspace:*",
"@lobechat/utils": "workspace:*",
"@lobechat/web-crawler": "workspace:*",
"@lobehub/analytics": "^1.6.4",
diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.md
index f08467ef3f0..98a9efb8d46 100644
--- a/packages/agent-gateway-client/PROTOCOL_V2.md
+++ b/packages/agent-gateway-client/PROTOCOL_V2.md
@@ -4,6 +4,7 @@ Status: design contract shared by three codebases. Every implementer works from
if you must deviate, document the deviation at the top of your report.
Repos:
+
- `agent-gateway` (Cloudflare Worker, Durable Objects) β€” worktree `/Users/arvinxx/CodeProjects/LobeHub/agent-gateway-wt-user-hub`
- `lobehub` server (`apps/server`) and client (`packages/agent-gateway-client`, `src/store/chat/.../gateway`) β€” worktree `/Users/arvinxx/CodeProjects/LobeHub/lobehub-wt-gateway-mux`
@@ -23,6 +24,23 @@ clients (web without the Labs flag, CLI, desktop).
Non-goals for this iteration: SharedWorker cross-tab sharing; removing `mirrorToOperationId`
/ `subagent_progress`; migrating CLI; removing v1.
+### 0.1 Native runtime message reconciliation
+
+For the server-owned native agent harness, protocol v2 avoids repeating the complete
+canonical conversation at every step boundary:
+
+- `step_start.data` carries `{ messageRevision }` instead of `uiMessages`.
+- After the step is durable, an `agent_event` with `event.type: 'message_patch'` carries
+ `{ revision, deletes, upserts }`. Each upsert contains the canonical top-level
+ `UIChatMessage` plus its immediate predecessor as `afterId` (`null` for the first row).
+- `agent_runtime_end.data` carries `{ messagePatchMode: true, messageRevision }` and omits
+ both `uiMessages` and `finalState`. The client settles only after it has that revision.
+- A missing revision or insertion anchor falls back to the existing authorized full-message
+ query; patches are an optimization, not a second source of truth.
+
+This extension is intentionally limited to mux (`/v2/ws`) and the native harness. V1,
+heterogeneous CLI ingest, and share visitors keep their existing snapshot behavior.
+
## 1. Topology
```
@@ -35,9 +53,7 @@ Browser tab ──── GET /v2/ws?token=… ───────────
Bindings (wrangler.toml): add `USER_HUB` β†’ class `UserHubDO`; migration tag `v3`
`new_classes = ["UserHubDO"]`. `Env.USER_HUB: DurableObjectNamespace`.
-Hub id: `env.USER_HUB.idFromName(\`user:${userId}\`)` where `userId` is the JWT `sub`
-(for share visitors this is the visitor user id β€” the same value LobeHub sends as
-`streamOwnerUserId`/`userId` in `init`, so ownership checks line up unchanged).
+Hub id: `env.USER_HUB.idFromName(\`user:${userId}\`)`where`userId`is the JWT`sub`(for share visitors this is the visitor user id β€” the same value LobeHub sends as`streamOwnerUserId`/`userId`in`init\`, so ownership checks line up unchanged).
## 2. Worker routes (src/index.ts)
@@ -59,6 +75,7 @@ Existing routes unchanged. New:
## 3. AgentOperationDO changes (src/AgentOperationDO.ts)
### 3.1 P0 fixes (independent value, land as their own commit)
+
1. **Persist the sequence.** Replace in-memory `eventCounter` with storage key `seq`
(number). `nextEventId()` must be monotonic across eviction/hibernation: load `seq` lazily
in `blockConcurrencyWhile` on construction, increment in memory, and write it in the same
@@ -92,16 +109,20 @@ Leave `interrupt` as-is (documented no-op; the web client interrupts via tRPC).
attempt to implement it.
### 3.2 Init metadata
+
`POST /api/operations/init` body becomes
+
```ts
{ operationId, userId,
meta?: { topicId?, threadId?, agentId?, groupId?, taskId?, scope?,
parentOperationId?, mirrorToOperationId?, rootOperationId? } }
```
+
Persist `meta` (storage key `meta`). Unknown fields ignored. Missing `meta` is fine (legacy).
### 3.3 Forwarding to the hub
-After `init` the op DO knows `userId` β‡’ `hub = env.USER_HUB.get(idFromName(\`user:${userId}\`))`.
+
+After `init` the op DO knows `userId` β‡’ `hub = env.USER_HUB.get(idFromName(\`user:${userId}\`))\`.
Two classes of forward, both `POST` to the hub stub (fire-and-forget via `waitUntil`, 5s
timeout, errors logged, never fail the backend request):
@@ -121,11 +142,12 @@ Ordering: the hub is called from inside `broadcastAndBuffer` in id order, but fo
async β€” include `id` and let the hub order by numeric id (it drops ids ≀ per-socket lastSeq).
### 3.4 Internal routes on the op DO (called by the hub)
+
- `POST /api/operations/hub-subscribe` `{}` β†’ sets `hubSubscribed=true`, returns
`{ userId, status, meta, seq }`. (`userId` undefined β‡’ not inited yet.)
- `POST /api/operations/hub-unsubscribe` `{}` β†’ `hubSubscribed=false`.
- `POST /api/operations/replay` `{ since: string }` β†’ `{ events: BufferedEvent['data'][],
- status?: SessionStatus, gap: boolean, seq: number }` β€” same semantics as Β§3.1.2.
+status?: SessionStatus, gap: boolean, seq: number }` β€” same semantics as Β§3.1.2.
- `POST /api/operations/client-message` `{ message: ClientMessage, connectionId }` β†’ the
op DO handles `tool_result` / `tool_confirmation` / `user_input` / `interrupt` exactly as
if they had arrived on a v1 socket (refactor the v1 `webSocketMessage` switch into a
@@ -137,13 +159,15 @@ stub calls bypass the worker so they need no token.
## 4. UserHubDO (new file src/UserHubDO.ts)
State:
+
- storage `conn:${connectionId}` β†’ `{ userId, clientId, connectedAt,
- subs: Record<operationId, { lastSeq: number; executor: boolean; state: 'pending'|'replaying'|'live' }> }`
+subs: Record<operationId, { lastSeq: number; executor: boolean; state: 'pending'|'replaying'|'live' }> }`
(subscriptions live in storage, NOT in the 2 KB socket attachment; attachment holds only
`{ connectionId, userId }`).
- in-memory: per-(connection, op) live-event queue used while `replaying`.
WebSocket handling (Hibernation API):
+
- `acceptWebSocket(server, [userId, connectionId])` (tags!) so `getWebSockets(tag)` works.
- `setWebSocketAutoResponse(new WebSocketRequestResponsePair('{"type":"heartbeat"}','{"type":"heartbeat_ack"}'))`
β€” heartbeats never wake the DO. Idle check alarm every 120s: close sockets whose
@@ -153,6 +177,7 @@ WebSocket handling (Hibernation API):
no subscriber left across all connections, call op DO `hub-unsubscribe`.
Client β†’ hub messages (JSON, all carry `operationId` where relevant):
+
```ts
| { type:'subscribe'; operationId; lastEventId?: string; executor?: boolean }
| { type:'unsubscribe'; operationId }
@@ -162,7 +187,9 @@ Client β†’ hub messages (JSON, all carry `operationId` where relevant):
| { type:'user_input'; operationId; requestId; content }
| { type:'interrupt'; operationId }
```
+
Hub β†’ client messages:
+
```ts
| { type:'ready'; userId; connectionId; protocol: 2 }
| { type:'agent_event'; operationId; id; event } // event.operationId may differ (mirrored member)
@@ -178,6 +205,7 @@ Hub β†’ client messages:
```
Subscribe algorithm (per connection, per op):
+
1. Record sub `{ lastSeq: Number(lastEventId ?? 0), executor, state:'replaying' }`.
2. Call op DO `hub-subscribe`. If it returns a `userId` that β‰  hub's userId β‡’
`subscribe_failed{forbidden}` and drop the sub. If `userId` is undefined (op not inited
@@ -212,7 +240,7 @@ Client messages that target an op: verify the connection is subscribed to it (el
- `shareChat.issueGatewayUserToken({ agentShareId })` β€” subject the visitor user id
resolved the same way `shareChat.refreshGatewayToken` resolves it (reuse its helper),
without requiring a running operation.
- Keep `refreshGatewayToken` untouched (v1 path).
+ Keep `refreshGatewayToken` untouched (v1 path).
3. `src/services/aiAgent.ts` `issueGatewayUserToken()` and `src/services/shareChat.ts`
`issueGatewayUserToken(agentShareId)` wrappers.
4. Tests for both procedures and the init body.
@@ -223,29 +251,37 @@ New `src/mux/` exporting `GatewayMuxClient` and `createOperationClient`:
```ts
interface GatewayMuxClientOptions {
- gatewayUrl: string; // same base as v1; client appends /v2/ws
- getToken: () => Promise<string>; // called before EVERY connect attempt
+ gatewayUrl: string; // same base as v1; client appends /v2/ws
+ getToken: () => Promise<string>; // called before EVERY connect attempt
clientId?: string;
- autoReconnect?: boolean; // default true
- heartbeatIntervalMs?: number; // default 30_000, sends exactly {"type":"heartbeat"}
+ autoReconnect?: boolean; // default true
+ heartbeatIntervalMs?: number; // default 30_000, sends exactly {"type":"heartbeat"}
}
class GatewayMuxClient {
- connect(): Promise<void>; disconnect(): void; // idempotent; refcount-free (owner decides)
- readonly status: 'disconnected'|'connecting'|'connected';
- subscribe(operationId, opts?: { lastEventId?: string; executor?: boolean }): OperationSubscription;
- on(event: 'lifecycle'|'status_changed'|'error'|'connected'|'disconnected'|'reconnecting', cb): () => void;
+ connect(): Promise<void>;
+ disconnect(): void; // idempotent; refcount-free (owner decides)
+ readonly status: 'disconnected' | 'connecting' | 'connected';
+ subscribe(
+ operationId,
+ opts?: { lastEventId?: string; executor?: boolean },
+ ): OperationSubscription;
+ on(
+ event: 'lifecycle' | 'status_changed' | 'error' | 'connected' | 'disconnected' | 'reconnecting',
+ cb,
+ ): () => void;
}
interface OperationSubscription {
operationId: string;
on<K extends keyof AgentStreamClientEvents>(event: K, cb: AgentStreamClientEvents[K]): () => void;
// plus 'resume_complete': (info: { status?: SessionStatus; gap: boolean; pending?: boolean }) => void
- sendToolResult(result: ToolResultPayload): boolean; // queued while disconnected, TTL 120s
+ sendToolResult(result: ToolResultPayload): boolean; // queued while disconnected, TTL 120s
sendInterrupt(): boolean;
unsubscribe(): void;
}
```
Behavior:
+
- Single socket; `subscribe` while disconnected triggers `connect()`; on (re)connect the
client re-sends `subscribe` for every live subscription with its per-op `lastEventId`.
- Reconnect: exponential 1s→30s **with full jitter**; immediate reconnect on `online` and on
@@ -285,4 +321,4 @@ Behavior:
- `executor: true` for subscriptions created by `executeGatewayAgent` (this tab started the
run); `false` for `reconnectToGatewayOperation`.
- Mux-level `lifecycle` events: store them in a small slice `gatewayFeed[operationId] =
- { status, meta, at }` (no UI yet; selector only) so later work can drive spinners/reconnect.
+{ status, meta, at }` (no UI yet; selector only) so later work can drive spinners/reconnect.
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index b523d7cc38d..5198a9df52f 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -53,6 +53,8 @@ export type {
AgentStreamEventType,
AgentStreamSessionCompletion,
ConnectionStatus,
+ MessagePatchData,
+ MessagePatchUpsert,
SessionStatus,
StepCompleteData,
StreamChunkData,
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index e54ff1d6d2f..153bfe034a5 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -1,3 +1,5 @@
+import type { UIChatMessage } from '@lobechat/types';
+
// ─── Agent Stream Event (mirrors server StreamEvent) ───
export type AgentStreamEventType =
@@ -39,6 +41,12 @@ export type AgentStreamEventType =
* cancellation marker.
*/
| 'agent_intervention_response'
+ /**
+ * Protocol-v2-only canonical conversation delta. Native server agent runs
+ * emit one after each durable step instead of repeating the whole topic on
+ * every `step_start` / `agent_runtime_end` boundary.
+ */
+ | 'message_patch'
| 'step_start'
| 'step_complete'
/**
@@ -59,6 +67,22 @@ export interface AgentStreamEvent {
type: AgentStreamEventType;
}
+export interface MessagePatchUpsert {
+ /** Immediate predecessor in the canonical top-level message list. */
+ afterId: string | null;
+ message: UIChatMessage;
+}
+
+/**
+ * Operation-local, monotonic patch carried only by Gateway mux / protocol v2.
+ * A missing revision is recovered with one normal message-list fetch.
+ */
+export interface MessagePatchData {
+ deletes: string[];
+ revision: number;
+ upserts: MessagePatchUpsert[];
+}
+
export type StreamChunkType =
| 'text'
| 'reasoning'
diff --git a/packages/builtin-tool-web-browsing/src/client/Portal/PageContent/index.tsx b/packages/builtin-tool-web-browsing/src/client/Portal/PageContent/index.tsx
index 853a931fc2d..9159498df60 100644
--- a/packages/builtin-tool-web-browsing/src/client/Portal/PageContent/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Portal/PageContent/index.tsx
@@ -1,13 +1,15 @@
-import type { CrawlResult } from '@lobechat/types';
+import type { CrawlPluginState, CrawlResult } from '@lobechat/types';
import type { CrawlSuccessResult } from '@lobechat/web-crawler';
import { CopyButton, Flexbox, Highlighter, Icon, Markdown, stopPropagation } from '@lobehub/ui';
-import { Alert, Segmented, Text } from '@lobehub/ui/base-ui';
+import { Alert, Segmented, Skeleton, Text } from '@lobehub/ui/base-ui';
import { Descriptions } from 'antd';
import { createStaticStyles } from 'antd-style';
import { ExternalLink } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useToolResultPayload } from '@/hooks/useToolResultPayload';
+
import { CRAWL_CONTENT_LIMITED_COUNT } from '../../../const';
const styles = createStaticStyles(({ css, cssVar }) => {
@@ -90,10 +92,23 @@ interface PageContentProps {
result?: CrawlResult;
}
-const PageContent = memo<PageContentProps>(({ result }) => {
+const PageContent = memo<PageContentProps>(({ messageId, result }) => {
const { t } = useTranslation('plugin');
const [display, setDisplay] = useState<DisplayType>(DisplayType.Render);
+ // The conversation read path hands the inline card a PREVIEW of the page and
+ // leaves the body on the server. `length` stays pinned to the real body, so a
+ // shorter `content` is the signal that this surface β€” the one that actually
+ // shows the page β€” has to go fetch it. Legacy rows carry the whole body and
+ // never trigger a request.
+ const previewed = result?.data as CrawlSuccessResult | undefined;
+ const isPreview =
+ typeof previewed?.length === 'number' && (previewed.content?.length ?? 0) < previewed.length;
+ const { isLoading, payload } = useToolResultPayload(messageId, isPreview);
+ const storedContent = (payload?.pluginState as CrawlPluginState | undefined)?.results?.find(
+ (stored) => stored.originalUrl === result?.originalUrl,
+ )?.data?.content;
+
if (!result || !result.data) return undefined;
if ('errorType' in result.data) {
@@ -131,7 +146,15 @@ const PageContent = memo<PageContentProps>(({ result }) => {
);
}
- const { url, title, description, content, siteName } = result.data as CrawlSuccessResult;
+ const {
+ url,
+ title,
+ description,
+ content: previewContent,
+ length,
+ siteName,
+ } = result.data as CrawlSuccessResult;
+ const content = storedContent ?? previewContent;
return (
<Flexbox gap={24}>
<Flexbox gap={8}>
@@ -175,7 +198,7 @@ const PageContent = memo<PageContentProps>(({ result }) => {
}}
items={[
{
- children: result.data.content?.length,
+ children: length ?? content?.length,
label: t('search.crawPages.meta.words'),
},
{
@@ -186,6 +209,7 @@ const PageContent = memo<PageContentProps>(({ result }) => {
/>
</div>
</Flexbox>
+ {isLoading && !storedContent && <Skeleton height={160} width={'100%'} />}
{content && (
<Flexbox gap={12} paddingBlock={'0 12px'}>
<Flexbox horizontal justify={'space-between'}>
diff --git a/packages/builtin-tool-web-browsing/src/client/Render/PageContent/Result.tsx b/packages/builtin-tool-web-browsing/src/client/Render/PageContent/Result.tsx
index 4e01f8b622f..35af8c5b09c 100644
--- a/packages/builtin-tool-web-browsing/src/client/Render/PageContent/Result.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Render/PageContent/Result.tsx
@@ -98,7 +98,7 @@ const CrawlerResultCard = memo<CrawlerData>(({ result, messageId, crawler, origi
);
}
- const { url, title, description } = result as CrawlSuccessResult;
+ const { url, title, description, length } = result as CrawlSuccessResult;
return (
<Block
@@ -132,7 +132,9 @@ const CrawlerResultCard = memo<CrawlerData>(({ result, messageId, crawler, origi
}}
items={[
{
- children: result.content?.length,
+ // `length` is pinned to the crawled body; `content` may be a
+ // preview once the read path projects this tool.
+ children: length ?? result.content?.length,
label: t('search.crawPages.meta.words'),
},
{
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 7cf02faedf4..a3dde4612d0 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -1042,6 +1042,11 @@ export class FlatListBuilder {
content: toolMsg.content || '',
id: toolMsg.id,
};
+ // A projected tool has an empty body and its real length here; the
+ // completion checks read this instead of the body.
+ if (typeof toolMsg.contentLength === 'number') {
+ result.contentLength = toolMsg.contentLength;
+ }
if (toolMsg.error) result.error = toolMsg.error;
if (toolMsg.pluginError) result.error = toolMsg.pluginError;
if (toolMsg.pluginState) result.state = toolMsg.pluginState;
diff --git a/packages/tool-view-model/package.json b/packages/tool-view-model/package.json
new file mode 100644
index 00000000000..6529b4171fa
--- /dev/null
+++ b/packages/tool-view-model/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@lobechat/tool-view-model",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "scripts": {
+ "test": "vitest"
+ },
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/tool-view-model/src/index.ts b/packages/tool-view-model/src/index.ts
new file mode 100644
index 00000000000..dd6023a5b75
--- /dev/null
+++ b/packages/tool-view-model/src/index.ts
@@ -0,0 +1,3 @@
+export { type ProjectorResolver, projectToolViewModels } from './project';
+export { getToolProjector, listProjectedTools } from './registry';
+export type { ToolProjection, ToolProjector, ToolProjectorInput } from './types';
diff --git a/packages/tool-view-model/src/project.test.ts b/packages/tool-view-model/src/project.test.ts
new file mode 100644
index 00000000000..4176b4dd709
--- /dev/null
+++ b/packages/tool-view-model/src/project.test.ts
@@ -0,0 +1,123 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { projectToolViewModels } from './project';
+import { listProjectedTools } from './registry';
+import type { ToolProjector } from './types';
+
+const toolMessage = (partial: Partial<UIChatMessage> = {}): UIChatMessage =>
+ ({
+ content: 'RAW BODY',
+ createdAt: 0,
+ id: 'tool-1',
+ plugin: { apiName: 'crawlSinglePage', arguments: '{}', identifier: 'lobe-web-browsing' },
+ pluginState: { results: [{ data: { content: 'x'.repeat(5000) } }] },
+ role: 'tool',
+ updatedAt: 0,
+ ...partial,
+ }) as UIChatMessage;
+
+const resolveWith = (projector: ToolProjector) => (identifier?: string | null) =>
+ identifier === 'lobe-web-browsing' ? projector : undefined;
+
+describe('projectToolViewModels', () => {
+ it('leaves every message untouched when no projector matches', () => {
+ const messages = [toolMessage(), toolMessage({ id: 'a', role: 'assistant' })];
+
+ expect(projectToolViewModels(messages, () => undefined)).toEqual(messages);
+ });
+
+ it('keeps the original content length after the body is dropped', () => {
+ const [projected] = projectToolViewModels(
+ [toolMessage()],
+ resolveWith(() => ({ content: null })),
+ );
+
+ expect(projected.content).toBe('');
+ expect(projected.contentLength).toBe('RAW BODY'.length);
+ expect(projected.payloadOmitted).toBe('detail');
+ });
+
+ it('replaces pluginState while leaving content alone', () => {
+ const [projected] = projectToolViewModels(
+ [toolMessage()],
+ resolveWith(() => ({ pluginState: { results: [{ title: 'T' }] } })),
+ );
+
+ expect(projected.content).toBe('RAW BODY');
+ expect(projected.pluginState).toEqual({ results: [{ title: 'T' }] });
+ expect(projected.payloadOmitted).toBe('detail');
+ });
+
+ it('records which surface has to fetch the stored payload back', () => {
+ const [projected] = projectToolViewModels(
+ [toolMessage()],
+ resolveWith(() => ({ content: null, storedPayloadNeededBy: 'render' })),
+ );
+
+ expect(projected.payloadOmitted).toBe('render');
+ });
+
+ it('does not mark a message as omitted when the projector declines', () => {
+ const [projected] = projectToolViewModels(
+ [toolMessage()],
+ resolveWith(() => undefined),
+ );
+
+ expect(projected.payloadOmitted).toBeUndefined();
+ expect(projected.pluginState).toEqual(toolMessage().pluginState);
+ });
+
+ it('falls back to the stored payload when a projector throws', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const [projected] = projectToolViewModels(
+ [toolMessage()],
+ resolveWith(() => {
+ throw new Error('bad shape');
+ }),
+ );
+
+ expect(projected).toEqual(toolMessage());
+ expect(error).toHaveBeenCalled();
+ error.mockRestore();
+ });
+
+ it('never projects a non-tool message, even with a plugin payload', () => {
+ const assistant = toolMessage({ id: 'a', role: 'assistant' });
+
+ const [projected] = projectToolViewModels(
+ [assistant],
+ resolveWith(() => ({ content: null })),
+ );
+
+ expect(projected).toEqual(assistant);
+ });
+
+ it('projects tool rows nested in compression groups, columns and members', () => {
+ const nested = [
+ toolMessage({ id: 'nested', compressedMessages: [toolMessage({ id: 'compressed' })] }),
+ toolMessage({ id: 'col-parent', columns: [[toolMessage({ id: 'col-child' })]] }),
+ toolMessage({ id: 'member-parent', members: [toolMessage({ id: 'member' })] }),
+ ];
+
+ const [compressedParent, columnParent, memberParent] = projectToolViewModels(
+ nested,
+ resolveWith(() => ({ content: null })),
+ );
+
+ expect(compressedParent.compressedMessages![0].payloadOmitted).toBe('detail');
+ expect(columnParent.columns![0][0].payloadOmitted).toBe('detail');
+ expect(memberParent.members![0].payloadOmitted).toBe('detail');
+ });
+});
+
+describe('registry', () => {
+ it('projects exactly the tools that were measured and audited', () => {
+ expect(listProjectedTools().sort()).toEqual([
+ 'lobe-agent-documents/readDocument',
+ 'lobe-local-system/runCommand',
+ 'lobe-web-browsing/crawlMultiPages',
+ 'lobe-web-browsing/crawlSinglePage',
+ ]);
+ });
+});
diff --git a/packages/tool-view-model/src/project.ts b/packages/tool-view-model/src/project.ts
new file mode 100644
index 00000000000..50a8a4385df
--- /dev/null
+++ b/packages/tool-view-model/src/project.ts
@@ -0,0 +1,88 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+import { getToolProjector } from './registry';
+import type { ToolProjector } from './types';
+
+/** Resolves the projector for one tool call. Injectable so the pipeline can be
+ * exercised without mutating the process-wide registry. */
+export type ProjectorResolver = (
+ identifier?: string | null,
+ apiName?: string | null,
+) => ToolProjector | undefined;
+
+const projectToolMessage = (message: UIChatMessage, resolve: ProjectorResolver): UIChatMessage => {
+ const projector = resolve(message.plugin?.identifier, message.plugin?.apiName);
+ if (!projector) return message;
+
+ let projection;
+ try {
+ projection = projector({
+ apiName: message.plugin!.apiName,
+ arguments: message.plugin?.arguments,
+ content: message.content,
+ identifier: message.plugin!.identifier,
+ pluginState: message.pluginState,
+ });
+ } catch (error) {
+ // A projector is a read-path detail; a bad one must degrade to today's
+ // behaviour rather than fail the whole conversation load.
+ console.error(
+ '[toolViewModel] projector threw for %s/%s: %O',
+ message.plugin?.identifier,
+ message.plugin?.apiName,
+ error,
+ );
+ return message;
+ }
+
+ if (!projection) return message;
+
+ const replacedContent = projection.content !== undefined;
+ const replacedState = projection.pluginState !== undefined;
+ if (!replacedContent && !replacedState) return message;
+
+ return {
+ ...message,
+ // Presence checks (the tool status icon, the assistant group's "is this
+ // tool settled" test) read the body's length, not the body. Preserve it
+ // from the ORIGINAL content so a trimmed body never reads as "returned
+ // nothing".
+ contentLength: message.content?.length ?? 0,
+ ...(replacedContent && { content: projection.content ?? '' }),
+ // Tells the client the stored payload is larger than what it holds, and
+ // which surface has to fetch it back.
+ payloadOmitted: projection.storedPayloadNeededBy ?? 'detail',
+ ...(replacedState && { pluginState: projection.pluginState }),
+ };
+};
+
+/**
+ * Reduce every tool message in a query result to its render-facing view model.
+ *
+ * Applies ONLY to the UI read path. The model-facing read goes straight through
+ * `MessageModel.query` into the LLM context and never reaches this function β€”
+ * the split is a layer boundary, not a flag a caller can forget to set.
+ */
+export const projectToolViewModels = (
+ messages: UIChatMessage[],
+ resolve: ProjectorResolver = getToolProjector,
+): UIChatMessage[] =>
+ messages.map((message) => {
+ const projected = message.role === 'tool' ? projectToolMessage(message, resolve) : message;
+
+ // A query result can nest further message lists (compression groups,
+ // parallel compare columns, group members). Their tool rows are the same
+ // rows and deserve the same treatment.
+ return {
+ ...projected,
+ ...(projected.columns?.length && {
+ columns: projected.columns.map((column) => projectToolViewModels(column, resolve)),
+ }),
+ ...(projected.compressedMessages?.length && {
+ compressedMessages: projectToolViewModels(projected.compressedMessages, resolve),
+ }),
+ ...(projected.members?.length && {
+ members: projectToolViewModels(projected.members, resolve),
+ }),
+ };
+ });
diff --git a/packages/tool-view-model/src/projectors/agentDocuments.ts b/packages/tool-view-model/src/projectors/agentDocuments.ts
new file mode 100644
index 00000000000..0800d9cd74b
--- /dev/null
+++ b/packages/tool-view-model/src/projectors/agentDocuments.ts
@@ -0,0 +1,23 @@
+import type { ToolProjector } from '../types';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+/**
+ * `readDocument`.
+ *
+ * The only surface is the inspector chip, which prints `pluginState.title` and
+ * falls back to the call's document id. Everything else in state is the document
+ * itself, stored twice β€” `content` and `xml`, two representations of the same
+ * text, together averaging ~63 kB against the 53 bytes the chip renders.
+ *
+ * The message body is the model's copy and is dropped with them; the reader
+ * surface fetches the raw payload when it needs the document.
+ */
+export const readDocumentProjector: ToolProjector = ({ pluginState }) => {
+ if (!isRecord(pluginState)) return { content: null, storedPayloadNeededBy: 'render' };
+
+ const { content: _content, xml: _xml, ...rest } = pluginState;
+
+ return { content: null, pluginState: rest, storedPayloadNeededBy: 'render' };
+};
diff --git a/packages/tool-view-model/src/projectors/localSystem.ts b/packages/tool-view-model/src/projectors/localSystem.ts
new file mode 100644
index 00000000000..32c424772fa
--- /dev/null
+++ b/packages/tool-view-model/src/projectors/localSystem.ts
@@ -0,0 +1,35 @@
+import type { ToolProjector } from '../types';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+/** State a settled command keeps: everything except the output itself. */
+const OUTPUT_KEYS = new Set(['output', 'stdout']);
+
+/**
+ * `runCommand`.
+ *
+ * The command's output is stored THREE times: the tool message body,
+ * `state.stdout`, and the legacy `state.output`. All three go. What stays is the
+ * small settled metadata the collapsed row reads β€” exit code, success,
+ * background flag, command id, stderr, produced files.
+ *
+ * The card DOES render the output, but only once the row is expanded, and the
+ * card mounts with that expansion β€” so it hydrates then rather than riding along
+ * with every conversation load. Hence `'render'`.
+ */
+export const runCommandProjector: ToolProjector = ({ content, pluginState }) => {
+ if (!isRecord(pluginState)) {
+ return content ? { content: null, storedPayloadNeededBy: 'render' } : undefined;
+ }
+
+ const carriesOutput =
+ typeof pluginState.stdout === 'string' || typeof pluginState.output === 'string' || !!content;
+ if (!carriesOutput) return undefined;
+
+ const projectedState = Object.fromEntries(
+ Object.entries(pluginState).filter(([key]) => !OUTPUT_KEYS.has(key)),
+ );
+
+ return { content: null, pluginState: projectedState, storedPayloadNeededBy: 'render' };
+};
diff --git a/packages/tool-view-model/src/projectors/projectors.test.ts b/packages/tool-view-model/src/projectors/projectors.test.ts
new file mode 100644
index 00000000000..7764539f511
--- /dev/null
+++ b/packages/tool-view-model/src/projectors/projectors.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it } from 'vitest';
+
+import { readDocumentProjector } from './agentDocuments';
+import { runCommandProjector } from './localSystem';
+import { crawlProjector } from './webBrowsing';
+
+const input = (partial: Record<string, unknown> = {}) => ({
+ apiName: 'x',
+ arguments: '{}',
+ content: 'MODEL COPY',
+ identifier: 'y',
+ ...partial,
+});
+
+describe('crawlProjector', () => {
+ const page = (content: string) => ({
+ crawler: 'naive',
+ data: { content, contentType: 'text', description: 'D', title: 'T', url: 'https://a.test' },
+ originalUrl: 'https://a.test',
+ });
+
+ it('drops the message body, which the crawl render never reads', () => {
+ const result = crawlProjector(input({ pluginState: { results: [page('x'.repeat(50_000))] } }));
+
+ expect(result?.content).toBeNull();
+ });
+
+ it('keeps the card fields and trims the page body to a preview', () => {
+ const body = 'x'.repeat(50_000);
+
+ const result = crawlProjector(input({ pluginState: { results: [page(body)] } }));
+ const [projected] = (result?.pluginState as any).results;
+
+ expect(projected.crawler).toBe('naive');
+ expect(projected.originalUrl).toBe('https://a.test');
+ expect(projected.data).toMatchObject({ description: 'D', title: 'T', url: 'https://a.test' });
+ expect(projected.data.content).toHaveLength(200);
+ expect(JSON.stringify(projected).length).toBeLessThan(600);
+ });
+
+ it('pins the character count to the original body, not the preview', () => {
+ const result = crawlProjector(input({ pluginState: { results: [page('x'.repeat(50_000))] } }));
+
+ expect((result?.pluginState as any).results[0].data.length).toBe(50_000);
+ });
+
+ it('prefers a stored length over recomputing it', () => {
+ const state = {
+ results: [
+ {
+ ...page('x'.repeat(50_000)),
+ data: { ...page('x').data, content: 'x'.repeat(50_000), length: 42 },
+ },
+ ],
+ };
+
+ const result = crawlProjector(input({ pluginState: state }));
+
+ expect((result?.pluginState as any).results[0].data.length).toBe(42);
+ });
+
+ it('leaves a short page untouched', () => {
+ const result = crawlProjector(input({ pluginState: { results: [page('short')] } }));
+
+ expect((result?.pluginState as any).results[0].data.content).toBe('short');
+ });
+
+ it('leaves an error result whole, since the card prints its content', () => {
+ const errorPage = {
+ crawler: 'naive',
+ data: { content: 'boom', errorMessage: 'nope', errorType: 'Timeout' },
+ originalUrl: 'https://a.test',
+ };
+
+ const result = crawlProjector(input({ pluginState: { results: [errorPage] } }));
+
+ expect((result?.pluginState as any).results[0]).toEqual(errorPage);
+ });
+
+ it('still drops the duplicated body when the state shape is unknown', () => {
+ expect(crawlProjector(input({ pluginState: { weird: true } }))).toEqual({ content: null });
+ });
+});
+
+describe('runCommandProjector', () => {
+ it('drops all three copies of the output and keeps the settled metadata', () => {
+ const result = runCommandProjector(
+ input({
+ pluginState: {
+ exitCode: 0,
+ outputFiles: ['/tmp/a.log'],
+ output: 'OUT',
+ stderr: 'warn',
+ stdout: 'OUT',
+ success: true,
+ },
+ }),
+ );
+
+ expect(result?.content).toBeNull();
+ expect(result?.pluginState).toEqual({
+ exitCode: 0,
+ outputFiles: ['/tmp/a.log'],
+ stderr: 'warn',
+ success: true,
+ });
+ });
+
+ it('asks the card itself to fetch, since the card is what renders the output', () => {
+ const result = runCommandProjector(input({ pluginState: { stdout: 'OUT' } }));
+
+ expect(result?.storedPayloadNeededBy).toBe('render');
+ });
+
+ it('drops a legacy row that only has `output`', () => {
+ const result = runCommandProjector(input({ pluginState: { output: 'OUT' } }));
+
+ expect(result?.pluginState).toEqual({});
+ expect(result?.content).toBeNull();
+ });
+
+ it('still drops the body when state carries no output at all', () => {
+ const result = runCommandProjector(input({ pluginState: { exitCode: 0 } }));
+
+ expect(result?.content).toBeNull();
+ expect(result?.pluginState).toEqual({ exitCode: 0 });
+ });
+
+ it('declines a call that produced nothing to drop', () => {
+ expect(
+ runCommandProjector(input({ content: '', pluginState: { exitCode: 0 } })),
+ ).toBeUndefined();
+ expect(runCommandProjector(input({ content: '', pluginState: undefined }))).toBeUndefined();
+ });
+});
+
+describe('readDocumentProjector', () => {
+ it('keeps only what the inspector chip renders', () => {
+ const result = readDocumentProjector(
+ input({
+ pluginState: {
+ content: 'x'.repeat(30_000),
+ id: 'doc_1',
+ title: 'Spec',
+ xml: 'y'.repeat(40_000),
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ content: null,
+ pluginState: { id: 'doc_1', title: 'Spec' },
+ storedPayloadNeededBy: 'render',
+ });
+ });
+
+ it('drops the duplicated body even without a usable state', () => {
+ expect(readDocumentProjector(input({ pluginState: undefined }))).toEqual({
+ content: null,
+ storedPayloadNeededBy: 'render',
+ });
+ });
+});
diff --git a/packages/tool-view-model/src/projectors/webBrowsing.ts b/packages/tool-view-model/src/projectors/webBrowsing.ts
new file mode 100644
index 00000000000..43bdec0c508
--- /dev/null
+++ b/packages/tool-view-model/src/projectors/webBrowsing.ts
@@ -0,0 +1,59 @@
+import type { ToolProjector } from '../types';
+
+/**
+ * How much of a crawled page body survives projection.
+ *
+ * The inline card shows `description || content.slice(0, 40)`, so 40 is all the
+ * render can consume today; the rest is headroom so a copy tweak doesn't need a
+ * server change. The full body lives in the detail portal, which fetches the raw
+ * payload on open.
+ */
+const CRAWL_PREVIEW_CHARS = 200;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+const projectCrawlResult = (result: unknown): unknown => {
+ if (!isRecord(result)) return result;
+
+ const data = result.data;
+ if (!isRecord(data)) return result;
+
+ // An error result's `content` IS what the card prints when `errorMessage` is
+ // missing, and it is short by construction. Leave it whole.
+ if ('errorType' in data) return result;
+
+ const content = data.content;
+ if (typeof content !== 'string' || content.length <= CRAWL_PREVIEW_CHARS) return result;
+
+ return {
+ ...result,
+ data: {
+ ...data,
+ content: content.slice(0, CRAWL_PREVIEW_CHARS),
+ // The card prints a character count. Pin it from the ORIGINAL body before
+ // truncating, or every crawled page would report exactly 200 characters.
+ length: typeof data.length === 'number' ? data.length : content.length,
+ },
+ };
+};
+
+/**
+ * `crawlSinglePage` / `crawlMultiPages`.
+ *
+ * The render (`Render/PageContent`) reads `pluginState.results` and the call
+ * arguments β€” never the tool message body, which holds a second copy of the same
+ * page text for the model. So the body goes entirely, and each result keeps its
+ * card fields plus a preview of the page.
+ */
+export const crawlProjector: ToolProjector = ({ pluginState }) => {
+ if (!isRecord(pluginState) || !Array.isArray(pluginState.results)) {
+ // Shape we don't recognise: drop the duplicated body, touch nothing else.
+ return { content: null };
+ }
+
+ return {
+ content: null,
+ pluginState: { ...pluginState, results: pluginState.results.map(projectCrawlResult) },
+ };
+};
diff --git a/packages/tool-view-model/src/registry.ts b/packages/tool-view-model/src/registry.ts
new file mode 100644
index 00000000000..0e7121a1301
--- /dev/null
+++ b/packages/tool-view-model/src/registry.ts
@@ -0,0 +1,41 @@
+import { readDocumentProjector } from './projectors/agentDocuments';
+import { runCommandProjector } from './projectors/localSystem';
+import { crawlProjector } from './projectors/webBrowsing';
+import type { ToolProjector } from './types';
+
+/**
+ * `identifier` β†’ `apiName` β†’ projector.
+ *
+ * Deliberately a static literal rather than the `register*()` pattern the
+ * client-side render registry uses: this map is read from the server read path,
+ * where there is no app bootstrap to guarantee registration ran first. A tool
+ * missing from here keeps today's behaviour (raw payload passes through), so
+ * the map can be filled one tool at a time.
+ */
+const toolProjectors: Record<string, Record<string, ToolProjector>> = {
+ 'lobe-agent-documents': {
+ readDocument: readDocumentProjector,
+ },
+ 'lobe-local-system': {
+ runCommand: runCommandProjector,
+ },
+ 'lobe-web-browsing': {
+ crawlMultiPages: crawlProjector,
+ crawlSinglePage: crawlProjector,
+ },
+};
+
+export const getToolProjector = (
+ identifier?: string | null,
+ apiName?: string | null,
+): ToolProjector | undefined => {
+ if (!identifier || !apiName) return undefined;
+
+ return toolProjectors[identifier]?.[apiName];
+};
+
+/** Every `identifier/apiName` pair that currently has a projector. */
+export const listProjectedTools = (): string[] =>
+ Object.entries(toolProjectors).flatMap(([identifier, apis]) =>
+ Object.keys(apis).map((apiName) => `${identifier}/${apiName}`),
+ );
diff --git a/packages/tool-view-model/src/types.ts b/packages/tool-view-model/src/types.ts
new file mode 100644
index 00000000000..96c2570d32f
--- /dev/null
+++ b/packages/tool-view-model/src/types.ts
@@ -0,0 +1,53 @@
+/**
+ * The raw, stored payload of one tool message, as a projector sees it.
+ *
+ * `content` and `pluginState` are what the DB holds. They serve TWO audiences
+ * that have been conflated so far: the model (the whole blob is replayed into
+ * the LLM context) and the screen (a render component picks a handful of fields
+ * out of it). A projector exists to split those apart.
+ */
+export interface ToolProjectorInput {
+ apiName: string;
+ /** JSON-encoded tool call arguments, exactly as the model produced them. */
+ arguments?: string;
+ content: string;
+ identifier: string;
+ pluginState?: unknown;
+}
+
+/**
+ * What a projector hands back. Both fields are optional and OMISSION MEANS
+ * "keep what is stored" β€” a projector that only shrinks `pluginState` leaves
+ * `content` untouched by simply not returning it.
+ *
+ * Returning `content: null` drops the body entirely; use it when the render
+ * needs nothing from it (the length is preserved separately as
+ * `UIChatMessage.contentLength`, which several presence checks rely on).
+ */
+export interface ToolProjection {
+ content?: string | null;
+ pluginState?: unknown;
+ /**
+ * Who still needs the stored payload once this projection applies.
+ *
+ * `'detail'` (the default) means the inline card is complete on its own and
+ * only a detail surface β€” the crawl portal, the raw viewer β€” has to fetch.
+ * `'render'` means the card itself renders the body, so it must be hydrated
+ * when the row is expanded.
+ *
+ * Declared here, next to the projection that created the gap, so the two
+ * cannot drift the way a separate registry would.
+ */
+ storedPayloadNeededBy?: 'detail' | 'render';
+}
+
+/**
+ * Reduces one tool message's stored payload to what the UI actually renders.
+ *
+ * MUST be pure and dependency-free: it runs on the server, inside the read
+ * path, for every tool message of every query. Return `undefined` to decline
+ * (the message passes through untouched), which is also the correct answer for
+ * a payload shape the projector does not recognise β€” a projector must never
+ * throw on unexpected input, and must never invent data that was not stored.
+ */
+export type ToolProjector = (input: ToolProjectorInput) => ToolProjection | undefined;
diff --git a/packages/tool-view-model/vitest.config.mts b/packages/tool-view-model/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/tool-view-model/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.ts
index d85de0cb886..241b9894eb7 100644
--- a/packages/types/src/message/common/tools.ts
+++ b/packages/types/src/message/common/tools.ts
@@ -81,6 +81,13 @@ export interface ChatToolPayload {
*/
export interface ChatToolResult {
content: string | null;
+ /**
+ * Length of the STORED result body, carried when the read path replaced
+ * `content` with a render-facing view model. Anything deciding "did this tool
+ * produce a result" must consult it β€” see `hasToolResultBody`; a bare
+ * `!!content` test reads a projected result as still running.
+ */
+ contentLength?: number;
error?: any;
id: string;
state?: any;
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index aaf82b1f6af..72550c26153 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -218,6 +218,13 @@ export interface UIChatMessage {
*/
compressedMessages?: UIChatMessage[];
content: string;
+ /**
+ * Character length of the STORED tool result body, kept when the read path
+ * replaced `content` with a render-facing view model. Presence checks (the
+ * tool status icon, "is this tool settled") must read this instead of
+ * `content.length`, which would otherwise report a trimmed body as empty.
+ */
+ contentLength?: number;
createdAt: number;
/** Lexical editor JSON state for rich text rendering */
editorData?: Record<string, any> | null;
@@ -246,6 +253,14 @@ export interface UIChatMessage {
* parent message id
*/
parentId?: string;
+ /**
+ * The UI read path reduced this tool message's `content` / `pluginState` to
+ * a view model, and which surface has to fetch the stored payload back:
+ * `'detail'` when the inline card is complete on its own (a detail portal or
+ * the raw viewer fetches), `'render'` when the card itself renders the body
+ * and must be hydrated as the row expands.
+ */
+ payloadOmitted?: 'detail' | 'render';
/**
* Performance metrics (tps, ttft, duration, latency)
* Aggregated from all children in group messages
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx
index cb510a2a359..752e31a56f8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx
@@ -12,6 +12,8 @@ import {
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useToolResultPayload } from '@/hooks/useToolResultPayload';
+
interface DebugProps {
apiName: string;
identifier: string;
@@ -19,13 +21,22 @@ interface DebugProps {
requestArgs?: string;
result?: { content: string | null; error?: any; state?: any };
toolCallId: string;
+ /** Tool message this panel inspects; lets it pull back a projected payload. */
+ toolMessageId?: string;
type?: string;
}
const Debug = memo<DebugProps>(
- ({ result, requestArgs, toolCallId, apiName, identifier, type, intervention }) => {
+ ({ result, requestArgs, toolCallId, apiName, identifier, type, intervention, toolMessageId }) => {
const { t } = useTranslation('plugin');
+ // This panel IS the raw viewer, and it only mounts once the user toggles it
+ // on β€” so whenever the read path projected this tool, fetch what it dropped.
+ const projected = useToolResultPayload(toolMessageId, !!toolMessageId);
+ const rawResult = projected.payload
+ ? { ...result, content: projected.payload.content, state: projected.payload.pluginState }
+ : result;
+
const params = useMemo(() => {
try {
return JSON.stringify(JSON.parse(requestArgs || ''), null, 2);
@@ -45,7 +56,7 @@ const Debug = memo<DebugProps>(
}, [requestArgs, toolCallId, apiName, identifier, type]);
const isJsonResult =
- result?.content?.trim().startsWith('{') || result?.content?.trim().startsWith('[');
+ rawResult?.content?.trim().startsWith('{') || rawResult?.content?.trim().startsWith('[');
const items: TabsProps['items'] = useMemo(
() => [
@@ -70,7 +81,9 @@ const Debug = memo<DebugProps>(
style={{ background: 'transparent', borderRadius: 0, height: '100%' }}
variant={'filled'}
>
- {isJsonResult ? JSON.stringify(result?.content, null, 2) : result?.content || ''}
+ {isJsonResult
+ ? JSON.stringify(rawResult?.content, null, 2)
+ : rawResult?.content || ''}
</Highlighter>
),
icon: <Icon icon={SquareArrowDownIcon} />,
@@ -98,7 +111,7 @@ const Debug = memo<DebugProps>(
style={{ background: 'transparent', borderRadius: 0, height: '100%' }}
variant={'filled'}
>
- {JSON.stringify(result?.state, null, 2)}
+ {JSON.stringify(rawResult?.state, null, 2)}
</Highlighter>
),
icon: <Icon icon={BracesIcon} />,
@@ -142,9 +155,9 @@ const Debug = memo<DebugProps>(
functionCall,
isJsonResult,
params,
- result?.content,
+ rawResult?.content,
result?.error,
- result?.state,
+ rawResult?.state,
intervention,
t,
],
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx
index 8762b9f3edb..716d03775aa 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx
@@ -1,7 +1,12 @@
import { getBuiltinRender } from '@lobechat/builtin-tools/renders';
import { type ChatPluginPayload } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { Skeleton } from '@lobehub/ui/base-ui';
import { memo } from 'react';
+import { useToolResultPayload } from '@/hooks/useToolResultPayload';
+
+import { dataSelectors, useConversationStore } from '../../../../../store';
import CustomRender from './CustomRender';
import { FallbackArgumentRender } from './FallbacktArgumentRender';
@@ -18,13 +23,34 @@ const ToolRender = memo<ToolRenderProps>(
({ showCustomToolRender, content, messageId, plugin, pluginState, toolCallId }) => {
const hasCustomRender = !!getBuiltinRender(plugin?.identifier, plugin?.apiName);
+ // Tools whose card renders the stored body β€” the read path projected it away
+ // and this component is where it comes back. Safe to fetch on mount: the
+ // whole detail only mounts when the row is expanded, so a conversation load
+ // asks for nothing.
+ const needsStoredPayload = useConversationStore(
+ (s) =>
+ !!messageId && dataSelectors.getDbMessageById(messageId)(s)?.payloadOmitted === 'render',
+ );
+ const { isLoading, payload } = useToolResultPayload(messageId, needsStoredPayload);
+
+ const resolvedContent = payload?.content ?? content;
+ const resolvedState = payload?.pluginState ?? pluginState;
+
+ if (needsStoredPayload && isLoading && !payload) {
+ return (
+ <Flexbox paddingBlock={8} width={'100%'}>
+ <Skeleton height={96} width={'100%'} />
+ </Flexbox>
+ );
+ }
+
if (hasCustomRender && showCustomToolRender) {
return (
<CustomRender
- content={content}
+ content={resolvedContent}
messageId={messageId}
plugin={plugin}
- pluginState={pluginState}
+ pluginState={resolvedState}
toolCallId={toolCallId}
/>
);
@@ -32,7 +58,7 @@ const ToolRender = memo<ToolRenderProps>(
return (
<FallbackArgumentRender
- content={content}
+ content={resolvedContent}
requestArgs={plugin?.arguments}
toolCallId={toolCallId}
/>
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
index 7f31bd2e5a6..f7c0826f613 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
@@ -15,7 +15,8 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
-import { LOADING_FLAT } from '@/const/message';
+
+import { hasToolResultBody } from '../toolResultBody';
interface StatusIndicatorProps {
intervention?: ToolIntervention;
@@ -40,7 +41,7 @@ const StatusIndicator = memo<StatusIndicatorProps>(
const { t } = useTranslation('chat');
const hasError = !!result?.error;
- const hasSuccessResult = !!result?.content && result.content !== LOADING_FLAT;
+ const hasSuccessResult = hasToolResultBody(result);
const hasResult = hasSuccessResult || hasError;
const isPending = intervention?.status === 'pending';
const isReject = intervention?.status === 'rejected';
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
index 89bb3ccfb45..7adbc883ed4 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
@@ -1,6 +1,5 @@
import { getBuiltinRender } from '@lobechat/builtin-tools/renders';
import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';
-import { LOADING_FLAT } from '@lobechat/const';
import { Flexbox } from '@lobehub/ui';
import { Accordion, Skeleton } from '@lobehub/ui/base-ui';
import { Divider } from 'antd';
@@ -17,6 +16,7 @@ import { toolSelectors } from '@/store/tool/selectors';
import { dataSelectors, useConversationStore } from '../../../store';
import Actions from './Actions';
import Inspectors from './Inspector';
+import { hasToolResultBody } from './toolResultBody';
const Debug = dynamic(() => import('./Debug'), {
loading: () => <Skeleton height={300} width={'100%'} />,
@@ -92,8 +92,7 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =
// This tool's own result is the source of truth for completion. The
// message-level toolCalling flag stays true while sibling tools are still
// running, so without this guard a finished tool flips back into "loading".
- const hasFinishedResult =
- hasError || (!!result && result.content !== LOADING_FLAT && !!result.content);
+ const hasFinishedResult = hasError || hasToolResultBody(result);
const looksLikeWaitingForToolResult = !hasError && !isArgumentsStreaming && !hasFinishedResult;
const isToolCallingFallback = looksLikeWaitingForToolResult && isAssistantMessageBusy;
const isToolCalling = !hasFinishedResult && (isToolCallingFromOperation || isToolCallingFallback);
@@ -157,6 +156,7 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =
requestArgs={requestArgs}
result={result}
toolCallId={id}
+ toolMessageId={toolMessageId}
type={type}
/>
)}
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.ts
new file mode 100644
index 00000000000..bf3f4b12379
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.ts
@@ -0,0 +1,28 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import { describe, expect, it } from 'vitest';
+
+import { hasToolResultBody } from './toolResultBody';
+
+describe('hasToolResultBody', () => {
+ it('counts a stored body that the read path projected away', () => {
+ // The regression: a settled tool whose body was replaced by a view model.
+ // Reading `content` alone would call it unfinished and, while the assistant
+ // message is still busy, swap its card for the loading placeholder.
+ expect(hasToolResultBody({ content: '', contentLength: 36_000 })).toBe(true);
+ });
+
+ it('counts an ordinary unprojected body', () => {
+ expect(hasToolResultBody({ content: 'done' })).toBe(true);
+ });
+
+ it('does not count a tool that genuinely returned nothing', () => {
+ expect(hasToolResultBody({ content: '' })).toBe(false);
+ expect(hasToolResultBody({ content: '', contentLength: 0 })).toBe(false);
+ expect(hasToolResultBody(undefined)).toBe(false);
+ });
+
+ it('does not count the streaming placeholder', () => {
+ expect(hasToolResultBody({ content: LOADING_FLAT })).toBe(false);
+ expect(hasToolResultBody({ content: LOADING_FLAT, contentLength: 12 })).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.ts
new file mode 100644
index 00000000000..84adb47ca01
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.ts
@@ -0,0 +1,17 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import type { ChatToolResult } from '@lobechat/types';
+
+/**
+ * Did this tool actually produce a result body?
+ *
+ * Shared by every "is this tool finished" test, because the honest answer is no
+ * longer `!!result.content`: the read path can replace a settled tool's body
+ * with a render-facing view model, leaving `content` empty and the real length
+ * in `contentLength`. Reading the body alone flips a finished tool back into
+ * its loading placeholder for as long as the assistant message is busy.
+ */
+export const hasToolResultBody = (result?: Pick<ChatToolResult, 'content' | 'contentLength'>) => {
+ if (!result || result.content === LOADING_FLAT) return false;
+
+ return !!result.content || (result.contentLength ?? 0) > 0;
+};
diff --git a/src/features/Conversation/Messages/Tool/Tool/index.tsx b/src/features/Conversation/Messages/Tool/Tool/index.tsx
index 43bc7bb2698..5faebdb7bc6 100644
--- a/src/features/Conversation/Messages/Tool/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Tool/Tool/index.tsx
@@ -62,6 +62,7 @@ const Tool = memo<InspectorProps>(
const result = toolMessage
? {
content: toolMessage.content,
+ contentLength: toolMessage.contentLength,
error: toolMessage.error,
id: toolCallId,
state: toolMessage.pluginState,
@@ -101,6 +102,7 @@ const Tool = memo<InspectorProps>(
requestArgs={requestArgs}
result={result}
toolCallId={toolCallId}
+ toolMessageId={toolMessage?.id}
type={type}
/>
)}
diff --git a/src/hooks/useToolResultPayload.ts b/src/hooks/useToolResultPayload.ts
new file mode 100644
index 00000000000..aa571962cc1
--- /dev/null
+++ b/src/hooks/useToolResultPayload.ts
@@ -0,0 +1,21 @@
+import useSWR from 'swr';
+
+import { messageService } from '@/services/message';
+
+/**
+ * Fetch the stored tool payload for a message the read path projected.
+ *
+ * Gate `enabled` on a real user action β€” opening the detail portal, unfolding a
+ * raw viewer. Tying it to render instead would pull every omitted payload back
+ * down as soon as a conversation loads, which is the exact cost the projection
+ * exists to avoid.
+ */
+export const useToolResultPayload = (messageId: string | undefined, enabled: boolean) => {
+ const { data, isLoading } = useSWR(
+ enabled && messageId ? ['toolResultPayload', messageId] : null,
+ ([, id]: [string, string]) => messageService.getToolResultPayload(id),
+ { revalidateOnFocus: false },
+ );
+
+ return { isLoading: enabled && isLoading, payload: data };
+};
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 985ea176823..0ec677b0582 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -175,6 +175,15 @@ export class MessageService {
return data as unknown as UIChatMessage[];
};
+ /**
+ * Stored tool payload for a message whose projected copy dropped it
+ * (`UIChatMessage.payloadOmitted`). Called by detail surfaces on open, never
+ * as part of loading a conversation.
+ */
+ getToolResultPayload = async (messageId: string) => {
+ return lambdaClient.message.getToolResultPayload.query({ messageId });
+ };
+
diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {
return lambdaClient.message.diagnoseTopic.query(params);
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
index cad335912da..36dae60f5fb 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
@@ -1066,6 +1066,100 @@ describe('createGatewayEventHandler', () => {
expect(lastCall?.[0]).not.toEqual(staleSnapshot);
});
+ it('applies an in-sequence protocol-v2 message patch without a DB refetch', async () => {
+ const getMessages = vi.spyOn(messageService, 'getMessages');
+ const key = messageMapKey(context);
+ const current = [
+ { content: 'question', id: 'user-1', role: 'user' },
+ { content: 'draft', id: 'asst-1', role: 'assistant' },
+ ] as unknown as UIChatMessage[];
+ const settled = { ...current[1], content: 'settled' };
+ const tool = { content: 'result', id: 'tool-1', role: 'tool' } as UIChatMessage;
+ const store = createStore({ [key]: current });
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'asst-1',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('message_patch', {
+ deletes: [],
+ revision: 1,
+ upserts: [
+ { afterId: 'user-1', message: settled },
+ { afterId: 'asst-1', message: tool },
+ ],
+ }),
+ );
+
+ expect(store.replaceMessages).toHaveBeenCalledWith([current[0], settled, tool], {
+ action: 'gateway/message_patch',
+ context,
+ preserveWorks: true,
+ });
+ expect(getMessages).not.toHaveBeenCalled();
+ });
+
+ it('falls back to one DB reconciliation when a message patch revision is missing', async () => {
+ const recovered = [
+ { content: 'canonical', id: 'asst-1', role: 'assistant' },
+ ] as unknown as UIChatMessage[];
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue(recovered);
+ const store = createStore();
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'asst-1',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(makeEvent('message_patch', { deletes: [], revision: 2, upserts: [] }));
+ await flush();
+
+ expect(getMessages).toHaveBeenCalledWith({ ...context, skipWorks: true });
+ expect(store.replaceMessages).toHaveBeenCalledWith(recovered, {
+ context,
+ preserveWorks: true,
+ });
+ });
+
+ it('settles a patched terminal event without downloading the full topic', async () => {
+ const getMessages = vi.spyOn(messageService, 'getMessages');
+ const key = messageMapKey(context);
+ const current = [
+ { content: 'draft', id: 'asst-1', role: 'assistant' },
+ ] as unknown as UIChatMessage[];
+ const settled = { ...current[0], content: 'settled' };
+ const store = createStore({ [key]: current });
+ vi.mocked(store.replaceMessages).mockImplementation((messages) => {
+ store.dbMessagesMap[key] = messages;
+ });
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'asst-1',
+ context,
+ operationId: 'op-1',
+ });
+
+ handler(
+ makeEvent('message_patch', {
+ deletes: [],
+ revision: 1,
+ upserts: [{ afterId: null, message: settled }],
+ }),
+ );
+ handler(
+ makeEvent('agent_runtime_end', {
+ messagePatchMode: true,
+ messageRevision: 1,
+ reason: 'completed',
+ }),
+ );
+ await flush();
+
+ expect(store.dbMessagesMap[key]).toEqual([settled]);
+ expect(getMessages).not.toHaveBeenCalled();
+ });
+
// Hetero / old-server stream_start has no assistantMessage.id, so it
// resolves the next bubble from the fetch return value. If that fetch
// started before step_start and we still returned the stale list, chunks
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 98e5d0433b0..919ab1e6eb3 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -2,6 +2,7 @@ import type {
AgentInterventionRequestData,
AgentInterventionResponseData,
AgentStreamEvent,
+ MessagePatchData,
StepCompleteData,
StreamChunkData,
StreamStartData,
@@ -33,6 +34,8 @@ import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { applyMessagePatch } from './messagePatch';
+
// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream
// cancel and a deferred-tool park. These must NOT mark the topic unread, and
// must take the non-success branch in `onSessionComplete` so the run clears
@@ -466,6 +469,7 @@ export const createGatewayEventHandler = (
// NOT reset on stream boundaries β€” a seq ≀ these is a redelivered duplicate.
let lastTextSnapshotSeq = 0;
let lastReasoningSnapshotSeq = 0;
+ let lastMessagePatchRevision = 0;
const latestToolStateByCallId = new Map<string, ToolStateChunkData & { operationId: string }>();
const toolStateBootstrapPromiseByCallId = new Map<string, Promise<void>>();
const lastAppliedToolStateSeqByCallId = new Map<string, number>();
@@ -1053,12 +1057,26 @@ export const createGatewayEventHandler = (
case 'step_start': {
const data = event.data as {
+ messageRevision?: number;
pendingToolsCalling?: unknown[];
phase?: string;
requiresApproval?: boolean;
uiMessages?: UIChatMessage[];
};
+ if (
+ typeof data?.messageRevision === 'number' &&
+ data.messageRevision !== lastMessagePatchRevision
+ ) {
+ enqueue(async () => {
+ const messages = await refreshMessagesFromDb({ skipWorks: true }).catch((error) => {
+ console.error(error);
+ return undefined;
+ });
+ if (messages) lastMessagePatchRevision = data.messageRevision!;
+ });
+ }
+
// The server's stepIndex is the authoritative step counter β€” mirror it
// onto the operation so step-based UI (OpStatusTray) stays correct
// even across page-refresh reconnects.
@@ -1090,6 +1108,32 @@ export const createGatewayEventHandler = (
break;
}
+ case 'message_patch': {
+ const patch = event.data as MessagePatchData;
+ if (patch.revision <= lastMessagePatchRevision) break;
+
+ const current = get().dbMessagesMap[messageMapKey(context)] ?? [];
+ const next =
+ patch.revision === lastMessagePatchRevision + 1
+ ? applyMessagePatch(current, patch)
+ : undefined;
+
+ if (next) {
+ applyPushedSnapshot(next, { action: 'gateway/message_patch', preserveWorks: true });
+ lastMessagePatchRevision = patch.revision;
+ hasStreamedContent = true;
+ } else {
+ enqueue(async () => {
+ const messages = await refreshMessagesFromDb({ skipWorks: true }).catch((error) => {
+ console.error(error);
+ return undefined;
+ });
+ if (messages) lastMessagePatchRevision = patch.revision;
+ });
+ }
+ break;
+ }
+
case 'tool_execute': {
// Fire-and-forget: the client-side tool may take a long time, and we
// must keep processing other events (stream_chunk, tool_end, etc.) on
@@ -1210,7 +1254,14 @@ export const createGatewayEventHandler = (
case 'agent_runtime_end': {
enqueue(async () => {
- const data = event.data as { reason?: string; uiMessages?: UIChatMessage[] } | undefined;
+ const data = event.data as
+ | {
+ messagePatchMode?: boolean;
+ messageRevision?: number;
+ reason?: string;
+ uiMessages?: UIChatMessage[];
+ }
+ | undefined;
void emitAgentSignal({
payload: {
@@ -1257,6 +1308,16 @@ export const createGatewayEventHandler = (
action: 'gateway/agent_runtime_end',
});
}
+ } else if (data?.messagePatchMode) {
+ if (
+ typeof data.messageRevision === 'number' &&
+ data.messageRevision !== lastMessagePatchRevision
+ ) {
+ terminalMessages = await refreshMessagesFromDb();
+ if (terminalMessages) lastMessagePatchRevision = data.messageRevision;
+ } else {
+ terminalMessages = get().dbMessagesMap[messageMapKey(context)] ?? [];
+ }
} else if (
(data?.reason === 'interrupted' || data?.reason === 'waiting_for_async_tool') &&
hasStreamedContent
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/messagePatch.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/messagePatch.test.ts
new file mode 100644
index 00000000000..9c851652f55
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/messagePatch.test.ts
@@ -0,0 +1,46 @@
+import type { MessagePatchData } from '@lobechat/agent-gateway-client';
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { applyMessagePatch } from './messagePatch';
+
+const message = (id: string, content = id): UIChatMessage =>
+ ({ content, createdAt: 1, id, role: 'assistant', updatedAt: 1 }) as UIChatMessage;
+
+describe('applyMessagePatch', () => {
+ it('updates, deletes, and inserts without replacing untouched history', () => {
+ const patch: MessagePatchData = {
+ deletes: ['b'],
+ revision: 2,
+ upserts: [
+ { afterId: null, message: message('a', 'updated') },
+ { afterId: 'a', message: message('c') },
+ ],
+ };
+
+ expect(applyMessagePatch([message('a'), message('b')], patch)).toEqual([
+ message('a', 'updated'),
+ message('c'),
+ ]);
+ });
+
+ it('fails closed when an insertion anchor is missing', () => {
+ const patch: MessagePatchData = {
+ deletes: [],
+ revision: 1,
+ upserts: [{ afterId: 'missing', message: message('new') }],
+ };
+
+ expect(applyMessagePatch([], patch)).toBeUndefined();
+ });
+
+ it('accepts an already-present row without requiring its anchor', () => {
+ const patch: MessagePatchData = {
+ deletes: [],
+ revision: 1,
+ upserts: [{ afterId: 'missing', message: message('a', 'settled') }],
+ };
+
+ expect(applyMessagePatch([message('a')], patch)).toEqual([message('a', 'settled')]);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/messagePatch.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/messagePatch.ts
new file mode 100644
index 00000000000..cf2b683c9c4
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/messagePatch.ts
@@ -0,0 +1,34 @@
+import type { MessagePatchData } from '@lobechat/agent-gateway-client';
+import type { UIChatMessage } from '@lobechat/types';
+
+/**
+ * Apply one canonical protocol-v2 patch to the raw conversation list.
+ * Returns undefined when an insertion anchor is missing; callers then perform
+ * the existing full DB reconciliation instead of guessing an order.
+ */
+export const applyMessagePatch = (
+ messages: UIChatMessage[],
+ patch: MessagePatchData,
+): UIChatMessage[] | undefined => {
+ const removed = new Set(patch.deletes);
+ const next = messages.filter((message) => !removed.has(message.id));
+
+ for (const { afterId, message } of patch.upserts) {
+ const existingIndex = next.findIndex((item) => item.id === message.id);
+ if (existingIndex >= 0) {
+ next[existingIndex] = message;
+ continue;
+ }
+
+ if (afterId === null) {
+ next.unshift(message);
+ continue;
+ }
+
+ const anchorIndex = next.findIndex((item) => item.id === afterId);
+ if (anchorIndex < 0) return undefined;
+ next.splice(anchorIndex + 1, 0, message);
+ }
+
+ return next;
+};