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.

⚡️ perf(agent): skip compression-group members in runtime topic reads (#23148)

YuTengjing55c24e8fb623
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.ts
index 0a627000000..bdd49730716 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.ts
@@ -258,7 +258,10 @@ describe('AgentRuntimeService.executeStep - message patches across inline steps'
await service.executeStep(inlineStep(2, { deferredMessagePatch: patch }));
- expect(queryUiMessages).toHaveBeenCalledWith(patch.state, { skipWorks: true });
+ expect(queryUiMessages).toHaveBeenCalledWith(patch.state, {
+ skipCompressedMembers: true,
+ skipWorks: true,
+ });
const patchAt = indexOf('message_patch', 1);
expect(patchAt).toBeLessThan(indexOf('step_start', 2));
expect(events()[patchAt].data).toMatchObject({
@@ -291,6 +294,7 @@ describe('AgentRuntimeService.executeStep - message patches across inline steps'
expect(result.nextStepScheduled).toBe(true);
expect(result.deferredMessagePatch).toBeUndefined();
expect(queryUiMessages).toHaveBeenCalledWith(expect.objectContaining({ stepCount: 2 }), {
+ skipCompressedMembers: true,
skipWorks: true,
});
const patchAt = indexOf('message_patch', 1);
@@ -458,3 +462,73 @@ describe('AgentRuntimeService.scheduleContinuation - handed-back message patch',
expect(queueService.scheduleMessage).toHaveBeenCalledTimes(1);
});
});
+
+describe('AgentRuntimeService.executeStep - compression groups in step reads', () => {
+ const group = (content: string, compressedMessages: UIChatMessage[] = []) =>
+ ({ ...row('g1', content, 'compressedGroup'), compressedMessages }) as UIChatMessage;
+ const member = row('m1', 'ORIGINAL MESSAGE');
+
+ const patches = (events: () => any[]) =>
+ events()
+ .filter((event) => event.type === 'message_patch')
+ .map((event) => event.data);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ stubRunningDurableOperation();
+ process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';
+ });
+
+ afterEach(() => {
+ delete process.env.AGENT_RUNTIME_BASE_URL;
+ });
+
+ it('reads without members only for a run that receives message patches', async () => {
+ const { coordinator, query, service } = buildService();
+ coordinator.loadAgentState
+ .mockResolvedValueOnce(runState())
+ .mockResolvedValueOnce(runState({ host: {} }));
+
+ await service.executeStep(inlineStep(1));
+ await service.executeStep(inlineStep(1));
+
+ expect(query.mock.calls[0][0]).toMatchObject({ skipCompressedMembers: true });
+ expect(query.mock.calls[1][0]).toMatchObject({ skipCompressedMembers: false });
+ });
+
+ it('ships a group the step changed with its members', async () => {
+ const { coordinator, events, query, queryUiMessages, service } = buildService();
+ coordinator.loadAgentState.mockResolvedValueOnce(runState({ stepCount: 2 }));
+ query.mockResolvedValueOnce([group('new summary')]);
+ queryUiMessages.mockResolvedValueOnce([group('new summary', [member])]);
+
+ await service.executeStep(
+ inlineStep(2, {
+ deferredMessagePatch: { ...pendingPatch(), before: [group('old summary')] },
+ }),
+ );
+
+ expect(queryUiMessages).toHaveBeenCalledWith(expect.anything(), { skipWorks: true });
+ const [patch] = patches(events);
+ expect(patch.upserts).toHaveLength(1);
+ expect(patch.upserts[0].message).toMatchObject({
+ compressedMessages: [member],
+ content: 'new summary',
+ });
+ });
+
+ it('ships no patch when the members cannot be read', async () => {
+ const { coordinator, events, query, queryUiMessages, service } = buildService();
+ coordinator.loadAgentState.mockResolvedValueOnce(runState({ stepCount: 2 }));
+ query.mockResolvedValueOnce([group('new summary')]);
+ queryUiMessages.mockResolvedValueOnce(undefined);
+
+ await service.executeStep(
+ inlineStep(2, {
+ deferredMessagePatch: { ...pendingPatch(), before: [group('old summary')] },
+ }),
+ );
+
+ expect(patches(events).filter((patch) => patch.revision === 2)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.ts
index c08d6d2b848..15fe63ec225 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.ts
@@ -1,7 +1,12 @@
+import type { MessagePatchData } from '@lobechat/agent-gateway-client';
import type { AgentState } from '@lobechat/agent-runtime';
import type { UIChatMessage } from '@lobechat/types';
-import { buildProjectedMessagePatch } from '../../messagePatch';
+import {
+ buildProjectedMessagePatch,
+ fillCompressedGroupUpserts,
+ hasCompressedGroupUpsert,
+} from '../../messagePatch';
import type { DeferredMessagePatch } from '../../types';
import type { AgentRuntimeServiceContext } from '../types';
@@ -26,6 +31,11 @@ export const stepMessagesScopeKey = (state: AgentState): string =>
* 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.
+ *
+ * Both sides leave compression-group members out, so a group the step created
+ * or changed (a compression) is read once more with its members, from `state`,
+ * before it ships. Nothing ships when that read fails, as when either side
+ * could not be read.
*/
export async function publishStepMessagePatch(
deps: StepMessagePatchDeps,
@@ -33,16 +43,29 @@ export async function publishStepMessagePatch(
after,
before,
operationId,
+ state,
stepIndex,
}: {
after: UIChatMessage[];
before: UIChatMessage[];
operationId: string;
+ state: AgentState;
stepIndex: number;
},
): Promise<void> {
+ let patch: MessagePatchData | undefined = buildProjectedMessagePatch(
+ before,
+ after,
+ stepIndex + 1,
+ );
+ if (hasCompressedGroupUpsert(patch)) {
+ const withMembers = await deps.queryUiMessages(state, { skipWorks: true });
+ patch = withMembers && fillCompressedGroupUpserts(patch, withMembers);
+ }
+ if (!patch) return;
+
await deps.streamManager.publishStreamEvent(operationId, {
- data: buildProjectedMessagePatch(before, after, stepIndex + 1),
+ data: patch,
stepIndex,
type: 'message_patch',
});
@@ -68,13 +91,14 @@ export async function publishDeferredMessagePatch(
const after =
entry?.uiMessages && entry.scopeKey === patch.scopeKey
? entry.uiMessages
- : await deps.queryUiMessages(patch.state, { skipWorks: true });
+ : await deps.queryUiMessages(patch.state, { skipCompressedMembers: true, skipWorks: true });
if (!after) return;
await publishStepMessagePatch(deps, {
after,
before: patch.before,
operationId,
+ state: patch.state,
stepIndex: patch.stepIndex,
});
} catch (error) {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
index 365082d2e52..191e72b261e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
@@ -245,7 +245,9 @@ export async function saveAndPublishStep(
stepIndex,
};
} else {
+ // Without group members, like the entry read it is diffed against.
const settledUiMessages = await deps.queryUiMessages(stepResult.newState, {
+ skipCompressedMembers: true,
skipWorks: shouldContinue,
});
if (settledUiMessages) {
@@ -253,6 +255,7 @@ export async function saveAndPublishStep(
after: settledUiMessages,
before: stepStartUiMessages,
operationId,
+ state: stepResult.newState,
stepIndex,
});
}
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts
index 4b98ad666f1..396e31bceaf 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts
@@ -42,6 +42,8 @@ export async function queryUiMessages(
* rendered works when applying a skipped snapshot (`preserveWorks`).
*/
skipWorks?: boolean;
+ /** See `QueryMessageParams.skipCompressedMembers`. */
+ skipCompressedMembers?: boolean;
},
): Promise<UIChatMessage[] | undefined> {
const agentId: string | undefined = agentState?.origin?.agentId;
@@ -78,6 +80,7 @@ export async function queryUiMessages(
agentId,
groupId,
...(includeFileWorks && { includeFileWorks: true }),
+ ...(options?.skipCompressedMembers && { skipCompressedMembers: true }),
skipWorks: options?.skipWorks,
threadId,
topicId,
@@ -139,6 +142,8 @@ export async function queryMessagesFromDB(deps: MessagesDeps, state: AgentState)
// and returns no group messages — the next LLM step then gets an empty
// context and the provider rejects it ("at least one message is required").
groupId: state.origin?.groupId,
+ // The model sees a compression group only as its summary.
+ skipCompressedMembers: true,
threadId: state.origin?.threadId,
topicId: state.origin?.topicId,
},
@@ -244,10 +249,17 @@ export async function queryStepEntryMessages(
try {
// Keep full tool payloads and raw attachment paths. Each consumer derives
// its own view; mid-stream Work summaries are not used by the runtime.
+ //
+ // A protocol-2 run leaves compression-group members out: the model sees a
+ // group only as its summary, and this read never reaches the client whole —
+ // only the message patch diffed against it does, which fills in the members
+ // of a group the step changed (`publishStepMessagePatch`). A protocol-1 run
+ // pushes this read as the `step_start` snapshot, so it keeps them.
messages = await deps.messageModel.query(
{
agentId: state.origin.agentId,
groupId: state.origin.groupId,
+ skipCompressedMembers: usesGatewayMessagePatch(state),
skipWorks: true,
threadId: state.origin.threadId,
topicId: state.origin.topicId,
diff --git a/apps/server/src/services/agentRuntime/messagePatch.test.ts b/apps/server/src/services/agentRuntime/messagePatch.test.ts
index aa57f4d542f..da6f2a4b3d9 100644
--- a/apps/server/src/services/agentRuntime/messagePatch.test.ts
+++ b/apps/server/src/services/agentRuntime/messagePatch.test.ts
@@ -1,7 +1,12 @@
import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { buildMessagePatch, buildProjectedMessagePatch } from './messagePatch';
+import {
+ buildMessagePatch,
+ buildProjectedMessagePatch,
+ fillCompressedGroupUpserts,
+ hasCompressedGroupUpsert,
+} from './messagePatch';
const message = (id: string, content: string): UIChatMessage =>
({ content, createdAt: 1, id, role: 'assistant', updatedAt: 1 }) as UIChatMessage;
@@ -80,3 +85,50 @@ describe('buildProjectedMessagePatch', () => {
expect(patch.deletes).toEqual([]);
});
});
+
+describe('fillCompressedGroupUpserts', () => {
+ const group = (id: string, content: string, compressedMessages: UIChatMessage[] = []) =>
+ ({ ...message(id, content), compressedMessages, role: 'compressedGroup' }) as UIChatMessage;
+ const crawlRow = {
+ content: 'THE WHOLE CRAWLED PAGE',
+ createdAt: 1,
+ id: 't1',
+ plugin: { apiName: 'crawlSinglePage', arguments: '{}', identifier: 'lobe-web-browsing' },
+ pluginState: { results: [] },
+ role: 'tool',
+ updatedAt: 1,
+ } as UIChatMessage;
+
+ it('ships a changed group with its members, projected, and leaves other rows as diffed', () => {
+ // Member-less on both sides: only the group the step changed is upserted.
+ const before = [group('g1', 'old summary'), message('m1', 'old')];
+ const after = [group('g1', 'new summary'), message('m1', 'new')];
+ const patch = buildProjectedMessagePatch(before, after, 3);
+ expect(hasCompressedGroupUpsert(patch)).toBe(true);
+
+ const filled = fillCompressedGroupUpserts(patch, [
+ group('g1', 'new summary', [message('a', 'member'), crawlRow]),
+ message('m1', 'new'),
+ ]);
+
+ expect(filled?.revision).toBe(3);
+ expect(filled?.upserts.map((upsert) => upsert.afterId)).toEqual([null, 'g1']);
+ const members = filled!.upserts[0].message.compressedMessages!;
+ expect(members.map((member) => member.id)).toEqual(['a', 't1']);
+ expect(members[1].content).not.toContain('THE WHOLE CRAWLED PAGE');
+ expect(filled?.upserts[1]).toEqual(patch.upserts[1]);
+ });
+
+ it('ships no group when the members read lacks it', () => {
+ const patch = buildProjectedMessagePatch([], [group('g1', 'summary')], 1);
+
+ expect(fillCompressedGroupUpserts(patch, [])).toBeUndefined();
+ });
+
+ it('has nothing to fill when no group changed', () => {
+ const before = [group('g1', 'summary'), message('m1', 'old')];
+ const after = [group('g1', 'summary'), message('m1', 'new')];
+
+ expect(hasCompressedGroupUpsert(buildProjectedMessagePatch(before, after, 2))).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/messagePatch.ts b/apps/server/src/services/agentRuntime/messagePatch.ts
index 25f53d51116..2317dc8e67b 100644
--- a/apps/server/src/services/agentRuntime/messagePatch.ts
+++ b/apps/server/src/services/agentRuntime/messagePatch.ts
@@ -52,3 +52,39 @@ export const buildProjectedMessagePatch = (
revision: number,
): MessagePatchData =>
buildMessagePatch(projectToolViewModels(before), projectToolViewModels(after), revision);
+
+/**
+ * Swap each upserted `compressedGroup` envelope for its copy in `withMembers`,
+ * projected like the rest of the patch.
+ *
+ * A protocol-2 run reads the topic without compression-group members (see
+ * `queryStepEntryMessages`), so both sides of the diff carry member-less envelopes
+ * and an untouched group never ships. A group the step created or changed
+ * does ship, and the client replaces its copy with whatever the patch holds:
+ * sent as read, the group would lose the original messages the client shows
+ * when it is expanded. Undefined when `withMembers` lacks one of them.
+ */
+export const fillCompressedGroupUpserts = (
+ patch: MessagePatchData,
+ withMembers: UIChatMessage[],
+): MessagePatchData | undefined => {
+ const byId = new Map(withMembers.map((message) => [message.id, message]));
+ const upserts: MessagePatchData['upserts'] = [];
+
+ for (const upsert of patch.upserts) {
+ if (upsert.message.role !== 'compressedGroup') {
+ upserts.push(upsert);
+ continue;
+ }
+
+ const filled = byId.get(upsert.message.id);
+ if (!filled) return undefined;
+ upserts.push({ ...upsert, message: projectToolViewModels([filled])[0] });
+ }
+
+ return { ...patch, upserts };
+};
+
+/** Whether {@link fillCompressedGroupUpserts} has anything to fill. */
+export const hasCompressedGroupUpsert = (patch: MessagePatchData): boolean =>
+ patch.upserts.some((upsert) => upsert.message.role === 'compressedGroup');
diff --git a/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.ts b/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.ts
index c584669c8aa..f05d6d55c11 100644
--- a/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.ts
+++ b/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.ts
@@ -8,6 +8,7 @@ import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
import {
MAX_COMPRESSED_GROUP_MEMBERS,
+ planMessageGroupHydration,
selectCompressedGroupMembers,
} from '../../message/groupNodes';
@@ -230,6 +231,244 @@ describe('MessageModel.query compression group member cap', () => {
});
});
+ describe('skipCompressedMembers', () => {
+ const seedGroup = async () => {
+ const at = (s: number) => new Date(Date.parse('2024-01-01T00:00:00Z') + s * 1000);
+ await serverDB.insert(messages).values([
+ {
+ content: 'MEMBER QUESTION',
+ createdAt: at(0),
+ favorite: true,
+ id: 'sk-1',
+ role: 'user',
+ topicId,
+ userId,
+ },
+ {
+ content: 'MEMBER ANSWER',
+ createdAt: at(1),
+ id: 'sk-2',
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ {
+ content: 'MEMBER TOOL RESULT',
+ createdAt: at(2),
+ id: 'sk-3',
+ role: 'tool',
+ topicId,
+ userId,
+ },
+ {
+ content: 'MEMBER FOLLOW-UP',
+ createdAt: at(3),
+ id: 'sk-4',
+ role: 'user',
+ topicId,
+ userId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ apiName: 'activateTools',
+ id: 'sk-3',
+ identifier: 'lobe-activator',
+ state: { activatedTools: [{ identifier: 'lobe-task' }] },
+ userId,
+ });
+ await serverDB.insert(messageGroups).values({
+ content: 'Summary of the group',
+ createdAt: at(4),
+ id: 'sk-group',
+ topicId,
+ type: MessageGroupType.Compression,
+ userId,
+ });
+ await serverDB.update(messages).set({ messageGroupId: 'sk-group' });
+ // A mainline message after the group, which the option leaves alone.
+ await serverDB.insert(messages).values({
+ content: 'MAINLINE AFTER',
+ createdAt: at(5),
+ id: 'sk-main',
+ parentId: 'sk-4',
+ role: 'user',
+ topicId,
+ userId,
+ });
+ };
+
+ it('should keep the summary, member ids and runtime state but no member content', async () => {
+ await seedGroup();
+
+ const result = await messageModel.query({ skipCompressedMembers: true, topicId });
+ const node = result.find((m) => m.role === 'compressedGroup') as any;
+
+ expect(node).toMatchObject({
+ compressedOmittedIds: ['sk-1', 'sk-2', 'sk-3', 'sk-4'],
+ compressedTurnCount: 2,
+ content: 'Summary of the group',
+ lastMessageId: 'sk-4',
+ pinnedMessages: [],
+ });
+ // Only the state-bearing member, as a flat tool row without content.
+ expect(node.compressedMessages).toHaveLength(1);
+ expect(node.compressedMessages[0]).toMatchObject({
+ content: '',
+ id: 'sk-3',
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },
+ role: 'tool',
+ });
+ expect(JSON.stringify(node)).not.toContain('MEMBER');
+
+ expect(result.find((m) => m.id === 'sk-main')?.content).toBe('MAINLINE AFTER');
+ });
+
+ it('should hydrate a group whose branches carry runtime state, keeping only the active branch', async () => {
+ const at = (s: number) => new Date(Date.parse('2024-01-01T00:00:00Z') + s * 1000);
+ const todos = (text: string) => ({
+ todos: { items: [{ status: 'todo', text }], updatedAt: '2024-01-01T00:00:00.000Z' },
+ });
+ // The user regenerated the reply, then switched back to the first branch.
+ await serverDB.insert(messages).values([
+ {
+ content: 'BRANCH QUESTION',
+ createdAt: at(0),
+ id: 'br-u',
+ metadata: { activeBranchIndex: 0 },
+ role: 'user',
+ topicId,
+ userId,
+ },
+ {
+ content: 'ACTIVE ANSWER',
+ createdAt: at(1),
+ id: 'br-a1',
+ parentId: 'br-u',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'createTodos',
+ arguments: '{}',
+ id: 'call-1',
+ identifier: 'lobe-gtd',
+ type: 'builtin',
+ },
+ ],
+ topicId,
+ userId,
+ },
+ {
+ content: '',
+ createdAt: at(2),
+ id: 'br-t1',
+ parentId: 'br-a1',
+ role: 'tool',
+ topicId,
+ userId,
+ },
+ {
+ content: 'ABANDONED ANSWER',
+ createdAt: at(3),
+ id: 'br-a2',
+ parentId: 'br-u',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'createTodos',
+ arguments: '{}',
+ id: 'call-2',
+ identifier: 'lobe-gtd',
+ type: 'builtin',
+ },
+ ],
+ topicId,
+ userId,
+ },
+ {
+ content: '',
+ createdAt: at(4),
+ id: 'br-t2',
+ parentId: 'br-a2',
+ role: 'tool',
+ topicId,
+ userId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values([
+ {
+ apiName: 'createTodos',
+ id: 'br-t1',
+ identifier: 'lobe-gtd',
+ state: todos('ACTIVE TODO'),
+ toolCallId: 'call-1',
+ userId,
+ },
+ {
+ apiName: 'createTodos',
+ id: 'br-t2',
+ identifier: 'lobe-gtd',
+ state: todos('ABANDONED TODO'),
+ toolCallId: 'call-2',
+ userId,
+ },
+ ]);
+ await serverDB.insert(messageGroups).values({
+ content: 'Summary of the branched group',
+ createdAt: at(5),
+ id: 'br-group',
+ topicId,
+ type: MessageGroupType.Compression,
+ userId,
+ });
+ await serverDB.update(messages).set({ messageGroupId: 'br-group' });
+
+ const result = await messageModel.query({ skipCompressedMembers: true, topicId });
+ const node = result.find((m) => m.role === 'compressedGroup') as any;
+ const serialized = JSON.stringify(node.compressedMessages);
+
+ expect(node.compressedOmittedIds).toBeUndefined();
+ expect(serialized).toContain('ACTIVE TODO');
+ expect(serialized).not.toContain('ABANDONED TODO');
+ });
+
+ it('should still skip a branched group that carries no runtime state', () => {
+ const record = (id: string, role: string, parentBranches: boolean) => ({
+ carriesTodos: false,
+ favorite: null,
+ id,
+ messageGroupId: 'g',
+ parentBranches,
+ pluginApiName: null,
+ pluginIdentifier: null,
+ role,
+ });
+ const plan = planMessageGroupHydration(
+ [{ id: 'g', type: MessageGroupType.Compression }],
+ [
+ record('u', 'user', false),
+ record('a1', 'assistant', true),
+ record('a2', 'assistant', true),
+ ],
+ true,
+ );
+
+ expect(plan.idsToHydrate).toEqual([]);
+ expect(plan.hydratedByGroup.get('g')).toEqual([]);
+ });
+
+ it('should still hydrate the members without the option', async () => {
+ await seedGroup();
+
+ const result = await messageModel.query({ topicId });
+ const node = result.find((m) => m.role === 'compressedGroup') as any;
+
+ expect(node.compressedOmittedIds).toBeUndefined();
+ expect(node.pinnedMessages.map((m: any) => m.id)).toEqual(['sk-1']);
+ expect(JSON.stringify(node.compressedMessages)).toContain('MEMBER ANSWER');
+ });
+ });
+
describe('selectCompressedGroupMembers', () => {
const rows = (roles: string[]) => roles.map((role, i) => ({ id: String(i), role }));
diff --git a/packages/database/src/models/message/groupNodes.ts b/packages/database/src/models/message/groupNodes.ts
index 7543d5d00fd..0196eecc224 100644
--- a/packages/database/src/models/message/groupNodes.ts
+++ b/packages/database/src/models/message/groupNodes.ts
@@ -41,12 +41,26 @@ export const compressedStateMarkerColumns = {
pluginIdentifier: messagePlugins.identifier,
};
+/**
+ * Column the light member select adds for `skipCompressedMembers` reads only.
+ * A window over the selected rows, so it sees exactly the members the plan does.
+ */
+export const compressedBranchMarkerColumns = {
+ parentBranches: sql<boolean>`count(*) filter (where ${messages.role} <> 'tool' and ${messages.parentId} is not null) over (partition by ${messages.messageGroupId}, ${messages.parentId}) > 1`,
+};
+
/** The light per-member row read before any member is hydrated. */
export interface MessageGroupMemberRecord {
carriesTodos: boolean | null;
favorite: boolean | null;
id: string;
messageGroupId: string | null;
+ /**
+ * The row's parent has more than one non-tool child in the group: the group
+ * holds a branch point, such as a regenerated reply. Selected only for
+ * `skipCompressedMembers` reads.
+ */
+ parentBranches?: boolean | null;
pluginApiName: string | null;
pluginIdentifier: string | null;
role: string | null;
@@ -98,6 +112,14 @@ export interface MessageGroupHydrationPlan {
export const planMessageGroupHydration = (
groups: Pick<MessageGroupRow, 'id' | 'type'>[],
records: MessageGroupMemberRecord[],
+ /**
+ * Hydrate no compression member, pinned ones included: every member is
+ * omitted, and those carrying runtime state keep only their plugin state.
+ * A group holding both a branch point and runtime state still hydrates as
+ * without the option: `parse()` keeps only the active branch, while flat
+ * state rows would also restore todos and activations from abandoned branches.
+ */
+ skipCompressedMembers = false,
): MessageGroupHydrationPlan => {
const recordsByGroup = new Map<string, MessageGroupMemberRecord[]>();
for (const record of records) {
@@ -114,12 +136,24 @@ export const planMessageGroupHydration = (
for (const group of groups) {
const groupRecords = recordsByGroup.get(group.id) ?? [];
const isCompression = group.type === MessageGroupType.Compression;
- const hydrated = isCompression ? selectCompressedGroupMembers(groupRecords) : groupRecords;
+ const skipMembers =
+ skipCompressedMembers &&
+ !(
+ groupRecords.some((record) => record.parentBranches === true) &&
+ groupRecords.some(carriesRuntimeState)
+ );
+ const hydrated = !isCompression
+ ? groupRecords
+ : skipMembers
+ ? []
+ : selectCompressedGroupMembers(groupRecords);
hydratedByGroup.set(group.id, hydrated);
for (const record of hydrated) ids.add(record.id);
if (!isCompression) continue;
- for (const record of groupRecords) if (record.favorite) ids.add(record.id);
+ if (!skipMembers) {
+ for (const record of groupRecords) if (record.favorite) ids.add(record.id);
+ }
const omitted = groupRecords.slice(0, groupRecords.length - hydrated.length);
const stateRecords = omitted.filter(carriesRuntimeState);
stateByGroup.set(group.id, stateRecords);
diff --git a/packages/database/src/models/message/query.ts b/packages/database/src/models/message/query.ts
index 246ead29165..e112c03d152 100644
--- a/packages/database/src/models/message/query.ts
+++ b/packages/database/src/models/message/query.ts
@@ -105,6 +105,7 @@ export class MessageConversationQueries extends MessageScope {
includeFileWorks,
pageSize = 1000,
sessionId,
+ skipCompressedMembers,
skipWorks,
topicId,
groupId,
@@ -206,6 +207,7 @@ export class MessageConversationQueries extends MessageScope {
includeFileWorks,
pageSize,
postProcessUrl: options.postProcessUrl,
+ skipCompressedMembers,
skipWorks,
timing,
topicId: topicId ?? undefined,
@@ -236,6 +238,7 @@ export class MessageConversationQueries extends MessageScope {
includeFileWorks,
pageSize,
postProcessUrl: options.postProcessUrl,
+ skipCompressedMembers,
skipWorks,
timing,
topicId: topicId ?? undefined,
@@ -270,6 +273,7 @@ export class MessageConversationQueries extends MessageScope {
includeFileWorks,
pageSize,
postProcessUrl: options.postProcessUrl,
+ skipCompressedMembers,
skipWorks,
timing,
topicId: topicId ?? undefined,
diff --git a/packages/database/src/models/message/queryByIds.ts b/packages/database/src/models/message/queryByIds.ts
index b9f4e2618ea..0d32f6dc028 100644
--- a/packages/database/src/models/message/queryByIds.ts
+++ b/packages/database/src/models/message/queryByIds.ts
@@ -39,6 +39,7 @@ import {
} from './attachments';
import {
buildMessageGroupNode,
+ compressedBranchMarkerColumns,
compressedStateMarkerColumns,
loadCompressedStateRows,
planMessageGroupHydration,
@@ -389,7 +390,12 @@ export class MessageByIdsQueries extends MessageScope {
file: { fileType: string; id?: string | null },
) => Promise<string>,
timing?: ModelTimingContext,
- options: { allowShareVisitor?: boolean; window?: MessageGroupNodeWindow } = {},
+ options: {
+ allowShareVisitor?: boolean;
+ /** See `QueryMessageParams.skipCompressedMembers`. */
+ skipCompressedMembers?: boolean;
+ window?: MessageGroupNodeWindow;
+ } = {},
): Promise<UIChatMessage[]> => {
// Effective visitor gate — see `queryMessageGroupNodesForPage`. Absent
// this predicate, a creator's default `query({ topicId })` on a visitor
@@ -450,6 +456,7 @@ export class MessageByIdsQueries extends MessageScope {
id: messages.id,
messageGroupId: messages.messageGroupId,
...compressedStateMarkerColumns,
+ ...(options.skipCompressedMembers && compressedBranchMarkerColumns),
role: messages.role,
})
.from(messages)
@@ -473,8 +480,13 @@ export class MessageByIdsQueries extends MessageScope {
});
// A compression group only hydrates its newest members (see
- // `MAX_COMPRESSED_GROUP_MEMBERS`) plus the pinned ones.
- const plan = planMessageGroupHydration(groups, groupMessageRecords);
+ // `MAX_COMPRESSED_GROUP_MEMBERS`) plus the pinned ones, or none at all
+ // with `skipCompressedMembers`.
+ const plan = planMessageGroupHydration(
+ groups,
+ groupMessageRecords,
+ options.skipCompressedMembers,
+ );
// 3. Query full message data using queryByIds (reuses all transformation logic),
// and only the plugin state of omitted members that carry runtime state
diff --git a/packages/database/src/models/message/queryWithWhere.ts b/packages/database/src/models/message/queryWithWhere.ts
index 5fd77cccb76..93df59e0640 100644
--- a/packages/database/src/models/message/queryWithWhere.ts
+++ b/packages/database/src/models/message/queryWithWhere.ts
@@ -61,6 +61,7 @@ export class MessagePageQueries extends MessageScope {
includeFileWorks,
pageSize = 1000,
postProcessUrl,
+ skipCompressedMembers,
skipWorks,
topicId,
timing,
@@ -214,6 +215,7 @@ export class MessagePageQueries extends MessageScope {
current,
hasBeforeCursor: !!before,
postProcessUrl,
+ skipCompressedMembers,
result,
timing,
topicId,
@@ -391,6 +393,7 @@ export class MessagePageQueries extends MessageScope {
result,
timing,
topicId,
+ skipCompressedMembers,
window,
}: {
/**
@@ -419,6 +422,8 @@ export class MessagePageQueries extends MessageScope {
timing?: ModelTimingContext;
topicId?: string;
/** Explicit group window (cursor pagination); overrides the row-derived one. */
+ /** See `QueryMessageParams.skipCompressedMembers`. */
+ skipCompressedMembers?: boolean;
window?: MessageGroupNodeWindow;
}): Promise<UIChatMessage[]> => {
if (!topicId) return [];
@@ -430,6 +435,7 @@ export class MessagePageQueries extends MessageScope {
() =>
this.byIds.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {
allowShareVisitor,
+ skipCompressedMembers,
window,
}),
{ current, hasMessages: result.length > 0, topicId },
@@ -445,6 +451,7 @@ export class MessagePageQueries extends MessageScope {
() =>
this.byIds.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {
allowShareVisitor,
+ skipCompressedMembers,
}),
{ current, hasMessages: false, topicId },
);
@@ -457,6 +464,7 @@ export class MessagePageQueries extends MessageScope {
() =>
this.byIds.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {
allowShareVisitor,
+ skipCompressedMembers,
}),
{ current, hasMessages: true, topicId },
);
@@ -477,7 +485,7 @@ export class MessagePageQueries extends MessageScope {
},
postProcessUrl,
timing,
- { allowShareVisitor },
+ { allowShareVisitor, skipCompressedMembers },
),
{ current, hasMessages: true, topicId },
);
diff --git a/packages/database/src/models/message/types.ts b/packages/database/src/models/message/types.ts
index 866501efd4e..c790f1e2996 100644
--- a/packages/database/src/models/message/types.ts
+++ b/packages/database/src/models/message/types.ts
@@ -71,6 +71,8 @@ export interface QueryMessagesOptions {
path: string | null,
file: { fileType: string; id?: string | null },
) => Promise<string>;
+ /** See `QueryMessageParams.skipCompressedMembers`. */
+ skipCompressedMembers?: boolean;
/**
* Skip the Work-summary assembly (see `QueryMessageParams.skipWorks`).
*/
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index 237b76bc878..43512d94ed9 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -42,6 +42,15 @@ export interface QueryMessageParams {
includeFileWorks?: boolean;
pageSize?: number;
sessionId?: string | null;
+ /**
+ * Load no compression-group member in full. A `compressedGroup` node keeps
+ * its summary, every member id (`compressedOmittedIds`) and the members that
+ * carry runtime state as flat `tool` rows, but no message content. A group
+ * otherwise loads its newest 300 members in full, often most of a long
+ * topic's bytes. For readers that use only the summary, such as the agent
+ * runtime's model context.
+ */
+ skipCompressedMembers?: boolean;
/**
* Skip the Work-summary assembly (`message.works`). Mid-stream refetches
* (tool_end / step_complete / step_start snapshots) set this so each tool