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.

✨ feat(topic): topic doctor — find and repair messages the reader is hiding (#17145)

Arvin Xua1966ecb24a9
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 67c1d716348..b0c5fc7201c 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -370,3 +370,14 @@ unquoted vars` — stashing `S="--session x --cdp 9226"` then `agent-browser $S`
you must not kill. Terminate the run, report the exact error, and ask the user to
clean up other processes — do not change watch mode, fall back to a static build, or
publish a report from a degraded surface.
+- **E7. The default `lobehub-dev` browser session is shared — a parallel run can steal your
+ tab.** `agent-browser` sessions are keyed by name, not by workspace, so two runs both using
+ `--session lobehub-dev` drive the **same** browser. The other run navigates the tab to _its_
+ dev server, after which your `eval` reads that page while `screenshot` may still show yours —
+ a screenshot that renders your fixture next to a `document.body.innerText` from the same
+ moment containing none of its strings, every assertion `false`. It reads like a product bug;
+ it is two runs sharing one browser. **Works**: give every run its own session name, seed auth
+ into it, and confirm the tab is yours before asserting — `agent-browser --session <name> tab
+ list` must print YOUR port and path. Same applies to ports: a worktree allocates its own
+ `SERVER_PORT`/`SPA_PORT`, so re-run `test-env.sh` inside the worktree you are testing rather
+ than assuming another checkout's ports.
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 8609ef12497..b9b37aacaae 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -16,6 +16,7 @@ import {
import { MessageModel } from '@/database/models/message';
import { TopicShareModel } from '@/database/models/topicShare';
import { CompressionRepository } from '@/database/repositories/compression';
+import { TopicDoctorRepo } from '@/database/repositories/topicDoctor';
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
@@ -36,6 +37,7 @@ const messageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
fileService: new FileService(ctx.serverDB, ctx.userId, wsId),
messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),
messageService: new MessageService(ctx.serverDB, ctx.userId, wsId),
+ topicDoctorRepo: new TopicDoctorRepo(ctx.serverDB, ctx.userId, wsId),
},
});
});
@@ -272,6 +274,28 @@ export const messageRouter = router({
return ctx.messageService.finalizeCompression(messageGroupId, content, params);
}),
+ /**
+ * Report the messages this topic's tree keeps off screen, and what could be done about it.
+ * Read-only — the repair is a separate, explicit call.
+ */
+ diagnoseTopic: messageProcedure
+ .input(z.object({ agentId: z.string().nullish(), topicId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ return ctx.topicDoctorRepo.diagnose(input);
+ }),
+
+ /**
+ * Rewrite the minimum needed to put those messages back on screen. The patch is re-derived
+ * from the database here rather than taken from the client — this edits conversation
+ * history, so it runs off the server's own view of the tree.
+ */
+ repairTopic: messageProcedure
+ .use(withScopedPermission('message:update'))
+ .input(z.object({ agentId: z.string().nullish(), topicId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ return ctx.topicDoctorRepo.repair(input);
+ }),
+
getHeatmaps: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.getHeatmaps();
}),
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 81ca83d95da..5aadfc73a46 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -26,6 +26,7 @@
"actions.copySessionIdSuccess": "Topic ID copied",
"actions.copyWorkingDirectory": "Copy Working Directory",
"actions.copyWorkingDirectorySuccess": "Working directory copied",
+ "actions.diagnose": "Check Message Chain",
"actions.duplicate": "Duplicate",
"actions.export": "Export Topics",
"actions.favorite": "Favorite",
@@ -46,6 +47,21 @@
"actions.unmarkCompleted": "Unarchive",
"defaultTitle": "Default Topic",
"displayItems": "Display Items",
+ "doctor.checkFailed": "The check could not be completed.",
+ "doctor.healthy": "Every message in this topic is showing. Nothing to fix.",
+ "doctor.issue.concurrent-fork": "A new question was sent while the previous run was still writing, so the conversation split in two and one side is hidden — {{count}} messages.",
+ "doctor.issue.lostContent": "{{count}} messages were saved empty: their text never reached the database.",
+ "doctor.issue.orphan-signal-turn": "A tool callback was attached to the wrong message, so it never shows up — {{count}} messages.",
+ "doctor.issue.segment-split": "A new message was sent before this topic finished loading, so a section of {{count}} messages broke off on its own — showing out of order and cut off from the assistant’s memory of the rest.",
+ "doctor.issue.stale-branch-index": "An interrupted regenerate left this message pointing at a branch that does not exist, hiding every answer under it — {{count}} messages.",
+ "doctor.notRepairable": "This cannot be undone — the content was never saved.",
+ "doctor.repair": "Repair",
+ "doctor.repairFailed": "Repair failed. Nothing was changed.",
+ "doctor.repaired_one": "Restored {{count}} message.",
+ "doctor.repaired_other": "Restored {{count}} messages.",
+ "doctor.summary_one": "{{count}} message exists in this topic but is not being shown.",
+ "doctor.summary_other": "{{count}} messages exist in this topic but are not being shown.",
+ "doctor.title": "Message Chain Check",
"draft": "[Draft]",
"duplicateLoading": "Copying Topic...",
"duplicateSuccess": "Topic Copied Successfully",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index feb96a91754..e657bbd6efa 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -26,6 +26,7 @@
"actions.copySessionIdSuccess": "会话 ID 已复制",
"actions.copyWorkingDirectory": "复制工作目录",
"actions.copyWorkingDirectorySuccess": "工作目录已复制",
+ "actions.diagnose": "检查消息链路",
"actions.duplicate": "复制",
"actions.export": "导出话题",
"actions.favorite": "收藏",
@@ -46,6 +47,21 @@
"actions.unmarkCompleted": "取消归档",
"defaultTitle": "默认话题",
"displayItems": "显示条目",
+ "doctor.checkFailed": "检查未能完成。",
+ "doctor.healthy": "这个话题的消息都正常显示,无需修复。",
+ "doctor.issue.concurrent-fork": "上一轮还在输出时你发了新问题,对话分成了两支,其中一支被隐藏了 —— 共 {{count}} 条消息。",
+ "doctor.issue.lostContent": "有 {{count}} 条消息存进来时是空的:正文没能写入数据库。",
+ "doctor.issue.orphan-signal-turn": "工具回调挂到了错误的消息上,导致它始终不显示 —— 共 {{count}} 条消息。",
+ "doctor.issue.segment-split": "在话题还没加载完时就发出了新消息,导致一段 {{count}} 条消息脱离主链、自成一支 —— 显示顺序错乱,且与助手对其余对话的记忆断开。",
+ "doctor.issue.stale-branch-index": "一次中断的重新生成,让这条消息指向了不存在的分支,它下面的回答全部被隐藏 —— 共 {{count}} 条消息。",
+ "doctor.notRepairable": "无法恢复 —— 这部分内容从未被保存。",
+ "doctor.repair": "修复",
+ "doctor.repairFailed": "修复失败,未做任何改动。",
+ "doctor.repaired_one": "已恢复 {{count}} 条消息。",
+ "doctor.repaired_other": "已恢复 {{count}} 条消息。",
+ "doctor.summary_one": "这个话题里有 {{count}} 条消息存在,但没有显示出来。",
+ "doctor.summary_other": "这个话题里有 {{count}} 条消息存在,但没有显示出来。",
+ "doctor.title": "消息链路检查",
"draft": "[草稿]",
"duplicateLoading": "话题复制中…",
"duplicateSuccess": "话题复制成功",
diff --git a/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts b/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts
new file mode 100644
index 00000000000..d11687bb286
--- /dev/null
+++ b/packages/conversation-flow/src/doctor/__tests__/diagnose.test.ts
@@ -0,0 +1,481 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../../parse';
+import type { Message } from '../../types';
+import { diagnoseTopic } from '../diagnose';
+
+interface Spec {
+ content?: string;
+ error?: any;
+ id: string;
+ meta?: Record<string, any>;
+ parent?: string;
+ reasoning?: any;
+ role: 'user' | 'assistant' | 'tool';
+ t: number;
+ toolCallId?: string;
+ tools?: string[];
+}
+
+const build = (specs: Spec[]): Message[] =>
+ specs.map(
+ ({ content, error, id, meta, parent, reasoning, role, t, toolCallId, tools }) =>
+ ({
+ agentId: 'agt_1',
+ content: content ?? '',
+ createdAt: t,
+ error,
+ id,
+ metadata: meta,
+ parentId: parent,
+ reasoning,
+ role,
+ tool_call_id: toolCallId,
+ tools: tools?.map((callId) => ({
+ apiName: 'run',
+ arguments: '{}',
+ id: callId,
+ identifier: 'shell',
+ type: 'builtin',
+ })),
+ }) as unknown as Message,
+ );
+
+/** Ids the renderer actually surfaces, at any nesting depth. */
+const renderedIds = (messages: Message[]): Set<string> => {
+ const out = new Set<string>();
+ const walk = (node: unknown) => {
+ if (Array.isArray(node)) return node.forEach(walk);
+ if (!node || typeof node !== 'object') return;
+ const record = node as Record<string, unknown>;
+ for (const key of ['id', 'result_msg_id']) {
+ if (typeof record[key] === 'string') out.add(record[key] as string);
+ }
+ Object.values(record).forEach((v) => v && typeof v === 'object' && walk(v));
+ };
+ walk(parse(messages).flatList);
+ return out;
+};
+
+const applyPatch = (messages: Message[], patch: ReturnType<typeof diagnoseTopic>['patch']) =>
+ messages.map((m) => {
+ const op = patch.find((o) => o.messageId === m.id);
+ if (op?.type === 'reparent') return { ...m, parentId: op.parentId };
+ if (op?.type === 'set-branch-index')
+ return { ...m, metadata: { ...m.metadata, activeBranchIndex: op.index } };
+ return m;
+ });
+
+describe('diagnoseTopic', () => {
+ it('reports nothing for a healthy conversation', () => {
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'hi', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ { content: 'done', id: 'a2', parent: 'a1', role: 'assistant', t: 30 },
+ { id: 'u2', parent: 'a2', role: 'user', t: 40 },
+ { content: 'ok', id: 'a3', parent: 'u2', role: 'assistant', t: 50 },
+ ]);
+
+ expect(diagnoseTopic(messages)).toEqual({ hiddenCount: 0, issues: [], patch: [] });
+ });
+
+ describe('concurrent fork', () => {
+ // A user turn starts while the previous run is still writing: the run's remaining steps
+ // and the new turn both hang off the pre-fork anchor, and the reader follows only one.
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'working', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ // the run keeps going under a1 …
+ { content: 'still working', id: 'a2', parent: 'a1', role: 'assistant', t: 30, tools: ['c2'] },
+ { content: 'out', id: 't2', parent: 'a2', role: 'tool', t: 40, toolCallId: 'c2' },
+ { content: 'run finished', id: 'a3', parent: 'a2', role: 'assistant', t: 50 },
+ // … while the user interjects, also under a1
+ { content: 'wait, also do X', id: 'u2', parent: 'a1', role: 'user', t: 35 },
+ { content: 'sure', id: 'b1', parent: 'u2', role: 'assistant', t: 45 },
+ ]);
+
+ it('detects the fork and hides one of the two branches', () => {
+ const { hiddenCount, issues, patch } = diagnoseTopic(messages);
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ kind: 'concurrent-fork',
+ messageId: 'a1',
+ repairable: true,
+ });
+ expect(hiddenCount).toBeGreaterThan(0);
+ // the user's own turn is what the reader drops
+ expect(issues[0].hiddenMessageIds).toEqual(expect.arrayContaining(['u2', 'b1']));
+
+ // repair re-anchors the interjection onto the tail of the run it interrupted
+ expect(patch).toEqual([{ messageId: 'u2', parentId: 'a3', type: 'reparent' }]);
+ });
+
+ it('makes every message visible again once repaired', () => {
+ const { patch } = diagnoseTopic(messages);
+ const repaired = applyPatch(messages, patch);
+
+ const rendered = renderedIds(repaired);
+ for (const message of repaired) expect(rendered.has(message.id)).toBe(true);
+ expect(diagnoseTopic(repaired).issues).toHaveLength(0);
+ });
+ });
+
+ describe('branches the user chose are left alone', () => {
+ it('ignores a regenerated answer', () => {
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'first try', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'second try', id: 'a2', parent: 'u1', role: 'assistant', t: 100 },
+ ]);
+
+ expect(diagnoseTopic(messages).issues).toHaveLength(0);
+ });
+
+ it('ignores a user branching off an earlier message after the run finished', () => {
+ // Same shape as a concurrent fork — a user child and an assistant child under one
+ // parent — but the subtrees do not overlap in time, so nothing was racing: the user
+ // deliberately went back and forked. Time overlap is the only thing separating the two.
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'working', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ { content: 'run finished', id: 'a2', parent: 'a1', role: 'assistant', t: 30 },
+ // long after the run ended
+ { content: 'actually, rewind', id: 'u2', parent: 'a1', role: 'user', t: 1000 },
+ { content: 'ok', id: 'b1', parent: 'u2', role: 'assistant', t: 1010 },
+ ]);
+
+ expect(diagnoseTopic(messages).issues).toHaveLength(0);
+ });
+ });
+
+ describe('stale branch index', () => {
+ // The client bumps activeBranchIndex ahead of itself while a regenerate is starting. If
+ // that run never lands, the index points past every branch and the resolver returns
+ // nothing — dropping all of them, including the answer the user already had.
+ const messages = build([
+ { id: 'u1', meta: { activeBranchIndex: 2 }, role: 'user', t: 0 },
+ { content: 'first try', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'second try', id: 'a2', parent: 'u1', role: 'assistant', t: 100 },
+ ]);
+
+ it('detects every branch being dropped', () => {
+ const { hiddenCount, issues, patch } = diagnoseTopic(messages);
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ kind: 'stale-branch-index',
+ messageId: 'u1',
+ repairable: true,
+ });
+ expect(issues[0].hiddenMessageIds).toEqual(expect.arrayContaining(['a1', 'a2']));
+ expect(hiddenCount).toBe(2);
+ expect(patch).toEqual([{ index: 1, messageId: 'u1', type: 'set-branch-index' }]);
+ });
+
+ it('points the index back at the newest branch that exists', () => {
+ const repaired = applyPatch(messages, diagnoseTopic(messages).patch);
+
+ expect(renderedIds(repaired).has('a2')).toBe(true);
+ expect(diagnoseTopic(repaired).issues).toHaveLength(0);
+ });
+
+ it('leaves an in-bounds index alone, discarded branch and all', () => {
+ // a1 is the regenerate the user threw away. It is invisible on purpose.
+ const branched = build([
+ { id: 'u1', meta: { activeBranchIndex: 1 }, role: 'user', t: 0 },
+ { content: 'first try', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'second try', id: 'a2', parent: 'u1', role: 'assistant', t: 100 },
+ ]);
+
+ expect(renderedIds(branched).has('a1')).toBe(false);
+ expect(diagnoseTopic(branched).issues).toHaveLength(0);
+ });
+
+ it('leaves a stale index above a single child alone', () => {
+ // With nothing to choose between, the reader never consults the index — the answer
+ // renders fine and there is nothing to repair.
+ const single = build([
+ { id: 'u1', meta: { activeBranchIndex: 1 }, role: 'user', t: 0 },
+ { content: 'the answer', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ ]);
+
+ expect(renderedIds(single).has('a1')).toBe(true);
+ expect(diagnoseTopic(single).issues).toHaveLength(0);
+ });
+ });
+
+ describe('a dropped message counts as restorable whenever the user would see it', () => {
+ // `hasSubstance` decides whether a repair is worth offering. It has to agree with what the
+ // renderer actually puts on screen — a message with no text but an error, or reasoning, is
+ // still visible, and reporting that topic as healthy would strand the message for good.
+ const branchesOf = (extra: Partial<Spec>) =>
+ build([
+ { id: 'u1', meta: { activeBranchIndex: 2 }, role: 'user', t: 0 },
+ { ...extra, id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { ...extra, id: 'a2', parent: 'u1', role: 'assistant', t: 100 },
+ ]);
+
+ it.each([
+ ['an error and no text', { error: { type: 'PluginServerError' } }],
+ ['reasoning and no text', { reasoning: { content: 'thinking…' } }],
+ ])('offers a repair for a message carrying %s', (_label, extra) => {
+ const messages = branchesOf(extra);
+
+ expect(renderedIds(messages).has('a2')).toBe(false);
+ expect(diagnoseTopic(messages).issues).toHaveLength(1);
+ expect(diagnoseTopic(messages).patch).toEqual([
+ { index: 1, messageId: 'u1', type: 'set-branch-index' },
+ ]);
+ });
+
+ it('stays quiet when the dropped messages carry only token usage', () => {
+ // Nothing to put back on screen — restoring a blank is not a repair.
+ const messages = branchesOf({ meta: { usage: { totalTokens: 12 } } });
+
+ expect(diagnoseTopic(messages).issues).toHaveLength(0);
+ });
+ });
+
+ describe('orphan signal turn', () => {
+ const signal = { sourceToolCallId: 'c1', sourceToolName: 'shell', type: 'tool-stdout' };
+
+ it('re-anchors a callback turn the reader drops onto the tool that triggered it', () => {
+ // The turn is only really lost when the chain has a competing continuation: the
+ // collector filters signal turns out of its candidates, picks the sibling, and the
+ // callback is emitted by nobody.
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ {
+ content: 'running',
+ id: 'a1',
+ parent: 'u1',
+ role: 'assistant',
+ t: 10,
+ tools: ['c1', 'c2'],
+ },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ // must hang off t1 (the call the signal names), not a1
+ {
+ content: 'the task finished, here is the summary',
+ id: 's1',
+ meta: { signal },
+ parent: 'a1',
+ role: 'assistant',
+ t: 30,
+ },
+ { content: 'out', id: 't2', parent: 'a1', role: 'tool', t: 40, toolCallId: 'c2' },
+ { content: 'final answer', id: 'a2', parent: 'a1', role: 'assistant', t: 50 },
+ ]);
+
+ const { issues, patch } = diagnoseTopic(messages);
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ hiddenMessageIds: ['s1'],
+ kind: 'orphan-signal-turn',
+ messageId: 's1',
+ repairable: true,
+ });
+ // anchored by the signal's own sourceToolCallId, not by "the most recent tool"
+ expect(patch).toEqual([{ messageId: 's1', parentId: 't1', type: 'reparent' }]);
+ expect(renderedIds(applyPatch(messages, patch)).has('s1')).toBe(true);
+ });
+
+ it('leaves a mis-parented callback turn alone when the reader still shows it', () => {
+ // Same defect in the tree, but this chain happens to surface it anyway. Rewriting
+ // history to fix something the user can already see is churn, not a repair.
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'running', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ {
+ content: 'saw output',
+ id: 's1',
+ meta: { signal },
+ parent: 'a1',
+ role: 'assistant',
+ t: 30,
+ },
+ ]);
+
+ expect(renderedIds(messages).has('s1')).toBe(true);
+ expect(diagnoseTopic(messages).issues).toHaveLength(0);
+ });
+ });
+
+ describe('lost content', () => {
+ // Rows the writer created but never filled in. Nothing to re-link and nothing worth
+ // deleting — the text never reached the database. Report it, offer no repair.
+ it('reports a run of empty shells as unrecoverable', () => {
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'step', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ { id: 'shell1', parent: 'a1', role: 'assistant', t: 30 },
+ { id: 'shell2', parent: 'shell1', role: 'assistant', t: 40 },
+ { id: 'shell3', parent: 'shell2', role: 'assistant', t: 50 },
+ { content: 'next question', id: 'u2', parent: 'shell3', role: 'user', t: 60 },
+ { content: 'ok', id: 'a2', parent: 'u2', role: 'assistant', t: 70 },
+ ]);
+
+ const { issues, patch } = diagnoseTopic(messages);
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ kind: 'lost-content',
+ lostMessageIds: ['shell1', 'shell2', 'shell3'],
+ messageId: 'shell1',
+ repairable: false,
+ });
+ expect(patch).toHaveLength(0);
+ });
+
+ it('ignores a lone turn-final shell', () => {
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'step', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ { id: 'shell1', parent: 'a1', role: 'assistant', t: 30 },
+ { content: 'next question', id: 'u2', parent: 'shell1', role: 'user', t: 60 },
+ { content: 'ok', id: 'a2', parent: 'u2', role: 'assistant', t: 70 },
+ ]);
+
+ expect(diagnoseTopic(messages).issues).toHaveLength(0);
+ });
+
+ it('never treats a message carrying token usage as a shell', () => {
+ const messages = build([
+ { id: 'u1', role: 'user', t: 0 },
+ { content: 'step', id: 'a1', parent: 'u1', role: 'assistant', t: 10, tools: ['c1'] },
+ { content: 'out', id: 't1', parent: 'a1', role: 'tool', t: 20, toolCallId: 'c1' },
+ {
+ id: 'usageOnly1',
+ meta: { usage: { totalTokens: 12 } },
+ parent: 'a1',
+ role: 'assistant',
+ t: 30,
+ },
+ {
+ id: 'usageOnly2',
+ meta: { usage: { totalTokens: 34 } },
+ parent: 'usageOnly1',
+ role: 'assistant',
+ t: 40,
+ },
+ { content: 'done', id: 'a2', parent: 'usageOnly2', role: 'assistant', t: 50 },
+ ]);
+
+ expect(diagnoseTopic(messages).issues).toHaveLength(0);
+ });
+ });
+
+ describe('segment split', () => {
+ // A new turn was sent while the local list was still empty, so it landed with no parent
+ // and a whole section broke off onto its own root — rendered, but out of order and cut
+ // off from the model's context.
+ const messages = build([
+ { content: 'first question', id: 'u1', role: 'user', t: 0 },
+ { content: 'first answer', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ // sent the next session with an empty list → no parent
+ { content: 'second question', id: 'u2', role: 'user', t: 100 },
+ { content: 'second answer', id: 'a2', parent: 'u2', role: 'assistant', t: 110 },
+ ]);
+
+ it('reattaches the stranded section onto the tail of what came before', () => {
+ const { hiddenCount, issues, patch } = diagnoseTopic(messages);
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({
+ kind: 'segment-split',
+ messageId: 'u2',
+ repairable: true,
+ });
+ // Nothing is hidden — the section renders, just on its own root.
+ expect(hiddenCount).toBe(0);
+ expect(issues[0].hiddenMessageIds).toEqual([]);
+ expect(issues[0].reattachedMessageIds).toEqual(expect.arrayContaining(['u2', 'a2']));
+
+ expect(patch).toEqual([{ messageId: 'u2', parentId: 'a1', type: 'reparent' }]);
+ });
+
+ it('collapses the tree to a single root once repaired', () => {
+ const { patch } = diagnoseTopic(messages);
+ const repaired = applyPatch(messages, patch);
+
+ const roots = repaired.filter(
+ (m) => !m.parentId || !repaired.some((o) => o.id === m.parentId),
+ );
+ expect(roots).toHaveLength(1);
+
+ const rendered = renderedIds(repaired);
+ for (const message of repaired) expect(rendered.has(message.id)).toBe(true);
+ expect(diagnoseTopic(repaired).issues).toHaveLength(0);
+ });
+
+ it('treats a dangling parent the same as a missing one', () => {
+ // The parent id was never synced, so the reader turns it into a second root just as it
+ // does for a null parent.
+ const dangling = build([
+ { content: 'q', id: 'u1', role: 'user', t: 0 },
+ { content: 'a', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'later q', id: 'u2', parent: 'ghost', role: 'user', t: 100 },
+ { content: 'later a', id: 'a2', parent: 'u2', role: 'assistant', t: 110 },
+ ]);
+
+ expect(diagnoseTopic(dangling).patch).toEqual([
+ { messageId: 'u2', parentId: 'a1', type: 'reparent' },
+ ]);
+ });
+
+ it('chains several stranded sections back in time order', () => {
+ const three = build([
+ { content: 'q1', id: 'u1', role: 'user', t: 0 },
+ { content: 'a1', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'q2', id: 'u2', role: 'user', t: 100 },
+ { content: 'a2', id: 'a2', parent: 'u2', role: 'assistant', t: 110 },
+ { content: 'q3', id: 'u3', role: 'user', t: 200 },
+ { content: 'a3', id: 'a3', parent: 'u3', role: 'assistant', t: 210 },
+ ]);
+
+ const { patch } = diagnoseTopic(three);
+ expect(patch).toEqual([
+ { messageId: 'u2', parentId: 'a1', type: 'reparent' },
+ { messageId: 'u3', parentId: 'a2', type: 'reparent' },
+ ]);
+
+ const repaired = applyPatch(three, patch);
+ const roots = repaired.filter(
+ (m) => !m.parentId || !repaired.some((o) => o.id === m.parentId),
+ );
+ expect(roots).toHaveLength(1);
+ expect(diagnoseTopic(repaired).issues).toHaveLength(0);
+ });
+
+ it('leaves a parentless assistant seed for a human to look at', () => {
+ // A re-entry always starts with a user turn; a rootless assistant is a murkier shape
+ // (a lost seed, not someone typing again) and must not be auto-rewired.
+ const strayAssistant = build([
+ { content: 'q', id: 'u1', role: 'user', t: 0 },
+ { content: 'a', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'orphan seed', id: 'a2', role: 'assistant', t: 100 },
+ ]);
+
+ expect(diagnoseTopic(strayAssistant).issues).toHaveLength(0);
+ });
+
+ it('does not touch a healthy single-root topic', () => {
+ const healthy = build([
+ { content: 'q', id: 'u1', role: 'user', t: 0 },
+ { content: 'a', id: 'a1', parent: 'u1', role: 'assistant', t: 10 },
+ { content: 'q2', id: 'u2', parent: 'a1', role: 'user', t: 20 },
+ { content: 'a2', id: 'a2', parent: 'u2', role: 'assistant', t: 30 },
+ ]);
+
+ expect(diagnoseTopic(healthy).issues).toHaveLength(0);
+ });
+ });
+});
diff --git a/packages/conversation-flow/src/doctor/diagnose.ts b/packages/conversation-flow/src/doctor/diagnose.ts
new file mode 100644
index 00000000000..b3e9d877ab8
--- /dev/null
+++ b/packages/conversation-flow/src/doctor/diagnose.ts
@@ -0,0 +1,348 @@
+import { parse } from '../parse';
+import type { Message, MessageGroupMetadata } from '../types';
+import type { RepairOp, TopicDiagnosis, TopicIssue } from './types';
+
+/**
+ * Every message id referenced anywhere in the rendered payload.
+ *
+ * The renderer does not emit one flat entry per message: tool results live in
+ * `children[].tools[].result_msg_id`, signal turns in `signalCallbacks[]`, post-task
+ * summaries in `taskCompletions[]`, and so on. Rather than mirror each nesting site
+ * (and silently start over-reporting whenever a new one is added), walk the payload
+ * generically and collect anything that could be a message id. Ids that are not
+ * messages (tool_call ids) fall out when the set is intersected with the topic.
+ */
+const collectRenderedIds = (node: unknown, out: Set<string>): void => {
+ if (Array.isArray(node)) {
+ for (const item of node) collectRenderedIds(item, out);
+ return;
+ }
+ if (!node || typeof node !== 'object') return;
+
+ const record = node as Record<string, unknown>;
+ for (const key of ['id', 'result_msg_id', 'sourceToolMessageId']) {
+ const value = record[key];
+ if (typeof value === 'string') out.add(value);
+ }
+ for (const value of Object.values(record)) {
+ if (value && typeof value === 'object') collectRenderedIds(value, out);
+ }
+};
+
+/** A toolless assistant tagged with a signal — a reactive callback turn, not a main-chain step. */
+const getSignal = (message: Message): { sourceToolCallId?: string } | undefined => {
+ if (message.role !== 'assistant') return undefined;
+ if (message.tools && message.tools.length > 0) return undefined;
+ return (message.metadata as { signal?: { sourceToolCallId?: string } } | null | undefined)
+ ?.signal;
+};
+
+/**
+ * Anything the user would actually see if this message were put back on screen. An error, a
+ * reasoning block or an audio clip is as visible as text — a message carrying only one of
+ * those is still worth restoring.
+ *
+ * Token accounting deliberately does not count: a turn-final assistant with usage but no
+ * text renders nothing.
+ */
+const hasSubstance = (message: Message): boolean =>
+ !!message.content?.trim() ||
+ !!message.reasoning ||
+ !!message.error ||
+ !!message.tools?.length ||
+ !!message.imageList?.length ||
+ !!message.fileList?.length ||
+ !!message.audioList?.length;
+
+/**
+ * An assistant that carries nothing at all: the writer created the row but its content and
+ * tool calls never landed. Derived from `hasSubstance` rather than restating it, so the two
+ * cannot drift — a shape counted as visible must never also be counted as an empty shell.
+ *
+ * Usage is the one exception: a turn-final assistant with tokens but no content is a
+ * legitimate shape (the group aggregates them), not a row that failed to be written.
+ */
+const isEmptyShell = (message: Message): boolean =>
+ message.role === 'assistant' &&
+ !hasSubstance(message) &&
+ !message.usage &&
+ !(message.metadata as { usage?: unknown } | null | undefined)?.usage;
+
+/** Mirrors the write-side anchor rule: tool messages and toolless signal turns are never a spine tail. */
+const canAnchor = (message: Message): boolean =>
+ message.role !== 'tool' && !getSignal(message) && !isEmptyShell(message);
+
+const timeSpan = (messages: Message[]): [number, number] => [
+ Math.min(...messages.map((m) => m.createdAt)),
+ Math.max(...messages.map((m) => m.createdAt)),
+];
+
+const overlaps = (a: [number, number], b: [number, number]): boolean =>
+ a[0] <= b[1] && b[0] <= a[1];
+
+/**
+ * Diagnose a topic's message tree.
+ *
+ * Ground truth for "the user cannot see this message" is the renderer itself: run the
+ * real `parse()` and diff its output against the tree. That diff is only a *candidate*
+ * set though — the losing side of a regenerate branch is unreachable by design. So each
+ * candidate is then attributed to a known defect shape, and only attributed messages are
+ * reported. Anything we cannot explain is left alone.
+ */
+export const diagnoseTopic = (
+ messages: Message[],
+ messageGroups?: MessageGroupMetadata[],
+): TopicDiagnosis => {
+ const mainFlow = messages.filter((m) => !m.threadId);
+ if (mainFlow.length === 0) return { hiddenCount: 0, issues: [], patch: [] };
+
+ const sorted = [...mainFlow].sort((a, b) => a.createdAt - b.createdAt);
+ const byId = new Map(sorted.map((m) => [m.id, m]));
+
+ const childrenOf = new Map<string, Message[]>();
+ for (const message of sorted) {
+ if (!message.parentId || !byId.has(message.parentId)) continue;
+ const siblings = childrenOf.get(message.parentId) ?? [];
+ siblings.push(message);
+ childrenOf.set(message.parentId, siblings);
+ }
+
+ const subtreeOf = (rootId: string): Message[] => {
+ const collected: Message[] = [];
+ const seen = new Set<string>();
+ const stack = [rootId];
+ while (stack.length > 0) {
+ const id = stack.pop()!;
+ if (seen.has(id)) continue;
+ seen.add(id);
+ const message = byId.get(id);
+ if (message) collected.push(message);
+ for (const child of childrenOf.get(id) ?? []) stack.push(child.id);
+ }
+ return collected;
+ };
+
+ const renderedIds = new Set<string>();
+ collectRenderedIds(parse(messages, messageGroups).flatList, renderedIds);
+ const isHidden = (message: Message) => !renderedIds.has(message.id);
+
+ /**
+ * The messages a repair would put back on screen — but only if at least one of them is
+ * worth putting back. A dropped turn that is itself empty (an empty callback turn, say)
+ * costs the user nothing, and rewriting their history to restore a blank is not a repair.
+ */
+ const restorable = (candidates: Message[]): string[] => {
+ const hiddenOnes = candidates.filter((m) => isHidden(m));
+ return hiddenOnes.some((m) => hasSubstance(m)) ? hiddenOnes.map((m) => m.id) : [];
+ };
+
+ const issues: TopicIssue[] = [];
+ const patch: RepairOp[] = [];
+ const hidden = new Set<string>();
+
+ const report = (issue: TopicIssue, op?: RepairOp) => {
+ issues.push(issue);
+ for (const id of issue.hiddenMessageIds) hidden.add(id);
+ if (op) patch.push(op);
+ };
+
+ // 0. Segment split: the client sent a turn while its local message list was still empty, so
+ // the new turn landed with no parent (or a parent that never synced) and became a second
+ // root. Every root but the earliest is a section that broke off mid-conversation: the
+ // reader still shows it, but on its own root it sorts by tree order rather than time —
+ // scrambling the transcript — and, worse, it starts a fresh parent chain, so the model
+ // loses all the history before it.
+ //
+ // Unlike the reachability rules this one is not "the message is hidden" — it is "the
+ // message is stranded". It is disjoint from the fork/branch rules by construction: those
+ // walk `childrenOf`, which only links messages to a parent that exists, so a root is
+ // never one of their branches.
+ const roots = sorted.filter((m) => !m.parentId || !byId.has(m.parentId));
+ if (roots.length > 1) {
+ // The earliest root is the conversation's real start and stays put; the rest are splits.
+ const [, ...strandedRoots] = roots;
+ for (const root of strandedRoots) {
+ // A stranded section always begins with a user turn — an assistant with no parent is a
+ // murkier shape (a lost seed, not a re-entry), so leave it for a human to look at.
+ if (root.role !== 'user') continue;
+
+ const section = subtreeOf(root.id);
+ if (!section.some((m) => hasSubstance(m))) continue;
+
+ // Reattach to the tail of what came before: the most recent real spine message written
+ // before this section began. Tool results and signal turns are never a spine tail, and
+ // a message inside this very section can't anchor it.
+ const sectionIds = new Set(section.map((m) => m.id));
+ const anchor = sorted
+ .filter((m) => canAnchor(m) && m.createdAt < root.createdAt && !sectionIds.has(m.id))
+ .sort((a, b) => b.createdAt - a.createdAt)[0];
+ if (!anchor) continue;
+
+ report(
+ {
+ hiddenMessageIds: [],
+ kind: 'segment-split',
+ messageId: root.id,
+ reattachedMessageIds: section.map((m) => m.id),
+ repairable: true,
+ },
+ { messageId: root.id, parentId: anchor.id, type: 'reparent' },
+ );
+ }
+ }
+
+ // 1. Concurrent fork: a user turn started while the previous run was still writing, so the
+ // run's remaining steps and the new turn both hang off the same pre-fork anchor. The
+ // reader can only follow one of them. Distinguishing this from a regenerate branch is
+ // the time overlap: a branch the user *chose* starts after its sibling is finished.
+ for (const [parentId, allChildren] of childrenOf) {
+ const branches = allChildren.filter((m) => m.role !== 'tool');
+ if (branches.length < 2) continue;
+
+ const userTurns = branches.filter((m) => m.role === 'user');
+ const continuations = branches.filter((m) => m.role === 'assistant');
+ if (userTurns.length === 0 || continuations.length === 0) continue;
+
+ for (const userTurn of userTurns) {
+ const userSubtree = subtreeOf(userTurn.id);
+ const userSpan = timeSpan(userSubtree);
+
+ for (const continuation of continuations) {
+ const runSubtree = subtreeOf(continuation.id);
+ if (!overlaps(userSpan, timeSpan(runSubtree))) continue;
+
+ // The assistant branch is the interrupted run finishing its turn — it keeps the
+ // anchor. The user's message belongs after that run, on the tail of its spine.
+ const runIds = new Set(runSubtree.map((m) => m.id));
+ const anchor = [...runSubtree]
+ .filter((m) => canAnchor(m))
+ .sort((a, b) => b.createdAt - a.createdAt)[0];
+
+ // The shape is wrong, but if the reader still gets everything on screen there is
+ // nothing to fix and no reason to rewrite the user's history.
+ const hiddenHere = restorable([...userSubtree, ...runSubtree]);
+ if (hiddenHere.length === 0) continue;
+
+ report(
+ {
+ hiddenMessageIds: hiddenHere,
+ kind: 'concurrent-fork',
+ messageId: parentId,
+ repairable: !!anchor && !runIds.has(userTurn.id),
+ },
+ anchor && !runIds.has(userTurn.id)
+ ? { messageId: userTurn.id, parentId: anchor.id, type: 'reparent' }
+ : undefined,
+ );
+ }
+ }
+ }
+
+ // 2. Orphan signal turn: a toolless callback turn must hang off the tool message that
+ // triggered it. Parented off an assistant it falls between two stools — the main chain
+ // filters signal turns out, and the signal collectors only scan a tool's children.
+ //
+ // Being mis-parented is not enough to act on, though: depending on the surrounding
+ // chain the reader sometimes still surfaces it. Only the ones it genuinely drops are
+ // reported — the renderer, not the shape, decides what counts as broken.
+ for (const message of sorted) {
+ const signal = getSignal(message);
+ if (!signal || !message.parentId) continue;
+ if (byId.get(message.parentId)?.role === 'tool') continue;
+
+ const ownSubtree = subtreeOf(message.id);
+ const hiddenHere = restorable(ownSubtree);
+ if (hiddenHere.length === 0) continue;
+
+ const ownIds = new Set(ownSubtree.map((m) => m.id));
+ const candidates = sorted.filter(
+ (m) => m.role === 'tool' && m.createdAt < message.createdAt && !ownIds.has(m.id),
+ );
+ // The signal names the tool call it is reacting to; fall back to the most recent tool
+ // result only when that call cannot be found.
+ const anchor =
+ candidates.find((m) => m.tool_call_id && m.tool_call_id === signal.sourceToolCallId) ??
+ candidates.at(-1);
+
+ report(
+ {
+ hiddenMessageIds: hiddenHere,
+ kind: 'orphan-signal-turn',
+ messageId: message.id,
+ repairable: !!anchor,
+ },
+ anchor ? { messageId: message.id, parentId: anchor.id, type: 'reparent' } : undefined,
+ );
+ }
+
+ // 3. Stale branch index: `activeBranchIndex === children.length` is the legitimate
+ // "the branch is being created" state during streaming. Left behind on a finished turn —
+ // the regenerate was aborted, so the branch never materialised — the resolver returns
+ // nothing and every branch under that message disappears. Point the index back at the
+ // newest branch that does exist, which is as close to the intent as we can get.
+ //
+ // Branch resolution only runs when there is a choice to make, so a stale index above a
+ // single child changes nothing and must be left alone. Getting this wrong means
+ // silently flipping which regenerate a user chose to keep.
+ for (const [parentId, allChildren] of childrenOf) {
+ const parent = byId.get(parentId);
+ const branches = allChildren.filter((m) => m.role !== 'tool');
+ if (!parent || branches.length < 2) continue;
+
+ const index = (parent.metadata as { activeBranchIndex?: number } | null | undefined)
+ ?.activeBranchIndex;
+ if (typeof index !== 'number' || index < branches.length) continue;
+
+ // Out of bounds for every branch, so the reader shows none of them — unlike a valid
+ // index, where the branches it passes over are the ones the user discarded.
+ const hiddenHere = restorable(branches.flatMap((branch) => subtreeOf(branch.id)));
+ if (hiddenHere.length === 0) continue;
+
+ report(
+ {
+ hiddenMessageIds: hiddenHere,
+ kind: 'stale-branch-index',
+ messageId: parentId,
+ repairable: true,
+ },
+ { index: branches.length - 1, messageId: parentId, type: 'set-branch-index' },
+ );
+ }
+
+ // 4. Lost content: rows the writer created but never filled in. They are absorbed into the
+ // assistant group as empty blocks rather than shown as blank bubbles, so there is
+ // nothing to re-link and nothing to delete that the user would notice — the text simply
+ // never reached the database. Only a *run* of them is worth reporting: a lone turn-final
+ // shell is a harmless artifact, whereas consecutive shells mean a whole stretch of the
+ // conversation was dropped on the way in, and that is worth saying out loud.
+ // The newest message may be a placeholder a live run is still filling in.
+ const newestId = sorted.at(-1)?.id;
+ const shells = new Set(
+ sorted.filter((m) => isEmptyShell(m) && m.parentId && m.id !== newestId).map((m) => m.id),
+ );
+
+ // Chains are parent-linked, not adjacent in time — a tool result can land between two
+ // shells of the same broken run.
+ for (const message of sorted) {
+ if (!shells.has(message.id)) continue;
+ if (message.parentId && shells.has(message.parentId)) continue; // not the head of its chain
+
+ const chain: Message[] = [];
+ let cursor: Message | undefined = message;
+ while (cursor) {
+ chain.push(cursor);
+ cursor = (childrenOf.get(cursor.id) ?? []).find((c) => shells.has(c.id));
+ }
+ if (chain.length < 2) continue;
+
+ report({
+ hiddenMessageIds: [],
+ kind: 'lost-content',
+ lostMessageIds: chain.map((m) => m.id),
+ messageId: chain[0].id,
+ repairable: false,
+ });
+ }
+
+ return { hiddenCount: hidden.size, issues, patch };
+};
diff --git a/packages/conversation-flow/src/doctor/index.ts b/packages/conversation-flow/src/doctor/index.ts
new file mode 100644
index 00000000000..17cf3d69527
--- /dev/null
+++ b/packages/conversation-flow/src/doctor/index.ts
@@ -0,0 +1,2 @@
+export { diagnoseTopic } from './diagnose';
+export type { RepairOp, TopicDiagnosis, TopicIssue, TopicIssueKind } from './types';
diff --git a/packages/conversation-flow/src/doctor/types.ts b/packages/conversation-flow/src/doctor/types.ts
new file mode 100644
index 00000000000..2536d823b96
--- /dev/null
+++ b/packages/conversation-flow/src/doctor/types.ts
@@ -0,0 +1,52 @@
+/**
+ * Topic Doctor Types
+ *
+ * A diagnosis describes what the reader cannot show the user, plus the minimal set of
+ * writes that would make it visible again. Damage that cannot be undone (content that never
+ * reached the database) is reported too, but carries no repair — saying so plainly is more
+ * useful than a button that deletes rows and calls it a fix.
+ */
+
+export type TopicIssueKind =
+ /** A run kept writing under its pre-fork anchor while a new user turn started under the same parent */
+ | 'concurrent-fork'
+ /** A toolless signal turn parented off an assistant: the main chain filters it out and the signal collectors never scan it */
+ | 'orphan-signal-turn'
+ /** `metadata.activeBranchIndex` is out of bounds, so the branch resolver skips the whole subtree */
+ | 'stale-branch-index'
+ /** A new turn was sent with no parent mid-conversation, so a whole section detached into its own root */
+ | 'segment-split'
+ /** A run of assistant rows whose content and tool calls never landed — unrecoverable */
+ | 'lost-content';
+
+export interface TopicIssue {
+ /** Messages the reader does not render. Empty for issues that damage content rather than reachability. */
+ hiddenMessageIds: string[];
+ kind: TopicIssueKind;
+ /** Messages whose content is gone for good (`lost-content` only) */
+ lostMessageIds?: string[];
+ /** The message the issue is anchored on */
+ messageId: string;
+ /**
+ * The detached section reconnected by this repair (`segment-split` only). These render
+ * today, but on their own root — out of order and severed from the model's context chain.
+ */
+ reattachedMessageIds?: string[];
+ /**
+ * False when the shape is understood but nothing can be safely rewritten — the issue is
+ * still reported so the user knows why the conversation looks the way it does.
+ */
+ repairable: boolean;
+}
+
+export type RepairOp =
+ | { messageId: string; parentId: string; type: 'reparent' }
+ | { index: number; messageId: string; type: 'set-branch-index' };
+
+export interface TopicDiagnosis {
+ /** Messages that exist but are not rendered, attributable to an issue */
+ hiddenCount: number;
+ issues: TopicIssue[];
+ /** Ops to apply, in order. Empty when nothing is safely repairable. */
+ patch: RepairOp[];
+}
diff --git a/packages/conversation-flow/src/index.ts b/packages/conversation-flow/src/index.ts
index 06926457884..c972cf6d0d0 100644
--- a/packages/conversation-flow/src/index.ts
+++ b/packages/conversation-flow/src/index.ts
@@ -1,6 +1,10 @@
// Main parse function
export { parse } from './parse';
+// Topic Doctor - detect and repair message trees the reader cannot fully render
+export type { RepairOp, TopicDiagnosis, TopicIssue, TopicIssueKind } from './doctor';
+export { diagnoseTopic } from './doctor';
+
// Context Tree Types - for navigation and context understanding
export type {
AssistantGroupNode,
diff --git a/packages/database/src/repositories/topicDoctor/index.ts b/packages/database/src/repositories/topicDoctor/index.ts
new file mode 100644
index 00000000000..d316da6d955
--- /dev/null
+++ b/packages/database/src/repositories/topicDoctor/index.ts
@@ -0,0 +1,116 @@
+import { diagnoseTopic, type TopicDiagnosis } from '@lobechat/conversation-flow';
+import { and, eq, inArray } from 'drizzle-orm';
+import type { AnyPgColumn } from 'drizzle-orm/pg-core';
+
+import { MessageModel } from '../../models/message';
+import { messages } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+interface TopicScope {
+ agentId?: string | null;
+ topicId: string;
+}
+
+export interface RepairResult {
+ /** Ops actually written */
+ applied: number;
+ /** Messages the reader was dropping that it will now render */
+ restoredMessageIds: string[];
+}
+
+/**
+ * TopicDoctorRepo — finds the messages a topic's tree hides from the reader, and rewrites
+ * the minimum needed to bring them back.
+ *
+ * The patch is always re-derived here from the database rather than taken from the caller:
+ * the client's copy of the tree can be stale, and this rewrites conversation history, so it
+ * is worth paying a read to be certain of what is being changed.
+ */
+export class TopicDoctorRepo {
+ private db: LobeChatDatabase;
+ private messageModel: MessageModel;
+ private userId: string;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ this.messageModel = new MessageModel(db, userId, workspaceId);
+ }
+
+ private ws = (cols: { userId: AnyPgColumn; workspaceId: AnyPgColumn }) =>
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);
+
+ diagnose = async ({ agentId, topicId }: TopicScope): Promise<TopicDiagnosis> => {
+ // The same list the client renders from, so the `parse()` inside the diagnosis sees
+ // exactly what the user sees.
+ const list = await this.messageModel.query({ agentId, topicId });
+
+ return diagnoseTopic(list as any);
+ };
+
+ repair = async (scope: TopicScope): Promise<RepairResult> => {
+ const diagnosis = await this.diagnose(scope);
+ const { patch } = diagnosis;
+ if (patch.length === 0) return { applied: 0, restoredMessageIds: [] };
+
+ // Only ever touch real rows of this topic that the caller owns. The synthetic group
+ // nodes `query()` splices into the list are not messages and must never be written to.
+ const targets = await this.db
+ .select({ id: messages.id, metadata: messages.metadata, parentId: messages.parentId })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.topicId, scope.topicId),
+ this.ws(messages),
+ inArray(
+ messages.id,
+ patch.map((op) => op.messageId),
+ ),
+ ),
+ );
+
+ const targetById = new Map(targets.map((row) => [row.id, row]));
+ const writable = patch.filter((op) => targetById.has(op.messageId));
+
+ await this.db.transaction(async (tx) => {
+ for (const op of writable) {
+ const current = targetById.get(op.messageId)!;
+ const metadata = (current.metadata ?? {}) as Record<string, any>;
+
+ // Keep what the row looked like before, so a bad repair can be walked back.
+ const next: Record<string, any> =
+ op.type === 'reparent'
+ ? { ...metadata, repairedFrom: { parentId: current.parentId } }
+ : {
+ ...metadata,
+ activeBranchIndex: op.index,
+ repairedFrom: { activeBranchIndex: metadata.activeBranchIndex ?? null },
+ };
+
+ await tx
+ .update(messages)
+ .set({
+ metadata: next,
+ ...(op.type === 'reparent' ? { parentId: op.parentId } : {}),
+ // A repair changes how history is threaded, not when it was written.
+ updatedAt: messages.updatedAt,
+ })
+ .where(and(eq(messages.id, op.messageId), this.ws(messages)));
+ }
+ });
+
+ // Both the messages a repair un-hides and the detached sections it reconnects count as
+ // "brought back": the latter rendered before, but stranded on their own root and severed
+ // from the model's context — putting them back in the chain is the point of the fix.
+ const restoredMessageIds = [
+ ...new Set(
+ diagnosis.issues.flatMap((i) => [...i.hiddenMessageIds, ...(i.reattachedMessageIds ?? [])]),
+ ),
+ ];
+
+ return { applied: writable.length, restoredMessageIds };
+ };
+}
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index a9039dc3af1..7196fe7419a 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -2,6 +2,7 @@ export default {
'actions.addNewTopic': 'Start New Topic',
'actions.addNewTopicInProject': 'Start new topic in {{directory}}',
'actions.autoRename': 'Smart Rename',
+ 'actions.diagnose': 'Check Message Chain',
'actions.archiveMergedPullRequests': 'Archive Topics with Merged PRs',
'actions.archiveMergedPullRequestsOwn': 'Archive My Topics with Merged PRs',
'actions.archiveMergedPullRequestsWorkspace': 'Archive All Topics with Merged PRs',
@@ -53,6 +54,26 @@ export default {
'actions.removeUnstarredOwn': 'Delete My Unstarred Topics',
'actions.removeUnstarredWorkspace': 'Delete All Unstarred Topics',
'defaultTitle': 'Default Topic',
+ 'doctor.checkFailed': 'The check could not be completed.',
+ 'doctor.healthy': 'Every message in this topic is showing. Nothing to fix.',
+ 'doctor.issue.concurrent-fork':
+ 'A new question was sent while the previous run was still writing, so the conversation split in two and one side is hidden — {{count}} messages.',
+ 'doctor.issue.lostContent':
+ '{{count}} messages were saved empty: their text never reached the database.',
+ 'doctor.issue.orphan-signal-turn':
+ 'A tool callback was attached to the wrong message, so it never shows up — {{count}} messages.',
+ 'doctor.issue.segment-split':
+ 'A new message was sent before this topic finished loading, so a section of {{count}} messages broke off on its own — showing out of order and cut off from the assistant’s memory of the rest.',
+ 'doctor.issue.stale-branch-index':
+ 'An interrupted regenerate left this message pointing at a branch that does not exist, hiding every answer under it — {{count}} messages.',
+ 'doctor.notRepairable': 'This cannot be undone — the content was never saved.',
+ 'doctor.repair': 'Repair',
+ 'doctor.repairFailed': 'Repair failed. Nothing was changed.',
+ 'doctor.repaired_one': 'Restored {{count}} message.',
+ 'doctor.repaired_other': 'Restored {{count}} messages.',
+ 'doctor.summary_one': '{{count}} message exists in this topic but is not being shown.',
+ 'doctor.summary_other': '{{count}} messages exist in this topic but are not being shown.',
+ 'doctor.title': 'Message Chain Check',
'displayItems': 'Display Items',
'draft': '[Draft]',
'duplicateLoading': 'Copying Topic...',
diff --git a/src/features/TopicDoctorModal/Content.tsx b/src/features/TopicDoctorModal/Content.tsx
new file mode 100644
index 00000000000..8a576e10e4f
--- /dev/null
+++ b/src/features/TopicDoctorModal/Content.tsx
@@ -0,0 +1,153 @@
+'use client';
+
+import type { TopicIssue } from '@lobechat/conversation-flow';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button, useModalContext } from '@lobehub/ui/base-ui';
+import { Skeleton } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleAlert, CircleCheck, EyeOff, Stethoscope } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { message } from '@/components/AntdStaticMethods';
+import { messageService } from '@/services/message';
+import { useChatStore } from '@/store/chat';
+
+export interface TopicDoctorContentProps {
+ agentId?: string | null;
+ topicId: string;
+}
+
+const styles = createStaticStyles(({ css }) => ({
+ issue: css`
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+ `,
+}));
+
+const TopicDoctorContent = memo<TopicDoctorContentProps>(({ agentId, topicId }) => {
+ const { t } = useTranslation(['topic', 'common']);
+ const { close } = useModalContext();
+ const refreshMessages = useChatStore((s) => s.refreshMessages);
+
+ const [repairing, setRepairing] = useState(false);
+
+ const { data, error, isLoading, mutate } = useSWR(['topic-doctor', agentId, topicId], () =>
+ messageService.diagnoseTopic({ agentId, topicId }),
+ );
+
+ if (isLoading) return <Skeleton active paragraph={{ rows: 3 }} title={false} />;
+
+ // Without this the check failing would leave the skeleton up forever: SWR clears `isLoading`
+ // but never produces `data`, so a `!data` skeleton has no way back.
+ if (error || !data)
+ return (
+ <Flexbox align={'center'} gap={12} paddingBlock={24}>
+ <Icon color={cssVar.colorError} icon={CircleAlert} size={32} />
+ <Text>{t('doctor.checkFailed')}</Text>
+ <Button onClick={() => mutate()}>{t('retry', { ns: 'common' })}</Button>
+ </Flexbox>
+ );
+
+ const { hiddenCount, issues, patch } = data;
+
+ if (issues.length === 0)
+ return (
+ <Flexbox align={'center'} gap={12} paddingBlock={24}>
+ <Icon color={cssVar.colorSuccess} icon={CircleCheck} size={32} />
+ <Text>{t('doctor.healthy')}</Text>
+ </Flexbox>
+ );
+
+ const describe = (issue: TopicIssue) => {
+ const count = issue.hiddenMessageIds.length;
+ switch (issue.kind) {
+ case 'concurrent-fork': {
+ return t('doctor.issue.concurrent-fork', { count });
+ }
+ case 'stale-branch-index': {
+ return t('doctor.issue.stale-branch-index', { count });
+ }
+ case 'orphan-signal-turn': {
+ return t('doctor.issue.orphan-signal-turn', { count });
+ }
+ // Nothing is hidden here — the section renders, but on its own root: out of order and
+ // cut off from the model's context. The count is the section being reconnected.
+ case 'segment-split': {
+ return t('doctor.issue.segment-split', {
+ count: issue.reattachedMessageIds?.length ?? 0,
+ });
+ }
+ // The one shape that cannot be undone: these rows reached the database with nothing in
+ // them, so the text is simply gone.
+ case 'lost-content': {
+ return t('doctor.issue.lostContent', { count: issue.lostMessageIds?.length ?? 0 });
+ }
+ }
+ };
+
+ const handleRepair = async () => {
+ setRepairing(true);
+ try {
+ const { restoredMessageIds } = await messageService.repairTopic({ agentId, topicId });
+ await refreshMessages({ agentId: agentId ?? undefined, topicId });
+ message.success(t('doctor.repaired', { count: restoredMessageIds.length }));
+ close();
+ } catch {
+ message.error(t('doctor.repairFailed'));
+ } finally {
+ setRepairing(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ {hiddenCount > 0 && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorWarning} icon={EyeOff} />
+ <Text>{t('doctor.summary', { count: hiddenCount })}</Text>
+ </Flexbox>
+ )}
+
+ <Flexbox gap={8}>
+ {issues.map((issue) => (
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={styles.issue}
+ gap={8}
+ key={issue.messageId}
+ >
+ <Icon
+ color={issue.repairable ? cssVar.colorWarning : cssVar.colorTextQuaternary}
+ icon={CircleAlert}
+ />
+ <Flexbox gap={2}>
+ <Text>{describe(issue)}</Text>
+ {!issue.repairable && <Text type={'secondary'}>{t('doctor.notRepairable')}</Text>}
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Flexbox>
+
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ disabled={patch.length === 0}
+ icon={Stethoscope}
+ loading={repairing}
+ type={'primary'}
+ onClick={handleRepair}
+ >
+ {t('doctor.repair')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+TopicDoctorContent.displayName = 'TopicDoctorContent';
+
+export default TopicDoctorContent;
diff --git a/src/features/TopicDoctorModal/index.tsx b/src/features/TopicDoctorModal/index.tsx
new file mode 100644
index 00000000000..48b85ee12fc
--- /dev/null
+++ b/src/features/TopicDoctorModal/index.tsx
@@ -0,0 +1,15 @@
+'use client';
+
+import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import TopicDoctorContent, { type TopicDoctorContentProps } from './Content';
+
+export const openTopicDoctorModal = (props: TopicDoctorContentProps): ModalInstance =>
+ createModal({
+ content: <TopicDoctorContent {...props} />,
+ footer: null,
+ maskClosable: true,
+ title: t('doctor.title', { ns: 'topic' }),
+ width: 'min(90vw, 480px)',
+ });
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index 2207f5cb828..0c7a60195f6 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -16,6 +16,7 @@ import {
PencilLine,
Share2,
Star,
+ Stethoscope,
Trash,
Wand2,
} from 'lucide-react';
@@ -29,6 +30,7 @@ import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsMo
import { createTopicForwardModal } from '@/features/Conversation/MessageForward/TopicForwardModal';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { openShareModal } from '@/features/ShareModal';
+import { openTopicDoctorModal } from '@/features/TopicDoctorModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
@@ -154,6 +156,15 @@ export const useTopicItemDropdownMenu = ({
});
},
},
+ {
+ disabled: !canEditTopic,
+ icon: <Icon icon={Stethoscope} />,
+ key: 'diagnose',
+ label: t('actions.diagnose'),
+ onClick: () => {
+ openTopicDoctorModal({ agentId: activeAgentId, topicId: id });
+ },
+ },
{
type: 'divider' as const,
},
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index e1b0ec339ad..5ea57194a37 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -149,6 +149,14 @@ export class MessageService {
return data as unknown as UIChatMessage[];
};
+ diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {
+ return lambdaClient.message.diagnoseTopic.query(params);
+ };
+
+ repairTopic = async (params: { agentId?: string | null; topicId: string }) => {
+ return lambdaClient.message.repairTopic.mutate(params);
+ };
+
countMessages = async (params?: {
endDate?: string;
range?: [string, string];