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.

♻️ refactor(agent): decide protocol-v2 payloads from the client, not a preference (#19817)

Arvin Xu17a45151a9f0
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 638223bbb1e..dbe3237d4c1 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -41,7 +41,7 @@ const hasEnteredStreamEndState = (
export interface AgentRuntimeCoordinatorOptions {
/** Whether terminal reconciliation is delivered by protocol-v2 message patches. */
- messagePatchModeResolver?: (state: AgentState) => Promise<boolean>;
+ messagePatchModeResolver?: (state: AgentState) => boolean;
/**
* Custom state manager implementation
* Defaults to automatic selection based on Redis availability
@@ -77,7 +77,7 @@ export interface AgentRuntimeCoordinatorOptions {
* Supports dependency injection, allowing custom implementations to be passed in
*/
export class AgentRuntimeCoordinator {
- private messagePatchModeResolver?: (state: AgentState) => Promise<boolean>;
+ private messagePatchModeResolver?: (state: AgentState) => boolean;
private stateManager: IAgentStateManager;
private streamEventManager: IStreamEventManager;
private uiMessagesResolver?: (state: AgentState) => Promise<UIChatMessage[] | undefined>;
@@ -155,10 +155,10 @@ export class AgentRuntimeCoordinator {
}
}
- private async resolveMessagePatchMode(state: AgentState): Promise<boolean> {
+ private resolveMessagePatchMode(state: AgentState): boolean {
if (!this.messagePatchModeResolver) return false;
try {
- return await this.messagePatchModeResolver(state);
+ return this.messagePatchModeResolver(state);
} catch (error) {
console.error('Failed to resolve message patch mode:', error);
return false;
@@ -197,7 +197,7 @@ 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);
+ const messagePatchMode = this.resolveMessagePatchMode(state);
if (!hasVisibleOutputEndPublished(state)) {
await this.publishVisibleOutputEnd(operationId, state, stepIndex);
}
@@ -235,7 +235,7 @@ 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);
+ const messagePatchMode = this.resolveMessagePatchMode(stepResult.newState);
if (!hasVisibleOutputEndPublished(stepResult.newState)) {
await this.publishVisibleOutputEnd(operationId, stepResult.newState, stepIndex);
}
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index 51f714fb577..8afa8d7ce0b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -674,7 +674,7 @@ describe('AgentRuntimeCoordinator', () => {
it('marks a protocol-v2 patched terminal event with its expected revision', async () => {
const coordinatorWithResolver = new AgentRuntimeCoordinator({
- messagePatchModeResolver: vi.fn().mockResolvedValue(true),
+ messagePatchModeResolver: vi.fn().mockReturnValue(true),
stateManager: mockStateManager,
streamEventManager: mockStreamManager,
uiMessagesResolver: vi.fn().mockResolvedValue(undefined),
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index a54dbda1062..3a7da75bf71 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1040,6 +1040,13 @@ const ExecAgentSchema = z
* ignores features it does not know rather than rejecting the run.
*/
streamFeatures: z.array(z.string()).optional(),
+ /**
+ * Wire protocol the calling client speaks. `2` declares it reconciles its
+ * message list from `message_patch` revisions, so the run may stop pushing
+ * whole `uiMessages` snapshots. Absent β‡’ 1 (an older bundle, the CLI, or a
+ * server-initiated run), which keeps the pushed snapshots.
+ */
+ clientProtocol: z.union([z.literal(1), z.literal(2)]).optional(),
/** The agent ID to run (either agentId or slug is required) */
agentId: z.string().optional(),
/** Application context for message storage */
@@ -2450,6 +2457,7 @@ export const aiAgentRouter = router({
operations: input.clientOperations ?? [],
replacesOperationId: input.replacesOperationId,
},
+ clientProtocol: input.clientProtocol,
includeFinalState: input.includeFinalState,
// This procedure serves the composer (`aiAgentService.execAgentTask`).
// The client already queues follow-ups behind a live run and shows the
@@ -2608,6 +2616,7 @@ export const aiAgentRouter = router({
});
const result = await ctx.aiAgentService.execAgent({
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(task.streamFeatures),
+ clientProtocol: task.clientProtocol,
includeFinalState: task.includeFinalState,
agentId,
appContext,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 50dfa9b2eaf..60bfda7ba57 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -1,3 +1,4 @@
+import { projectToolViewModels } from '@lobechat/tool-view-model';
import {
CreateNewMessageParamsSchema,
UpdateMessageParamsSchema,
@@ -453,6 +454,12 @@ export const messageRouter = router({
// a `file` summary that would crash their works UI. New clients set it.
includeFileWorks: z.boolean().optional(),
pageSize: z.number().optional(),
+ /**
+ * Hand back render-facing tool view models instead of the stored
+ * payloads (`@lobechat/tool-view-model`). Opt-in per read: see the
+ * note where it is applied.
+ */
+ projectToolPayloads: z.boolean().optional(),
sessionId: z.string().nullish(),
// Mid-stream refetches skip the Work-summary assembly β€” see
// `QueryMessageParams.skipWorks`.
@@ -525,10 +532,12 @@ export const messageRouter = router({
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);
+ // Only the caller knows whether this list is going to be rendered or fed
+ // to a model: a run that executes in the browser assembles its context
+ // from the very list this read returns, and a projected tool result would
+ // silently disappear from it. Absent β‡’ whole payloads, which is never the
+ // answer that loses data.
+ return input.projectToolPayloads ? projectToolViewModels(messages) : messages;
}),
/**
@@ -555,6 +564,8 @@ export const messageRouter = router({
// Same opt-in as `getMessages`: only clients that ship the `file` work
// descriptor ask for `file` work summaries.
includeFileWorks: z.boolean().optional(),
+ /** Same opt-in as `getMessages`: render-facing tool view models. */
+ projectToolPayloads: z.boolean().optional(),
roundLimit: z.number().int().positive().max(MAX_CURSOR_ROUND_LIMIT).optional(),
sessionId: z.string().nullish(),
skipWorks: z.boolean().optional(),
@@ -565,7 +576,7 @@ export const messageRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- const { topicShareId, topicId, ...queryParams } = input;
+ const { projectToolPayloads, topicShareId, topicId, ...queryParams } = input;
// Public access via topicShareId
if (topicShareId) {
@@ -620,14 +631,11 @@ export const messageRouter = router({
},
);
- // Reads through its own `MessageModel`, so apply the tool view-model step
- // explicitly β€” same as `getMessages`.
- return {
- ...page,
- messages: await new MessageService(ctx.serverDB, ctx.userId, wsId).projectToolPayloads(
- page.messages,
- ),
- };
+ // Same rule as `getMessages`: only the caller knows whether this page is
+ // rendered or fed to a model, so projection is opt-in per read.
+ return projectToolPayloads
+ ? { ...page, messages: projectToolViewModels(page.messages) }
+ : page;
}),
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 0252875f77d..8057d6adcca 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -2829,12 +2829,9 @@ describe('AgentRuntimeService', () => {
expect(result).toEqual(stubMessages);
});
- it.each([
- { skipToolProjection: false, visitorUserId: undefined },
- { skipToolProjection: true, visitorUserId: 'visitor_1' },
- ])(
- 'includes visitor rows with skipToolProjection=$skipToolProjection',
- async ({ skipToolProjection, visitorUserId }) => {
+ it.each([undefined, 'visitor_1'])(
+ 'includes visitor rows (visitor=%s)',
+ async (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
@@ -2848,10 +2845,10 @@ describe('AgentRuntimeService', () => {
principal: visitorUserId ? { actor: { shareVisitor: { visitorUserId } } } : undefined,
} as any);
- expect(queryMessages).toHaveBeenCalledWith(expect.anything(), {
- allowShareVisitor: true,
- skipToolProjection,
- });
+ // The pushed snapshot always carries whole tool payloads now: it only
+ // reaches a client that did not ask for protocol 2, which has no way to
+ // fetch an omitted payload back.
+ expect(queryMessages).toHaveBeenCalledWith(expect.anything(), { allowShareVisitor: true });
},
);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 1ef05b0fdd2..3023c95921a 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -54,7 +54,6 @@ 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 { isDeviceCapablePlan, isDeviceLockedPlan } from '@/helpers/executionTarget';
@@ -94,7 +93,7 @@ import { stepChangedCredentials } from './credentialFacts';
import { logToolCallPc } from './formalObservation';
import { type AgentHook, hookDispatcher } from './hooks';
import { HumanInterventionHandler } from './HumanInterventionHandler';
-import { buildMessagePatch } from './messagePatch';
+import { buildProjectedMessagePatch } from './messagePatch';
import { OperationTraceRecorder } from './OperationTraceRecorder';
import { createDefaultSnapshotStore } from './snapshotStore';
import { buildStepPresentation, formatTokenCount } from './stepPresentation';
@@ -477,8 +476,6 @@ 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
@@ -533,8 +530,6 @@ 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;
@@ -565,12 +560,6 @@ 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.
// Gateway pushes are deferred off the step path: every point where this
// invocation can stop or hand the run over calls `drainPushes` first.
@@ -586,7 +575,7 @@ export class AgentRuntimeService {
// the client can use the pushed payload directly instead of refetching
// from DB. Falls back gracefully when topicId isn't set.
uiMessagesResolver: async (state) =>
- (await this.usesGatewayMessagePatch(state)) ? undefined : this.queryUiMessages(state),
+ this.usesGatewayMessagePatch(state) ? undefined : this.queryUiMessages(state),
});
this.queueService =
options?.queueService === null ? null : (options?.queueService ?? new QueueService());
@@ -1254,6 +1243,7 @@ export class AgentRuntimeService {
// What the host needs to deliver and retry the run. Hooks are stamped
// right after creation once the dispatcher has serialized them.
host: {
+ ...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),
...(params.includeFinalState === true && { includeFinalState: true }),
queue: { retries: queueRetries, retryDelay: queueRetryDelay },
},
@@ -1552,15 +1542,7 @@ export class AgentRuntimeService {
// terminal Source of Truth β€” wiping the conversation the run just
// produced. Visitor-facing redaction of the pushed snapshot happens in
// `GatewayStreamNotifier`.
- //
- // 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,
- },
+ { allowShareVisitor: true },
);
} catch (error) {
// Stream events must never fail the step. If the DB hiccups, fall back
@@ -1571,13 +1553,21 @@ export class AgentRuntimeService {
}
/** Native harness + Gateway mux is the only producer of message patches. */
- private async usesGatewayMessagePatch(agentState: AgentState): Promise<boolean> {
+ /**
+ * Whether this run reconciles the client's message list through
+ * `message_patch` revisions instead of pushing whole `uiMessages` snapshots.
+ *
+ * Decided by the capability the starting client declared when the operation
+ * was created (`host.clientProtocol`), NOT by a user preference: the run is
+ * delivered to whatever bundle that client is, and a desktop build older than
+ * `message_patch` would drop every mid-run reconciliation it was sent.
+ *
+ * A share visitor is always excluded β€” the visitor surface has no
+ * owner-scoped read to reconcile against.
+ */
+ private usesGatewayMessagePatch(agentState: AgentState): 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;
+ return agentState.host?.clientProtocol === 2;
}
/**
@@ -1914,7 +1904,7 @@ export class AgentRuntimeService {
};
}
- const gatewayMessagePatchEnabled = await this.usesGatewayMessagePatch(agentState);
+ const gatewayMessagePatchEnabled = this.usesGatewayMessagePatch(agentState);
const { uiMessages: stepStartUiMessages, messages: stepEntryMessages } =
await this.queryStepEntryMessages(agentState);
await this.streamManager.publishStreamEvent(operationId, {
@@ -2424,8 +2414,16 @@ export class AgentRuntimeService {
skipWorks: shouldContinue,
});
if (settledUiMessages) {
+ // Projected: this branch runs only for a client that asked for
+ // protocol 2, which renders tool view models and can fetch a stored
+ // payload back. The model-facing lists are read elsewhere, straight
+ // off `MessageModel`, and stay whole.
await this.streamManager.publishStreamEvent(operationId, {
- data: buildMessagePatch(stepStartUiMessages, settledUiMessages, stepIndex + 1),
+ data: buildProjectedMessagePatch(
+ stepStartUiMessages,
+ settledUiMessages,
+ stepIndex + 1,
+ ),
stepIndex,
type: 'message_patch',
});
@@ -4208,10 +4206,7 @@ export class AgentRuntimeService {
const [uiResult] = await Promise.all([
(async () => {
try {
- return await this.messageService.prepareUiMessages(
- messages,
- !!state.principal?.actor?.shareVisitor?.visitorUserId,
- );
+ return await this.messageService.prepareUiMessages(messages);
} catch (error) {
console.error('[queryStepEntryMessages] Failed to prepare UI messages: %O', error);
return undefined;
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index d6d5cd0e0d5..1062aeb32d5 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -1759,16 +1759,14 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =
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,
- });
+ it('sends only the expected revision when the client declared protocol 2', async () => {
+ const service = new AgentRuntimeService({} as any, 'user-1', { 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({
+ host: { clientProtocol: 2 },
lastModified: new Date().toISOString(),
origin: { agentId: 'agt_1', topicId: 'tpc_1' },
status: 'done',
@@ -1790,6 +1788,40 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =
);
expect(stepStartCall[1].data).toEqual({ messageRevision: 5 });
});
+
+ it('still pushes the whole snapshot to a client that declared nothing', async () => {
+ const service = new AgentRuntimeService({} as any, 'user-1', { 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({
+ // An older desktop bundle: it only learns the settled list from what the
+ // server pushes, so a revision alone would leave it rendering stale rows.
+ host: {},
+ 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 = {
+ prepareUiMessages: vi.fn().mockResolvedValue([{ id: 'large-history', role: 'user' }]),
+ };
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-legacy',
+ stepIndex: 5,
+ });
+
+ const stepStartCall = streamManager.publishStreamEvent.mock.calls.find(
+ ([, evt]: any) => evt?.type === 'step_start',
+ );
+ expect(stepStartCall[1].data).toEqual({
+ uiMessages: [{ id: 'large-history', role: 'user' }],
+ });
+ });
});
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
index c71efecbc50..aa57f4d542f 100644
--- a/apps/server/src/services/agentRuntime/messagePatch.test.ts
+++ b/apps/server/src/services/agentRuntime/messagePatch.test.ts
@@ -1,7 +1,7 @@
import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { buildMessagePatch } from './messagePatch';
+import { buildMessagePatch, buildProjectedMessagePatch } from './messagePatch';
const message = (id: string, content: string): UIChatMessage =>
({ content, createdAt: 1, id, role: 'assistant', updatedAt: 1 }) as UIChatMessage;
@@ -40,3 +40,43 @@ describe('buildMessagePatch', () => {
]);
});
});
+
+describe('buildProjectedMessagePatch', () => {
+ const toolRow = (id: string, content: string): UIChatMessage =>
+ ({
+ content,
+ createdAt: 1,
+ id,
+ plugin: { apiName: 'crawlSinglePage', arguments: '{}', identifier: 'lobe-web-browsing' },
+ pluginState: { results: [] },
+ role: 'tool',
+ updatedAt: 1,
+ }) as UIChatMessage;
+
+ it('ships the view model, not the stored tool body', () => {
+ const { upserts } = buildProjectedMessagePatch(
+ [],
+ [toolRow('t1', 'THE WHOLE CRAWLED PAGE')],
+ 1,
+ );
+
+ expect(upserts).toHaveLength(1);
+ expect(upserts[0].message.content).not.toContain('THE WHOLE CRAWLED PAGE');
+ expect(upserts[0].message.payloadOmitted).toBeDefined();
+ // The row still reads as "returned something" for the status icon.
+ expect(upserts[0].message.contentLength).toBe('THE WHOLE CRAWLED PAGE'.length);
+ });
+
+ it('does not resend a row whose only change is projected away', () => {
+ // Both bodies collapse to the same view model, so the diff must compare the
+ // projected forms β€” otherwise every step reships a settled tool row.
+ const patch = buildProjectedMessagePatch(
+ [toolRow('t1', 'first body')],
+ [toolRow('t1', 'first body')],
+ 2,
+ );
+
+ expect(patch.upserts).toEqual([]);
+ expect(patch.deletes).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/messagePatch.ts b/apps/server/src/services/agentRuntime/messagePatch.ts
index ca955d2b6f5..25f53d51116 100644
--- a/apps/server/src/services/agentRuntime/messagePatch.ts
+++ b/apps/server/src/services/agentRuntime/messagePatch.ts
@@ -1,4 +1,5 @@
import type { MessagePatchData } from '@lobechat/agent-gateway-client';
+import { projectToolViewModels } from '@lobechat/tool-view-model';
import type { UIChatMessage } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
@@ -32,3 +33,22 @@ export const buildMessagePatch = (
}),
};
};
+
+/**
+ * The wire form of {@link buildMessagePatch}: both sides reduced to tool view
+ * models before diffing.
+ *
+ * A patch only ever goes to a client that asked for protocol 2, and that client
+ * reads its conversation through the projected `message.getMessages` too β€” so an
+ * unprojected upsert would both put the bodies the projection exists to keep off
+ * the socket back on it, and replace the client's projected cache copy with a
+ * shape the rest of its list does not have. Projecting AFTER the diff would not
+ * do: `isEqual` has to compare like for like, or a row whose only change was
+ * projected away still ships.
+ */
+export const buildProjectedMessagePatch = (
+ before: UIChatMessage[],
+ after: UIChatMessage[],
+ revision: number,
+): MessagePatchData =>
+ buildMessagePatch(projectToolViewModels(before), projectToolViewModels(after), revision);
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 18fff93f10b..14da1e82729 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -499,6 +499,11 @@ export interface OperationCreationParams {
botContext?: ChatTopicBotContext;
/** Bot platform context for injecting platform capabilities (e.g. markdown support) */
botPlatformContext?: BotPlatformContext;
+ /**
+ * Wire protocol the client that started this run speaks; `2` lets the run
+ * deliver message revisions instead of whole `uiMessages` snapshots. Absent β‡’ 1.
+ */
+ clientProtocol?: 1 | 2;
/**
* Borrowed-connector attribution, resolved once during tool discovery. Run
* context for the context engine to inject β€” see `expertise`.
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index eb71ebe1533..75ccae0b59f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1544,6 +1544,7 @@ export class AiAgentService {
queueRetryDelay,
signal,
stream,
+ clientProtocol: params.clientProtocol,
includeFinalState: params.includeFinalState,
topicStartOwnerOperationId: params.topicStartOwnerOperationId,
updateAbortedAssistantMessage,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index e7356673e1d..ce499e17988 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -34,6 +34,8 @@ export interface StartOperationInput {
botContext?: InternalExecAgentParams['botContext'];
botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
clientIp?: string;
+ /** Wire protocol the calling client declared; `2` opts the run into message_patch delivery. */
+ clientProtocol?: 1 | 2;
/** Tri-state disabled plugin identifiers, kept on the world slot for the context rules. */
disabledPluginIds?: string[];
discordContext?: any;
@@ -159,6 +161,7 @@ export const startOperation = async (
: undefined);
const result = await deps.agentRuntimeService.createOperation({
acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,
+ clientProtocol: input.clientProtocol,
includeFinalState: input.includeFinalState,
activeDeviceId: discovery.activeDeviceId,
activeDeviceScope: discovery.activeDeviceScope,
diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.ts
index b4ffd76cb48..dcc0ab79f67 100644
--- a/apps/server/src/services/message/__tests__/index.test.ts
+++ b/apps/server/src/services/message/__tests__/index.test.ts
@@ -4,13 +4,11 @@ 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
@@ -26,7 +24,6 @@ describe('MessageService', () => {
let mockDB: LobeChatDatabase;
let mockMessageModel: MessageModel;
let mockFileService: FileService;
- let mockUserModel: UserModel;
const userId = 'test-user-id';
beforeEach(() => {
@@ -50,11 +47,6 @@ 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;
@@ -62,58 +54,55 @@ describe('MessageService', () => {
vi.mocked(FileService).mockImplementation(function () {
return mockFileService;
});
- vi.mocked(UserModel).mockImplementation(function () {
- return mockUserModel;
- });
messageService = new MessageService(mockDB, userId);
});
describe('prepareUiMessages', () => {
- it.each([false, true])(
- 'derives nested UI views without changing raw model data (visitor=%s)',
- async (visitor) => {
- mockFileService.getFileAccessUrl = vi.fn(async (file) => `/proxy/${file.id}`);
- const tool = {
- content: 'FULL TOOL RESULT',
- id: 'tool',
- role: 'tool',
- plugin: { apiName: 'crawlSinglePage', arguments: '{}', identifier: 'lobe-web-browsing' },
- pluginState: { results: [] },
- imageList: [{ id: 'image', url: 'raw/image', width: 42 }],
- audioList: [{ id: 'audio', url: 'raw/audio', durationMs: 123 }],
- videoList: [{ id: 'video', url: 'raw/video' }],
- fileList: [{ id: 'hidden', inaccessible: true, url: '' }],
- };
- const raw = [
- {
- id: 'group',
- role: 'assistant',
- columns: [[tool]],
- members: [tool],
- compressedMessages: [tool],
- },
- ] as any;
- const before = structuredClone(raw);
- const [ui] = await messageService.prepareUiMessages(raw, visitor);
- for (const nested of [ui.columns![0][0], ui.members![0], ui.compressedMessages![0]]) {
- expect(nested.content).toBe(visitor ? 'FULL TOOL RESULT' : '');
- expect(nested.imageList![0]).toEqual({ id: 'image', url: '/proxy/image', width: 42 });
- expect(nested.audioList![0]).toEqual({
- id: 'audio',
- url: '/proxy/audio',
- durationMs: 123,
- });
- expect(nested.videoList![0].url).toBe('/proxy/video');
- expect(nested.fileList![0].url).toBe('');
- }
- expect(raw).toEqual(before);
- expect(mockFileService.getFileAccessUrl).not.toHaveBeenCalledWith(
- expect.objectContaining({ id: 'hidden' }),
- );
- expect(mockMessageModel.query).not.toHaveBeenCalled();
- },
- );
+ it('derives nested UI views without changing raw model data', async () => {
+ mockFileService.getFileAccessUrl = vi.fn(async (file) => `/proxy/${file.id}`);
+ const tool = {
+ content: 'FULL TOOL RESULT',
+ id: 'tool',
+ role: 'tool',
+ plugin: { apiName: 'crawlSinglePage', arguments: '{}', identifier: 'lobe-web-browsing' },
+ pluginState: { results: [] },
+ imageList: [{ id: 'image', url: 'raw/image', width: 42 }],
+ audioList: [{ id: 'audio', url: 'raw/audio', durationMs: 123 }],
+ videoList: [{ id: 'video', url: 'raw/video' }],
+ fileList: [{ id: 'hidden', inaccessible: true, url: '' }],
+ };
+ const raw = [
+ {
+ id: 'group',
+ role: 'assistant',
+ columns: [[tool]],
+ members: [tool],
+ compressedMessages: [tool],
+ },
+ ] as any;
+ const before = structuredClone(raw);
+ const [ui] = await messageService.prepareUiMessages(raw);
+ for (const nested of [ui.columns![0][0], ui.members![0], ui.compressedMessages![0]]) {
+ // The push path never projects: a pushed snapshot only ever reaches a
+ // client that did not declare protocol 2, and it has no way to fetch
+ // an omitted payload back.
+ expect(nested.content).toBe('FULL TOOL RESULT');
+ expect(nested.imageList![0]).toEqual({ id: 'image', url: '/proxy/image', width: 42 });
+ expect(nested.audioList![0]).toEqual({
+ id: 'audio',
+ url: '/proxy/audio',
+ durationMs: 123,
+ });
+ expect(nested.videoList![0].url).toBe('/proxy/video');
+ expect(nested.fileList![0].url).toBe('');
+ }
+ expect(raw).toEqual(before);
+ expect(mockFileService.getFileAccessUrl).not.toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'hidden' }),
+ );
+ expect(mockMessageModel.query).not.toHaveBeenCalled();
+ });
});
describe('queryMessages', () => {
@@ -125,73 +114,27 @@ describe('MessageService', () => {
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);
+ it('hands back the stored payloads: only the caller knows if a model reads them', async () => {
vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
const result = await messageService.queryMessages({ topicId: 'topic-1' });
+ // The projection decision belongs to the read's caller (`message.getMessages`
+ // takes `projectToolPayloads`), because a browser-executed run assembles
+ // its LLM context from this very list.
+ expect(projectToolViewModels).not.toHaveBeenCalled();
expect(result).toEqual([toolRow]);
});
- it('keeps the whole payload when the preference read fails', async () => {
- vi.mocked(mockUserModel.getUserPreference).mockRejectedValue(new Error('db down'));
+ it('passes the share-visitor scope through to the model read', async () => {
vi.mocked(mockMessageModel.query).mockResolvedValue([toolRow]);
- const error = vi.spyOn(console, 'error').mockImplementation(() => {});
- const result = await messageService.queryMessages({ topicId: 'topic-1' });
+ await messageService.queryMessages({ topicId: 'topic-1' }, { allowShareVisitor: true });
- 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(
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
{ topicId: 'topic-1' },
- { allowShareVisitor: true, skipToolProjection: true },
+ expect.objectContaining({ allowShareVisitor: true }),
);
-
- expect(result).toEqual([toolRow]);
- });
-
- it('drops the body of a tool with no projector but keeps its state', async () => {
- const unprojected = {
- ...toolRow,
- plugin: { apiName: 'noSuchApi', arguments: '{}', identifier: 'some-mcp-server' },
- };
- vi.mocked(mockMessageModel.query).mockResolvedValue([unprojected]);
-
- const [projected] = await messageService.queryMessages({ topicId: 'topic-1' });
-
- expect(projected.content).toBe('');
- expect(projected.payloadOmitted).toBe('render');
- // Only a per-tool projector knows which state keys the collapsed row needs.
- expect(projected.pluginState).toEqual(unprojected.pluginState);
});
});
diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.ts
index 5831f1bb4bc..c8a822b6603 100644
--- a/apps/server/src/services/message/index.ts
+++ b/apps/server/src/services/message/index.ts
@@ -2,7 +2,6 @@ import { type LobeChatDatabase } from '@lobechat/database';
import { CompressionRepository } from '@lobechat/database';
import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';
import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';
-import { projectToolViewModels } from '@lobechat/tool-view-model';
import {
type CreateMessageParams,
type HeterogeneousToolStateSnapshot,
@@ -13,7 +12,6 @@ import {
import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
import { MessageModel } from '@/database/models/message';
-import { UserModel } from '@/database/models/user';
import { FileService } from '../file';
import { resolveMessageFileUrls } from './resolveMessageFileUrls';
@@ -108,43 +106,11 @@ 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;
}
/**
@@ -219,42 +185,25 @@ 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[]> {
- const messages = await this.messageModel.query(params, {
+ return this.messageModel.query(params, {
...this.getQueryOptions(),
...(options?.allowShareVisitor && { allowShareVisitor: true }),
});
-
- return options?.skipToolProjection ? messages : this.projectToolPayloads(messages);
- }
-
- /** Build the UI view from an already authorized, unprocessed DB snapshot. */
- async prepareUiMessages(messages: UIChatMessage[], skipToolProjection = false) {
- const resolved = await resolveMessageFileUrls(messages, (file) =>
- this.fileService.getFileAccessUrl(file),
- );
- return skipToolProjection ? resolved : this.projectToolPayloads(resolved);
}
/**
- * Reduce tool payloads to render-facing view models, for the mux cohort only.
+ * Build the UI view from an already authorized, unprocessed DB snapshot.
*
- * 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.
+ * Never projects: this is the PUSH path, and a pushed snapshot is only ever
+ * sent to a client that did not declare protocol 2 β€” an older bundle that
+ * cannot fetch an omitted payload back. Protocol-2 clients receive a
+ * `message_patch` revision instead and read through `message.getMessages`,
+ * which is where the projection decision is made.
*/
- async projectToolPayloads(messages: UIChatMessage[]): Promise<UIChatMessage[]> {
- return (await this.isToolProjectionEnabled()) ? projectToolViewModels(messages) : messages;
+ async prepareUiMessages(messages: UIChatMessage[]) {
+ return resolveMessageFileUrls(messages, (file) => this.fileService.getFileAccessUrl(file));
}
/**
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index bf8eb56e807..ead13cef11d 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -43,6 +43,7 @@ export type {
ResumeCompleteInfo,
ToolResultPayload,
} from './mux/types';
+export { CLIENT_PROTOCOL_VERSION } from './protocol';
export type {
AgentInterventionInteractionKind,
AgentInterventionProvider,
diff --git a/packages/agent-gateway-client/src/protocol.ts b/packages/agent-gateway-client/src/protocol.ts
new file mode 100644
index 00000000000..c1a91f840e9
--- /dev/null
+++ b/packages/agent-gateway-client/src/protocol.ts
@@ -0,0 +1,12 @@
+/**
+ * Highest wire protocol this bundle speaks to the Agent Gateway and to the run
+ * that feeds it. Sent when a run starts (`clientProtocol`) β€” subject to the
+ * rollout gate, see `canUseGatewayProtocolV2` β€” so the run may deliver message
+ * revisions (`message_patch`) instead of whole `uiMessages` snapshots. A client
+ * that sends nothing is treated as protocol 1 and keeps the snapshots.
+ *
+ * Bump this only together with the client-side handling of whatever the new
+ * version lets the server omit β€” a desktop build lags the server by weeks, and
+ * this constant is exactly what tells the two apart.
+ */
+export const CLIENT_PROTOCOL_VERSION = 2 as const;
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 2f6d74eb739..c19fc6818de 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -168,6 +168,20 @@ export interface AgentRunPlan {
* carried by the runtime without interpretation.
*/
export interface AgentRunHostEnvelope {
+ /**
+ * Wire protocol the client that started this run asked for. `2` means that
+ * client reconciles its message list from `message_patch` revisions, so the
+ * host may stop pushing whole `uiMessages` snapshots with the step and
+ * terminal events.
+ *
+ * Absent means `1`: an older bundle that only learns the settled list from
+ * what the server pushes, or a client the rollout has not reached.
+ * Deliberately declared by the client rather than derived from a preference
+ * or a transport check β€” a desktop build months behind the server reads the
+ * same events over the same socket, and guessing on its behalf is how it ends
+ * up rendering a run it cannot reconstruct.
+ */
+ clientProtocol?: 1 | 2;
/** Serialized lifecycle hook configs (webhook mode), so a queue worker can rebuild the dispatcher. */
hooks?: SerializedAgentHook[];
/** Opt into runtime state snapshots on step_complete events. Defaults to false. */
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index b422761fcf7..d18a67840f8 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -225,6 +225,12 @@ export interface ExecAgentParams {
* input β€” derived from the request context.
*/
clientIp?: string;
+ /**
+ * Wire protocol this client speaks; `2` declares that it reconciles its
+ * message list from `message_patch` revisions, so the server may stop
+ * pushing whole `uiMessages` snapshots to it. Absent β‡’ 1.
+ */
+ clientProtocol?: 1 | 2;
/** Explicit device ID to bind to the topic and activate for this run */
deviceId?: string;
/** Optional existing message IDs to include in context */
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 17118efd317..129583e41bc 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -218,16 +218,6 @@ export const UserLabSchema = z.object({
enableTaskVerify: z.boolean().optional(),
/** Capture a conversation turn as an eval test case (developer-facing). */
enableEvalCapture: z.boolean().optional(),
- /**
- * route every agent run in this tab over one shared gateway WebSocket
- * (protocol v2 mux) instead of one socket per run
- *
- * @deprecated The Labs toggle is gone; the transport is gated by the
- * `agent_gateway_mux` feature flag. Still read on the server to pick
- * message-patch delivery and read-path projection until those decisions move
- * to the client's declared protocol, which removes this field.
- */
- enableGatewayMux: z.boolean().optional(),
/**
* enable Goals: hand the agent a goal it plans into tasks, tracks and delivers
*/
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index 0bde274160c..a86a51587d3 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -942,6 +942,7 @@ describe('DataSlice', () => {
expect(messageService.getMessages).toHaveBeenCalledWith({
agentId: 'test-session',
groupId: null,
+ projectToolPayloads: false,
threadId: 'test-thread',
topicId: 'test-topic',
});
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 4029e32e67e..f31a8902605 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -4,6 +4,7 @@ import debug from 'debug';
import { type SWRResponse } from 'swr';
import { type StateCreator } from 'zustand/vanilla';
+import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { messageService } from '@/services/message';
import {
@@ -391,7 +392,7 @@ export const dataSlice: StateCreator<
? topicSelectors.getTopicById(context.topicId)(getChatStoreState())
: undefined;
const wasPending = hasPendingInterventions(dbMessages);
- let messages = await runMessageListQuery(context, messageService.getMessageListPage);
+ let messages = await runMessageListQuery(context, readConversationMessageListPage);
if (!syncContinuation || !context.topicId) return messages;
if (wasPending || hasPendingInterventions(messages)) sync.pending.add(syncKey);
if (!sync.pending.has(syncKey) || hasPendingInterventions(messages)) return messages;
@@ -401,7 +402,7 @@ export const dataSlice: StateCreator<
const topic = await topicService.getTopicDetail(context.topicId);
if (!isInterventionRunActive(topic)) {
// Read after completion without dropping loaded history or its cursor.
- messages = await runMessageListQuery(context, messageService.getMessageListPage, {
+ messages = await runMessageListQuery(context, readConversationMessageListPage, {
force: true,
});
}
diff --git a/src/helpers/conversationMessageRead.test.ts b/src/helpers/conversationMessageRead.test.ts
new file mode 100644
index 00000000000..8f06f4470b9
--- /dev/null
+++ b/src/helpers/conversationMessageRead.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { messageService } from '@/services/message';
+import * as agentStore from '@/store/agent';
+import * as serverConfigStore from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+
+import {
+ readConversationMessageListPage,
+ readConversationMessages,
+} from './conversationMessageRead';
+
+const mockGatewayMode = ({
+ gatewayMode,
+ protocolV2 = true,
+}: {
+ gatewayMode: boolean;
+ protocolV2?: boolean;
+}) => {
+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({
+ featureFlags: { enableGatewayMux: protocolV2 },
+ serverConfig: {
+ ...(protocolV2 && { agentGatewayProtocol: 2 }),
+ ...(gatewayMode && { agentGatewayUrl: 'https://gateway.test', enableGatewayMode: true }),
+ },
+ } as unknown as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);
+ vi.spyOn(agentStore, 'getAgentStoreState').mockReturnValue({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { chatConfig: {} } },
+ } as unknown as ReturnType<typeof agentStore.getAgentStoreState>);
+ useUserStore.setState({ settings: {} } as never);
+};
+
+describe('readConversationMessages', () => {
+ it('asks for projected tool payloads when the run executes on the server', async () => {
+ mockGatewayMode({ gatewayMode: true });
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue([]);
+
+ await readConversationMessages({ agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(getMessages).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ projectToolPayloads: true,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('keeps whole payloads outside the protocol-v2 rollout', async () => {
+ mockGatewayMode({ gatewayMode: true, protocolV2: false });
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue([]);
+
+ await readConversationMessages({ agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(getMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ projectToolPayloads: false }),
+ );
+ });
+
+ it('keeps whole payloads when the run can execute in the browser', async () => {
+ // The browser assembles its LLM context from this very list, so a projected
+ // tool result would silently disappear from the model's view.
+ mockGatewayMode({ gatewayMode: false });
+ const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue([]);
+
+ await readConversationMessages({ agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(getMessages).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ projectToolPayloads: false,
+ topicId: 'topic-1',
+ });
+ });
+});
+
+describe('readConversationMessageListPage', () => {
+ it('applies the same projection gate to the paged list read', async () => {
+ mockGatewayMode({ gatewayMode: true });
+ const getPage = vi.spyOn(messageService, 'getMessageListPage').mockResolvedValue([]);
+
+ await readConversationMessageListPage({ agentId: 'agent-1', topicId: 'topic-1' });
+
+ expect(getPage).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ projectToolPayloads: true,
+ topicId: 'topic-1',
+ });
+ });
+});
diff --git a/src/helpers/conversationMessageRead.ts b/src/helpers/conversationMessageRead.ts
new file mode 100644
index 00000000000..375e1814f19
--- /dev/null
+++ b/src/helpers/conversationMessageRead.ts
@@ -0,0 +1,49 @@
+import { type MessageReadQueryContext, messageService } from '@/services/message';
+import { getAgentStoreState } from '@/store/agent';
+
+import { resolveGatewayModeEnabled } from './gatewayMode';
+import { canUseGatewayProtocolV2 } from './gatewayProtocol';
+
+/**
+ * The conversation-list read every rendering surface shares.
+ *
+ * It asks for projected tool payloads (`@lobechat/tool-view-model`) only for a
+ * protocol-v2 client whose runs execute on the server. Both halves matter:
+ *
+ * - Protocol v2 is what the projection ships with, so it moves with the same
+ * rollout dial rather than reaching everyone the moment this code deploys.
+ * - Gateway mode is the correctness half. Off it, the run executes in the
+ * browser and assembles its LLM context from the very list this read fills
+ * (`dbMessagesMap` β†’ `ClientMessageTransport`), so a projected tool result
+ * would silently vanish from the model's view of its own work. Whole payloads
+ * are the answer that cannot lose data, so that is what an unknown or
+ * client-side agent gets.
+ *
+ * The choice deliberately stays out of the message-list cache key: a list
+ * cached while Gateway mode was on can still be read by a run the user has
+ * since switched to the browser, which is why `ClientMessageTransport` refills
+ * omitted payloads before building a context rather than trusting this gate.
+ */
+const withConversationReadOptions = (
+ context: MessageReadQueryContext,
+): MessageReadQueryContext => ({
+ ...context,
+ projectToolPayloads:
+ canUseGatewayProtocolV2() &&
+ resolveGatewayModeEnabled(getAgentStoreState(), context.agentId ?? undefined),
+});
+
+export const readConversationMessages = (
+ context: MessageReadQueryContext,
+): Promise<Awaited<ReturnType<typeof messageService.getMessages>>> =>
+ messageService.getMessages(withConversationReadOptions(context));
+
+/**
+ * The paged form of {@link readConversationMessages}, for the message-list
+ * cache: the newest round-cursor window of a topic, or the plain list for other
+ * contexts. Same projection gate.
+ */
+export const readConversationMessageListPage = (
+ context: MessageReadQueryContext,
+): ReturnType<typeof messageService.getMessageListPage> =>
+ messageService.getMessageListPage(withConversationReadOptions(context));
diff --git a/src/helpers/gatewayProtocol.test.ts b/src/helpers/gatewayProtocol.test.ts
new file mode 100644
index 00000000000..ffc7897066f
--- /dev/null
+++ b/src/helpers/gatewayProtocol.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import * as serverConfigStore from '@/store/serverConfig';
+
+import { canUseGatewayProtocolV2 } from './gatewayProtocol';
+
+const mockConfig = (protocol?: number, rollout?: boolean) =>
+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({
+ featureFlags: { enableGatewayMux: rollout },
+ serverConfig: { agentGatewayProtocol: protocol },
+ } as unknown as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete (globalThis as { window?: unknown }).window;
+});
+
+describe('canUseGatewayProtocolV2', () => {
+ it('needs both the deployment capability and the rollout', () => {
+ mockConfig(2, true);
+ expect(canUseGatewayProtocolV2()).toBe(true);
+
+ // In the rollout, but this deployment's gateway has no `/v2/ws` at all.
+ mockConfig(1, true);
+ expect(canUseGatewayProtocolV2()).toBe(false);
+
+ // The gateway has it; this user is not in the rollout yet.
+ mockConfig(2, false);
+ expect(canUseGatewayProtocolV2()).toBe(false);
+ });
+
+ it('defaults to v1 when the server said nothing', () => {
+ mockConfig(undefined, undefined);
+ expect(canUseGatewayProtocolV2()).toBe(false);
+ });
+
+ it('prefers the global store the shell publishes before React mounts', () => {
+ mockConfig(1, false);
+ (globalThis as { window?: unknown }).window = {
+ global_serverConfigStore: {
+ getState: () => ({
+ featureFlags: { enableGatewayMux: true },
+ serverConfig: { agentGatewayProtocol: 2 },
+ }),
+ },
+ };
+
+ expect(canUseGatewayProtocolV2()).toBe(true);
+ });
+});
diff --git a/src/helpers/gatewayProtocol.ts b/src/helpers/gatewayProtocol.ts
new file mode 100644
index 00000000000..e32312e75db
--- /dev/null
+++ b/src/helpers/gatewayProtocol.ts
@@ -0,0 +1,33 @@
+import { getServerConfigStoreState } from '@/store/serverConfig';
+
+/**
+ * `serverConfig` / `featureFlags`, read the same way the gateway transport does:
+ * the global store first (the SPA and the desktop shell publish it on `window`
+ * before the React store exists), then the module-level state.
+ */
+const getConfigState = () =>
+ (typeof window !== 'undefined' ? window.global_serverConfigStore?.getState() : undefined) ??
+ getServerConfigStoreState();
+
+/**
+ * Whether this client speaks protocol v2 to the Agent Gateway: one multiplexed
+ * socket per user, message revisions instead of pushed message snapshots, and
+ * projected tool payloads on the conversation read.
+ *
+ * Two independent halves, both required:
+ *
+ * - `agentGatewayProtocol === 2` β€” the deployment's gateway actually exposes
+ * `/v2/ws`. A capability, not a choice: there is no negotiation on the socket,
+ * and a self-hosted gateway that only has `/ws` cannot serve any of this.
+ * - `enableGatewayMux` β€” this user is inside the rollout. Server-published, so
+ * it moves without a deploy and takes everything protocol v2 changes with it,
+ * in one step and in one direction.
+ *
+ * Read non-reactively: a run keeps the protocol it started with even if either
+ * half changes underneath it.
+ */
+export const canUseGatewayProtocolV2 = (): boolean => {
+ const state = getConfigState();
+
+ return state?.serverConfig?.agentGatewayProtocol === 2 && !!state.featureFlags?.enableGatewayMux;
+};
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 43d01a27eb1..525de64013b 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -1,4 +1,5 @@
import type { AgentStreamClientFeature } from '@lobechat/agent-gateway-client';
+import { CLIENT_PROTOCOL_VERSION } from '@lobechat/agent-gateway-client';
import type {
ExecAgentAppContext,
ExecAgentResult,
@@ -8,6 +9,7 @@ import type {
UserInterventionConfig,
} from '@lobechat/types';
+import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';
import { lambdaClient } from '@/libs/trpc/client';
export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };
@@ -273,8 +275,15 @@ class AiAgentService {
params: ExecAgentTaskParams,
options?: { signal?: AbortSignal },
): Promise<ExecAgentResult> {
+ // Ask for protocol-v2 delivery β€” message revisions instead of whole message
+ // snapshots β€” when this client both understands it and is inside the
+ // rollout. Anything else stays on the pushed snapshots, which is what an
+ // older bundle needs to render the run at all. A caller may still pin it
+ // (a replay harness asserting v1 delivery).
+ const clientProtocol = canUseGatewayProtocolV2() ? CLIENT_PROTOCOL_VERSION : undefined;
+
return await lambdaClient.aiAgent.execAgent.mutate(
- { ...params, streamFeatures: STREAM_FEATURES },
+ { clientProtocol, ...params, streamFeatures: STREAM_FEATURES },
options,
);
}
diff --git a/src/services/message/__tests__/hydrateProjectedTools.test.ts b/src/services/message/__tests__/hydrateProjectedTools.test.ts
index 962435f24b2..8532bcf6d64 100644
--- a/src/services/message/__tests__/hydrateProjectedTools.test.ts
+++ b/src/services/message/__tests__/hydrateProjectedTools.test.ts
@@ -2,6 +2,7 @@ import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import {
+ hydrateProjectedConversation,
hydrateProjectedToolMessages,
mergeStoredToolPayloads,
} from '../hydrateProjectedTools';
@@ -113,3 +114,64 @@ describe('mergeStoredToolPayloads', () => {
expect(missing).toEqual(['t1']);
});
});
+
+describe('hydrateProjectedConversation', () => {
+ const folded = [
+ msg({
+ children: [
+ {
+ content: '',
+ id: 'a1',
+ tools: [
+ {
+ apiName: 'run',
+ arguments: '{}',
+ id: 'call-1',
+ identifier: 'shell',
+ result: { content: '', id: 't1', state: { exitCode: 0 } },
+ result_msg_id: 't1',
+ type: 'default',
+ },
+ ],
+ },
+ ],
+ id: 'a1',
+ role: 'assistantGroup',
+ }),
+ ];
+
+ it('restores folded tool results using ids from the raw list', async () => {
+ const fetch = vi.fn().mockResolvedValue({
+ t1: { content: 'full stdout', pluginState: { exitCode: 0, stdout: 'full stdout' } },
+ });
+
+ const result = await hydrateProjectedConversation(folded, [projectedTool()], fetch);
+
+ expect(fetch).toHaveBeenCalledWith(['t1']);
+ expect(result[0].children?.[0].tools?.[0].result).toEqual({
+ content: 'full stdout',
+ id: 't1',
+ state: { exitCode: 0, stdout: 'full stdout' },
+ });
+ });
+
+ it('restores nested member lists', async () => {
+ const fetch = vi.fn().mockResolvedValue({ t1: { content: 'full' } });
+
+ const result = await hydrateProjectedConversation(
+ [msg({ id: 'g', members: [projectedTool()], role: 'supervisor' })],
+ undefined,
+ fetch,
+ );
+
+ expect(result[0].members?.[0].content).toBe('full');
+ });
+
+ it('makes no request when nothing was projected', async () => {
+ const fetch = vi.fn();
+ const messages = [msg({ id: 'u1' })];
+
+ expect(await hydrateProjectedConversation(messages, messages, fetch)).toBe(messages);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/message/hydrateProjectedTools.ts b/src/services/message/hydrateProjectedTools.ts
index 53e3ac4b530..d152eac1bf3 100644
--- a/src/services/message/hydrateProjectedTools.ts
+++ b/src/services/message/hydrateProjectedTools.ts
@@ -1,4 +1,4 @@
-import type { UIChatMessage } from '@lobechat/types';
+import type { ChatToolPayloadWithResult, UIChatMessage } from '@lobechat/types';
export interface StoredToolPayload {
content: string;
@@ -80,3 +80,107 @@ export const hydrateProjectedToolMessages = async (
return { messages, missing: ids };
}
};
+
+/**
+ * Ids of every projected tool row in a list, nested lists included
+ * (compression groups, compare columns, group members, council blocks).
+ */
+const collectProjectedToolIds = (
+ messages: UIChatMessage[] | undefined,
+ ids: Set<string> = new Set(),
+): Set<string> => {
+ for (const message of messages ?? []) {
+ if (message.role === 'tool' && message.payloadOmitted) ids.add(message.id);
+
+ for (const nested of [message.compressedMessages, message.members, ...(message.columns ?? [])])
+ collectProjectedToolIds(nested, ids);
+ for (const block of message.children ?? []) collectProjectedToolIds(block.council, ids);
+ }
+ return ids;
+};
+
+const restoreToolResult = (
+ tool: ChatToolPayloadWithResult,
+ payloads: Record<string, StoredToolPayload>,
+): ChatToolPayloadWithResult => {
+ const id = tool.result_msg_id ?? tool.result?.id;
+ const payload = id ? payloads[id] : undefined;
+ if (!tool.result || typeof payload?.content !== 'string') return tool;
+
+ return {
+ ...tool,
+ result: {
+ ...tool.result,
+ content: payload.content,
+ ...(payload.pluginState !== undefined && { state: payload.pluginState }),
+ },
+ };
+};
+
+const restoreDeep = (
+ messages: UIChatMessage[],
+ payloads: Record<string, StoredToolPayload>,
+): UIChatMessage[] =>
+ messages.map((message) => {
+ const payload = message.role === 'tool' ? payloads[message.id] : undefined;
+ const restored =
+ typeof payload?.content === 'string'
+ ? {
+ ...message,
+ content: payload.content,
+ ...(payload.pluginState !== undefined && { pluginState: payload.pluginState }),
+ }
+ : message;
+
+ return {
+ ...restored,
+ ...(restored.children?.length && {
+ children: restored.children.map((block) => ({
+ ...block,
+ ...(block.tools?.length && {
+ tools: block.tools.map((tool) => restoreToolResult(tool, payloads)),
+ }),
+ ...(block.council?.length && { council: restoreDeep(block.council, payloads) }),
+ })),
+ }),
+ ...(restored.columns?.length && {
+ columns: restored.columns.map((column) => restoreDeep(column, payloads)),
+ }),
+ ...(restored.compressedMessages?.length && {
+ compressedMessages: restoreDeep(restored.compressedMessages, payloads),
+ }),
+ ...(restored.members?.length && { members: restoreDeep(restored.members, payloads) }),
+ };
+ });
+
+/**
+ * Restore projected tool payloads in a FOLDED conversation before it becomes
+ * an LLM context.
+ *
+ * A browser-executed run builds its first step from the display list, where a
+ * tool result is folded into its assistant group (`children[].tools[].result`)
+ * and no longer carries `payloadOmitted`. The ids therefore come from the raw
+ * store list (`rawMessages`) as well as the folded one, and the restore walks
+ * every place a tool body can sit. Returns the input untouched β€” no request β€”
+ * when nothing was projected; on a fetch failure it logs and returns the input,
+ * matching {@link hydrateProjectedToolMessages}.
+ */
+export const hydrateProjectedConversation = async (
+ messages: UIChatMessage[],
+ rawMessages: UIChatMessage[] | undefined,
+ fetchStoredPayloads: (messageIds: string[]) => Promise<Record<string, StoredToolPayload>>,
+): Promise<UIChatMessage[]> => {
+ const ids = [...collectProjectedToolIds(messages, collectProjectedToolIds(rawMessages))];
+ if (ids.length === 0) return messages;
+
+ try {
+ return restoreDeep(messages, await fetchStoredPayloads(ids));
+ } catch (error) {
+ console.error(
+ '[hydrateProjectedTools] failed to restore %d tool payloads: %O',
+ ids.length,
+ error,
+ );
+ return messages;
+ }
+};
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index b32b0e699cf..3f5cb44191c 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -36,11 +36,17 @@ export interface MessageQueryContext {
topicShareId?: string;
}
-interface MessageReadQueryContext {
+export interface MessageReadQueryContext {
agentId?: string | null;
/** Agent-share visitor surface β€” routes the read through `shareChat.getMessages`. */
agentShareId?: string;
groupId?: string | null;
+ /**
+ * Ask the server for render-facing tool view models instead of the stored
+ * payloads. Only set it for a read whose result is never turned into an LLM
+ * context in the browser β€” see `readConversationMessages`.
+ */
+ projectToolPayloads?: boolean;
/**
* Skip the Work-summary assembly on the server β€” set by mid-stream
* refetches (tool_end / step_complete) so each tool round doesn't re-run
@@ -275,6 +281,7 @@ export class MessageService {
cursor,
groupId: params.groupId,
includeFileWorks: true,
+ projectToolPayloads: params.projectToolPayloads,
// The row budget is the real bound; ask for as many whole rounds as it holds.
roundLimit: MESSAGE_PAGE_ROW_BUDGET,
skipWorks: params.skipWorks,
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.test.ts b/src/store/chat/agents/transports/ClientMessageTransport.test.ts
index 7725941eea5..97196055bcf 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.test.ts
@@ -38,6 +38,84 @@ describe('ClientMessageTransport', () => {
vi.restoreAllMocks();
});
+ describe('query', () => {
+ const projectedRow = {
+ content: '',
+ id: 'tool-1',
+ payloadOmitted: 'detail',
+ role: 'tool',
+ } as any;
+
+ const storeWith = (messages: any[]) => {
+ const store = createStore();
+ (store as any).dbMessagesMap['message-key'] = messages;
+ return store;
+ };
+
+ it('refills a projected tool payload before the list becomes a context', async () => {
+ const fetchPayloads = vi
+ .spyOn(messageService, 'getToolResultPayloads')
+ .mockResolvedValue({ 'tool-1': { content: 'REAL TOOL OUTPUT', pluginState: { a: 1 } } });
+ const transport = new ClientMessageTransport(
+ () => storeWith([projectedRow]),
+ 'message-key',
+ 'operation-1',
+ );
+
+ const [row] = await transport.query();
+
+ expect(fetchPayloads).toHaveBeenCalledWith(['tool-1']);
+ expect(row.content).toBe('REAL TOOL OUTPUT');
+ expect(row.pluginState).toEqual({ a: 1 });
+ });
+
+ it('fetches each stored payload once across the steps of a run', async () => {
+ const fetchPayloads = vi
+ .spyOn(messageService, 'getToolResultPayloads')
+ .mockResolvedValue({ 'tool-1': { content: 'REAL TOOL OUTPUT' } });
+ const store = storeWith([projectedRow]);
+ const transport = new ClientMessageTransport(() => store, 'message-key', 'operation-1');
+
+ await transport.query();
+ (store as any).dbMessagesMap['message-key'] = [
+ projectedRow,
+ { content: 'hi', id: 'user-1', role: 'user' },
+ ];
+ const second = await transport.query();
+
+ expect(fetchPayloads).toHaveBeenCalledTimes(1);
+ expect(second[0].content).toBe('REAL TOOL OUTPUT');
+ });
+
+ it('leaves an unprojected list alone without asking the server', async () => {
+ const fetchPayloads = vi.spyOn(messageService, 'getToolResultPayloads');
+ const rows = [{ content: 'FULL', id: 'tool-1', role: 'tool' }] as any[];
+ const transport = new ClientMessageTransport(
+ () => storeWith(rows),
+ 'message-key',
+ 'operation-1',
+ );
+
+ expect(await transport.query()).toEqual(rows);
+ expect(fetchPayloads).not.toHaveBeenCalled();
+ });
+
+ it('keeps the projected row when the refill fails, rather than failing the step', async () => {
+ vi.spyOn(messageService, 'getToolResultPayloads').mockRejectedValue(new Error('offline'));
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const transport = new ClientMessageTransport(
+ () => storeWith([projectedRow]),
+ 'message-key',
+ 'operation-1',
+ );
+
+ const [row] = await transport.query();
+
+ expect(row.content).toBe('');
+ error.mockRestore();
+ });
+ });
+
it('creates an optimistic message with a stable id and persists it quietly', async () => {
const store = createStore();
const transport = new ClientMessageTransport(() => store, 'message-key', 'operation-1');
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.ts
index 6c7c0d6b195..c2fcf5481f3 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts
@@ -15,10 +15,18 @@ import { ChatErrorType } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { type MessageBatchOperation, messageService } from '@/services/message';
+import {
+ mergeStoredToolPayloads,
+ selectProjectedToolIds,
+ type StoredToolPayload,
+} from '@/services/message/hydrateProjectedTools';
import type { ChatStore } from '@/store/chat/store';
/** Client message adapter backed by the optimistic chat store. */
export class ClientMessageTransport implements MessageTransport {
+ /** Stored tool payloads refilled for this run β€” see `withStoredToolPayloads`. */
+ private readonly storedToolPayloads = new Map<string, StoredToolPayload>();
+
constructor(
private readonly get: () => ChatStore,
private readonly messageKey: string,
@@ -78,7 +86,7 @@ export class ClientMessageTransport implements MessageTransport {
_params?: QueryMessagesInput,
_options?: QueryMessagesOptions,
): Promise<UIChatMessage[]> {
- return this.getMessages();
+ return this.withStoredToolPayloads(this.getMessages());
}
async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {
@@ -208,4 +216,39 @@ export class ClientMessageTransport implements MessageTransport {
private getMessages(): UIChatMessage[] {
return this.get().dbMessagesMap[this.messageKey] ?? [];
}
+
+ /**
+ * Put the stored tool payloads back before this list becomes an LLM context.
+ *
+ * A browser-executed run reads its history from the same store the UI
+ * renders, and that store can be holding a list fetched while the read path
+ * was projecting tool payloads to view models (`payloadOmitted`) β€” Gateway
+ * mode was on for this agent when the list was cached and has since been
+ * turned off, or another surface seeded the bucket. Rendering is happy with
+ * the view model; the model is not, and would silently lose the tool output
+ * it is supposed to reason about.
+ *
+ * The fetched payloads are cached per operation: a run queries once per step,
+ * the map is keyed by row id and so stays valid as the conversation grows. A
+ * failed refill leaves the row projected β€” a degraded context still beats a
+ * step that cannot run at all.
+ */
+ private async withStoredToolPayloads(messages: UIChatMessage[]): Promise<UIChatMessage[]> {
+ const missing = selectProjectedToolIds(messages).filter(
+ (id) => !this.storedToolPayloads.has(id),
+ );
+
+ if (missing.length > 0) {
+ try {
+ const fetched = await messageService.getToolResultPayloads(missing);
+ for (const [id, payload] of Object.entries(fetched)) {
+ this.storedToolPayloads.set(id, payload);
+ }
+ } catch (error) {
+ console.error('[ClientMessageTransport] failed to restore tool payloads:', error);
+ }
+ }
+
+ return mergeStoredToolPayloads(messages, Object.fromEntries(this.storedToolPayloads)).messages;
+ }
}
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 6e1453704fb..ed0198684fd 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -323,6 +323,76 @@ describe('StreamingExecutor actions', () => {
},
);
+ it('restores projected tool payloads before the first client LLM call', async () => {
+ act(() => {
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
+ });
+ const { result } = renderHook(() => useChatStore());
+ const context = { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID };
+ const toolCall = {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call-1',
+ identifier: 'web',
+ type: 'default',
+ } as const;
+
+ // The store holds a list read while Gateway mode projected tool payloads.
+ seedDbMessages(context, [
+ { content: 'find it', id: 'user-1', role: 'user' } as UIChatMessage,
+ { content: '', id: 'assistant-1', role: 'assistant', tools: [toolCall] } as UIChatMessage,
+ {
+ content: 'view-model summary',
+ id: 'tool-1',
+ payloadOmitted: 'detail',
+ role: 'tool',
+ tool_call_id: 'call-1',
+ } as UIChatMessage,
+ { content: 'and now?', id: TEST_IDS.USER_MESSAGE_ID, role: 'user' } as UIChatMessage,
+ ]);
+ const payloadSpy = vi
+ .spyOn(messageService, 'getToolResultPayloads')
+ .mockResolvedValue({ 'tool-1': { content: 'FULL STORED TOOL BODY' } });
+ const streamSpy = spyOnClientLLMStream();
+
+ // The send path hands over FOLDED display messages: the tool result sits
+ // inside the assistant group and carries no `payloadOmitted` marker.
+ await act(async () => {
+ await result.current.executeClientAgent({
+ context,
+ messages: [
+ { content: 'find it', id: 'user-1', role: 'user' } as UIChatMessage,
+ {
+ children: [
+ {
+ content: '',
+ id: 'assistant-1',
+ tools: [
+ {
+ ...toolCall,
+ result: { content: 'view-model summary', id: 'tool-1' },
+ result_msg_id: 'tool-1',
+ },
+ ],
+ },
+ ],
+ content: '',
+ id: 'assistant-1',
+ role: 'assistantGroup',
+ } as UIChatMessage,
+ { content: 'and now?', id: TEST_IDS.USER_MESSAGE_ID, role: 'user' } as UIChatMessage,
+ ],
+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,
+ parentMessageType: 'user',
+ });
+ });
+
+ expect(payloadSpy).toHaveBeenCalledWith(['tool-1']);
+ const firstPayload = JSON.stringify(streamSpy.mock.calls[0][0].messages);
+ expect(firstPayload).toContain('FULL STORED TOOL BODY');
+ expect(firstPayload).not.toContain('view-model summary');
+ });
+
it('writes topics.status=running at run start so off-conversation surfaces see it', async () => {
act(() => {
useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index b8640c879fc..d92e42f25e7 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -41,6 +41,7 @@ import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';
import { localFileService } from '@/services/electron/localFileService';
import { messageService } from '@/services/message';
+import { hydrateProjectedConversation } from '@/services/message/hydrateProjectedTools';
import { workService } from '@/services/work';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -632,8 +633,18 @@ export class StreamingExecutorActionImpl {
});
}
- // Create a new array to avoid modifying the original messages
- const messages = [...originalMessages];
+ // The first step reads `state.messages` directly, before any
+ // `MessageTransport.query()` refill, and those are the folded display
+ // messages. A list cached while the read path projected tool payloads
+ // (Gateway mode on, since switched off) would hand the model empty tool
+ // bodies, so put the stored payloads back first. Ids come from the raw
+ // store list too: a folded tool result no longer carries `payloadOmitted`.
+ // Also returns a new array, so the caller's messages are never mutated.
+ const messages = await hydrateProjectedConversation(
+ [...originalMessages],
+ this.#get().dbMessagesMap[messageKey],
+ messageService.getToolResultPayloads,
+ );
// Decide tool / function-calling capability from real data, not a guess.
// The enabled-model list hydrates asynchronously (auth session β†’ aiProvider
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 03cd70b54e1..a223abd70cd 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -34,6 +34,7 @@ import {
resolveExecutionTarget,
resolveWorkspaceScoped,
} from '@/helpers/executionTarget';
+import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';
import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';
import {
aiAgentService,
@@ -85,25 +86,6 @@ const getGatewayServerConfig = () =>
? window.global_serverConfigStore?.getState()?.serverConfig
: undefined) ?? getServerConfigStoreState()?.serverConfig;
-const getGatewayFeatureFlags = () =>
- (typeof window !== 'undefined'
- ? window.global_serverConfigStore?.getState()?.featureFlags
- : undefined) ?? getServerConfigStoreState()?.featureFlags;
-
-/**
- * Whether this client may open the multiplexed (protocol v2) gateway socket.
- *
- * Both halves are required and mean different things: the deployment has to
- * actually expose `/v2/ws` (`agentGatewayProtocol` β€” a capability, since there
- * is no negotiation on the socket itself), and this user has to be inside the
- * rollout (`enableGatewayMux`, a server-published feature flag). Read
- * non-reactively like the other gateway prefs: a connection keeps the transport
- * it was opened with even if either side changes mid-run.
- */
-const canUseGatewayMux = (): boolean =>
- getGatewayServerConfig()?.agentGatewayProtocol === 2 &&
- !!getGatewayFeatureFlags()?.enableGatewayMux;
-
/**
* Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.
*
@@ -491,8 +473,9 @@ export class GatewayActionImpl {
// the rollout to reach them.
const muxIdentity: GatewayMuxIdentity = { agentShareId, gatewayUrl };
const useGatewayMux =
- (agentShareId ? getGatewayServerConfig()?.agentGatewayProtocol === 2 : canUseGatewayMux()) &&
- !isGatewayMuxUnavailable(muxIdentity);
+ (agentShareId
+ ? getGatewayServerConfig()?.agentGatewayProtocol === 2
+ : canUseGatewayProtocolV2()) && !isGatewayMuxUnavailable(muxIdentity);
let muxClient: OperationClient | undefined;
if (useGatewayMux) {
const mux = this.resolveGatewayMux(muxIdentity);
@@ -718,11 +701,11 @@ export class GatewayActionImpl {
* first run never pays the WebSocket handshake on its critical path β€”
* `connectToGateway` then only sends a `subscribe` frame on the already-open
* socket. No-op when gateway mode is off or this client may not use the
- * multiplexed transport (see `canUseGatewayMux`); safe to call repeatedly
+ * multiplexed transport (see `canUseGatewayProtocolV2`); safe to call repeatedly
* (`connect` is idempotent).
*/
warmupGatewayMux = (): void => {
- if (!canUseGatewayMux()) return;
+ if (!canUseGatewayProtocolV2()) return;
const serverConfig = getGatewayServerConfig();
if (!serverConfig?.agentGatewayUrl || !serverConfig.enableGatewayMode) return;
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 36dae60f5fb..0cb2bcb35b2 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
@@ -206,7 +206,11 @@ describe('createGatewayEventHandler', () => {
// Mid-stream tool_end refetches skip the Work-summary assembly and graft
// previously rendered works back via `preserveWorks`.
- expect(getMessages).toHaveBeenCalledWith({ ...context, skipWorks: true });
+ expect(getMessages).toHaveBeenCalledWith({
+ ...context,
+ projectToolPayloads: false,
+ skipWorks: true,
+ });
expect(store.replaceMessages).toHaveBeenCalledWith([], { context, preserveWorks: true });
});
@@ -1116,7 +1120,11 @@ describe('createGatewayEventHandler', () => {
handler(makeEvent('message_patch', { deletes: [], revision: 2, upserts: [] }));
await flush();
- expect(getMessages).toHaveBeenCalledWith({ ...context, skipWorks: true });
+ expect(getMessages).toHaveBeenCalledWith({
+ ...context,
+ projectToolPayloads: false,
+ skipWorks: true,
+ });
expect(store.replaceMessages).toHaveBeenCalledWith(recovered, {
context,
preserveWorks: true,
@@ -1376,7 +1384,11 @@ describe('createGatewayEventHandler', () => {
}),
);
await flush();
- expect(getMessages).toHaveBeenCalledWith({ ...context, skipWorks: true });
+ expect(getMessages).toHaveBeenCalledWith({
+ ...context,
+ projectToolPayloads: false,
+ skipWorks: true,
+ });
expect(store.updateTopicStatus).toHaveBeenLastCalledWith(
expect.objectContaining({ status: 'running', topicId: 'topic-1' }),
);
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 9142662c6e8..ac83b08df9b 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -17,6 +17,7 @@ import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';
import type { BuiltinToolResult, ConversationContext, UIChatMessage } from '@lobechat/types';
import { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';
+import { readConversationMessages } from '@/helpers/conversationMessageRead';
import { messageService } from '@/services/message';
import { didToolMutateWorkView, workService } from '@/services/work';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
@@ -88,9 +89,7 @@ const fetchAndReplaceMessages = async (
const skipWorks = options?.skipWorks;
const snapshotGeneration = options?.snapshotGeneration;
const started = snapshotGeneration?.current;
- const messages = await messageService.getMessages(
- skipWorks ? { ...context, skipWorks } : context,
- );
+ const messages = await readConversationMessages(skipWorks ? { ...context, skipWorks } : context);
if (snapshotGeneration && snapshotGeneration.current !== started) return undefined;
if (snapshotGeneration) snapshotGeneration.current += 1;
get().replaceMessages(messages, { context, preserveWorks: skipWorks });
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index 951171fd63b..e21e8a1865b 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -1657,6 +1657,9 @@ describe('chatMessage actions', () => {
expect(messageService.getMessages).toHaveBeenCalledWith({
agentId: 'prefetch-agent',
groupId: null,
+ // Whole tool payloads: the conversation read only asks for projected
+ // ones for a protocol-v2 client whose runs execute on the server.
+ projectToolPayloads: false,
threadId: null,
topicId: 'prefetch-topic',
});
@@ -1736,6 +1739,7 @@ describe('chatMessage actions', () => {
expect(messageService.getMessages).toHaveBeenCalledWith({
agentId: 'prefetch-agent',
groupId: null,
+ projectToolPayloads: false,
threadId: null,
topicId: 'cached-topic',
});
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index e2bb26d6c0b..a7e97e0cf15 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -4,9 +4,9 @@ import debug from 'debug';
import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
+import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { isMessageListKey } from '@/libs/swr/keys';
-import { messageService } from '@/services/message';
import {
getMessageListCacheIdentity,
getMessageListFetchPolicy,
@@ -97,7 +97,7 @@ export class MessageQueryActionImpl {
prefetchingMessageKeys.add(messagesKey);
- const request = runMessageListQuery(context, messageService.getMessageListPage).then(
+ const request = runMessageListQuery(context, readConversationMessageListPage).then(
(messages) => {
// Re-check at DELIVERY time, not just at start: the user can open this
// topic and submit a follow-up while the request is in flight. Applying
@@ -358,7 +358,7 @@ export class MessageQueryActionImpl {
return useClientDataSWRWithSync<UIChatMessage[]>(
shouldFetch ? messageListKey(context) : null,
- () => runMessageListQuery(context, messageService.getMessageListPage),
+ () => runMessageListQuery(context, readConversationMessageListPage),
{
...getMessageListFetchPolicy(context),
onData: (data) => {