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.

🐛 fix(hetero): restore projected tool bodies before replaying a transcript (#19694)

Arvin Xu49b635d80cb9
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 41cc44d10ac..312a10a2374 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -86,7 +86,7 @@ import { getNativeHeteroSessionBindingKey } from './heteroResume';
import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';
import { createPendingCreateLedger } from './pendingCreateLedger';
import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';
-import { buildResumeReplayMessages } from './resumeReplay';
+import { buildResumeReplayMessages, hydrateProjectedToolMessages } from './resumeReplay';
import { buildLobeHubSessionEnv } from './sessionEnv';
/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */
@@ -2483,10 +2483,16 @@ 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.
+ // 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.
const resumeReplayMessages = resumeSessionId
? buildResumeReplayMessages(
- (get().dbMessagesMap?.[messageMapKey(context)] ??
- get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined,
+ await hydrateProjectedToolMessages(
+ (get().dbMessagesMap?.[messageMapKey(context)] ??
+ get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined,
+ messageService.getToolResultPayload,
+ ),
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.ts
index 606b209a10d..04c49628955 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 } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
-import { buildResumeReplayMessages } from './resumeReplay';
+import { buildResumeReplayMessages, hydrateProjectedToolMessages } from './resumeReplay';
const msg = (over: Partial<UIChatMessage>): UIChatMessage =>
({ content: '', createdAt: 1_780_000_000_000, id: 'm', role: 'user', ...over }) as UIChatMessage;
@@ -70,3 +70,57 @@ describe('buildResumeReplayMessages', () => {
expect(buildResumeReplayMessages([])).toEqual([]);
});
});
+
+describe('hydrateProjectedToolMessages', () => {
+ const projectedTool = (over: Partial<UIChatMessage> = {}) =>
+ msg({
+ content: '',
+ contentLength: 9736,
+ id: 't1',
+ payloadOmitted: 'render',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ ...over,
+ });
+
+ 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);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts
index 2cae804721f..cd755673b42 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts
@@ -1,4 +1,50 @@
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.
+ *
+ * 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.
+ *
+ * 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.
+ */
+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));
+};
/**
* Map the topic's chat messages into the normalized shape