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(cli): add `lh topic view` command (#15340)

Arvin Xue1fe37933d08
diff --git a/apps/cli/src/commands/topic.test.ts b/apps/cli/src/commands/topic.test.ts
index fdff6d8127c..e08dad267fd 100644
--- a/apps/cli/src/commands/topic.test.ts
+++ b/apps/cli/src/commands/topic.test.ts
@@ -6,9 +6,13 @@ 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() },
getTopics: { query: vi.fn() },
recentTopics: { query: vi.fn() },
removeTopic: { mutate: vi.fn() },
@@ -41,6 +45,18 @@ 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(),
+ });
});
afterEach(() => {
@@ -203,4 +219,130 @@ describe('topic command', () => {
expect(mockTrpcClient.topic.recentTopics.query).toHaveBeenCalledWith({ limit: 10 });
});
});
+
+ 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 program = createProgram();
+ await program.parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ expect(mockTrpcClient.topic.getTopicDetail.query).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 't1' }),
+ );
+ expect(mockTrpcClient.message.getMessages.query).toHaveBeenCalledWith(
+ expect.objectContaining({ topicId: 't1' }),
+ );
+ expect(consoleSpy).toHaveBeenCalled();
+ });
+
+ 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']);
+
+ // 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();
+ });
+
+ it('should output json when --json flag is set', async () => {
+ mockTrpcClient.message.getMessages.query.mockResolvedValue([
+ { content: 'Hello', id: 'm1', role: 'user' },
+ ]);
+
+ 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');
+ });
+
+ 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']);
+
+ 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);
+ });
+
+ it('should respect -L for message page size', async () => {
+ mockTrpcClient.message.getMessages.query.mockResolvedValue([]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '-L', '10']);
+
+ expect(mockTrpcClient.message.getMessages.query).toHaveBeenCalledWith(
+ expect.objectContaining({ pageSize: 10, topicId: 't1' }),
+ );
+ });
+
+ 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' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'topic', 'view', 't1', '--from', '2', '--to', '3']);
+
+ // 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('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' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ const output = consoleSpy.mock.calls.flat().join('\n');
+ expect(output).toContain('web_search');
+ expect(output).toContain('lobehub');
+ });
+
+ 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' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'topic', 'view', 't1']);
+
+ 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'));
+ });
+ });
});
diff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.ts
index 7e62ffa2151..53dd5b212b7 100644
--- a/apps/cli/src/commands/topic.ts
+++ b/apps/cli/src/commands/topic.ts
@@ -332,4 +332,170 @@ 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.`,
+ ),
+ );
+ }
+ },
+ );
}
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index fe58e234809..bb3f23e6384 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -39,6 +39,14 @@ const topicProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
});
export const topicRouter = router({
+ getTopicDetail: topicProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const topic = await ctx.topicModel.findById(input.id);
+ if (!topic) return null;
+ return topic;
+ }),
+
getTopicContext: topicProcedure
.input(z.object({ topicId: z.string() }))
.query(async ({ input, ctx }) => {