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(agent-runtime): stop server-runtime regenerate from continuing the old answer (#16519)

Arvin Xu9446583a3b23
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
index 495697abe61..6cd06e932c7 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts
@@ -3,14 +3,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
-const { mockCreateOperation, mockFindById, mockMessageCreate, mockMessageQuery } = vi.hoisted(
- () => ({
+const { mockCreateOperation, mockFindById, mockMessageCreate, mockMessageQuery, mockQueryTree } =
+ vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
mockFindById: vi.fn(),
mockMessageCreate: vi.fn(),
mockMessageQuery: vi.fn(),
- }),
-);
+ mockQueryTree: vi.fn(),
+ }));
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
@@ -23,6 +23,7 @@ vi.mock('@/database/models/message', () => ({
create: mockMessageCreate,
findById: mockFindById,
query: mockMessageQuery,
+ queryTopicMessageTree: mockQueryTree,
update: vi.fn().mockResolvedValue({}),
})),
}));
@@ -158,6 +159,7 @@ describe('AiAgentService.execAgent - resume mode', () => {
]);
mockMessageCreate.mockResolvedValue({ id: 'assistant-msg-new' });
+ mockQueryTree.mockResolvedValue([]);
service = new AiAgentService({} as any, 'user-1');
});
@@ -252,4 +254,187 @@ describe('AiAgentService.execAgent - resume mode', () => {
}),
).rejects.toThrow('parentMessageId is required when resume is true');
});
+
+ // Regression: gateway/server-runtime regenerate must replace, not continue.
+ // The flat topic query returns the anchor user message's existing answer
+ // branch; feeding it back makes the model continue the old answer
+ // ([U1, A1] -> continue) instead of producing a fresh one ([U1] -> A2).
+ it('regenerate: drops the anchor user message existing answer branch from history', async () => {
+ mockFindById.mockResolvedValue({
+ id: 'u1',
+ role: 'user',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+
+ mockMessageQuery.mockResolvedValue([
+ { content: 'prior question', id: 'prior-u', role: 'user' },
+ { content: 'prior answer', id: 'prior-a', parentId: 'prior-u', role: 'assistant' },
+ { content: 'the question', id: 'u1', parentId: 'prior-a', role: 'user' },
+ // Old answer being regenerated β€” must NOT be fed back as context.
+ { content: 'OLD answer', id: 'a1', parentId: 'u1', role: 'assistant' },
+ ]);
+ mockQueryTree.mockResolvedValue([
+ { id: 'prior-u', messageGroupId: null, parentId: null },
+ { id: 'prior-a', messageGroupId: null, parentId: 'prior-u' },
+ { id: 'u1', messageGroupId: null, parentId: 'prior-a' },
+ { id: 'a1', messageGroupId: null, parentId: 'u1' },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'u1',
+ prompt: 'ignored',
+ resume: true,
+ });
+
+ const call = mockCreateOperation.mock.calls[0][0];
+ expect(call.initialMessages.map((m: any) => m.id)).toEqual(['prior-u', 'prior-a', 'u1']);
+ });
+
+ // Regression: regenerating a MIDDLE turn must also drop the turns that
+ // continued from it (they live on the old branch), so history ends at U1.
+ it('regenerate: drops later turns that continued from the anchor (middle-turn regenerate)', async () => {
+ mockFindById.mockResolvedValue({
+ id: 'u1',
+ role: 'user',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+
+ mockMessageQuery.mockResolvedValue([
+ { content: 'the question', id: 'u1', role: 'user' },
+ { content: 'OLD answer', id: 'a1', parentId: 'u1', role: 'assistant' },
+ { content: 'follow-up question', id: 'u2', parentId: 'a1', role: 'user' },
+ { content: 'follow-up answer', id: 'a2', parentId: 'u2', role: 'assistant' },
+ ]);
+ mockQueryTree.mockResolvedValue([
+ { id: 'u1', messageGroupId: null, parentId: null },
+ { id: 'a1', messageGroupId: null, parentId: 'u1' },
+ { id: 'u2', messageGroupId: null, parentId: 'a1' },
+ { id: 'a2', messageGroupId: null, parentId: 'u2' },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'u1',
+ prompt: 'ignored',
+ resume: true,
+ });
+
+ const call = mockCreateOperation.mock.calls[0][0];
+ expect(call.initialMessages.map((m: any) => m.id)).toEqual(['u1']);
+ });
+
+ // Regression: after /compact, the old branch is hidden inside a compression
+ // group and `query` returns a synthetic `compressedGroup` node that carries no
+ // `parentId`. Pruning must use the raw message tree so the group (whose members
+ // descend from the anchor) is dropped instead of being fed back as a summary.
+ it('regenerate: drops a compressedGroup node whose compacted members descend from the anchor', async () => {
+ mockFindById.mockResolvedValue({
+ id: 'u1',
+ role: 'user',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+
+ // `query` hides the grouped messages and injects a synthetic group node
+ // (id = group id, role = 'compressedGroup', no parentId).
+ mockMessageQuery.mockResolvedValue([
+ { content: 'prior question', id: 'prior-u', role: 'user' },
+ { content: 'prior answer', id: 'prior-a', parentId: 'prior-u', role: 'assistant' },
+ { content: 'the question', id: 'u1', parentId: 'prior-a', role: 'user' },
+ { content: 'summary of old branch', id: 'grp-1', role: 'compressedGroup' },
+ ]);
+ // Raw tree still has the hidden members linked to the anchor via parentId.
+ mockQueryTree.mockResolvedValue([
+ { id: 'prior-u', messageGroupId: null, parentId: null },
+ { id: 'prior-a', messageGroupId: null, parentId: 'prior-u' },
+ { id: 'u1', messageGroupId: null, parentId: 'prior-a' },
+ { id: 'a1', messageGroupId: 'grp-1', parentId: 'u1' },
+ { id: 'u2', messageGroupId: 'grp-1', parentId: 'a1' },
+ { id: 'a2', messageGroupId: 'grp-1', parentId: 'u2' },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'u1',
+ prompt: 'ignored',
+ resume: true,
+ });
+
+ const call = mockCreateOperation.mock.calls[0][0];
+ expect(call.initialMessages.map((m: any) => m.id)).toEqual(['prior-u', 'prior-a', 'u1']);
+ });
+
+ // Guard: a compression group of PRIOR turns (not descended from the anchor)
+ // must be kept β€” it is legitimate earlier context.
+ it('regenerate: keeps a compressedGroup node whose members precede the anchor', async () => {
+ mockFindById.mockResolvedValue({
+ id: 'u1',
+ role: 'user',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+
+ mockMessageQuery.mockResolvedValue([
+ { content: 'summary of early turns', id: 'grp-0', role: 'compressedGroup' },
+ { content: 'the question', id: 'u1', parentId: 'old-a', role: 'user' },
+ { content: 'OLD answer', id: 'a1', parentId: 'u1', role: 'assistant' },
+ ]);
+ mockQueryTree.mockResolvedValue([
+ { id: 'old-u', messageGroupId: 'grp-0', parentId: null },
+ { id: 'old-a', messageGroupId: 'grp-0', parentId: 'old-u' },
+ { id: 'u1', messageGroupId: null, parentId: 'old-a' },
+ { id: 'a1', messageGroupId: null, parentId: 'u1' },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'u1',
+ prompt: 'ignored',
+ resume: true,
+ });
+
+ const call = mockCreateOperation.mock.calls[0][0];
+ expect(call.initialMessages.map((m: any) => m.id)).toEqual(['grp-0', 'u1']);
+ });
+
+ // Guard: the human-approval resume path anchors on a tool message and must
+ // keep the in-flight turn β€” including parallel-tool sibling messages β€” intact.
+ it('resume on a non-user anchor (tool message) keeps full history untouched', async () => {
+ mockFindById.mockResolvedValue({
+ id: 'tool-1',
+ role: 'tool',
+ sessionId: 'session-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+
+ mockMessageQuery.mockResolvedValue([
+ { content: 'q', id: 'u1', role: 'user' },
+ { content: 'a with tool calls', id: 'a1', parentId: 'u1', role: 'assistant' },
+ { content: 'tool result A', id: 'tool-1', parentId: 'a1', role: 'tool' },
+ { content: 'tool result B', id: 'tool-2', parentId: 'a1', role: 'tool' },
+ ]);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { sessionId: 'session-1', threadId: 'thread-1', topicId: 'topic-1' },
+ parentMessageId: 'tool-1',
+ prompt: '',
+ resume: true,
+ });
+
+ const call = mockCreateOperation.mock.calls[0][0];
+ expect(call.initialMessages.map((m: any) => m.id)).toEqual(['u1', 'a1', 'tool-1', 'tool-2']);
+ });
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 59110b9a646..c944ed07a03 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -124,6 +124,7 @@ import { markdownToTxt } from '@/utils/markdownToTxt';
import { resolveDeviceAccessPolicy } from './deviceAccessPolicy';
import { buildAllowedBuiltinTools, isDeviceToolIdentifier } from './deviceToolRegistry';
import { ingestAttachment } from './ingestAttachment';
+import { pruneRegeneratedBranch } from './pruneRegeneratedBranch';
import { resolveDeviceWorkingDirectory } from './resolveDeviceWorkingDirectory';
import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCache';
@@ -1097,7 +1098,7 @@ export class AiAgentService {
log('execAgent: appended additional instructions to systemRole');
}
- let resumeParentMessage;
+ let resumeParentMessage: Awaited<ReturnType<MessageModel['findById']>>;
// `resumeApproval` implies the same "load parent message + skip user
// message creation" semantics as `resume`. Callers that go through the
@@ -2041,6 +2042,40 @@ export class AiAgentService {
historyMessagesCache = [];
}
+ // ── Regenerate: drop the anchor user message's existing answer branch ──
+ // In gateway/server runtime mode the client only sends `parentMessageId`
+ // (the user message being regenerated) and lets the server rebuild the
+ // context. The topic query above still returns the anchor's *previous*
+ // assistant branch (the answer being replaced) and β€” when a middle turn is
+ // regenerated β€” the later turns that continued from it. Leaving them in
+ // makes the model see an already-answered turn and "continue" it instead of
+ // producing a fresh answer (`[U1, A1]` β†’ continue rather than `[U1]` β†’ A2).
+ //
+ // The branch must be pruned even after `/compact`: compaction hides the
+ // grouped messages and `query` returns a synthetic `compressedGroup` node
+ // that carries neither `parentId` nor (for compaction) the group's
+ // `parentMessageId`, so ancestry can't be walked from `query` output alone.
+ // We load the raw message tree (including hidden/compacted messages) and
+ // compute the anchor's descendants from it, then drop both regular
+ // descendant messages and any group node whose members fall in that branch.
+ //
+ // Scoped to a `user`-role anchor: the human-approval resume path anchors on
+ // a tool message and must keep the in-flight turn (including parallel-tool
+ // sibling messages) intact, so it is intentionally left untouched.
+ if (
+ historyMessagesCache &&
+ effectiveResume &&
+ parentMessageId &&
+ resumeParentMessage?.role === 'user' &&
+ appContext?.topicId
+ ) {
+ const tree = await this.messageModel.queryTopicMessageTree({
+ threadId: appContext.threadId,
+ topicId: appContext.topicId,
+ });
+ historyMessagesCache = pruneRegeneratedBranch(historyMessagesCache, tree, parentMessageId);
+ }
+
return historyMessagesCache;
};
diff --git a/apps/server/src/services/aiAgent/pruneRegeneratedBranch.ts b/apps/server/src/services/aiAgent/pruneRegeneratedBranch.ts
new file mode 100644
index 00000000000..5fab52af02a
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pruneRegeneratedBranch.ts
@@ -0,0 +1,80 @@
+/**
+ * Raw parent/group links for the full message tree of a topic, including
+ * messages hidden inside MessageGroups. See `MessageModel.queryTopicMessageTree`.
+ */
+export interface MessageTreeRow {
+ id: string;
+ messageGroupId: string | null;
+ parentId: string | null;
+}
+
+interface HistoryItemLike {
+ id: string;
+ role?: string;
+}
+
+/**
+ * Prune the regenerate anchor's old answer branch from server-rebuilt history.
+ *
+ * In gateway/server-runtime mode a regenerate only sends `parentMessageId` (the
+ * user message being regenerated) and the server rebuilds the LLM context from a
+ * flat topic query. That query still contains the anchor's *previous* assistant
+ * branch (the answer being replaced) and β€” for a middle-turn regenerate β€” the
+ * later turns that continued from it. Leaving them in makes the model "continue"
+ * an already-answered turn (`[U1, A1]` β†’ continue) instead of producing a fresh
+ * answer (`[U1]` β†’ A2).
+ *
+ * The branch must be pruned even after `/compact`: compaction hides the grouped
+ * messages and the query returns a synthetic `compressedGroup` node that carries
+ * no `parentId` (and compaction never sets the group's `parentMessageId`), so
+ * ancestry can't be walked from the query output alone. `tree` supplies the raw
+ * links for the whole topic (including hidden/compacted messages); we compute
+ * the anchor's descendants from it, then drop both regular descendant messages
+ * and any group node whose members fall on that branch. Prior-turn groups (not
+ * descended from the anchor) are kept.
+ *
+ * @param history - the rebuilt history items (may include `compressedGroup` /
+ * `compareGroup` synthetic nodes whose `id` is a group id)
+ * @param tree - raw `id β†’ parentId / messageGroupId` links for the whole topic
+ * @param anchorId - the regenerate anchor (the user message id)
+ */
+export const pruneRegeneratedBranch = <T extends HistoryItemLike>(
+ history: T[],
+ tree: MessageTreeRow[],
+ anchorId: string,
+): T[] => {
+ const parentOf = new Map(tree.map((row) => [row.id, row.parentId]));
+
+ const descendsFromAnchor = (id: string | null | undefined): boolean => {
+ let cursor = id ? parentOf.get(id) : undefined;
+ const seen = new Set<string>();
+ while (cursor && !seen.has(cursor)) {
+ if (cursor === anchorId) return true;
+ seen.add(cursor);
+ cursor = parentOf.get(cursor);
+ }
+ return false;
+ };
+
+ // Message ids on the anchor's old branch (old answer + later turns),
+ // including messages hidden inside compaction groups.
+ const descendantIds = new Set(
+ tree.filter((row) => descendsFromAnchor(row.id)).map((row) => row.id),
+ );
+
+ // Group nodes whose members fall on that branch (e.g. a compacted old branch).
+ const prunedGroupIds = new Set(
+ tree
+ .filter((row) => row.messageGroupId && descendantIds.has(row.id))
+ .map((row) => row.messageGroupId as string),
+ );
+
+ return history.filter((msg) => {
+ if (msg.id === anchorId) return true;
+ // Synthetic MessageGroup nodes carry the group id, not a message id.
+ if (msg.role === 'compressedGroup' || msg.role === 'compareGroup') {
+ return !prunedGroupIds.has(msg.id);
+ }
+ return !descendantIds.has(msg.id);
+ });
+};
diff --git a/packages/database/src/models/__tests__/messages/regenerateBranchPrune.test.ts b/packages/database/src/models/__tests__/messages/regenerateBranchPrune.test.ts
new file mode 100644
index 00000000000..e54914282fc
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/regenerateBranchPrune.test.ts
@@ -0,0 +1,179 @@
+// @vitest-environment node
+import { MessageGroupType } from '@lobechat/types';
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+// Real prune helper used by AiAgentService.execAgent in server-runtime regenerate.
+import { pruneRegeneratedBranch } from '../../../../../../apps/server/src/services/aiAgent/pruneRegeneratedBranch';
+import { getTestDB } from '../../../core/getTestDB';
+import { messageGroups, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const userId = 'regenerate-prune-test-user';
+const topicId = 'regenerate-prune-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);
+});
+
+/**
+ * End-to-end (real DB) verification of the server-runtime regenerate prune chain:
+ * real MessageModel.query + real MessageModel.queryTopicMessageTree + the real
+ * pruneRegeneratedBranch helper that execAgent uses. No mocks, no LLM.
+ *
+ * Tree: prior-u β†’ prior-a β†’ u1(anchor) β†’ a1(old answer) β†’ u2 β†’ a2
+ */
+describe('server-runtime regenerate branch prune (real DB)', () => {
+ const seedConversation = async () => {
+ await serverDB.insert(messages).values([
+ {
+ id: 'prior-u',
+ content: 'prior q',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: 'prior-a',
+ content: 'prior a',
+ role: 'assistant',
+ parentId: 'prior-u',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ {
+ id: 'u1',
+ content: 'the question',
+ role: 'user',
+ parentId: 'prior-a',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ {
+ id: 'a1',
+ content: 'OLD answer',
+ role: 'assistant',
+ parentId: 'u1',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ },
+ {
+ id: 'u2',
+ content: 'follow-up q',
+ role: 'user',
+ parentId: 'a1',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:04:00Z'),
+ },
+ {
+ id: 'a2',
+ content: 'follow-up a',
+ role: 'assistant',
+ parentId: 'u2',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:05:00Z'),
+ },
+ ]);
+ };
+
+ it('drops the uncompacted old branch (a1 + later turns) so history ends at the anchor', async () => {
+ await seedConversation();
+
+ const history = await messageModel.query({ topicId });
+ const tree = await messageModel.queryTopicMessageTree({ topicId });
+
+ const pruned = pruneRegeneratedBranch(history, tree, 'u1');
+
+ expect(pruned.map((m) => m.id)).toEqual(['prior-u', 'prior-a', 'u1']);
+ });
+
+ it('drops a compressedGroup whose compacted members descend from the anchor (regression: /compact)', async () => {
+ await seedConversation();
+
+ // Compact the old branch [a1, u2, a2] into a compression group.
+ await serverDB.insert(messageGroups).values({
+ id: 'grp-old-branch',
+ content: 'summary of old branch',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:06:00Z'),
+ });
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: 'grp-old-branch' })
+ .where(inArray(messages.id, ['a1', 'u2', 'a2']));
+
+ const history = await messageModel.query({ topicId });
+ const tree = await messageModel.queryTopicMessageTree({ topicId });
+
+ // Premise: query hides the grouped messages and injects a synthetic
+ // compressedGroup node that carries NO parentId.
+ const groupNode = history.find((m) => m.role === 'compressedGroup') as any;
+ expect(groupNode).toBeDefined();
+ expect(groupNode.id).toBe('grp-old-branch');
+ expect(groupNode.parentId ?? null).toBeNull();
+ expect(history.map((m) => m.id)).toEqual(['prior-u', 'prior-a', 'u1', 'grp-old-branch']);
+
+ // queryTopicMessageTree still exposes the hidden members with their parentIds.
+ const treeIds = tree.map((r) => r.id).sort();
+ expect(treeIds).toEqual(['a1', 'a2', 'prior-a', 'prior-u', 'u1', 'u2']);
+ const a1Row = tree.find((r) => r.id === 'a1')!;
+ expect(a1Row.parentId).toBe('u1');
+ expect(a1Row.messageGroupId).toBe('grp-old-branch');
+
+ // The fix: the compressedGroup summarizing the old branch is pruned.
+ const pruned = pruneRegeneratedBranch(history, tree, 'u1');
+ expect(pruned.map((m) => m.id)).toEqual(['prior-u', 'prior-a', 'u1']);
+ });
+
+ it('keeps a compressedGroup whose members precede the anchor (legitimate earlier context)', async () => {
+ await seedConversation();
+
+ // Compact the PRIOR turn [prior-u, prior-a] β€” this is context before the anchor.
+ await serverDB.insert(messageGroups).values({
+ id: 'grp-prior',
+ content: 'summary of prior turns',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:30Z'),
+ });
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: 'grp-prior' })
+ .where(inArray(messages.id, ['prior-u', 'prior-a']));
+
+ const history = await messageModel.query({ topicId });
+ const tree = await messageModel.queryTopicMessageTree({ topicId });
+
+ const pruned = pruneRegeneratedBranch(history, tree, 'u1');
+
+ // Prior-turn group kept; the anchor's own old branch (a1, u2, a2) dropped.
+ expect(pruned.map((m) => m.id)).toEqual(['grp-prior', 'u1']);
+ });
+});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index ea6d45cbaae..44e6ee76091 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -445,6 +445,34 @@ export class MessageModel {
return messageItems;
};
+ /**
+ * Lightweight parent/group links for the FULL message tree of a topic,
+ * INCLUDING messages hidden inside MessageGroups (compression / parallel).
+ *
+ * `query` replaces grouped messages with synthetic group nodes that expose
+ * neither their members' `parentId` nor (for compaction) the group's
+ * `parentMessageId`, so branch-ancestry can't be reconstructed from `query`
+ * output alone. This returns the raw `id β†’ parentId` / `messageGroupId` links
+ * so callers (e.g. server-runtime regenerate pruning) can walk ancestry across
+ * a compacted range.
+ */
+ queryTopicMessageTree = async ({
+ threadId,
+ topicId,
+ }: {
+ threadId?: string | null;
+ topicId: string;
+ }): Promise<{ id: string; messageGroupId: string | null; parentId: string | null }[]> => {
+ return this.db
+ .select({
+ id: messages.id,
+ messageGroupId: messages.messageGroupId,
+ parentId: messages.parentId,
+ })
+ .from(messages)
+ .where(and(this.ownership(), this.matchTopic(topicId), this.matchThread(threadId)));
+ };
+
/**
* Query messages with full relations (files, plugins, translations, etc.)
*