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): include web page URLs in lh --json output (#21487)

Lobehub Coderf824fdcfd3ae
diff --git a/apps/cli/src/commands/acceptance/index.list.test.ts b/apps/cli/src/commands/acceptance/index.list.test.ts
new file mode 100644
index 00000000000..bf9ff5d59fd
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/index.list.test.ts
@@ -0,0 +1,43 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTrpcClient } from '../../api/client';
+import { registerAcceptanceCommands } from '.';
+
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn() }));
+vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: () => undefined }));
+vi.mock('../../settings', () => ({ resolveServerUrl: () => 'https://app.lobehub.com' }));
+
+const list = vi.fn();
+let output: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ output = vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.mocked(getTrpcClient).mockResolvedValue({
+ acceptance: { list: { query: list } },
+ } as unknown as Awaited<ReturnType<typeof getTrpcClient>>);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('acceptance list', () => {
+ it('links every acceptance to its page in JSON output', async () => {
+ list.mockResolvedValue([{ id: 'acc_1', requirement: 'Ship it', status: 'pending' }]);
+
+ const program = new Command().exitOverride();
+ registerAcceptanceCommands(program);
+ await program.parseAsync(['node', 'lh', 'acceptance', 'list', '--json']);
+
+ expect(JSON.parse(String(output.mock.calls.at(-1)?.[0]))).toEqual([
+ {
+ id: 'acc_1',
+ requirement: 'Ship it',
+ status: 'pending',
+ url: 'https://app.lobehub.com/acceptance/acc_1',
+ },
+ ]);
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/index.ts b/apps/cli/src/commands/acceptance/index.ts
index 6073f014354..d1479603ba2 100644
--- a/apps/cli/src/commands/acceptance/index.ts
+++ b/apps/cli/src/commands/acceptance/index.ts
@@ -11,6 +11,7 @@ import { getTrpcClient } from '../../api/client';
import { resolveServerUrl } from '../../settings';
import { outputJson, printTable, timeAgo, truncate } from '../../utils/format';
import { log } from '../../utils/logger';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from '../resourceUrl';
import { collectCommentFeedback } from './commentFeedback';
import { attachCriterionCommands } from './criterion';
import { attachAcceptanceFlowCommands } from './flow';
@@ -246,7 +247,12 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
const items = await client.acceptance.list.query();
if (options.json !== undefined) {
- outputJson(items, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.acceptance(item.id),
+ ),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
if (items.length === 0) {
@@ -275,7 +281,10 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
const bundle = await client.acceptance.getBundle.query({ id });
if (options.json !== undefined) {
- outputJson(bundle, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrl(bundle, await resolveUrlBuilder(client), resourcePath.acceptance(id)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
@@ -574,7 +583,10 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
const client = await getTrpcClient();
const result = await client.acceptance.setPreviewUrl.mutate({ id, url });
if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.acceptance(id)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
console.log(`${pc.green('βœ“')} r${result.roundIndex} preview: ${result.previewUrl}`);
@@ -616,7 +628,10 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
url,
});
if (options.json !== undefined) {
- outputJson(linked, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrl(linked, await resolveUrlBuilder(client), resourcePath.acceptance(id)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
console.log(
@@ -636,7 +651,10 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
const result = await client.acceptance.accept.mutate({ comment: options.comment, id });
if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.acceptance(id)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
console.log(`${pc.green('βœ“')} Delivery accepted (${result.id})`);
@@ -653,7 +671,10 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
const result = await client.acceptance.reject.mutate({ comment: options.comment, id });
if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.acceptance(id)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
console.log(`${pc.red('βœ—')} Delivery rejected (${result.id}) β€” next round re-opens it`);
diff --git a/apps/cli/src/commands/agent-group.test.ts b/apps/cli/src/commands/agent-group.test.ts
index 8dd40861180..4eaf226e768 100644
--- a/apps/cli/src/commands/agent-group.test.ts
+++ b/apps/cli/src/commands/agent-group.test.ts
@@ -73,6 +73,15 @@ describe('agent-group command', () => {
});
describe('view', () => {
+ it('prints null instead of crashing for a missing group with --json', async () => {
+ mockTrpcClient.group.getGroupDetail.query.mockResolvedValue(null);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent-group', 'view', 'missing', '--json']);
+
+ expect(consoleSpy).toHaveBeenCalledWith('null');
+ });
+
it('should view group details', async () => {
mockTrpcClient.group.getGroupDetail.query.mockResolvedValue({
agents: [{ id: 'a1', title: 'Agent 1' }],
diff --git a/apps/cli/src/commands/agent-group.ts b/apps/cli/src/commands/agent-group.ts
index 06e55fa2bc2..28d6ce33374 100644
--- a/apps/cli/src/commands/agent-group.ts
+++ b/apps/cli/src/commands/agent-group.ts
@@ -4,6 +4,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';
export function registerAgentGroupCommand(program: Command) {
@@ -21,7 +22,12 @@ export function registerAgentGroupCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(groups, fields);
+ outputJson(
+ withUrls(groups, await resolveUrlBuilder(client), (group: any) =>
+ resourcePath.group(group.id),
+ ),
+ fields,
+ );
return;
}
@@ -51,7 +57,10 @@ export function registerAgentGroupCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(detail, fields);
+ outputJson(
+ withUrl(detail, await resolveUrlBuilder(client), resourcePath.group(id)),
+ fields,
+ );
return;
}
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index 2123570cba1..d2ad74bb260 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -200,7 +200,7 @@ describe('agent command', () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'agent', 'list', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(agents, null, 2));
+ expect(consoleSpy.mock.calls[0][0]).toContain('"url": "https://app.lobehub.com/agent/a1"');
});
});
@@ -657,9 +657,8 @@ describe('agent command', () => {
'--json',
]);
- expect(consoleSpy).toHaveBeenCalledWith(
- JSON.stringify({ id: 'a1', title: 'Updated' }, null, 2),
- );
+ expect(JSON.parse(consoleSpy.mock.calls[0][0])).toMatchObject({ id: 'a1', title: 'Updated' });
+ expect(consoleSpy.mock.calls[0][0]).toContain('"url": "https://app.lobehub.com/agent/a1"');
});
});
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index b8db49f6c08..ba392d6a858 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -11,6 +11,7 @@ import { log } from '../utils/logger';
import { resolveAgentId } from './agent/resolveAgentId';
import { registerAgentRunCommand } from './agent/run';
import { registerAgentSpaceFsCommand } from './agent/spaceFs';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';
const readGraphConfig = async (graphFile: string): Promise<unknown> => {
@@ -77,7 +78,12 @@ export function registerAgentCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.agent(item.id),
+ ),
+ fields,
+ );
return;
}
@@ -125,7 +131,10 @@ export function registerAgentCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.agent(agentId)),
+ fields,
+ );
return;
}
@@ -312,7 +321,14 @@ export function registerAgentCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result?.agent ?? result, fields);
+ outputJson(
+ withUrl(
+ result?.agent ?? result,
+ await resolveUrlBuilder(client),
+ resourcePath.agent(agentId),
+ ),
+ fields,
+ );
return;
}
diff --git a/apps/cli/src/commands/dashboard.ts b/apps/cli/src/commands/dashboard.ts
index c33dbc8ac8e..0e5b0fab975 100644
--- a/apps/cli/src/commands/dashboard.ts
+++ b/apps/cli/src/commands/dashboard.ts
@@ -5,6 +5,7 @@ import { getTrpcClient } from '../api/client';
import { resolveWorkspaceId } from '../api/workspace';
import { outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';
/** Where a board opens: inside its project when it belongs to one, else on the home dashboards. */
@@ -28,7 +29,11 @@ export function registerDashboardCommand(program: Command) {
const { data } = options.project
? await client.dashboard.listByProject.query({ projectId: options.project })
: await client.dashboard.list.query({});
- if (options.json !== undefined) return outputJson(data, options.json);
+ if (options.json !== undefined)
+ return outputJson(
+ withUrls(data, await resolveUrlBuilder(client), resourcePath.dashboard),
+ options.json,
+ );
if (data.length === 0) return console.log('No dashboards found.');
printTable(
data.map((item) => [
@@ -48,7 +53,11 @@ export function registerDashboardCommand(program: Command) {
.action(async (id: string, options: { json?: boolean | string }) => {
const client = await getTrpcClient();
const { data } = await client.dashboard.detail.query({ id });
- if (options.json !== undefined) return outputJson(data, options.json);
+ if (options.json !== undefined)
+ return outputJson(
+ withUrl(data, await resolveUrlBuilder(client), resourcePath.dashboard(data)),
+ options.json,
+ );
const buildUrl = await resolveAppUrlBuilder(client);
console.log(`\n${pc.bold(data.title)} ${pc.dim(data.id)}`);
if (data.description) console.log(data.description);
@@ -98,7 +107,11 @@ export function registerDashboardCommand(program: Command) {
title: options.title,
widgetId: options.widget,
});
- if (options.json !== undefined) return outputJson(data, options.json);
+ if (options.json !== undefined)
+ return outputJson(
+ withUrl(data, await resolveUrlBuilder(client), resourcePath.dashboard(data)),
+ options.json,
+ );
const buildUrl = await resolveAppUrlBuilder(client);
console.log(`${pc.green('βœ“')} Created dashboard ${pc.bold(data.id)}`);
console.log(`${pc.bold('dashboard')}: ${buildUrl(dashboardPath(data))}`);
diff --git a/apps/cli/src/commands/doc.test.ts b/apps/cli/src/commands/doc.test.ts
index c71b8302f7a..bd9ba5c51f6 100644
--- a/apps/cli/src/commands/doc.test.ts
+++ b/apps/cli/src/commands/doc.test.ts
@@ -99,13 +99,17 @@ describe('doc command', () => {
});
it('should output JSON when --json flag is used', async () => {
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
const docs = [{ fileType: 'md', id: 'doc1', title: 'Test' }];
mockTrpcClient.document.queryDocuments.query.mockResolvedValue(docs);
const program = createProgram();
await program.parseAsync(['node', 'test', 'doc', 'list', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(docs, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify([{ ...docs[0], url: 'https://app.lobehub.com/page/doc1' }], null, 2),
+ );
});
it('should output JSON with selected fields', async () => {
@@ -199,13 +203,21 @@ describe('doc command', () => {
});
it('should output JSON when --json flag is used', async () => {
- const doc = { content: 'test', id: 'doc1', title: 'Test' };
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
+ const doc = { content: 'test', id: 'doc1', knowledgeBaseId: 'kb1', title: 'Test' };
mockTrpcClient.document.getDocumentById.query.mockResolvedValue(doc);
const program = createProgram();
await program.parseAsync(['node', 'test', 'doc', 'view', 'doc1', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(doc, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify(
+ { ...doc, url: 'https://app.lobehub.com/resource/library/kb1?file=doc1' },
+ null,
+ 2,
+ ),
+ );
});
it('should exit with error when document not found', async () => {
@@ -659,13 +671,17 @@ describe('doc command', () => {
});
it('should output JSON with --json flag', async () => {
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
const docs = [{ id: 'doc1', title: 'Note' }];
mockTrpcClient.notebook.listDocuments.query.mockResolvedValue({ data: docs, total: 1 });
const program = createProgram();
await program.parseAsync(['node', 'test', 'doc', 'topic-docs', 'topic_123', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(docs, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify([{ ...docs[0], url: 'https://app.lobehub.com/page/doc1' }], null, 2),
+ );
});
it('should show message when no documents found', async () => {
diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.ts
index ae07a103efd..e68c4a66968 100644
--- a/apps/cli/src/commands/doc.ts
+++ b/apps/cli/src/commands/doc.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 { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';
// ── Helpers ────────────────────────────────────────────────
@@ -55,7 +56,10 @@ export function registerDocCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(docs, fields);
+ outputJson(
+ withUrls(docs, await resolveUrlBuilder(client), resourcePath.document),
+ fields,
+ );
return;
}
@@ -93,7 +97,14 @@ export function registerDocCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(document, fields);
+ outputJson(
+ withUrl(
+ document,
+ await resolveUrlBuilder(client),
+ resourcePath.document(document as any),
+ ),
+ fields,
+ );
return;
}
@@ -365,7 +376,7 @@ export function registerDocCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(docs, fields);
+ outputJson(withUrls(docs, await resolveUrlBuilder(client), resourcePath.document), fields);
return;
}
diff --git a/apps/cli/src/commands/file.test.ts b/apps/cli/src/commands/file.test.ts
index b62e05c84fe..d990ae756f5 100644
--- a/apps/cli/src/commands/file.test.ts
+++ b/apps/cli/src/commands/file.test.ts
@@ -50,6 +50,7 @@ describe('file command', () => {
});
afterEach(() => {
+ vi.unstubAllEnvs();
exitSpy.mockRestore();
consoleSpy.mockRestore();
});
@@ -81,13 +82,22 @@ describe('file command', () => {
});
it('should output JSON when --json flag is used', async () => {
- const items = [{ id: 'f1', name: 'doc.pdf' }];
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
+ // A file's own `url` is its storage address, so the page link lands in `appUrl`.
+ const items = [{ id: 'f1', name: 'doc.pdf', url: 'https://s3.example.com/doc.pdf' }];
mockTrpcClient.file.getFiles.query.mockResolvedValue(items);
const program = createProgram();
await program.parseAsync(['node', 'test', 'file', 'list', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(items, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify(
+ [{ ...items[0], appUrl: 'https://app.lobehub.com/resource?file=f1' }],
+ null,
+ 2,
+ ),
+ );
});
it('should show message when no files found', async () => {
diff --git a/apps/cli/src/commands/file.ts b/apps/cli/src/commands/file.ts
index d046f56c054..56a4a699ecd 100644
--- a/apps/cli/src/commands/file.ts
+++ b/apps/cli/src/commands/file.ts
@@ -5,6 +5,7 @@ import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
import { uploadLocalFile } from '../utils/uploadLocalFile';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
export function registerFileCommand(program: Command) {
const file = program.command('file').description('Manage files');
@@ -28,7 +29,12 @@ export function registerFileCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.file({ ...item, knowledgeBaseId: item.knowledgeBaseId ?? options.kbId }),
+ ),
+ fields,
+ );
return;
}
@@ -66,7 +72,10 @@ export function registerFileCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.file(result as any)),
+ fields,
+ );
return;
}
@@ -158,7 +167,10 @@ export function registerFileCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.file(result as any)),
+ fields,
+ );
return;
}
@@ -200,7 +212,10 @@ export function registerFileCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.file(result as any)),
+ fields,
+ );
return;
}
@@ -245,7 +260,7 @@ export function registerFileCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(withUrls(items, await resolveUrlBuilder(client), resourcePath.file), fields);
return;
}
@@ -279,7 +294,7 @@ export function registerFileCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(withUrls(items, await resolveUrlBuilder(client), resourcePath.file), fields);
return;
}
diff --git a/apps/cli/src/commands/kb.test.ts b/apps/cli/src/commands/kb.test.ts
index a31ff2ed911..4747bd8afc4 100644
--- a/apps/cli/src/commands/kb.test.ts
+++ b/apps/cli/src/commands/kb.test.ts
@@ -49,6 +49,7 @@ describe('kb command', () => {
});
afterEach(() => {
+ vi.unstubAllEnvs();
exitSpy.mockRestore();
consoleSpy.mockRestore();
});
@@ -74,13 +75,21 @@ describe('kb command', () => {
});
it('should output JSON when --json flag is used', async () => {
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
const items = [{ id: 'kb1', name: 'Test' }];
mockTrpcClient.knowledgeBase.getKnowledgeBases.query.mockResolvedValue(items);
const program = createProgram();
await program.parseAsync(['node', 'test', 'kb', 'list', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(items, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify(
+ [{ ...items[0], url: 'https://app.lobehub.com/resource/library/kb1' }],
+ null,
+ 2,
+ ),
+ );
});
it('should show message when no knowledge bases found', async () => {
diff --git a/apps/cli/src/commands/kb.ts b/apps/cli/src/commands/kb.ts
index 57e6a0e02a4..da57be7e07c 100644
--- a/apps/cli/src/commands/kb.ts
+++ b/apps/cli/src/commands/kb.ts
@@ -7,6 +7,7 @@ import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
import { uploadLocalFile } from '../utils/uploadLocalFile';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';
function formatFileType(fileType: string): string {
@@ -45,7 +46,12 @@ export function registerKbCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.knowledgeBase(item.id),
+ ),
+ fields,
+ );
return;
}
@@ -112,7 +118,11 @@ export function registerKbCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson({ ...result, files: allItems }, fields);
+ const toUrl = await resolveUrlBuilder(client);
+ const files = withUrls(allItems, toUrl, (item) =>
+ resourcePath.file({ id: item.id, knowledgeBaseId: id }),
+ );
+ outputJson(withUrl({ ...result, files }, toUrl, resourcePath.knowledgeBase(id)), fields);
return;
}
diff --git a/apps/cli/src/commands/message.ts b/apps/cli/src/commands/message.ts
index 283687b243b..9571682dbbb 100644
--- a/apps/cli/src/commands/message.ts
+++ b/apps/cli/src/commands/message.ts
@@ -4,6 +4,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 { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';
export function registerMessageCommand(program: Command) {
const message = program.command('message').description('Manage messages');
@@ -56,7 +57,10 @@ export function registerMessageCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), resourcePath.message),
+ fields,
+ );
return;
}
@@ -91,7 +95,7 @@ export function registerMessageCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(withUrls(items, await resolveUrlBuilder(client), resourcePath.message), fields);
return;
}
diff --git a/apps/cli/src/commands/project.test.ts b/apps/cli/src/commands/project.test.ts
index dc3217667d4..188d4cb3775 100644
--- a/apps/cli/src/commands/project.test.ts
+++ b/apps/cli/src/commands/project.test.ts
@@ -51,6 +51,17 @@ describe('project command', () => {
vi.restoreAllMocks();
});
+ it('links the project page in view --json output', async () => {
+ mockClient.project.detail.query.mockResolvedValue({
+ data: { project: { id: 'prj_1', name: 'Apollo' } },
+ });
+ await createProgram().parseAsync(['node', 'test', 'project', 'view', 'prj_1', '--json']);
+ expect(JSON.parse(vi.mocked(console.log).mock.calls.at(-1)![0])).toMatchObject({
+ project: { id: 'prj_1' },
+ url: 'https://app.example.com/project/prj_1',
+ });
+ });
+
it('creates a project', async () => {
mockClient.project.create.mutate.mockResolvedValue({ data: { id: 'prj_1' } });
await createProgram().parseAsync([
diff --git a/apps/cli/src/commands/project.ts b/apps/cli/src/commands/project.ts
index f11cf8f7806..7b136b4bc5d 100644
--- a/apps/cli/src/commands/project.ts
+++ b/apps/cli/src/commands/project.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 { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';
const statusValues = PROJECT_STATUSES.join(', ');
@@ -23,7 +24,11 @@ export function registerProjectCommand(program: Command) {
const result = await client.project.list.query({
statuses: options.status as (typeof PROJECT_STATUSES)[number][] | undefined,
});
- if (options.json !== undefined) return outputJson(result.data, options.json);
+ if (options.json !== undefined)
+ return outputJson(
+ withUrls(result.data, await resolveUrlBuilder(client), (p) => resourcePath.project(p.id)),
+ options.json,
+ );
if (result.data.length === 0) return console.log('No projects found.');
printTable(
result.data.map((item) => [
@@ -42,8 +47,13 @@ export function registerProjectCommand(program: Command) {
.description('View project detail')
.option('--json [fields]', 'Output JSON')
.action(async (id: string, options: { json?: boolean | string }) => {
- const { data } = await (await getTrpcClient()).project.detail.query({ id });
- if (options.json !== undefined) return outputJson(data, options.json);
+ const client = await getTrpcClient();
+ const { data } = await client.project.detail.query({ id });
+ if (options.json !== undefined)
+ return outputJson(
+ withUrl(data, await resolveUrlBuilder(client), resourcePath.project(data.project.id)),
+ options.json,
+ );
console.log(`\n${pc.bold(data.project.name)} ${pc.dim(data.project.id)}`);
console.log(`${pc.dim('Status:')} ${data.project.status}`);
console.log(`${pc.dim('Visibility:')} ${data.project.visibility}`);
diff --git a/apps/cli/src/commands/provider.test.ts b/apps/cli/src/commands/provider.test.ts
index f6b05a1e228..83ab9f7c67f 100644
--- a/apps/cli/src/commands/provider.test.ts
+++ b/apps/cli/src/commands/provider.test.ts
@@ -40,6 +40,7 @@ describe('provider command', () => {
});
afterEach(() => {
+ vi.unstubAllEnvs();
exitSpy.mockRestore();
consoleSpy.mockRestore();
});
@@ -64,13 +65,21 @@ describe('provider command', () => {
});
it('should output JSON', async () => {
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
const providers = [{ id: 'openai', name: 'OpenAI' }];
mockTrpcClient.aiProvider.getAiProviderList.query.mockResolvedValue(providers);
const program = createProgram();
await program.parseAsync(['node', 'test', 'provider', 'list', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(providers, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify(
+ [{ ...providers[0], url: 'https://app.lobehub.com/settings/provider/openai' }],
+ null,
+ 2,
+ ),
+ );
});
});
diff --git a/apps/cli/src/commands/provider.ts b/apps/cli/src/commands/provider.ts
index 5d67ea78b9c..f990411e63a 100644
--- a/apps/cli/src/commands/provider.ts
+++ b/apps/cli/src/commands/provider.ts
@@ -5,6 +5,7 @@ import { getTrpcClient } from '../api/client';
import { CLI_PRODUCT_NAME } from '../constants/identity';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
export function registerProviderCommand(program: Command) {
const provider = program.command('provider').description('Manage AI providers');
@@ -22,7 +23,12 @@ export function registerProviderCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.provider(item.id),
+ ),
+ fields,
+ );
return;
}
@@ -59,7 +65,10 @@ export function registerProviderCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), resourcePath.provider(id)),
+ fields,
+ );
return;
}
diff --git a/apps/cli/src/commands/resourceUrl.test.ts b/apps/cli/src/commands/resourceUrl.test.ts
new file mode 100644
index 00000000000..9155f5e4738
--- /dev/null
+++ b/apps/cli/src/commands/resourceUrl.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ resolveUrlBuilder,
+ resourcePath,
+ searchResultPath,
+ withUrl,
+ withUrls,
+} from './resourceUrl';
+
+vi.mock('../api/workspace', () => ({ resolveWorkspaceId: () => 'ws-1' }));
+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));
+
+const clientWith = (query: () => Promise<unknown>) =>
+ ({ workspace: { getById: { query } } }) as any;
+
+describe('resourcePath', () => {
+ it.each([
+ [resourcePath.agent('agt_1'), '/agent/agt_1'],
+ [resourcePath.topic({ agentId: 'agt_1', id: 'tpc_1' }), '/agent/agt_1/tpc_1'],
+ [resourcePath.topic({ groupId: 'grp_1', id: 'tpc_1' }), '/group/grp_1/tpc_1'],
+ [
+ resourcePath.message({ agentId: 'agt_1', id: 'msg_1', topicId: 'tpc_1' }),
+ '/agent/agt_1/tpc_1#msg_1',
+ ],
+ [resourcePath.document({ id: 'docs_1' }), '/page/docs_1'],
+ [
+ resourcePath.document({ id: 'docs_1', knowledgeBaseId: 'kb_1' }),
+ '/resource/library/kb_1?file=docs_1',
+ ],
+ [resourcePath.file({ id: 'file_1' }), '/resource?file=file_1'],
+ [resourcePath.dashboard({ id: 'dsh_1', projectId: 'prj_1' }), '/project/prj_1/dashboard/dsh_1'],
+ [resourcePath.task({ identifier: 'T-1', name: 'Ship it' }), '/task/T-1/ship-it'],
+ [resourcePath.acceptance('acc_1'), '/acceptance/acc_1'],
+ ])('builds %s', (actual, expected) => {
+ expect(actual).toBe(expected);
+ });
+
+ it('gives no path when the entity lacks the ids its page needs', () => {
+ expect(resourcePath.topic({ id: 'tpc_1' })).toBeUndefined();
+ expect(resourcePath.task({ name: 'no identifier' })).toBeUndefined();
+ expect(searchResultPath({ id: 'x', type: 'unknown' })).toBeUndefined();
+ });
+});
+
+describe('withUrl', () => {
+ it('prefixes the active workspace slug', async () => {
+ const toUrl = await resolveUrlBuilder(clientWith(async () => ({ slug: 'acme' })));
+
+ expect(withUrls([{ id: 'agt_1' }], toUrl, (a) => resourcePath.agent(a.id))).toEqual([
+ { id: 'agt_1', url: 'https://app.example.com/acme/agent/agt_1' },
+ ]);
+ });
+
+ it('keeps an entity-owned url and adds the page link as appUrl', async () => {
+ const toUrl = await resolveUrlBuilder(clientWith(async () => ({ slug: 'acme' })));
+ const file = { id: 'file_1', url: 'https://s3.example.com/a.png' };
+
+ expect(withUrl(file, toUrl, resourcePath.file(file))).toEqual({
+ ...file,
+ appUrl: 'https://app.example.com/acme/resource?file=file_1',
+ });
+ });
+
+ it('passes a not-found null read through', async () => {
+ const toUrl = await resolveUrlBuilder(clientWith(async () => ({ slug: 'acme' })));
+
+ expect(withUrl(null as unknown as object, toUrl, resourcePath.group('grp_1'))).toBeNull();
+ });
+
+ it('leaves items untouched when the workspace lookup fails', async () => {
+ const toUrl = await resolveUrlBuilder(clientWith(() => Promise.reject(new Error('denied'))));
+
+ expect(withUrl({ id: 'agt_1' }, toUrl, resourcePath.agent('agt_1'))).toEqual({ id: 'agt_1' });
+ });
+});
diff --git a/apps/cli/src/commands/resourceUrl.ts b/apps/cli/src/commands/resourceUrl.ts
new file mode 100644
index 00000000000..e33d412ca65
--- /dev/null
+++ b/apps/cli/src/commands/resourceUrl.ts
@@ -0,0 +1,154 @@
+import type { TrpcClient } from '../api/client';
+import { resolveServerUrl } from '../settings';
+import { buildAppUrl, resolveAppUrlBuilder, taskPath } from './task/url';
+
+/**
+ * Web paths of the entities `lh` prints, matching the SPA routes (and the
+ * command menu's navigation). Each returns `undefined` when the entity lacks
+ * the ids its page needs, so JSON output simply omits the `url` field.
+ */
+type Id = string | null | undefined;
+
+const seg = (value: string) => encodeURIComponent(value);
+
+const libraryItemPath = (id: string, knowledgeBaseId: Id) =>
+ `/resource/library/${seg(knowledgeBaseId!)}?file=${seg(id)}`;
+
+export const resourcePath = {
+ acceptance: (id: Id) => (id ? `/acceptance/${seg(id)}` : undefined),
+ agent: (id: Id) => (id ? `/agent/${seg(id)}` : undefined),
+ dashboard: (dashboard: { id?: Id; projectId?: Id }) => {
+ if (!dashboard.id) return undefined;
+ return dashboard.projectId
+ ? `/project/${seg(dashboard.projectId)}/dashboard/${seg(dashboard.id)}`
+ : `/dashboard/${seg(dashboard.id)}`;
+ },
+ /** A document opens inside its library when it has one, else as a standalone page. */
+ document: (doc: { id?: Id; knowledgeBaseId?: Id }) => {
+ if (!doc.id) return undefined;
+ return doc.knowledgeBaseId
+ ? libraryItemPath(doc.id, doc.knowledgeBaseId)
+ : `/page/${seg(doc.id)}`;
+ },
+ file: (file: { id?: Id; knowledgeBaseId?: Id }) => {
+ if (!file.id) return undefined;
+ return file.knowledgeBaseId
+ ? libraryItemPath(file.id, file.knowledgeBaseId)
+ : `/resource?file=${seg(file.id)}`;
+ },
+ goal: (id: Id) => (id ? `/goal/${seg(id)}` : undefined),
+ group: (id: Id) => (id ? `/group/${seg(id)}` : undefined),
+ knowledgeBase: (id: Id) => (id ? `/resource/library/${seg(id)}` : undefined),
+ /** A message anchors inside its topic, or its agent/group chat when it has no topic. */
+ message: (message: { agentId?: Id; groupId?: Id; id?: Id; topicId?: Id }) => {
+ if (!message.id) return undefined;
+ const base = message.topicId
+ ? resourcePath.topic({
+ agentId: message.agentId,
+ groupId: message.groupId,
+ id: message.topicId,
+ })
+ : (resourcePath.agent(message.agentId) ?? resourcePath.group(message.groupId));
+ return base ? `${base}#${seg(message.id)}` : undefined;
+ },
+ project: (id: Id) => (id ? `/project/${seg(id)}` : undefined),
+ provider: (id: Id) => (id ? `/settings/provider/${seg(id)}` : undefined),
+ task: (task: { identifier?: Id; name?: Id }) =>
+ task.identifier ? taskPath(task.identifier, task.name) : undefined,
+ topic: (topic: { agentId?: Id; groupId?: Id; id?: Id }) => {
+ if (!topic.id) return undefined;
+ if (topic.groupId) return `/group/${seg(topic.groupId)}/${seg(topic.id)}`;
+ if (topic.agentId) return `/agent/${seg(topic.agentId)}/${seg(topic.id)}`;
+ return undefined;
+ },
+};
+
+/** Mirrors the command menu's navigation for a unified `lh search` hit. */
+export const searchResultPath = (item: Record<string, any>): string | undefined => {
+ switch (item.type) {
+ case 'agent': {
+ return resourcePath.agent(item.id);
+ }
+ case 'chatGroup': {
+ return resourcePath.group(item.id);
+ }
+ case 'topic': {
+ return resourcePath.topic(item);
+ }
+ case 'message': {
+ return resourcePath.message(item);
+ }
+ case 'file': {
+ return resourcePath.file(item);
+ }
+ case 'page': {
+ return item.id ? `/page/${seg(item.id)}` : undefined;
+ }
+ case 'knowledgeBase': {
+ return resourcePath.knowledgeBase(item.id);
+ }
+ case 'task': {
+ return resourcePath.task({ identifier: item.identifier, name: item.title });
+ }
+ case 'mcp':
+ case 'plugin': {
+ return item.identifier ? `/community/mcp/${seg(item.identifier)}` : undefined;
+ }
+ case 'communityAgent': {
+ return item.identifier ? `/community/agent/${seg(item.identifier)}` : undefined;
+ }
+ case 'memory': {
+ return item.id ? `/memory/preferences?preferenceId=${seg(item.id)}` : undefined;
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+/** A workspace's home, built from its own slug rather than the active scope. */
+export const workspaceUrl = (workspace: { slug?: Id }) =>
+ workspace.slug
+ ? buildAppUrl({
+ pathname: '/',
+ serverUrl: resolveServerUrl(),
+ workspaceSlug: workspace.slug,
+ }).replace(/\/$/, '')
+ : undefined;
+
+export type UrlBuilder = (pathname: string | undefined) => string | undefined;
+
+/**
+ * Best-effort link builder for JSON output: a read must not fail over a link,
+ * and an operation-token run may be refused the workspace lookup behind it.
+ */
+export const resolveUrlBuilder = async (client: TrpcClient): Promise<UrlBuilder> => {
+ try {
+ const buildUrl = await resolveAppUrlBuilder(client);
+ return (pathname) => (pathname ? buildUrl(pathname) : undefined);
+ } catch {
+ return () => undefined;
+ }
+};
+
+/**
+ * Appends the web link as `url`; items whose page can't be resolved are left
+ * as-is. Entities that already own a `url` (a file's storage address) keep it
+ * and get the link as `appUrl` instead.
+ */
+export const withUrls = <T extends object>(
+ items: T[],
+ toUrl: UrlBuilder,
+ toPath: (item: T) => string | undefined,
+): T[] => items.map((item) => withUrl(item, toUrl, toPath(item)));
+
+export const withUrl = <T extends object>(
+ item: T,
+ toUrl: UrlBuilder,
+ pathname: string | undefined,
+): T => {
+ const url = toUrl(pathname);
+ // A not-found read can come back as `null`; pass it through untouched.
+ if (!url || !item || typeof item !== 'object') return item;
+ return 'url' in item ? { ...item, appUrl: url } : { ...item, url };
+};
diff --git a/apps/cli/src/commands/search.test.ts b/apps/cli/src/commands/search.test.ts
index 7ea3ca4ea65..158f8af8650 100644
--- a/apps/cli/src/commands/search.test.ts
+++ b/apps/cli/src/commands/search.test.ts
@@ -43,6 +43,7 @@ describe('search command', () => {
});
afterEach(() => {
+ vi.unstubAllEnvs();
exitSpy.mockRestore();
consoleSpy.mockRestore();
});
@@ -88,13 +89,29 @@ describe('search command', () => {
});
it('should output JSON when --json flag is used', async () => {
- const results = [{ id: '1', title: 'Test', type: 'agent' }];
+ vi.stubEnv('LOBEHUB_SERVER', 'https://app.lobehub.com');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');
+ const results = [
+ { id: 'agt_1', title: 'Test', type: 'agent' },
+ { agentId: 'agt_1', id: 'tpc_1', title: 'Chat', type: 'topic' },
+ { id: 'x', type: 'unknown' },
+ ];
mockTrpcClient.search.query.query.mockResolvedValue(results);
const program = createProgram();
await program.parseAsync(['node', 'test', 'search', '-q', 'test', '--json']);
- expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(results, null, 2));
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify(
+ [
+ { ...results[0], url: 'https://app.lobehub.com/agent/agt_1' },
+ { ...results[1], url: 'https://app.lobehub.com/agent/agt_1/tpc_1' },
+ results[2],
+ ],
+ null,
+ 2,
+ ),
+ );
});
it('should show message when no results found', async () => {
diff --git a/apps/cli/src/commands/search.ts b/apps/cli/src/commands/search.ts
index ef91bc2e236..203f60e854b 100644
--- a/apps/cli/src/commands/search.ts
+++ b/apps/cli/src/commands/search.ts
@@ -4,6 +4,7 @@ import pc from 'picocolors';
import { getToolsTrpcClient, getTrpcClient } from '../api/client';
import { outputJson, printTable, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { resolveUrlBuilder, searchResultPath, withUrl, withUrls } from './resourceUrl';
const SEARCH_TYPES = [
'agent',
@@ -126,7 +127,19 @@ async function localSearch(
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ const toUrl = await resolveUrlBuilder(client);
+ const link = (items: any[]) => withUrls(items, toUrl, searchResultPath);
+ outputJson(
+ Array.isArray(result)
+ ? link(result)
+ : Object.fromEntries(
+ Object.entries(result as Record<string, unknown>).map(([type, items]) => [
+ type,
+ Array.isArray(items) ? link(items) : items,
+ ]),
+ ),
+ fields,
+ );
return;
}
@@ -306,7 +319,10 @@ async function localView(target: string, options: { json?: string | boolean }) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(result, fields);
+ outputJson(
+ withUrl(result, await resolveUrlBuilder(client), searchResultPath({ ...result, id, type })),
+ fields,
+ );
return;
}
diff --git a/apps/cli/src/commands/task.test.ts b/apps/cli/src/commands/task.test.ts
index c9f89e46ca2..4a3647a3726 100644
--- a/apps/cli/src/commands/task.test.ts
+++ b/apps/cli/src/commands/task.test.ts
@@ -177,3 +177,85 @@ describe('task usage', () => {
consoleSpy.mockRestore();
});
});
+
+describe('task list', () => {
+ const mockList = vi.fn();
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockList.mockReset();
+ mockResolveWorkspaceId.mockReset();
+ mockGetWorkspace.mockReset();
+ mockGetTrpcClient.mockResolvedValue({
+ task: { list: { query: mockList } },
+ workspace: { getById: { query: mockGetWorkspace } },
+ });
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ });
+
+ it('links every task to its workspace page in JSON output', async () => {
+ mockResolveWorkspaceId.mockReturnValue('ws-1');
+ mockGetWorkspace.mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });
+ mockList.mockResolvedValue({
+ data: [{ id: 'task_1', identifier: 'T-1031', name: 'Weekly digest', status: 'backlog' }],
+ });
+
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'test', 'task', 'list', '--json']);
+
+ expect(JSON.parse(String(consoleSpy.mock.calls.at(-1)?.[0]))).toEqual([
+ {
+ id: 'task_1',
+ identifier: 'T-1031',
+ name: 'Weekly digest',
+ status: 'backlog',
+ url: 'https://app.example.com/lobehub/task/T-1031/weekly-digest',
+ },
+ ]);
+ });
+
+ it('still lists tasks when the workspace lookup behind the link fails', async () => {
+ mockResolveWorkspaceId.mockReturnValue('ws-1');
+ mockGetWorkspace.mockRejectedValue(new Error('forbidden'));
+ mockList.mockResolvedValue({ data: [{ id: 'task_1', identifier: 'T-1', name: 'A' }] });
+
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'test', 'task', 'list', '--json']);
+
+ expect(JSON.parse(String(consoleSpy.mock.calls.at(-1)?.[0]))).toEqual([
+ { id: 'task_1', identifier: 'T-1', name: 'A' },
+ ]);
+ });
+});
+
+describe('task topic list', () => {
+ it('links each topic through the agent that owns it', async () => {
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockResolveWorkspaceId.mockReturnValue(undefined);
+ mockGetTrpcClient.mockResolvedValue({
+ task: {
+ getTopics: {
+ query: vi.fn().mockResolvedValue({ data: [{ agentId: 'agt_1', id: 'tpc_1', seq: 1 }] }),
+ },
+ },
+ });
+
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'test', 'task', 'topic', 'list', 'T-1', '--json']);
+
+ expect(JSON.parse(String(consoleSpy.mock.calls.at(-1)?.[0]))).toEqual([
+ { agentId: 'agt_1', id: 'tpc_1', seq: 1, url: 'https://app.example.com/agent/agt_1/tpc_1' },
+ ]);
+ consoleSpy.mockRestore();
+ });
+});
diff --git a/apps/cli/src/commands/task/archive.ts b/apps/cli/src/commands/task/archive.ts
index 6f275a5c7f3..ea30de2e4fd 100644
--- a/apps/cli/src/commands/task/archive.ts
+++ b/apps/cli/src/commands/task/archive.ts
@@ -4,6 +4,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { outputJson } from '../../utils/format';
import { log } from '../../utils/logger';
+import { resolveUrlBuilder, resourcePath, withUrl } from '../resourceUrl';
export function registerArchiveCommands(task: Command) {
// ── archive / unarchive ─────────────────────────────────
@@ -20,7 +21,10 @@ export function registerArchiveCommands(task: Command) {
const result = await client.task.archive.mutate({ archived, id });
if (options.json !== undefined) {
- outputJson(result.data, options.json);
+ outputJson(
+ withUrl(result.data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
+ options.json,
+ );
return;
}
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index 57fbfc6d148..8ca060d3262 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -13,6 +13,7 @@ import {
truncate,
} from '../../utils/format';
import { log } from '../../utils/logger';
+import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from '../resourceUrl';
import { registerArchiveCommands } from './archive';
import { resolveAssigneeUserId } from './assignee';
import { registerCheckpointCommands } from './checkpoint';
@@ -78,7 +79,10 @@ export function registerTaskCommand(program: Command) {
const result = await client.task.list.query(input as any);
if (options.json !== undefined) {
- outputJson(result.data, options.json);
+ outputJson(
+ withUrls(result.data, await resolveUrlBuilder(client), resourcePath.task),
+ options.json,
+ );
return;
}
@@ -213,7 +217,10 @@ export function registerTaskCommand(program: Command) {
const doc = await client.document.getDocumentDetail.query({ id });
if (options.json !== undefined) {
- outputJson(doc, options.json);
+ outputJson(
+ withUrl(doc, await resolveUrlBuilder(client), resourcePath.document(doc)),
+ options.json,
+ );
return;
}
@@ -239,7 +246,10 @@ export function registerTaskCommand(program: Command) {
const items = Array.isArray(messages) ? messages : [];
if (options.json !== undefined) {
- outputJson(items, options.json);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), resourcePath.message),
+ options.json,
+ );
return;
}
@@ -643,7 +653,10 @@ export function registerTaskCommand(program: Command) {
const result = await client.task.update.mutate(input as any);
if (options.json !== undefined) {
- outputJson(result.data, typeof options.json === 'string' ? options.json : undefined);
+ outputJson(
+ withUrl(result.data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
return;
}
@@ -697,7 +710,10 @@ export function registerTaskCommand(program: Command) {
const result = await client.task.getTaskTree.query({ id });
if (options.json !== undefined) {
- outputJson(result.data, options.json);
+ outputJson(
+ withUrls(result.data, await resolveUrlBuilder(client), resourcePath.task),
+ options.json,
+ );
return;
}
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.ts
index d2b9f27d5bc..46c2b1a85a4 100644
--- a/apps/cli/src/commands/task/lifecycle.ts
+++ b/apps/cli/src/commands/task/lifecycle.ts
@@ -8,6 +8,7 @@ import { outputJson } from '../../utils/format';
import { log } from '../../utils/logger';
import { followAgentRun } from '../agent/followRun';
import { pollAgentRunStatus, RUN_POLL_INTERVAL_MS } from '../agent/runStatus';
+import { resolveUrlBuilder, resourcePath } from '../resourceUrl';
type LifecycleClient = Awaited<ReturnType<typeof getTrpcClient>>;
@@ -204,7 +205,9 @@ export function registerLifecycleCommands(task: Command) {
const operationId = result.operationId;
if (!shouldFollow && options.json) {
+ const toUrl = await resolveUrlBuilder(client);
outputJson({
+ taskUrl: toUrl(resourcePath.task({ identifier: result.taskIdentifier })),
autoStarted: result.autoStarted,
operationId,
status: result.status,
diff --git a/apps/cli/src/commands/task/topic.ts b/apps/cli/src/commands/task/topic.ts
index d4e38d472aa..44c461211e2 100644
--- a/apps/cli/src/commands/task/topic.ts
+++ b/apps/cli/src/commands/task/topic.ts
@@ -4,6 +4,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 { resolveUrlBuilder, resourcePath, withUrls } from '../resourceUrl';
import { statusBadge } from './helpers';
export function registerTopicCommands(task: Command) {
@@ -19,7 +20,10 @@ export function registerTopicCommands(task: Command) {
const result = await client.task.getTopics.query({ id });
if (options.json !== undefined) {
- outputJson(result.data, options.json);
+ outputJson(
+ withUrls(result.data, await resolveUrlBuilder(client), resourcePath.topic),
+ options.json,
+ );
return;
}
@@ -67,7 +71,10 @@ export function registerTopicCommands(task: Command) {
const items = Array.isArray(messages) ? messages : [];
if (options.json !== undefined) {
- outputJson(items, options.json);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), resourcePath.message),
+ options.json,
+ );
return;
}
diff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.ts
index 574e5934aa6..e72fcd289c1 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 { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';
import { registerTopicExportCommand } from './topic/export';
import { registerTopicViewCommand } from './topic/view';
@@ -41,7 +42,12 @@ export function registerTopicCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.topic({ ...item, agentId: item.agentId ?? options.agentId }),
+ ),
+ fields,
+ );
return;
}
@@ -79,7 +85,12 @@ export function registerTopicCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.topic({ ...item, agentId: item.agentId ?? options.agentId }),
+ ),
+ fields,
+ );
return;
}
@@ -317,7 +328,12 @@ export function registerTopicCommand(program: Command) {
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
- outputJson(items, fields);
+ outputJson(
+ withUrls(items, await resolveUrlBuilder(client), (item: any) =>
+ resourcePath.topic({ agentId: item.agent?.id, groupId: item.group?.id, id: item.id }),
+ ),
+ fields,
+ );
return;
}
diff --git a/apps/cli/src/commands/workspace.test.ts b/apps/cli/src/commands/workspace.test.ts
index 20cb3662630..25f8d5edd60 100644
--- a/apps/cli/src/commands/workspace.test.ts
+++ b/apps/cli/src/commands/workspace.test.ts
@@ -245,7 +245,11 @@ describe('workspace command', () => {
expect(mockGetTrpcClient).toHaveBeenCalledWith('ws_1');
expect(consoleSpy).toHaveBeenCalledWith(
- JSON.stringify({ id: 'ws_1', name: 'Acme', slug: 'acme' }, null, 2),
+ JSON.stringify(
+ { id: 'ws_1', name: 'Acme', slug: 'acme', url: 'https://app.lobehub.com/acme' },
+ null,
+ 2,
+ ),
);
});
diff --git a/apps/cli/src/commands/workspace.ts b/apps/cli/src/commands/workspace.ts
index 7ca5438f14b..5fd92d75c92 100644
--- a/apps/cli/src/commands/workspace.ts
+++ b/apps/cli/src/commands/workspace.ts
@@ -8,6 +8,7 @@ import { CLI_PRIMARY_BIN } from '../constants/identity';
import { type ActiveWorkspaceRecord, resolveServerUrl, saveActiveWorkspace } from '../settings';
import { formatCost, outputJson, printTable, timeAgo, timeUntil, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { workspaceUrl } from './resourceUrl';
interface WorkspaceRow {
id: string;
@@ -193,7 +194,11 @@ export function registerWorkspaceCommand(program: Command) {
.option('--json [fields]', 'Output JSON')
.action(async (options: { json?: boolean | string }) => {
const workspaces = await listWorkspaces();
- if (options.json !== undefined) return outputJson(workspaces, options.json);
+ if (options.json !== undefined)
+ return outputJson(
+ workspaces.map((w) => ({ ...w, url: workspaceUrl(w) })),
+ options.json,
+ );
if (workspaces.length === 0) return console.log('No workspaces found.');
// The marker has to follow the same precedence every other command uses,
@@ -226,7 +231,8 @@ export function registerWorkspaceCommand(program: Command) {
process.exit(1);
}
- if (options.json !== undefined) return outputJson(detail, options.json);
+ if (options.json !== undefined)
+ return outputJson({ ...detail, url: workspaceUrl(detail) }, options.json);
const row = detail as WorkspaceRow & { description?: string | null; frozen?: boolean };
console.log(`\n${pc.bold(row.name)} ${pc.dim(row.id)}`);
@@ -264,7 +270,8 @@ export function registerWorkspaceCommand(program: Command) {
if (options.use) persistScope(created.id);
- if (options.json !== undefined) return outputJson(created, options.json);
+ if (options.json !== undefined)
+ return outputJson({ ...created, url: workspaceUrl(created) }, options.json);
console.log(`Created ${pc.bold(created.name)} ${pc.dim(created.id)}`);
if (options.use) {
console.log(`Scope set to ${pc.bold(created.name)}.`);
diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.ts
index 30a97d33c46..f54776ec893 100644
--- a/packages/database/src/models/__tests__/taskTopic.test.ts
+++ b/packages/database/src/models/__tests__/taskTopic.test.ts
@@ -610,7 +610,7 @@ describe('TaskTopicModel', () => {
await serverDB
.insert(topics)
.values([
- { id: 'tpc_d1', title: 'First', userId },
+ { agentId: null, id: 'tpc_d1', title: 'First', userId },
{ id: 'tpc_d2', title: 'Second', userId },
])
.onConflictDoNothing();
@@ -633,6 +633,9 @@ describe('TaskTopicModel', () => {
const d1 = rows.find((r) => r.id === 'tpc_d1')!;
expect(d1.title).toBe('First');
+ // The CLI links a task topic through the conversation that owns it.
+ expect(d1).toHaveProperty('agentId', null);
+ expect(d1).toHaveProperty('groupId', null);
expect(d1.operationId).toBe('op_d1');
expect(d1.status).toBe('completed');
expect(d1.reviewIteration).toBe(2);
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index 917f8dad7f6..9f3a65ea376 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -407,7 +407,9 @@ export class TaskTopicModel {
async findWithDetails(taskId: string) {
return this.db
.select({
+ agentId: topics.agentId,
createdAt: topics.createdAt,
+ groupId: topics.groupId,
handoff: taskTopics.handoff,
id: topics.id,
metadata: topics.metadata,