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(task): link created task identifiers to their detail page (#16303)

Arvin Xu9af8f5087720
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index 44503909482..0273b78d6a4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -7,6 +7,13 @@ vi.mock('@/server/routers/lambda/task', () => ({
taskRouter: { createCaller: () => ({}) },
}));
+// APP_URL is a server-only env var; the unit-test env is flagged as client, so
+// reading `appEnv.APP_URL` would throw. Stub it β€” createTask embeds it as the
+// base URL for absolute task deep-links (so IM / mobile links are clickable).
+vi.mock('@/envs/app', () => ({
+ appEnv: { APP_URL: 'https://app.lobehub.com' },
+}));
+
// TaskService's transitive deps (taskReview β†’ ModelRuntime) call getLLMConfig
// at module load, which fails in unit-test env. The runtime is passed a
// taskService instance per test, so a stubbed class is all we need here.
@@ -156,6 +163,9 @@ describe('createTaskRuntime', () => {
});
expect(result.success).toBe(true);
+ // The identifier is an absolute markdown link so it stays clickable when
+ // the tool result is delivered to an IM channel / mobile.
+ expect(result.content).toContain('[T-1](https://app.lobehub.com/task/T-1)');
expect(deps.taskService.createTask).toHaveBeenCalledWith(
expect.objectContaining({
assigneeAgentId: 'agt-xyz',
@@ -164,6 +174,24 @@ describe('createTaskRuntime', () => {
);
});
+ it('embeds a workspace-scoped link when the task is in a workspace', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ // The factory supplies this; for a workspace task it prefixes `/{slug}`.
+ resolveLinkBaseUrl: async () => 'https://app.lobehub.com/acme',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService as any,
+ });
+
+ const result = await runtime.createTask({ instruction: 'Do something', name: 'Test' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('[T-1](https://app.lobehub.com/acme/task/T-1)');
+ });
+
it('leaves createdByAgentId undefined when no agentId in context', async () => {
const deps = makeDeps();
@@ -485,8 +513,10 @@ describe('createTaskRuntime', () => {
expect(result.success).toBe(true);
expect(deps.taskService.createTask).toHaveBeenCalledTimes(2);
expect(result.content).toContain('Created 2 tasks');
- expect(result.content).toContain('T-A');
- expect(result.content).toContain('T-B');
+ // Identifiers are rendered as absolute markdown links so they stay
+ // clickable when the message is delivered to IM / mobile.
+ expect(result.content).toContain('[T-A](https://app.lobehub.com/task/T-A)');
+ expect(result.content).toContain('[T-B](https://app.lobehub.com/task/T-B)');
});
it('continues past per-item failures and reports them in the summary', async () => {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index f2053c8946c..fbf1d131be3 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -1,5 +1,6 @@
import { normalizeListTasksParams, TaskIdentifier } from '@lobechat/builtin-tool-task';
import type { LobeChatDatabase } from '@lobechat/database';
+import type { TaskCreatedItem } from '@lobechat/prompts';
import {
formatDependencyAdded,
formatDependencyRemoved,
@@ -8,6 +9,7 @@ import {
formatTaskDetail,
formatTaskEdited,
formatTaskList,
+ formatTasksCreated,
priorityLabel,
} from '@lobechat/prompts';
import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';
@@ -15,7 +17,9 @@ import { eq } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
import { TaskModel } from '@/database/models/task';
+import { WorkspaceModel } from '@/database/models/workspace';
import { tasks } from '@/database/schemas';
+import { appEnv } from '@/envs/app';
import { taskRouter } from '@/server/routers/lambda/task';
import { TaskService } from '@/server/services/task';
@@ -49,6 +53,11 @@ export interface TaskRuntimeDeps {
// back to this session (LOBE-10625). All optional β€” a task can be created
// outside an agent turn (e.g. via the API).
operationId?: string;
+ // Resolves the base URL for task deep-links: app origin + optional `/{slug}`
+ // workspace prefix. Provided by the factory (which owns db / userId / the
+ // resolved workspaceId); when absent (unit tests) links fall back to the bare
+ // app origin.
+ resolveLinkBaseUrl?: () => Promise<string>;
scope?: string | null;
taskCaller: ReturnType<typeof taskRouter.createCaller>;
taskId?: string;
@@ -67,6 +76,14 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const taskService = () => deps.taskService;
const taskCaller = () => deps.taskCaller;
+ // Base URL for task deep-links embedded in tool results. These results can be
+ // pushed to IM / bot channels and mobile, so the link must be ABSOLUTE β€” and
+ // workspace-scoped tasks live under `/{slug}/task/...`, so the slug has to be
+ // in the path too or the link resolves to the wrong (personal) scope. The
+ // factory supplies the workspace-aware resolver; fall back to the bare origin.
+ const taskLinkBaseUrl = async (): Promise<string> =>
+ (await deps.resolveLinkBaseUrl?.()) ?? appEnv.APP_URL.replace(/\/$/, '');
+
const resolveAssigneeAgent = async (assigneeAgentId?: string | null) => {
if (!assigneeAgentId) return { success: true } as const;
@@ -129,6 +146,10 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
return {
content: formatTaskCreated({
+ // Absolute, workspace-scoped link: this content can be pushed to IM /
+ // bot channels and mobile, where a relative path has no app origin to
+ // resolve against and the `/{slug}` prefix would otherwise be lost.
+ baseUrl: await taskLinkBaseUrl(),
identifier: task.identifier,
instruction: args.instruction,
name: task.name,
@@ -184,36 +205,29 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
return { content: 'No tasks provided.', success: false };
}
- const lines: string[] = [];
- let succeeded = 0;
- let failed = 0;
+ const results: TaskCreatedItem[] = [];
- for (const [index, item] of items.entries()) {
+ for (const item of items) {
try {
const result = await createTaskImpl(item);
- if (result.success) {
- succeeded += 1;
- lines.push(
- `${index + 1}. ${result.identifier ?? '(unknown id)'} "${item.name}" β€” created`,
- );
- } else {
- failed += 1;
- lines.push(`${index + 1}. "${item.name}" β€” failed: ${result.content}`);
- }
+ results.push({
+ error: result.success ? undefined : result.content,
+ identifier: result.identifier,
+ name: item.name,
+ success: result.success,
+ });
} catch (error) {
- failed += 1;
const message = error instanceof Error ? error.message : 'Unknown error';
- lines.push(`${index + 1}. "${item.name}" β€” failed: ${message}`);
+ results.push({ error: message, name: item.name, success: false });
}
}
- const header =
- failed === 0
- ? `Created ${succeeded} task${succeeded === 1 ? '' : 's'}:`
- : `Created ${succeeded}/${items.length} tasks (${failed} failed):`;
+ const failed = results.filter((r) => !r.success).length;
return {
- content: [header, ...lines].join('\n'),
+ // Absolute, workspace-scoped links so the summary stays clickable when
+ // pushed to IM / mobile.
+ content: formatTasksCreated(results, await taskLinkBaseUrl()),
success: failed === 0,
};
},
@@ -687,6 +701,22 @@ export const taskRuntime: ServerRuntimeRegistration = {
const { agentId, assistantMessageId, operationId, taskId, toolCallId, topicId, scope } =
context;
+ // Workspace slug for deep-links: resolved once (memoized) from the workspace
+ // owning the created task (`workspaceId` is set by `ensureModels` below),
+ // and only when the task is actually workspace-scoped.
+ let workspaceId: string | undefined;
+ let slugPromise: Promise<string | undefined> | undefined;
+ const resolveLinkBaseUrl = async (): Promise<string> => {
+ const origin = appEnv.APP_URL.replace(/\/$/, '');
+ if (!workspaceId) return origin;
+ slugPromise ??= new WorkspaceModel(db, userId)
+ .findById(workspaceId)
+ .then((workspace) => workspace?.slug ?? undefined)
+ .catch(() => undefined);
+ const slug = await slugPromise;
+ return slug ? `${origin}/${slug}` : origin;
+ };
+
// Models are wired in lazily after the workspaceId is resolved from the
// owning task row. `createTaskRuntime` reads them through this shared
// `deps` object, so re-assigning the fields below propagates into every
@@ -695,6 +725,7 @@ export const taskRuntime: ServerRuntimeRegistration = {
agentId,
assistantMessageId,
operationId,
+ resolveLinkBaseUrl,
scope,
taskId,
toolCallId,
@@ -715,6 +746,7 @@ export const taskRuntime: ServerRuntimeRegistration = {
// up the owning task row for callers that pre-date the propagation work
// and still construct `ToolExecutionContext` without `workspaceId`.
const wsId = context.workspaceId ?? (await resolveWorkspaceId(db, taskId));
+ workspaceId = wsId;
deps.agentModel = new AgentModel(db, userId, wsId);
deps.taskModel = new TaskModel(db, userId, wsId);
deps.taskService = new TaskService(db, userId, wsId);
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index b0ad00c2085..296e534da86 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -6,6 +6,7 @@ import {
formatTaskDetail,
formatTaskEdited,
formatTaskList,
+ formatTasksCreated,
priorityLabel,
} from '@lobechat/prompts';
import type {
@@ -18,6 +19,7 @@ import type {
import { BaseExecutor } from '@lobechat/types';
import debug from 'debug';
+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { taskService } from '@/services/task';
import { getChatStoreState } from '@/store/chat';
import { getTaskStoreState } from '@/store/task';
@@ -37,6 +39,14 @@ import { TaskApiName } from '../../types';
const log = debug('lobe-task:executor');
+// In-app (SPA) deep-link base for tasks: a relative path so it resolves against
+// the current origin and stays durable. Workspace-scoped tasks live under
+// `/{slug}/task/...`, so prefix the active workspace slug when there is one.
+const taskLinkBaseUrl = (): string | undefined => {
+ const slug = getActiveWorkspaceSlug();
+ return slug ? `/${slug}` : undefined;
+};
+
// APIs whose execution mutates state that's surfaced in the renderer's task
// list or detail caches. Used by `onAfterCall` to decide what to revalidate.
const LIST_MUTATING_APIS = new Set<string>([
@@ -199,6 +209,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
return {
content: formatTaskCreated({
+ baseUrl: taskLinkBaseUrl(),
identifier: task.identifier,
instruction: params.instruction,
name: task.name,
@@ -250,9 +261,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
}
const results: CreateTasksItemResult[] = [];
- const lines: string[] = [];
- for (const [index, item] of items.entries()) {
+ for (const item of items) {
const result = await this.createTask(item, ctx);
const success = result.success === true;
const identifier =
@@ -265,23 +275,17 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
(typeof result.content === 'string' ? result.content : 'Unknown error');
results.push({ error, identifier, name: item.name, success });
-
- if (success) {
- lines.push(`${index + 1}. ${identifier ?? '(unknown id)'} "${item.name}" β€” created`);
- } else {
- lines.push(`${index + 1}. "${item.name}" β€” failed: ${error}`);
- }
}
const succeeded = results.filter((r) => r.success).length;
const failed = results.length - succeeded;
- const header =
- failed === 0
- ? `Created ${succeeded} task${succeeded === 1 ? '' : 's'}:`
- : `Created ${succeeded}/${results.length} tasks (${failed} failed):`;
+ // Relative, workspace-aware links: this content is rendered in-app (SPA),
+ // where a relative path resolves against the current origin and is more
+ // durable than baking in one. The server runtime passes an absolute baseUrl
+ // for IM / mobile.
return {
- content: [header, ...lines].join('\n'),
+ content: formatTasksCreated(results, taskLinkBaseUrl()),
state: { failed, results, succeeded },
success: failed === 0,
};
diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.ts
index 6eaf7ef87cd..84a512effbd 100644
--- a/packages/prompts/src/prompts/task/index.test.ts
+++ b/packages/prompts/src/prompts/task/index.test.ts
@@ -1,12 +1,83 @@
import { describe, expect, it } from 'vitest';
-import { buildTaskRunPrompt } from './index';
+import {
+ buildTaskRunPrompt,
+ formatTaskCreated,
+ formatTasksCreated,
+ taskDetailHref,
+ taskRef,
+} from './index';
// Fixed reference time for stable timeAgo output
const NOW = new Date('2026-03-22T12:00:00Z');
const baseTask = { id: 'task_test', status: 'running' };
+describe('task deep-links', () => {
+ it('taskDetailHref returns a relative path without baseUrl', () => {
+ expect(taskDetailHref('T-198')).toBe('/task/T-198');
+ });
+
+ it('taskDetailHref returns an absolute url with baseUrl (and strips trailing slash)', () => {
+ expect(taskDetailHref('T-198', 'https://app.lobehub.com')).toBe(
+ 'https://app.lobehub.com/task/T-198',
+ );
+ expect(taskDetailHref('T-198', 'https://app.lobehub.com/')).toBe(
+ 'https://app.lobehub.com/task/T-198',
+ );
+ });
+
+ it('taskRef renders a markdown link', () => {
+ expect(taskRef('T-199')).toBe('[T-199](/task/T-199)');
+ expect(taskRef('T-199', 'https://app.lobehub.com')).toBe(
+ '[T-199](https://app.lobehub.com/task/T-199)',
+ );
+ });
+
+ it('formatTaskCreated links identifier + parent, absolute when baseUrl is given (IM/bot)', () => {
+ const out = formatTaskCreated({
+ baseUrl: 'https://app.lobehub.com',
+ identifier: 'T-198',
+ instruction: 'do it',
+ name: 'Parent task',
+ parentLabel: 'T-100',
+ priority: 2,
+ status: 'backlog',
+ });
+ expect(out).toContain(
+ 'Task created: [T-198](https://app.lobehub.com/task/T-198) "Parent task"',
+ );
+ expect(out).toContain('Parent: [T-100](https://app.lobehub.com/task/T-100)');
+ });
+
+ it('formatTasksCreated renders a header + linked lines (relative without baseUrl)', () => {
+ const out = formatTasksCreated([
+ { identifier: 'T-1', name: 'A', success: true },
+ { identifier: 'T-2', name: 'B', success: true },
+ ]);
+ expect(out).toBe(
+ [
+ 'Created 2 tasks:',
+ '1. [T-1](/task/T-1) "A" β€” created',
+ '2. [T-2](/task/T-2) "B" β€” created',
+ ].join('\n'),
+ );
+ });
+
+ it('formatTasksCreated uses absolute links with baseUrl and reports failures', () => {
+ const out = formatTasksCreated(
+ [
+ { identifier: 'T-1', name: 'A', success: true },
+ { error: 'boom', name: 'B', success: false },
+ ],
+ 'https://app.lobehub.com',
+ );
+ expect(out).toContain('Created 1/2 tasks (1 failed):');
+ expect(out).toContain('1. [T-1](https://app.lobehub.com/task/T-1) "A" β€” created');
+ expect(out).toContain('2. "B" β€” failed: boom');
+ });
+});
+
describe('buildTaskRunPrompt', () => {
it('should build prompt with only task instruction', () => {
const result = buildTaskRunPrompt(
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 0068f7f4a33..e8e33106bfe 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -55,6 +55,25 @@ export interface TaskSummary {
status: string;
}
+/**
+ * Deep-link to a task's detail page, so the agent can present task identifiers
+ * as clickable references β€” mirroring how Linear surfaces an issue's `url`.
+ *
+ * Pass `baseUrl` (e.g. `appEnv.APP_URL`) for an ABSOLUTE link. This is required
+ * whenever the message can leave the app β€” IM/bot channels (Slack, Telegram,
+ * WeChat…), push notifications, mobile β€” where there is no app origin to
+ * resolve a relative path against. Omit it only for in-app (SPA) rendering,
+ * where a relative path resolves against the current origin and is more durable.
+ */
+export const taskDetailHref = (identifier: string, baseUrl?: string): string => {
+ const path = `/task/${identifier}`;
+ return baseUrl ? `${baseUrl.replace(/\/$/, '')}${path}` : path;
+};
+
+/** Markdown-link form of a task identifier, e.g. `[T-198](https://app.lobehub.com/task/T-198)`. */
+export const taskRef = (identifier: string, baseUrl?: string): string =>
+ `[${identifier}](${taskDetailHref(identifier, baseUrl)})`;
+
// Re-export shared types from @lobechat/types for backward compatibility
export type {
TaskDetailActivity,
@@ -73,18 +92,52 @@ export const formatTaskLine = (t: TaskSummary): string =>
* Format createTask response
*/
export const formatTaskCreated = (
- t: TaskSummary & { instruction: string; parentLabel?: string },
+ t: TaskSummary & { baseUrl?: string; instruction: string; parentLabel?: string },
): string => {
const lines = [
- `Task created: ${t.identifier} "${t.name}"`,
+ `Task created: ${taskRef(t.identifier, t.baseUrl)} "${t.name}"`,
` Status: ${statusIcon(t.status)} ${t.status}`,
` Priority: ${priorityLabel(t.priority)}`,
];
- if (t.parentLabel) lines.push(` Parent: ${t.parentLabel}`);
+ if (t.parentLabel) lines.push(` Parent: ${taskRef(t.parentLabel, t.baseUrl)}`);
lines.push(` Instruction: ${t.instruction}`);
return lines.join('\n');
};
+export interface TaskCreatedItem {
+ error?: string;
+ identifier?: string;
+ name: string;
+ success: boolean;
+}
+
+/**
+ * Format the createTasks (batch) response: a header plus one line per task,
+ * with successful identifiers rendered as links (absolute when `baseUrl` is
+ * given β€” required for IM / mobile, see {@link taskDetailHref}).
+ *
+ * Single source of truth shared by the client executor and the server runtime
+ * so the two stay identical.
+ */
+export const formatTasksCreated = (results: TaskCreatedItem[], baseUrl?: string): string => {
+ const lines = results.map((r, index) => {
+ if (r.success) {
+ const ref = r.identifier ? taskRef(r.identifier, baseUrl) : '(unknown id)';
+ return `${index + 1}. ${ref} "${r.name}" β€” created`;
+ }
+ return `${index + 1}. "${r.name}" β€” failed: ${r.error ?? 'Unknown error'}`;
+ });
+
+ const succeeded = results.filter((r) => r.success).length;
+ const failed = results.length - succeeded;
+ const header =
+ failed === 0
+ ? `Created ${succeeded} task${succeeded === 1 ? '' : 's'}:`
+ : `Created ${succeeded}/${results.length} tasks (${failed} failed):`;
+
+ return [header, ...lines].join('\n');
+};
+
export interface TaskListFilters {
assigneeAgentId?: string;
isDefaultScope?: boolean;