π€― 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
π fix(message): cap compression-group members hydrated by getMessages (#21074)
Arvin Xu7e93a461019a
diff --git a/apps/server/src/routers/lambda/_helpers/getMessagesPageSize.test.ts b/apps/server/src/routers/lambda/_helpers/getMessagesPageSize.test.tsnew file mode 100644index 00000000000..445fa1140ce--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/getMessagesPageSize.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { getMessagesPageSizeSchema, MAX_GET_MESSAGES_PAGE_SIZE } from './getMessagesPageSize';++describe('getMessagesPageSizeSchema', () => {+ it('keeps an absent page size absent so the model default applies', () => {+ expect(getMessagesPageSizeSchema.parse(undefined)).toBeUndefined();+ });++ it('passes a page size within the cap through', () => {+ expect(getMessagesPageSizeSchema.parse(200)).toBe(200);+ });++ it('clamps an oversized page size instead of rejecting it', () => {+ expect(getMessagesPageSizeSchema.parse(50_000)).toBe(MAX_GET_MESSAGES_PAGE_SIZE);+ });++ it('raises a non-positive page size to one', () => {+ expect(getMessagesPageSizeSchema.parse(0)).toBe(1);+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/getMessagesPageSize.ts b/apps/server/src/routers/lambda/_helpers/getMessagesPageSize.tsnew file mode 100644index 00000000000..7d1bf1a30ed--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/getMessagesPageSize.ts@@ -0,0 +1,14 @@+import { z } from 'zod';++/**+ * Upper bound on rows per `getMessages` page (the model's default). Clamped, not+ * rejected: already-shipped clients must keep loading rather than get a 400.+ */+export const MAX_GET_MESSAGES_PAGE_SIZE = 1000;++export const getMessagesPageSizeSchema = z+ .number()+ .optional()+ .transform((value) =>+ value === undefined ? undefined : Math.min(Math.max(value, 1), MAX_GET_MESSAGES_PAGE_SIZE),+ );diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 830d364c222..c3a2950ab22 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -32,6 +32,7 @@ import {assertCanUseTopicTargets,assertCanViewMessageTargets,} from './_helpers/conversationResourceGuard';+import { getMessagesPageSizeSchema } from './_helpers/getMessagesPageSize';import { messagesByCursorInputSchema, readMessagesByCursor } from './_helpers/messagesByCursor';import { projectSharedTopicMessages } from './_helpers/projectSharedTopicMessages';import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';@@ -462,7 +463,7 @@ export const messageRouter = router({// set, so already-deployed clients (no `file` descriptor) never receive// a `file` summary that would crash their works UI. New clients set it.includeFileWorks: z.boolean().optional(),- pageSize: z.number().optional(),+ pageSize: getMessagesPageSizeSchema,/*** Hand back render-facing tool view models instead of the stored* payloads (`@lobechat/tool-view-model`). Opt-in per read: see thediff --git a/packages/agent-runtime/src/utils/messageSelectors.test.ts b/packages/agent-runtime/src/utils/messageSelectors.test.tsindex c20bb15dfca..1f2740050c2 100644--- a/packages/agent-runtime/src/utils/messageSelectors.test.ts+++ b/packages/agent-runtime/src/utils/messageSelectors.test.ts@@ -107,10 +107,12 @@ describe('TODO state selectors', () => {const item = { status: 'processing' as const, text: 'Ship the fix' };it('normalizes canonical and legacy states, including empty clear tombstones', () => {- expect(normalizeTodosState({ items: [item], updatedAt: 'canonical-time' }, 'fallback')).toEqual({- items: [item],- updatedAt: 'canonical-time',- });+ expect(normalizeTodosState({ items: [item], updatedAt: 'canonical-time' }, 'fallback')).toEqual(+ {+ items: [item],+ updatedAt: 'canonical-time',+ },+ );expect(normalizeTodosState([item], 'fallback')).toEqual({items: [item],updatedAt: 'fallback',@@ -129,7 +131,9 @@ describe('TODO state selectors', () => {it('rejects alternate fields and malformed items', () => {expect(normalizeTodosState({ tasks: [item] }, 'fallback')).toBeUndefined();expect(normalizeTodosState({ todoList: [item] }, 'fallback')).toBeUndefined();- expect(normalizeTodosState({ items: [{ status: 'unknown', text: 'bad' }] }, 'fallback')).toBeUndefined();+ expect(+ normalizeTodosState({ items: [{ status: 'unknown', text: 'bad' }] }, 'fallback'),+ ).toBeUndefined();expect(normalizeTodosState({ items: [{ status: 'todo' }] }, 'fallback')).toBeUndefined();});@@ -539,3 +543,33 @@ describe('extractActivatedToolIdsFromMessages', () => {expect(extractActivatedToolIdsFromMessages(messages)).toBeUndefined();});});++describe('flat tool rows inside compressedGroup compressedMessages', () => {+ // The capped compression read path puts the state-bearing rows of members it+ // does not hydrate here as flat tool rows; released clients rely on this.+ it('restores activated tools, skills and todos from flat tool rows', () => {+ const todos = { items: [{ status: 'todo', text: 'old' }], updatedAt: 'old' };+ const messages = [+ createMessage({+ compressedMessages: [+ createToolMessage({+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },+ } as any),+ createToolMessage({+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },+ pluginState: { id: 'skl_old', name: 'xlsx' },+ } as any),+ createToolMessage({ pluginState: { todos } }),+ ],+ role: 'compressedGroup',+ } as any),+ ];++ expect(extractActivatedToolIdsFromMessages(messages)).toEqual(['lobe-task']);+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([+ { description: undefined, id: 'skl_old', name: 'xlsx' },+ ]);+ expect(extractTodosFromMessages(messages)).toEqual(todos);+ });+});diff --git a/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.ts b/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.tsnew file mode 100644index 00000000000..eea2daf7058--- /dev/null+++ b/packages/database/src/models/__tests__/messages/compressedGroupMembers.test.ts@@ -0,0 +1,237 @@+// @vitest-environment node+import { MessageGroupType } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { messageGroups, messagePlugins, messages, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { MessageModel } from '../../message';+import {+ MAX_COMPRESSED_GROUP_MEMBERS,+ selectCompressedGroupMembers,+} from '../../message/groupNodes';++const userId = 'compressed-group-members-test-user';+const topicId = 'compressed-group-members-topic';++let messageModel: MessageModel;+let serverDB: LobeChatDatabase;++beforeEach(async () => {+ serverDB = await getTestDB();++ await serverDB.delete(messageGroups);+ await serverDB.delete(messages);+ await serverDB.delete(topics);+ await serverDB.delete(users);++ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(topics).values({ id: topicId, userId });++ messageModel = new MessageModel(serverDB, userId);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('MessageModel.query compression group member cap', () => {+ describe('large compression groups', () => {+ it('should hydrate only the newest members, aligned to a round start, keeping pinned ones', async () => {+ // One more than the cap plus 20, so the newest-cap slice starts on an assistant+ // row (odd index) and is trimmed forward to the next user message.+ const total = MAX_COMPRESSED_GROUP_MEMBERS + 21;+ const base = Date.parse('2024-01-01T00:00:00Z');+ await serverDB.insert(messages).values(+ Array.from({ length: total }, (_, i) => ({+ content: `member ${i}`,+ createdAt: new Date(base + i * 1000),+ favorite: i === 0,+ id: `big-${String(i).padStart(4, '0')}`,+ role: i % 2 === 0 ? 'user' : 'assistant',+ topicId,+ userId,+ })),+ );+ await serverDB.insert(messageGroups).values({+ content: 'Summary of a long conversation',+ createdAt: new Date(base + total * 1000),+ id: 'big-group',+ topicId,+ type: MessageGroupType.Compression,+ userId,+ });+ await serverDB.update(messages).set({ messageGroupId: 'big-group' });++ const result = await messageModel.query({ topicId });+ const node = result.find((m) => m.role === 'compressedGroup') as any;++ // Slice = indices [21, total) trimmed to the first user row (22).+ const omitted = 22;+ expect(node.compressedOmittedIds).toHaveLength(omitted);+ expect(node.compressedOmittedIds[0]).toBe('big-0000');+ expect(node.compressedOmittedIds.at(-1)).toBe('big-0021');+ // Every even index is a user message: the whole group's turns, not the slice's.+ expect(node.compressedTurnCount).toBe(Math.ceil(total / 2));+ const ids = node.compressedMessages.map((m: any) => m.id);+ expect(ids).not.toContain('big-0000');+ expect(ids).not.toContain('big-0021');+ expect(ids[0]).toBe('big-0022');+ expect(ids.at(-1)).toBe(`big-${String(total - 1).padStart(4, '0')}`);+ expect(node.compressedMessages).toHaveLength(total - omitted);++ // The pinned member predates the slice but still loads; the chain link+ // still points at the group's real last member.+ expect(node.pinnedMessages.map((m: any) => m.id)).toEqual(['big-0000']);+ expect(node.lastMessageId).toBe(`big-${String(total - 1).padStart(4, '0')}`);+ });++ it('should leave a group within the cap untouched', async () => {+ await serverDB.insert(messages).values([+ { content: 'a', id: 'small-1', role: 'user', topicId, userId },+ { content: 'b', id: 'small-2', role: 'assistant', topicId, userId },+ ]);+ await serverDB.insert(messageGroups).values({+ content: 'Summary',+ id: 'small-group',+ topicId,+ type: MessageGroupType.Compression,+ userId,+ });+ await serverDB.update(messages).set({ messageGroupId: 'small-group' });++ const result = await messageModel.query({ topicId });+ const node = result.find((m) => m.role === 'compressedGroup') as any;++ expect(node.compressedOmittedIds).toBeUndefined();+ expect(node.compressedTurnCount).toBeUndefined();+ expect(node.compressedMessages).toHaveLength(2);+ });+ });++ describe('state-bearing members outside the hydrated slice', () => {+ it('should keep only the plugin state of omitted members that later runs restore', async () => {+ const total = MAX_COMPRESSED_GROUP_MEMBERS + 21;+ const base = Date.parse('2024-01-01T00:00:00Z');+ const idOf = (i: number) => `st-${String(i).padStart(4, '0')}`;+ // Indices 1..4 are omitted tool rows: an activator call, a TODO write+ // from another tool, a plain tool result that carries no state, and a+ // non-activation `lobe-skills` call (its command state is not restored).+ const toolRows = new Set([1, 2, 3, 4]);+ await serverDB.insert(messages).values(+ Array.from({ length: total }, (_, i) => ({+ content: `member ${i}`,+ createdAt: new Date(base + i * 1000),+ id: idOf(i),+ role: toolRows.has(i) ? 'tool' : i % 2 === 0 ? 'user' : 'assistant',+ topicId,+ userId,+ })),+ );+ await serverDB.insert(messagePlugins).values([+ {+ apiName: 'activateTools',+ id: idOf(1),+ identifier: 'lobe-activator',+ state: { activatedTools: [{ identifier: 'lobe-task' }] },+ userId,+ },+ {+ apiName: 'writeTodos',+ id: idOf(2),+ identifier: 'lobe-agent',+ state: { todos: { items: [{ status: 'todo', text: 'ship it' }] } },+ userId,+ },+ {+ apiName: 'search',+ id: idOf(3),+ identifier: 'lobe-web-browsing',+ state: { results: [] },+ userId,+ },+ {+ apiName: 'runCommand',+ id: idOf(4),+ identifier: 'lobe-skills',+ state: { command: 'x'.repeat(1000) },+ userId,+ },+ ]);+ await serverDB.insert(messageGroups).values({+ content: 'Summary',+ createdAt: new Date(base + total * 1000),+ id: 'state-group',+ topicId,+ type: MessageGroupType.Compression,+ userId,+ });+ await serverDB.update(messages).set({ messageGroupId: 'state-group' });++ const result = await messageModel.query({ topicId });+ const node = result.find((m) => m.role === 'compressedGroup') as any;++ // Kept as flat tool rows ahead of the hydrated slice, where every released+ // client's runtime selectors already look for them.+ const stateRows = node.compressedMessages.filter((m: any) => m.role === 'tool');+ expect(stateRows.map((m: any) => m.id)).toEqual([idOf(1), idOf(2)]);+ expect(node.compressedMessages.slice(0, 2)).toEqual(stateRows);+ expect(stateRows[0]).toMatchObject({+ content: '',+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator', type: 'default' },+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },+ });+ expect(stateRows[1]).toMatchObject({+ plugin: { apiName: 'writeTodos', identifier: 'lobe-agent', type: 'default' },+ pluginState: { todos: { items: [{ status: 'todo', text: 'ship it' }] } },+ });+ });++ it('should not add state messages when nothing was omitted', async () => {+ await serverDB.insert(messages).values([+ { content: 'a', id: 'st-small-1', role: 'user', topicId, userId },+ { content: 'b', id: 'st-small-2', role: 'tool', topicId, userId },+ ]);+ await serverDB.insert(messagePlugins).values({+ apiName: 'activateTools',+ id: 'st-small-2',+ identifier: 'lobe-activator',+ state: { activatedTools: [{ identifier: 'lobe-task' }] },+ userId,+ });+ await serverDB.insert(messageGroups).values({+ content: 'Summary',+ id: 'st-small-group',+ topicId,+ type: MessageGroupType.Compression,+ userId,+ });+ await serverDB.update(messages).set({ messageGroupId: 'st-small-group' });++ const result = await messageModel.query({ topicId });+ const node = result.find((m) => m.role === 'compressedGroup') as any;++ // The single tool row is hydrated as a normal member, not duplicated.+ expect(node.compressedMessages.map((m: any) => m.id)).toEqual(['st-small-1', 'st-small-2']);+ });+ });++ describe('selectCompressedGroupMembers', () => {+ const rows = (roles: string[]) => roles.map((role, i) => ({ id: String(i), role }));++ it('returns every member when within the limit', () => {+ const members = rows(['user', 'assistant']);+ expect(selectCompressedGroupMembers(members, 2)).toBe(members);+ });++ it('keeps the newest members and trims forward to a user message', () => {+ const members = rows(['user', 'assistant', 'tool', 'assistant', 'user', 'assistant']);+ expect(selectCompressedGroupMembers(members, 4).map((m) => m.id)).toEqual(['4', '5']);+ });++ it('keeps the newest slice whole when it holds no user message', () => {+ const members = rows(['user', 'assistant', 'tool', 'assistant']);+ expect(selectCompressedGroupMembers(members, 3).map((m) => m.id)).toEqual(['1', '2', '3']);+ });+ });+});diff --git a/packages/database/src/models/message/groupNodes.ts b/packages/database/src/models/message/groupNodes.tsnew file mode 100644index 00000000000..7543d5d00fd--- /dev/null+++ b/packages/database/src/models/message/groupNodes.ts@@ -0,0 +1,256 @@+import { parse } from '@lobechat/conversation-flow';+import type { UIChatMessage } from '@lobechat/types';+import { MessageGroupType } from '@lobechat/types';+import { eq, inArray, sql } from 'drizzle-orm';++import type { MessageGroupItem } from '../../schemas';+import { messagePlugins, messages } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/**+ * Most members a `compressedGroup` node hydrates into `compressedMessages`.+ * A long-running topic compresses thousands of messages into one group, and+ * every read of the topic used to load each of them in full and run them+ * through `parse()` β one such read of a 5k-member group held a server+ * instance for ~2 minutes and stalled every request sharing it. The newest+ * members are kept (aligned to a round start); pinned members load regardless,+ * and omitted members that carry runtime state keep their plugin state as+ * flat `tool` rows.+ */+export const MAX_COMPRESSED_GROUP_MEMBERS = 300;++/**+ * Tool calls whose `pluginState` later runs read back from history to restore+ * activated skills and tools (see `extractActivatedSkillsFromMessages` /+ * `extractActivatedToolIdsFromMessages` in `@lobechat/agent-runtime`): the+ * activation APIs of these identifiers only β their command / script /+ * resource calls carry no restored state and can be large. Literal copies β+ * the tool packages are not database dependencies.+ */+const STATE_BEARING_TOOL_IDENTIFIERS = new Set(['lobe-activator', 'lobe-skills']);+const STATE_BEARING_API_NAMES = new Set(['activateSkill', 'activateTools']);++/**+ * Columns the light member select adds (it left-joins `message_plugins`), so+ * an omitted member that carries runtime state is known without loading it.+ */+export const compressedStateMarkerColumns = {+ // Key test, not `IS NOT NULL` on an extracted value β see jsonbNullTest.test.ts.+ carriesTodos: sql<boolean>`coalesce(jsonb_exists(${messagePlugins.state}, 'todos'), false)`,+ pluginApiName: messagePlugins.apiName,+ pluginIdentifier: messagePlugins.identifier,+};++/** 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;+ pluginApiName: string | null;+ pluginIdentifier: string | null;+ role: string | null;+}++const carriesRuntimeState = (record: MessageGroupMemberRecord) =>+ record.role === 'tool' &&+ (record.carriesTodos === true ||+ (!!record.pluginIdentifier &&+ STATE_BEARING_TOOL_IDENTIFIERS.has(record.pluginIdentifier) &&+ !!record.pluginApiName &&+ STATE_BEARING_API_NAMES.has(record.pluginApiName)));++type MessageGroupRow = Pick<+ MessageGroupItem,+ 'content' | 'createdAt' | 'id' | 'metadata' | 'topicId' | 'type' | 'updatedAt'+>;++/**+ * Pick the members of one compression group to hydrate: the newest+ * {@link MAX_COMPRESSED_GROUP_MEMBERS}, trimmed forward to the first mainline+ * `user` message so the slice parses as one chain (same rule as the newest-page+ * trim in `MessageModel.queryWithWhere`). A slice with no user message is kept whole.+ */+export const selectCompressedGroupMembers = <T extends { role: string | null }>(+ members: T[],+ limit: number = MAX_COMPRESSED_GROUP_MEMBERS,+): T[] => {+ if (members.length <= limit) return members;++ const tail = members.slice(-limit);+ const firstRoundStart = tail.findIndex((member) => member.role === 'user');+ return firstRoundStart > 0 ? tail.slice(firstRoundStart) : tail;+};++export interface MessageGroupHydrationPlan {+ /** Members to hydrate per group: all of a compare group, the capped slice of a compression group. */+ hydratedByGroup: Map<string, MessageGroupMemberRecord[]>;+ /** Every id `queryByIds` must load: the hydrated members plus pinned compression members. */+ idsToHydrate: string[];+ /** All members per group, ascending. */+ recordsByGroup: Map<string, MessageGroupMemberRecord[]>;+ /** Omitted compression members that carry runtime state, per group, ascending. */+ stateByGroup: Map<string, MessageGroupMemberRecord[]>;+ /** Every id whose plugin state `loadCompressedStateRows` must load. */+ stateIds: string[];+}++export const planMessageGroupHydration = (+ groups: Pick<MessageGroupRow, 'id' | 'type'>[],+ records: MessageGroupMemberRecord[],+): MessageGroupHydrationPlan => {+ const recordsByGroup = new Map<string, MessageGroupMemberRecord[]>();+ for (const record of records) {+ if (!record.messageGroupId) continue;+ const groupRecords = recordsByGroup.get(record.messageGroupId) ?? [];+ groupRecords.push(record);+ recordsByGroup.set(record.messageGroupId, groupRecords);+ }++ const hydratedByGroup = new Map<string, MessageGroupMemberRecord[]>();+ const stateByGroup = new Map<string, MessageGroupMemberRecord[]>();+ const ids = new Set<string>();+ const stateIds: string[] = [];+ for (const group of groups) {+ const groupRecords = recordsByGroup.get(group.id) ?? [];+ const isCompression = group.type === MessageGroupType.Compression;+ const hydrated = isCompression ? selectCompressedGroupMembers(groupRecords) : 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);+ const omitted = groupRecords.slice(0, groupRecords.length - hydrated.length);+ const stateRecords = omitted.filter(carriesRuntimeState);+ stateByGroup.set(group.id, stateRecords);+ for (const record of stateRecords) stateIds.push(record.id);+ }++ return { hydratedByGroup, idsToHydrate: [...ids], recordsByGroup, stateByGroup, stateIds };+};++export interface CompressedStateRow {+ apiName: string | null;+ createdAt: Date;+ id: string;+ identifier: string | null;+ state: unknown;+ type: string | null;+ updatedAt: Date;+}++/**+ * Plugin payload + state of the omitted state-bearing members β no message+ * content, which is what makes hydrating every member expensive. The ids come+ * from the caller's scoped member select.+ */+export const loadCompressedStateRows = async (+ db: LobeChatDatabase,+ ids: string[],+): Promise<Map<string, CompressedStateRow>> => {+ if (ids.length === 0) return new Map();++ const rows = await db+ .select({+ apiName: messagePlugins.apiName,+ createdAt: messages.createdAt,+ id: messagePlugins.id,+ identifier: messagePlugins.identifier,+ state: messagePlugins.state,+ type: messagePlugins.type,+ updatedAt: messages.updatedAt,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messages.id, messagePlugins.id))+ .where(inArray(messagePlugins.id, ids));++ return new Map(rows.map((row) => [row.id, row]));+};++const toSnapshot = (m: UIChatMessage) => ({+ content: m.content,+ createdAt: m.createdAt,+ id: m.id,+ model: m.model,+ provider: m.provider,+ role: m.role,+});++/**+ * Build one MessageGroup node from its hydrated members:+ * - compressedGroup: `pinnedMessages` (favorite=true) and `compressedMessages`+ * parsed through conversation-flow (e.g. into assistantGroup display nodes)+ * - compareGroup: `children` with basic info+ */+export const buildMessageGroupNode = (+ group: MessageGroupRow,+ plan: MessageGroupHydrationPlan,+ messageMap: Map<string, UIChatMessage>,+ stateRows: Map<string, CompressedStateRow> = new Map(),+): UIChatMessage => {+ const records = plan.recordsByGroup.get(group.id) ?? [];+ const hydrated = plan.hydratedByGroup.get(group.id) ?? [];+ const groupMsgs = hydrated+ .map((record) => messageMap.get(record.id))+ .filter(Boolean) as UIChatMessage[];++ if (group.type !== MessageGroupType.Compression) {+ return {+ children: groupMsgs.map(toSnapshot),+ createdAt: group.createdAt,+ id: group.id,+ role: 'compareGroup',+ topicId: group.topicId,+ updatedAt: group.updatedAt,+ } as unknown as UIChatMessage;+ }++ const pinnedMessages = records+ .filter((record) => record.favorite === true)+ .map((record) => messageMap.get(record.id))+ .filter(Boolean)+ .map((m) => toSnapshot(m!));+ // `hydrated` is a suffix of `records`, so the omitted members lead it.+ const compressedOmittedIds = records+ .slice(0, records.length - hydrated.length)+ .map((record) => record.id);+ // Omitted members that carry runtime state, as flat `tool` rows (plugin ++ // state, no content) ahead of the hydrated slice. Every released client's+ // selectors already restore state from flat tool rows in `compressedMessages`,+ // and the compressed history view does not render `tool` rows.+ const stateMessages = (plan.stateByGroup.get(group.id) ?? [])+ .map((record) => stateRows.get(record.id))+ .filter(Boolean)+ .map((row) => ({+ content: '',+ createdAt: row!.createdAt,+ id: row!.id,+ plugin: {+ apiName: row!.apiName,+ identifier: row!.identifier,+ type: row!.type,+ },+ pluginState: row!.state,+ role: 'tool',+ updatedAt: row!.updatedAt,+ })) as unknown as UIChatMessage[];++ return {+ compressedMessages: [...stateMessages, ...parse(groupMsgs).flatList],+ ...(compressedOmittedIds.length > 0 && {+ compressedOmittedIds,+ compressedTurnCount:+ records.filter((record) => record.role === 'user').length || records.length,+ }),+ content: group.content,+ createdAt: group.createdAt,+ id: group.id,+ // The group's real last member, for parent-child linking in conversation-flow.+ lastMessageId: records.at(-1)?.id,+ metadata: group.metadata,+ pinnedMessages,+ role: 'compressedGroup',+ topicId: group.topicId,+ updatedAt: group.updatedAt,+ } as unknown as UIChatMessage;+};diff --git a/packages/database/src/models/message/queryByIds.ts b/packages/database/src/models/message/queryByIds.tsindex c0fb8542c41..f59ed24c842 100644--- a/packages/database/src/models/message/queryByIds.ts+++ b/packages/database/src/models/message/queryByIds.ts@@ -1,4 +1,3 @@-import { parse } from '@lobechat/conversation-flow';import type {ChatAudioItem,ChatFileItem,@@ -7,7 +6,6 @@ import type {ThreadStatus,UIChatMessage,} from '@lobechat/types';-import { MessageGroupType } from '@lobechat/types';import { logTimingSink as logTiming, runTimedSinkStage as runTimedStage } from '@lobechat/utils';import { and, asc, eq, gte, inArray, lte, sql } from 'drizzle-orm';import pMap from 'p-map';@@ -15,6 +13,7 @@ import pMap from 'p-map';import {documents,files,+ type MessageGroupItem,messageGroups,messagePlugins,messageQueries,@@ -37,6 +36,12 @@ import {materializeChatAudioItem,toFileDocumentsMap,} from './attachments';+import {+ buildMessageGroupNode,+ compressedStateMarkerColumns,+ loadCompressedStateRows,+ planMessageGroupHydration,+} from './groupNodes';import type { MessageRelationQueries } from './relations';import type { MessageScopeArgs } from './scope';import { MessageScope } from './scope';@@ -424,7 +429,7 @@ export class MessageByIdsQueries extends MessageScope {whereConditions.push(sql`${messageGroups.createdAt} < ${options.window.before}::timestamptz`);}- const groups = await runTimedStage(+ const groups: MessageGroupItem[] = await runTimedStage(timing,'db.message.messageGroups.groups.select',() =>@@ -451,8 +456,11 @@ export class MessageByIdsQueries extends MessageScope {favorite: messages.favorite,id: messages.id,messageGroupId: messages.messageGroupId,+ ...compressedStateMarkerColumns,+ role: messages.role,}).from(messages)+ .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id)).where(and(// The parent topic has already been classified by the caller@@ -471,89 +479,25 @@ export class MessageByIdsQueries extends MessageScope {rowCount: groupMessageRecords.length,});- // 3. Query full message data using queryByIds (reuses all transformation logic)- const allMessageIds = groupMessageRecords.map((m) => m.id as string);- const fullMessages = await runTimedStage(- timing,- 'db.message.messageGroups.queryByIds',- () => this.queryByIds(allMessageIds, { allowShareVisitor: includeVisitor, postProcessUrl }),- { messageCount: allMessageIds.length },- );-- // Create a map for quick lookup- const messageMap = new Map(fullMessages.map((m) => [m.id, m]));- const favoriteMap = new Map(groupMessageRecords.map((m) => [m.id, m.favorite]));+ // A compression group only hydrates its newest members (see+ // `MAX_COMPRESSED_GROUP_MEMBERS`) plus the pinned ones.+ const plan = planMessageGroupHydration(groups, groupMessageRecords);++ // 3. Query full message data using queryByIds (reuses all transformation logic),+ // and only the plugin state of omitted members that carry runtime state+ const [fullMessages, stateRows] = await Promise.all([+ runTimedStage(+ timing,+ 'db.message.messageGroups.queryByIds',+ () =>+ this.queryByIds(plan.idsToHydrate, { allowShareVisitor: includeVisitor, postProcessUrl }),+ { messageCount: plan.idsToHydrate.length, totalMemberCount: groupMessageRecords.length },+ ),+ loadCompressedStateRows(this.db, plan.stateIds),+ ]);// 4. Build MessageGroup nodes- return groups.map((group) => {- // Get messages for this group- const groupMsgIds = groupMessageRecords- .filter((m) => m.messageGroupId === group.id)- .map((m) => m.id as string);-- const groupMsgs = groupMsgIds- .map((id) => messageMap.get(id))- .filter(Boolean) as UIChatMessage[];-- if (group.type === MessageGroupType.Compression) {- // compressedGroup: extract pinnedMessages (favorite=true)- const pinnedMessages = groupMsgIds- .filter((id) => favoriteMap.get(id) === true)- .map((id) => {- const m = messageMap.get(id);- return m- ? {- content: m.content,- createdAt: m.createdAt,- id: m.id,- model: m.model,- provider: m.provider,- role: m.role,- }- : null;- })- .filter(Boolean);-- // compressedMessages: parse messages through conversation-flow for proper grouping- // This transforms raw messages into displayMessages format (e.g., assistantGroup)- const { flatList } = parse(groupMsgs);- const compressedMessages = flatList;-- // Get the last message ID for parent-child linking in conversation-flow- const lastMessageId = groupMsgIds.at(-1);-- return {- compressedMessages,- content: group.content,- createdAt: group.createdAt,- id: group.id,- lastMessageId,- metadata: group.metadata,- pinnedMessages,- role: 'compressedGroup',- topicId: group.topicId,- updatedAt: group.updatedAt,- } as unknown as UIChatMessage;- } else {- // compareGroup (parallel): include children with basic info- const children = groupMsgs.map((m) => ({- content: m.content,- createdAt: m.createdAt,- id: m.id,- model: m.model,- provider: m.provider,- role: m.role,- }));-- return {- children,- createdAt: group.createdAt,- id: group.id,- role: 'compareGroup',- topicId: group.topicId,- updatedAt: group.updatedAt,- } as unknown as UIChatMessage;- }- });+ const messageMap = new Map(fullMessages.map((m) => [m.id, m]));+ return groups.map((group) => buildMessageGroupNode(group, plan, messageMap, stateRows));};}diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.tsindex 5027506ad4e..58f0603a872 100644--- a/packages/database/src/models/message/visitor.ts+++ b/packages/database/src/models/message/visitor.ts@@ -69,6 +69,8 @@ const VISITOR_MESSAGE_ALLOWED_KEYS = ['performance','observationId','traceId',+ 'compressedOmittedIds',+ 'compressedTurnCount',] as const satisfies readonly (keyof UIChatMessage)[];type VisitorAllowedKey = (typeof VISITOR_MESSAGE_ALLOWED_KEYS)[number];diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.tsindex ff903ca4705..3938fe398ee 100644--- a/packages/types/src/message/ui/chat.ts+++ b/packages/types/src/message/ui/chat.ts@@ -223,6 +223,19 @@ export interface UIChatMessage {* Used for rendering expanded view with conversation-flow parsing*/compressedMessages?: UIChatMessage[];+ /**+ * Ids of the group's oldest members that `compressedMessages` leaves out. A+ * compression group can hold thousands of messages; the read path only+ * hydrates the newest ones (see `MAX_COMPRESSED_GROUP_MEMBERS`) but keeps+ * every member addressable, e.g. by a `#<message-id>` deep link.+ */+ compressedOmittedIds?: string[];+ /**+ * Conversation turns (mainline `user` messages) across the WHOLE group, set+ * when `compressedOmittedIds` is: `compressedMessages` then holds only the+ * newest members and undercounts the history it folded away.+ */+ compressedTurnCount?: number;content: string;/*** Character length of the STORED tool result body, kept when the read pathdiff --git a/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.test.tsindex fec56ebeb2d..f34425dbc31 100644--- a/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts@@ -63,6 +63,22 @@ describe('resolveMessageDeepLink', () => {expect(resolve(messages, 'compressed-hit')?.index).toBe(2);});+ it('resolves a compressed member the read path did not hydrate to its group row', () => {+ const messages = [+ message('first'),+ message('compressed-row', {+ compressedMessages: [message('compressed-newest')],+ compressedOmittedIds: ['compressed-oldest'],+ role: 'compressedGroup',+ }),+ ];++ expect(resolve(messages, 'compressed-oldest')).toMatchObject({+ displayMessageId: 'compressed-row',+ index: 1,+ });+ });+it('returns undefined when the message is not rendered by the list', () => {expect(resolve([message('first')], 'missing')).toBeUndefined();});diff --git a/src/features/Conversation/ChatList/utils/messageDeepLink.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.tsindex 50921201c87..7c27b7fafea 100644--- a/src/features/Conversation/ChatList/utils/messageDeepLink.ts+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.ts@@ -33,6 +33,8 @@ function messageContainsMessage(message: UIChatMessage, messageId: string): booltrue ||message.compressedMessages?.some((child) => messageContainsMessage(child, messageId)) ===true ||+ // Compression members the read path did not hydrate still belong to the group row.+ message.compressedOmittedIds?.includes(messageId) === true ||message.members?.some((member) => messageContainsMessage(member, messageId)) === true ||message.tasks?.some((task) => messageContainsMessage(task, messageId)) === true ||message.pinnedMessages?.some((pinned) => pinned.id === messageId) === true ||diff --git a/src/features/Conversation/Messages/CompressedGroup/index.tsx b/src/features/Conversation/Messages/CompressedGroup/index.tsxindex baa8234c5f7..d45e03435b7 100644--- a/src/features/Conversation/Messages/CompressedGroup/index.tsx+++ b/src/features/Conversation/Messages/CompressedGroup/index.tsx@@ -109,6 +109,7 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {() =>getCompressedTurnCount({compressedMessages,+ compressedTurnCount: (message as UIChatMessage | undefined)?.compressedTurnCount,originalMessageCount: ((message as UIChatMessage | undefined)?.metadata as CompressionGroupMetadata | undefined)?.originalMessageCount,diff --git a/src/features/Conversation/Messages/CompressedGroup/logic.test.ts b/src/features/Conversation/Messages/CompressedGroup/logic.test.tsindex 6a110760550..b88d43872dc 100644--- a/src/features/Conversation/Messages/CompressedGroup/logic.test.ts+++ b/src/features/Conversation/Messages/CompressedGroup/logic.test.ts@@ -52,6 +52,12 @@ describe('getCompressedTurnCount', () => {expect(getCompressedTurnCount({ compressedMessages })).toBe(2);});+ it('prefers the whole-group turn count of a capped read over the hydrated slice', () => {+ const compressedMessages = [{ id: 'u300', role: 'user' }] as any;++ expect(getCompressedTurnCount({ compressedMessages, compressedTurnCount: 2600 })).toBe(2600);+ });+it('falls back to the message count when no user message is present', () => {const compressedMessages = [{ id: 'a1', role: 'assistant' },diff --git a/src/features/Conversation/Messages/CompressedGroup/logic.ts b/src/features/Conversation/Messages/CompressedGroup/logic.tsindex ff3f4b04604..2de76aae3a6 100644--- a/src/features/Conversation/Messages/CompressedGroup/logic.ts+++ b/src/features/Conversation/Messages/CompressedGroup/logic.ts@@ -15,18 +15,24 @@ export const shouldShowCompressedGroupPanel = ({* How much history a compressed group folded away, counted in conversation* turns so the collapsed bar can say "the previous N turns".*- * The nested messages are the only truthful count once they are loaded. Before- * that (and on a group restored from a source that carries no detail) fall back- * to the server-side `originalMessageCount`, which counts messages rather than- * turns but still gives the reader a size.+ * A capped read hydrates only the group's newest members, so the server's+ * whole-group `compressedTurnCount` wins when present. Otherwise the nested+ * messages are the only truthful count once they are loaded. Before that (and+ * on a group restored from a source that carries no detail) fall back to the+ * server-side `originalMessageCount`, which counts messages rather than turns+ * but still gives the reader a size.*/export const getCompressedTurnCount = ({compressedMessages,+ compressedTurnCount,originalMessageCount,}: {compressedMessages?: UIChatMessage[];+ compressedTurnCount?: number;originalMessageCount?: number;}) => {+ if (compressedTurnCount) return compressedTurnCount;+if (compressedMessages?.length) {const userTurns = compressedMessages.filter((message) => message.role === 'user').length;