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(cli): make topic view complete and pageable (#17224)

AmAzing-1880c1b9c5b0
diff --git a/apps/cli/src/commands/topic.test.ts b/apps/cli/src/commands/topic.test.ts
index e08dad267fd..a36d97418e8 100644
--- a/apps/cli/src/commands/topic.test.ts
+++ b/apps/cli/src/commands/topic.test.ts
@@ -6,13 +6,10 @@ import { registerTopicCommand } from './topic';
const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
- message: {
- getMessages: { query: vi.fn() },
- },
topic: {
batchDelete: { mutate: vi.fn() },
createTopic: { mutate: vi.fn() },
- getTopicDetail: { query: vi.fn() },
+ getTopicTranscript: { query: vi.fn() },
getTopics: { query: vi.fn() },
recentTopics: { query: vi.fn() },
removeTopic: { mutate: vi.fn() },
@@ -37,6 +34,7 @@ describe('topic command', () => {
let consoleSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
+ vi.clearAllMocks();
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
@@ -45,17 +43,15 @@ describe('topic command', () => {
(fn as ReturnType<typeof vi.fn>).mockReset();
}
}
- for (const method of Object.values(mockTrpcClient.message)) {
- for (const fn of Object.values(method)) {
- (fn as ReturnType<typeof vi.fn>).mockReset();
- }
- }
- // Default stub for getTopicDetail
- mockTrpcClient.topic.getTopicDetail.query.mockResolvedValue({
- favorite: false,
- id: 't1',
- title: 'Test Topic',
- updatedAt: new Date().toISOString(),
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [],
+ topic: {
+ favorite: false,
+ id: 't1',
+ title: 'Test Topic',
+ updatedAt: new Date().toISOString(),
+ },
+ total: 0,
});
});
@@ -221,128 +217,302 @@ describe('topic command', () => {
});
describe('view', () => {
- it('should display topic metadata and messages', async () => {
- mockTrpcClient.message.getMessages.query.mockResolvedValue([
- { content: 'Hello world', id: 'm1', role: 'user' },
- { content: 'Hi there', id: 'm2', role: 'assistant' },
- ]);
+ const topicDetail = {
+ favorite: true,
+ id: 't1',
+ model: 'gpt-test',
+ provider: 'test-provider',
+ status: 'completed',
+ title: 'Test Topic',
+ updatedAt: new Date('2026-01-01T00:00:00.000Z').toISOString(),
+ };
+
+ const message = (overrides: Record<string, unknown> = {}) => ({
+ content: 'Hello world',
+ createdAt: new Date('2026-01-01T00:00:00.000Z').toISOString(),
+ id: 'm1',
+ messageGroupId: null,
+ parentId: null,
+ role: 'user',
+ threadId: null,
+ tools: null,
+ ...overrides,
+ });
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1']);
+ const output = () => consoleSpy.mock.calls.map(([line]) => String(line)).join('\n');
- expect(mockTrpcClient.topic.getTopicDetail.query).toHaveBeenCalledWith(
- expect.objectContaining({ id: 't1' }),
- );
- expect(mockTrpcClient.message.getMessages.query).toHaveBeenCalledWith(
- expect.objectContaining({ topicId: 't1' }),
- );
- expect(consoleSpy).toHaveBeenCalled();
+ it('renders metadata and the transcript returned by the aggregate endpoint', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [message(), message({ content: 'Hi there', id: 'm2', role: 'assistant' })],
+ topic: topicDetail,
+ total: 2,
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ expect(mockTrpcClient.topic.getTopicTranscript.query).toHaveBeenCalledWith({
+ includeMessages: true,
+ limit: 50,
+ offset: 0,
+ topicId: 't1',
+ });
+ expect(output()).toContain('Test Topic');
+ expect(output()).toContain('Hello world');
+ expect(output()).toContain('Hi there');
+ expect(output()).toContain('Showing 1–2 of 2');
});
- it('should skip message query entirely when --no-messages flag is set', async () => {
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '--no-messages']);
+ it('uses the aggregate endpoint without loading messages for --no-messages', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [],
+ topic: topicDetail,
+ total: null,
+ });
- // getTopicDetail is still called (for metadata)
- expect(mockTrpcClient.topic.getTopicDetail.query).toHaveBeenCalled();
- // but getMessages must NOT be called
- expect(mockTrpcClient.message.getMessages.query).not.toHaveBeenCalled();
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', '--no-messages']);
+
+ expect(mockTrpcClient.topic.getTopicTranscript.query).toHaveBeenCalledWith({
+ includeMessages: false,
+ limit: 50,
+ offset: 0,
+ topicId: 't1',
+ });
+ expect(output()).toContain('Test Topic');
+ expect(output()).toContain('(messages skipped)');
});
- it('should output json when --json flag is set', async () => {
- mockTrpcClient.message.getMessages.query.mockResolvedValue([
- { content: 'Hello', id: 'm1', role: 'user' },
- ]);
+ it('keeps one stable JSON shape for transcript output', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [message({ content: 'JSON message' })],
+ topic: topicDetail,
+ total: 75,
+ });
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '--json']);
-
- const calls = consoleSpy.mock.calls.flat().join('');
- const parsed = JSON.parse(calls);
- expect(parsed.topic.id).toBe('t1');
- expect(parsed.messages).toHaveLength(1);
- expect(parsed.messages[0]).toHaveProperty('role', 'user');
- expect(parsed.messages[0]).toHaveProperty('content', 'Hello');
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', '--json']);
+
+ const parsed = JSON.parse(output());
+ expect(Object.keys(parsed)).toEqual(['messages', 'pagination', 'topic']);
+ expect(parsed.messages[0]).toMatchObject({ content: 'JSON message', role: 'user' });
+ expect(parsed.pagination).toEqual({ from: 1, limit: 50, to: 1, total: 75 });
+ expect(parsed.topic).toMatchObject({ id: 't1', title: 'Test Topic' });
});
- it('should output json with empty messages for --no-messages --json', async () => {
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '--no-messages', '--json']);
+ it('keeps the same JSON shape when messages are skipped', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [],
+ topic: topicDetail,
+ total: null,
+ });
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'topic',
+ 'view',
+ 't1',
+ '--no-messages',
+ '--json',
+ ]);
- expect(mockTrpcClient.message.getMessages.query).not.toHaveBeenCalled();
- const calls = consoleSpy.mock.calls.flat().join('');
- const parsed = JSON.parse(calls);
- expect(parsed.topic.id).toBe('t1');
- expect(parsed.messages).toHaveLength(0);
+ const parsed = JSON.parse(output());
+ expect(Object.keys(parsed)).toEqual(['messages', 'pagination', 'topic']);
+ expect(parsed).toMatchObject({ messages: [], pagination: null });
+ expect(parsed.topic).toMatchObject({ id: 't1', title: 'Test Topic' });
});
- it('should respect -L for message page size', async () => {
- mockTrpcClient.message.getMessages.query.mockResolvedValue([]);
+ it('maps --from to a server-side offset instead of slicing the first page', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [message({ content: 'Message 51', id: 'm51' })],
+ topic: topicDetail,
+ total: 100,
+ });
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '-L', '10']);
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', '--from', '51']);
- expect(mockTrpcClient.message.getMessages.query).toHaveBeenCalledWith(
- expect.objectContaining({ pageSize: 10, topicId: 't1' }),
+ expect(mockTrpcClient.topic.getTopicTranscript.query).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 50, offset: 50 }),
);
+ expect(output()).toContain('Message 51');
+ expect(output()).toContain('Showing 51–51 of 100. Next: --from 52 -L 50');
});
- it('should slice messages with --from and --to', async () => {
- mockTrpcClient.message.getMessages.query.mockResolvedValue([
- { content: 'msg1', id: 'm1', role: 'user' },
- { content: 'msg2', id: 'm2', role: 'assistant' },
- { content: 'msg3', id: 'm3', role: 'user' },
+ it('turns an inclusive --from/--to range into an exact server page', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [message({ id: 'm51' }), message({ id: 'm52' })],
+ topic: topicDetail,
+ total: 100,
+ });
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'topic',
+ 'view',
+ 't1',
+ '--from',
+ '51',
+ '--to',
+ '52',
]);
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '--from', '2', '--to', '3']);
+ expect(mockTrpcClient.topic.getTopicTranscript.query).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 2, offset: 50 }),
+ );
+ });
- // Should print only m2 and m3 (index 1 and 2)
- const output = consoleSpy.mock.calls.flat().join('\n');
- expect(output).toContain('msg2');
- expect(output).toContain('msg3');
- expect(output).not.toContain('msg1');
+ it.each([
+ ['--from', '10x'],
+ ['--from', '0'],
+ ['--limit', '-1'],
+ ['--limit', '1.5'],
+ ['--limit', '501'],
+ ])('rejects invalid numeric input %s %s', async (option, value) => {
+ exitSpy.mockImplementation((() => {
+ throw new Error('process.exit');
+ }) as any);
+
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', option, value]),
+ ).rejects.toThrow('process.exit');
+
+ expect(log.error).toHaveBeenCalled();
+ expect(mockTrpcClient.topic.getTopicTranscript.query).not.toHaveBeenCalled();
});
- it('should render tool calls inline', async () => {
- mockTrpcClient.message.getMessages.query.mockResolvedValue([
- {
- content: "I'll search for that.",
- id: 'm1',
- role: 'assistant',
- tools: [
- {
- function: { arguments: '{"query":"lobehub"}', name: 'web_search' },
- id: 'call_1',
- type: 'function',
- },
- ],
- },
- { content: 'search results...', id: 'm2', role: 'tool' },
- ]);
+ it.each([
+ ['--from', '5', '--to', '4'],
+ ['--from', '1', '--to', '501'],
+ ['--limit', '10', '--to', '20'],
+ ])('rejects an invalid range: %s %s %s %s', async (...args) => {
+ exitSpy.mockImplementation((() => {
+ throw new Error('process.exit');
+ }) as any);
+
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', ...args]),
+ ).rejects.toThrow('process.exit');
+
+ expect(log.error).toHaveBeenCalled();
+ expect(mockTrpcClient.topic.getTopicTranscript.query).not.toHaveBeenCalled();
+ });
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1']);
+ it('propagates a missing-topic error instead of returning a successful empty topic', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockRejectedValue(
+ new Error('Topic not found: missing-topic'),
+ );
+
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'topic', 'view', 'missing-topic']),
+ ).rejects.toThrow('Topic not found: missing-topic');
- const output = consoleSpy.mock.calls.flat().join('\n');
- expect(output).toContain('web_search');
- expect(output).toContain('lobehub');
+ expect(consoleSpy).not.toHaveBeenCalled();
});
- it('should render threaded messages with indentation', async () => {
- mockTrpcClient.message.getMessages.query.mockResolvedValue([
- { content: 'Parent message', id: 'm1', parentId: null, role: 'user' },
- { content: 'Thread reply', id: 'm2', parentId: 'm1', role: 'assistant' },
- ]);
+ it('renders the persisted ChatToolPayload shape', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [
+ message({
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"query":"lobehub"}',
+ id: 'call_1',
+ identifier: 'web',
+ type: 'default',
+ },
+ ],
+ }),
+ ],
+ topic: topicDetail,
+ total: 1,
+ });
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'topic', 'view', 't1']);
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ expect(output()).toContain('web.search');
+ expect(output()).toContain('lobehub');
+ });
+
+ it('preserves group-chat roles and marks real thread messages', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [
+ message({ content: 'Supervisor message', id: 'm1', role: 'supervisor' }),
+ message({ content: 'Task message', id: 'm2', role: 'task', threadId: 'thread-1' }),
+ message({ content: 'Verify message', id: 'm3', role: 'verify' }),
+ ],
+ topic: topicDetail,
+ total: 3,
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ expect(output()).toContain('supervisor');
+ expect(output()).toContain('task');
+ expect(output()).toContain('verify');
+ expect(output()).toContain('[thread thread-1]');
+ expect(output().indexOf('Task message')).toBeGreaterThan(
+ output().indexOf('Supervisor message'),
+ );
+ });
+
+ it('sanitizes terminal controls, redacts base64 data, and bounds long output', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValue({
+ items: [
+ message({
+ content: `safe\u001B[31m text data:image/png;base64,${'A'.repeat(100)}`,
+ id: 'unsafe',
+ }),
+ message({ content: `${'x'.repeat(20_001)}SECRET_END`, id: 'long' }),
+ message({
+ id: 'tool-args',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'large',
+ arguments: `${'y'.repeat(8_001)}TOOL_SECRET`,
+ id: 'call-large',
+ identifier: 'test',
+ type: 'default',
+ },
+ ],
+ }),
+ ],
+ topic: topicDetail,
+ total: 3,
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ expect(output()).not.toContain('\u001B');
+ expect(output()).not.toContain('data:image/png;base64');
+ expect(output()).not.toContain('SECRET_END');
+ expect(output()).not.toContain('TOOL_SECRET');
+ expect(output()).toContain('[base64 data omitted]');
+ expect(output()).toContain('[message content truncated; use --json for full output]');
+ expect(output()).toContain('[tool arguments omitted:');
+ });
+
+ it('distinguishes an empty topic from an out-of-range page', async () => {
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValueOnce({
+ items: [],
+ topic: topicDetail,
+ total: 0,
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1']);
+ expect(output()).toContain('(no messages)');
+ expect(output()).not.toContain('requested range');
+
+ consoleSpy.mockClear();
+ mockTrpcClient.topic.getTopicTranscript.query.mockResolvedValueOnce({
+ items: [],
+ topic: topicDetail,
+ total: 100,
+ });
- const output = consoleSpy.mock.calls.flat().join('\n');
- expect(output).toContain('Parent message');
- expect(output).toContain('Thread reply');
- // thread reply should appear after parent (basic ordering check)
- expect(output.indexOf('Thread reply')).toBeGreaterThan(output.indexOf('Parent message'));
+ await createProgram().parseAsync(['node', 'test', 'topic', 'view', 't1', '--from', '101']);
+ expect(output()).toContain('(no messages in requested range; topic has 100 messages)');
});
});
});
diff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.ts
index 53dd5b212b7..3f675275614 100644
--- a/apps/cli/src/commands/topic.ts
+++ b/apps/cli/src/commands/topic.ts
@@ -6,6 +6,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { registerTopicViewCommand } from './topic/view';
export function registerTopicCommand(program: Command) {
const topic = program.command('topic').description('Manage conversation topics');
@@ -333,169 +334,5 @@ export function registerTopicCommand(program: Command) {
printTable(rows, ['ID', 'TITLE', 'UPDATED']);
});
- // ── view ──────────────────────────────────────────────
-
- topic
- .command('view <id>')
- .description('View topic details and its messages')
- .option('-L, --limit <n>', 'Max messages to fetch per page', '50')
- .option('--from <n>', 'Show messages starting from this index (1-based)', '1')
- .option('--to <n>', 'Show messages up to this index (inclusive)')
- .option('--no-messages', 'Skip messages, show topic metadata only')
- .option('--json', 'Output JSON')
- .action(
- async (
- id: string,
- options: {
- from?: string;
- json?: boolean;
- limit?: string;
- messages?: boolean;
- to?: string;
- },
- ) => {
- const client = await getTrpcClient();
-
- // ── 1. Fetch topic detail (single query by id) ──
- const topicDetail = await client.topic.getTopicDetail.query({ id } as any);
-
- // ── 2. Fetch messages only when needed ──
- if (options.messages === false) {
- // --no-messages: skip message query entirely
- if (options.json) {
- console.log(JSON.stringify({ messages: [], topic: topicDetail ?? { id } }, null, 2));
- return;
- }
- console.log('');
- console.log(
- `${pc.bold('Topic:')} ${pc.cyan((topicDetail as any)?.title ?? id)} ${pc.dim(`(${id})`)}`,
- );
- console.log('');
- return;
- }
-
- const msgLimit = Number.parseInt(options.limit || '50', 10);
- const msgResult = await client.message.getMessages.query({
- pageSize: msgLimit,
- topicId: id,
- } as any);
- const allMessages: any[] = Array.isArray(msgResult)
- ? msgResult
- : ((msgResult as any).items ?? []);
-
- // Apply --from / --to slicing (1-based)
- const fromIdx = Math.max(1, Number.parseInt(options.from || '1', 10)) - 1;
- const toIdx = options.to ? Number.parseInt(options.to, 10) : allMessages.length;
- const messages = allMessages.slice(fromIdx, toIdx);
-
- if (options.json) {
- console.log(
- JSON.stringify(
- {
- messages: messages.map((m: any) => ({
- content: m.content ?? null,
- createdAt: m.createdAt ?? null,
- id: m.id,
- parentId: m.parentId ?? null,
- role: m.role,
- threadId: m.threadId ?? null,
- tools: m.tools ?? null,
- })),
- topic: { id },
- },
- null,
- 2,
- ),
- );
- return;
- }
-
- // ── Header ──
- const t = topicDetail as any;
- console.log('');
- console.log(`${pc.bold('Topic:')} ${pc.cyan(t?.title ?? id)} ${pc.dim(`(${id})`)}`);
- if (t?.favorite) console.log(`${pc.bold('Favorite:')} β˜…`);
- if (t?.updatedAt) console.log(`${pc.bold('Updated:')} ${timeAgo(t.updatedAt)}`);
- if (t?.status) console.log(`${pc.bold('Status:')} ${t.status}`);
- if (t?.model) console.log(`${pc.bold('Model:')} ${t.model}${t.provider ? ` (${t.provider})` : ''}`);
- console.log('');
-
- // ── Messages ──
- if (messages.length === 0) {
- console.log(pc.dim(' (no messages)'));
- return;
- }
-
- // Build parentId β†’ children map for thread display
- const childrenOf = new Map<string | null, any[]>();
- for (const m of messages) {
- const key = m.parentId ?? null;
- if (!childrenOf.has(key)) childrenOf.set(key, []);
- childrenOf.get(key)!.push(m);
- }
-
- const printMessage = (m: any, depth: number) => {
- const indent = ' '.repeat(depth + 1);
- const roleLabel =
- m.role === 'user'
- ? pc.green('user ')
- : m.role === 'tool'
- ? pc.yellow('tool ')
- : pc.blue('assistant');
- const threadMark = depth > 0 ? pc.dim('↳ ') : '';
-
- // Full content (no truncation)
- const content = (m.content || '').trim();
- if (content) {
- console.log(`${indent}${threadMark}${roleLabel} ${content}`);
- }
-
- // Tool calls (assistant requesting tools)
- if (m.tools && Array.isArray(m.tools) && m.tools.length > 0) {
- for (const tool of m.tools) {
- const toolName = tool.function?.name ?? tool.id ?? 'unknown';
- const toolArgs = tool.function?.arguments
- ? (() => {
- try {
- return JSON.stringify(JSON.parse(tool.function.arguments), null, 2)
- .split('\n')
- .map((l: string) => `${indent} ${l}`)
- .join('\n');
- } catch {
- return `${indent} ${tool.function.arguments}`;
- }
- })()
- : '';
- console.log(`${indent} ${pc.yellow('βš™')} ${pc.bold(toolName)}`);
- if (toolArgs) console.log(toolArgs);
- }
- }
-
- // Render thread children recursively
- const children = childrenOf.get(m.id) ?? [];
- for (const child of children) {
- printMessage(child, depth + 1);
- }
- };
-
- // Print only top-level messages (parentId === null/undefined, or parentId not in current page)
- const msgIds = new Set(messages.map((m: any) => m.id));
- const topLevel = messages.filter(
- (m: any) => !m.parentId || !msgIds.has(m.parentId),
- );
-
- for (const m of topLevel) {
- printMessage(m, 0);
- }
-
- if (allMessages.length > msgLimit) {
- console.log('');
- console.log(
- pc.dim(
- ` … total ${allMessages.length} messages, showing ${fromIdx + 1}–${Math.min(toIdx, allMessages.length)}. Use -L / --from / --to to paginate.`,
- ),
- );
- }
- },
- );
+ registerTopicViewCommand(topic);
}
diff --git a/apps/cli/src/commands/topic/view.ts b/apps/cli/src/commands/topic/view.ts
new file mode 100644
index 00000000000..6ac37015b9b
--- /dev/null
+++ b/apps/cli/src/commands/topic/view.ts
@@ -0,0 +1,337 @@
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../../api/client';
+import { timeAgo } from '../../utils/format';
+import { log } from '../../utils/logger';
+
+const DEFAULT_LIMIT = 50;
+const MAX_LIMIT = 500;
+const MAX_CONTENT_LENGTH = 20_000;
+const MAX_TOOL_ARGUMENTS_LENGTH = 8_000;
+const MAX_DATA_URL_PREFIX_LENGTH = 256;
+
+interface TopicViewOptions {
+ from?: string;
+ json?: boolean;
+ limit?: string;
+ messages?: boolean;
+ to?: string;
+}
+
+interface PersistedToolPayload {
+ apiName?: string;
+ arguments?: string;
+ id?: string;
+ identifier?: string;
+}
+
+interface TranscriptMessage {
+ content: string | null;
+ createdAt: Date;
+ id: string;
+ messageGroupId: string | null;
+ parentId: string | null;
+ role: string;
+ threadId: string | null;
+ tools: unknown[] | null;
+}
+
+interface TopicDetail {
+ favorite?: boolean | null;
+ id: string;
+ model?: string | null;
+ provider?: string | null;
+ status?: string | null;
+ title?: string | null;
+ updatedAt?: Date | string | null;
+}
+
+interface Pagination {
+ from: number;
+ limit: number;
+ offset: number;
+}
+
+const fail = (message: string): never => {
+ log.error(message);
+ process.exit(1);
+};
+
+const parsePositiveInteger = (value: string, option: string): number => {
+ if (!/^\d+$/.test(value)) {
+ return fail(`${option} must be a positive integer.`);
+ }
+
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
+ return fail(`${option} must be a positive safe integer.`);
+ }
+
+ return parsed;
+};
+
+const resolvePagination = (options: TopicViewOptions): Pagination => {
+ const from = parsePositiveInteger(options.from ?? '1', '--from');
+
+ if (options.to !== undefined && options.limit !== undefined) {
+ return fail('--to cannot be combined with --limit. Use one to define the page size.');
+ }
+
+ let limit: number;
+ if (options.to !== undefined) {
+ const to = parsePositiveInteger(options.to, '--to');
+ if (to < from) {
+ return fail('--to must be greater than or equal to --from.');
+ }
+ limit = to - from + 1;
+ } else {
+ limit = parsePositiveInteger(options.limit ?? String(DEFAULT_LIMIT), '--limit');
+ }
+
+ if (limit > MAX_LIMIT) {
+ return fail(`A topic view page cannot exceed ${MAX_LIMIT} messages.`);
+ }
+
+ return { from, limit, offset: from - 1 };
+};
+
+const isBase64Character = (char: string): boolean => {
+ const code = char.codePointAt(0) ?? 0;
+ return (
+ (code >= 48 && code <= 57) ||
+ (code >= 65 && code <= 90) ||
+ (code >= 97 && code <= 122) ||
+ char === '+' ||
+ char === '/' ||
+ char === '=' ||
+ char === '-' ||
+ char === '_'
+ );
+};
+
+/** Replace base64 data URLs without scanning an unbounded prefix or using a backtracking regexp. */
+const redactBase64DataUrls = (value: string): string => {
+ const lowerValue = value.toLowerCase();
+ const marker = ';base64,';
+ let cursor = 0;
+ let output = '';
+
+ while (cursor < value.length) {
+ const dataStart = lowerValue.indexOf('data:', cursor);
+ if (dataStart === -1) {
+ output += value.slice(cursor);
+ break;
+ }
+
+ const payloadMarker = lowerValue.indexOf(marker, dataStart + 5);
+ if (payloadMarker === -1 || payloadMarker - dataStart > MAX_DATA_URL_PREFIX_LENGTH) {
+ output += value.slice(cursor, dataStart + 5);
+ cursor = dataStart + 5;
+ continue;
+ }
+
+ let payloadEnd = payloadMarker + marker.length;
+ while (payloadEnd < value.length && isBase64Character(value[payloadEnd])) {
+ payloadEnd += 1;
+ }
+
+ output += `${value.slice(cursor, dataStart)}[base64 data omitted]`;
+ cursor = payloadEnd;
+ }
+
+ return output;
+};
+
+const sanitizeTerminalControls = (value: string): string =>
+ value
+ .replaceAll('οΏ½', '')
+ // Keep newlines and tabs for formatting while dropping terminal control sequences.
+ // eslint-disable-next-line no-control-regex
+ .replaceAll(/[\u0000-\u0008\v\f\u000E-\u001F\u007F-\u009F]/g, '')
+ // Preserve valid surrogate pairs (emoji) and remove only lone surrogates.
+ .replaceAll(/[\uD800-\uDFFF]/gu, '');
+
+const normalizeTerminalText = (value: string): string =>
+ redactBase64DataUrls(
+ sanitizeTerminalControls(value)
+ .replaceAll('\r\n', '\n')
+ .replaceAll('\r', '\n')
+ .replaceAll('\t', ' ')
+ .replaceAll(/[\u202A-\u202E\u2066-\u2069]/g, ''),
+ );
+
+const formatTerminalText = (value: string, maxLength: number, label: string): string => {
+ const truncated = value.length > maxLength;
+ const normalized = normalizeTerminalText(truncated ? value.slice(0, maxLength) : value);
+
+ return truncated ? `${normalized}\n[${label} truncated; use --json for full output]` : normalized;
+};
+
+const formatSingleLine = (value: unknown, maxLength = 200): string => {
+ const stringValue = String(value ?? '');
+ const truncated = stringValue.length > maxLength;
+ const normalized = normalizeTerminalText(
+ truncated ? stringValue.slice(0, maxLength) : stringValue,
+ )
+ .replaceAll(/\s+/g, ' ')
+ .trim();
+
+ return truncated ? `${normalized}…` : normalized;
+};
+
+const colorRole = (role: string): string => {
+ const padded = role.padEnd(10);
+ if (role === 'user') return pc.green(padded);
+ if (role === 'assistant') return pc.blue(padded);
+ if (role === 'tool') return pc.yellow(padded);
+ return pc.magenta(padded);
+};
+
+const formatToolArguments = (argumentsValue: unknown): string | undefined => {
+ if (typeof argumentsValue !== 'string' || argumentsValue.length === 0) return undefined;
+
+ if (argumentsValue.length > MAX_TOOL_ARGUMENTS_LENGTH) {
+ return `[tool arguments omitted: ${argumentsValue.length.toLocaleString('en-US')} characters; use --json for full output]`;
+ }
+
+ let formatted = argumentsValue;
+ try {
+ formatted = JSON.stringify(JSON.parse(argumentsValue), null, 2);
+ } catch {
+ // Tool arguments can be partial JSON while the model is still streaming.
+ }
+
+ return formatTerminalText(formatted, MAX_TOOL_ARGUMENTS_LENGTH, 'tool arguments');
+};
+
+const renderTopicHeader = (topic: TopicDetail) => {
+ const id = formatSingleLine(topic.id);
+ const title = formatSingleLine(topic.title || 'Untitled');
+
+ console.log('');
+ console.log(`${pc.bold('Topic:')} ${pc.cyan(title)} ${pc.dim(`(${id})`)}`);
+ if (topic.favorite) console.log(`${pc.bold('Favorite:')} β˜…`);
+ if (topic.updatedAt) console.log(`${pc.bold('Updated:')} ${timeAgo(topic.updatedAt)}`);
+ if (topic.status) console.log(`${pc.bold('Status:')} ${formatSingleLine(topic.status)}`);
+ if (topic.model) {
+ const provider = topic.provider ? ` (${formatSingleLine(topic.provider)})` : '';
+ console.log(`${pc.bold('Model:')} ${formatSingleLine(topic.model)}${provider}`);
+ }
+ console.log('');
+};
+
+const renderMessage = (message: TranscriptMessage) => {
+ const role = formatSingleLine(message.role || 'unknown', 32) || 'unknown';
+ const thread = message.threadId
+ ? pc.dim(`↳ [thread ${formatSingleLine(message.threadId, 80)}] `)
+ : '';
+ const content = message.content
+ ? formatTerminalText(message.content, MAX_CONTENT_LENGTH, 'message content').trim()
+ : '';
+
+ if (content) {
+ const lines = content.split('\n');
+ console.log(` ${thread}${colorRole(role)} ${lines[0]}`);
+ for (const line of lines.slice(1)) console.log(` ${line}`);
+ } else if (!message.tools?.length) {
+ console.log(` ${thread}${colorRole(role)} ${pc.dim('(empty)')}`);
+ }
+
+ for (const rawTool of message.tools ?? []) {
+ const tool =
+ rawTool && typeof rawTool === 'object'
+ ? (rawTool as PersistedToolPayload)
+ : ({} as PersistedToolPayload);
+ const identifier = formatSingleLine(tool.identifier, 80);
+ const apiName = formatSingleLine(tool.apiName, 80);
+ const toolName =
+ identifier && apiName
+ ? `${identifier}.${apiName}`
+ : apiName || identifier || tool.id || 'unknown';
+ console.log(` ${pc.yellow('βš™')} ${pc.bold(formatSingleLine(toolName, 160))}`);
+
+ const toolArguments = formatToolArguments(tool.arguments);
+ if (toolArguments) {
+ for (const line of toolArguments.split('\n')) console.log(` ${line}`);
+ }
+ }
+};
+
+export function registerTopicViewCommand(topic: Command) {
+ topic
+ .command('view <id>')
+ .description('View topic details and its messages')
+ .option('-L, --limit <n>', `Number of messages to show (default: 50, max: ${MAX_LIMIT})`)
+ .option('--from <n>', 'Show messages starting from this index (1-based)', '1')
+ .option('--to <n>', 'Show messages up to this index (inclusive)')
+ .option('--no-messages', 'Skip messages, show topic metadata only')
+ .option('--json', 'Output JSON')
+ .action(async (id: string, options: TopicViewOptions) => {
+ const includeMessages = options.messages !== false;
+ const pagination = includeMessages
+ ? resolvePagination(options)
+ : { from: 1, limit: DEFAULT_LIMIT, offset: 0 };
+ const client = await getTrpcClient();
+ const result = await client.topic.getTopicTranscript.query({
+ includeMessages,
+ limit: pagination.limit,
+ offset: pagination.offset,
+ topicId: id,
+ });
+
+ const messages = result.items as TranscriptMessage[];
+ const topicDetail = result.topic as TopicDetail;
+ const total = result.total ?? 0;
+ const displayedTo = messages.length > 0 ? pagination.from + messages.length - 1 : null;
+
+ if (options.json) {
+ console.log(
+ JSON.stringify(
+ {
+ messages,
+ pagination: includeMessages
+ ? {
+ from: pagination.from,
+ limit: pagination.limit,
+ to: displayedTo,
+ total,
+ }
+ : null,
+ topic: topicDetail,
+ },
+ null,
+ 2,
+ ),
+ );
+ return;
+ }
+
+ renderTopicHeader(topicDetail);
+
+ if (!includeMessages) {
+ console.log(pc.dim(' (messages skipped)'));
+ return;
+ }
+
+ if (messages.length === 0) {
+ console.log(
+ pc.dim(
+ total === 0
+ ? ' (no messages)'
+ : ` (no messages in requested range; topic has ${total} messages)`,
+ ),
+ );
+ return;
+ }
+
+ for (const message of messages) renderMessage(message);
+
+ console.log('');
+ const next =
+ displayedTo !== null && displayedTo < total
+ ? ` Next: --from ${displayedTo + 1} -L ${pagination.limit}`
+ : '';
+ console.log(pc.dim(` Showing ${pagination.from}–${displayedTo} of ${total}.${next}`));
+ });
+}
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
index 100ebcbcf09..f4d0f350697 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { type LobeChatDatabase } from '@lobechat/database';
-import { sessions, topics } from '@lobechat/database/schemas';
+import { messages, sessions, topics } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -29,6 +29,7 @@ vi.mock('@/server/utils/scheduleAfterResponse', () => ({
describe('Topic Router Integration Tests', () => {
let serverDB: LobeChatDatabase;
let userId: string;
+ let otherUserId: string | undefined;
let testSessionId: string;
let testAgentId: string;
@@ -36,6 +37,7 @@ describe('Topic Router Integration Tests', () => {
serverDB = await getTestDB();
testDB = serverDB;
userId = await createTestUser(serverDB);
+ otherUserId = undefined;
// Create test agent
const { agents } = await import('@/database/schemas');
@@ -60,6 +62,7 @@ describe('Topic Router Integration Tests', () => {
afterEach(async () => {
await cleanupTestUser(serverDB, userId);
+ if (otherUserId) await cleanupTestUser(serverDB, otherUserId);
});
describe('createTopic', () => {
@@ -133,6 +136,116 @@ describe('Topic Router Integration Tests', () => {
});
});
+ describe('getTopicTranscript', () => {
+ it('returns topic metadata with exact message pagination', async () => {
+ await serverDB.insert(topics).values({
+ id: 'transcript-topic',
+ title: 'Transcript Topic',
+ userId,
+ });
+ await serverDB.insert(messages).values([
+ {
+ content: 'first',
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ id: 'transcript-message-a',
+ role: 'user',
+ topicId: 'transcript-topic',
+ userId,
+ },
+ {
+ content: 'second',
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ id: 'transcript-message-b',
+ role: 'assistant',
+ topicId: 'transcript-topic',
+ userId,
+ },
+ {
+ content: 'third',
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ id: 'transcript-message-c',
+ role: 'tool',
+ topicId: 'transcript-topic',
+ userId,
+ },
+ ]);
+
+ const caller = topicRouter.createCaller(createTestContext(userId));
+ const result = await caller.getTopicTranscript({
+ limit: 1,
+ offset: 1,
+ topicId: 'transcript-topic',
+ });
+
+ expect(result.topic).toMatchObject({ id: 'transcript-topic', title: 'Transcript Topic' });
+ expect(result.items).toEqual([
+ expect.objectContaining({ content: 'second', id: 'transcript-message-b' }),
+ ]);
+ expect(result.total).toBe(3);
+ });
+
+ it('does not load messages when includeMessages is false', async () => {
+ await serverDB.insert(topics).values({
+ id: 'metadata-only-topic',
+ title: 'Metadata Only',
+ userId,
+ });
+ await serverDB.insert(messages).values({
+ content: 'must not be returned',
+ id: 'metadata-only-message',
+ role: 'user',
+ topicId: 'metadata-only-topic',
+ userId,
+ });
+
+ const caller = topicRouter.createCaller(createTestContext(userId));
+ const result = await caller.getTopicTranscript({
+ includeMessages: false,
+ topicId: 'metadata-only-topic',
+ });
+
+ expect(result).toMatchObject({
+ items: [],
+ topic: { id: 'metadata-only-topic', title: 'Metadata Only' },
+ total: null,
+ });
+ });
+
+ it('rejects a missing topic instead of returning a successful empty result', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ await expect(caller.getTopicTranscript({ topicId: 'missing-topic' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ message: 'Topic not found: missing-topic',
+ });
+ });
+
+ it('does not expose a personal topic to another authenticated user who knows its id', async () => {
+ await serverDB.insert(topics).values({
+ id: 'private-transcript-topic',
+ title: 'Private Transcript',
+ userId,
+ });
+ await serverDB.insert(messages).values({
+ content: 'private message',
+ id: 'private-transcript-message',
+ role: 'user',
+ topicId: 'private-transcript-topic',
+ userId,
+ });
+
+ otherUserId = await createTestUser(serverDB);
+ const otherCaller = topicRouter.createCaller(createTestContext(otherUserId));
+
+ await expect(
+ otherCaller.getTopicTranscript({ topicId: 'private-transcript-topic' }),
+ ).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ message: 'Topic not found: private-transcript-topic',
+ });
+ });
+ });
+
describe('batchCreateTopics', () => {
it('should batch create topics with agentId', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 5f67f1ff5ae..9972efd7bc1 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -56,6 +56,7 @@ const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),
fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
heteroSessionImporterRepo: new HeteroSessionImporterRepo(ctx.serverDB, ctx.userId, wsId),
+ messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),
topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),
@@ -131,6 +132,38 @@ export const topicRouter = router({
return topic;
}),
+ getTopicTranscript: topicProcedure
+ .input(
+ z.object({
+ includeMessages: z.boolean().default(true),
+ limit: z.number().int().min(1).max(500).default(50),
+ offset: z.number().int().min(0).default(0),
+ topicId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const topic = await ctx.topicModel.findById(input.topicId);
+
+ if (!topic) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Topic not found: ${input.topicId}`,
+ });
+ }
+
+ if (!input.includeMessages) {
+ return { items: [], topic, total: null };
+ }
+
+ const transcript = await ctx.messageModel.queryTopicTranscript({
+ limit: input.limit,
+ offset: input.offset,
+ topicId: input.topicId,
+ });
+
+ return { ...transcript, topic };
+ }),
+
getTopicContext: topicProcedure
.input(z.object({ topicId: z.string() }))
.query(async ({ input, ctx }) => {
@@ -151,9 +184,7 @@ export const topicRouter = router({
}
// Fallback: fetch recent messages with correct agentId/groupId
- const wsId = ctx.workspaceId ?? undefined;
- const messageModel = new MessageModel(ctx.serverDB, ctx.userId, wsId);
- const messages = await messageModel.query({
+ const messages = await ctx.messageModel.query({
agentId: topic.agentId ?? undefined,
groupId: topic.groupId ?? undefined,
topicId: input.topicId,
diff --git a/packages/database/src/models/__tests__/messages/message.topic-transcript.test.ts b/packages/database/src/models/__tests__/messages/message.topic-transcript.test.ts
new file mode 100644
index 00000000000..f56b3a5a4aa
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.topic-transcript.test.ts
@@ -0,0 +1,226 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ chatGroups,
+ messageGroups,
+ messages,
+ sessions,
+ threads,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'topic-transcript-user';
+const otherUserId = 'topic-transcript-other-user';
+const testUserIds = [userId, otherUserId];
+
+const cleanup = async () => {
+ await serverDB.delete(users).where(inArray(users.id, testUserIds));
+};
+
+beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(cleanup);
+
+describe('MessageModel.queryTopicTranscript', () => {
+ it('returns every persisted topic message with stable database pagination', async () => {
+ const topicId = 'topic-transcript-target';
+ const createdAt = new Date('2026-01-01T00:00:00.000Z');
+
+ await serverDB.insert(sessions).values({ id: 'topic-transcript-session', userId });
+ await serverDB.insert(chatGroups).values({ id: 'topic-transcript-chat-group', userId });
+ await serverDB.insert(topics).values([
+ { id: topicId, title: 'Transcript target', userId },
+ { id: 'topic-transcript-other-topic', title: 'Other topic', userId },
+ ]);
+ await serverDB.insert(threads).values({
+ id: 'topic-transcript-thread',
+ topicId,
+ type: 'continuation',
+ userId,
+ });
+ await serverDB.insert(messageGroups).values({
+ id: 'topic-transcript-message-group',
+ topicId,
+ type: 'parallel',
+ userId,
+ });
+ await serverDB.insert(messages).values([
+ {
+ content: 'plain message',
+ createdAt,
+ id: 'topic-transcript-m-a',
+ role: 'user',
+ topicId,
+ userId,
+ },
+ {
+ content: 'legacy session message',
+ createdAt,
+ id: 'topic-transcript-m-b',
+ role: 'assistant',
+ sessionId: 'topic-transcript-session',
+ topicId,
+ userId,
+ },
+ {
+ content: 'group message',
+ createdAt,
+ groupId: 'topic-transcript-chat-group',
+ id: 'topic-transcript-m-c',
+ role: 'supervisor',
+ topicId,
+ userId,
+ },
+ {
+ content: 'thread message',
+ createdAt,
+ id: 'topic-transcript-m-d',
+ role: 'task',
+ threadId: 'topic-transcript-thread',
+ topicId,
+ userId,
+ },
+ {
+ content: 'raw message-group member',
+ createdAt,
+ id: 'topic-transcript-m-e',
+ messageGroupId: 'topic-transcript-message-group',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"query":"lobehub"}',
+ id: 'topic-transcript-tool',
+ identifier: 'web',
+ type: 'default',
+ },
+ ],
+ topicId,
+ userId,
+ },
+ {
+ content: 'different topic',
+ createdAt,
+ id: 'topic-transcript-other-topic-message',
+ role: 'user',
+ topicId: 'topic-transcript-other-topic',
+ userId,
+ },
+ {
+ content: 'different owner',
+ createdAt,
+ id: 'topic-transcript-other-owner-message',
+ role: 'user',
+ topicId,
+ userId: otherUserId,
+ },
+ ]);
+
+ const model = new MessageModel(serverDB, userId);
+ const full = await model.queryTopicTranscript({ limit: 10, offset: 0, topicId });
+
+ expect(full.total).toBe(5);
+ expect(full.items.map(({ id }) => id)).toEqual([
+ 'topic-transcript-m-a',
+ 'topic-transcript-m-b',
+ 'topic-transcript-m-c',
+ 'topic-transcript-m-d',
+ 'topic-transcript-m-e',
+ ]);
+ expect(full.items[1]).toMatchObject({ content: 'legacy session message' });
+ expect(full.items[2]).toMatchObject({ content: 'group message', role: 'supervisor' });
+ expect(full.items[3]).toMatchObject({
+ content: 'thread message',
+ threadId: 'topic-transcript-thread',
+ });
+ expect(full.items[4]).toMatchObject({
+ messageGroupId: 'topic-transcript-message-group',
+ tools: [expect.objectContaining({ apiName: 'search', identifier: 'web' })],
+ });
+
+ const page = await model.queryTopicTranscript({ limit: 2, offset: 1, topicId });
+ expect(page.total).toBe(5);
+ expect(page.items.map(({ id }) => id)).toEqual([
+ 'topic-transcript-m-b',
+ 'topic-transcript-m-c',
+ ]);
+
+ await expect(
+ new MessageModel(serverDB, otherUserId).queryTopicTranscript({
+ limit: 10,
+ offset: 0,
+ topicId,
+ }),
+ ).resolves.toEqual({
+ items: [expect.objectContaining({ id: 'topic-transcript-other-owner-message' })],
+ total: 1,
+ });
+ });
+
+ it('isolates personal and workspace transcripts for the same user', async () => {
+ await serverDB.insert(workspaces).values([
+ {
+ id: 'topic-transcript-workspace-a',
+ name: 'Workspace A',
+ primaryOwnerId: userId,
+ slug: 'topic-transcript-workspace-a',
+ },
+ {
+ id: 'topic-transcript-workspace-b',
+ name: 'Workspace B',
+ primaryOwnerId: userId,
+ slug: 'topic-transcript-workspace-b',
+ },
+ ]);
+ await serverDB.insert(topics).values({
+ id: 'topic-transcript-workspace-topic',
+ title: 'Workspace transcript',
+ userId,
+ workspaceId: 'topic-transcript-workspace-a',
+ });
+ await serverDB.insert(messages).values({
+ content: 'workspace A only',
+ id: 'topic-transcript-workspace-message',
+ role: 'user',
+ topicId: 'topic-transcript-workspace-topic',
+ userId,
+ workspaceId: 'topic-transcript-workspace-a',
+ });
+
+ const input = {
+ limit: 10,
+ offset: 0,
+ topicId: 'topic-transcript-workspace-topic',
+ };
+
+ await expect(
+ new MessageModel(serverDB, userId, 'topic-transcript-workspace-a').queryTopicTranscript(
+ input,
+ ),
+ ).resolves.toMatchObject({
+ items: [expect.objectContaining({ id: 'topic-transcript-workspace-message' })],
+ total: 1,
+ });
+ await expect(new MessageModel(serverDB, userId).queryTopicTranscript(input)).resolves.toEqual({
+ items: [],
+ total: 0,
+ });
+ await expect(
+ new MessageModel(serverDB, userId, 'topic-transcript-workspace-b').queryTopicTranscript(
+ input,
+ ),
+ ).resolves.toEqual({ items: [], total: 0 });
+ });
+});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index d78d0209090..f51b574c89a 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -108,6 +108,22 @@ export interface QueryMessagesOptions {
where?: SQL;
}
+export interface TopicTranscriptMessage {
+ content: string | null;
+ createdAt: Date;
+ id: string;
+ messageGroupId: string | null;
+ parentId: string | null;
+ role: string;
+ threadId: string | null;
+ tools: ChatToolPayload[] | null;
+}
+
+export interface TopicTranscriptResult {
+ items: TopicTranscriptMessage[];
+ total: number;
+}
+
export interface ModelTimingContext extends TimingSink {}
interface MessageRelatedFile {
@@ -446,6 +462,57 @@ export class MessageModel {
return messageItems;
};
+ /**
+ * Return a lightweight, ownership-scoped transcript for a topic.
+ *
+ * Unlike the conversation query, this intentionally does not infer missing
+ * session, group, or thread filters as `IS NULL`, and it does not replace raw
+ * message-group members with synthetic nodes. Consumers such as the CLI need
+ * the complete persisted transcript and exact database pagination.
+ */
+ queryTopicTranscript = async ({
+ limit,
+ offset,
+ topicId,
+ }: {
+ limit: number;
+ offset: number;
+ topicId: string;
+ }): Promise<TopicTranscriptResult> => {
+ const where = and(this.ownership(), eq(messages.topicId, topicId));
+
+ const [items, totalResult] = await Promise.all([
+ this.db
+ .select({
+ content: messages.content,
+ createdAt: messages.createdAt,
+ id: messages.id,
+ messageGroupId: messages.messageGroupId,
+ parentId: messages.parentId,
+ role: messages.role,
+ threadId: messages.threadId,
+ tools: messages.tools,
+ })
+ .from(messages)
+ .where(where)
+ .orderBy(asc(messages.createdAt), asc(messages.id))
+ .limit(limit)
+ .offset(offset),
+ this.db
+ .select({ count: count(messages.id) })
+ .from(messages)
+ .where(where),
+ ]);
+
+ return {
+ items: items.map(({ tools, ...message }) => ({
+ ...message,
+ tools: Array.isArray(tools) ? (tools as ChatToolPayload[]) : null,
+ })),
+ total: totalResult[0]?.count ?? 0,
+ };
+ };
+
/**
* Lightweight parent/group links for the FULL message tree of a topic,
* INCLUDING messages hidden inside MessageGroups (compression / parallel).