π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β‘οΈ perf(tools): drop a tool's body by default, keep its state until a projector says otherwise (#19699)
Arvin Xu02f6a5d719b7
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 6278a760a2c..1fb1f1d12b2 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -398,6 +398,15 @@ export const messageRouter = router({* Raw tool payload for one message, fetched on demand when the projected* read path dropped it (`UIChatMessage.payloadOmitted`).*/+ /** Bulk form of {@link getToolResultPayload}; see its note on ids as locators. */+ getToolResultPayloads: messageProcedure+ .input(z.object({ messageIds: z.array(z.string()).min(1).max(500) }))+ .query(async ({ input, ctx }) => {+ await assertCanViewMessageTargets(guardCtx(ctx), input.messageIds);++ return ctx.messageService.getToolResultPayloads(input.messageIds);+ }),+getToolResultPayload: messageProcedure.input(z.object({ messageId: z.string() })).query(async ({ input, ctx }) => {diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.tsindex 7944c23c9dd..b4ffd76cb48 100644--- a/apps/server/src/services/message/__tests__/index.test.ts+++ b/apps/server/src/services/message/__tests__/index.test.ts@@ -179,16 +179,19 @@ describe('MessageService', () => {expect(result).toEqual([toolRow]);});- it('leaves a tool without a projector exactly as stored', async () => {+ 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 result = await messageService.queryMessages({ topicId: 'topic-1' });+ const [projected] = await messageService.queryMessages({ topicId: 'topic-1' });- expect(result).toEqual([unprojected]);+ 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.tsindex a009a2eadc0..5831f1bb4bc 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -281,6 +281,26 @@ export class MessageService {return { content: message.content ?? '', pluginState: plugin?.state };}+ /**+ * Stored tool payloads for several messages at once.+ *+ * A topic can hold hundreds of projected tool rows, and an export needs every+ * one of them; asking per row would be that many authenticated round trips,+ * each repeating the same authorization and joins. Ownership is enforced by+ * the model read, so ids the caller may not see simply do not come back.+ */+ async getToolResultPayloads(+ messageIds: string[],+ ): Promise<Record<string, { content: string; pluginState?: unknown }>> {+ if (messageIds.length === 0) return {};++ const rows = await this.messageModel.queryByIds(messageIds);++ return Object.fromEntries(+ rows.map((row) => [row.id, { content: row.content ?? '', pluginState: row.pluginState }]),+ );+ }+/*** Quiet write-behind batch for streaming runtimes. Unlike createMessage /* updateMessage, this intentionally does not query the full message list afterdiff --git a/packages/tool-view-model/package.json b/packages/tool-view-model/package.jsonindex 6529b4171fa..7107d2634b8 100644--- a/packages/tool-view-model/package.json+++ b/packages/tool-view-model/package.json@@ -9,6 +9,9 @@"scripts": {"test": "vitest"},+ "dependencies": {+ "@lobechat/const": "workspace:*"+ },"devDependencies": {"@lobechat/types": "workspace:*"}diff --git a/packages/tool-view-model/src/project.test.ts b/packages/tool-view-model/src/project.test.tsindex e57762a8beb..fde8710aecd 100644--- a/packages/tool-view-model/src/project.test.ts+++ b/packages/tool-view-model/src/project.test.ts@@ -1,3 +1,4 @@+import { LOADING_FLAT } from '@lobechat/const';import type { UIChatMessage } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';@@ -21,10 +22,35 @@ 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' })];+ it('drops the body of a tool with no projector, keeping its state whole', () => {+ const [projected] = projectToolViewModels([toolMessage()], () => undefined);- expect(projectToolViewModels(messages, () => undefined)).toEqual(messages);+ expect(projected.content).toBe('');+ expect(projected.contentLength).toBe('RAW BODY'.length);+ expect(projected.payloadOmitted).toBe('render');+ // State drives the collapsed row and whole-list selectors, which never get+ // an "expand" to hydrate on.+ expect(projected.pluginState).toEqual(toolMessage().pluginState);+ });++ it('leaves a still-streaming row alone β the sentinel IS how it reads as running', () => {+ // `hasToolResultBody` recognises the placeholder only while it sits in+ // `content`; projecting it away would report a running tool as finished.+ const streaming = toolMessage({ content: LOADING_FLAT });++ expect(projectToolViewModels([streaming], () => undefined)[0]).toEqual(streaming);+ });++ it('does not flag an empty result, which has nothing to fetch back', () => {+ const empty = toolMessage({ content: '' });++ expect(projectToolViewModels([empty], () => undefined)[0]).toEqual(empty);+ });++ it('never touches a non-tool message', () => {+ const assistant = toolMessage({ id: 'a', role: 'assistant' });++ expect(projectToolViewModels([assistant], () => undefined)[0]).toEqual(assistant);});it('keeps the original content length after the body is dropped', () => {@@ -58,14 +84,14 @@ describe('projectToolViewModels', () => {expect(projected.payloadOmitted).toBe('render');});- it('does not mark a message as omitted when the projector declines', () => {+ it('respects a projector that declines β it knows the shape, the default does not', () => {const [projected] = projectToolViewModels([toolMessage()],resolveWith(() => undefined),);expect(projected.payloadOmitted).toBeUndefined();- expect(projected.pluginState).toEqual(toolMessage().pluginState);+ expect(projected.content).toBe('RAW BODY');});it('falls back to the stored payload when a projector throws', () => {diff --git a/packages/tool-view-model/src/project.ts b/packages/tool-view-model/src/project.tsindex 50a8a4385df..cd6c93eafd5 100644--- a/packages/tool-view-model/src/project.ts+++ b/packages/tool-view-model/src/project.ts@@ -1,7 +1,8 @@+import { LOADING_FLAT } from '@lobechat/const';import type { UIChatMessage } from '@lobechat/types';import { getToolProjector } from './registry';-import type { ToolProjector } from './types';+import type { ToolProjection, ToolProjector } from './types';/** Resolves the projector for one tool call. Injectable so the pipeline can be* exercised without mutating the process-wide registry. */@@ -10,9 +11,36 @@ export type ProjectorResolver = (apiName?: string | null,) => ToolProjector | undefined;+/**+ * What a tool message without a projector gets.+ *+ * The body is the MODEL's copy of the result. On screen it reaches exactly two+ * surfaces, both of which open on demand and both of which now hydrate: the+ * fallback renderer and the raw/debug viewer. No collapsed row reads it β+ * inspectors take `result.error` and the settled-ness of `result`, never its+ * content β so dropping it costs the list nothing.+ *+ * `pluginState` is deliberately NOT touched here. It is read far outside the+ * expanded card: the collapsed row's own chips, `getBuiltinRenderDisplayControl`+ * deciding whether a card auto-opens, and whole-list selectors+ * (`selectTodosFromMessages`, `selectActivatedToolIdsFromMessages`,+ * `selectActivatedSkillsFromMessages`). Those run before any expansion, so+ * "fetch it back on open" cannot cover them β which is exactly what a per-tool+ * projector is for: it knows which state keys the collapsed row needs.+ */+const BODY_ONLY_PROJECTION: ToolProjection = { content: null, storedPayloadNeededBy: 'render' };+const projectToolMessage = (message: UIChatMessage, resolve: ProjectorResolver): UIChatMessage => {const projector = resolve(message.plugin?.identifier, message.plugin?.apiName);- if (!projector) return message;++ // No projector: keep the state whole and drop just the body β and only when+ // there is a settled body. An empty result would be flagged for a fetch that+ // returns nothing, and the streaming sentinel is the one string whose+ // presence in `content` is how the row is known to be still running.+ if (!projector) {+ const hasSettledBody = !!message.content && message.content !== LOADING_FLAT;+ return hasSettledBody ? applyProjection(message, BODY_ONLY_PROJECTION) : message;+ }let projection;try {@@ -37,6 +65,10 @@ const projectToolMessage = (message: UIChatMessage, resolve: ProjectorResolver):if (!projection) return message;+ return applyProjection(message, projection);+};++const applyProjection = (message: UIChatMessage, projection: ToolProjection): UIChatMessage => {const replacedContent = projection.content !== undefined;const replacedState = projection.pluginState !== undefined;if (!replacedContent && !replacedState) return message;diff --git a/packages/tool-view-model/src/registry.ts b/packages/tool-view-model/src/registry.tsindex d73c2416eba..a9e73ed6154 100644--- a/packages/tool-view-model/src/registry.ts+++ b/packages/tool-view-model/src/registry.ts@@ -8,9 +8,12 @@ import type { ToolProjector } from './types';** 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.+ * where there is no app bootstrap to guarantee registration ran first.+ *+ * A tool missing from here still has its BODY dropped β see+ * `BODY_ONLY_PROJECTION` β and keeps its `pluginState` whole. An entry here is+ * how a tool additionally sheds state, which needs per-tool knowledge of the+ * keys its collapsed row reads.*/const toolProjectors: Record<string, Record<string, ToolProjector>> = {// Every tool below renders through the SAME shared card,diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 0fb5617f132..23b167621da 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -211,6 +211,10 @@ const SKIP_BATCH_PROCEDURES = new Set([...initialLoadProcedures, ...slowProcedurconst LARGE_INPUT_QUERY_PROCEDURES = new Set(['agent.getTransferJobStatus','group.getTransferJobStatus',+ // Takes every projected tool row of a topic at once; ~60 ids already exceed+ // the batched GET's 2083-char budget, and a tool-heavy topic is exactly when+ // it is called.+ 'message.getToolResultPayloads',]);// 3. splitLink to conditionally disable batchingdiff --git a/src/features/Conversation/Messages/Tool/Tool/index.tsx b/src/features/Conversation/Messages/Tool/Tool/index.tsxindex 5faebdb7bc6..5c8bad5f0c2 100644--- a/src/features/Conversation/Messages/Tool/Tool/index.tsx+++ b/src/features/Conversation/Messages/Tool/Tool/index.tsx@@ -115,6 +115,9 @@ const Tool = memo<InspectorProps>(result={result}showCustomToolRender={showCustomToolRender}toolCallId={toolCallId}+ // Without this the render has no row to fetch a projected+ // body back from, and the expanded card stays empty.+ toolMessageId={toolMessage?.id}type={type}/></Flexbox>diff --git a/src/features/ShareModal/ShareJSON/index.tsx b/src/features/ShareModal/ShareJSON/index.tsxindex c85ab65d777..2a8f9e6b647 100644--- a/src/features/ShareModal/ShareJSON/index.tsx+++ b/src/features/ShareModal/ShareJSON/index.tsx@@ -12,6 +12,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';import { useShareData } from '../ShareDataProvider';import { styles } from '../style';+import { useExportMessages } from '../useExportMessages';import { generateFullExport } from './generateFullExport';import { generateMessages } from './generateMessages';import Preview from './Preview';@@ -66,6 +67,9 @@ const ShareJSON = memo(() => {];const { dbMessages, systemRole, title, topic } = useShareData();+ // Tool bodies the read path left on the server would otherwise serialize as+ // empty strings and be lost on re-import β see `useExportMessages`.+ const { isHydrating, isIncomplete, messages: exportMessages } = useExportMessages(dbMessages);// Always include tool messages (includeTool: true)const data =@@ -73,13 +77,13 @@ const ShareJSON = memo(() => {? generateMessages({...fieldValue,includeTool: true,- messages: dbMessages,+ messages: exportMessages,systemRole: systemRole ?? '',}): generateFullExport({...fieldValue,includeTool: true,- messages: dbMessages,+ messages: exportMessages,systemRole: systemRole ?? '',topic: topic ?? undefined,});@@ -92,7 +96,11 @@ const ShareJSON = memo(() => {<><Buttonblock+ // Both actions serialize `content`; until the omitted tool bodies land+ // it is still the projected view, which would export as empty results.+ disabled={isHydrating || isIncomplete}icon={CopyIcon}+ loading={isHydrating}size={isMobile ? undefined : 'large'}type={'primary'}onClick={async () => {@@ -104,6 +112,7 @@ const ShareJSON = memo(() => {</Button><Buttonblock+ disabled={isHydrating || isIncomplete}size={isMobile ? undefined : 'large'}onClick={() => {exportFile(content, `${title}.json`);diff --git a/src/features/ShareModal/ShareText/index.tsx b/src/features/ShareModal/ShareText/index.tsxindex 25513b1710c..f6aef18b61a 100644--- a/src/features/ShareModal/ShareText/index.tsx+++ b/src/features/ShareModal/ShareText/index.tsx@@ -11,6 +11,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';import { useShareData } from '../ShareDataProvider';import { styles } from '../style';+import { useExportMessages } from '../useExportMessages';import Preview from './Preview';import { generateMarkdown } from './template';import { type FieldType } from './type';@@ -62,9 +63,16 @@ const ShareText = memo(() => {];const { displayMessages, systemRole, title } = useShareData();+ // Markdown serializes each tool's `content` too, so the same omitted rows+ // would export as empty code blocks β see `useExportMessages`.+ const {+ isHydrating,+ isIncomplete,+ messages: exportMessages,+ } = useExportMessages(displayMessages);const content = generateMarkdown({...fieldValue,- messages: displayMessages,+ messages: exportMessages,systemRole: systemRole ?? '',title,}).replaceAll('\n\n\n', '\n');@@ -75,7 +83,9 @@ const ShareText = memo(() => {<><Buttonblock+ disabled={isHydrating || isIncomplete}icon={CopyIcon}+ loading={isHydrating}size={isMobile ? undefined : 'large'}type={'primary'}onClick={async () => {@@ -87,6 +97,7 @@ const ShareText = memo(() => {</Button><Buttonblock+ disabled={isHydrating || isIncomplete}size={isMobile ? undefined : 'large'}onClick={() => {exportFile(content, `${title}.md`);diff --git a/src/features/ShareModal/useExportMessages.ts b/src/features/ShareModal/useExportMessages.tsnew file mode 100644index 00000000000..4fa4b657bc1--- /dev/null+++ b/src/features/ShareModal/useExportMessages.ts@@ -0,0 +1,45 @@+import type { UIChatMessage } from '@lobechat/types';+import useSWR from 'swr';++import { messageService } from '@/services/message';+import {+ mergeStoredToolPayloads,+ selectProjectedToolIds,+} from '@/services/message/hydrateProjectedTools';++/**+ * The messages an export may serialize.+ *+ * The store holds render-facing view models, whose tool payloads live on the+ * server until a card asks for them. An export has no card to expand: it+ * serializes what it is handed, calls the result lossless, and import later+ * treats it as authoritative β so a projected row would silently turn a tool+ * result into an empty string, permanently, on the round trip.+ *+ * Restoring them when this tab opens is the right moment: the user asked for+ * the export, and the preview renders from the same value.+ *+ * Only the fetched payload MAP is cached. It is keyed by row id, so it stays+ * valid while the conversation grows; merging happens against the current+ * messages, so a new turn arriving with the modal open is exported too.+ */+export const useExportMessages = (messages: UIChatMessage[]) => {+ const omittedIds = selectProjectedToolIds(messages);++ const { data, isLoading } = useSWR(+ omittedIds.length > 0 ? ['shareExportToolPayloads', ...omittedIds] : null,+ ([, ...ids]: string[]) => messageService.getToolResultPayloads(ids),+ { revalidateOnFocus: false },+ );++ const hydrated = mergeStoredToolPayloads(messages, data);++ // A row we could not restore would serialize as an empty result and import+ // would take it as the truth, so the export stays blocked rather than+ // quietly shipping a lossy file.+ return {+ isHydrating: omittedIds.length > 0 && isLoading,+ isIncomplete: !isLoading && hydrated.missing.length > 0,+ messages: hydrated.messages,+ };+};diff --git a/src/services/message/__tests__/hydrateProjectedTools.test.ts b/src/services/message/__tests__/hydrateProjectedTools.test.tsnew file mode 100644index 00000000000..962435f24b2--- /dev/null+++ b/src/services/message/__tests__/hydrateProjectedTools.test.ts@@ -0,0 +1,115 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import {+ hydrateProjectedToolMessages,+ mergeStoredToolPayloads,+} from '../hydrateProjectedTools';++const msg = (over: Partial<UIChatMessage>): UIChatMessage =>+ ({ content: '', createdAt: 1_780_000_000_000, id: 'm', role: 'user', ...over }) as UIChatMessage;++const projectedTool = (over: Partial<UIChatMessage> = {}) =>+ msg({+ content: '',+ contentLength: 9736,+ id: 't1',+ payloadOmitted: 'render',+ pluginState: { exitCode: 0 },+ role: 'tool',+ tool_call_id: 'call_1',+ ...over,+ });++describe('hydrateProjectedToolMessages', () => {+ it('restores both halves β a projector reduces state as well as the body', () => {+ // An export calls itself lossless; restoring only the body would still ship+ // a command without its stdout or a document without its text.+ const fetchStored = vi.fn().mockResolvedValue({+ t1: { content: 'real output', pluginState: { exitCode: 0, stdout: 'real output' } },+ });++ return hydrateProjectedToolMessages([projectedTool()], fetchStored).then(({ messages }) => {+ expect(messages[0].content).toBe('real output');+ expect(messages[0].pluginState).toEqual({ exitCode: 0, stdout: 'real output' });+ });+ });++ it('asks for every omitted row in one request', async () => {+ const fetchStored = vi.fn().mockResolvedValue({});++ await hydrateProjectedToolMessages(+ [projectedTool(), projectedTool({ id: 't2' }), projectedTool({ id: 't3' })],+ fetchStored,+ );++ expect(fetchStored).toHaveBeenCalledTimes(1);+ expect(fetchStored).toHaveBeenCalledWith(['t1', 't2', 't3']);+ });++ it('reports a row the server did not return instead of passing it off as restored', async () => {+ const fetchStored = vi.fn().mockResolvedValue({ t1: { content: 'ok' } });++ const { messages, missing } = await hydrateProjectedToolMessages(+ [projectedTool(), projectedTool({ id: 't2' })],+ fetchStored,+ );++ expect(missing).toEqual(['t2']);+ expect(messages[1].content).toBe('');+ });++ it('reports every row when the request itself fails', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const fetchStored = vi.fn().mockRejectedValue(new Error('offline'));++ const { messages, missing } = await hydrateProjectedToolMessages(+ [projectedTool()],+ fetchStored,+ );++ expect(missing).toEqual(['t1']);+ expect(messages[0].content).toBe('');+ expect(error).toHaveBeenCalled();+ error.mockRestore();+ });++ it('fetches nothing when no tool body was projected away', async () => {+ const fetchStored = vi.fn();+ const messages = [msg({ content: 'plain', id: 't2', role: 'tool', tool_call_id: 'c2' })];++ const result = await hydrateProjectedToolMessages(messages, fetchStored);++ expect(result).toEqual({ messages, missing: [] });+ expect(fetchStored).not.toHaveBeenCalled();+ });++ it('leaves every other message untouched', async () => {+ const user = msg({ content: 'hi', id: 'u1', role: 'user' });+ const fetchStored = vi.fn().mockResolvedValue({ t1: { content: 'out' } });++ const { messages } = await hydrateProjectedToolMessages([user, projectedTool()], fetchStored);++ expect(messages[0]).toBe(user);+ });+});++describe('mergeStoredToolPayloads', () => {+ it('merges into the messages given NOW, not the ones the fetch saw', () => {+ // The export modal caches the payload map by row id; a turn arriving while+ // it is open must still make it into the file.+ const payloads = { t1: { content: 'restored' } };+ const later = [projectedTool(), msg({ content: 'a new turn', id: 'u2', role: 'user' })];++ const { messages, missing } = mergeStoredToolPayloads(later, payloads);++ expect(messages.map((m) => m.content)).toEqual(['restored', 'a new turn']);+ expect(missing).toEqual([]);+ });++ it('reports every projected row while the map is still absent', () => {+ const { missing } = mergeStoredToolPayloads([projectedTool()], undefined);++ expect(missing).toEqual(['t1']);+ });+});diff --git a/src/services/message/hydrateProjectedTools.ts b/src/services/message/hydrateProjectedTools.tsnew file mode 100644index 00000000000..53e3ac4b530--- /dev/null+++ b/src/services/message/hydrateProjectedTools.ts@@ -0,0 +1,82 @@+import type { UIChatMessage } from '@lobechat/types';++export interface StoredToolPayload {+ content: string;+ pluginState?: unknown;+}++export interface HydratedToolMessages {+ messages: UIChatMessage[];+ /** Ids whose stored payload could not be fetched β the row is still projected. */+ missing: string[];+}++/**+ * Put back the stored payload of every tool message the read path projected+ * away, for the consumers that need the real thing rather than a render.+ *+ * Both halves are restored. Projectors reduce `pluginState` as well as the body+ * β a document loses its text and XML, a command its stdout, a crawl its page β+ * so restoring only the body would still hand a lossy row to an export that+ * calls itself lossless.+ *+ * Failures are reported rather than thrown: a resume replay would rather ship a+ * degraded transcript than lose the user's prompt, while an export must refuse+ * to serialize. `missing` lets each caller pick.+ */+/** Ids of the rows whose stored payload has to be fetched back. */+export const selectProjectedToolIds = (messages: UIChatMessage[] | undefined): string[] =>+ (messages ?? []).filter((m) => m.role === 'tool' && !!m.payloadOmitted).map((m) => m.id);++/**+ * Merge a fetched payload map into the CURRENT messages.+ *+ * Kept separate from the fetch so a caller can cache the map β keyed by row id,+ * and therefore still valid as the conversation grows β while merging against+ * whatever the list looks like now. Caching merged messages instead would pin+ * the whole conversation at the moment of the fetch.+ */+export const mergeStoredToolPayloads = (+ messages: UIChatMessage[],+ payloads: Record<string, StoredToolPayload> | undefined,+): HydratedToolMessages => {+ const ids = selectProjectedToolIds(messages);+ if (ids.length === 0) return { messages, missing: [] };++ const restored = payloads ?? {};++ return {+ messages: messages.map((m) => {+ const payload = restored[m.id];+ if (typeof payload?.content !== 'string') return m;++ return {+ ...m,+ content: payload.content,+ ...(payload.pluginState !== undefined && { pluginState: payload.pluginState }),+ };+ }),+ missing: ids.filter((id) => typeof restored[id]?.content !== 'string'),+ };+};++export const hydrateProjectedToolMessages = async (+ messages: UIChatMessage[] | undefined,+ fetchStoredPayloads: (messageIds: string[]) => Promise<Record<string, StoredToolPayload>>,+): Promise<HydratedToolMessages> => {+ if (!messages?.length) return { messages: messages ?? [], missing: [] };++ const ids = selectProjectedToolIds(messages);+ if (ids.length === 0) return { messages, missing: [] };++ try {+ return mergeStoredToolPayloads(messages, await fetchStoredPayloads(ids));+ } catch (error) {+ console.error(+ '[hydrateProjectedTools] failed to restore %d tool payloads: %O',+ ids.length,+ error,+ );+ return { messages, missing: ids };+ }+};diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex e709acfb7bb..e86d22769a1 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -16,6 +16,7 @@ import {type UpdateMessageResult,} from '@lobechat/types';import { type HeatmapsProps } from '@lobehub/charts';+import pMap from 'p-map';import { lambdaClient } from '@/libs/trpc/client';@@ -100,6 +101,9 @@ const getBatchMutationAbortKey = (operations: MessageBatchOperation[]) => {if (operation.type === 'updateToolMessage') return `tool-message-${operation.id}`;};+/** Matches the `getToolResultPayloads` input cap in the lambda router. */+const TOOL_PAYLOAD_BATCH_SIZE = 500;+export class MessageService {batchMutate = async (operations: MessageBatchOperation[], signal?: AbortSignal) => {const input = {@@ -186,6 +190,31 @@ export class MessageService {return lambdaClient.message.getToolResultPayload.query({ messageId });};+ /**+ * Bulk form, for surfaces that need every omitted row at once (export).+ *+ * Chunked to the endpoint's own cap: a tool-dense topic can hold more+ * projected rows than one request accepts, and the schema would reject the+ * whole set rather than return what it could.+ */+ getToolResultPayloads = async (messageIds: string[]) => {+ const chunks: string[][] = [];+ for (let i = 0; i < messageIds.length; i += TOOL_PAYLOAD_BATCH_SIZE) {+ chunks.push(messageIds.slice(i, i + TOOL_PAYLOAD_BATCH_SIZE));+ }++ const results = await pMap(+ chunks,+ (ids) => lambdaClient.message.getToolResultPayloads.query({ messageIds: ids }),+ { concurrency: 3 },+ );++ return Object.assign({}, ...results) as Record<+ string,+ { content: string; pluginState?: unknown }+ >;+ };+diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {return lambdaClient.message.diagnoseTopic.query(params);};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 312a10a2374..b998151b8ab 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -64,6 +64,7 @@ import {type MessageQueryContext,messageService,} from '@/services/message';+import { hydrateProjectedToolMessages } from '@/services/message/hydrateProjectedTools';import { threadService } from '@/services/thread';import { workService } from '@/services/work';import { topicSelectors } from '@/store/chat/selectors';@@ -86,7 +87,7 @@ import { getNativeHeteroSessionBindingKey } from './heteroResume';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';-import { buildResumeReplayMessages, hydrateProjectedToolMessages } from './resumeReplay';+import { buildResumeReplayMessages, shouldHydrateResumeReplay } from './resumeReplay';import { buildLobeHubSessionEnv } from './sessionEnv';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */@@ -2483,16 +2484,31 @@ export const executeHeterogeneousAgent = async (// it, `--resume <staleId>` dies with "No conversation found with session ID".// Raw rows first: the display map collapses history into virtual// `assistantGroup` rows, which carry no replayable turn.+ const replaySource = (get().dbMessagesMap?.[messageMapKey(context)] ??+ get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined;+// Tool bodies the read path projected away are restored first: this// transcript is written to disk and resumed from, so an emptied tool result// would persist as "this tool returned nothing" for every later turn.+ //+ // Only for Claude Code. Main consumes `resumeReplayMessages` in exactly one+ // place (`HeterogeneousAgentImpl`'s `ensureClaudeCodeResumeTranscript`),+ // which is gated on `agentType === 'claude-code'` and no-ops when the+ // transcript is still on disk. Restoring for the other adapters would spend+ // one authenticated round trip per historical tool, every turn, on a+ // payload nothing reads.const resumeReplayMessages = resumeSessionId? buildResumeReplayMessages(- await hydrateProjectedToolMessages(- (get().dbMessagesMap?.[messageMapKey(context)] ??- get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined,- messageService.getToolResultPayload,- ),+ shouldHydrateResumeReplay(heterogeneousProvider.type)+ ? // A degraded transcript still resumes; a thrown error would lose+ // the prompt, so `missing` is deliberately not acted on here.+ (+ await hydrateProjectedToolMessages(+ replaySource,+ messageService.getToolResultPayloads,+ )+ ).messages+ : replaySource,message,): undefined;diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.tsindex 04c49628955..5685c20457b 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.ts@@ -1,7 +1,7 @@import type { UIChatMessage } from '@lobechat/types';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';-import { buildResumeReplayMessages, hydrateProjectedToolMessages } from './resumeReplay';+import { buildResumeReplayMessages, shouldHydrateResumeReplay } from './resumeReplay';const msg = (over: Partial<UIChatMessage>): UIChatMessage =>({ content: '', createdAt: 1_780_000_000_000, id: 'm', role: 'user', ...over }) as UIChatMessage;@@ -71,56 +71,15 @@ describe('buildResumeReplayMessages', () => {});});-describe('hydrateProjectedToolMessages', () => {- const projectedTool = (over: Partial<UIChatMessage> = {}) =>- msg({- content: '',- contentLength: 9736,- id: 't1',- payloadOmitted: 'render',- role: 'tool',- tool_call_id: 'call_1',- ...over,- });+describe('shouldHydrateResumeReplay', () => {+ it('pays for a restored transcript only where one is actually rebuilt', () => {+ // Main rebuilds a transcript for Claude Code and nothing else; the other+ // adapters are handed the replay and ignore it, so restoring their bodies+ // would be one authenticated round trip per historical tool, every turn.+ expect(shouldHydrateResumeReplay('claude-code')).toBe(true);- it('restores a projected tool body before it is replayed into the transcript', async () => {- // The regression: this transcript is written to disk and resumed from, so- // replaying the emptied body persists "this tool returned nothing".- const fetchStored = vi.fn().mockResolvedValue({ content: 'the real command output' });-- const hydrated = await hydrateProjectedToolMessages([projectedTool()], fetchStored);- const [replayed] = buildResumeReplayMessages(hydrated);-- expect(fetchStored).toHaveBeenCalledWith('t1');- expect(replayed).toMatchObject({ content: 'the real command output', role: 'tool' });- });-- it('fetches nothing when no tool body was projected away', async () => {- const fetchStored = vi.fn();- const messages = [msg({ content: 'plain', id: 't2', role: 'tool', tool_call_id: 'c2' })];-- expect(await hydrateProjectedToolMessages(messages, fetchStored)).toBe(messages);- expect(fetchStored).not.toHaveBeenCalled();- });-- it('replays the trimmed body rather than losing the turn when the fetch fails', async () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {});- const fetchStored = vi.fn().mockRejectedValue(new Error('offline'));-- const hydrated = await hydrateProjectedToolMessages([projectedTool()], fetchStored);-- expect(hydrated?.[0].content).toBe('');- expect(error).toHaveBeenCalled();- error.mockRestore();- });-- it('leaves every other message untouched', async () => {- const user = msg({ content: 'hi', id: 'u1', role: 'user' });- const fetchStored = vi.fn().mockResolvedValue({ content: 'out' });-- const hydrated = await hydrateProjectedToolMessages([user, projectedTool()], fetchStored);-- expect(hydrated?.[0]).toBe(user);- expect(fetchStored).toHaveBeenCalledTimes(1);+ for (const other of ['codex', 'opencode', 'pi', 'droid', undefined]) {+ expect(shouldHydrateResumeReplay(other)).toBe(false);+ }});});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.tsindex cd755673b42..3fbb2e28396 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts@@ -1,50 +1,19 @@import type { HeteroSessionImportMessage, UIChatMessage } from '@lobechat/types';-import pMap from 'p-map';--/** Bounded so rebuilding a long topic's transcript can't stampede the API. */-const HYDRATE_CONCURRENCY = 6;/**- * Restore the stored body of any tool message the read path projected away,- * for the ONE consumer that feeds it back to a model.+ * Is a restored transcript worth paying for on this adapter?*- * Everything else the store drives is a render, which the view model already- * satisfies. A resume replay is different: it rebuilds a transcript that the- * external CLI then resumes from, so an emptied tool result would be written to- * disk and every later turn would read it back as a tool that returned nothing.+ * Main consumes `resumeReplayMessages` in exactly one place β+ * `HeterogeneousAgentImpl`'s `ensureClaudeCodeResumeTranscript` β which is+ * gated on `agentType === 'claude-code'`. Every other adapter is handed the+ * replay and ignores it, so restoring bodies for them would spend one+ * authenticated round trip per historical tool, on every turn, for nothing.*- * Only runs when a GC'd session forces a rebuild, so the fetch cost lands on a- * path that is already doing far more expensive work.+ * Keep this in step with that call site if another adapter starts rebuilding a+ * transcript.*/-export const hydrateProjectedToolMessages = async (- messages: UIChatMessage[] | undefined,- fetchStoredPayload: (messageId: string) => Promise<{ content: string } | undefined | null>,-): Promise<UIChatMessage[] | undefined> => {- if (!messages?.length) return messages;-- const projected = messages.filter((m) => m.role === 'tool' && !!m.payloadOmitted);- if (projected.length === 0) return messages;-- const restored = new Map<string, string>();- await pMap(- projected,- async (m) => {- try {- const payload = await fetchStoredPayload(m.id);- if (typeof payload?.content === 'string') restored.set(m.id, payload.content);- } catch (error) {- // Replay the trimmed body rather than failing the turn: a degraded- // transcript still resumes, a thrown error loses the user's prompt.- console.error('[resumeReplay] failed to restore tool payload %s: %O', m.id, error);- }- },- { concurrency: HYDRATE_CONCURRENCY },- );-- if (restored.size === 0) return messages;-- return messages.map((m) => (restored.has(m.id) ? { ...m, content: restored.get(m.id)! } : m));-};+export const shouldHydrateResumeReplay = (providerType?: string): boolean =>+ providerType === 'claude-code';/*** Map the topic's chat messages into the normalized shape