π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(cli): return URLs for created resources (#18828)
Arvin Xuc11536481054
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.tsindex 918eee3e457..1685feeb7e1 100644--- a/apps/cli/src/commands/acceptanceRun.ts+++ b/apps/cli/src/commands/acceptanceRun.ts@@ -719,6 +719,12 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption// The chained round's index β `?r=<roundIndex>` on the acceptance URL// deep-links this round's report as the fixed snapshot view.const roundIndex = attached?.roundIndex ?? null;+ const acceptanceUrl = new URL(+ `/acceptance/${encodeURIComponent(acceptanceId)}`,+ resolveServerUrl(),+ ).toString();+ const roundUrl =+ roundIndex === null ? null : `${acceptanceUrl}?r=${encodeURIComponent(String(roundIndex))}`;// 2. Ingest each case as a check result + its evidence. `checkItemId` is// the stable key within this immutable run.@@ -831,6 +837,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOptionoutputJson({acceptanceId,+ acceptanceUrl,cases: cases.length,droppedProgrammaticChecks: droppedLabels,evidence: evidenceCount,@@ -839,6 +846,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOptionplanItems: plan?.length ?? 0,pullRequest,roundIndex,+ roundUrl,scenario,subject: subject!.ref,unplanned,@@ -873,9 +881,9 @@ async function ingestReportAction(reportDir: string, options: IngestReportOptionif (options.open) {// The acceptance page is the only link surfaced to users β the raw /verify// page stays internal. `?r=<roundIndex>` is this round's fixed snapshot.- console.log(`${pc.bold('open acceptance')}: /acceptance/${acceptanceId}`);- if (roundIndex !== null) {- console.log(`${pc.bold('round snapshot')}: /acceptance/${acceptanceId}?r=${roundIndex}`);+ console.log(`${pc.bold('open acceptance')}: ${acceptanceUrl}`);+ if (roundUrl) {+ console.log(`${pc.bold('round snapshot')}: ${roundUrl}`);}}}diff --git a/apps/cli/src/commands/agent-group.ts b/apps/cli/src/commands/agent-group.tsindex afa93b930a3..06e55fa2bc2 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 { resolveAppUrlBuilder } from './task/url';export function registerAgentGroupCommand(program: Command) {const agentGroup = program.command('agent-group').description('Manage agent groups');@@ -86,19 +87,23 @@ export function registerAgentGroupCommand(program: Command) {.option('--json', 'Output JSON').action(async (options: { description?: string; json?: boolean; title: string }) => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: Record<string, any> = { title: options.title };if (options.description) input.description = options.description;const result = await client.group.createGroup.mutate(input as any);+ const r = result as any;+ const groupId = r.group?.id;+ const url = buildUrl(`/group/${encodeURIComponent(groupId)}`);if (options.json) {- console.log(JSON.stringify(result, null, 2));+ console.log(JSON.stringify({ ...result, url }, null, 2));return;}- const r = result as any;- console.log(`${pc.green('β')} Created agent group ${pc.bold(r.group?.id || '')}`);+ console.log(`${pc.green('β')} Created agent group ${pc.bold(groupId || '')}`);+ console.log(`${pc.bold('group')}: ${url}`);});// ββ edit βββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex b4143ef749c..f6f698eb7c9 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -17,6 +17,7 @@ import { confirm, outputJson, printTable, truncate } from '../utils/format';import { log, setVerbose } from '../utils/logger';import { resolveAgentId } from './agent/resolveAgentId';import { registerAgentSpaceFsCommand } from './agent/spaceFs';+import { resolveAppUrlBuilder } from './task/url';const readGraphConfig = async (graphFile: string): Promise<unknown> => {const content = await readFile(graphFile, 'utf8');@@ -157,6 +158,7 @@ export function registerAgentCommand(program: Command) {title?: string;}) => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const config: Record<string, any> = {};if (options.title) config.title = options.title;@@ -170,8 +172,11 @@ export function registerAgentCommand(program: Command) {const result = await client.agent.createAgent.mutate(input as any);const r = result as any;- console.log(`${pc.green('β')} Created agent ${pc.bold(r.agentId || r.id)}`);+ const agentId = r.agentId || r.id;+ const url = buildUrl(`/agent/${encodeURIComponent(agentId)}`);+ console.log(`${pc.green('β')} Created agent ${pc.bold(agentId)}`);if (r.sessionId) console.log(` Session: ${r.sessionId}`);+ console.log(`${pc.bold('agent')}: ${url}`);},);diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.tsindex a257c0896fb..965757d6d41 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 { resolveAppUrlBuilder } from './task/url';// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββ@@ -136,6 +137,7 @@ export function registerDocCommand(program: Command) {}) => {const content = readBodyContent(options);const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const result = await client.document.createDocument.mutate({content,@@ -146,8 +148,13 @@ export function registerDocCommand(program: Command) {slug: options.slug,title: options.title,});+ const pathname = options.kb+ ? `/resource/library/${encodeURIComponent(options.kb)}?file=${encodeURIComponent(result.id)}`+ : `/page/${encodeURIComponent(result.id)}`;+ const url = buildUrl(pathname);console.log(`${pc.green('β')} Created document ${pc.bold(result.id)}`);+ console.log(`${pc.bold('document')}: ${url}`);},);@@ -180,6 +187,7 @@ export function registerDocCommand(program: Command) {}const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const items = documents.map((d) => ({content: d.content,@@ -193,9 +201,18 @@ export function registerDocCommand(program: Command) {const result = await client.document.createDocuments.mutate({ documents: items });const created = Array.isArray(result) ? result : [result];+ const urls = await Promise.all(+ created.map((document, index) => {+ const source = items[index];+ const pathname = source?.knowledgeBaseId+ ? `/resource/library/${encodeURIComponent(source.knowledgeBaseId)}?file=${encodeURIComponent(document.id)}`+ : `/page/${encodeURIComponent(document.id)}`;+ return buildUrl(pathname);+ }),+ );console.log(`${pc.green('β')} Created ${created.length} document(s)`);- for (const doc of created) {- console.log(` ${pc.dim('β’')} ${doc.id} β ${doc.title || 'Untitled'}`);+ for (const [index, doc] of created.entries()) {+ console.log(` ${pc.dim('β’')} ${doc.id} β ${doc.title || 'Untitled'} β ${urls[index]}`);}});diff --git a/apps/cli/src/commands/eval.ts b/apps/cli/src/commands/eval.tsindex 2546543434d..0f5f1c35e9f 100644--- a/apps/cli/src/commands/eval.ts+++ b/apps/cli/src/commands/eval.ts@@ -7,6 +7,7 @@ import pc from 'picocolors';import { getTrpcClient } from '../api/client';import { resolveLocalDeviceId } from '../utils/device';import { log } from '../utils/logger';+import { resolveAppUrlBuilder } from './task/url';const JSON_VERSION = 'v1' as const;@@ -43,6 +44,21 @@ const outputJsonSuccess = (data: unknown) => {const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null;+const getCreatedId = (value: unknown) => {+ if (!isRecord(value)) return undefined;+ if (typeof value.id === 'string') return value.id;+ return isRecord(value.data) && typeof value.data.id === 'string' ? value.data.id : undefined;+};++const withResourceUrl = (+ buildUrl: (pathname: string) => string,+ data: unknown,+ pathname: string,+) => ({+ ...(isRecord(data) ? data : { data }),+ url: buildUrl(pathname),+});+const toJsonError = (error: unknown): JsonError => {if (error instanceof Error) {const maybeData = (error as Error & { data?: { code?: string } }).data;@@ -151,6 +167,9 @@ const executeCommand = async (if (successMessage) {console.log(`${pc.green('OK')} ${successMessage}`);+ if (isRecord(data) && typeof data.url === 'string') {+ console.log(`${pc.bold('url')}: ${data.url}`);+ }return;}@@ -215,13 +234,18 @@ export function registerEvalCommand(program: Command) {options,async () => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: Record<string, any> = {identifier: options.identifier,name: options.name,};if (options.description) input.description = options.description;if (options.referenceUrl) input.referenceUrl = options.referenceUrl;- return client.agentEval.createBenchmark.mutate(input as any);+ const result = await client.agentEval.createBenchmark.mutate(input as any);+ const id = getCreatedId(result);+ return id+ ? withResourceUrl(buildUrl, result, `/eval/bench/${encodeURIComponent(id)}`)+ : result;},`Created benchmark ${pc.bold(options.name)}`,),@@ -323,6 +347,7 @@ export function registerEvalCommand(program: Command) {options,async () => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: Record<string, any> = {benchmarkIds: options.benchmarkIds.split(',')@@ -332,7 +357,11 @@ export function registerEvalCommand(program: Command) {};if (options.id) input.id = options.id;if (options.description) input.description = options.description;- return client.agentEval.createExperiment.mutate(input as any);+ const result = await client.agentEval.createExperiment.mutate(input as any);+ const id = getCreatedId(result);+ return id+ ? withResourceUrl(buildUrl, result, `/eval/experiments/${encodeURIComponent(id)}`)+ : result;},`Created experiment ${pc.bold(options.name)}`,),@@ -455,6 +484,7 @@ export function registerEvalCommand(program: Command) {options,async () => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: Record<string, any> = {benchmarkId: options.benchmarkId,identifier: options.identifier,@@ -464,7 +494,15 @@ export function registerEvalCommand(program: Command) {if (options.evalMode) input.evalMode = options.evalMode;if (options.evalConfig) input.evalConfig = options.evalConfig;if (options.metadata) input.metadata = options.metadata;- return client.agentEval.createDataset.mutate(input as any);+ const result = await client.agentEval.createDataset.mutate(input as any);+ const id = getCreatedId(result);+ return id+ ? withResourceUrl(+ buildUrl,+ result,+ `/eval/bench/${encodeURIComponent(options.benchmarkId)}/datasets/${encodeURIComponent(id)}`,+ )+ : result;},`Created dataset ${pc.bold(options.name)}`,),@@ -775,6 +813,7 @@ export function registerEvalCommand(program: Command) {}const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: Record<string, any> = { datasetId: options.datasetId };if (options.agentId) input.targetAgentId = options.agentId;if (options.name) input.name = options.name;@@ -802,10 +841,20 @@ export function registerEvalCommand(program: Command) {mode: 'exclude',};if (Object.keys(config).length > 0) input.config = config;- if (options.external) {- return client.agentEvalExternal.runCreate.mutate(input as any);- }- return client.agentEval.createRun.mutate(input as any);+ const dataset = options.external+ ? await client.agentEvalExternal.datasetGet.query({ datasetId: options.datasetId })+ : await client.agentEval.getDataset.query({ id: options.datasetId });+ const result = options.external+ ? await client.agentEvalExternal.runCreate.mutate(input as any)+ : await client.agentEval.createRun.mutate(input as any);+ const id = getCreatedId(result);+ return id+ ? withResourceUrl(+ buildUrl,+ result,+ `/eval/bench/${encodeURIComponent(dataset.benchmarkId)}/runs/${encodeURIComponent(id)}`,+ )+ : result;},'Created evaluation run',),diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 217c041391f..8e5237bd988 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -5,6 +5,7 @@ import pc from 'picocolors';import { getTrpcClient } from '../api/client';import { outputJson, printTable, truncate } from '../utils/format';import { log } from '../utils/logger';+import { resolveAppUrlBuilder } from './task/url';const nodeIcon = { decision: 'β', finding: 'β', problem: 'β', work: 'β£' } as const;const terminalOutcomes = new Set(['achieved', 'waiting_human', 'no_progress', 'failed']);@@ -82,6 +83,7 @@ export function registerGoalCommand(program: Command) {.option('--json [fields]', 'Output JSON').action(async (title: string, options) => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const result = await client.goal.create.mutate({agentId: options.agent,config:@@ -107,8 +109,10 @@ export function registerGoalCommand(program: Command) {title,work: options.work,});- if (options.json !== undefined) return outputJson(result.data, options.json);+ const url = buildUrl(`/goal/${encodeURIComponent(result.data.id)}`);+ if (options.json !== undefined) return outputJson({ ...result.data, url }, options.json);printGraph(result.data);+ console.log(`${pc.bold('goal')}: ${url}`);});goaldiff --git a/apps/cli/src/commands/kb.ts b/apps/cli/src/commands/kb.tsindex 1f82719f89b..251a477c2f9 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 { resolveAppUrlBuilder } from './task/url';function formatFileType(fileType: string): string {if (!fileType) return '';@@ -150,6 +151,7 @@ export function registerKbCommand(program: Command) {.option('--avatar <url>', 'Avatar URL').action(async (options: { avatar?: string; description?: string; name: string }) => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: { avatar?: string; description?: string; name: string } = {name: options.name,@@ -158,7 +160,9 @@ export function registerKbCommand(program: Command) {if (options.avatar) input.avatar = options.avatar;const id = await client.knowledgeBase.createKnowledgeBase.mutate(input);+ const url = buildUrl(`/resource/library/${encodeURIComponent(String(id))}`);console.log(`${pc.green('β')} Created knowledge base ${pc.bold(String(id))}`);+ console.log(`${pc.bold('knowledge base')}: ${url}`);});// ββ edit ββββββββββββββββββββββββββββββββββββββββββββββ@@ -284,6 +288,7 @@ export function registerKbCommand(program: Command) {options: { content?: string; parent?: string; title: string },) => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const result = await client.document.createDocument.mutate({content: options.content,editorData: JSON.stringify({}),@@ -292,7 +297,11 @@ export function registerKbCommand(program: Command) {parentId: options.parent,title: options.title,});+ const url = buildUrl(+ `/resource/library/${encodeURIComponent(knowledgeBaseId)}?file=${encodeURIComponent((result as any).id)}`,+ );console.log(`${pc.green('β')} Created document ${pc.bold((result as any).id)}`);+ console.log(`${pc.bold('document')}: ${url}`);},);diff --git a/apps/cli/src/commands/project.test.ts b/apps/cli/src/commands/project.test.tsindex 779b15bad47..1574459f9f9 100644--- a/apps/cli/src/commands/project.test.ts+++ b/apps/cli/src/commands/project.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { registerProjectCommand } from './project';-const { mockClient } = vi.hoisted(() => ({+const { mockClient, mockResolveWorkspaceId } = vi.hoisted(() => ({mockClient: {project: {acceptCompletion: { mutate: vi.fn() },@@ -23,10 +23,17 @@ const { mockClient } = vi.hoisted(() => ({updateStatus: { mutate: vi.fn() },},task: { create: { mutate: vi.fn() } },+ workspace: { getById: { query: vi.fn() } },},+ mockResolveWorkspaceId: vi.fn(),}));vi.mock('../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('../api/workspace', () => ({ resolveWorkspaceId: mockResolveWorkspaceId }));+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));+vi.mock('../utils/logger', () => ({+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },+}));function createProgram() {const program = new Command();program.exitOverride();@@ -37,6 +44,7 @@ function createProgram() {describe('project command', () => {beforeEach(() => {vi.clearAllMocks();+ mockResolveWorkspaceId.mockReturnValue(undefined);vi.spyOn(console, 'log').mockImplementation(() => {});});@@ -59,6 +67,9 @@ describe('project command', () => {name: 'Apollo',visibility: 'private',});+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('https://app.example.com/project/prj_1'),+ );});it('binds an agent with its project role', async () => {@@ -82,7 +93,11 @@ describe('project command', () => {});it('creates a task directly in the project', async () => {- mockClient.task.create.mutate.mockResolvedValue({ data: { identifier: 'T-1' } });+ mockResolveWorkspaceId.mockReturnValue('ws-1');+ mockClient.workspace.getById.query.mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });+ mockClient.task.create.mutate.mockResolvedValue({+ data: { identifier: 'T-1' },+ });await createProgram().parseAsync(['node','test',@@ -102,6 +117,9 @@ describe('project command', () => {parentTaskId: undefined,projectId: 'prj_1',});+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('https://app.example.com/lobehub/task/T-1'),+ );});it('requests and accepts human completion review', async () => {diff --git a/apps/cli/src/commands/project.ts b/apps/cli/src/commands/project.tsindex e03fb2cfba5..3e99ded2aec 100644--- a/apps/cli/src/commands/project.ts+++ b/apps/cli/src/commands/project.ts@@ -5,6 +5,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 { resolveAppUrlBuilder } from './task/url';const statusValues = PROJECT_STATUSES.join(', ');@@ -67,8 +68,12 @@ export function registerProjectCommand(program: Command) {slug?: string;visibility?: (typeof PROJECT_VISIBILITIES)[number];}) => {- const result = await (await getTrpcClient()).project.create.mutate(options);+ const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);+ const result = await client.project.create.mutate(options);+ const url = buildUrl(`/project/${encodeURIComponent(result.data.id)}`);console.log(`${pc.green('β')} Created project ${pc.bold(result.data.id)}`);+ console.log(`${pc.bold('project')}: ${url}`);},);@@ -183,16 +188,18 @@ export function registerProjectCommand(program: Command) {projectId: string,options: { agent?: string; instruction: string; name?: string; parent?: string },) => {- const result = await (- await getTrpcClient()- ).task.create.mutate({+ const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);+ const result = await client.task.create.mutate({assigneeAgentId: options.agent,instruction: options.instruction,name: options.name,parentTaskId: options.parent,projectId,});+ const url = buildUrl(`/task/${encodeURIComponent(result.data.identifier)}`);console.log(`${pc.green('β')} Created task ${pc.bold(result.data.identifier)}`);+ console.log(`${pc.bold('task')}: ${url}`);},);task.command('move <projectId> <taskId>').action(async (projectId: string, taskId: string) => {diff --git a/apps/cli/src/commands/task.test.ts b/apps/cli/src/commands/task.test.tsnew file mode 100644index 00000000000..bdd9a40d9d3--- /dev/null+++ b/apps/cli/src/commands/task.test.ts@@ -0,0 +1,87 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerTaskCommand } from './task';++const { mockCreateTask, mockGetTrpcClient, mockGetWorkspace, mockLogInfo, mockResolveWorkspaceId } =+ vi.hoisted(() => ({+ mockCreateTask: vi.fn(),+ mockGetTrpcClient: vi.fn(),+ mockGetWorkspace: vi.fn(),+ mockLogInfo: vi.fn(),+ mockResolveWorkspaceId: vi.fn(),+ }));++vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../api/workspace', () => ({ resolveWorkspaceId: mockResolveWorkspaceId }));+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));+vi.mock('../utils/logger', () => ({+ log: { debug: vi.fn(), error: vi.fn(), info: mockLogInfo, warn: vi.fn() },+}));++describe('task create', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ mockCreateTask.mockReset();+ mockGetWorkspace.mockReset();+ mockResolveWorkspaceId.mockReset();+ mockGetTrpcClient.mockResolvedValue({+ task: { create: { mutate: mockCreateTask } },+ workspace: { getById: { query: mockGetWorkspace } },+ });+ mockLogInfo.mockReset();+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ });++ const run = async (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerTaskCommand(program);+ await program.parseAsync(['node', 'test', 'task', 'create', ...args]);+ };++ it('includes the personal task URL in JSON output', async () => {+ mockCreateTask.mockResolvedValue({+ data: { id: 'task_1', identifier: 'T-1', name: 'Personal task' },+ message: 'Task created',+ success: true,+ });++ await run('--instruction', 'Do the thing', '--json');++ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify(+ {+ id: 'task_1',+ identifier: 'T-1',+ name: 'Personal task',+ url: 'https://app.example.com/task/T-1',+ },+ null,+ 2,+ ),+ );+ });++ it('prints a clickable workspace task URL in human output', async () => {+ mockResolveWorkspaceId.mockReturnValue('ws-1');+ mockGetWorkspace.mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });+ mockCreateTask.mockResolvedValue({+ data: { id: 'task_2', identifier: 'LOBE-321', name: 'Workspace task' },+ message: 'Task created',+ success: true,+ });++ await run('--instruction', 'Do the workspace thing');++ expect(mockLogInfo).toHaveBeenCalledWith(expect.stringContaining('LOBE-321'));+ expect(consoleSpy).toHaveBeenCalledWith(+ expect.stringContaining('https://app.example.com/lobehub/task/LOBE-321'),+ );+ });+});diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.tsindex cc236dadc8f..41ba589e370 100644--- a/apps/cli/src/commands/task/index.ts+++ b/apps/cli/src/commands/task/index.ts@@ -20,6 +20,7 @@ import { briefIcon, priorityLabel, statusBadge } from './helpers';import { registerLifecycleCommands } from './lifecycle';import { registerReviewCommands } from './review';import { registerTopicCommands } from './topic';+import { resolveAppUrlBuilder } from './url';export function registerTaskCommand(program: Command) {const task = program.command('task').description('Manage agent tasks');@@ -510,6 +511,7 @@ export function registerTaskCommand(program: Command) {priority?: string;}) => {const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);const input: Record<string, any> = {instruction: options.instruction,@@ -521,13 +523,15 @@ export function registerTaskCommand(program: Command) {if (options.prefix) input.identifierPrefix = options.prefix;const result = await client.task.create.mutate(input as any);+ const url = buildUrl(`/task/${encodeURIComponent(result.data.identifier)}`);if (options.json !== undefined) {- outputJson(result.data, options.json);+ outputJson({ ...result.data, url }, options.json);return;}log.info(`Task created: ${pc.bold(result.data.identifier)} ${result.data.name || ''}`);+ console.log(`${pc.bold('task')}: ${url}`);},);diff --git a/apps/cli/src/commands/task/url.test.ts b/apps/cli/src/commands/task/url.test.tsnew file mode 100644index 00000000000..14322cb3dd9--- /dev/null+++ b/apps/cli/src/commands/task/url.test.ts@@ -0,0 +1,43 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { buildAppUrl, resolveAppUrl } from './url';++vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));+vi.mock('../../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));++const { resolveWorkspaceId } = await import('../../api/workspace');++describe('app URLs', () => {+ afterEach(() => {+ vi.mocked(resolveWorkspaceId).mockReset();+ });++ it('builds a workspace-aware URL and encodes the workspace slug', () => {+ expect(+ buildAppUrl({+ pathname: '/goal/goal-1',+ serverUrl: 'https://app.example.com',+ workspaceSlug: 'Lobe Hub',+ }),+ ).toBe('https://app.example.com/Lobe%20Hub/goal/goal-1');+ });++ it('does not fetch workspace context in personal mode', async () => {+ vi.mocked(resolveWorkspaceId).mockReturnValue(undefined);+ const query = vi.fn();++ await expect(+ resolveAppUrl({ workspace: { getById: { query } } } as never, '/project/prj-1'),+ ).resolves.toBe('https://app.example.com/project/prj-1');+ expect(query).not.toHaveBeenCalled();+ });++ it('uses the server-resolved slug in workspace mode', async () => {+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');+ const query = vi.fn().mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });++ await expect(+ resolveAppUrl({ workspace: { getById: { query } } } as never, '/agent/agt-1'),+ ).resolves.toBe('https://app.example.com/lobehub/agent/agt-1');+ });+});diff --git a/apps/cli/src/commands/task/url.ts b/apps/cli/src/commands/task/url.tsnew file mode 100644index 00000000000..b93cd109da3--- /dev/null+++ b/apps/cli/src/commands/task/url.ts@@ -0,0 +1,39 @@+import type { TrpcClient } from '../../api/client';+import { resolveWorkspaceId } from '../../api/workspace';+import { resolveServerUrl } from '../../settings';++interface AppUrlOptions {+ pathname: string;+ serverUrl: string;+ workspaceSlug?: string;+}++export const buildAppUrl = ({ pathname, serverUrl, workspaceSlug }: AppUrlOptions) => {+ const normalizedPath = pathname.startsWith('/') ? pathname : `/${pathname}`;+ const path = workspaceSlug+ ? `/${encodeURIComponent(workspaceSlug)}${normalizedPath}`+ : normalizedPath;++ return new URL(path, `${serverUrl}/`).toString();+};++export const buildTaskUrl = ({+ identifier,+ serverUrl,+ workspaceSlug,+}: Omit<AppUrlOptions, 'pathname'> & { identifier: string }) =>+ buildAppUrl({+ pathname: `/task/${encodeURIComponent(identifier)}`,+ serverUrl,+ workspaceSlug,+ });++export const resolveAppUrlBuilder = async (client: TrpcClient) => {+ const workspace = resolveWorkspaceId() ? await client.workspace.getById.query() : null;++ return (pathname: string) =>+ buildAppUrl({ pathname, serverUrl: resolveServerUrl(), workspaceSlug: workspace?.slug });+};++export const resolveAppUrl = async (client: TrpcClient, pathname: string) =>+ (await resolveAppUrlBuilder(client))(pathname);diff --git a/apps/server/src/routers/lambda/__tests__/workspace.test.ts b/apps/server/src/routers/lambda/__tests__/workspace.test.tsnew file mode 100644index 00000000000..b77b703ff9d--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/workspace.test.ts@@ -0,0 +1,16 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { workspaceRouter } from '@/business/server/lambda-routers/workspace';++describe('workspaceRouter.getById', () => {+ it('returns null in the community build', async () => {+ const caller = workspaceRouter.createCaller({+ serverDB: {},+ userId: 'user-1',+ workspaceId: 'ignored-community-workspace',+ } as never);++ await expect(caller.getById()).resolves.toBeNull();+ });+});diff --git a/packages/business-server/src/lambda-routers/workspace.ts b/packages/business-server/src/lambda-routers/workspace.tsindex 7f0570ccf6e..a40e6324b18 100644--- a/packages/business-server/src/lambda-routers/workspace.ts+++ b/packages/business-server/src/lambda-routers/workspace.ts@@ -1,6 +1,7 @@import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { authedProcedure, router } from '@/libs/trpc/lambda';// Cloud overrides this at the same path with the real workspaceRouter backed by cloudDB.@@ -15,4 +16,5 @@ export const workspaceRouter = router({message: 'Workspace market organization is a cloud-only feature.',});}),+ getById: wsCompatProcedure.query(() => null),});diff --git a/packages/business-server/src/trpc-middlewares/workspaceAuth.test.ts b/packages/business-server/src/trpc-middlewares/workspaceAuth.test.tsnew file mode 100644index 00000000000..f17a91f1834--- /dev/null+++ b/packages/business-server/src/trpc-middlewares/workspaceAuth.test.ts@@ -0,0 +1,27 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { router } from '@/libs/trpc/lambda';++import { wsCompatProcedure } from './workspaceAuth';++const testRouter = router({+ context: wsCompatProcedure.query(({ ctx }) => ({+ workspaceId: ctx.workspaceId,+ workspaceSlug: ctx.workspaceSlug,+ })),+});++describe('community wsCompatProcedure', () => {+ it('does not synthesize a workspace slug', async () => {+ const caller = testRouter.createCaller({+ userId: 'user-1',+ workspaceId: 'unverified-workspace',+ } as never);++ await expect(caller.context()).resolves.toEqual({+ workspaceId: 'unverified-workspace',+ workspaceSlug: undefined,+ });+ });+});diff --git a/packages/business-server/src/trpc-middlewares/workspaceAuth.ts b/packages/business-server/src/trpc-middlewares/workspaceAuth.tsindex f2924c778a7..482f07f73f1 100644--- a/packages/business-server/src/trpc-middlewares/workspaceAuth.ts+++ b/packages/business-server/src/trpc-middlewares/workspaceAuth.ts@@ -5,7 +5,13 @@ import { trpc } from '@/libs/trpc/lambda/init';export type WorkspaceRole = 'admin' | 'member' | 'owner' | 'viewer';-export const cloudWorkspaceAuth = trpc.middleware(async (opts) => opts.next());+export const cloudWorkspaceAuth = trpc.middleware(async (opts) =>+ opts.next({+ ctx: {+ workspaceSlug: undefined as string | undefined,+ },+ }),+);export const lobeWorkspaceAuth = trpc.middleware(async (opts) => opts.next());@@ -29,4 +35,4 @@ export const wsMemberProcedure = authedProcedure;export const wsOwnerProcedure = authedProcedure.use(requireWorkspaceId);export const wsAdminProcedure = authedProcedure.use(requireWorkspaceId);-export const wsCompatProcedure = authedProcedure;+export const wsCompatProcedure = authedProcedure.use(cloudWorkspaceAuth);