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.

♻️ refactor(task): use stable IDs internally and preserve identifier links (#21729)

Bryan0aee76c9c3ae
diff --git a/apps/cli/src/commands/project.test.ts b/apps/cli/src/commands/project.test.ts
index 86e2fd91034..e7f36915fdd 100644
--- a/apps/cli/src/commands/project.test.ts
+++ b/apps/cli/src/commands/project.test.ts
@@ -116,7 +116,7 @@ describe('project command', () => {
mockResolveWorkspaceId.mockReturnValue('ws-1');
mockClient.workspace.getById.query.mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });
mockClient.task.create.mutate.mockResolvedValue({
- data: { identifier: 'T-1' },
+ data: { id: 'task_1', identifier: 'T-1' },
});
await createProgram().parseAsync([
'node',
diff --git a/apps/cli/src/commands/resourceUrl.test.ts b/apps/cli/src/commands/resourceUrl.test.ts
index 2698fc43b60..e091843d0f0 100644
--- a/apps/cli/src/commands/resourceUrl.test.ts
+++ b/apps/cli/src/commands/resourceUrl.test.ts
@@ -37,7 +37,7 @@ describe('resourcePath', () => {
],
[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.task({ id: 'task_1', 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);
diff --git a/apps/cli/src/commands/resourceUrl.ts b/apps/cli/src/commands/resourceUrl.ts
index e33d412ca65..e93c5a801a9 100644
--- a/apps/cli/src/commands/resourceUrl.ts
+++ b/apps/cli/src/commands/resourceUrl.ts
@@ -53,8 +53,8 @@ export const resourcePath = {
},
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,
+ task: (task: { id?: Id; identifier?: Id; name?: Id }) =>
+ task.identifier || task.id ? taskPath((task.identifier ?? task.id)!, 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)}`;
@@ -88,7 +88,7 @@ export const searchResultPath = (item: Record<string, any>): string | undefined
return resourcePath.knowledgeBase(item.id);
}
case 'task': {
- return resourcePath.task({ identifier: item.identifier, name: item.title });
+ return resourcePath.task({ id: item.id, identifier: item.identifier, name: item.title });
}
case 'mcp':
case 'plugin': {
diff --git a/apps/cli/src/commands/task/checkpoint.ts b/apps/cli/src/commands/task/checkpoint.ts
index 8d579798a4f..36b94571afe 100644
--- a/apps/cli/src/commands/task/checkpoint.ts
+++ b/apps/cli/src/commands/task/checkpoint.ts
@@ -23,10 +23,14 @@ export function registerCheckpointCommands(task: Command) {
console.log(` topic.after: ${c.topic.after ?? false}`);
}
if (c.tasks?.beforeIds?.length > 0) {
- console.log(` tasks.beforeIds: ${c.tasks.beforeIds.join(', ')}`);
+ console.log(
+ ` tasks.beforeIds: ${(c.beforeTasks?.map((task: { identifier: string }) => task.identifier) ?? c.tasks.beforeIds).join(', ')}`,
+ );
}
if (c.tasks?.afterIds?.length > 0) {
- console.log(` tasks.afterIds: ${c.tasks.afterIds.join(', ')}`);
+ console.log(
+ ` tasks.afterIds: ${(c.afterTasks?.map((task: { identifier: string }) => task.identifier) ?? c.tasks.afterIds).join(', ')}`,
+ );
}
if (
!c.topic &&
@@ -75,6 +79,8 @@ export function registerCheckpointCommands(task: Command) {
}
if (options.before !== undefined) {
checkpoint.tasks = { ...checkpoint.tasks };
+ // Explicit input is a new selection, rather than a config round trip.
+ delete checkpoint.tasks.beforeTasks;
checkpoint.tasks.beforeIds = options.before
.split(',')
.map((s: string) => s.trim())
@@ -82,6 +88,7 @@ export function registerCheckpointCommands(task: Command) {
}
if (options.after !== undefined) {
checkpoint.tasks = { ...checkpoint.tasks };
+ delete checkpoint.tasks.afterTasks;
checkpoint.tasks.afterIds = options.after
.split(',')
.map((s: string) => s.trim())
diff --git a/apps/cli/src/commands/task/dep.ts b/apps/cli/src/commands/task/dep.ts
index 0c71698b57b..597a2cf1a35 100644
--- a/apps/cli/src/commands/task/dep.ts
+++ b/apps/cli/src/commands/task/dep.ts
@@ -50,7 +50,12 @@ export function registerDepCommands(task: Command) {
return;
}
- const rows = result.data.map((d: any) => [d.type, d.dependsOnId, timeAgo(d.createdAt)]);
- printTable(rows, ['TYPE', 'DEPENDS ON', 'CREATED']);
+ const rows = result.data.map((d: any) => [
+ d.type,
+ d.dependsOnIdentifier ?? d.dependsOnId,
+ d.dependsOnId,
+ timeAgo(d.createdAt),
+ ]);
+ printTable(rows, ['TYPE', 'DEPENDS ON', 'ID', 'CREATED']);
});
}
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index 8ca060d3262..e9843a2855e 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -288,6 +288,7 @@ export function registerTaskCommand(program: Command) {
// ── Header ──
console.log(`\n${pc.bold(t.identifier)} ${t.name || ''}`);
+ console.log(`ID: ${t.id}`);
console.log(`${pc.dim('URL:')} ${url}`);
console.log(
`${pc.dim('Status:')} ${statusBadge(t.status)} ${pc.dim('Priority:')} ${priorityLabel(t.priority)}`,
@@ -575,6 +576,7 @@ export function registerTaskCommand(program: Command) {
}
log.info(`Task created: ${pc.bold(result.data.identifier)} ${result.data.name || ''}`);
+ console.log(`ID: ${result.data.id}`);
console.log(`${pc.bold('task')}: ${url}`);
},
);
@@ -643,7 +645,19 @@ export function registerTaskCommand(program: Command) {
}
if (!hasFieldEdits) {
const result = await client.task.updateStatus.mutate({ id, status: options.status });
- log.info(`${pc.bold(result.data.identifier)} → ${options.status}`);
+ if (options.json !== undefined) {
+ outputJson(
+ withUrl(
+ result.data,
+ await resolveUrlBuilder(client),
+ resourcePath.task(result.data),
+ ),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
+ } else {
+ log.info(`${pc.bold(result.data.identifier)} → ${options.status}`);
+ console.log(`ID: ${result.data.id}`);
+ }
return;
}
@@ -662,6 +676,7 @@ export function registerTaskCommand(program: Command) {
const statusSuffix = options.status ? ` → ${options.status}` : '';
log.info(`Task updated: ${pc.bold(result.data.identifier)}${statusSuffix}`);
+ console.log(`ID: ${result.data.id}`);
},
);
@@ -678,8 +693,8 @@ export function registerTaskCommand(program: Command) {
}
const client = await getTrpcClient();
- await client.task.delete.mutate({ id });
- log.info(`Task ${pc.bold(id)} deleted.`);
+ const result = await client.task.delete.mutate({ id });
+ log.info(`Task ${pc.bold(result.data.identifier)} (id: ${result.data.id}) deleted.`);
});
// ── clear ──────────────────────────────────────────────
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.ts
index 65de75b3148..aa2583f615e 100644
--- a/apps/cli/src/commands/task/lifecycle.ts
+++ b/apps/cli/src/commands/task/lifecycle.ts
@@ -63,11 +63,13 @@ export function registerLifecycleCommands(task: Command) {
if (taskDetail.data.status === 'running') {
log.info(`Task ${pc.bold(taskDetail.data.identifier)} is already running.`);
+ console.log(`ID: ${taskDetail.data.id}`);
return;
}
const statusResult = await client.task.updateStatus.mutate({ id, status: 'running' });
log.info(`Task ${pc.bold(statusResult.data.identifier)} started.`);
+ console.log(`ID: ${statusResult.data.id}`);
// Auto-run unless --no-run
if (options.run === false) return;
@@ -207,7 +209,7 @@ export function registerLifecycleCommands(task: Command) {
if (!shouldFollow && options.json) {
const toUrl = await resolveUrlBuilder(client);
outputJson({
- taskUrl: toUrl(resourcePath.task({ identifier: result.taskIdentifier })),
+ taskUrl: toUrl(resourcePath.task({ id: result.taskId })),
autoStarted: result.autoStarted,
operationId,
status: result.status,
@@ -219,6 +221,7 @@ export function registerLifecycleCommands(task: Command) {
}
if (i === 0) {
log.info(`Task ${pc.bold(result.taskIdentifier)} running`);
+ console.log(`ID: ${result.taskId}`);
}
log.info(`Operation: ${pc.dim(operationId)} · Topic: ${pc.dim(result.topicId || 'n/a')}`);
@@ -377,8 +380,8 @@ export function registerLifecycleCommands(task: Command) {
.description('Manually send heartbeat for a running task')
.action(async (id: string) => {
const client = await getTrpcClient();
- await client.task.heartbeat.mutate({ id });
- log.info(`Heartbeat sent for ${pc.bold(id)}.`);
+ const result = await client.task.heartbeat.mutate({ id });
+ log.info(`Heartbeat sent for ${pc.bold(result.data.identifier)} (id: ${result.data.id}).`);
});
// ── watchdog ──────────────────────────────────────────────
diff --git a/apps/cli/src/commands/task/refs.test.ts b/apps/cli/src/commands/task/refs.test.ts
new file mode 100644
index 00000000000..426f4a8c44c
--- /dev/null
+++ b/apps/cli/src/commands/task/refs.test.ts
@@ -0,0 +1,119 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerTaskCommand } from '../task';
+import { registerCheckpointCommands } from './checkpoint';
+import { registerDepCommands } from './dep';
+import { registerLifecycleCommands } from './lifecycle';
+
+const { client, info } = vi.hoisted(() => ({
+ info: vi.fn(),
+ client: {
+ task: {
+ create: { mutate: vi.fn() },
+ delete: { mutate: vi.fn() },
+ heartbeat: { mutate: vi.fn() },
+ getDependencies: { query: vi.fn() },
+ getCheckpoint: { query: vi.fn() },
+ updateCheckpoint: { mutate: vi.fn() },
+ },
+ },
+}));
+vi.mock('../../api/client', () => ({ getTrpcClient: async () => client }));
+vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: () => undefined }));
+vi.mock('../../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));
+vi.mock('../../utils/logger', () => ({
+ log: { info, warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+const run = async (register: (command: Command) => void, ...args: string[]) => {
+ const root = new Command();
+ root.exitOverride();
+ register(root.command('task'));
+ await root.parseAsync(['node', 'test', 'task', ...args]);
+};
+let output: ReturnType<typeof vi.spyOn>;
+beforeEach(() => {
+ vi.clearAllMocks();
+ output = vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+afterEach(() => vi.restoreAllMocks());
+const printed = () => output.mock.calls.map((call) => call.join(' ')).join('\n');
+
+describe('task reference output', () => {
+ it('shows identifier and stable id for dependencies', async () => {
+ client.task.getDependencies.query.mockResolvedValue({
+ data: [
+ {
+ type: 'blocks',
+ dependsOnId: 'task_2',
+ dependsOnIdentifier: 'T-2',
+ createdAt: new Date(),
+ },
+ ],
+ });
+ await run(registerDepCommands, 'dep', 'list', 'T-1');
+ expect(printed()).toContain('T-2');
+ expect(printed()).toContain('task_2');
+ });
+ it('shows checkpoint labels while preserving the legacy field format', async () => {
+ client.task.getCheckpoint.query.mockResolvedValue({
+ data: {
+ tasks: { beforeIds: ['T-2'] },
+ beforeTasks: [{ id: 'task_2', identifier: 'T-2' }],
+ },
+ });
+ await run(registerCheckpointCommands, 'checkpoint', 'view', 'task_1');
+ expect(printed()).toContain('tasks.beforeIds: T-2');
+ });
+ it('forwards checkpoint references without converting user input to ids', async () => {
+ const beforeTasks = [{ id: 'task_1', identifier: 'T-1' }];
+ client.task.getCheckpoint.query.mockResolvedValue({
+ data: { tasks: { beforeIds: ['T-1'], beforeTasks } },
+ });
+ await run(registerCheckpointCommands, 'checkpoint', 'set', 't-1', '--before', 't-2,task_3');
+ expect(client.task.updateCheckpoint.mutate).toHaveBeenCalledWith({
+ id: 't-1',
+ checkpoint: { tasks: { beforeIds: ['t-2', 'task_3'] } },
+ });
+ });
+ it('preserves existing pairs when editing unrelated checkpoint options', async () => {
+ const tasks = { beforeIds: ['T-1'], beforeTasks: [{ id: 'task_1', identifier: 'T-1' }] };
+ client.task.getCheckpoint.query.mockResolvedValue({ data: { tasks } });
+ await run(registerCheckpointCommands, 'checkpoint', 'set', 'T-9', '--topic-after', 'true');
+ expect(client.task.updateCheckpoint.mutate).toHaveBeenCalledWith({
+ id: 'T-9',
+ checkpoint: { tasks, topic: { after: true } },
+ });
+ });
+ it('uses returned identity for heartbeat acknowledgements', async () => {
+ client.task.heartbeat.mutate.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ await run(registerLifecycleCommands, 'heartbeat', 't-1');
+ expect(info).toHaveBeenCalledWith('Heartbeat sent for T-1 (id: task_1).');
+ });
+ it('uses returned identity for delete acknowledgements', async () => {
+ client.task.delete.mutate.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ const root = new Command();
+ registerTaskCommand(root);
+ await root.parseAsync(['node', 'test', 'task', 'delete', 't-1', '--yes']);
+ expect(info).toHaveBeenCalledWith('Task T-1 (id: task_1) deleted.');
+ });
+ it('prints a stable id and a public identifier link after create', async () => {
+ client.task.create.mutate.mockResolvedValue({
+ data: { id: 'task_1', identifier: 'T-1', name: 'Ship' },
+ });
+ const root = new Command();
+ registerTaskCommand(root);
+ await root.parseAsync([
+ 'node',
+ 'test',
+ 'task',
+ 'create',
+ '--instruction',
+ 'Ship it',
+ '--name',
+ 'Ship',
+ ]);
+ expect(printed()).toContain('ID: task_1');
+ expect(printed()).toContain('/task/T-1/ship');
+ });
+});
diff --git a/apps/cli/src/commands/task/url.ts b/apps/cli/src/commands/task/url.ts
index 6205ed0e8a8..f27161abb9e 100644
--- a/apps/cli/src/commands/task/url.ts
+++ b/apps/cli/src/commands/task/url.ts
@@ -23,19 +23,20 @@ export const buildAppUrl = ({ pathname, serverUrl, workspaceSlug }: AppUrlOption
* `name` only adds the readable slug tail (`/task/T-501/ship-the-thing`); the
* identifier alone still resolves the task, so omitting it stays valid.
*/
-export const taskPath = (identifier: string, name?: string | null) => {
+export const taskPath = (taskId: string, name?: string | null) => {
const slug = taskTitleSlug(name);
- return `/task/${encodeURIComponent(identifier)}${slug ? `/${slug}` : ''}`;
+ return `/task/${encodeURIComponent(taskId)}${slug ? `/${slug}` : ''}`;
};
export const buildTaskUrl = ({
+ id,
identifier,
name,
serverUrl,
workspaceSlug,
-}: Omit<AppUrlOptions, 'pathname'> & { identifier: string; name?: string | null }) =>
- buildAppUrl({ pathname: taskPath(identifier, name), serverUrl, workspaceSlug });
+}: Omit<AppUrlOptions, 'pathname'> & { id: string; identifier?: string; name?: string | null }) =>
+ buildAppUrl({ pathname: taskPath(identifier ?? id, name), serverUrl, workspaceSlug });
export const resolveAppUrlBuilder = async (client: TrpcClient) => {
const workspace = resolveWorkspaceId() ? await client.workspace.getById.query() : null;
diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts
index d4faf9c5090..91772289f24 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts
@@ -63,6 +63,14 @@ describe('onTopicComplete webhook', () => {
expect(json).toHaveBeenCalledWith({ success: true });
});
+ it('accepts a stable-id-only payload from a newer queue writer', async () => {
+ const { taskIdentifier: _legacy, ...payload } = failedRunPayload;
+ const { context, json } = makeContext(payload);
+ await onTopicComplete(context);
+ expect(json).toHaveBeenCalledWith({ success: true });
+ expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);
+ });
+
it('acks a delayed delivery for a run the sweep already settled without re-applying it', async () => {
isRunAlreadySettled.mockResolvedValue(true);
const { context, json } = makeContext(failedRunPayload);
diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts
index 90a9e877763..a3b708b118b 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts
@@ -24,7 +24,7 @@ export interface OnTopicCompletePayload {
// Static body field set by TaskRunnerService — what triggered the run.
runTrigger?: TaskRunTrigger;
taskId: string;
- taskIdentifier: string;
+ taskIdentifier?: string;
topicId?: string;
userId: string;
}
@@ -45,7 +45,7 @@ export async function onTopicComplete(c: Context) {
userId,
} = body;
- if (!taskId || !userId || !taskIdentifier || !operationId) {
+ if (!taskId || !userId || !operationId) {
return c.json({ error: 'Missing required fields' }, 400);
}
@@ -61,7 +61,7 @@ export async function onTopicComplete(c: Context) {
// System-level callback: derive workspace from the task row so the
// lifecycle service writes briefs / status into the correct workspace.
const [taskRow] = await db
- .select({ workspaceId: tasks.workspaceId })
+ .select({ identifier: tasks.identifier, workspaceId: tasks.workspaceId })
.from(tasks)
.where(and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId)))
.limit(1);
@@ -93,7 +93,7 @@ export async function onTopicComplete(c: Context) {
reason: reason || 'done',
runTrigger,
taskId,
- taskIdentifier,
+ taskIdentifier: taskRow?.identifier ?? taskIdentifier ?? taskId,
topicId,
});
diff --git a/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts b/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts
index 10e60790248..d6b59bfa406 100644
--- a/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as AgentDocumentModels from '@/database/models/agentDocuments';
+import { TaskModel } from '@/database/models/task';
import { createCallerFactory } from '@/libs/trpc/lambda';
import { createContextInner } from '@/libs/trpc/lambda/context';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
@@ -83,8 +84,13 @@ describe('agentDocumentRouter tool outcomes', () => {
let serviceImpl: MockAgentDocumentsService;
+ afterEach(() => vi.restoreAllMocks());
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(TaskModel.prototype, 'resolve').mockResolvedValue({
+ id: 'task-1',
+ identifier: 'T-1',
+ } as never);
agentDocumentMocks.deleteDocumentWork.mockResolvedValue(undefined);
agentDocumentMocks.getServerDB.mockResolvedValue({ kind: 'server-db' });
agentDocumentMocks.findTopicById.mockResolvedValue({ title: 'Topic fallback' });
@@ -113,7 +119,7 @@ describe('agentDocumentRouter tool outcomes', () => {
toolContext: {
messageId: 'message-1',
operationId: 'operation-1',
- taskId: 'task-1',
+ taskId: 'T-1',
threadId: 'thread-1',
toolCallId: 'tool-call-1',
toolMessageId: 'tool-message-1',
@@ -144,6 +150,21 @@ describe('agentDocumentRouter tool outcomes', () => {
expect(agentDocumentMocks.registerDocument).not.toHaveBeenCalled();
});
+ it('rejects an invisible task context before creating a document', async () => {
+ vi.mocked(TaskModel.prototype.resolve).mockResolvedValue(null);
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+ await expect(
+ caller.createDocument({
+ agentId: 'agent-1',
+ content: 'body',
+ title: 'Title',
+ trigger: 'tool',
+ toolContext: { messageId: 'msg', taskId: 'T-1', toolCallId: 'call' },
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(serviceImpl.createDocument).not.toHaveBeenCalled();
+ });
+
it('does not emit outcome for normal createDocument', async () => {
const caller = createCaller(await createContextInner({ userId: 'user-1' }));
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.checkpointCompatibility.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.checkpointCompatibility.integration.test.ts
new file mode 100644
index 00000000000..95540397e01
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.checkpointCompatibility.integration.test.ts
@@ -0,0 +1,194 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { tasks } from '@/database/schemas/task';
+
+import { taskRouter } from '../../task';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => testDB }));
+let userId: string;
+let model: TaskModel;
+let caller: ReturnType<typeof taskRouter.createCaller>;
+beforeEach(async () => {
+ testDB = await getTestDB();
+ userId = await createTestUser(testDB);
+ model = new TaskModel(testDB, userId);
+ caller = taskRouter.createCaller(createTestContext(userId));
+});
+afterEach(async () => {
+ await cleanupTestUser(testDB, userId);
+});
+
+const fixture = async () => {
+ const parent = await model.create({ instruction: 'parent' });
+ const a = await model.create({ instruction: 'a', parentTaskId: parent.id });
+ const b = await model.create({ instruction: 'b', parentTaskId: parent.id });
+ return { parent, a, b };
+};
+
+describe('checkpoint mixed-version compatibility', () => {
+ it.each(['updateCheckpoint', 'update', 'updateConfig', 'configPatch'] as const)(
+ 'preserves unchanged legacy selections after a child is deleted through %s',
+ async (entry) => {
+ const { parent, a } = await fixture();
+ const tasks = { beforeIds: [a.identifier], afterIds: [a.identifier] };
+ await model.updateCheckpointConfig(parent.id, { tasks });
+ await model.delete(a.id);
+ const checkpoint = { tasks, topic: { before: true } };
+ if (entry === 'updateCheckpoint') {
+ await caller.updateCheckpoint({ id: parent.id, checkpoint });
+ } else if (entry === 'updateConfig') {
+ await caller.updateConfig({ id: parent.id, config: { checkpoint } });
+ } else {
+ await caller.update({
+ id: parent.id,
+ ...(entry === 'configPatch'
+ ? { configPatch: { checkpoint } }
+ : { config: { checkpoint } }),
+ });
+ }
+ expect(model.getCheckpointConfig((await model.findById(parent.id))!)).toEqual(checkpoint);
+ await expect(
+ caller.updateCheckpoint({
+ id: parent.id,
+ checkpoint: { tasks: { beforeIds: ['MISSING-NEW'] } },
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ },
+ );
+
+ it('dual-writes canonical labels and stable pairs, so an old reader still pauses', async () => {
+ const { parent, a } = await fixture();
+ await caller.updateCheckpoint({
+ id: parent.id,
+ checkpoint: {
+ tasks: {
+ beforeIds: [a.id, a.identifier.toLowerCase()],
+ afterIds: [a.identifier.toLowerCase(), a.id],
+ },
+ },
+ });
+ const stored = (await model.findById(parent.id))!;
+ const checkpoint = model.getCheckpointConfig(stored);
+ expect(checkpoint.tasks).toEqual({
+ beforeIds: [a.identifier],
+ beforeTasks: [{ id: a.id, identifier: a.identifier }],
+ afterIds: [a.identifier],
+ afterTasks: [{ id: a.id, identifier: a.identifier }],
+ });
+ // The exact canary read rule, without the new fields.
+ expect(checkpoint.tasks?.beforeIds?.includes(a.identifier)).toBe(true);
+ expect(checkpoint.tasks?.afterIds?.includes(a.identifier)).toBe(true);
+ expect(model.shouldPauseBeforeStart(stored, a)).toBe(true);
+ expect(model.shouldPauseAfterComplete(stored, a)).toBe(true);
+ });
+
+ it('honors old-writer array replacement even while stale pairs survive deep merge', async () => {
+ const { parent, a, b } = await fixture();
+ await caller.updateCheckpoint({
+ id: parent.id,
+ checkpoint: { tasks: { beforeIds: [a.id], afterIds: [a.id] } },
+ });
+ await model.updateTaskConfig(parent.id, {
+ checkpoint: { tasks: { beforeIds: [b.identifier], afterIds: [] } },
+ });
+ const stored = (await model.findById(parent.id))!;
+ expect(model.getCheckpointConfig(stored).tasks).toMatchObject({
+ beforeTasks: [{ id: a.id, identifier: a.identifier }],
+ afterTasks: [{ id: a.id, identifier: a.identifier }],
+ });
+ expect(model.shouldPauseBeforeStart(stored, a)).toBe(false);
+ expect(model.shouldPauseBeforeStart(stored, b)).toBe(true);
+ expect(model.shouldPauseAfterComplete(stored, a)).toBe(false);
+ });
+
+ it('preserves consistent pairs across rename, alias reuse and a whole-config round trip', async () => {
+ const { parent, a, b } = await fixture();
+ const checkpoint = {
+ tasks: {
+ beforeIds: [a.identifier],
+ beforeTasks: [{ id: a.id, identifier: a.identifier }],
+ afterIds: [a.identifier],
+ afterTasks: [{ id: a.id, identifier: a.identifier }],
+ },
+ };
+ await model.updateTaskConfig(parent.id, { checkpoint });
+ await testDB.update(tasks).set({ identifier: 'REN-1' }).where(eq(tasks.id, a.id));
+ await testDB.update(tasks).set({ identifier: a.identifier }).where(eq(tasks.id, b.id));
+ await caller.updateCheckpoint({ id: parent.id, checkpoint });
+ await caller.updateConfig({ id: parent.id, config: { checkpoint } });
+ await caller.update({ id: parent.id, config: { checkpoint } });
+ const stored = (await model.findById(parent.id))!;
+ expect(model.getCheckpointConfig(stored)).toEqual(checkpoint);
+ expect(model.shouldPauseBeforeStart(stored, { ...a, identifier: 'REN-1' })).toBe(true);
+ expect(model.shouldPauseBeforeStart(stored, { ...b, identifier: a.identifier })).toBe(false);
+ expect(model.shouldPauseAfterComplete(stored, { ...a, identifier: 'REN-1' })).toBe(true);
+ const result = (await caller.getCheckpoint({ id: parent.id })).data;
+ expect(result.tasks).toEqual(checkpoint.tasks);
+ expect(result.beforeTasks).toEqual([{ id: a.id, identifier: 'REN-1' }]);
+ });
+
+ it('keeps exact legacy matching, including inactive lowercase and raw id values', async () => {
+ const { parent, a } = await fixture();
+ await model.updateCheckpointConfig(parent.id, {
+ tasks: { beforeIds: [a.identifier], afterIds: [a.identifier] },
+ });
+ const stored = (await model.findById(parent.id))!;
+ expect(model.shouldPauseBeforeStart(stored, a)).toBe(true);
+ expect(model.shouldPauseAfterComplete(stored, a)).toBe(true);
+ await model.updateCheckpointConfig(parent.id, {
+ tasks: { beforeIds: [a.identifier.toLowerCase()], afterIds: [a.id] },
+ });
+ const inactive = (await model.findById(parent.id))!;
+ expect(model.shouldPauseBeforeStart(inactive, a)).toBe(false);
+ expect(model.shouldPauseAfterComplete(inactive, a)).toBe(false);
+ });
+
+ it.each(['create', 'update', 'updateConfig', 'configPatch'] as const)(
+ 'dual-writes free config through %s',
+ async (entry) => {
+ const { parent, a } = await fixture();
+ const config = { checkpoint: { tasks: { beforeIds: [a.id, a.identifier.toLowerCase()] } } };
+ const result =
+ entry === 'create'
+ ? await caller.create({ instruction: 'new parent', config })
+ : entry === 'updateConfig'
+ ? await caller.updateConfig({ id: parent.id, config })
+ : await caller.update({
+ id: parent.id,
+ ...(entry === 'configPatch' ? { configPatch: config } : { config }),
+ });
+ const stored = (await model.findById(result.data!.id))!;
+ expect(model.getCheckpointConfig(stored).tasks).toEqual({
+ beforeIds: [a.identifier],
+ beforeTasks: [{ id: a.id, identifier: a.identifier }],
+ });
+ },
+ );
+
+ it('reports every missing ref as NOT_FOUND before changing config', async () => {
+ const { parent } = await fixture();
+ await expect(
+ caller.updateCheckpoint({
+ id: parent.id,
+ checkpoint: { tasks: { beforeIds: ['MISSING-1'], afterIds: ['task_missing'] } },
+ }),
+ ).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ message: expect.stringContaining('MISSING-1, task_missing'),
+ });
+ await expect(
+ caller.updateCheckpoint({
+ id: parent.id,
+ checkpoint: { tasks: { afterIds: ['MISSING-2'] } },
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: expect.stringContaining('MISSING-2') });
+ expect(model.getCheckpointConfig((await model.findById(parent.id))!)).toEqual({});
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.refs.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.refs.integration.test.ts
new file mode 100644
index 00000000000..b3fc658505a
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.refs.integration.test.ts
@@ -0,0 +1,103 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AcceptanceModel } from '@/database/models/acceptance';
+import { TaskModel } from '@/database/models/task';
+
+import { acceptanceRouter } from '../../acceptance';
+import { briefRouter } from '../../brief';
+import { taskRouter } from '../../task';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => testDB }));
+
+let userId: string;
+let model: TaskModel;
+let caller: ReturnType<typeof taskRouter.createCaller>;
+let briefs: ReturnType<typeof briefRouter.createCaller>;
+
+beforeEach(async () => {
+ testDB = await getTestDB();
+ userId = await createTestUser(testDB);
+ model = new TaskModel(testDB, userId);
+ caller = taskRouter.createCaller(createTestContext(userId));
+ briefs = briefRouter.createCaller(createTestContext(userId));
+});
+afterEach(async () => {
+ await cleanupTestUser(testDB, userId);
+});
+
+describe('task ref boundaries', () => {
+ it('lists children using parentTaskId as an identifier, including grouped lists', async () => {
+ const parent = await model.create({ instruction: 'parent' });
+ const child = await model.create({ instruction: 'child', parentTaskId: parent.id });
+ expect((await caller.list({ parentTaskId: parent.identifier })).data.map((t) => t.id)).toEqual([
+ child.id,
+ ]);
+ const groups = await caller.groupList({ parentTaskId: parent.identifier, groupBy: 'priority' });
+ expect(JSON.stringify(groups.data)).toContain(child.id);
+ });
+
+ it('resolves a brief task ref before reading and writing its FK', async () => {
+ const task = await model.create({ instruction: 'task' });
+ const brief = await briefs.create({
+ taskId: task.identifier,
+ title: 'title',
+ summary: 'summary',
+ type: 'insight',
+ });
+ expect(brief.data.taskId).toBe(task.id);
+ expect(
+ (await briefs.findByTaskId({ taskId: task.identifier })).data.map((b) => b.id),
+ ).toContain(brief.data.id);
+ });
+
+ it('returns NOT_FOUND for an unknown brief task instead of an FK error', async () => {
+ await expect(
+ briefs.create({ taskId: 'UNKNOWN-1', title: 'title', summary: 'summary', type: 'insight' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('reorders mixed id and identifier refs and rejects duplicate aliases', async () => {
+ const parent = await model.create({ instruction: 'parent' });
+ const a = await model.create({ instruction: 'a', parentTaskId: parent.id });
+ const b = await model.create({ instruction: 'b', parentTaskId: parent.id });
+ const result = await caller.reorderSubtasks({ id: parent.id, order: [b.id, a.identifier] });
+ expect(result.data.map((t) => t.id)).toEqual([b.id, a.id]);
+ await expect(
+ caller.reorderSubtasks({ id: parent.id, order: [a.id, a.identifier] }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('maps acceptance statuses back to requested refs and includes historical identifier subjects', async () => {
+ const task = await model.create({ instruction: 'task' });
+ const acceptances = new AcceptanceModel(testDB, userId);
+ await acceptances.ensureForSubject('task', task.identifier);
+ const caller = acceptanceRouter.createCaller(createTestContext(userId));
+ const result = await caller.listStatusesBySubjects({
+ subjectType: 'task',
+ subjectIds: [task.id, task.identifier.toLowerCase()],
+ });
+ expect(result).toEqual([
+ { status: 'pending', subjectId: task.id },
+ { status: 'pending', subjectId: task.identifier.toLowerCase() },
+ ]);
+ });
+
+ it('dual-writes checkpoint identifiers and stable pairs, collapsing aliases', async () => {
+ const parent = await model.create({ instruction: 'parent' });
+ const child = await model.create({ instruction: 'child', parentTaskId: parent.id });
+ await caller.updateCheckpoint({
+ id: parent.id,
+ checkpoint: { tasks: { beforeIds: [child.identifier, child.id] } },
+ });
+ const stored = await model.findById(parent.id);
+ expect(model.getCheckpointConfig(stored!).tasks).toEqual({
+ beforeIds: [child.identifier],
+ beforeTasks: [{ id: child.id, identifier: child.identifier }],
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
index 9907f8f91fa..efe21796250 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
@@ -24,8 +24,8 @@ export const listSchema = z.object({
offset: z.number().min(0).default(0),
// Which timestamp orders the page, newest first. Defaults to creation time.
orderBy: z.enum(['createdAt', 'updatedAt']).optional(),
- parentIdentifier: z.string().optional(),
- parentTaskId: z.string().nullish(),
+ parentIdentifier: z.string().trim().min(1).optional(),
+ parentTaskId: z.string().trim().min(1).nullish(),
priorities: z.array(z.number().min(0).max(4)).max(5).optional(),
projectId: z.string().optional(),
// "My tasks" narrowing: 'assigned' → tasks whose member assignee is the
@@ -59,7 +59,8 @@ export const groupListSchema = z
.max(10)
.optional(),
includeArchived: z.boolean().optional(),
- parentTaskId: z.string().nullish(),
+ parentIdentifier: z.string().trim().min(1).optional(),
+ parentTaskId: z.string().trim().min(1).nullish(),
projectId: z.string().optional(),
// Same "My tasks" narrowing as `listSchema.scope`, so the board renders the
// exact set its list view does. Always resolved against `ctx.userId`.
diff --git a/apps/server/src/routers/lambda/acceptance/bundle.ts b/apps/server/src/routers/lambda/acceptance/bundle.ts
index 46eb2cea15a..e3dc08cb14a 100644
--- a/apps/server/src/routers/lambda/acceptance/bundle.ts
+++ b/apps/server/src/routers/lambda/acceptance/bundle.ts
@@ -305,6 +305,7 @@ export const bundleRouter = router({
...(task
? {
taskId: task.id,
+ taskIdentifier: task.identifier,
deliveryAcceptanceId: storedRepair.deliveryAcceptanceId,
}
: {}),
diff --git a/apps/server/src/routers/lambda/acceptance/subject.ts b/apps/server/src/routers/lambda/acceptance/subject.ts
index 04ba4644dfe..16f76ee35a2 100644
--- a/apps/server/src/routers/lambda/acceptance/subject.ts
+++ b/apps/server/src/routers/lambda/acceptance/subject.ts
@@ -2,7 +2,9 @@ import { creatableAcceptanceSubjectTypes } from '@lobechat/const/verify';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { TaskModel } from '@/database/models/task';
import { router } from '@/libs/trpc/lambda';
+import { resolveTasksOrThrow } from '@/server/services/task/utils';
import { acceptanceResponse } from '@/server/services/verify/acceptanceResponse';
import { acceptanceProcedure, acceptanceWriteProcedure } from './procedures';
@@ -170,10 +172,23 @@ export const subjectRouter = router({
subjectType: subjectTypeSchema,
}),
)
- .query(async ({ ctx, input }) =>
- ctx.acceptanceService.acceptanceModel.listStatusesBySubjects(
- input.subjectType,
- input.subjectIds,
- ),
- ),
+ .query(async ({ ctx, input }) => {
+ const model = ctx.acceptanceService.acceptanceModel;
+ if (input.subjectType !== 'task')
+ return model.listStatusesBySubjects(input.subjectType, input.subjectIds);
+ const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ const resolved = await resolveTasksOrThrow(taskModel, input.subjectIds, {
+ duplicates: 'collapse',
+ });
+ const rows = await model.listStatusesBySubjects(
+ 'task',
+ resolved.tasks.flatMap((task) => [task.id, task.identifier]),
+ );
+ const bySubject = new Map(rows.map((row) => [row.subjectId, row.status]));
+ return input.subjectIds.flatMap((subjectId) => {
+ const task = resolved.byRef.get(subjectId)!;
+ const status = bySubject.get(task.id) ?? bySubject.get(task.identifier);
+ return status ? [{ status, subjectId }] : [];
+ });
+ }),
});
diff --git a/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts b/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts
index 83678eeb227..54e72eae8f2 100644
--- a/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts
+++ b/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts
@@ -3,9 +3,11 @@ import { MOVE_DOCUMENTS_MAX_IDS } from '@lobechat/builtin-tool-agent-documents';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { TaskModel } from '@/database/models/task';
import { router } from '@/libs/trpc/lambda';
import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
import {
agentDocumentProcedure,
@@ -155,6 +157,13 @@ export const toolDocumentsRouter = router({
.and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
+ if ('toolContext' in input && input.toolContext?.taskId) {
+ const task = await resolveTaskOrThrow(
+ new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ input.toolContext.taskId,
+ );
+ input.toolContext = { ...input.toolContext, taskId: task.id };
+ }
try {
const doc = await ctx.agentDocumentService.createDocument(
input.agentId,
@@ -213,6 +222,13 @@ export const toolDocumentsRouter = router({
.and(agentDocumentToolTriggerSchema),
)
.mutation(async ({ ctx, input }) => {
+ if ('toolContext' in input && input.toolContext?.taskId) {
+ const task = await resolveTaskOrThrow(
+ new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ input.toolContext.taskId,
+ );
+ input.toolContext = { ...input.toolContext, taskId: task.id };
+ }
try {
// Use the creator-facing finder: a visitor topic's title must not be
// copied into a creator-owned document.
diff --git a/apps/server/src/routers/lambda/brief.ts b/apps/server/src/routers/lambda/brief.ts
index 7e48b449c56..694ce47a122 100644
--- a/apps/server/src/routers/lambda/brief.ts
+++ b/apps/server/src/routers/lambda/brief.ts
@@ -10,6 +10,7 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentSignalSelfReviewBriefService } from '@/server/services/agentSignal/services/briefs/selfReview';
import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/selfIteration/review/brief';
import { BriefService } from '@/server/services/brief';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
import { applyGoalBriefAction } from './_helpers/goalBriefAction';
@@ -71,14 +72,15 @@ export const briefRouter = router({
// Resolve taskId if it's an identifier
if (createData.taskId) {
const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
- const task = await taskModel.resolve(createData.taskId);
- if (task) createData.taskId = task.id;
+ const task = await resolveTaskOrThrow(taskModel, createData.taskId);
+ createData.taskId = task.id;
}
const model = new BriefModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
const brief = await model.create(createData);
return { data: brief, message: 'Brief created', success: true };
} catch (error) {
+ if (error instanceof TRPCError) throw error;
console.error('[brief:create]', error);
throw new TRPCError({
cause: error,
@@ -127,9 +129,12 @@ export const briefRouter = router({
.query(async ({ input, ctx }) => {
try {
const model = new BriefModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
- const items = await model.findByTaskId(input.taskId);
+ const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ const task = await resolveTaskOrThrow(taskModel, input.taskId);
+ const items = await model.findByTaskId(task.id);
return { data: items, success: true };
} catch (error) {
+ if (error instanceof TRPCError) throw error;
console.error('[brief:findByTaskId]', error);
throw new TRPCError({
cause: error,
diff --git a/apps/server/src/routers/lambda/recent.ts b/apps/server/src/routers/lambda/recent.ts
index 742d0f42fbf..a71c0d852fd 100644
--- a/apps/server/src/routers/lambda/recent.ts
+++ b/apps/server/src/routers/lambda/recent.ts
@@ -66,8 +66,8 @@ export const recentRouter = router({
}
case 'task': {
routePath = item.routeId
- ? `/agent/${item.routeId}/task/${item.id}`
- : `/task/${item.id}`;
+ ? `/agent/${item.routeId}/task/${item.taskIdentifier ?? item.id}`
+ : `/task/${item.taskIdentifier ?? item.id}`;
break;
}
}
@@ -77,6 +77,7 @@ export const recentRouter = router({
description: item.description,
icon: item.type,
id: item.id,
+ taskIdentifier: item.taskIdentifier,
lastAssistantMessage: item.lastAssistantMessage,
metadata: item.metadata as ChatTopicMetadata | undefined,
routePath,
diff --git a/apps/server/src/routers/lambda/task/comments.ts b/apps/server/src/routers/lambda/task/comments.ts
index 46aee2866f7..15413051b84 100644
--- a/apps/server/src/routers/lambda/task/comments.ts
+++ b/apps/server/src/routers/lambda/task/comments.ts
@@ -7,6 +7,7 @@ import type { TaskModel } from '@/database/models/task';
import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { assertAssigneeAgentBelongsToUser } from '@/server/services/task/patchValidation';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
import {
extractCommentMentionedUserIds,
filterActiveWorkspaceMemberIds,
@@ -14,7 +15,7 @@ import {
} from '@/server/utils/commentMentions';
import { after } from '@/server/utils/scheduleAfterResponse';
-import { resolveOrThrow, taskProcedureWrite } from './procedures';
+import { taskProcedureWrite } from './procedures';
/**
* Recipients of a new comment on a task. A member comment pings the creator
@@ -123,7 +124,7 @@ export const commentsRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
await assertAssigneeAgentBelongsToUser(
ctx.serverDB,
{ userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },
diff --git a/apps/server/src/routers/lambda/task/execution.ts b/apps/server/src/routers/lambda/task/execution.ts
index b201bd4391c..a88cea39ed8 100644
--- a/apps/server/src/routers/lambda/task/execution.ts
+++ b/apps/server/src/routers/lambda/task/execution.ts
@@ -2,10 +2,11 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router } from '@/libs/trpc/lambda';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
import { failStuckTasks } from '@/server/services/taskLifecycle/failStuckTasks';
import { TaskRunnerService } from '@/server/services/taskRunner';
-import { idInput, resolveOrThrow, taskProcedure, taskProcedureWrite } from './procedures';
+import { idInput, taskProcedure, taskProcedureWrite } from './procedures';
/** Internal repair dispatch binds its durable operation pointer before a Task can execute. */
export const createTaskExecutionRouter = (
@@ -24,7 +25,7 @@ export const createTaskExecutionRouter = (
)
.mutation(async ({ input, ctx }) => {
try {
- const task = await resolveOrThrow(ctx.taskModel, input.id);
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.id);
const runner = new TaskRunnerService(
ctx.serverDB,
@@ -51,9 +52,13 @@ export const createTaskExecutionRouter = (
heartbeat: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
await model.updateHeartbeat(task.id);
- return { message: 'Heartbeat updated', success: true };
+ return {
+ data: { id: task.id, identifier: task.identifier },
+ message: 'Heartbeat updated',
+ success: true,
+ };
} catch (error) {
if (error instanceof TRPCError) throw error;
console.error('[task:heartbeat]', error);
@@ -120,7 +125,9 @@ export const createTaskExecutionRouter = (
}),
previewSubtaskLayers: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
- const plan = await ctx.taskService.previewSubtaskLayers(input.id);
+ const plan = await ctx.taskService.previewSubtaskLayers(
+ (await resolveTaskOrThrow(ctx.taskModel, input.id)).id,
+ );
return { data: plan, success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
@@ -134,7 +141,9 @@ export const createTaskExecutionRouter = (
}),
runReadySubtasks: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {
try {
- const result = await ctx.taskService.runReadySubtasks(input.id);
+ const result = await ctx.taskService.runReadySubtasks(
+ (await resolveTaskOrThrow(ctx.taskModel, input.id)).id,
+ );
return { data: result, success: result.failed.length === 0 };
} catch (error) {
if (error instanceof TRPCError) throw error;
diff --git a/apps/server/src/routers/lambda/task/lifecycle.ts b/apps/server/src/routers/lambda/task/lifecycle.ts
index cec5dcf22dd..89631054b12 100644
--- a/apps/server/src/routers/lambda/task/lifecycle.ts
+++ b/apps/server/src/routers/lambda/task/lifecycle.ts
@@ -12,16 +12,12 @@ import {
schedulePatternSchema,
scheduleTimezoneSchema,
} from '@/server/services/task/scheduleValidation';
+import { normalizeTaskConfig, resolveTaskOrThrow } from '@/server/services/task/utils';
import { AcceptanceService } from '@/server/services/verify/acceptanceService';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { TransferErrorCode } from '@/types/transferError';
-import {
- idInput,
- resolveOrThrow,
- taskProcedureWrite,
- taskVerifyConfigPatchSchema,
-} from './procedures';
+import { idInput, taskProcedureWrite, taskVerifyConfigPatchSchema } from './procedures';
// Priority: 0=None, 1=Urgent, 2=High, 3=Normal, 4=Low
// Unknown fields are stripped, including the removed identifierPrefix. Released
@@ -136,7 +132,13 @@ export const lifecycleRouter = router({
const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};
const task = await ctx.taskService.createTask({
...createInput,
- config: parsedVerify.success ? taskConfig : createInput.config,
+ parentTaskId: createInput.parentTaskId
+ ? (await resolveTaskOrThrow(ctx.taskModel, createInput.parentTaskId)).id
+ : undefined,
+ config: await normalizeTaskConfig(
+ ctx.taskModel,
+ parsedVerify.success ? taskConfig : createInput.config,
+ ),
});
try {
if (parsedVerify.success) {
@@ -193,7 +195,7 @@ export const lifecycleRouter = router({
try {
// Any member who can edit tasks may delete one they can see, whoever
// created it; viewers are gated by `taskProcedureWrite`.
- const task = await resolveOrThrow(ctx.taskModel, input.id);
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.id);
await ctx.taskService.deleteTask(task.id);
return { data: task, message: 'Task deleted', success: true };
} catch (error) {
@@ -212,7 +214,7 @@ export const lifecycleRouter = router({
.input(idInput.extend({ archived: z.boolean() }))
.mutation(async ({ input, ctx }) => {
try {
- const task = await resolveOrThrow(ctx.taskModel, input.id);
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.id);
// Same scope as delete: any member who can edit tasks, whoever created it.
if (input.archived) {
await assertNotInOpenGoal(
diff --git a/apps/server/src/routers/lambda/task/procedures.ts b/apps/server/src/routers/lambda/task/procedures.ts
index b94bc56104b..b97544e5c54 100644
--- a/apps/server/src/routers/lambda/task/procedures.ts
+++ b/apps/server/src/routers/lambda/task/procedures.ts
@@ -1,4 +1,3 @@
-import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
@@ -41,7 +40,7 @@ export const taskProcedureWrite = taskProcedure.use(withScopedPermission('agent:
// All procedures that take an id accept either raw id (task_xxx) or identifier (TASK-1)
// Resolution happens in the model layer via model.resolve()
-export const idInput = z.object({ id: z.string() });
+export const idInput = z.object({ id: z.string().trim().min(1) });
export const taskVerifyConfigPatchSchema = z.object({
enabled: z.boolean().nullish(),
@@ -51,10 +50,3 @@ export const taskVerifyConfigPatchSchema = z.object({
verifyCriteriaIds: z.array(z.string()).nullish(),
verifyRubricId: z.string().nullish(),
});
-
-// Helper: resolve id/identifier and throw if not found
-export async function resolveOrThrow(model: TaskModel, id: string) {
- const task = await model.resolve(id);
- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
- return task;
-}
diff --git a/apps/server/src/routers/lambda/task/queries.ts b/apps/server/src/routers/lambda/task/queries.ts
index 53a14e59af6..14d0b7403f6 100644
--- a/apps/server/src/routers/lambda/task/queries.ts
+++ b/apps/server/src/routers/lambda/task/queries.ts
@@ -3,14 +3,16 @@ import { TRPCError } from '@trpc/server';
import { UserModel } from '@/database/models/user';
import { router } from '@/libs/trpc/lambda';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
import { groupListSchema, listSchema, resolveClosedAfter } from '../_helpers/taskListSchemas';
-import { idInput, resolveOrThrow, taskProcedure } from './procedures';
+import { idInput, taskProcedure } from './procedures';
export const queriesRouter = router({
detail: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
- const detail = await ctx.taskService.getTaskDetail(input.id);
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.id);
+ const detail = await ctx.taskService.getTaskDetail(task.id);
if (!detail) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
}
@@ -29,7 +31,7 @@ export const queriesRouter = router({
find: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
return { data: task, success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
@@ -44,9 +46,14 @@ export const queriesRouter = router({
getDependencies: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const deps = await model.getDependencies(task.id);
- return { data: deps, success: true };
+ const upstreams = await model.findByIds(deps.map((dep) => dep.dependsOnId));
+ const byId = new Map(upstreams.map((upstream) => [upstream.id, upstream.identifier]));
+ return {
+ data: deps.map((dep) => ({ ...dep, dependsOnIdentifier: byId.get(dep.dependsOnId) })),
+ success: true,
+ };
} catch (error) {
if (error instanceof TRPCError) throw error;
console.error('[task:getDependencies]', error);
@@ -60,7 +67,7 @@ export const queriesRouter = router({
getPinnedDocuments: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const docs = await model.getPinnedDocuments(task.id);
return { data: docs, success: true };
} catch (error) {
@@ -76,7 +83,7 @@ export const queriesRouter = router({
getTopics: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const results = await ctx.taskTopicModel.findWithDetails(task.id);
return { data: results, success: true };
} catch (error) {
@@ -92,7 +99,7 @@ export const queriesRouter = router({
getSubtasks: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const subtasks = await model.findSubtasks(task.id);
return { data: subtasks, success: true };
} catch (error) {
@@ -108,7 +115,7 @@ export const queriesRouter = router({
getTaskTree: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const tree = await model.getTaskTree(task.id);
return { data: tree, success: true };
} catch (error) {
@@ -124,15 +131,22 @@ export const queriesRouter = router({
groupList: taskProcedure.input(groupListSchema).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const { completedWithin, scope, ...query } = input;
+ const { completedWithin, parentIdentifier, scope, ...query } = input;
+ const parentRef = query.parentTaskId !== undefined ? query.parentTaskId : parentIdentifier;
+ const parentTaskId =
+ typeof parentRef === 'string'
+ ? (await resolveTaskOrThrow(model, parentRef)).id
+ : query.parentTaskId;
const groups = await model.groupList({
...query,
+ parentTaskId,
closedAfter: resolveClosedAfter(completedWithin),
...(scope === 'assigned' ? { assigneeUserId: ctx.userId } : {}),
...(scope === 'created' ? { createdByUserId: ctx.userId } : {}),
});
return { data: groups, success: true };
} catch (error) {
+ if (error instanceof TRPCError) throw error;
console.error('[task:groupList]', error);
throw new TRPCError({
cause: error,
@@ -145,19 +159,11 @@ export const queriesRouter = router({
try {
const model = ctx.taskModel;
const { completedWithin, parentIdentifier, scope, ...query } = input;
- let parentTaskId = query.parentTaskId;
-
- if (parentIdentifier) {
- const parent = await model.resolve(parentIdentifier);
- if (!parent) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: `Parent task not found: ${parentIdentifier}`,
- });
- }
-
- parentTaskId = parent.id;
- }
+ const parentRef = query.parentTaskId !== undefined ? query.parentTaskId : parentIdentifier;
+ const parentTaskId =
+ typeof parentRef === 'string'
+ ? (await resolveTaskOrThrow(model, parentRef)).id
+ : query.parentTaskId;
const result = await model.list({
...query,
@@ -224,7 +230,7 @@ export const queriesRouter = router({
}),
usage: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
- const task = await resolveOrThrow(ctx.taskModel, input.id);
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.id);
const usage = await ctx.taskTopicModel.sumRunCostByTaskIds([task.id]);
return {
diff --git a/apps/server/src/routers/lambda/task/relations.ts b/apps/server/src/routers/lambda/task/relations.ts
index 694ac2be011..bc598496820 100644
--- a/apps/server/src/routers/lambda/task/relations.ts
+++ b/apps/server/src/routers/lambda/task/relations.ts
@@ -2,8 +2,9 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router } from '@/libs/trpc/lambda';
+import { resolveTaskOrThrow, resolveTasksOrThrow } from '@/server/services/task/utils';
-import { resolveOrThrow, taskProcedureWrite } from './procedures';
+import { taskProcedureWrite } from './procedures';
export const relationsRouter = router({
reorderSubtasks: taskProcedureWrite
@@ -17,32 +18,23 @@ export const relationsRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const subtasks = await model.findSubtasks(task.id);
- // Build identifier → id map
- const idMap = new Map<string, string>();
- for (const s of subtasks) idMap.set(s.identifier, s.id);
-
- // Validate all identifiers exist
- const reorderItems: Array<{ id: string; sortOrder: number }> = [];
- for (let i = 0; i < input.order.length; i++) {
- const identifier = input.order[i].toUpperCase();
- const taskId = idMap.get(identifier);
- if (!taskId) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Subtask not found: ${identifier}`,
- });
- }
- reorderItems.push({ id: taskId, sortOrder: i });
+ const ordered = (await resolveTasksOrThrow(model, input.order, { duplicates: 'reject' }))
+ .tasks;
+ const directIds = new Set(subtasks.map((subtask) => subtask.id));
+ if (ordered.some((subtask) => !directIds.has(subtask.id))) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Task is not a direct subtask' });
}
+ const reorderItems = ordered.map((subtask, sortOrder) => ({ id: subtask.id, sortOrder }));
await model.reorder(reorderItems);
return {
data: reorderItems.map((item, i) => ({
- identifier: input.order[i],
+ id: item.id,
+ identifier: ordered[i].identifier,
sortOrder: item.sortOrder,
})),
message: 'Subtasks reordered',
@@ -69,8 +61,8 @@ export const relationsRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.taskId);
- const dep = await resolveOrThrow(model, input.dependsOnId);
+ const task = await resolveTaskOrThrow(model, input.taskId);
+ const dep = await resolveTaskOrThrow(model, input.dependsOnId);
await model.addDependency(task.id, dep.id, input.type);
return { message: 'Dependency added', success: true };
} catch (error) {
@@ -91,8 +83,8 @@ export const relationsRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.taskId);
- const dep = await resolveOrThrow(model, input.dependsOnId);
+ const task = await resolveTaskOrThrow(model, input.taskId);
+ const dep = await resolveTaskOrThrow(model, input.dependsOnId);
await model.removeDependency(task.id, dep.id);
return { message: 'Dependency removed', success: true };
} catch (error) {
@@ -116,7 +108,7 @@ export const relationsRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.taskId);
+ const task = await resolveTaskOrThrow(model, input.taskId);
await model.pinDocument(task.id, input.documentId, input.pinnedBy);
return { message: 'Document pinned', success: true };
} catch (error) {
@@ -134,7 +126,7 @@ export const relationsRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.taskId);
+ const task = await resolveTaskOrThrow(model, input.taskId);
await model.unpinDocument(task.id, input.documentId);
return { message: 'Document unpinned', success: true };
} catch (error) {
diff --git a/apps/server/src/routers/lambda/task/review.ts b/apps/server/src/routers/lambda/task/review.ts
index 4bb0962cd8c..a8fa03fd5c6 100644
--- a/apps/server/src/routers/lambda/task/review.ts
+++ b/apps/server/src/routers/lambda/task/review.ts
@@ -2,25 +2,59 @@ import type { TaskVerifyConfig } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { checkpointTaskPairsMatch } from '@/database/models/task/checkpoint';
import { router } from '@/libs/trpc/lambda';
+import { normalizeCheckpointTaskRefs, resolveTaskOrThrow } from '@/server/services/task/utils';
import { AcceptanceService } from '@/server/services/verify/acceptanceService';
import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';
import {
idInput,
- resolveOrThrow,
taskProcedure,
taskProcedureWrite,
taskVerifyConfigPatchSchema,
} from './procedures';
+const checkpointTaskRefSchema = z.object({ id: z.string(), identifier: z.string() });
+
export const reviewRouter = router({
getCheckpoint: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const checkpoint = model.getCheckpointConfig(task);
- return { data: checkpoint, success: true };
+ const references = (
+ ids: string[] | undefined,
+ pairs: { id: string; identifier: string }[] | undefined,
+ ) => (checkpointTaskPairsMatch(ids, pairs) ? pairs!.map((pair) => pair.id) : (ids ?? []));
+ const refs = [
+ ...references(checkpoint.tasks?.beforeIds, checkpoint.tasks?.beforeTasks),
+ ...references(checkpoint.tasks?.afterIds, checkpoint.tasks?.afterTasks),
+ ];
+ const resolved = await model.resolveRefs(refs);
+ const display = (
+ values: string[] | undefined,
+ pairs: { id: string; identifier: string }[] | undefined,
+ ) =>
+ checkpointTaskPairsMatch(values, pairs)
+ ? pairs!.map((pair) => ({
+ id: pair.id,
+ identifier: resolved.byRef.get(pair.id)?.identifier ?? pair.identifier,
+ }))
+ : values?.map((ref) => {
+ const task = resolved.byRef.get(ref);
+ return task?.identifier === ref
+ ? { id: task.id, identifier: task.identifier }
+ : { identifier: ref };
+ });
+ return {
+ data: {
+ ...checkpoint,
+ beforeTasks: display(checkpoint.tasks?.beforeIds, checkpoint.tasks?.beforeTasks),
+ afterTasks: display(checkpoint.tasks?.afterIds, checkpoint.tasks?.afterTasks),
+ },
+ success: true,
+ };
} catch (error) {
if (error instanceof TRPCError) throw error;
console.error('[task:getCheckpoint]', error);
@@ -40,7 +74,9 @@ export const reviewRouter = router({
tasks: z
.object({
afterIds: z.array(z.string()).optional(),
+ afterTasks: z.array(checkpointTaskRefSchema).optional(),
beforeIds: z.array(z.string()).optional(),
+ beforeTasks: z.array(checkpointTaskRefSchema).optional(),
})
.optional(),
topic: z
@@ -57,8 +93,11 @@ export const reviewRouter = router({
const { id, checkpoint } = input;
try {
const model = ctx.taskModel;
- const resolved = await resolveOrThrow(model, id);
- const task = await model.updateCheckpointConfig(resolved.id, checkpoint);
+ const resolved = await resolveTaskOrThrow(model, id);
+ const task = await model.updateCheckpointConfig(
+ resolved.id,
+ await normalizeCheckpointTaskRefs(model, checkpoint, model.getCheckpointConfig(resolved)),
+ );
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
return {
data: model.getCheckpointConfig(task),
@@ -78,7 +117,7 @@ export const reviewRouter = router({
getReview: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
return { data: model.getReviewConfig(task) || null, success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
@@ -123,7 +162,7 @@ export const reviewRouter = router({
const { id, review } = input;
try {
const model = ctx.taskModel;
- const resolved = await resolveOrThrow(model, id);
+ const resolved = await resolveTaskOrThrow(model, id);
const task = await model.updateReviewConfig(resolved.id, review);
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
return {
@@ -144,7 +183,7 @@ export const reviewRouter = router({
getVerifyConfig: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveTaskOrThrow(model, input.id);
const resolved = await resolveTaskAcceptance(
ctx.serverDB,
ctx.userId,
@@ -179,7 +218,7 @@ export const reviewRouter = router({
const { id, verify } = input;
try {
const model = ctx.taskModel;
- const task = await resolveOrThrow(model, id);
+ const task = await resolveTaskOrThrow(model, id);
const acceptanceService = new AcceptanceService(
ctx.serverDB,
ctx.userId,
@@ -239,7 +278,10 @@ export const reviewRouter = router({
)
.mutation(async ({ input, ctx }) => {
try {
- const result = await ctx.taskService.runReview(input);
+ const result = await ctx.taskService.runReview({
+ ...input,
+ id: (await resolveTaskOrThrow(ctx.taskModel, input.id)).id,
+ });
return { data: result, success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
diff --git a/apps/server/src/routers/lambda/task/update.ts b/apps/server/src/routers/lambda/task/update.ts
index 1a28fd9ff38..bb5ea4f7061 100644
--- a/apps/server/src/routers/lambda/task/update.ts
+++ b/apps/server/src/routers/lambda/task/update.ts
@@ -13,9 +13,10 @@ import {
schedulePatternSchema,
scheduleTimezoneSchema,
} from '@/server/services/task/scheduleValidation';
+import { normalizeTaskConfig, resolveTaskOrThrow } from '@/server/services/task/utils';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
-import { idInput, resolveOrThrow, taskProcedureWrite } from './procedures';
+import { idInput, taskProcedureWrite } from './procedures';
const updateSchema = z.object({
assigneeAgentId: z.string().nullish(),
@@ -83,7 +84,14 @@ export const updateRouter = router({
update: taskProcedureWrite
.input(idInput.merge(updateSchema).extend({ actorAgentId: z.string().optional() }))
.mutation(async ({ input, ctx }) => {
- const { actorAgentId, configPatch, id, parentTaskId, status, ...data } = input;
+ const {
+ actorAgentId,
+ configPatch: rawConfigPatch,
+ id,
+ parentTaskId,
+ status,
+ ...data
+ } = input;
try {
const model = ctx.taskModel;
const actor = await resolveActivityActor(ctx, actorAgentId);
@@ -101,6 +109,14 @@ export const updateRouter = router({
},
{ data, id, parentTaskId },
);
+ const configPatch = await normalizeTaskConfig(model, rawConfigPatch, resolved.config);
+ if (normalizedUpdateData.config) {
+ normalizedUpdateData.config = await normalizeTaskConfig(
+ model,
+ normalizedUpdateData.config,
+ resolved.config,
+ );
+ }
// Agent attribution comes from `resolveActivityActor` above. The
// assignment activity is written inside this update's own transaction
// (see `TaskModel.updateWithLog`), so a concurrent reassignment cannot
@@ -146,7 +162,7 @@ export const updateRouter = router({
.input(idInput.merge(z.object({ visibility: z.enum(['private', 'public']) })))
.mutation(async ({ input, ctx }) => {
try {
- const resolved = await resolveOrThrow(ctx.taskModel, input.id);
+ const resolved = await resolveTaskOrThrow(ctx.taskModel, input.id);
// Mirror the edit-lock contract from `update`: reject visibility flips
// while another workspace member is actively editing this task. Without
@@ -255,8 +271,11 @@ export const updateRouter = router({
const { id, config } = input;
try {
const model = ctx.taskModel;
- const resolved = await resolveOrThrow(model, id);
- const task = await model.updateTaskConfig(resolved.id, config);
+ const resolved = await resolveTaskOrThrow(model, id);
+ const task = await model.updateTaskConfig(
+ resolved.id,
+ (await normalizeTaskConfig(model, config, resolved.config))!,
+ );
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
return { data: task, message: 'Config updated', success: true };
} catch (error) {
@@ -285,7 +304,10 @@ export const updateRouter = router({
// A person (or their agent) changed it: record who. System
// transitions call the service without an actor and stay silent.
const actor = await resolveActivityActor(ctx, actorAgentId);
- const result = await ctx.taskService.updateStatus(statusInput, actor);
+ const result = await ctx.taskService.updateStatus(
+ { ...statusInput, id: (await resolveTaskOrThrow(ctx.taskModel, statusInput.id)).id },
+ actor,
+ );
const {
task,
unlocked,
@@ -301,6 +323,8 @@ export const updateRouter = router({
success: true,
...(completionDeferred && { completionDeferred: true }),
...(unlocked.length > 0 && { unlocked }),
+ unlockedTasks: result.unlockedTasks,
+ pausedTasks: result.pausedTasks,
...(paused.length > 0 && { paused }),
...(checkpointTriggered && { checkpointTriggered: true }),
...(allSubtasksDone && { allSubtasksDone: true, parentTaskId }),
@@ -325,7 +349,7 @@ export const updateRouter = router({
.mutation(async ({ input, ctx }) => {
try {
const result = await ctx.taskService.updateStatusCascade(
- input,
+ { ...input, id: (await resolveTaskOrThrow(ctx.taskModel, input.id)).id },
await resolveActivityActor(ctx),
);
return { data: result, message: `Task family ${input.status}`, success: true };
@@ -341,7 +365,7 @@ export const updateRouter = router({
}),
acquireTaskLock: taskProcedureWrite.input(idInput).mutation(async ({ ctx, input }) => {
if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };
- const resolved = await resolveOrThrow(ctx.taskModel, input.id);
+ const resolved = await resolveTaskOrThrow(ctx.taskModel, input.id);
const prev = await ctx.editLockService.getActiveHolder('task', resolved.id);
const result = await ctx.editLockService.acquire('task', resolved.id);
if ((result.holderId ?? null) !== (prev ?? null)) {
@@ -354,7 +378,7 @@ export const updateRouter = router({
}),
getTaskLock: taskProcedureWrite.input(idInput).query(async ({ ctx, input }) => {
if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };
- const resolved = await resolveOrThrow(ctx.taskModel, input.id);
+ const resolved = await resolveTaskOrThrow(ctx.taskModel, input.id);
const holder = await ctx.editLockService.getActiveHolder('task', resolved.id);
return {
expiresAt: null,
@@ -364,7 +388,7 @@ export const updateRouter = router({
}),
releaseTaskLock: taskProcedureWrite.input(idInput).mutation(async ({ ctx, input }) => {
if (!ctx.workspaceId) return;
- const resolved = await resolveOrThrow(ctx.taskModel, input.id);
+ const resolved = await resolveTaskOrThrow(ctx.taskModel, input.id);
// Only broadcast "unlocked" when we actually released our own lock — if the
// lease expired and another member took over, the lock is still held.
const released = await ctx.editLockService.release('task', resolved.id);
diff --git a/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.ts b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.ts
index 68c007fe03c..0f5f7af945b 100644
--- a/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.ts
@@ -1,6 +1,7 @@
import type { TaskDetailData } from '@lobechat/types';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { TaskModel } from '@/database/models/task';
import { TaskDetailService } from '@/server/services/task/detail';
import { buildViewedTaskContextPrompt, joinSystemContext } from './viewedTaskContext';
@@ -19,10 +20,32 @@ describe('buildViewedTaskContextPrompt', () => {
let getTaskDetail: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
+ vi.spyOn(TaskModel.prototype, 'resolve').mockImplementation(
+ async (ref) => ({ id: ref }) as never,
+ );
getTaskDetail = vi
.spyOn(TaskDetailService.prototype, 'getTaskDetail')
.mockResolvedValue(taskDetail as never);
});
+ afterEach(() => vi.restoreAllMocks());
+
+ it('resolves legacy route identifiers before the ID-only detail read', async () => {
+ vi.mocked(TaskModel.prototype.resolve).mockResolvedValue({ id: 'task_858' } as never);
+ getTaskDetail.mockImplementation(async (id) => (id === 'task_858' ? taskDetail : null));
+ const prompt = await buildViewedTaskContextPrompt(deps, { scope: 'task' }, 'T-858');
+ expect(prompt).toContain('The user is currently viewing the detail page of task T-858');
+ });
+
+ it('does not read a detail for an invisible legacy reference', async () => {
+ vi.mocked(TaskModel.prototype.resolve).mockResolvedValue(null);
+ const prompt = await buildViewedTaskContextPrompt(
+ deps,
+ { defaultTaskAssigneeAgentId: 'agt_inbox', scope: 'task' },
+ 'T-858',
+ );
+ expect(getTaskDetail).not.toHaveBeenCalled();
+ expect(prompt).toContain('Default Lobe AI agent id: agt_inbox');
+ });
it('describes the task viewed on a task detail page', async () => {
const prompt = await buildViewedTaskContextPrompt(
diff --git a/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.ts b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.ts
index 3cfd5723b30..afc6c6872e5 100644
--- a/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.ts
+++ b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.ts
@@ -2,7 +2,9 @@ import type { LobeChatDatabase } from '@lobechat/database';
import { buildTaskDetailPrompt, buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';
import debug from 'debug';
+import { TaskModel } from '@/database/models/task';
import { TaskDetailService } from '@/server/services/task/detail';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
import type { InternalExecAgentParams } from '../types';
@@ -33,11 +35,15 @@ export const buildViewedTaskContextPrompt = async (
if (taskId) {
try {
+ const viewedTask = await resolveTaskOrThrow(
+ new TaskModel(deps.db, deps.userId, deps.workspaceId),
+ taskId,
+ );
const task = await new TaskDetailService(
deps.db,
deps.userId,
deps.workspaceId,
- ).getTaskDetail(taskId);
+ ).getTaskDetail(viewedTask.id);
if (task) return buildTaskDetailPrompt({ defaultAssigneeAgentId, task });
} catch (error) {
log('failed to load viewed task %s: %O', taskId, error);
diff --git a/apps/server/src/services/task/detail.ts b/apps/server/src/services/task/detail.ts
index 12ee5747104..a1c210972c7 100644
--- a/apps/server/src/services/task/detail.ts
+++ b/apps/server/src/services/task/detail.ts
@@ -72,8 +72,8 @@ export class TaskDetailService {
this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);
}
- async getTaskDetail(taskIdOrIdentifier: string): Promise<TaskDetailData | null> {
- let task = await this.taskModel.resolve(taskIdOrIdentifier);
+ async getTaskDetail(taskId: string): Promise<TaskDetailData | null> {
+ let task = await this.taskModel.findById(taskId);
if (!task) return null;
// Auto-detect heartbeat timeout for running tasks before assembling detail.
@@ -82,7 +82,7 @@ export class TaskDetailService {
if (elapsed > task.heartbeatTimeout) {
await this.taskModel.updateStatus(task.id, 'paused', { error: 'Heartbeat timeout' });
await this.taskTopicModel.timeoutRunning(task.id);
- task = await this.taskModel.resolve(taskIdOrIdentifier);
+ task = await this.taskModel.findById(taskId);
if (!task) return null;
}
}
@@ -184,10 +184,10 @@ export class TaskDetailService {
// Build dependency map for all descendants
const idToIdentifier = new Map(allDescendants.map((s) => [s.id, s.identifier]));
- const depMap = new Map<string, string>();
+ const depMap = new Map<string, { id: string; identifier: string }>();
for (const dep of allDescendantDeps) {
const depId = idToIdentifier.get(dep.dependsOnId);
- if (depId) depMap.set(dep.taskId, depId);
+ if (depId) depMap.set(dep.taskId, { id: dep.dependsOnId, identifier: depId });
}
const runningTopicByTaskId = new Map<string, (typeof allDescendantTopics)[number]>();
@@ -236,11 +236,13 @@ export class TaskDetailService {
...(s.archivedAt ? { archivedAt: new Date(s.archivedAt).toISOString() } : {}),
assigneeUserId: s.assigneeUserId,
automationMode: s.automationMode,
- blockedBy: depMap.get(s.id),
+ blockedBy: depMap.get(s.id)?.identifier,
+ blockedById: depMap.get(s.id)?.id,
createdByUserId: s.createdByUserId,
visibility: s.visibility,
children: buildSubtaskTree(s.id),
...(s.heartbeatInterval != null ? { heartbeat: { interval: s.heartbeatInterval } } : {}),
+ id: s.id,
identifier: s.identifier,
name: s.name,
priority: s.priority,
@@ -272,11 +274,17 @@ export class TaskDetailService {
);
// Resolve parent
- let parent: { agentId: string | null; identifier: string; name: string | null } | null = null;
+ let parent: {
+ id: string;
+ agentId: string | null;
+ identifier: string;
+ name: string | null;
+ } | null = null;
if (task.parentTaskId) {
const parentTask = await this.taskModel.findById(task.parentTaskId);
if (parentTask) {
parent = {
+ id: parentTask.id,
agentId: parentTask.assigneeAgentId,
identifier: parentTask.identifier,
name: parentTask.name,
@@ -501,6 +509,7 @@ export class TaskDetailService {
const info = depIdToInfo.get(d.dependsOnId);
return {
dependsOn: info?.identifier ?? d.dependsOnId,
+ dependsOnId: d.dependsOnId,
name: info?.name,
type: d.type,
};
diff --git a/apps/server/src/services/task/index.detailState.test.ts b/apps/server/src/services/task/index.detailState.test.ts
index c6eb3400286..e25474e49e2 100644
--- a/apps/server/src/services/task/index.detailState.test.ts
+++ b/apps/server/src/services/task/index.detailState.test.ts
@@ -10,7 +10,7 @@ import { TaskService } from './index';
const mocks = vi.hoisted(() => ({
findByOperations: vi.fn(),
findWithHandoff: vi.fn(),
- resolve: vi.fn(),
+ findById: vi.fn(),
timeoutRunning: vi.fn(),
update: vi.fn(),
updateStatus: vi.fn(),
@@ -56,7 +56,7 @@ vi.mock('@/database/models/task', () => ({
getDependencies: vi.fn().mockResolvedValue([]),
getTreePinnedDocuments: vi.fn().mockResolvedValue({ nodeMap: {}, tree: [] }),
getVerifyConfig: vi.fn().mockReturnValue(undefined),
- resolve: mocks.resolve,
+ findById: mocks.findById,
update: mocks.update,
updateStatus: mocks.updateStatus,
};
@@ -99,7 +99,7 @@ describe('TaskService.getTaskDetail state', () => {
lastHeartbeatAt: new Date(Date.now() - 120_000),
status: 'running',
};
- mocks.resolve
+ mocks.findById
.mockResolvedValueOnce(stale)
.mockResolvedValueOnce({ ...stale, error: 'Heartbeat timeout', status: 'paused' });
@@ -109,14 +109,14 @@ describe('TaskService.getTaskDetail state', () => {
error: 'Heartbeat timeout',
});
expect(mocks.timeoutRunning).toHaveBeenCalledWith('task-1');
- expect(mocks.resolve).toHaveBeenCalledTimes(2);
+ expect(mocks.findById).toHaveBeenCalledTimes(2);
// The re-read task is no longer running, so its timeout error is cleared.
expect(mocks.update).toHaveBeenCalledWith('task-1', { error: null });
expect(detail).toMatchObject({ error: null, status: 'paused' });
});
it('keeps a running task whose heartbeat is still fresh', async () => {
- mocks.resolve.mockResolvedValue({
+ mocks.findById.mockResolvedValue({
...baseTask,
heartbeatTimeout: 600,
lastHeartbeatAt: new Date(),
@@ -130,7 +130,7 @@ describe('TaskService.getTaskDetail state', () => {
});
it("decorates each run row with its verify round's verdict", async () => {
- mocks.resolve.mockResolvedValue(baseTask);
+ mocks.findById.mockResolvedValue(baseTask);
mocks.findWithHandoff.mockResolvedValue([
{
createdAt: new Date('2024-01-02T00:00:00Z'),
diff --git a/apps/server/src/services/task/index.statusCompletion.test.ts b/apps/server/src/services/task/index.statusCompletion.test.ts
index dc7932d3201..7896e3e0bfe 100644
--- a/apps/server/src/services/task/index.statusCompletion.test.ts
+++ b/apps/server/src/services/task/index.statusCompletion.test.ts
@@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({
areAllSubtasksCompleted: vi.fn(),
cascadeOnCompletion: vi.fn(),
findById: vi.fn(),
- resolve: vi.fn(),
shouldPauseAfterComplete: vi.fn(),
updateStatus: vi.fn(),
}));
@@ -30,7 +29,6 @@ vi.mock('@/database/models/task', () => ({
return {
areAllSubtasksCompleted: mocks.areAllSubtasksCompleted,
findById: mocks.findById,
- resolve: mocks.resolve,
shouldPauseAfterComplete: mocks.shouldPauseAfterComplete,
updateStatus: mocks.updateStatus,
};
@@ -55,7 +53,7 @@ const subtask = {
describe('TaskService.updateStatus completion', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.resolve.mockResolvedValue({ ...subtask, status: 'todo' });
+ mocks.findById.mockResolvedValueOnce({ ...subtask, status: 'todo' });
mocks.updateStatus.mockImplementation(async (id: string, status: string) => ({
...subtask,
id,
@@ -70,13 +68,13 @@ describe('TaskService.updateStatus completion', () => {
mocks.areAllSubtasksCompleted.mockResolvedValue(true);
const result = await new TaskService(db as any, 'user-1').updateStatus({
- id: 'T-2',
+ id: 'task-2',
status: 'completed',
});
expect(mocks.shouldPauseAfterComplete).toHaveBeenCalledWith(
{ id: 'task-1', identifier: 'T-1' },
- 'T-2',
+ expect.objectContaining({ id: 'task-2', identifier: 'T-2' }),
);
expect(mocks.updateStatus).toHaveBeenCalledWith('task-1', 'paused');
expect(mocks.areAllSubtasksCompleted).toHaveBeenCalledWith('task-1');
@@ -95,7 +93,7 @@ describe('TaskService.updateStatus completion', () => {
mocks.areAllSubtasksCompleted.mockResolvedValue(false);
const result = await new TaskService(db as any, 'user-1').updateStatus({
- id: 'T-2',
+ id: 'task-2',
status: 'completed',
});
@@ -109,10 +107,10 @@ describe('TaskService.updateStatus completion', () => {
await expect(
new TaskService(db as any, 'user-1').updateStatus({
error: 'boom',
- id: 'T-2',
+ id: 'task-2',
status: 'completed',
}),
).rejects.toThrow('Task error can only be provided when status is failed.');
- expect(mocks.resolve).not.toHaveBeenCalled();
+ expect(mocks.findById).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 97ddf2d32bf..16bb83d62bc 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -130,7 +130,7 @@ describe('TaskService', () => {
getTaskFileIds: vi.fn().mockResolvedValue([]),
getTreeAgentIdsForTaskIds: vi.fn().mockResolvedValue({}),
getTreePinnedDocuments: vi.fn(),
- resolve: vi.fn(),
+
update: vi.fn(),
updateContext: vi.fn(),
updateStatus: vi.fn(),
@@ -298,13 +298,13 @@ describe('TaskService', () => {
describe('getTaskDetail', () => {
it('should return null when task is not found', async () => {
- mockTaskModel.resolve.mockResolvedValue(null);
+ mockTaskModel.findById.mockResolvedValue(null);
const service = new TaskService(db, userId);
const result = await service.getTaskDetail('TASK-1');
expect(result).toBeNull();
- expect(mockTaskModel.resolve).toHaveBeenCalledWith('TASK-1');
+ expect(mockTaskModel.findById).toHaveBeenCalledWith('TASK-1');
});
it('should return task detail for a simple task with no subtasks or dependencies', async () => {
@@ -328,7 +328,7 @@ describe('TaskService', () => {
totalTopics: 0,
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -353,7 +353,7 @@ describe('TaskService', () => {
expect(result?.createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(result?.startedAt).toBe('2024-01-01T00:02:00.000Z');
expect(result?.subtasks).toEqual([]);
- expect(result?.dependencies).toEqual([]);
+ expect(result?.dependencies).toMatchObject([]);
expect(result?.activities).toBeUndefined();
expect(result?.workspace).toBeUndefined();
expect(result?.parent).toBeNull();
@@ -378,7 +378,7 @@ describe('TaskService', () => {
priority: 'normal',
status: 'todo',
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValueOnce(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -429,7 +429,7 @@ describe('TaskService', () => {
name: 'Parent Task',
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValueOnce(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -444,7 +444,7 @@ describe('TaskService', () => {
const service = new TaskService(db, userId);
const result = await service.getTaskDetail('TASK-2');
- expect(result?.parent).toEqual({
+ expect(result?.parent).toMatchObject({
agentId: 'agt_parent',
identifier: 'TASK-1',
name: 'Parent Task',
@@ -472,7 +472,7 @@ describe('TaskService', () => {
totalTopics: 0,
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValueOnce(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -532,7 +532,7 @@ describe('TaskService', () => {
// task_003 depends on task_002
const subtaskDeps = [{ dependsOnId: 'task_002', taskId: 'task_003' }];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue(subtasks);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -548,7 +548,7 @@ describe('TaskService', () => {
const result = await service.getTaskDetail('TASK-1');
expect(result?.subtasks).toHaveLength(2);
- expect(result?.subtasks?.[0]).toEqual({
+ expect(result?.subtasks?.[0]).toMatchObject({
blockedBy: undefined,
children: undefined,
identifier: 'TASK-2',
@@ -556,7 +556,7 @@ describe('TaskService', () => {
priority: 'normal',
status: 'todo',
});
- expect(result?.subtasks?.[1]).toEqual({
+ expect(result?.subtasks?.[1]).toMatchObject({
blockedBy: 'TASK-2',
children: undefined,
identifier: 'TASK-3',
@@ -598,7 +598,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue(subtasks);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -677,7 +677,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue(allDescendants);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -699,7 +699,7 @@ describe('TaskService', () => {
const child1 = result?.subtasks?.[0];
expect(child1?.identifier).toBe('TASK-2');
expect(child1?.children).toHaveLength(1);
- expect(child1?.children?.[0]).toEqual({
+ expect(child1?.children?.[0]).toMatchObject({
blockedBy: undefined,
children: undefined,
identifier: 'TASK-4',
@@ -737,7 +737,7 @@ describe('TaskService', () => {
const dependencies = [{ dependsOnId: 'task_002', taskId: 'task_003', type: 'blocks' }];
const depTasks = [{ id: 'task_002', identifier: 'TASK-2', name: 'Task 2' }];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue(dependencies);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -751,7 +751,7 @@ describe('TaskService', () => {
const service = new TaskService(db, userId);
const result = await service.getTaskDetail('TASK-3');
- expect(result?.dependencies).toEqual([
+ expect(result?.dependencies).toMatchObject([
{ dependsOn: 'TASK-2', name: 'Task 2', type: 'blocks' },
]);
});
@@ -778,7 +778,7 @@ describe('TaskService', () => {
const dependencies = [{ dependsOnId: 'task_missing', taskId: 'task_003', type: 'blocks' }];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue(dependencies);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -792,7 +792,7 @@ describe('TaskService', () => {
const service = new TaskService(db, userId);
const result = await service.getTaskDetail('TASK-3');
- expect(result?.dependencies).toEqual([
+ expect(result?.dependencies).toMatchObject([
{ dependsOn: 'task_missing', name: undefined, type: 'blocks' },
]);
});
@@ -848,7 +848,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -904,7 +904,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -964,7 +964,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -1030,7 +1030,7 @@ describe('TaskService', () => {
{ createdAt: new Date(), handoff: null, seq: 2, status: 'completed', topicId: 'topic-2' },
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -1119,7 +1119,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue(descendants);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(directTopics);
@@ -1200,7 +1200,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -1243,7 +1243,7 @@ describe('TaskService', () => {
totalTopics: 0,
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -1307,7 +1307,7 @@ describe('TaskService', () => {
],
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -1355,7 +1355,7 @@ describe('TaskService', () => {
totalTopics: 0,
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -1397,7 +1397,7 @@ describe('TaskService', () => {
totalTopics: 0,
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);
@@ -1434,7 +1434,7 @@ describe('TaskService', () => {
totalTopics: 0,
};
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
// Simulate optional calls failing
@@ -1493,7 +1493,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -1551,7 +1551,7 @@ describe('TaskService', () => {
},
];
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
mockTaskModel.getDependencies.mockResolvedValue([]);
mockTaskTopicModel.findWithHandoff.mockResolvedValue(topics);
@@ -1575,7 +1575,7 @@ describe('TaskService', () => {
describe('completion requested by the task own run', () => {
it('defers instead of interrupting the calling operation', async () => {
const task = { automationMode: 'schedule', id: 'task-self', status: 'running' };
- mockTaskModel.resolve.mockResolvedValue(task);
+ mockTaskModel.findById.mockResolvedValue(task);
mockTaskTopicModel.findByTaskId.mockResolvedValue([
{ topicId: 'topic-self', operationId: 'op-self', status: 'running' },
]);
@@ -1596,7 +1596,7 @@ describe('TaskService', () => {
});
it('still interrupts when the operation is not one of the task runs', async () => {
- mockTaskModel.resolve.mockResolvedValue({ id: 'task-live', status: 'running' });
+ mockTaskModel.findById.mockResolvedValue({ id: 'task-live', status: 'running' });
mockTaskTopicModel.findByTaskId.mockResolvedValue([
{ topicId: 'topic-live', operationId: 'op-live', status: 'running' },
]);
@@ -1618,7 +1618,7 @@ describe('TaskService', () => {
it.each([{ success: true, deviceCancellationConfirmed: false }, { success: false }])(
'keeps a live Task and topic unchanged when cancellation is unconfirmed: %j',
async (result) => {
- mockTaskModel.resolve.mockResolvedValue({ id: 'task-live', status: 'running' });
+ mockTaskModel.findById.mockResolvedValue({ id: 'task-live', status: 'running' });
mockTaskTopicModel.findByTaskId.mockResolvedValue([
{ topicId: 'topic-live', operationId: 'op-live', status: 'running' },
]);
@@ -1641,7 +1641,7 @@ describe('TaskService', () => {
});
it('interrupts a running execution before deleting the task row', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-live',
identifier: 'T-2',
status: 'running',
@@ -1660,7 +1660,7 @@ describe('TaskService', () => {
});
it('keeps the task when its execution cannot be stopped', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-live',
identifier: 'T-2',
status: 'running',
@@ -1677,7 +1677,7 @@ describe('TaskService', () => {
});
it('refuses to delete a task whose run is still starting', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-starting',
identifier: 'T-4',
startedAt: new Date(),
@@ -1692,7 +1692,7 @@ describe('TaskService', () => {
});
it('deletes a running task whose start died long ago', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-stale',
identifier: 'T-5',
startedAt: new Date(Date.now() - 60 * 60 * 1000),
@@ -1706,7 +1706,7 @@ describe('TaskService', () => {
});
it('loses to a run that started after the checks instead of orphaning it', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-race',
identifier: 'T-6',
status: 'backlog',
@@ -1720,7 +1720,7 @@ describe('TaskService', () => {
});
it('loses to a run that recorded a new topic while the delete was interrupting', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-cont',
identifier: 'T-8',
status: 'running',
@@ -1750,7 +1750,7 @@ describe('TaskService', () => {
});
it('treats a task already gone as deleted', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-gone',
identifier: 'T-7',
status: 'backlog',
@@ -1764,7 +1764,7 @@ describe('TaskService', () => {
});
it("does not interrupt the caller's own run", async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-self',
identifier: 'T-3',
status: 'running',
@@ -1780,7 +1780,7 @@ describe('TaskService', () => {
});
it('cascades the underlying topic rows when the task row is deleted', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-topics',
identifier: 'T-9',
status: 'backlog',
@@ -1802,7 +1802,7 @@ describe('TaskService', () => {
});
it('spares the kept operation topic when a task deletes itself mid-run', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-self-topics',
identifier: 'T-12',
status: 'running',
@@ -1834,7 +1834,7 @@ describe('TaskService', () => {
});
it('deletes no topic rows when the task has none', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-bare',
identifier: 'T-10',
status: 'backlog',
@@ -1847,7 +1847,7 @@ describe('TaskService', () => {
});
it('leaves topic rows alone when the delete loses the race', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'task-race-topics',
identifier: 'T-11',
status: 'backlog',
@@ -1878,7 +1878,7 @@ describe('TaskService', () => {
it('stamps scheduleStartedAt when a user starts a schedule (backlog → scheduled)', async () => {
const prev = baseTask({ status: 'backlog', automationMode: 'schedule' });
const next = baseTask({ status: 'scheduled', automationMode: 'schedule' });
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
const service = new TaskService(db, userId);
@@ -1900,7 +1900,7 @@ describe('TaskService', () => {
// counter window — otherwise every successful tick would zero out the cap.
const prev = baseTask({ status: 'running', automationMode: 'schedule' });
const next = baseTask({ status: 'scheduled', automationMode: 'schedule' });
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
mockTaskTopicModel.findByTaskId.mockResolvedValue([]);
@@ -1922,7 +1922,7 @@ describe('TaskService', () => {
heartbeatInterval: 3600,
status: 'scheduled',
});
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
const service = new TaskService(db, userId);
@@ -1956,7 +1956,7 @@ describe('TaskService', () => {
heartbeatInterval: 3600,
status: 'scheduled',
});
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
const service = new TaskService(db, userId);
@@ -1983,7 +1983,7 @@ describe('TaskService', () => {
heartbeatInterval: 3600,
status: 'scheduled',
});
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
scheduleNextTopic.mockRejectedValueOnce(new Error('qstash unavailable'));
@@ -2012,7 +2012,7 @@ describe('TaskService', () => {
heartbeatInterval: 3600,
status: 'scheduled',
});
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateWithLog.mockResolvedValue(next);
scheduleNextTopic.mockRejectedValueOnce(new Error('qstash unavailable'));
@@ -2037,7 +2037,7 @@ describe('TaskService', () => {
it('does NOT stamp when the new status is not scheduled', async () => {
const prev = baseTask({ status: 'backlog' });
const next = baseTask({ status: 'paused' });
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
const service = new TaskService(db, userId);
@@ -2049,7 +2049,7 @@ describe('TaskService', () => {
it('stamps on user-initiated restart (paused → scheduled)', async () => {
const prev = baseTask({ status: 'paused', automationMode: 'schedule' });
const next = baseTask({ status: 'scheduled', automationMode: 'schedule' });
- mockTaskModel.resolve.mockResolvedValue(prev);
+ mockTaskModel.findById.mockResolvedValue(prev);
mockTaskModel.updateStatus.mockResolvedValue(next);
const service = new TaskService(db, userId);
@@ -2144,7 +2144,7 @@ describe('TaskService', () => {
});
it('rejects creating a public subtask under a private parent', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'parent_id',
identifier: 'T-1',
visibility: 'private',
@@ -2162,7 +2162,7 @@ describe('TaskService', () => {
});
it('allows a private subtask under a public parent', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
id: 'parent_id',
identifier: 'T-1',
visibility: 'public',
@@ -2201,7 +2201,7 @@ describe('TaskService', () => {
const openChild = baseTask({ id: 'task-c1', identifier: 'C-1', status: 'backlog' });
// Already finished: not part of the cascade, so no row.
const doneChild = baseTask({ id: 'task-c2', identifier: 'C-2', status: 'completed' });
- mockTaskModel.resolve.mockResolvedValue(parent);
+ mockTaskModel.findById.mockResolvedValue(parent);
mockTaskModel.findSubtasks.mockResolvedValue([openChild, doneChild]);
mockTaskModel.updateStatusForIds.mockResolvedValue([
{ ...parent, status: 'canceled' },
@@ -2244,7 +2244,7 @@ describe('TaskService', () => {
it('stays silent for a system cascade', async () => {
const parent = baseTask({ id: 'task-p', identifier: 'P-1', status: 'running' });
- mockTaskModel.resolve.mockResolvedValue(parent);
+ mockTaskModel.findById.mockResolvedValue(parent);
mockTaskModel.findSubtasks.mockResolvedValue([]);
mockTaskModel.updateStatusForIds.mockResolvedValue([{ ...parent, status: 'canceled' }]);
mockTaskTopicModel.cancelRunningByTaskIds.mockResolvedValue([]);
@@ -2259,7 +2259,7 @@ describe('TaskService', () => {
describe('assignee activity log', () => {
it('renders a status log as a property activity', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
createdAt: null,
heartbeatInterval: null,
heartbeatTimeout: null,
@@ -2305,7 +2305,7 @@ describe('TaskService', () => {
});
it('keeps a deleted actor as a person, not the system, via the payload tombstone', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
createdAt: null,
heartbeatInterval: null,
heartbeatTimeout: null,
@@ -2358,7 +2358,7 @@ describe('TaskService', () => {
});
it('keeps the actor identity when the agent is invisible to this viewer', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
createdAt: null,
heartbeatInterval: null,
heartbeatTimeout: null,
@@ -2550,7 +2550,7 @@ describe('TaskService', () => {
});
it('renders assignment logs as activities with both sides resolved', async () => {
- mockTaskModel.resolve.mockResolvedValue({
+ mockTaskModel.findById.mockResolvedValue({
createdAt: null,
heartbeatInterval: null,
heartbeatTimeout: null,
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index eebb126b5e2..6df54703dda 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -13,7 +13,7 @@ import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '../aiAgent';
-import { type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';
+import { displaySubtaskPlan, type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';
import { type ReviewResult, TaskReviewService } from '../taskReview';
import { TaskRunnerService } from '../taskRunner';
import { writeKeepingArchivedIdle } from './archiveGuard';
@@ -28,7 +28,7 @@ import {
type UpdateStatusCascadeResult,
type UpdateStatusResult,
} from './statusTransitions';
-import { interruptTaskOperation, resolveTaskOrThrow } from './utils';
+import { findTaskOrThrow, interruptTaskOperation } from './utils';
export type { UpdateStatusCascadeResult, UpdateStatusResult } from './statusTransitions';
@@ -65,8 +65,9 @@ export interface CreateTaskInput {
}
export interface RunReadySubtasksResult {
- failed: { error: string; identifier: string }[];
+ failed: { error: string; id?: string; identifier: string }[];
kickedOff: string[];
+ kickedOffTasks?: { id: string; identifier: string }[];
plan: SubtaskGraphPlan;
skipped?: { reason: 'nothing-runnable' };
}
@@ -121,7 +122,7 @@ export class TaskService {
let parentVisibility: 'private' | 'public' | undefined;
if (createData.parentTaskId) {
- const parent = await this.resolveOrThrow(createData.parentTaskId);
+ const parent = await this.findOrThrow(createData.parentTaskId);
createData.parentTaskId = parent.id;
parentVisibility = parent.visibility;
if (createData.projectId && createData.projectId !== parent.projectId) {
@@ -322,11 +323,8 @@ export class TaskService {
* `keepOperationId` spares the caller's own run (an agent deleting the task
* it is executing), which would otherwise interrupt itself mid-tool-call.
*/
- async deleteTask(
- idOrIdentifier: string,
- options: { keepOperationId?: string } = {},
- ): Promise<TaskItem> {
- const task = await this.resolveOrThrow(idOrIdentifier);
+ async deleteTask(taskId: string, options: { keepOperationId?: string } = {}): Promise<TaskItem> {
+ const task = await this.findOrThrow(taskId);
const runningTopics = await this.taskTopicModel.findRunningByTaskIds([task.id]);
@@ -428,7 +426,7 @@ export class TaskService {
id: string;
topicId?: string;
}): Promise<ReviewResult> {
- const task = await this.resolveOrThrow(input.id);
+ const task = await this.findOrThrow(input.id);
const reviewConfig = this.taskModel.getReviewConfig(task);
if (!reviewConfig?.enabled) {
@@ -501,23 +499,23 @@ export class TaskService {
}
/**
- * Compute the subtask execution plan for `idOrIdentifier` without
+ * Compute the subtask execution plan for `taskId` without
* actually kicking anything off.
*/
- async previewSubtaskLayers(idOrIdentifier: string): Promise<SubtaskGraphPlan> {
- const parent = await this.resolveOrThrow(idOrIdentifier);
+ async previewSubtaskLayers(taskId: string): Promise<SubtaskGraphPlan> {
+ const parent = await this.findOrThrow(taskId);
const graph = new TaskGraphService(this.db, this.userId, this.workspaceId);
- const { plan } = await graph.planForParent(parent.id);
- return plan;
+ const { plan, descendants } = await graph.planForParent(parent.id);
+ return displaySubtaskPlan(plan, descendants);
}
/**
- * Kick off the first runnable layer of subtasks under `idOrIdentifier`.
+ * Kick off the first runnable layer of subtasks under `taskId`.
* Subsequent layers fire automatically through
* `TaskRunnerService.cascadeOnCompletion` as each upstream finishes.
*/
- async runReadySubtasks(idOrIdentifier: string): Promise<RunReadySubtasksResult> {
- const parent = await this.resolveOrThrow(idOrIdentifier);
+ async runReadySubtasks(taskId: string): Promise<RunReadySubtasksResult> {
+ const parent = await this.findOrThrow(taskId);
const graph = new TaskGraphService(this.db, this.userId, this.workspaceId);
const { descendants, plan } = await graph.planForParent(parent.id);
@@ -525,26 +523,24 @@ export class TaskService {
return {
failed: [],
kickedOff: [],
- plan,
+ plan: displaySubtaskPlan(plan, descendants),
skipped: { reason: 'nothing-runnable' as const },
};
}
const firstLayer = plan.layers[0];
- const identifierToId = new Map(descendants.map((d) => [d.identifier, d.id]));
+ const byId = new Map(descendants.map((d) => [d.id, d]));
const runner = new TaskRunnerService(this.db, this.userId, this.workspaceId);
const kickedOff: string[] = [];
- const failed: { error: string; identifier: string }[] = [];
+ const failed: { error: string; id?: string; identifier: string }[] = [];
const settled = await pMap(
firstLayer,
- async (identifier): Promise<PromiseSettledResult<string>> => {
+ async (id): Promise<PromiseSettledResult<string>> => {
try {
- const id = identifierToId.get(identifier);
- if (!id) throw new Error(`Subtask ${identifier} not found`);
await runner.runTask({ taskId: id });
- return { status: 'fulfilled', value: identifier };
+ return { status: 'fulfilled', value: id };
} catch (reason) {
return { reason, status: 'rejected' };
}
@@ -553,17 +549,27 @@ export class TaskService {
);
for (const [index, result] of settled.entries()) {
- const identifier = firstLayer[index];
+ const id = firstLayer[index];
+ const identifier = byId.get(id)!.identifier;
if (result.status === 'fulfilled') {
kickedOff.push(identifier);
} else {
const message =
result.reason instanceof Error ? result.reason.message : 'Failed to start task';
- failed.push({ error: message, identifier });
+ failed.push({ error: message, id, identifier });
}
}
- return { failed, kickedOff, plan };
+ return {
+ failed,
+ kickedOff,
+ kickedOffTasks: settled.flatMap((result, index) =>
+ result.status === 'fulfilled'
+ ? [{ id: firstLayer[index], identifier: byId.get(firstLayer[index])!.identifier }]
+ : [],
+ ),
+ plan: displaySubtaskPlan(plan, descendants),
+ };
}
private async assertAssigneeAgentBelongsToUser(assigneeAgentId?: string | null): Promise<void> {
@@ -717,13 +723,11 @@ export class TaskService {
);
}
- private async resolveOrThrow(idOrIdentifier: string): Promise<TaskItem> {
- return resolveTaskOrThrow(this.deps, idOrIdentifier);
+ private async findOrThrow(taskId: string): Promise<TaskItem> {
+ return findTaskOrThrow(this.taskModel, taskId);
}
- async getTaskDetail(taskIdOrIdentifier: string): Promise<TaskDetailData | null> {
- return new TaskDetailService(this.db, this.userId, this.workspaceId).getTaskDetail(
- taskIdOrIdentifier,
- );
+ async getTaskDetail(taskId: string): Promise<TaskDetailData | null> {
+ return new TaskDetailService(this.db, this.userId, this.workspaceId).getTaskDetail(taskId);
}
}
diff --git a/apps/server/src/services/task/patchValidation.test.ts b/apps/server/src/services/task/patchValidation.test.ts
index 5aa5f393909..de74bbeb4f1 100644
--- a/apps/server/src/services/task/patchValidation.test.ts
+++ b/apps/server/src/services/task/patchValidation.test.ts
@@ -32,7 +32,7 @@ const storedTask = (id: string, overrides: Record<string, unknown> = {}) => ({
const buildContext = (rows: Record<string, Record<string, unknown>> = {}) => {
const taskModel = {
findAllDescendants: vi.fn().mockResolvedValue([]),
- findById: vi.fn().mockResolvedValue({ id: 'parent-1', projectId: 'project-1' }),
+ findById: vi.fn(async (id: string) => storedTask(id, rows[id])),
resolve: vi.fn(async (id: string) => storedTask(id, rows[id])),
};
const taskService = {
@@ -94,7 +94,10 @@ describe('resolveTaskPatchInvariants hierarchy', () => {
});
it('refuses a public child under a private parent', async () => {
- const { context, taskService } = buildContext({ 'task-1': { visibility: 'public' } });
+ const { context, taskService } = buildContext({
+ 'task-1': { visibility: 'public' },
+ 'parent-1': { visibility: 'private' },
+ });
const patch = { parentTaskId: 'parent-1' };
taskService.assertParentVisibilityCompat.mockImplementation(() => {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Subtask cannot be more public than' });
@@ -103,7 +106,7 @@ describe('resolveTaskPatchInvariants hierarchy', () => {
await expect(
resolveTaskPatchInvariants(context, { data: patch, id: 'task-1', parentTaskId: 'parent-1' }),
).rejects.toThrow('Subtask cannot be more public than');
- expect(taskService.assertParentVisibilityCompat).toHaveBeenCalledWith('public', undefined);
+ expect(taskService.assertParentVisibilityCompat).toHaveBeenCalledWith('public', 'private');
});
it('accepts clearing the parent', async () => {
@@ -139,7 +142,10 @@ describe('resolveTaskPatchInvariants assignment', () => {
});
it('refuses a private assignee agent on a public task', async () => {
- const { context, taskService } = buildContext({ 'task-1': { visibility: 'public' } });
+ const { context, taskService } = buildContext({
+ 'task-1': { visibility: 'public' },
+ 'parent-1': { visibility: 'private' },
+ });
const patch = { assigneeAgentId: 'agent-1' };
taskService.assertAgentVisibilityCompat.mockImplementation(() => {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Public task needs a public agent' });
diff --git a/apps/server/src/services/task/patchValidation.ts b/apps/server/src/services/task/patchValidation.ts
index ffe1a0d4b91..c14053d02d4 100644
--- a/apps/server/src/services/task/patchValidation.ts
+++ b/apps/server/src/services/task/patchValidation.ts
@@ -9,6 +9,7 @@ import type { TaskService } from '@/server/services/task';
import { assertArchivedTaskStaysIdle } from './archiveGuard';
import { assertResultingScheduleValid } from './scheduleValidation';
+import { findTaskOrThrow, resolveTaskOrThrow } from './utils';
/**
* The invariants a task patch must satisfy, shared by every write boundary: the
@@ -52,12 +53,6 @@ export interface TaskPatchInvariantContext {
workspaceId?: string;
}
-async function resolveOrThrow(model: TaskModel, id: string): Promise<ResolvedTask> {
- const task = await model.resolve(id);
- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
- return task;
-}
-
export async function assertAssigneeAgentBelongsToUser(
db: LobeChatDatabase,
callerCtx: { userId: string; workspaceId?: string },
@@ -86,7 +81,7 @@ async function resolveSafeParentTaskId(
): Promise<string | null> {
if (parentTaskId === null) return null;
- const parent = await resolveOrThrow(model, parentTaskId);
+ const parent = await findTaskOrThrow(model, parentTaskId);
if (parent.id === taskId) {
throw new TRPCError({
code: 'BAD_REQUEST',
@@ -102,7 +97,7 @@ async function resolveSafeParentTaskId(
});
}
- const task = await resolveOrThrow(model, taskId);
+ const task = await findTaskOrThrow(model, taskId);
if (task.projectId !== parent.projectId) {
throw new TRPCError({
code: 'BAD_REQUEST',
@@ -134,7 +129,7 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(
data.assigneeAgentId,
);
- const resolved = await resolveOrThrow(ctx.taskModel, id);
+ const resolved = await resolveTaskOrThrow(ctx.taskModel, id);
assertResultingScheduleValid(resolved, data);
assertArchivedTaskStaysIdle(resolved, data);
@@ -170,7 +165,11 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(
const resolvedParentTaskId =
parentTaskId === undefined
? undefined
- : await resolveSafeParentTaskId(ctx.taskModel, resolved.id, parentTaskId);
+ : await resolveSafeParentTaskId(
+ ctx.taskModel,
+ resolved.id,
+ parentTaskId === null ? null : (await resolveTaskOrThrow(ctx.taskModel, parentTaskId)).id,
+ );
// Reparenting a public task under a private one breaks the parent visibility
// invariant — a subtask cannot be more public than its parent (otherwise
diff --git a/apps/server/src/services/task/statusTransitions.ts b/apps/server/src/services/task/statusTransitions.ts
index 75d2db7a134..376fecd6d8f 100644
--- a/apps/server/src/services/task/statusTransitions.ts
+++ b/apps/server/src/services/task/statusTransitions.ts
@@ -13,7 +13,7 @@ import { TaskRunnerService } from '../taskRunner';
import { createTaskSchedulerModule } from '../taskScheduler';
import { assertArchivedTaskStaysIdle, writeKeepingArchivedIdle } from './archiveGuard';
import type { TaskServiceDeps } from './deps';
-import { interruptTaskOperation, resolveTaskOrThrow } from './utils';
+import { findTaskOrThrow, interruptTaskOperation } from './utils';
/** Concurrent agent-operation interrupts issued by one status cascade. */
const INTERRUPT_CONCURRENCY = 5;
@@ -25,15 +25,20 @@ export interface UpdateStatusResult {
completionDeferred?: boolean;
parentTaskId?: string | null;
paused: string[];
+ pausedTasks?: { id: string; identifier: string }[];
task: TaskItem;
unlocked: string[];
+ unlockedTasks?: { id: string; identifier: string }[];
}
export interface UpdateStatusCascadeResult {
paused: string[];
+ pausedTasks?: { id: string; identifier: string }[];
task: TaskItem;
unlocked: string[];
+ unlockedTasks?: { id: string; identifier: string }[];
updatedSubtasks: string[];
+ updatedSubtaskTasks?: { id: string; identifier: string }[];
}
/**
@@ -72,7 +77,7 @@ export async function updateStatus(
});
}
- const resolved = await resolveTaskOrThrow(deps, id);
+ const resolved = await findTaskOrThrow(deps.taskModel, id);
assertArchivedTaskStaysIdle(resolved, { status });
if (resolved.status === 'running' && status !== 'running') {
@@ -201,13 +206,15 @@ export async function updateStatus(
const unlocked: string[] = [];
const paused: string[] = [];
+ const pausedTasks: { id: string; identifier: string }[] = [];
+ const unlockedTasks: { id: string; identifier: string }[] = [];
let allSubtasksDone = false;
let checkpointTriggered = false;
if (status === 'completed') {
if (task.parentTaskId) {
const parentTask = await deps.taskModel.findById(task.parentTaskId);
- if (parentTask && deps.taskModel.shouldPauseAfterComplete(parentTask, task.identifier)) {
+ if (parentTask && deps.taskModel.shouldPauseAfterComplete(parentTask, task)) {
await deps.taskModel.updateStatus(parentTask.id, 'paused');
checkpointTriggered = true;
}
@@ -219,10 +226,14 @@ export async function updateStatus(
const cascade = await runner.cascadeOnCompletion(task.id);
unlocked.push(...cascade.started);
paused.push(...cascade.paused);
+ pausedTasks.push(...(cascade.pausedTasks ?? []));
+ unlockedTasks.push(...(cascade.startedTasks ?? []));
}
return {
paused,
+ pausedTasks,
+ unlockedTasks,
task,
unlocked,
...(checkpointTriggered && { checkpointTriggered: true }),
@@ -245,7 +256,7 @@ export async function updateStatusCascade(
/** The person confirming "include subtasks"; absent for system callers. */
actor?: { agentId?: string | null; userId?: string | null },
): Promise<UpdateStatusCascadeResult> {
- const resolved = await resolveTaskOrThrow(deps, input.id);
+ const resolved = await findTaskOrThrow(deps.taskModel, input.id);
const subtasks = await deps.taskModel.findSubtasks(resolved.id);
const unfinishedStatuses = new Set<string>(UNFINISHED_TASK_STATUSES);
const openSubtasks = subtasks.filter((task) => unfinishedStatuses.has(task.status));
@@ -344,17 +355,26 @@ export async function updateStatusCascade(
const unlocked: string[] = [];
const paused: string[] = [];
+ const pausedTasks: { id: string; identifier: string }[] = [];
+ const unlockedTasks: { id: string; identifier: string }[] = [];
if (input.status === 'completed') {
const runner = new TaskRunnerService(deps.db, deps.userId, deps.workspaceId);
const cascade = await runner.cascadeOnCompletionMany(updatedTasks.map(({ id }) => id));
unlocked.push(...cascade.started);
paused.push(...cascade.paused);
+ pausedTasks.push(...(cascade.pausedTasks ?? []));
+ unlockedTasks.push(...(cascade.startedTasks ?? []));
}
return {
paused,
+ pausedTasks,
+ unlockedTasks,
task,
unlocked,
+ updatedSubtaskTasks: updatedTasks
+ .filter(({ parentTaskId }) => parentTaskId === resolved.id)
+ .map(({ id, identifier }) => ({ id, identifier })),
updatedSubtasks: updatedTasks
.filter(({ parentTaskId }) => parentTaskId === resolved.id)
.map(({ identifier }) => identifier),
diff --git a/apps/server/src/services/task/utils.checkpoint.test.ts b/apps/server/src/services/task/utils.checkpoint.test.ts
new file mode 100644
index 00000000000..202a3a2fbda
--- /dev/null
+++ b/apps/server/src/services/task/utils.checkpoint.test.ts
@@ -0,0 +1,43 @@
+import type { CheckpointConfig } from '@lobechat/types';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { normalizeCheckpointTaskRefs } from './utils';
+
+afterEach(() => vi.restoreAllMocks());
+describe('normalizeCheckpointTaskRefs', () => {
+ it('preserves a consistent round-trip without a task lookup, including original order', async () => {
+ const model = new TaskModel({} as LobeChatDatabase, 'user');
+ const resolve = vi.spyOn(model, 'resolveRefs');
+ const checkpoint: CheckpointConfig = {
+ tasks: {
+ beforeIds: ['OLD-1', 'OLD-2', 'OLD-1'],
+ beforeTasks: [
+ { id: 'task_2', identifier: 'OLD-2' },
+ { id: 'task_1', identifier: 'OLD-1' },
+ ],
+ },
+ };
+ const result = await normalizeCheckpointTaskRefs(model, checkpoint);
+ expect(result).toEqual(checkpoint);
+ expect(result.tasks?.beforeTasks).toBe(checkpoint.tasks?.beforeTasks);
+ expect(result.tasks?.beforeIds).toBe(checkpoint.tasks?.beforeIds);
+ expect(resolve).not.toHaveBeenCalled();
+ });
+ it('clears stale pairs alongside an explicitly emptied list', async () => {
+ const model = new TaskModel({} as LobeChatDatabase, 'user');
+ vi.spyOn(model, 'resolveRefs').mockResolvedValue({
+ ambiguous: [],
+ missing: [],
+ byRef: new Map(),
+ tasks: [],
+ });
+ expect(
+ await normalizeCheckpointTaskRefs(model, {
+ tasks: { beforeIds: [], beforeTasks: [{ id: 'task_1', identifier: 'T-1' }] },
+ }),
+ ).toEqual({ tasks: { beforeIds: [], beforeTasks: [] } });
+ });
+});
diff --git a/apps/server/src/services/task/utils.ts b/apps/server/src/services/task/utils.ts
index c0bde0f5826..f532e7184c9 100644
--- a/apps/server/src/services/task/utils.ts
+++ b/apps/server/src/services/task/utils.ts
@@ -1,5 +1,9 @@
-import type { TaskItem } from '@lobechat/types';
+import type { CheckpointConfig, TaskItem } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
+import isEqual from 'fast-deep-equal';
+
+import { checkpointTaskPairsMatch } from '@/database/models/task/checkpoint';
import type { AiAgentService } from '../aiAgent';
import type { TaskServiceDeps } from './deps';
@@ -16,10 +20,111 @@ export const interruptTaskOperation = async (service: AiAgentService, operationI
};
export async function resolveTaskOrThrow(
- deps: Pick<TaskServiceDeps, 'taskModel'>,
- idOrIdentifier: string,
+ taskModel: TaskServiceDeps['taskModel'],
+ ref: string,
): Promise<TaskItem> {
- const task = await deps.taskModel.resolve(idOrIdentifier);
+ if (!ref.trim())
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Task reference must not be empty' });
+ try {
+ const task = await taskModel.resolve(ref);
+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
+ return task;
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith('Ambiguous task reference:'))
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ throw error;
+ }
+}
+
+export async function resolveTasksOrThrow(
+ taskModel: TaskServiceDeps['taskModel'],
+ refs: string[],
+ options: { duplicates: 'collapse' | 'reject' },
+) {
+ if (refs.some((ref) => !ref.trim()))
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Task reference must not be empty' });
+ const result = await taskModel.resolveRefs(refs);
+ if (result.ambiguous.length)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Ambiguous task references: ${result.ambiguous.join(', ')}`,
+ });
+ if (result.missing.length)
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Task not found: ${result.missing.join(', ')}`,
+ });
+ if (options.duplicates === 'reject' && result.tasks.length !== refs.length) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Duplicate task references' });
+ }
+ return result;
+}
+
+/** Domain reads accept only canonical ids, preserving ownership and NOT_FOUND. */
+export async function findTaskOrThrow(taskModel: TaskServiceDeps['taskModel'], taskId: string) {
+ const task = await taskModel.findById(taskId);
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
return task;
}
+
+/** Input-only normalization; historical config is never reinterpreted on read. */
+export async function normalizeCheckpointTaskRefs(
+ taskModel: TaskServiceDeps['taskModel'],
+ checkpoint: CheckpointConfig,
+ previous?: CheckpointConfig,
+) {
+ if (!checkpoint.tasks) return checkpoint;
+ const tasks = { ...checkpoint.tasks };
+ const pending = (
+ [
+ ['beforeIds', 'beforeTasks'],
+ ['afterIds', 'afterTasks'],
+ ] as const
+ ).filter(
+ ([idsKey, pairsKey]) =>
+ tasks[idsKey] !== undefined &&
+ !checkpointTaskPairsMatch(tasks[idsKey], tasks[pairsKey]) &&
+ // Whole-config round trips must not reinterpret unchanged legacy selections.
+ // They can contain deleted tasks or exact historical values that never matched.
+ !(
+ tasks[pairsKey] === undefined &&
+ previous?.tasks?.[pairsKey] === undefined &&
+ isEqual(tasks[idsKey], previous?.tasks?.[idsKey])
+ ),
+ );
+ if (!pending.length) return checkpoint;
+ const resolved = await resolveTasksOrThrow(
+ taskModel,
+ pending.flatMap(([idsKey]) => tasks[idsKey]!),
+ { duplicates: 'collapse' },
+ );
+ for (const [idsKey, pairsKey] of pending) {
+ const selected = [
+ ...new Map(
+ tasks[idsKey]!.map((ref) => {
+ const task = resolved.byRef.get(ref)!;
+ return [task.id, task] as const;
+ }),
+ ).values(),
+ ];
+ tasks[idsKey] = selected.map((task) => task.identifier);
+ tasks[pairsKey] = selected.map(({ id, identifier }) => ({ id, identifier }));
+ }
+ return { ...checkpoint, tasks };
+}
+
+export async function normalizeTaskConfig(
+ taskModel: TaskServiceDeps['taskModel'],
+ config: Record<string, unknown> | undefined,
+ previous?: unknown,
+) {
+ if (!config?.checkpoint) return config;
+ return {
+ ...config,
+ checkpoint: await normalizeCheckpointTaskRefs(
+ taskModel,
+ config.checkpoint as CheckpointConfig,
+ isRecord(previous) ? (previous.checkpoint as CheckpointConfig | undefined) : undefined,
+ ),
+ };
+}
diff --git a/apps/server/src/services/taskGraph/index.stableId.test.ts b/apps/server/src/services/taskGraph/index.stableId.test.ts
new file mode 100644
index 00000000000..0f5d7e49302
--- /dev/null
+++ b/apps/server/src/services/taskGraph/index.stableId.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { planSubtaskLayers } from './index';
+
+describe('subtask graph identity', () => {
+ it('keeps distinct ids separate even if their display identifiers collide', () => {
+ const plan = planSubtaskLayers([
+ { id: 'task_old', identifier: 'T-1', status: 'completed', dependsOn: [] },
+ { id: 'task_new', identifier: 'T-1', status: 'backlog', dependsOn: [] },
+ { id: 'task_child', identifier: 'T-2', status: 'backlog', dependsOn: ['task_old'] },
+ ]);
+ expect(plan.alreadyDone).toEqual(['task_old']);
+ expect(plan.layers).toEqual([['task_child', 'task_new']]);
+ });
+});
diff --git a/apps/server/src/services/taskGraph/index.test.ts b/apps/server/src/services/taskGraph/index.test.ts
index 175c3b7fa17..3630a1af9fb 100644
--- a/apps/server/src/services/taskGraph/index.test.ts
+++ b/apps/server/src/services/taskGraph/index.test.ts
@@ -4,6 +4,7 @@ import { planSubtaskLayers, type SubtaskNode } from './index';
const node = (identifier: string, status: string, dependsOn: string[] = []): SubtaskNode => ({
dependsOn,
+ id: identifier,
identifier,
status,
});
diff --git a/apps/server/src/services/taskGraph/index.ts b/apps/server/src/services/taskGraph/index.ts
index 51630f7e6cd..28c7a687883 100644
--- a/apps/server/src/services/taskGraph/index.ts
+++ b/apps/server/src/services/taskGraph/index.ts
@@ -21,8 +21,10 @@ const UNKNOWN_STATUS = '__unknown__';
export interface SubtaskGraphPlan {
/** Tasks that already finished (completed / canceled) and are skipped. */
alreadyDone: string[];
+ alreadyDoneTasks?: { id: string; identifier: string }[];
/** Tasks blocked by an unbroken cycle and therefore unreachable. */
blockedByCycle: string[];
+ blockedByCycleTasks?: { id: string; identifier: string }[];
/**
* Tasks waiting on a dependency we cannot satisfy in this batch — either an
* in-flight task (running / scheduled / etc.) or a task outside this subtree.
@@ -31,16 +33,20 @@ export interface SubtaskGraphPlan {
* layer.
*/
blockedExternally: string[];
+ blockedExternallyTasks?: { id: string; identifier: string }[];
/** Identifiers participating in at least one dependency cycle. */
cycles: string[];
+ cyclesTasks?: { id: string; identifier: string }[];
/**
* Descendants whose own state excludes them from this batch (running /
* scheduled / archived / etc.). Distinct from `blockedExternally`, which describes a
* runnable task held back by *some other* task.
*/
ineligible: string[];
+ ineligibleTasks?: { id: string; identifier: string }[];
/** Topologically sorted layers of runnable tasks. Layer N waits on layer N-1. */
layers: string[][];
+ layerTasks?: { id: string; identifier: string }[][];
/** Total runnable tasks across all layers. */
totalRunnable: number;
}
@@ -50,6 +56,7 @@ export interface SubtaskNode {
archived?: boolean;
/** Tasks this one depends on (must be `completed` first). */
dependsOn: string[];
+ id: string;
identifier: string;
status: string;
}
@@ -77,27 +84,27 @@ export const planSubtaskLayers = (
const alreadyDone: string[] = [];
const ineligible: string[] = [];
const runnableSet = new Set<string>();
- const statusByIdentifier = new Map<string, string>();
+ const statusById = new Map<string, string>();
for (const node of nodes) {
- statusByIdentifier.set(node.identifier, node.status);
+ statusById.set(node.id, node.status);
if (TERMINAL_STATUSES.has(node.status)) {
- alreadyDone.push(node.identifier);
+ alreadyDone.push(node.id);
} else if (RUNNABLE_STATUSES.has(node.status) && !node.archived) {
- runnableSet.add(node.identifier);
+ runnableSet.add(node.id);
} else {
- ineligible.push(node.identifier);
+ ineligible.push(node.id);
}
}
- const resolveDepStatus = (depIdentifier: string): string =>
- statusByIdentifier.get(depIdentifier) ?? externalStatuses.get(depIdentifier) ?? UNKNOWN_STATUS;
+ const resolveDepStatus = (depId: string): string =>
+ statusById.get(depId) ?? externalStatuses.get(depId) ?? UNKNOWN_STATUS;
type EdgeKind = 'satisfied' | 'in-batch' | 'external';
- const classifyEdge = (depIdentifier: string): EdgeKind => {
- const status = resolveDepStatus(depIdentifier);
+ const classifyEdge = (depId: string): EdgeKind => {
+ const status = resolveDepStatus(depId);
if (TERMINAL_STATUSES.has(status)) return 'satisfied';
- if (runnableSet.has(depIdentifier)) return 'in-batch';
+ if (runnableSet.has(depId)) return 'in-batch';
// Runnable status outside this batch, in-flight (running/scheduled), or
// unknown — all block until something else completes them.
return 'external';
@@ -113,17 +120,17 @@ export const planSubtaskLayers = (
}
for (const node of nodes) {
- if (!runnableSet.has(node.identifier)) continue;
+ if (!runnableSet.has(node.id)) continue;
for (const dep of node.dependsOn) {
const kind = classifyEdge(dep);
if (kind === 'satisfied') continue;
if (kind === 'external') {
- externallyBlocked.add(node.identifier);
+ externallyBlocked.add(node.id);
continue;
}
// in-batch
- inBatchUpstream.get(node.identifier)!.push(dep);
- inBatchDownstream.get(dep)!.push(node.identifier);
+ inBatchUpstream.get(node.id)!.push(dep);
+ inBatchDownstream.get(dep)!.push(node.id);
}
}
@@ -260,51 +267,56 @@ export class TaskGraphService {
const ids = descendants.map((d) => d.id);
const deps = await this.taskModel.getDependenciesByTaskIds(ids);
- const idToIdentifier = new Map(descendants.map((d) => [d.id, d.identifier]));
-
- // Fetch upstream tasks referenced by `blocks` deps that aren't in this
- // subtree, so we know whether they're done or still in flight.
- const externalUpstreamIds = new Set<string>();
- for (const dep of deps) {
- if (dep.type !== 'blocks') continue;
- if (!idToIdentifier.has(dep.dependsOnId)) externalUpstreamIds.add(dep.dependsOnId);
- }
- const externalUpstreams =
- externalUpstreamIds.size > 0 ? await this.taskModel.findByIds([...externalUpstreamIds]) : [];
- const allIdToIdentifier = new Map(idToIdentifier);
- const externalStatusByIdentifier = new Map<string, string>();
- for (const upstream of externalUpstreams) {
- allIdToIdentifier.set(upstream.id, upstream.identifier);
- externalStatusByIdentifier.set(upstream.identifier, upstream.status);
- }
-
- const dependsOnByIdentifier = new Map<string, string[]>();
+ const descendantIds = new Set(ids);
+ const externalIds = [
+ ...new Set(
+ deps
+ .filter((dep) => dep.type === 'blocks' && !descendantIds.has(dep.dependsOnId))
+ .map((dep) => dep.dependsOnId),
+ ),
+ ];
+ const upstreams = externalIds.length ? await this.taskModel.findByIds(externalIds) : [];
+ const externalStatuses = new Map(upstreams.map((task) => [task.id, task.status]));
+ const knownIds = new Set([...ids, ...upstreams.map((task) => task.id)]);
+ const dependsOnById = new Map<string, string[]>();
let missingCounter = 0;
for (const dep of deps) {
- if (dep.type !== 'blocks') continue;
- const taskIdentifier = idToIdentifier.get(dep.taskId);
- if (!taskIdentifier) continue;
-
- let upstreamIdentifier = allIdToIdentifier.get(dep.dependsOnId);
- if (!upstreamIdentifier) {
- // Upstream task no longer exists. Synthesize a placeholder identifier
- // (with no recorded status) so the dependent is treated as externally
- // blocked rather than silently freed.
- upstreamIdentifier = `__missing:${missingCounter++}`;
- }
-
- const list = dependsOnByIdentifier.get(taskIdentifier) ?? [];
- list.push(upstreamIdentifier);
- dependsOnByIdentifier.set(taskIdentifier, list);
+ if (dep.type !== 'blocks' || !descendantIds.has(dep.taskId)) continue;
+ const list = dependsOnById.get(dep.taskId) ?? [];
+ list.push(knownIds.has(dep.dependsOnId) ? dep.dependsOnId : `__missing:${missingCounter++}`);
+ dependsOnById.set(dep.taskId, list);
}
-
- const nodes: SubtaskNode[] = descendants.map((d) => ({
- archived: !!d.archivedAt,
- dependsOn: dependsOnByIdentifier.get(d.identifier) ?? [],
- identifier: d.identifier,
- status: d.status,
+ const nodes = descendants.map((task) => ({
+ archived: !!task.archivedAt,
+ dependsOn: dependsOnById.get(task.id) ?? [],
+ id: task.id,
+ identifier: task.identifier,
+ status: task.status,
}));
- return { descendants, plan: planSubtaskLayers(nodes, externalStatusByIdentifier) };
+ return { descendants, plan: planSubtaskLayers(nodes, externalStatuses) };
}
}
+
+/** Keep identifier outputs for older clients, adding stable references alongside. */
+export const displaySubtaskPlan = (plan: SubtaskGraphPlan, descendants: TaskItem[]) => {
+ const byId = new Map(descendants.map((task) => [task.id, task]));
+ const tasks = (ids: string[]) =>
+ ids.map((id) => ({ id, identifier: byId.get(id)?.identifier ?? id }));
+ const identifiers = (ids: string[]) => tasks(ids).map((task) => task.identifier);
+ return {
+ alreadyDone: identifiers(plan.alreadyDone),
+ alreadyDoneTasks: tasks(plan.alreadyDone),
+ blockedByCycle: identifiers(plan.blockedByCycle),
+ blockedByCycleTasks: tasks(plan.blockedByCycle),
+ blockedExternally: identifiers(plan.blockedExternally),
+ blockedExternallyTasks: tasks(plan.blockedExternally),
+ cycles: identifiers(plan.cycles),
+ cyclesTasks: tasks(plan.cycles),
+ ineligible: identifiers(plan.ineligible),
+ ineligibleTasks: tasks(plan.ineligible),
+ layers: plan.layers.map(identifiers),
+ layerTasks: plan.layers.map(tasks),
+ totalRunnable: plan.totalRunnable,
+ };
+};
diff --git a/apps/server/src/services/taskLifecycle/failStuckTasks.ts b/apps/server/src/services/taskLifecycle/failStuckTasks.ts
index 07ab87d4aeb..2c5d041df22 100644
--- a/apps/server/src/services/taskLifecycle/failStuckTasks.ts
+++ b/apps/server/src/services/taskLifecycle/failStuckTasks.ts
@@ -18,9 +18,14 @@ const log = debug('lobe-server:task:fail-stuck-tasks');
*/
export const failStuckTasks = async (
db: LobeChatDatabase,
-): Promise<{ checked: number; failed: string[] }> => {
+): Promise<{
+ checked: number;
+ failed: string[];
+ failedTasks: { id: string; identifier: string }[];
+}> => {
const stuckTasks = await TaskModel.findStuckTasks(db);
const failed: string[] = [];
+ const failedTasks: { id: string; identifier: string }[] = [];
for (const task of stuckTasks) {
const workspaceId = task.workspaceId ?? undefined;
@@ -45,7 +50,8 @@ export const failStuckTasks = async (
);
failed.push(task.identifier);
+ failedTasks.push({ id: task.id, identifier: task.identifier });
}
- return { checked: stuckTasks.length, failed };
+ return { checked: stuckTasks.length, failed, failedTasks };
};
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 8a0a4d5ea25..8d0f0cb7cc4 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -554,7 +554,7 @@ export class TaskLifecycleService {
if (completedTask.parentTaskId) {
const parentTask = await this.taskModel.findById(completedTask.parentTaskId);
- if (parentTask && this.taskModel.shouldPauseAfterComplete(parentTask, task.identifier)) {
+ if (parentTask && this.taskModel.shouldPauseAfterComplete(parentTask, task)) {
await this.taskModel.updateStatus(parentTask.id, 'paused');
}
}
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index b9297255467..6bb22246785 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -299,10 +299,11 @@ export async function buildTaskPrompt(
? await taskModel.getDependenciesByTaskIds(subtaskIds).catch(() => [])
: [];
const subtaskIdToIdentifier = new Map(subtasks.map((s: any) => [s.id, s.identifier]));
- const subtaskDepMap = new Map<string, string>();
+ const subtaskDepMap = new Map<string, { id: string; identifier: string }>();
for (const dep of subtaskDeps as any[]) {
const depIdentifier = subtaskIdToIdentifier.get(dep.dependsOnId);
- if (depIdentifier) subtaskDepMap.set(dep.taskId, depIdentifier);
+ if (depIdentifier)
+ subtaskDepMap.set(dep.taskId, { id: dep.dependsOnId, identifier: depIdentifier });
}
const depTaskIds = [...new Set(dependencies.map((d: any) => d.dependsOnId))];
@@ -312,11 +313,14 @@ export async function buildTaskPrompt(
let parentIdentifier: string | null = null;
let parentTaskContext:
| {
+ id: string;
identifier: string;
instruction: string;
name?: string | null;
subtasks?: Array<{
blockedBy?: string;
+ blockedById?: string;
+ id: string;
identifier: string;
name?: string | null;
priority?: number | null;
@@ -336,18 +340,21 @@ export async function buildTaskPrompt(
? await taskModel.getDependenciesByTaskIds(siblingIds).catch(() => [])
: [];
const siblingIdToIdentifier = new Map(siblings.map((s: any) => [s.id, s.identifier]));
- const siblingDepMap = new Map<string, string>();
+ const siblingDepMap = new Map<string, { id: string; identifier: string }>();
for (const dep of siblingDeps as any[]) {
const depId = siblingIdToIdentifier.get(dep.dependsOnId);
- if (depId) siblingDepMap.set(dep.taskId, depId);
+ if (depId) siblingDepMap.set(dep.taskId, { id: dep.dependsOnId, identifier: depId });
}
parentTaskContext = {
+ id: parent.id,
identifier: parent.identifier,
instruction: parent.instruction,
name: parent.name,
subtasks: siblings.map((s: any) => ({
- blockedBy: siblingDepMap.get(s.id),
+ id: s.id,
+ blockedBy: siblingDepMap.get(s.id)?.identifier,
+ blockedById: siblingDepMap.get(s.id)?.id,
identifier: s.identifier,
name: s.name,
priority: s.priority,
@@ -461,6 +468,7 @@ export async function buildTaskPrompt(
automationMode: task.automationMode,
dependencies: dependencies.map((d: any) => ({
dependsOn: depIdToIdentifier.get(d.dependsOnId) ?? d.dependsOnId,
+ dependsOnId: d.dependsOnId,
type: d.type,
})),
description: task.description,
@@ -471,6 +479,7 @@ export async function buildTaskPrompt(
instruction: task.instruction,
name: task.name,
parentIdentifier,
+ parentTaskId: task.parentTaskId,
priority: task.priority,
review: taskModel.getReviewConfig(task) as any,
schedulePattern: task.schedulePattern,
@@ -485,7 +494,9 @@ export async function buildTaskPrompt(
}
: undefined,
subtasks: subtasks.map((s: any) => ({
- blockedBy: subtaskDepMap.get(s.id),
+ id: s.id,
+ blockedBy: subtaskDepMap.get(s.id)?.identifier,
+ blockedById: subtaskDepMap.get(s.id)?.id,
identifier: s.identifier,
name: s.name,
priority: s.priority,
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 070e429a35e..68f0a2c77f6 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -109,7 +109,7 @@ export class TaskRunnerService {
async runTask(params: RunTaskParams): Promise<RunTaskResult> {
const {
additionalPluginIds,
- taskId: idOrIdentifier,
+ taskId,
continueTopicId,
deviceId,
extraPrompt,
@@ -118,7 +118,7 @@ export class TaskRunnerService {
trigger = 'manual',
} = params;
- const task = await this.taskModel.resolve(idOrIdentifier);
+ const task = await this.taskModel.findById(taskId);
if (!task) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
}
@@ -450,7 +450,7 @@ export class TaskRunnerService {
} catch (error) {
if (weSetRunning) {
try {
- const failedTask = await this.taskModel.resolve(idOrIdentifier);
+ const failedTask = await this.taskModel.findById(taskId);
if (failedTask && failedTask.status === 'running') {
const errorText = error instanceof Error ? error.message : 'Unknown error';
// A failed kickoff must not kill an automation task's schedule: the
@@ -480,7 +480,7 @@ export class TaskRunnerService {
* payload shape unchanged.
*/
static cascadeEmpty(): CascadeResult {
- return { failed: [], paused: [], started: [] };
+ return { failed: [], paused: [], started: [], pausedTasks: [], startedTasks: [] };
}
/**
@@ -509,7 +509,7 @@ export class TaskRunnerService {
const unlocked = await this.taskModel.getUnlockedTasksForMany(completedTaskIds);
if (unlocked.length === 0) return TaskRunnerService.cascadeEmpty();
- const result: CascadeResult = { failed: [], paused: [], started: [] };
+ const result: CascadeResult = TaskRunnerService.cascadeEmpty();
for (const task of unlocked) {
// An archived dependent stays idle; restoring it leaves it ready to run.
@@ -517,12 +517,14 @@ export class TaskRunnerService {
if (await this.shouldHoldForCheckpoint(task)) {
await this.taskModel.updateStatus(task.id, 'paused');
result.paused.push(task.identifier);
+ result.pausedTasks!.push({ id: task.id, identifier: task.identifier });
continue;
}
try {
await this.runTask({ taskId: task.id });
result.started.push(task.identifier);
+ result.startedTasks!.push({ id: task.id, identifier: task.identifier });
} catch (error) {
// Archived after discovery: the runner refused it, nothing failed.
if (error instanceof TRPCError && error.code === 'PRECONDITION_FAILED') continue;
@@ -534,7 +536,7 @@ export class TaskRunnerService {
} catch {
/* ignore — surfaced via failed list */
}
- result.failed.push({ error: message, identifier: task.identifier });
+ result.failed.push({ error: message, id: task.id, identifier: task.identifier });
}
}
@@ -545,15 +547,17 @@ export class TaskRunnerService {
if (!task.parentTaskId) return false;
const parent = await this.taskModel.findById(task.parentTaskId);
if (!parent) return false;
- return this.taskModel.shouldPauseBeforeStart(parent, task.identifier);
+ return this.taskModel.shouldPauseBeforeStart(parent, task);
}
}
export interface CascadeResult {
/** Tasks where kickoff threw and were marked paused with an error. */
- failed: { error: string; identifier: string }[];
+ failed: { error: string; id?: string; identifier: string }[];
/** Tasks held back by a parent's `beforeIds` checkpoint. */
paused: string[];
+ pausedTasks?: { id: string; identifier: string }[];
/** Tasks that were successfully kicked off (topic created). */
started: string[];
+ startedTasks?: { id: string; identifier: string }[];
}
diff --git a/apps/server/src/services/taskRunner/runTask.archiveRace.test.ts b/apps/server/src/services/taskRunner/runTask.archiveRace.test.ts
index 4c99b8b6d68..efa346776d0 100644
--- a/apps/server/src/services/taskRunner/runTask.archiveRace.test.ts
+++ b/apps/server/src/services/taskRunner/runTask.archiveRace.test.ts
@@ -60,7 +60,7 @@ describe('TaskRunnerService.runTask vs. archiving', () => {
findById: vi.fn().mockResolvedValue({ ...task, status: 'running' }),
getUnlockedTasksForMany: vi.fn().mockResolvedValue([]),
lockForUpdate: vi.fn().mockResolvedValue(true),
- resolve: vi.fn().mockResolvedValue({ ...task }),
+ findById: vi.fn().mockResolvedValue({ ...task }),
update: vi.fn(),
updateCurrentTopic: vi.fn(),
updateHeartbeat: vi.fn(),
@@ -87,7 +87,7 @@ describe('TaskRunnerService.runTask vs. archiving', () => {
});
it('refuses an archived task before touching its status', async () => {
- taskModel.resolve.mockResolvedValue({ ...task, archivedAt: new Date() });
+ taskModel.findById.mockResolvedValue({ ...task, archivedAt: new Date() });
await expect(
new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' }),
@@ -125,7 +125,7 @@ describe('TaskRunnerService.runTask vs. archiving', () => {
const result = await new TaskRunnerService(db, 'user-1').cascadeOnCompletionMany(['task-0']);
- expect(result).toEqual({ failed: [], paused: [], started: [] });
+ expect(result).toMatchObject({ failed: [], paused: [], started: [] });
expect(taskModel.updateStatus).not.toHaveBeenCalled();
expect(mocks.execAgent).not.toHaveBeenCalled();
});
@@ -133,7 +133,7 @@ describe('TaskRunnerService.runTask vs. archiving', () => {
it('treats a dependent archived after discovery as skipped, not failed', async () => {
taskModel.getUnlockedTasksForMany.mockResolvedValue([{ ...task, id: 'task-2' }]);
// The runner re-reads the task and finds it archived.
- taskModel.resolve.mockResolvedValue({ ...task, archivedAt: new Date(), id: 'task-2' });
+ taskModel.findById.mockResolvedValue({ ...task, archivedAt: new Date(), id: 'task-2' });
const result = await new TaskRunnerService(db, 'user-1').cascadeOnCompletionMany(['task-0']);
diff --git a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
index b5cfa6e8f49..f2b1543658a 100644
--- a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
+++ b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
@@ -59,9 +59,11 @@ describe('TaskRunnerService.runTask vs. a concurrent delete', () => {
getCheckpointConfig: vi.fn().mockReturnValue({}),
getReviewConfig: vi.fn().mockReturnValue(undefined),
incrementTopicCount: vi.fn(),
- findById: vi.fn().mockResolvedValue({ ...task, status: 'running' }),
+ findById: vi
+ .fn()
+ .mockResolvedValueOnce({ ...task })
+ .mockResolvedValue({ ...task, status: 'running' }),
lockForUpdate: vi.fn().mockResolvedValue(true),
- resolve: vi.fn().mockResolvedValue({ ...task }),
update: vi.fn(),
updateCurrentTopic: vi.fn(),
updateHeartbeat: vi.fn(),
diff --git a/apps/server/src/services/taskRunner/runTask.modelSnapshot.test.ts b/apps/server/src/services/taskRunner/runTask.modelSnapshot.test.ts
index fca6a4385f2..2134b4ee58c 100644
--- a/apps/server/src/services/taskRunner/runTask.modelSnapshot.test.ts
+++ b/apps/server/src/services/taskRunner/runTask.modelSnapshot.test.ts
@@ -52,12 +52,14 @@ describe('TaskRunnerService.runTask model snapshot backfill', () => {
totalTopics: 0,
};
taskModel = {
- findById: vi.fn().mockResolvedValue({ ...task, status: 'running' }),
+ findById: vi
+ .fn()
+ .mockResolvedValueOnce({ ...task })
+ .mockResolvedValue({ ...task, status: 'running' }),
getCheckpointConfig: vi.fn().mockReturnValue({}),
getReviewConfig: vi.fn().mockReturnValue(undefined),
incrementTopicCount: vi.fn(),
lockForUpdate: vi.fn().mockResolvedValue(true),
- resolve: vi.fn().mockResolvedValue({ ...task }),
update: vi.fn(),
updateCurrentTopic: vi.fn(),
updateHeartbeat: vi.fn(),
diff --git a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts
index cacd64bc380..14c78ff7b13 100644
--- a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts
@@ -476,7 +476,7 @@ describe('BuiltinToolsExecutor manifest-driven Work registration', () => {
expect(result.workRegistration).toEqual({
action: 'create',
changeType: 'created',
- targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ targets: [{ taskId: 'task_1', taskIdentifier: undefined }],
type: 'task',
});
});
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 31d489946f1..fd86ad32033 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -212,7 +212,9 @@ describe('createTaskRuntime', () => {
agentId: 'agt-manager',
taskCaller: taskCaller as any,
taskId: 'T-1',
- taskModel: {} as any,
+ taskModel: {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ } as any,
taskService: {} as any,
});
@@ -222,9 +224,9 @@ describe('createTaskRuntime', () => {
expect(taskCaller.addComment).toHaveBeenCalledWith({
authorAgentId: 'agt-manager',
content: 'Keep the original parent.',
- id: 'T-1',
+ id: 'task-1',
});
- expect(result.content).toBe('Comment added to task T-1.');
+ expect(result.content).toBe('Comment added to task T-1 (id: task-1).');
});
it('updates and deletes comments by commentId', async () => {
@@ -235,7 +237,9 @@ describe('createTaskRuntime', () => {
const runtime = createTaskRuntime({
agentModel: { existsById: vi.fn() } as any,
taskCaller: taskCaller as any,
- taskModel: {} as any,
+ taskModel: {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ } as any,
taskService: {} as any,
});
@@ -703,7 +707,7 @@ describe('createTaskRuntime', () => {
expect(deps.taskModel.update).not.toHaveBeenCalled();
});
- it('delegates parentIdentifier to router update for resolution and safety validation', async () => {
+ it('resolves parentIdentifier before the router update and safety validation', async () => {
const deps = makeDeps();
const runtime = createTaskRuntime({
@@ -714,13 +718,20 @@ describe('createTaskRuntime', () => {
taskService: deps.taskService as any,
});
+ deps.taskModel.resolve.mockImplementation(async (ref) => ({
+ id: ref === 'T-43' ? 'task-43' : 'task-1',
+ identifier: ref,
+ }));
const result = await runtime.editTask({
identifier: 'T-1',
parentIdentifier: 'T-43',
});
expect(result.success).toBe(true);
- expect(deps.taskCaller.update).toHaveBeenCalledWith({ id: 'task-1', parentTaskId: 'T-43' });
+ expect(deps.taskCaller.update).toHaveBeenCalledWith({
+ id: 'task-1',
+ parentTaskId: 'task-43',
+ });
expect(deps.taskModel.update).not.toHaveBeenCalled();
expect(result.content).toContain('parent → T-43');
});
@@ -798,7 +809,9 @@ describe('createTaskRuntime', () => {
agentId: 'agt-xyz',
scope: 'task',
taskCaller: taskCaller as any,
- taskModel: {} as any,
+ taskModel: {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ } as any,
taskService: {} as any,
});
@@ -867,8 +880,8 @@ describe('createTaskRuntime', () => {
expect(result.state).toEqual({
failed: 0,
results: [
- { error: undefined, identifier: 'T-A', name: 'A', success: true },
- { error: undefined, identifier: 'T-B', name: 'B', success: true },
+ { error: undefined, taskId: 'db-A', identifier: 'T-A', name: 'A', success: true },
+ { error: undefined, taskId: 'db-B', identifier: 'T-B', name: 'B', success: true },
],
succeeded: 2,
});
@@ -1103,12 +1116,14 @@ describe('createTaskRuntime', () => {
it('handles status-only updates', async () => {
const taskCaller = {
- updateStatus: vi.fn().mockResolvedValue({ data: { identifier: 'T-1' } }),
+ updateStatus: vi.fn().mockResolvedValue({ data: { id: 'task-1', identifier: 'T-1' } }),
};
const runtime = createTaskRuntime({
agentModel: { existsById: vi.fn() } as any,
taskCaller: taskCaller as any,
- taskModel: {} as any,
+ taskModel: {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ } as any,
taskService: {} as any,
});
@@ -1117,7 +1132,7 @@ describe('createTaskRuntime', () => {
expect(result.success).toBe(true);
expect(taskCaller.updateStatus).toHaveBeenCalledWith({
error: undefined,
- id: 'T-1',
+ id: 'task-1',
status: 'completed',
});
});
@@ -1146,90 +1161,6 @@ describe('createTaskRuntime', () => {
expect(taskCaller.updateStatus).not.toHaveBeenCalled();
});
});
-
- describe('runTask / runTasks', () => {
- it('forwards identifier + prompt + continueTopicId to taskCaller.run', async () => {
- const taskCaller = {
- run: vi.fn().mockResolvedValue({ operationId: 'op_1', topicId: 'tpc_1' }),
- };
- const runtime = createTaskRuntime({
- agentModel: { existsById: vi.fn() } as any,
- taskCaller: taskCaller as any,
- taskModel: {} as any,
- taskService: {} as any,
- });
-
- const result = await runtime.runTask({
- continueTopicId: 'tpc_existing',
- identifier: 'T-1',
- prompt: 'extra',
- });
-
- expect(result.success).toBe(true);
- expect(taskCaller.run).toHaveBeenCalledWith({
- continueTopicId: 'tpc_existing',
- id: 'T-1',
- prompt: 'extra',
- });
- expect(result.content).toContain('Task T-1 started');
- expect(result.content).toContain('Topic: tpc_1');
- });
-
- it('falls back to current task context when identifier omitted', async () => {
- const taskCaller = {
- run: vi.fn().mockResolvedValue({ operationId: 'op', topicId: 'tpc' }),
- };
- const runtime = createTaskRuntime({
- agentModel: { existsById: vi.fn() } as any,
- taskCaller: taskCaller as any,
- taskId: 'T-current',
- taskModel: {} as any,
- taskService: {} as any,
- });
-
- await runtime.runTask({});
-
- expect(taskCaller.run).toHaveBeenCalledWith(expect.objectContaining({ id: 'T-current' }));
- });
-
- it('refuses to run when neither identifier nor task context is available', async () => {
- const taskCaller = { run: vi.fn() };
- const runtime = createTaskRuntime({
- agentModel: { existsById: vi.fn() } as any,
- taskCaller: taskCaller as any,
- taskModel: {} as any,
- taskService: {} as any,
- });
-
- const result = await runtime.runTask({});
-
- expect(result.success).toBe(false);
- expect(taskCaller.run).not.toHaveBeenCalled();
- });
-
- it('runs identifiers sequentially and surfaces per-item failures without aborting', async () => {
- const taskCaller = {
- run: vi
- .fn()
- .mockResolvedValueOnce({ topicId: 'tpc_a' })
- .mockRejectedValueOnce(new Error('Task already has a running topic'))
- .mockResolvedValueOnce({ topicId: 'tpc_c' }),
- };
- const runtime = createTaskRuntime({
- agentModel: { existsById: vi.fn() } as any,
- taskCaller: taskCaller as any,
- taskModel: {} as any,
- taskService: {} as any,
- });
-
- const result = await runtime.runTasks({ identifiers: ['T-A', 'T-B', 'T-C'] });
-
- expect(taskCaller.run).toHaveBeenCalledTimes(3);
- expect(result.success).toBe(false);
- expect(result.content).toContain('Started 2/3 tasks (1 failed)');
- expect(result.content).toContain('T-B — failed: Task already has a running topic');
- });
- });
});
describe('createTaskRuntime — human assignee (assigneeUserId)', () => {
@@ -1436,7 +1367,7 @@ describe('createTaskRuntime — human assignee (assigneeUserId)', () => {
const baseDeps = {
agentModel: {} as any,
taskCaller: {} as any,
- taskModel: {} as any,
+ taskModel: { resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }) } as any,
taskService: {} as any,
};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.refs.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.refs.test.ts
new file mode 100644
index 00000000000..2be8dd82aaf
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.refs.test.ts
@@ -0,0 +1,94 @@
+import type { TaskItem } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { matchTaskRefs, parseTaskRef } from '@/database/models/task/refs';
+
+import { createTaskRuntime } from './task';
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+vi.mock('@/server/routers/lambda/task', () => ({ taskRouter: { createCaller: vi.fn() } }));
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const setup = () => {
+ const rows = Array.from({ length: 12 }, (_, i) => String(i + 1)).map((n) => ({
+ id: `task_${n}`,
+ identifier: `T-${n}`,
+ status: 'backlog',
+ })) as TaskItem[];
+ const resolveRefs = async (refs: string[]) => matchTaskRefs(refs.map(parseTaskRef), rows);
+ const run = vi.fn().mockResolvedValue({ topicId: 'tpc_1', operationId: 'op_1' });
+ const model = {
+ addDependency: vi.fn(),
+ removeDependency: vi.fn(),
+ resolveRefs,
+ resolve: async (ref: string) => (await resolveRefs([ref])).byRef.get(ref) ?? null,
+ };
+ const runtime = createTaskRuntime({
+ taskId: 'task_1',
+ taskModel: model as never,
+ taskCaller: { run } as never,
+ taskService: {} as never,
+ agentModel: {} as never,
+ });
+ return { model, run, runtime };
+};
+
+describe('task runtime canonical references', () => {
+ it.each(['addDependencies', 'removeDependencies'] as const)(
+ 'caps concurrent database writes for %s',
+ async (field) => {
+ const { model, runtime } = setup();
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const write = field === 'addDependencies' ? model.addDependency : model.removeDependency;
+ write.mockImplementation(() => gate);
+ const pending = runtime.editTask({
+ identifier: 'task_1',
+ [field]: Array.from({ length: 11 }, (_, i) => `task_${i + 2}`),
+ });
+ try {
+ await vi.waitFor(() => expect(write.mock.calls.length).toBeGreaterThanOrEqual(5));
+ expect(write).toHaveBeenCalledTimes(5);
+ } finally {
+ release();
+ await pending;
+ }
+ expect(write).toHaveBeenCalledTimes(11);
+ },
+ );
+ it('resolves a run ref before calling the router and returns canonical state', async () => {
+ const { run, runtime } = setup();
+ const result = await runtime.runTask({
+ identifier: 't-1',
+ prompt: 'extra',
+ continueTopicId: 'old',
+ });
+ expect(run).toHaveBeenCalledWith({ id: 'task_1', prompt: 'extra', continueTopicId: 'old' });
+ expect(result).toMatchObject({ success: true, state: { taskId: 'task_1', identifier: 'T-1' } });
+ expect(result.content).toContain('T-1 (id: task_1)');
+ });
+ it('uses the canonical task context when a ref is omitted', async () => {
+ const { run, runtime } = setup();
+ await runtime.runTask({});
+ expect(run).toHaveBeenCalledWith(expect.objectContaining({ id: 'task_1' }));
+ });
+ it('executes aliases once, reports original refs and preserves per-item failures', async () => {
+ const { run, runtime } = setup();
+ run
+ .mockResolvedValueOnce({ topicId: 'first' })
+ .mockRejectedValueOnce(new Error('Already running'));
+ const result = await runtime.runTasks({ identifiers: [' T-1 ', 'task_1', 't-2', 'missing'] });
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(result.state).toMatchObject({
+ succeeded: 1,
+ failed: 2,
+ results: [
+ { taskId: 'task_1', identifier: 'T-1', refs: [' T-1 ', 'task_1'], success: true },
+ { taskId: 'task_2', identifier: 'T-2', refs: ['t-2'], success: false },
+ { refs: ['missing'], success: false },
+ ],
+ });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 0031886e042..5473b70150e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -23,6 +23,7 @@ import {
} from '@lobechat/prompts';
import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';
import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';
+import pMap from 'p-map';
import { AgentModel } from '@/database/models/agent';
import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
@@ -34,9 +35,11 @@ import { appEnv } from '@/envs/app';
import { formatPgError, unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { taskRouter } from '@/server/routers/lambda/task';
import { TaskService } from '@/server/services/task';
+import { resolveTaskOrThrow, resolveTasksOrThrow } from '@/server/services/task/utils';
import { resolveTaskWorkspaceId } from './resolveWorkspaceScope';
import { createTaskAssigneeHelpers } from './taskAssignees';
+import { taskResult, taskResultLabel } from './taskResults';
import { type ServerRuntimeRegistration } from './types';
export interface TaskRuntimeDeps {
@@ -207,10 +210,12 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
// 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(),
+ id: task.id,
identifier: task.identifier,
instruction: args.instruction,
name: task.name,
parentLabel,
+ parentTaskId,
priority: task.priority,
status: task.status,
}),
@@ -231,16 +236,22 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
try {
+ const task = await resolveTaskOrThrow(taskModel(), id);
const result = await taskCaller().addComment({
authorAgentId: agentId,
content: args.content,
- id,
+ id: task.id,
});
return {
- content: `Comment added to task ${id}.`,
+ content: `Comment added to task ${taskResultLabel(task)}.`,
success: true,
- state: { commentId: result.data.id, identifier: id, success: true },
+ state: {
+ commentId: result.data.id,
+ identifier: task.identifier,
+ taskId: task.id,
+ success: true,
+ },
};
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to add task comment';
@@ -275,6 +286,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
results.push({
error: result.success ? undefined : result.content,
identifier: result.identifier,
+ taskId: result.taskId,
name: item.name,
success: result.success,
});
@@ -311,7 +323,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
return {
- content: formatTaskDeleted(task.identifier, task.name),
+ content: formatTaskDeleted(taskResultLabel(task), task.name),
// Surface the deleted task's internal id so the dispatch-layer Work
// deletion (`work: { action: 'delete' }`) can locate the Work by
// `works.resourceId = taskId` after the task row is gone.
@@ -394,7 +406,9 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
if (args.parentIdentifier !== undefined) {
const parentIdentifier = args.parentIdentifier?.trim() || null;
- updateData.parentTaskId = parentIdentifier;
+ updateData.parentTaskId = parentIdentifier
+ ? (await resolveTaskOrThrow(taskModel(), parentIdentifier)).id
+ : null;
changes.push(parentIdentifier ? `parent → ${parentIdentifier}` : 'parent cleared');
}
if (args.priority !== undefined) {
@@ -413,18 +427,10 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
apply: (depId: string) => Promise<unknown>,
onChange: (depIdentifier: string) => void,
): Promise<string | undefined> => {
- const resolved = await Promise.all(
- ids.map((id) =>
- taskModel()
- .resolve(id)
- .then((r) => ({ id, resolved: r })),
- ),
- );
- const missing = resolved.find((r) => !r.resolved);
- if (missing) return `Dependency task not found: ${missing.id}`;
-
- await Promise.all(resolved.map(({ resolved: dep }) => apply(dep!.id)));
- resolved.forEach(({ resolved: dep }) => onChange(dep!.identifier));
+ const resolved = await resolveTasksOrThrow(taskModel(), ids, { duplicates: 'collapse' });
+ await pMap(resolved.tasks, (dep) => apply(dep.id), { concurrency: 5 });
+ resolved.tasks.forEach((dep) => onChange(taskResultLabel(dep)));
+ return undefined;
};
const depResults: Promise<string | undefined>[] = [];
@@ -456,7 +462,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const firstDepError = depErrors.find((e) => e);
if (firstDepError) return { content: firstDepError, success: false };
- return { content: formatTaskEdited(task.identifier, changes), success: true };
+ return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
},
listTasks: async (args: {
@@ -477,6 +483,13 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
return {
content: formatTaskList(result.data, normalized.displayFilters),
+ state: {
+ results: result.data.map((task) => ({
+ identifier: task.identifier,
+ taskId: task.id,
+ success: true,
+ })),
+ },
success: true,
};
} catch (error) {
@@ -657,7 +670,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
if (schedulePreview) changes.push(schedulePreview);
- return { content: formatTaskEdited(task.identifier, changes), success: true };
+ return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
},
setTaskVerify: async (args: {
@@ -738,7 +751,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
await taskCaller().updateVerifyConfig({ id: task.id, verify });
- return { content: formatTaskEdited(task.identifier, changes), success: true };
+ return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
},
runTask: async (args: { continueTopicId?: string; identifier?: string; prompt?: string }) => {
@@ -751,19 +764,20 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
try {
+ const task = await resolveTaskOrThrow(taskModel(), id);
const result = await taskCaller().run({
continueTopicId: args.continueTopicId,
- id,
+ id: task.id,
prompt: args.prompt,
});
const topicId = (result as { topicId?: string } | undefined)?.topicId;
const operationId = (result as { operationId?: string } | undefined)?.operationId;
- const lines = [`Task ${id} started.`];
+ const lines = [`Task ${taskResultLabel(task)} started.`];
if (topicId) lines.push(` Topic: ${topicId}`);
if (operationId) lines.push(` Operation: ${operationId}`);
- return { content: lines.join('\n'), success: true };
+ return taskResult(task, lines.join('\n'), { topicId, operationId });
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to run task';
return { content: `Failed to run task ${id}: ${message}`, success: false };
@@ -772,39 +786,53 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
runTasks: async (args: { identifiers: string[] }) => {
const identifiers = Array.isArray(args.identifiers)
- ? args.identifiers.map((value) => value?.trim()).filter((value): value is string => !!value)
+ ? args.identifiers.filter(
+ (value): value is string => typeof value === 'string' && !!value.trim(),
+ )
: [];
if (identifiers.length === 0) {
return { content: 'No task identifiers provided.', success: false };
}
- const lines: string[] = [];
- let succeeded = 0;
- let failed = 0;
-
- for (const [index, identifier] of identifiers.entries()) {
+ const resolved = await taskModel().resolveRefs(identifiers);
+ if (resolved.ambiguous.length)
+ throw new Error(`Ambiguous task references: ${resolved.ambiguous.join(', ')}`);
+ const results: {
+ taskId?: string;
+ identifier?: string;
+ refs: string[];
+ success: boolean;
+ error?: string;
+ }[] = [];
+ for (const task of resolved.tasks) {
+ const refs = identifiers.filter((ref) => resolved.byRef.get(ref)?.id === task.id);
try {
- const result = await taskCaller().run({ id: identifier });
- const topicId = (result as { topicId?: string } | undefined)?.topicId;
- succeeded += 1;
- lines.push(
- `${index + 1}. ${identifier} — started${topicId ? ` (topic ${topicId})` : ''}`,
- );
+ await taskCaller().run({ id: task.id });
+ results.push({ taskId: task.id, identifier: task.identifier, refs, success: true });
} catch (error) {
- failed += 1;
- const message = error instanceof Error ? error.message : 'Unknown error';
- lines.push(`${index + 1}. ${identifier} — failed: ${message}`);
+ results.push({
+ taskId: task.id,
+ identifier: task.identifier,
+ refs,
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ });
}
}
-
- const header =
- failed === 0
- ? `Started ${succeeded} task${succeeded === 1 ? '' : 's'}:`
- : `Started ${succeeded}/${identifiers.length} tasks (${failed} failed):`;
-
+ for (const ref of resolved.missing)
+ results.push({ refs: [ref], success: false, error: `Task not found: ${ref}` });
+ const succeeded = results.filter((result) => result.success).length;
+ const failed = results.length - succeeded;
return {
- content: [header, ...lines].join('\n'),
+ content: [
+ `Started ${succeeded}/${results.length} tasks (${failed} failed):`,
+ ...results.map(
+ (result) =>
+ `${result.identifier ?? result.refs[0]}${result.taskId ? ` (id: ${result.taskId})` : ''} — ${result.success ? 'started' : `failed: ${result.error}`}`,
+ ),
+ ].join('\n'),
+ state: { results, succeeded, failed },
success: failed === 0,
};
},
@@ -833,6 +861,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
try {
+ const target = await resolveTaskOrThrow(taskModel(), id);
// Completing the task that owns the current operation is a delivery
// request, not an external cancellation. TaskService.updateStatus
// interrupts every still-running topic when a task leaves `running`;
@@ -840,31 +869,35 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
// leave an `interrupted` operation / `canceled` topic. Persist the
// intent instead and let onTopicComplete finalize it after the runtime
// has reached `done`.
- if (args.status === 'completed' && operationId && taskId) {
- const target = await taskModel().resolve(id);
- if (target?.id === taskId) {
- await taskModel().updateContext(target.id, {
- completion: { requestedByOperationId: operationId },
- });
- return {
- content: `Task ${target.identifier} completion requested. It will be finalized when the current run finishes.`,
- success: true,
- };
- }
+ if (args.status === 'completed' && operationId && taskId && target?.id === taskId) {
+ await taskModel().updateContext(target.id, {
+ completion: { requestedByOperationId: operationId },
+ });
+ return {
+ content: `Task ${target.identifier} completion requested. It will be finalized when the current run finishes.`,
+ success: true,
+ state: { taskId: target.id, identifier: target.identifier, success: true },
+ };
}
const result = await taskCaller().updateStatus({
error: args.error,
- id,
+ id: target.id,
status: args.status,
});
return {
content:
args.status === 'failed' && args.error
- ? `Task ${result.data.identifier} status updated to failed. Error: ${args.error}`
- : `Task ${result.data.identifier} status updated to ${args.status}.`,
+ ? `Task ${taskResultLabel(result.data)} status updated to failed. Error: ${args.error}`
+ : `Task ${taskResultLabel(result.data)} status updated to ${args.status}.`,
success: true,
+ state: {
+ taskId: result.data.id,
+ identifier: result.data.identifier,
+ status: result.data.status,
+ success: true,
+ },
};
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to update task status';
@@ -885,11 +918,13 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
};
}
- const detail = await taskService().getTaskDetail(id);
+ const task = await resolveTaskOrThrow(taskModel(), id);
+ const detail = await taskService().getTaskDetail(task.id);
if (!detail) return { content: `Task not found: ${id}`, success: false };
return {
content: formatTaskDetail(detail),
+ state: { taskId: detail.id, identifier: detail.identifier, success: true },
success: true,
};
},
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/taskResults.ts b/apps/server/src/services/toolExecution/serverRuntimes/taskResults.ts
new file mode 100644
index 00000000000..03079721343
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/taskResults.ts
@@ -0,0 +1,14 @@
+import { taskResultState } from '@lobechat/builtin-tool-task';
+
+export const taskResult = (
+ task: { id: string; identifier: string },
+ content: string,
+ extra: Record<string, unknown> = {},
+) => ({
+ content,
+ state: taskResultState(task, extra),
+ success: true,
+});
+
+export const taskResultLabel = (task: { id: string; identifier: string }) =>
+ `${task.identifier} (id: ${task.id})`;
diff --git a/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts b/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts
index 4ce354fd07e..677355841f9 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts
@@ -10,7 +10,7 @@ import { AcceptanceService } from '../acceptanceService';
const mocks = vi.hoisted(() => ({
projectFindByIds: vi.fn(),
queryPage: vi.fn(),
- taskResolveMany: vi.fn(),
+ taskResolveRefs: vi.fn(),
}));
vi.mock('@/database/models/acceptance', () => ({
@@ -20,7 +20,7 @@ vi.mock('@/database/models/acceptance', () => ({
}));
vi.mock('@/database/models/task', () => ({
TaskModel: vi.fn(function () {
- return { resolveMany: mocks.taskResolveMany };
+ return { resolveRefs: mocks.taskResolveRefs };
}),
}));
vi.mock('@/database/models/topic', () => ({
@@ -79,7 +79,9 @@ describe('AcceptanceService.listPageWithSubjects', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.queryPage.mockResolvedValue({ items: rows, nextCursor: 'cursor-2' });
- mocks.taskResolveMany.mockResolvedValue([{ id: 'task-1', identifier: 'T-1', name: 'Task 1' }]);
+ mocks.taskResolveRefs.mockResolvedValue({
+ byRef: new Map([['task-1', { id: 'task-1', identifier: 'T-1', name: 'Task 1' }]]),
+ });
mocks.projectFindByIds.mockResolvedValue([{ id: 'project-1', name: 'Project 1' }]);
});
@@ -126,7 +128,7 @@ describe('AcceptanceService.listPageWithSubjects', () => {
});
it('degrades subject titles and projects when their reads fail', async () => {
- mocks.taskResolveMany.mockRejectedValue(new Error('db down'));
+ mocks.taskResolveRefs.mockRejectedValue(new Error('db down'));
mocks.projectFindByIds.mockRejectedValue(new Error('db down'));
const service = new AcceptanceService(db() as any, 'user-1');
diff --git a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts
index 1c54cb10f3e..13ea1b03439 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts
@@ -20,7 +20,7 @@ vi.mock('@/database/models/task', () => ({
constructor(_db: unknown, userId: string, workspaceId?: string) {
mocks.taskScopes.push([userId, workspaceId]);
}
- resolveMany = mocks.resolveTasks;
+ resolveRefs = mocks.resolveTasks;
},
}));
vi.mock('@/database/models/topic', () => ({
@@ -50,9 +50,9 @@ describe('AcceptanceService.listWithSubjects', () => {
},
];
const query = vi.fn().mockResolvedValue(rows);
- mocks.resolveTasks.mockResolvedValue([
- { id: 'recent', identifier: 'T-1', name: 'Recent report' },
- ]);
+ mocks.resolveTasks.mockResolvedValue({
+ byRef: new Map([['recent', { id: 'recent', identifier: 'T-1', name: 'Recent report' }]]),
+ });
mocks.resolveTopics.mockResolvedValue([{ id: 'older', title: 'Needle report' }]);
mocks.resolveDocuments.mockResolvedValue([]);
const service = new AcceptanceService({} as any, 'user-1') as any;
@@ -119,7 +119,9 @@ describe('AcceptanceService.listWithSubjects', () => {
it('resolves foreign rows in a fixed number of reads however many owners a page spans', async () => {
mocks.resolveTasks.mockReset();
- mocks.resolveTasks.mockResolvedValue([{ id: 'mine', identifier: 'T-1', name: 'Task mine' }]);
+ mocks.resolveTasks.mockResolvedValue({
+ byRef: new Map([['mine', { id: 'mine', identifier: 'T-1', name: 'Task mine' }]]),
+ });
mocks.resolveTopics.mockResolvedValue([]);
mocks.resolveDocuments.mockResolvedValue([]);
mocks.taskScopes.length = 0;
diff --git a/apps/server/src/services/verify/acceptanceService/listing.ts b/apps/server/src/services/verify/acceptanceService/listing.ts
index 80d233b64ff..76ceec2f984 100644
--- a/apps/server/src/services/verify/acceptanceService/listing.ts
+++ b/apps/server/src/services/verify/acceptanceService/listing.ts
@@ -53,7 +53,7 @@ export const resolveSubjects = async (
try {
const [tasks, topics, documents] = await Promise.all([
- new TaskModel(deps.db, deps.userId, deps.workspaceId).resolveMany(
+ new TaskModel(deps.db, deps.userId, deps.workspaceId).resolveRefs(
idsByType.get('task') ?? [],
),
// Creator-facing lookup: exclude agent-share visitor topics from the
@@ -66,10 +66,9 @@ export const resolveSubjects = async (
),
]);
const taskTitles = new Map<string, string | null>();
- for (const task of tasks) {
+ for (const [ref, task] of tasks.byRef) {
const title = task.name ?? task.identifier;
- taskTitles.set(task.id, title);
- taskTitles.set(task.identifier, title);
+ taskTitles.set(ref, title);
}
const topicTitles = new Map(topics.map((topic) => [topic.id, topic.title ?? null]));
const documentTitles = new Map(
diff --git a/packages/builtin-skills/src/task/SKILL.md b/packages/builtin-skills/src/task/SKILL.md
index 7e052d9e325..c20bf7d231b 100644
--- a/packages/builtin-skills/src/task/SKILL.md
+++ b/packages/builtin-skills/src/task/SKILL.md
@@ -45,6 +45,7 @@ You are executing a task within the LobeHub task system. Use the `lh task` CLI v
# Task Execution Guidelines
+- **Use stable task references**: Commands accept display identifiers (for example `T-12`) and stable ids (`task_…`). Prefer the id returned by a tool for subsequent calls. Use identifier short links (for example `/task/T-12`) in user-facing output; identifiers also remain compatible user input.
- **Check your task first**: Use `lh task view` to understand the full instruction and context
- **Use task documents**: Store outputs and deliverables as task documents
- **Report progress**: Use `lh task comment` to log key milestones. To notify a member who needs to act, mention them with `<mention name="Name" id="user_xxx" />`, taking the id from `lh workspace members` (never guess it); a plain "@Name" is only text. Each mention sends a notification, so do not @ people in routine progress notes.
diff --git a/packages/builtin-skills/src/task/references/commands.md b/packages/builtin-skills/src/task/references/commands.md
index 503a7bc77cc..a9725c4fd3a 100644
--- a/packages/builtin-skills/src/task/references/commands.md
+++ b/packages/builtin-skills/src/task/references/commands.md
@@ -38,7 +38,7 @@
- `lh task checkpoint set <id> [--on-agent-request <bool>] [--topic-before <bool>] [--topic-after <bool>] [--before <ids>] [--after <ids>]` - Configure checkpoints
- `--on-agent-request`: Allow agent to request review
- `--topic-before/after`: Pause before/after each topic
- - `--before/after <ids>`: Pause before/after specific subtask identifiers
+ - `--before/after <ids>`: Pause before/after specific subtasks; accepts stable ids or display identifiers
## Review Commands (LLM-as-Judge)
@@ -74,7 +74,7 @@
## Tips
- All commands support `--json [fields]` for structured output
-- Task identifiers use format like TASK-1, TASK-2, etc.
+- Task identifiers use formats like T-1 or ABC-2. They are display labels and compatible input aliases; prefer stable task ids from previous results for subsequent calls. Use identifier short links such as `/task/T-1` in user-facing output.
- Use `lh task tree` to visualize full task hierarchy before planning work
- Use `lh task comment` to log progress — comments appear in task activities
- Documents pinned to the task are accessible to the agent during execution
diff --git a/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx
index ec7f237661d..57abaca4cc1 100644
--- a/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/DeleteTask/index.tsx
@@ -29,10 +29,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
export const DeleteTaskInspector = memo<BuiltinInspectorProps<DeleteTaskParams, DeleteTaskState>>(
- ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
- const identifier = args?.identifier || partialArgs?.identifier;
+ const identifier = pluginState?.identifier ?? args?.identifier ?? partialArgs?.identifier;
return (
<div className={inspectorTextStyles.root}>
diff --git a/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx
index a6d106f1cfd..ced9e283d78 100644
--- a/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx
@@ -148,11 +148,11 @@ const MemberChip = memo<{ userId: string }>(({ userId }) => {
MemberChip.displayName = 'MemberChip';
export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, EditTaskState>>(
- ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
const params = args || partialArgs || ({} as Partial<EditTaskParams>);
- const identifier = params.identifier;
+ const identifier = pluginState?.identifier ?? params.identifier;
const segments: { content: ReactNode; key: string }[] = [];
diff --git a/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx
index 32addf8fd72..187de30a645 100644
--- a/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/RunTask/index.tsx
@@ -1,8 +1,7 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx, Icon } from '@lobehub/ui';
import { Play } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -51,11 +50,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
export const RunTaskInspector = memo<BuiltinInspectorProps<RunTaskParams, RunTaskState>>(
- ({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
const params = args || partialArgs || ({} as Partial<RunTaskParams>);
- const identifier = params.identifier;
+ const identifier = pluginState?.identifier ?? params.identifier;
const continueTopicId = params.continueTopicId;
const prompt = params.prompt;
diff --git a/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx b/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx
index 9fc8a2d466f..90a13becbf9 100644
--- a/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/SetTaskSchedule/index.tsx
@@ -43,10 +43,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
export const SetTaskScheduleInspector = memo<
BuiltinInspectorProps<SetTaskScheduleParams, SetTaskScheduleState>
->(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
- const identifier = args?.identifier || partialArgs?.identifier;
+ const identifier = pluginState?.identifier ?? args?.identifier ?? partialArgs?.identifier;
const automationMode = args?.automationMode ?? partialArgs?.automationMode;
const modeLabel = automationMode === null ? 'off' : automationMode;
diff --git a/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx b/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx
index 0807a00abec..0cfbe5cb530 100644
--- a/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/SetTaskVerify/index.tsx
@@ -27,10 +27,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
export const SetTaskVerifyInspector = memo<
BuiltinInspectorProps<SetTaskVerifyParams, SetTaskVerifyState>
->(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
- const identifier = args?.identifier || partialArgs?.identifier;
+ const identifier = pluginState?.identifier ?? args?.identifier ?? partialArgs?.identifier;
return (
<div className={inspectorTextStyles.root} style={{ flexWrap: 'wrap', gap: 4 }}>
diff --git a/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx b/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx
index 44390080065..0258a8410d0 100644
--- a/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/UpdateTaskStatus/index.tsx
@@ -50,10 +50,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
export const UpdateTaskStatusInspector = memo<
BuiltinInspectorProps<UpdateTaskStatusParams, UpdateTaskStatusState>
->(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
- const identifier = args?.identifier || partialArgs?.identifier;
+ const identifier = pluginState?.identifier ?? args?.identifier ?? partialArgs?.identifier;
const status = (args?.status || partialArgs?.status) as TaskStatus | undefined;
const tone = status ? STATUS_TONE[status] : undefined;
diff --git a/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx
index 1f4cd471801..b7a82c6fbb5 100644
--- a/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Inspector/ViewTask/index.tsx
@@ -30,7 +30,7 @@ export const ViewTaskInspector = memo<BuiltinInspectorProps<ViewTaskParams, View
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
const { t } = useTranslation('plugin');
- const identifier = args?.identifier || partialArgs?.identifier || pluginState?.identifier;
+ const identifier = pluginState?.identifier ?? args?.identifier ?? partialArgs?.identifier;
return (
<div className={inspectorTextStyles.root}>
diff --git a/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx b/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx
index 7ce80bef396..377f75e1f5c 100644
--- a/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/CreateTask/index.tsx
@@ -1,19 +1,17 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Block, Markdown } from '@lobehub/ui';
-import { ActionIcon, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { ActionIcon, Block, createStaticStyles, cssVar, Markdown, Text } from '@lobehub/ui';
import { PanelRight, PanelRightClose } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import TaskPriorityTag from '@/features/AgentTasks/features/TaskPriorityTag';
import TaskStatusTag from '@/features/AgentTasks/features/TaskStatusTag';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
+import { resolveTaskOpenTarget } from '../../../taskRef';
import type { CreateTaskParams, CreateTaskState } from '../../../types';
+import { useTaskDetailToggle } from '../shared';
const styles = createStaticStyles(({ css, cssVar }) => ({
description: css`
@@ -78,16 +76,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
export const CreateTaskRender = memo<BuiltinRenderProps<CreateTaskParams, CreateTaskState>>(
({ args, pluginState }) => {
const { t } = useTranslation('chat');
- const [activeTaskDetailId, showTaskDetail, openTaskDetail, closeTaskDetail] = useChatStore(
- (s) => [
- chatPortalSelectors.taskDetailId(s),
- chatPortalSelectors.showTaskDetail(s),
- s.openTaskDetail,
- s.closeTaskDetail,
- ],
- );
-
const identifier = pluginState?.identifier;
+ const target = resolveTaskOpenTarget(pluginState);
+ const { canOpen, isExpanded, open, toggle } = useTaskDetailToggle(target);
// Auto-expanding the freshly created task's detail portal is driven by the
// executor's `onAfterCall` hook (gateway `tool_end`), not a render effect —
// see `client/executor`. The card itself only handles the manual toggle.
@@ -103,20 +94,13 @@ export const CreateTaskRender = memo<BuiltinRenderProps<CreateTaskParams, Create
const description = pluginState?.description;
const instruction = args?.instruction;
const parent = pluginState?.parentIdentifier ?? args?.parentIdentifier;
- const isExpanded = !!identifier && showTaskDetail && activeTaskDetailId === identifier;
-
- const toggle = () => {
- if (!identifier) return;
- if (isExpanded) closeTaskDetail();
- else openTaskDetail(identifier);
- };
return (
<Block
- clickable={!!identifier}
+ clickable={canOpen}
variant={'outlined'}
width={'100%'}
- onClick={identifier ? () => openTaskDetail(identifier) : undefined}
+ onClick={canOpen ? open : undefined}
>
<div className={styles.taskItem}>
<div className={styles.row}>
diff --git a/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx b/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx
index 9ba6fa1398a..402575f8bcb 100644
--- a/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/EditTask/index.tsx
@@ -1,15 +1,14 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Markdown } from '@lobehub/ui';
-import { Text } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
+import { createStaticStyles, Markdown, Text } from '@lobehub/ui';
import { Pencil } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import TaskPriorityTag from '@/features/AgentTasks/features/TaskPriorityTag';
+import { resolveTaskOpenTarget } from '../../../taskRef';
import type { EditTaskParams, EditTaskState } from '../../../types';
import {
AssigneeInline,
@@ -81,6 +80,7 @@ export const EditTaskRender = memo<BuiltinRenderProps<EditTaskParams, EditTaskSt
<TaskResultCard
icon={Pencil}
identifier={identifier}
+ taskId={resolveTaskOpenTarget(pluginState, params)}
title={t('builtins.lobe-task.apiName.editTask')}
>
{hasAnyChange ? (
diff --git a/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx b/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx
index 80d5413985c..48cc326ed6a 100644
--- a/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/RunTask/index.tsx
@@ -1,12 +1,12 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Markdown } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { createStaticStyles, cssVar, Markdown } from '@lobehub/ui';
import { Play } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { resolveTaskOpenTarget } from '../../../taskRef';
import type { RunTaskParams, RunTaskState } from '../../../types';
import { InlineField, monoChipClassName, SectionField, TaskResultCard } from '../shared';
@@ -45,6 +45,7 @@ export const RunTaskRender = memo<BuiltinRenderProps<RunTaskParams, RunTaskState
icon={Play}
iconColor={cssVar.colorWarning}
identifier={identifier}
+ taskId={resolveTaskOpenTarget(pluginState, params)}
title={t('builtins.lobe-task.apiName.runTask')}
>
{hasBody ? (
diff --git a/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx b/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx
index 755ffdd09f5..5872b38516d 100644
--- a/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/SetTaskVerify/index.tsx
@@ -1,12 +1,12 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Icon, Markdown } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { createStaticStyles, cssVar, Icon, Markdown } from '@lobehub/ui';
import { Check, ShieldCheck, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { resolveTaskOpenTarget } from '../../../taskRef';
import type { SetTaskVerifyParams, SetTaskVerifyState } from '../../../types';
import { TaskResultCard } from '../shared';
@@ -69,6 +69,7 @@ export const SetTaskVerifyRender = memo<
icon={ShieldCheck}
iconColor={enabled === false ? cssVar.colorTextTertiary : cssVar.colorSuccess}
identifier={identifier}
+ taskId={resolveTaskOpenTarget(pluginState, params)}
title={t('builtins.lobe-task.apiName.setTaskVerify')}
>
{requirement ? (
diff --git a/packages/builtin-tool-task/src/client/Render/shared.tsx b/packages/builtin-tool-task/src/client/Render/shared.tsx
index 348f79f0918..4d9fcd471d3 100644
--- a/packages/builtin-tool-task/src/client/Render/shared.tsx
+++ b/packages/builtin-tool-task/src/client/Render/shared.tsx
@@ -1,8 +1,6 @@
'use client';
-import { Block, Icon } from '@lobehub/ui';
-import { ActionIcon, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { ActionIcon, Block, createStaticStyles, cssVar, cx, Icon, Text } from '@lobehub/ui';
import type { LucideIcon } from 'lucide-react';
import { PanelRight, PanelRightClose } from 'lucide-react';
import type { ReactNode } from 'react';
@@ -15,6 +13,7 @@ import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDispla
import { useUserDisplayMeta } from '@/features/AgentTasks/shared/useUserDisplayMeta';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useTaskStore } from '@/store/task';
const styles = createStaticStyles(({ css, cssVar }) => ({
assignee: css`
@@ -127,8 +126,14 @@ export const useTaskDetailToggle = (identifier?: string) => {
],
);
+ const canonicalActive = useTaskStore((state) =>
+ activeTaskDetailId ? (state.taskRefIndex[activeTaskDetailId] ?? activeTaskDetailId) : undefined,
+ );
+ const canonicalTarget = useTaskStore((state) =>
+ identifier ? (state.taskRefIndex[identifier] ?? identifier) : undefined,
+ );
const canOpen = !!identifier;
- const isExpanded = canOpen && showTaskDetail && activeTaskDetailId === identifier;
+ const isExpanded = canOpen && showTaskDetail && canonicalActive === canonicalTarget;
const open = () => {
if (identifier) openTaskDetail(identifier);
@@ -150,6 +155,7 @@ interface TaskResultCardProps {
icon?: LucideIcon;
iconColor?: string;
identifier?: string;
+ taskId?: string;
title: ReactNode;
}
@@ -159,9 +165,9 @@ interface TaskResultCardProps {
* optional body of detail fields. The whole card opens the task detail portal.
*/
export const TaskResultCard = memo<TaskResultCardProps>(
- ({ children, headerExtra, icon, iconColor, identifier, title }) => {
+ ({ children, headerExtra, icon, iconColor, identifier, taskId, title }) => {
const { t } = useTranslation('chat');
- const { canOpen, isExpanded, open, toggle } = useTaskDetailToggle(identifier);
+ const { canOpen, isExpanded, open, toggle } = useTaskDetailToggle(taskId ?? identifier);
return (
<Block
diff --git a/packages/builtin-tool-task/src/client/executor/assignee.test.ts b/packages/builtin-tool-task/src/client/executor/assignee.test.ts
index 9e2f996530c..18dbed32996 100644
--- a/packages/builtin-tool-task/src/client/executor/assignee.test.ts
+++ b/packages/builtin-tool-task/src/client/executor/assignee.test.ts
@@ -37,7 +37,9 @@ vi.mock('@/store/task/slices/detail/reducer', () => ({
findSubtaskParentId: vi.fn(() => undefined),
}));
-vi.mock('@/services/task', () => ({ taskService: {} }));
+vi.mock('@/services/task', () => ({
+ taskService: { find: vi.fn(async () => ({ data: { id: 'task-1', identifier: 'T-1' } })) },
+}));
// Keep the role gate deterministic: only 'viewer' is excluded here.
vi.mock('@lobechat/const/rbac', () => ({
@@ -130,7 +132,7 @@ describe('TaskExecutor — human assignee (assigneeUserId)', () => {
expect(result.success).toBe(true);
expect(mocks.updateTask).toHaveBeenCalledWith(
- 'T-1',
+ 'task-1',
{ assigneeUserId: 'usr_2' },
{ source: 'external' },
);
@@ -143,7 +145,7 @@ describe('TaskExecutor — human assignee (assigneeUserId)', () => {
} as any);
expect(mocks.updateTask).toHaveBeenCalledWith(
- 'T-1',
+ 'task-1',
{ assigneeUserId: 'usr_2' },
{ actorAgentId: 'agt-self', source: 'external' },
);
@@ -153,7 +155,7 @@ describe('TaskExecutor — human assignee (assigneeUserId)', () => {
await taskExecutor.editTask({ assigneeAgentId: 'agt-new', identifier: 'T-1' });
expect(mocks.updateTask).toHaveBeenCalledWith(
- 'T-1',
+ 'task-1',
{ assigneeAgentId: 'agt-new' },
{ source: 'external' },
);
@@ -167,7 +169,7 @@ describe('TaskExecutor — human assignee (assigneeUserId)', () => {
});
expect(mocks.updateTask).toHaveBeenCalledWith(
- 'T-1',
+ 'task-1',
{ assigneeAgentId: 'agt-new', assigneeUserId: 'usr_2' },
{ source: 'external' },
);
@@ -177,7 +179,7 @@ describe('TaskExecutor — human assignee (assigneeUserId)', () => {
const result = await taskExecutor.editTask({ assigneeUserId: null, identifier: 'T-1' });
expect(mocks.updateTask).toHaveBeenCalledWith(
- 'T-1',
+ 'task-1',
{ assigneeUserId: null },
{ source: 'external' },
);
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index f28b56158ef..5b7c16069af 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -31,12 +31,14 @@ import { getTaskStoreState } from '@/store/task';
import { findSubtaskParentId } from '@/store/task/slices/detail/reducer';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { isTrpcErrorCode } from '@/utils/trpcError';
import { MISSING_TASK_NAME_ERROR } from '../../constants';
import { normalizeListTasksParams } from '../../listTasks';
import { selectAssignableMembers } from '../../listWorkspaceMembers';
import { TaskIdentifier } from '../../manifest';
import { normalizeSetTaskVerifyParams } from '../../setTaskVerify';
+import { resolveTaskOpenTarget } from '../../taskRef';
import type {
AddTaskCommentParams,
CreateTaskParams,
@@ -91,14 +93,6 @@ const memberLabel = (userId: string): string => {
return name ? `${name} (${userId})` : userId;
};
-const extractIdentifier = (params: unknown, result: BuiltinToolResult): string | undefined => {
- const fromState = (result.state as { identifier?: unknown } | undefined)?.identifier;
- if (typeof fromState === 'string' && fromState.length > 0) return fromState;
- const fromParams = (params as { identifier?: unknown } | null | undefined)?.identifier;
- if (typeof fromParams === 'string' && fromParams.length > 0) return fromParams;
- return undefined;
-};
-
class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
readonly identifier = TaskIdentifier;
protected readonly apiEnum = TaskApiName;
@@ -107,7 +101,10 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
if (!result.success) return;
const store = getTaskStoreState();
- const identifier = extractIdentifier(params, result);
+ const identifier = resolveTaskOpenTarget(
+ result.state as { taskId?: string; identifier?: string },
+ params as { identifier?: string },
+ );
// Auto-expand the freshly created task's detail in the right-side portal so
// the user can review it without leaving the conversation. This fires once
@@ -172,14 +169,15 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
try {
log('[TaskExecutor] addTaskComment - identifier:', identifier);
- const result = await getTaskStoreState().addComment(identifier, params.content, {
+ const target = (await taskService.find(identifier)).data;
+ const result = await getTaskStoreState().addComment(target.id, params.content, {
authorAgentId: ctx?.agentId,
});
const commentId = (result as { data?: { id?: string } } | undefined)?.data?.id;
return {
- content: `Comment added to task ${identifier}.`,
- state: { commentId, identifier, success: true },
+ content: `Comment added to task ${target.identifier} (id: ${target.id}).`,
+ state: { commentId, identifier: target.identifier, taskId: target.id, success: true },
success: true,
};
} catch (error) {
@@ -230,13 +228,14 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
// Executing agent and human owner are independent, coexisting sides (the
// member owns the outcome, the agent executes) — a member owner does not
// suppress the usual current-agent default.
+ const parent = parentIdentifier ? (await taskService.find(parentIdentifier)).data : undefined;
const task = await getTaskStoreState().createTask({
assigneeAgentId: assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),
assigneeUserId,
createdByAgentId: ctx?.agentId,
instruction: params.instruction,
name: params.name,
- parentTaskId: parentIdentifier,
+ parentTaskId: parent?.id,
priority: params.priority,
});
@@ -252,10 +251,12 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
content: formatTaskCreated({
assigneeLabel: task.assigneeUserId ? memberLabel(task.assigneeUserId) : undefined,
baseUrl: taskLinkBaseUrl(),
+ id: task.id,
identifier: task.identifier,
instruction: params.instruction,
name: task.name,
- parentLabel: parentIdentifier,
+ parentLabel: parent?.identifier,
+ parentTaskId: parent?.id,
priority: task.priority,
status: task.status,
}),
@@ -327,7 +328,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
(typeof result.content === 'string' ? result.content : 'Unknown error');
const identifier = (result.state as { identifier?: string } | undefined)?.identifier;
- results.push({ error, identifier, name: item.name, success });
+ results.push({
+ error,
+ identifier,
+ taskId: (result.state as { taskId?: string })?.taskId,
+ name: item.name,
+ success,
+ });
}
const succeeded = results.filter((r) => r.success).length;
@@ -355,7 +362,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const label = deleted?.identifier ?? params.identifier;
return {
- content: formatTaskDeleted(label, deleted?.name),
+ content: formatTaskDeleted(`${label} (id: ${deleted?.id})`, deleted?.name),
// Surface the deleted task's internal id so the manifest-driven dispatch
// layer (`work: { action: 'delete' }`) can delete its Work + refresh the
// conversation caches — the task row is gone, so the Work can only be
@@ -416,7 +423,9 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
try {
log('[TaskExecutor] editTask - params:', params);
- const { identifier, addDependencies, removeDependencies } = params;
+ const { addDependencies, removeDependencies } = params;
+ const target = (await taskService.find(params.identifier)).data;
+ const identifier = target.id;
const store = getTaskStoreState();
const changes: string[] = [];
const ops: Promise<unknown>[] = [];
@@ -462,7 +471,9 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
}
if (params.parentIdentifier !== undefined) {
const parentIdentifier = params.parentIdentifier?.trim() || null;
- updateData.parentTaskId = parentIdentifier;
+ updateData.parentTaskId = parentIdentifier
+ ? (await taskService.find(parentIdentifier)).data.id
+ : null;
changes.push(parentIdentifier ? `parent → ${parentIdentifier}` : 'parent cleared');
}
if (params.priority !== undefined) {
@@ -485,24 +496,32 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
);
}
- if (addDependencies?.length) {
- addDependencies.forEach((dep) => {
- ops.push(store.addDependency(identifier, dep));
- changes.push(formatDependencyAdded(identifier, dep));
- });
- }
- if (removeDependencies?.length) {
- removeDependencies.forEach((dep) => {
- ops.push(store.removeDependency(identifier, dep));
- changes.push(formatDependencyRemoved(identifier, dep));
- });
- }
+ const applyDependencies = async (refs: string[], remove: boolean) => {
+ const tasks = await Promise.all(
+ refs.map(async (ref) => (await taskService.find(ref)).data),
+ );
+ for (const dep of new Map(tasks.map((task) => [task.id, task])).values()) {
+ ops.push(
+ remove
+ ? store.removeDependency(identifier, dep.id)
+ : store.addDependency(identifier, dep.id),
+ );
+ const label = `${dep.identifier} (id: ${dep.id})`;
+ changes.push(
+ remove
+ ? formatDependencyRemoved(target.identifier, label)
+ : formatDependencyAdded(target.identifier, label),
+ );
+ }
+ };
+ if (addDependencies?.length) await applyDependencies(addDependencies, false);
+ if (removeDependencies?.length) await applyDependencies(removeDependencies, true);
await Promise.all(ops);
return {
- content: formatTaskEdited(identifier, changes),
- state: { identifier, success: true },
+ content: formatTaskEdited(`${target.identifier} (id: ${target.id})`, changes),
+ state: { identifier: target.identifier, taskId: target.id, success: true },
success: true,
};
} catch (error) {
@@ -553,7 +572,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
try {
log('[TaskExecutor] setTaskSchedule - params:', params);
- const { identifier } = params;
+ const target = (await taskService.find(params.identifier)).data;
+ const identifier = target.id;
const store = getTaskStoreState();
const changes: string[] = [];
const ops: Promise<unknown>[] = [];
@@ -563,7 +583,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const schedule = await this.checkResultingSchedule(params);
if (schedule && !schedule.valid) {
return {
- content: formatInvalidScheduleMessage(identifier, schedule.error),
+ content: formatInvalidScheduleMessage(target.identifier, schedule.error),
error: { message: schedule.error, type: 'InvalidSchedule' },
success: false,
};
@@ -649,8 +669,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
if (schedule?.valid) changes.push(schedule.preview);
return {
- content: formatTaskEdited(identifier, changes),
- state: { automationMode: params.automationMode, identifier, success: true },
+ content: formatTaskEdited(`${target.identifier} (id: ${target.id})`, changes),
+ state: {
+ automationMode: params.automationMode,
+ identifier: target.identifier,
+ taskId: target.id,
+ success: true,
+ },
success: true,
};
} catch (error) {
@@ -680,7 +705,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
log('[TaskExecutor] setTaskVerify - params:', params);
params = normalizeSetTaskVerifyParams(params);
- const { identifier } = params;
+ const target = (await taskService.find(params.identifier)).data;
+ const identifier = target.id;
// Only forward keys the caller actually provided. The TRPC contract
// (task.updateVerifyConfig) treats `null` as "clear" and omission as
@@ -754,8 +780,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
await getTaskStoreState().internal_refreshTaskDetail(identifier);
return {
- content: formatTaskEdited(identifier, changes),
- state: { enabled: params.enabled, identifier, success: true },
+ content: formatTaskEdited(`${target.identifier} (id: ${target.id})`, changes),
+ state: {
+ enabled: params.enabled,
+ identifier: target.identifier,
+ taskId: target.id,
+ success: true,
+ },
success: true,
};
} catch (error) {
@@ -843,7 +874,16 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
return {
content: formatTaskList(tasks, normalized.displayFilters),
- state: { count: tasks.length, success: true, total: result.total },
+ state: {
+ count: tasks.length,
+ success: true,
+ total: result.total,
+ results: tasks.map((task) => ({
+ identifier: task.identifier,
+ taskId: task.id,
+ success: true,
+ })),
+ },
success: true,
};
} catch (error) {
@@ -872,7 +912,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
try {
log('[TaskExecutor] runTask - identifier:', identifier);
- const result = await taskService.run(identifier, {
+ const target = (await taskService.find(identifier)).data;
+ const result = await taskService.run(target.id, {
continueTopicId: params.continueTopicId,
prompt: params.prompt,
});
@@ -883,13 +924,19 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const store = getTaskStoreState();
await Promise.all([store.internal_refreshTaskDetail(identifier), store.refreshTaskList()]);
- const lines = [`Task ${identifier} started.`];
+ const lines = [`Task ${target.identifier} (id: ${target.id}) started.`];
if (topicId) lines.push(` Topic: ${topicId}`);
if (operationId) lines.push(` Operation: ${operationId}`);
return {
content: lines.join('\n'),
- state: { identifier, operationId, success: true, topicId },
+ state: {
+ identifier: target.identifier,
+ taskId: target.id,
+ operationId,
+ success: true,
+ topicId,
+ },
success: true,
};
} catch (error) {
@@ -908,7 +955,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
_ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
const identifiers = Array.isArray(params.identifiers)
- ? params.identifiers.map((id) => id?.trim()).filter((id): id is string => !!id)
+ ? params.identifiers.filter((id): id is string => typeof id === 'string' && !!id.trim())
: [];
if (identifiers.length === 0) {
@@ -922,19 +969,50 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
log('[TaskExecutor] runTasks - count:', identifiers.length);
const results: RunTasksItemResult[] = [];
- const lines: string[] = [];
- for (const [index, identifier] of identifiers.entries()) {
+ const byId = new Map<string, { id: string; identifier: string; refs: string[] }>();
+ for (const ref of identifiers) {
try {
- const result = await taskService.run(identifier);
- const topicId = (result as { topicId?: string } | undefined)?.topicId;
- const operationId = (result as { operationId?: string } | undefined)?.operationId;
- results.push({ identifier, operationId, success: true, topicId });
- lines.push(`${index + 1}. ${identifier} — started${topicId ? ` (topic ${topicId})` : ''}`);
+ const { data: task } = await taskService.find(ref);
+ const group = byId.get(task.id) ?? { id: task.id, identifier: task.identifier, refs: [] };
+ group.refs.push(ref);
+ byId.set(task.id, group);
} catch (error) {
- const message = error instanceof Error ? error.message : 'Unknown error';
- results.push({ error: message, identifier, success: false });
- lines.push(`${index + 1}. ${identifier} — failed: ${message}`);
+ if (isTrpcErrorCode(error, 'BAD_REQUEST')) {
+ const message = error instanceof Error ? error.message : 'Invalid task reference';
+ return {
+ content: message,
+ error: { message, type: 'InvalidTaskReference' },
+ success: false,
+ };
+ }
+ results.push({
+ identifier: ref,
+ refs: [ref],
+ error: error instanceof Error ? error.message : 'Task not found',
+ success: false,
+ });
+ }
+ }
+ for (const task of byId.values()) {
+ try {
+ const result = await taskService.run(task.id);
+ results.push({
+ identifier: task.identifier,
+ taskId: task.id,
+ refs: task.refs,
+ operationId: result.operationId,
+ topicId: result.topicId,
+ success: true,
+ });
+ } catch (error) {
+ results.push({
+ identifier: task.identifier,
+ taskId: task.id,
+ refs: task.refs,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ success: false,
+ });
}
}
@@ -952,7 +1030,15 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
: `Started ${succeeded}/${results.length} tasks (${failed} failed):`;
return {
- content: [header, ...lines].join('\n'),
+ content: [
+ header,
+ ...results.map((result) => {
+ const label = result.taskId
+ ? `${result.identifier} (id: ${result.taskId})`
+ : result.identifier;
+ return `${label} — ${result.success ? 'started' : `failed: ${result.error}`}`;
+ }),
+ ].join('\n'),
state: { failed, results, succeeded },
success: failed === 0,
};
@@ -992,7 +1078,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
log('[TaskExecutor] updateTaskStatus - params:', params);
const identifier = params.identifier ?? ctx?.taskId ?? undefined;
- const id = await getTaskStoreState().updateTaskStatus(identifier, params.status, {
+ const target = (await taskService.find(identifier ?? getTaskStoreState().activeTaskId!)).data;
+ await getTaskStoreState().updateTaskStatus(target.id, params.status, {
...(ctx?.agentId ? { actorAgentId: ctx.agentId } : {}),
error: params.error,
});
@@ -1003,9 +1090,14 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
return {
content:
params.status === 'failed' && params.error
- ? `Task ${id} status updated to failed. Error: ${params.error}`
- : `Task ${id} status updated to ${params.status}.`,
- state: { status: params.status, success: true },
+ ? `Task ${target.identifier} (id: ${target.id}) status updated to failed. Error: ${params.error}`
+ : `Task ${target.identifier} (id: ${target.id}) status updated to ${params.status}.`,
+ state: {
+ identifier: target.identifier,
+ taskId: target.id,
+ status: params.status,
+ success: true,
+ },
success: true,
};
} catch (error) {
@@ -1032,7 +1124,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
return {
content: formatTaskDetail(detail),
- state: { identifier: detail.identifier, success: true },
+ state: { identifier: detail.identifier, taskId: detail.id, success: true },
success: true,
};
} catch (error) {
diff --git a/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts b/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts
index 046ab09e40d..9ae40a9ec52 100644
--- a/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts
+++ b/packages/builtin-tool-task/src/client/executor/onAfterCall.test.ts
@@ -28,6 +28,7 @@ vi.mock('@/store/task/slices/detail/reducer', () => ({
vi.mock('@/services/task', () => ({
taskService: {
+ find: vi.fn(async (ref) => ({ data: { id: ref, identifier: ref } })),
updateVerifyConfig: mocks.updateVerifyConfig,
},
}));
diff --git a/packages/builtin-tool-task/src/client/executor/runTasks.test.ts b/packages/builtin-tool-task/src/client/executor/runTasks.test.ts
new file mode 100644
index 00000000000..5aa222b911e
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/executor/runTasks.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ find: vi.fn(), run: vi.fn(), refreshTaskList: vi.fn() }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: vi.fn(),
+}));
+vi.mock('@/business/client/hooks/useWorkspaceMembers', () => ({ getWorkspaceMembers: vi.fn() }));
+vi.mock('@/store/user', () => ({ useUserStore: { getState: () => ({}) } }));
+vi.mock('@/store/user/selectors', () => ({ userProfileSelectors: {} }));
+vi.mock('@/store/chat', () => ({ getChatStoreState: vi.fn() }));
+vi.mock('@/store/task', () => ({
+ getTaskStoreState: () => ({ refreshTaskList: mocks.refreshTaskList }),
+}));
+vi.mock('@/store/task/slices/detail/reducer', () => ({ findSubtaskParentId: vi.fn() }));
+vi.mock('@/services/task', () => ({ taskService: { find: mocks.find, run: mocks.run } }));
+
+const { taskExecutor } = await import('./index');
+
+describe('TaskExecutor batch references', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.find.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ mocks.run.mockResolvedValue({ topicId: 'topic_1' });
+ });
+ it('retains original refs and executes mixed aliases only once', async () => {
+ const result = await taskExecutor.runTasks({ identifiers: [' T-1 ', 'task_1'] });
+ expect(mocks.run).toHaveBeenCalledExactlyOnceWith('task_1');
+ expect(result.state).toMatchObject({
+ results: [{ taskId: 'task_1', identifier: 'T-1', refs: [' T-1 ', 'task_1'] }],
+ });
+ });
+ it('rejects the entire ambiguous batch before executing any task', async () => {
+ mocks.find
+ .mockResolvedValueOnce({ data: { id: 'task_1', identifier: 'T-1' } })
+ .mockRejectedValueOnce(
+ Object.assign(new Error('Ambiguous task reference: T-2'), {
+ data: { code: 'BAD_REQUEST' },
+ }),
+ );
+ const result = await taskExecutor.runTasks({ identifiers: ['T-1', 'T-2'] });
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Ambiguous task reference');
+ expect(mocks.run).not.toHaveBeenCalled();
+ });
+ it('includes lookup and kickoff failures in the model-visible content', async () => {
+ mocks.find.mockRejectedValueOnce(new Error('Task not found: T-9'));
+ mocks.run.mockRejectedValueOnce(new Error('Already running'));
+ const result = await taskExecutor.runTasks({ identifiers: ['T-9', 'task_1'] });
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('T-9');
+ expect(result.content).toContain('Task not found: T-9');
+ expect(result.content).toContain('T-1 (id: task_1)');
+ expect(result.content).toContain('Already running');
+ });
+});
diff --git a/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.ts b/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.ts
index 307fc8d4c56..438e8eb02be 100644
--- a/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.ts
+++ b/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.ts
@@ -31,6 +31,7 @@ vi.mock('@/store/task/slices/detail/reducer', () => ({
vi.mock('@/services/task', () => ({
taskService: {
+ find: vi.fn(async () => ({ data: { id: 'task-1', identifier: 'T-1' } })),
getDetail: mocks.getDetail,
update: mocks.update,
updateConfig: mocks.updateConfig,
diff --git a/packages/builtin-tool-task/src/index.ts b/packages/builtin-tool-task/src/index.ts
index 33d0dbe7b97..39a63a1b365 100644
--- a/packages/builtin-tool-task/src/index.ts
+++ b/packages/builtin-tool-task/src/index.ts
@@ -21,6 +21,7 @@ export {
export { TaskIdentifier, TaskManifest } from './manifest';
export { normalizeSetTaskVerifyParams } from './setTaskVerify';
export { systemPrompt } from './systemRole';
+export { resolveTaskOpenTarget, taskResultState } from './taskRef';
export type {
CreateGoalParams,
CreateGoalState,
diff --git a/packages/builtin-tool-task/src/manifest.test.ts b/packages/builtin-tool-task/src/manifest.test.ts
index 5fe8a7623c8..23c8bc5ceb1 100644
--- a/packages/builtin-tool-task/src/manifest.test.ts
+++ b/packages/builtin-tool-task/src/manifest.test.ts
@@ -60,3 +60,23 @@ describe('TaskManifest identifier examples', () => {
expect(text).toMatch(/\bT-1\b/);
});
});
+
+describe('stable task references', () => {
+ it('keeps parameter names and teaches stable ids at every ref input', () => {
+ for (const api of TaskManifest.api) {
+ const properties = (
+ api.parameters as { properties: Record<string, { description?: string }> }
+ ).properties;
+ for (const key of [
+ 'identifier',
+ 'parentIdentifier',
+ 'identifiers',
+ 'addDependencies',
+ 'removeDependencies',
+ ]) {
+ const property = properties[key];
+ if (property) expect(property.description).toContain('prefer stable ids');
+ }
+ }
+ });
+});
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index c493584998d..30dd52e5a9e 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -36,7 +36,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
parentIdentifier: {
description:
- 'Identifier of the parent task (e.g. "T-1"). If provided, the new task becomes a subtask.',
+ 'Identifier of the parent task (e.g. "T-1"). If provided, the new task becomes a subtask. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
priority: {
@@ -88,7 +88,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
parentIdentifier: {
description:
- 'Identifier of the parent task (e.g. "T-1"). If provided, the new task becomes a subtask.',
+ 'Identifier of the parent task (e.g. "T-1"). If provided, the new task becomes a subtask. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
priority: {
@@ -131,7 +131,7 @@ export const TaskManifest: BuiltinToolManifest = {
offset: { description: 'Pagination offset.', type: 'number' },
parentIdentifier: {
description:
- 'List subtasks of this parent (e.g. "T-1"). When omitted, no parent filter is applied unless listTasks is called without any filters, which defaults to top-level tasks.',
+ 'List subtasks of this parent (e.g. "T-1"). When omitted, no parent filter is applied unless listTasks is called without any filters, which defaults to top-level tasks. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
priorities: {
@@ -180,7 +180,7 @@ export const TaskManifest: BuiltinToolManifest = {
properties: {
identifier: {
description:
- 'The task identifier to view (e.g. "T-1"). If omitted, the current task is used only when a current task context exists.',
+ 'The task identifier to view (e.g. "T-1"). If omitted, the current task is used only when a current task context exists. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
},
@@ -202,7 +202,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
identifier: {
description:
- 'The task identifier to comment on (e.g. "T-1"). If omitted, the current task is used only when a current task context exists.',
+ 'The task identifier to comment on (e.g. "T-1"). If omitted, the current task is used only when a current task context exists. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
},
@@ -252,7 +252,8 @@ export const TaskManifest: BuiltinToolManifest = {
parameters: {
properties: {
addDependencies: {
- description: 'Identifiers of tasks this task should block on (e.g. ["T-2", "T-3"]).',
+ description:
+ 'Identifiers of tasks this task should block on (e.g. ["T-2", "T-3"]). Accepts identifiers or ids returned by previous results; prefer stable ids.',
items: { type: 'string' },
type: 'array',
},
@@ -272,7 +273,8 @@ export const TaskManifest: BuiltinToolManifest = {
type: 'string',
},
identifier: {
- description: 'The identifier of the task to edit.',
+ description:
+ 'The identifier of the task to edit. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
instruction: {
@@ -285,7 +287,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
parentIdentifier: {
description:
- 'Set the parent task by identifier (e.g. "T-1"). Pass null to move this task to top level. Omit to keep the current parent.',
+ 'Set the parent task by identifier (e.g. "T-1"). Pass null to move this task to top level. Omit to keep the current parent. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: ['string', 'null'],
},
priority: {
@@ -293,7 +295,8 @@ export const TaskManifest: BuiltinToolManifest = {
type: 'number',
},
removeDependencies: {
- description: 'Identifiers of existing dependencies to remove.',
+ description:
+ 'Identifiers of existing dependencies to remove. Accepts identifiers or ids returned by previous results; prefer stable ids.',
items: { type: 'string' },
type: 'array',
},
@@ -318,7 +321,8 @@ export const TaskManifest: BuiltinToolManifest = {
type: 'string',
},
identifier: {
- description: 'The task identifier to run (e.g. "T-1").',
+ description:
+ 'The task identifier to run (e.g. "T-1"). Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
prompt: {
@@ -338,7 +342,8 @@ export const TaskManifest: BuiltinToolManifest = {
parameters: {
properties: {
identifiers: {
- description: 'Identifiers of tasks to run, in execution order (e.g. ["T-1", "T-2"]).',
+ description:
+ 'Identifiers of tasks to run, in execution order (e.g. ["T-1", "T-2"]). Accepts identifiers or ids returned by previous results; prefer stable ids.',
items: { type: 'string' },
type: 'array',
},
@@ -365,7 +370,8 @@ export const TaskManifest: BuiltinToolManifest = {
type: 'number',
},
identifier: {
- description: 'The identifier of the task to configure (e.g. "T-1").',
+ description:
+ 'The identifier of the task to configure (e.g. "T-1"). Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
maxExecutions: {
@@ -404,7 +410,8 @@ export const TaskManifest: BuiltinToolManifest = {
type: ['boolean', 'null'],
},
identifier: {
- description: 'The identifier of the task to configure (e.g. "T-1").',
+ description:
+ 'The identifier of the task to configure (e.g. "T-1"). Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
maxIterations: {
@@ -454,7 +461,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
identifier: {
description:
- 'The task identifier (e.g. "T-1"). If omitted, the current task is used only when a current task context exists.',
+ 'The task identifier (e.g. "T-1"). If omitted, the current task is used only when a current task context exists. Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
status: {
@@ -475,7 +482,8 @@ export const TaskManifest: BuiltinToolManifest = {
parameters: {
properties: {
identifier: {
- description: 'The identifier of the task to delete (e.g. "T-1").',
+ description:
+ 'The identifier of the task to delete (e.g. "T-1"). Accepts identifiers or ids returned by previous results; prefer stable ids.',
type: 'string',
},
},
diff --git a/packages/builtin-tool-task/src/systemRole.test.ts b/packages/builtin-tool-task/src/systemRole.test.ts
index 95bb8d0b9c1..3f223791c49 100644
--- a/packages/builtin-tool-task/src/systemRole.test.ts
+++ b/packages/builtin-tool-task/src/systemRole.test.ts
@@ -3,6 +3,15 @@ import { describe, expect, it } from 'vitest';
import { systemPrompt } from './systemRole';
describe('systemPrompt', () => {
+ it('prefers stable ids without rejecting user identifiers', () => {
+ expect(systemPrompt).toContain(
+ 'use the stable id returned by createTask/listTasks in subsequent calls',
+ );
+ expect(systemPrompt).toContain('User-provided identifiers remain accepted');
+ expect(systemPrompt).toContain(
+ 'Use the display identifier in user-facing URLs, e.g. /task/T-3',
+ );
+ });
it('does not instruct the task tool to run the goal workflow', () => {
expect(systemPrompt).not.toContain('**createGoal**');
});
diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.ts
index ddf42745cfc..168e5f7d872 100644
--- a/packages/builtin-tool-task/src/systemRole.ts
+++ b/packages/builtin-tool-task/src/systemRole.ts
@@ -12,7 +12,9 @@ export const systemPrompt = `You have access to Task management tools. Use them
- **runTask**: Actually START a task — kicks off the assigned agent in a new (or continued) topic. Use this to launch execution; do NOT use updateTaskStatus(running) to start a task, that only flips a flag without executing. The task must have an assigneeAgentId
- **runTasks**: Start multiple tasks in one call. Prefer this when launching a batch of related subtasks (e.g. all subtasks you just created); cuts down on tool calls and makes the start atomic from the user's perspective
- **updateTaskStatus**: Change a task's status. If you mark a task as failed, include an error message explaining why. Use this to mark tasks completed/cancelled/paused/failed — NOT to start them (use runTask for that). Omitting identifier only works when there is a current task context
-- **deleteTask**: Delete a task. Subtasks become top-level (not cascaded); dependencies/topics/comments cascade-delete; irreversible. The freed identifier (e.g. "T-9") can be reused by a later task — always quote the identifier freshly returned by createTask/listTasks, never a remembered one
+- **deleteTask**: Delete a task. Subtasks become top-level (not cascaded); dependencies/topics/comments cascade-delete; irreversible. The freed identifier (e.g. "T-9") can be reused by a later task — use the stable id returned by createTask/listTasks in subsequent calls. User-provided identifiers remain accepted
+
+Task links: Use the display identifier in user-facing URLs, e.g. /task/T-3. Keep stable task ids for subsequent tool calls and internal references.
Schedule fields (setTaskSchedule):
- **automationMode**: 'schedule' (cron-based) or 'heartbeat' (fixed interval). Pass null to disable automation
diff --git a/packages/builtin-tool-task/src/taskRef.test.ts b/packages/builtin-tool-task/src/taskRef.test.ts
new file mode 100644
index 00000000000..a89fca30fb2
--- /dev/null
+++ b/packages/builtin-tool-task/src/taskRef.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveTaskOpenTarget } from './taskRef';
+
+describe('historical task cards', () => {
+ it('prefers stable state identity and never overrides it with display aliases', () => {
+ expect(
+ resolveTaskOpenTarget({ taskId: 'task_old', identifier: 'T-1' }, { identifier: 'T-2' }),
+ ).toBe('task_old');
+ });
+ it('opens historical cards through identifier and argument fallbacks', () => {
+ expect(resolveTaskOpenTarget({ identifier: 'T-1' }, { identifier: 'T-2' })).toBe('T-1');
+ expect(resolveTaskOpenTarget(undefined, { identifier: 'T-2' })).toBe('T-2');
+ expect(resolveTaskOpenTarget()).toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tool-task/src/taskRef.ts b/packages/builtin-tool-task/src/taskRef.ts
new file mode 100644
index 00000000000..3a2b6e630e0
--- /dev/null
+++ b/packages/builtin-tool-task/src/taskRef.ts
@@ -0,0 +1,15 @@
+/** Canonical identity for new results, with historical message fallbacks. */
+export const resolveTaskOpenTarget = (
+ state?: { taskId?: string; identifier?: string } | null,
+ args?: { identifier?: string } | null,
+): string | undefined => state?.taskId ?? state?.identifier ?? args?.identifier;
+
+export const taskResultState = (
+ task: { id: string; identifier: string },
+ extra: Record<string, unknown> = {},
+) => ({
+ ...extra,
+ identifier: task.identifier,
+ success: true,
+ taskId: task.id,
+});
diff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.ts
index 84cccb00dc8..32a9c159f6c 100644
--- a/packages/builtin-tool-task/src/types.ts
+++ b/packages/builtin-tool-task/src/types.ts
@@ -78,6 +78,7 @@ export interface CreateTaskState {
/** Lifecycle status the task was created in (usually `backlog`). */
status?: TaskStatus;
success: boolean;
+ taskId?: string;
}
// ==================== createGoal ====================
@@ -124,6 +125,7 @@ export interface CreateTasksItemResult {
identifier?: string;
name: string;
success: boolean;
+ taskId?: string;
}
export interface CreateTasksState {
@@ -178,6 +180,7 @@ export interface ViewTaskParams {
export interface ViewTaskState {
identifier?: string;
success: boolean;
+ taskId?: string;
}
// ==================== task comments ====================
@@ -191,6 +194,7 @@ export interface AddTaskCommentState {
commentId?: string;
identifier: string;
success: boolean;
+ taskId?: string;
}
export interface UpdateTaskCommentParams {
@@ -231,6 +235,7 @@ export interface EditTaskParams {
export interface EditTaskState {
identifier: string;
success: boolean;
+ taskId?: string;
}
// ==================== runTask / runTasks ====================
@@ -247,6 +252,7 @@ export interface RunTaskState {
identifier: string;
operationId?: string;
success: boolean;
+ taskId?: string;
topicId?: string;
}
@@ -259,7 +265,9 @@ export interface RunTasksItemResult {
error?: string;
identifier: string;
operationId?: string;
+ refs?: string[];
success: boolean;
+ taskId?: string;
topicId?: string;
}
@@ -289,6 +297,7 @@ export interface SetTaskScheduleState {
automationMode?: TaskAutomationMode | null;
identifier: string;
success: boolean;
+ taskId?: string;
}
// ==================== setTaskVerify ====================
@@ -313,6 +322,7 @@ export interface SetTaskVerifyState {
enabled?: boolean | null;
identifier: string;
success: boolean;
+ taskId?: string;
}
// ==================== updateTaskStatus ====================
@@ -324,8 +334,10 @@ export interface UpdateTaskStatusParams {
}
export interface UpdateTaskStatusState {
+ identifier?: string;
status: TaskStatus;
success: boolean;
+ taskId?: string;
}
// ==================== deleteTask ====================
@@ -337,4 +349,5 @@ export interface DeleteTaskParams {
export interface DeleteTaskState {
identifier: string;
success: boolean;
+ taskId?: string;
}
diff --git a/packages/builtin-tools/src/workRegistration.test.ts b/packages/builtin-tools/src/workRegistration.test.ts
index 736f1a58db1..238ba34f44c 100644
--- a/packages/builtin-tools/src/workRegistration.test.ts
+++ b/packages/builtin-tools/src/workRegistration.test.ts
@@ -72,7 +72,7 @@ describe('extractTaskWorkTargets', () => {
args: { name: 'A', instruction: 'do' },
result: { state: { identifier: 'T-1', taskId: 'task_1', success: true }, success: true },
}),
- ).toEqual([{ taskId: 'task_1', taskIdentifier: 'T-1' }]);
+ ).toEqual([{ taskId: 'task_1', taskIdentifier: undefined }]);
});
it('falls back to args.identifier for updates that return no state (server runtime)', () => {
@@ -146,7 +146,7 @@ describe('resolveWorkRegistration', () => {
).toEqual({
action: 'create',
changeType: 'created',
- targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ targets: [{ taskId: 'task_1', taskIdentifier: undefined }],
type: 'task',
});
@@ -171,7 +171,7 @@ describe('resolveWorkRegistration', () => {
}),
).toEqual({
action: 'delete',
- targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ targets: [{ taskId: 'task_1', taskIdentifier: undefined }],
type: 'task',
});
});
diff --git a/packages/builtin-tools/src/workRegistration.ts b/packages/builtin-tools/src/workRegistration.ts
index 829ca4af3d8..bfde7526fba 100644
--- a/packages/builtin-tools/src/workRegistration.ts
+++ b/packages/builtin-tools/src/workRegistration.ts
@@ -168,7 +168,9 @@ export const extractTaskWorkTargets = ({
.filter((item) => (item as TaskWorkTargetCandidate).success === true)
.map((item) => ({
taskId: asString((item as TaskWorkTargetCandidate).taskId),
- taskIdentifier: asString((item as TaskWorkTargetCandidate).identifier),
+ taskIdentifier: asString((item as TaskWorkTargetCandidate).taskId)
+ ? undefined
+ : asString((item as TaskWorkTargetCandidate).identifier),
}))
.filter((target) => Boolean(target.taskId || target.taskIdentifier));
};
diff --git a/packages/context-engine/src/processors/TaskCallbackMessage.ts b/packages/context-engine/src/processors/TaskCallbackMessage.ts
index 88a98fce8ce..6f7f82157be 100644
--- a/packages/context-engine/src/processors/TaskCallbackMessage.ts
+++ b/packages/context-engine/src/processors/TaskCallbackMessage.ts
@@ -47,7 +47,7 @@ export class TaskCallbackMessageProcessor extends BaseProcessor {
return [
{
...message,
- content: `<task_result task="${identifier}" status="${reason}">\n${content}\n</task_result>`,
+ content: `<task_result task="${identifier}"${callback?.taskId ? ` id="${callback.taskId}"` : ''} status="${reason}">\n${content}\n</task_result>`,
role: 'user' as const,
},
];
diff --git a/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts b/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts
index 0133d6de655..c18a11bf264 100644
--- a/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts
+++ b/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts
@@ -28,7 +28,7 @@ describe('TaskCallbackMessageProcessor', () => {
expect(result.messages).toHaveLength(3);
const last = result.messages[2];
expect(last.role).toBe('user');
- expect(last.content).toContain('<task_result task="T-42" status="done">');
+ expect(last.content).toContain('<task_result task="T-42" id="t1" status="done">');
expect(last.content).toContain('Fixed the null deref');
expect(result.metadata.taskCallbackMessagesSurfaced).toBe(1);
});
diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.ts
index 4e572e9d149..e316ef3da6c 100644
--- a/packages/database/src/models/__tests__/recent.test.ts
+++ b/packages/database/src/models/__tests__/recent.test.ts
@@ -439,6 +439,7 @@ describe('RecentModel', () => {
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
id: 'task-active',
+ taskIdentifier: 'T-1',
type: 'task',
title: 'Active Task',
routeId: 'agent-assignee',
diff --git a/packages/database/src/models/__tests__/task.checkpoint.test.ts b/packages/database/src/models/__tests__/task.checkpoint.test.ts
new file mode 100644
index 00000000000..69663d45905
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.checkpoint.test.ts
@@ -0,0 +1,121 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users } from '../../schemas';
+import { TaskModel } from '../task';
+
+const serverDB = await getTestDB();
+const userId = 'task-checkpoint-user';
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+});
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+describe('checkpoint', () => {
+ it('should get and update checkpoint config', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ // Initially empty
+ const empty = model.getCheckpointConfig(task);
+ expect(empty).toEqual({});
+
+ // Set checkpoint
+ const updated = await model.updateCheckpointConfig(task.id, {
+ onAgentRequest: true,
+ tasks: { afterIds: ['T-2'], beforeIds: ['T-3'] },
+ topic: { after: true },
+ });
+
+ const config = model.getCheckpointConfig(updated!);
+ expect(config.onAgentRequest).toBe(true);
+ expect(config.topic?.after).toBe(true);
+ expect(config.tasks?.beforeIds).toEqual(['T-3']);
+ expect(config.tasks?.afterIds).toEqual(['T-2']);
+ });
+
+ it('should check shouldPauseBeforeStart', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const parent = await model.create({ instruction: 'Parent' });
+
+ await model.updateCheckpointConfig(parent.id, {
+ tasks: { beforeIds: ['T-5'] },
+ });
+
+ const parentUpdated = (await model.findById(parent.id))!;
+ expect(
+ model.shouldPauseBeforeStart(parentUpdated, { id: 'task_unused', identifier: 'T-5' }),
+ ).toBe(true);
+ expect(
+ model.shouldPauseBeforeStart(parentUpdated, { id: 'task_unused', identifier: 'T-6' }),
+ ).toBe(false);
+ });
+
+ it('should pause on topic complete by default (no config)', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ // No checkpoint configured → should pause (default behavior)
+ expect(model.shouldPauseOnTopicComplete(task)).toBe(true);
+ });
+
+ it('should pause on topic complete when topic.after is true', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ await model.updateCheckpointConfig(task.id, {
+ topic: { after: true },
+ });
+
+ const updated = (await model.findById(task.id))!;
+ expect(model.shouldPauseOnTopicComplete(updated)).toBe(true);
+ });
+
+ it('should not pause on topic complete when only onAgentRequest is set', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ await model.updateCheckpointConfig(task.id, {
+ onAgentRequest: true,
+ });
+
+ const updated = (await model.findById(task.id))!;
+ // Has explicit config but topic.after is not true → don't auto-pause
+ expect(model.shouldPauseOnTopicComplete(updated)).toBe(false);
+ });
+
+ it('should not pause on topic complete when topic.after is false', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ await model.updateCheckpointConfig(task.id, {
+ topic: { after: false },
+ });
+
+ const updated = (await model.findById(task.id))!;
+ expect(model.shouldPauseOnTopicComplete(updated)).toBe(false);
+ });
+
+ it('should check shouldPauseAfterComplete', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const parent = await model.create({ instruction: 'Parent' });
+
+ await model.updateCheckpointConfig(parent.id, {
+ tasks: { afterIds: ['T-2', 'T-3'] },
+ });
+
+ const parentUpdated = (await model.findById(parent.id))!;
+ expect(
+ model.shouldPauseAfterComplete(parentUpdated, { id: 'task_unused', identifier: 'T-2' }),
+ ).toBe(true);
+ expect(
+ model.shouldPauseAfterComplete(parentUpdated, { id: 'task_unused', identifier: 'T-3' }),
+ ).toBe(true);
+ expect(
+ model.shouldPauseAfterComplete(parentUpdated, { id: 'task_unused', identifier: 'T-4' }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/__tests__/task.checkpointTransfer.test.ts b/packages/database/src/models/__tests__/task.checkpointTransfer.test.ts
new file mode 100644
index 00000000000..b2298b83340
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.checkpointTransfer.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { tasks, users, workspaces } from '../../schemas';
+import { TaskModel } from '../task';
+
+const db = await getTestDB();
+const userId = 'checkpoint-transfer-user';
+const workspaceId = 'checkpoint-transfer-workspace';
+const model = new TaskModel(db, userId);
+const destination = new TaskModel(db, userId, workspaceId);
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId });
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'target', slug: workspaceId, primaryOwnerId: userId });
+ await destination.create({ instruction: 'existing destination task' });
+});
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+describe.each(['copy', 'transfer'] as const)('checkpoint %s compatibility', (mode) => {
+ it.each(['legacy', 'dual', 'stale', 'renamed'] as const)(
+ 'rewrites both representations from %s data',
+ async (history) => {
+ const parent = await model.create({ instruction: 'parent' });
+ const a = await model.create({ instruction: 'child A', parentTaskId: parent.id });
+ const b = await model.create({ instruction: 'child B', parentTaskId: parent.id });
+ const label = history === 'stale' ? b.identifier : a.identifier;
+ const pair = { id: a.id, identifier: a.identifier };
+ await model.updateTaskConfig(parent.id, {
+ checkpoint: {
+ tasks: {
+ beforeIds: [label],
+ afterIds: [label],
+ ...(history !== 'legacy' ? { beforeTasks: [pair], afterTasks: [pair] } : {}),
+ },
+ },
+ });
+ if (history === 'renamed') {
+ await db.update(tasks).set({ identifier: 'REN-1' }).where(eq(tasks.id, a.id));
+ await db.update(tasks).set({ identifier: a.identifier }).where(eq(tasks.id, b.id));
+ }
+ const rootId =
+ mode === 'copy'
+ ? (await model.copyToWorkspace(parent.id, workspaceId, userId)).rootId
+ : (await model.transferTo(parent.id, workspaceId, userId), parent.id);
+ const children = await destination.findSubtasks(rootId);
+ const intended = children.find(
+ (child) => child.instruction === (history === 'stale' ? 'child B' : 'child A'),
+ )!;
+ const other = children.find((child) => child.id !== intended.id)!;
+ const stored = (await destination.findById(rootId))!;
+ const refs = destination.getCheckpointConfig(stored).tasks!;
+ const expected = { id: intended.id, identifier: intended.identifier };
+ expect(refs).toEqual({
+ beforeIds: [intended.identifier],
+ beforeTasks: [expected],
+ afterIds: [intended.identifier],
+ afterTasks: [expected],
+ });
+ expect(refs.beforeIds?.includes(intended.identifier)).toBe(true);
+ expect(refs.afterIds?.includes(intended.identifier)).toBe(true);
+ expect(destination.shouldPauseBeforeStart(stored, intended)).toBe(true);
+ expect(destination.shouldPauseBeforeStart(stored, other)).toBe(false);
+ expect(destination.shouldPauseAfterComplete(stored, intended)).toBe(true);
+ expect(
+ mode === 'copy'
+ ? intended.id !== a.id && intended.id !== b.id
+ : [a.id, b.id].includes(intended.id),
+ ).toBe(true);
+ },
+ );
+});
diff --git a/packages/database/src/models/__tests__/task.resolveRefs.test.ts b/packages/database/src/models/__tests__/task.resolveRefs.test.ts
new file mode 100644
index 00000000000..e78aca91394
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.resolveRefs.test.ts
@@ -0,0 +1,132 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { tasks, users, workspaces } from '../../schemas';
+import { TaskModel } from '../task';
+import { WorkModel } from '../work';
+
+const db = await getTestDB();
+const userId = 'task-refs-user';
+const otherId = 'task-refs-other';
+const wsId = 'task-refs-ws';
+const model = new TaskModel(db, userId);
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: wsId, name: 'refs', slug: wsId, primaryOwnerId: userId })
+ .onConflictDoNothing();
+});
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+ await db.delete(users).where(eq(users.id, otherId));
+});
+
+describe('Task stable refs', () => {
+ it('maps mixed refs in input order, deduplicates aliases and excludes invisible rows', async () => {
+ const a = await model.create({ instruction: 'a' });
+ const b = await model.create({ instruction: 'b' });
+ const other = await new TaskModel(db, otherId).create({ instruction: 'other' });
+ const result = await model.resolveRefs([
+ b.identifier.toLowerCase(),
+ a.id,
+ b.id,
+ other.id,
+ 'missing',
+ ]);
+ expect(result.tasks.map((t) => t.id)).toEqual([b.id, a.id]);
+ expect(result.byRef.get(b.identifier.toLowerCase())?.id).toBe(b.id);
+ expect(result.missing).toEqual([other.id, 'missing']);
+ expect(result.ambiguous).toEqual([]);
+ expect((await model.resolveRefs([])).tasks).toEqual([]);
+ await db.update(tasks).set({ isDeleted: true }).where(eq(tasks.id, a.id));
+ expect((await model.resolveRefs([a.id, a.identifier])).missing).toEqual([a.id, a.identifier]);
+ });
+
+ it('isolates personal and workspace identifiers and hides other members private tasks', async () => {
+ const personal = await model.create({ instruction: 'personal' });
+ const workspace = new TaskModel(db, userId, wsId);
+ const publicTask = await workspace.create({ instruction: 'public', visibility: 'public' });
+ const privateTask = await workspace.create({ instruction: 'private', visibility: 'private' });
+ expect(personal.identifier).toBe(publicTask.identifier);
+ expect((await workspace.resolve(personal.identifier))?.id).toBe(publicTask.id);
+ const teammate = new TaskModel(db, otherId, wsId);
+ expect((await teammate.resolve(publicTask.id))?.id).toBe(publicTask.id);
+ expect(
+ (await teammate.resolveRefs([privateTask.id, privateTask.identifier, personal.id])).missing,
+ ).toEqual([privateTask.id, privateTask.identifier, personal.id]);
+ });
+
+ it('never registers Work on a replacement task when the stable id is gone', async () => {
+ const a = await model.create({ instruction: 'old' });
+ await model.delete(a.id);
+ const b = await model.create({ instruction: 'replacement' });
+ expect(b.identifier).toBe(a.identifier);
+ const result = await new WorkModel(db, userId).registerTask({
+ taskId: a.id,
+ taskIdentifier: a.identifier,
+ changeType: 'created',
+ toolName: 'createTask',
+ toolIdentifier: 'lobe-task',
+ });
+ expect(result).toBeNull();
+ });
+
+ it('matches canonical and historical checkpoint entries without activating lowercase history', async () => {
+ const child = await model.create({ instruction: 'child' });
+ const parent = await model.create({
+ instruction: 'parent',
+ config: {
+ checkpoint: {
+ tasks: {
+ beforeIds: [child.identifier],
+ beforeTasks: [{ id: child.id, identifier: child.identifier }],
+ afterIds: [child.identifier],
+ },
+ },
+ },
+ });
+ expect(model.shouldPauseBeforeStart(parent, child)).toBe(true);
+ expect(model.shouldPauseAfterComplete(parent, child)).toBe(true);
+ const lowercase = {
+ ...parent,
+ config: { checkpoint: { tasks: { beforeIds: [child.identifier.toLowerCase()] } } },
+ };
+ expect(model.shouldPauseBeforeStart(lowercase, child)).toBe(false);
+ });
+
+ it('rewrites checkpoint refs after copy and transfer', async () => {
+ const parent = await model.create({ instruction: 'parent' });
+ const child = await model.create({ instruction: 'child', parentTaskId: parent.id });
+ await model.update(parent.id, {
+ config: {
+ checkpoint: {
+ tasks: {
+ beforeIds: [child.identifier],
+ afterIds: [child.identifier],
+ afterTasks: [{ id: child.id, identifier: child.identifier }],
+ },
+ },
+ },
+ });
+ const { rootId } = await model.copyToWorkspace(parent.id, wsId, userId);
+ const workspace = new TaskModel(db, userId, wsId);
+ const [copiedChild] = await workspace.findSubtasks(rootId);
+ const copied = await workspace.findById(rootId);
+ expect(workspace.getCheckpointConfig(copied!).tasks).toEqual({
+ beforeIds: [copiedChild.identifier],
+ beforeTasks: [{ id: copiedChild.id, identifier: copiedChild.identifier }],
+ afterIds: [copiedChild.identifier],
+ afterTasks: [{ id: copiedChild.id, identifier: copiedChild.identifier }],
+ });
+ await model.transferTo(parent.id, wsId, userId);
+ const moved = await workspace.findById(parent.id);
+ const movedChild = (await workspace.findById(child.id))!;
+ expect(workspace.getCheckpointConfig(moved!).tasks).toMatchObject({
+ beforeIds: [movedChild.identifier],
+ beforeTasks: [{ id: child.id, identifier: movedChild.identifier }],
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/task.surface.test.ts b/packages/database/src/models/__tests__/task.surface.test.ts
index 9c313cacac3..14e7af1df9a 100644
--- a/packages/database/src/models/__tests__/task.surface.test.ts
+++ b/packages/database/src/models/__tests__/task.surface.test.ts
@@ -62,7 +62,6 @@ describe('TaskModel public surface', () => {
'findAllDescendants',
'findAssigneesByIds',
'findById',
- 'findByIdentifier',
'findByIds',
'findCommentById',
'findSubtasks',
@@ -90,7 +89,7 @@ describe('TaskModel public surface', () => {
'removeDependency',
'reorder',
'resolve',
- 'resolveMany',
+ 'resolveRefs',
'resolveVerifyConfig',
'shouldPauseAfterComplete',
'shouldPauseBeforeStart',
@@ -138,18 +137,6 @@ describe('TaskModel public surface', () => {
// Methods with no other direct test before the split.
describe('TaskModel previously uncovered reads', () => {
- it('resolveMany matches ids and case-insensitive identifiers within scope', async () => {
- const model = new TaskModel(serverDB, userId);
- const a = await model.create({ instruction: 'a' });
- const b = await model.create({ instruction: 'b' });
- const other = await new TaskModel(serverDB, userId2).create({ instruction: 'other' });
-
- expect(await model.resolveMany([])).toEqual([]);
-
- const resolved = await model.resolveMany([a.id, b.identifier.toLowerCase(), other.id]);
- expect(resolved.map(({ id }) => id).sort()).toEqual([a.id, b.id].sort());
- });
-
it('findCommentById returns only comments in scope', async () => {
const model = new TaskModel(serverDB, userId);
const task = await model.create({ instruction: 'commented' });
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index 812d06f7cae..7ba3ee63d1f 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -217,12 +217,12 @@ describe('TaskModel', () => {
});
});
- describe('findByIdentifier', () => {
+ describe('resolve identifier', () => {
it('should find task by identifier', async () => {
const model = new TaskModel(serverDB, userId);
await model.create({ instruction: 'Test task' });
- const found = await model.findByIdentifier('T-1');
+ const found = await model.resolve('T-1');
expect(found).toBeDefined();
expect(found!.identifier).toBe('T-1');
});
@@ -1347,102 +1347,6 @@ describe('TaskModel', () => {
});
});
- describe('checkpoint', () => {
- it('should get and update checkpoint config', async () => {
- const model = new TaskModel(serverDB, userId);
- const task = await model.create({ instruction: 'Test' });
-
- // Initially empty
- const empty = model.getCheckpointConfig(task);
- expect(empty).toEqual({});
-
- // Set checkpoint
- const updated = await model.updateCheckpointConfig(task.id, {
- onAgentRequest: true,
- tasks: { afterIds: ['T-2'], beforeIds: ['T-3'] },
- topic: { after: true },
- });
-
- const config = model.getCheckpointConfig(updated!);
- expect(config.onAgentRequest).toBe(true);
- expect(config.topic?.after).toBe(true);
- expect(config.tasks?.beforeIds).toEqual(['T-3']);
- expect(config.tasks?.afterIds).toEqual(['T-2']);
- });
-
- it('should check shouldPauseBeforeStart', async () => {
- const model = new TaskModel(serverDB, userId);
- const parent = await model.create({ instruction: 'Parent' });
-
- await model.updateCheckpointConfig(parent.id, {
- tasks: { beforeIds: ['T-5'] },
- });
-
- const parentUpdated = (await model.findById(parent.id))!;
- expect(model.shouldPauseBeforeStart(parentUpdated, 'T-5')).toBe(true);
- expect(model.shouldPauseBeforeStart(parentUpdated, 'T-6')).toBe(false);
- });
-
- it('should pause on topic complete by default (no config)', async () => {
- const model = new TaskModel(serverDB, userId);
- const task = await model.create({ instruction: 'Test' });
-
- // No checkpoint configured → should pause (default behavior)
- expect(model.shouldPauseOnTopicComplete(task)).toBe(true);
- });
-
- it('should pause on topic complete when topic.after is true', async () => {
- const model = new TaskModel(serverDB, userId);
- const task = await model.create({ instruction: 'Test' });
-
- await model.updateCheckpointConfig(task.id, {
- topic: { after: true },
- });
-
- const updated = (await model.findById(task.id))!;
- expect(model.shouldPauseOnTopicComplete(updated)).toBe(true);
- });
-
- it('should not pause on topic complete when only onAgentRequest is set', async () => {
- const model = new TaskModel(serverDB, userId);
- const task = await model.create({ instruction: 'Test' });
-
- await model.updateCheckpointConfig(task.id, {
- onAgentRequest: true,
- });
-
- const updated = (await model.findById(task.id))!;
- // Has explicit config but topic.after is not true → don't auto-pause
- expect(model.shouldPauseOnTopicComplete(updated)).toBe(false);
- });
-
- it('should not pause on topic complete when topic.after is false', async () => {
- const model = new TaskModel(serverDB, userId);
- const task = await model.create({ instruction: 'Test' });
-
- await model.updateCheckpointConfig(task.id, {
- topic: { after: false },
- });
-
- const updated = (await model.findById(task.id))!;
- expect(model.shouldPauseOnTopicComplete(updated)).toBe(false);
- });
-
- it('should check shouldPauseAfterComplete', async () => {
- const model = new TaskModel(serverDB, userId);
- const parent = await model.create({ instruction: 'Parent' });
-
- await model.updateCheckpointConfig(parent.id, {
- tasks: { afterIds: ['T-2', 'T-3'] },
- });
-
- const parentUpdated = (await model.findById(parent.id))!;
- expect(model.shouldPauseAfterComplete(parentUpdated, 'T-2')).toBe(true);
- expect(model.shouldPauseAfterComplete(parentUpdated, 'T-3')).toBe(true);
- expect(model.shouldPauseAfterComplete(parentUpdated, 'T-4')).toBe(false);
- });
- });
-
describe('updateTaskConfig', () => {
it('should merge partial config into empty config', async () => {
const model = new TaskModel(serverDB, userId);
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index b1242effca9..6c2c92a3587 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -33,6 +33,7 @@ export interface RecentDbItem {
slugTitle?: string | null;
/** Task lifecycle status when `type === 'task'`; null for topic/document. */
status: TaskStatus | null;
+ taskIdentifier?: string | null;
title: string;
type: 'topic' | 'document' | 'task';
updatedAt: Date;
@@ -127,6 +128,7 @@ export class RecentModel {
? topics.description
: sql<string | null>`NULL`.as('description'),
id: topics.id,
+ taskIdentifier: sql<string | null>`NULL`.as('task_identifier'),
metadata: sql<any>`${topics.metadata}`.as('metadata'),
routeGroupId: sql<string | null>`${topics.groupId}`.as('route_group_id'),
routeId: sql<string | null>`${topics.agentId}`.as('route_id'),
@@ -174,6 +176,7 @@ export class RecentModel {
.select({
description: sql<string | null>`NULL`.as('description'),
id: documents.id,
+ taskIdentifier: sql<string | null>`NULL`.as('task_identifier'),
metadata: sql<any>`NULL`.as('metadata'),
routeGroupId: sql<string | null>`NULL`.as('route_group_id'),
routeId: sql<string | null>`NULL`.as('route_id'),
@@ -204,6 +207,7 @@ export class RecentModel {
.select({
description: sql<string | null>`NULL`.as('description'),
id: tasks.id,
+ taskIdentifier: sql<string | null>`${tasks.identifier}`.as('task_identifier'),
metadata: sql<any>`NULL`.as('metadata'),
routeGroupId: sql<string | null>`NULL`.as('route_group_id'),
routeId: sql<string | null>`${tasks.assigneeAgentId}`.as('route_id'),
@@ -249,6 +253,7 @@ export class RecentModel {
? `${preview.slice(0, LAST_MESSAGE_PREVIEW_LENGTH)}…`
: preview,
metadata: row.metadata ?? undefined,
+ taskIdentifier: row.taskIdentifier,
routeGroupId: row.routeGroupId,
routeId: row.routeId,
slugTitle: row.slugTitle,
diff --git a/packages/database/src/models/task/checkpoint.test.ts b/packages/database/src/models/task/checkpoint.test.ts
new file mode 100644
index 00000000000..55c808ed3a5
--- /dev/null
+++ b/packages/database/src/models/task/checkpoint.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ checkpointTaskMatcher,
+ checkpointTaskPairsMatch,
+ remapCheckpointConfig,
+} from './checkpoint';
+
+const a = { id: 'task_a', identifier: 'T-1' };
+const b = { id: 'task_b', identifier: 'T-2' };
+const target = { id: 'task_new', identifier: 'T-10' };
+
+describe('checkpoint identity consistency', () => {
+ it('compares exact identifier sets, regardless of order or duplicates', () => {
+ expect(checkpointTaskPairsMatch(['T-2', 'T-1', 'T-1'], [a, b])).toBe(true);
+ expect(checkpointTaskPairsMatch(['t-1'], [a])).toBe(false);
+ expect(checkpointTaskPairsMatch(['T-1'], undefined)).toBe(false);
+ expect(checkpointTaskPairsMatch([], [])).toBe(true);
+ });
+ it('matches a renamed child by id and rejects a replacement holding its old label', () => {
+ const match = checkpointTaskMatcher(['T-1'], [a]);
+ expect(match({ ...a, identifier: 'REN-1' })).toBe(true);
+ expect(match({ ...b, identifier: 'T-1' })).toBe(false);
+ });
+ it('falls back to exact legacy labels when old writers leave stale pairs', () => {
+ const match = checkpointTaskMatcher(['T-2'], [a]);
+ expect(match(a)).toBe(false);
+ expect(match(b)).toBe(true);
+ expect(checkpointTaskMatcher([], [a])(a)).toBe(false);
+ expect(checkpointTaskMatcher(['t-1'], undefined)(a)).toBe(false);
+ expect(checkpointTaskMatcher(['task_a'], undefined)(a)).toBe(false);
+ expect(checkpointTaskMatcher(['T-1'], undefined)(a)).toBe(true);
+ });
+});
+
+describe('checkpoint relocation', () => {
+ it('rewrites both fields and fills pairs for legacy data without activating invalid history', () => {
+ expect(
+ remapCheckpointConfig(
+ {
+ model: 'm',
+ checkpoint: {
+ topic: { after: true },
+ tasks: { beforeIds: ['T-1', 't-1', 'OUTSIDE-2', 'task_a'] },
+ },
+ },
+ [{ source: a, target }],
+ ),
+ ).toEqual({
+ model: 'm',
+ checkpoint: {
+ topic: { after: true },
+ tasks: {
+ beforeIds: ['T-10', 't-1', 'OUTSIDE-2', 'task_a'],
+ beforeTasks: [target],
+ },
+ },
+ });
+ });
+ it('uses consistent ids after rename even if the old label now belongs to a different task', () => {
+ expect(
+ remapCheckpointConfig(
+ {
+ checkpoint: {
+ tasks: {
+ beforeIds: ['T-1'],
+ beforeTasks: [a],
+ },
+ },
+ },
+ [
+ { source: { ...a, identifier: 'REN-1' }, target },
+ { source: { ...b, identifier: 'T-1' }, target: { id: 'task_wrong', identifier: 'T-11' } },
+ ],
+ ),
+ ).toEqual({ checkpoint: { tasks: { beforeIds: ['T-10'], beforeTasks: [target] } } });
+ });
+ it('rebuilds stale pairs from the legacy intent and preserves unrelated references', () => {
+ expect(
+ remapCheckpointConfig(
+ {
+ checkpoint: {
+ tasks: {
+ afterIds: ['T-2'],
+ afterTasks: [a],
+ },
+ },
+ },
+ [{ source: b, target }],
+ ),
+ ).toEqual({
+ checkpoint: {
+ tasks: {
+ afterIds: ['T-10'],
+ afterTasks: [target],
+ },
+ },
+ });
+ expect(
+ remapCheckpointConfig(
+ {
+ checkpoint: {
+ tasks: {
+ beforeIds: ['T-1'],
+ beforeTasks: [a],
+ },
+ },
+ },
+ [],
+ ),
+ ).toEqual({ checkpoint: { tasks: { beforeIds: ['T-1'], beforeTasks: [a] } } });
+ });
+ it('keeps absent and non-checkpoint configs intact', () => {
+ expect(remapCheckpointConfig(null, [])).toBeNull();
+ const config = { model: 'm' };
+ expect(remapCheckpointConfig(config, [])).toBe(config);
+ });
+});
diff --git a/packages/database/src/models/task/checkpoint.ts b/packages/database/src/models/task/checkpoint.ts
new file mode 100644
index 00000000000..305daaa79ff
--- /dev/null
+++ b/packages/database/src/models/task/checkpoint.ts
@@ -0,0 +1,63 @@
+import type { CheckpointConfig, CheckpointTaskRef, TaskItem } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+
+/** Old writers can leave stale pairs behind when replacing only the label list. */
+export const checkpointTaskPairsMatch = (
+ ids: readonly string[] | undefined,
+ pairs: readonly CheckpointTaskRef[] | undefined,
+): boolean => {
+ if (!pairs) return false;
+ const identifiers = new Set(ids ?? []);
+ const snapshots = new Set(pairs.map((pair) => pair.identifier));
+ return identifiers.size === snapshots.size && [...identifiers].every((id) => snapshots.has(id));
+};
+
+/** Trust stable ids only while their label snapshots agree with the legacy field. */
+export const checkpointTaskMatcher = (
+ ids: readonly string[] | undefined,
+ pairs: readonly CheckpointTaskRef[] | undefined,
+): ((child: Pick<TaskItem, 'id' | 'identifier'>) => boolean) => {
+ if (checkpointTaskPairsMatch(ids, pairs)) {
+ const taskIds = new Set(pairs!.map((pair) => pair.id));
+ return (child) => taskIds.has(child.id);
+ }
+ return (child) => ids?.includes(child.identifier) ?? false;
+};
+
+export interface CheckpointTaskRelocation {
+ source: CheckpointTaskRef;
+ target: CheckpointTaskRef;
+}
+
+/** Relocate both representations, preserving exact, inactive historical values. */
+export const remapCheckpointConfig = (
+ config: TaskItem['config'],
+ relocations: readonly CheckpointTaskRelocation[],
+): TaskItem['config'] => {
+ if (!isRecord(config)) return config;
+ const checkpoint = config.checkpoint as CheckpointConfig | undefined;
+ if (!checkpoint?.tasks) return config;
+ const byId = new Map(relocations.map(({ source, target }) => [source.id, target]));
+ const byIdentifier = new Map(
+ relocations.map(({ source, target }) => [source.identifier, target]),
+ );
+ const tasks = { ...checkpoint.tasks };
+ for (const [idsKey, pairsKey] of [
+ ['beforeIds', 'beforeTasks'],
+ ['afterIds', 'afterTasks'],
+ ] as const) {
+ const ids = tasks[idsKey];
+ if (!ids) continue;
+ const pairs = tasks[pairsKey];
+ const references = checkpointTaskPairsMatch(ids, pairs)
+ ? pairs!.map((pair) => byId.get(pair.id) ?? pair)
+ : ids.map((identifier) => byIdentifier.get(identifier) ?? { identifier });
+ tasks[idsKey] = [...new Set(references.map((ref) => ref.identifier))];
+ tasks[pairsKey] = [
+ ...new Map(
+ references.flatMap((ref) => ('id' in ref ? [[ref.id, ref] as const] : [])),
+ ).values(),
+ ];
+ }
+ return { ...config, checkpoint: { ...checkpoint, tasks } };
+};
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index 2ad302fafc4..c7d9216a79f 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -22,12 +22,14 @@ import type { LobeChatDatabase } from '../../type';
import { ProjectModel } from '../project';
import type { TaskListFilterOptions, TaskListOptions } from '../taskListFilters';
import * as activities from './activities';
+import { checkpointTaskMatcher } from './checkpoint';
import * as comments from './comments';
import * as config from './config';
import { getTaskVisibility, type TaskModelContext, taskOwnership } from './context';
import * as dependencies from './dependencies';
import * as documents from './documents';
import * as queries from './queries';
+import { resolveRefs } from './refs';
import * as rows from './rows';
import type { OrphanedRunningTopic } from './scheduling';
import * as scheduling from './scheduling';
@@ -125,18 +127,14 @@ export class TaskModel {
return rows.findAssigneesByIds(this.ctx, ids);
}
- async resolveMany(idsOrIdentifiers: string[]): Promise<TaskItem[]> {
- return rows.resolveMany(this.ctx, idsOrIdentifiers);
+ async resolveRefs(refs: string[]) {
+ return resolveRefs(this.ctx, refs);
}
- // Resolve id or identifier (e.g. 'T-1') to a task
- async resolve(idOrIdentifier: string): Promise<TaskItem | null> {
- if (idOrIdentifier.startsWith('task_')) return this.findById(idOrIdentifier);
- return this.findByIdentifier(idOrIdentifier.toUpperCase());
- }
-
- async findByIdentifier(identifier: string): Promise<TaskItem | null> {
- return rows.findByIdentifier(this.ctx, identifier);
+ async resolve(ref: string): Promise<TaskItem | null> {
+ const result = await this.resolveRefs([ref]);
+ if (result.ambiguous.length) throw new Error(`Ambiguous task reference: ${ref}`);
+ return result.byRef.get(ref) ?? null;
}
async update(
@@ -408,15 +406,21 @@ export class TaskModel {
}
// Check if a task should be paused before starting (parent's tasks.beforeIds)
- shouldPauseBeforeStart(parentTask: TaskItem, childIdentifier: string): boolean {
+ shouldPauseBeforeStart(
+ parentTask: TaskItem,
+ child: Pick<TaskItem, 'id' | 'identifier'>,
+ ): boolean {
const checkpoint = this.getCheckpointConfig(parentTask);
- return checkpoint.tasks?.beforeIds?.includes(childIdentifier) ?? false;
+ return checkpointTaskMatcher(checkpoint.tasks?.beforeIds, checkpoint.tasks?.beforeTasks)(child);
}
// Check if a task should be paused after completing (parent's tasks.afterIds)
- shouldPauseAfterComplete(parentTask: TaskItem, childIdentifier: string): boolean {
+ shouldPauseAfterComplete(
+ parentTask: TaskItem,
+ child: Pick<TaskItem, 'id' | 'identifier'>,
+ ): boolean {
const checkpoint = this.getCheckpointConfig(parentTask);
- return checkpoint.tasks?.afterIds?.includes(childIdentifier) ?? false;
+ return checkpointTaskMatcher(checkpoint.tasks?.afterIds, checkpoint.tasks?.afterTasks)(child);
}
// ========== Heartbeat ==========
diff --git a/packages/database/src/models/task/refs.test.ts b/packages/database/src/models/task/refs.test.ts
new file mode 100644
index 00000000000..22141003aa2
--- /dev/null
+++ b/packages/database/src/models/task/refs.test.ts
@@ -0,0 +1,30 @@
+import type { TaskItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { matchTaskRefs, parseTaskRef } from './refs';
+
+const task = (id: string, identifier: string) => ({ id, identifier }) as TaskItem;
+
+describe('task ref classification and matching', () => {
+ it('trims and preserves case-sensitive ids, uppercasing aliases only', () => {
+ expect(parseTaskRef(' task_AbC ')).toEqual({
+ kind: 'id',
+ raw: ' task_AbC ',
+ value: 'task_AbC',
+ });
+ expect(parseTaskRef(' abc-3 ')).toEqual({ kind: 'identifier', raw: ' abc-3 ', value: 'ABC-3' });
+ expect(parseTaskRef('TASK_AbC').kind).toBe('identifier');
+ expect(parseTaskRef(' ').value).toBe('');
+ });
+ it('never crosses buckets and returns ambiguous refs rather than an arbitrary match', () => {
+ const rows = [task('task_AbC', 'T-1'), task('task_B', 'T-1'), task('task_C', 'TASK_MISSING')];
+ const result = matchTaskRefs(
+ ['T-1', 'task_missing', 'task_AbC', ' task_AbC ', 'nonsense'].map(parseTaskRef),
+ rows,
+ );
+ expect(result.ambiguous).toEqual(['T-1']);
+ expect(result.missing).toEqual(['task_missing', 'nonsense']);
+ expect(result.tasks.map((t) => t.id)).toEqual(['task_AbC']);
+ expect(result.byRef.get(' task_AbC ')?.id).toBe('task_AbC');
+ });
+});
diff --git a/packages/database/src/models/task/refs.ts b/packages/database/src/models/task/refs.ts
new file mode 100644
index 00000000000..b638318a7d6
--- /dev/null
+++ b/packages/database/src/models/task/refs.ts
@@ -0,0 +1,70 @@
+import type { TaskItem } from '@lobechat/types';
+import { and, inArray, or } from 'drizzle-orm';
+
+import { tasks } from '../../schemas/task';
+import { type TaskModelContext, taskOwnership } from './context';
+
+export interface ParsedTaskRef {
+ kind: 'id' | 'identifier';
+ raw: string;
+ value: string;
+}
+
+/** Classify once. An id must never fall back to an identifier (or vice versa). */
+export const parseTaskRef = (raw: string): ParsedTaskRef => {
+ const value = raw.trim();
+ return value.startsWith('task_')
+ ? { kind: 'id', raw, value }
+ : { kind: 'identifier', raw, value: value.toUpperCase() };
+};
+
+export const matchTaskRefs = (refs: ParsedTaskRef[], rows: TaskItem[]) => {
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ const byIdentifier = new Map<string, TaskItem[]>();
+ for (const row of rows) {
+ const matches = byIdentifier.get(row.identifier) ?? [];
+ matches.push(row);
+ byIdentifier.set(row.identifier, matches);
+ }
+ const byRef = new Map<string, TaskItem>();
+ const resolved = new Map<string, TaskItem>();
+ const missing: string[] = [];
+ const ambiguous: string[] = [];
+ for (const ref of refs) {
+ const matches =
+ ref.kind === 'id'
+ ? byId.has(ref.value)
+ ? [byId.get(ref.value)!]
+ : []
+ : (byIdentifier.get(ref.value) ?? []);
+ if (matches.length > 1) ambiguous.push(ref.raw);
+ else if (matches.length === 0) missing.push(ref.raw);
+ else {
+ byRef.set(ref.raw, matches[0]);
+ resolved.set(matches[0].id, matches[0]);
+ }
+ }
+ return { ambiguous, byRef, missing, tasks: [...resolved.values()] };
+};
+
+export const resolveRefs = async (ctx: TaskModelContext, rawRefs: string[]) => {
+ const refs = rawRefs.map(parseTaskRef);
+ const ids = refs.filter((ref) => ref.kind === 'id').map((ref) => ref.value);
+ const identifiers = refs.filter((ref) => ref.kind === 'identifier').map((ref) => ref.value);
+ const rows =
+ refs.length === 0
+ ? []
+ : await ctx.db
+ .select()
+ .from(tasks)
+ .where(
+ and(
+ taskOwnership(ctx),
+ or(
+ ids.length ? inArray(tasks.id, ids) : undefined,
+ identifiers.length ? inArray(tasks.identifier, identifiers) : undefined,
+ ),
+ ),
+ );
+ return matchTaskRefs(refs, rows);
+};
diff --git a/packages/database/src/models/task/rows.ts b/packages/database/src/models/task/rows.ts
index 92e1346952a..b98775b3154 100644
--- a/packages/database/src/models/task/rows.ts
+++ b/packages/database/src/models/task/rows.ts
@@ -97,36 +97,6 @@ export const findAssigneesByIds = async (
.where(and(inArray(tasks.id, ids), taskOwnership(ctx)));
};
-export const resolveMany = async (
- ctx: TaskModelContext,
- idsOrIdentifiers: string[],
-): Promise<TaskItem[]> => {
- if (idsOrIdentifiers.length === 0) return [];
- const identifiers = idsOrIdentifiers.map((value) => value.toUpperCase());
- return ctx.db
- .select()
- .from(tasks)
- .where(
- and(
- or(inArray(tasks.id, idsOrIdentifiers), inArray(tasks.identifier, identifiers)),
- taskOwnership(ctx),
- ),
- );
-};
-
-export const findByIdentifier = async (
- ctx: TaskModelContext,
- identifier: string,
-): Promise<TaskItem | null> => {
- const result = await ctx.db
- .select()
- .from(tasks)
- .where(and(eq(tasks.identifier, identifier), taskOwnership(ctx)))
- .limit(1);
-
- return result[0] || null;
-};
-
/** The column write itself — the assignee rule lives in `update`. */
export const writeRow = async (
ctx: TaskModelContext,
diff --git a/packages/database/src/models/task/transfer.ts b/packages/database/src/models/task/transfer.ts
index db4daf364e9..4c48e4060f0 100644
--- a/packages/database/src/models/task/transfer.ts
+++ b/packages/database/src/models/task/transfer.ts
@@ -10,6 +10,7 @@ import {
tasks,
} from '../../schemas/task';
import type { LobeChatDatabase } from '../../type';
+import { type CheckpointTaskRelocation, remapCheckpointConfig } from './checkpoint';
import type { TaskModelContext } from './context';
import { collectTaskSubtree } from './tree';
import { DEFAULT_TASK_IDENTIFIER_PREFIX } from './utils';
@@ -69,6 +70,10 @@ export const transferTo = async (
// Reallocate identifier + seq in target scope to avoid collisions.
const baseSeq = await nextSeqIn(trx as LobeChatDatabase, targetWorkspaceId, targetUserId);
+ const relocations = subtree.map((task, index) => ({
+ source: task,
+ target: { id: task.id, identifier: `T-${baseSeq + index}` },
+ }));
// Update each task individually because identifier/seq are per-row.
for (const [idx, task] of subtree.entries()) {
const seq = baseSeq + idx;
@@ -79,6 +84,7 @@ export const transferTo = async (
// Clear cross-scope refs: agent / topic may be invalid in new scope.
assigneeAgentId: targetWorkspaceId === ctx.workspaceId ? task.assigneeAgentId : null,
createdByUserId: targetUserId,
+ config: remapCheckpointConfig(task.config, relocations),
currentTopicId: null,
identifier,
seq,
@@ -138,6 +144,7 @@ export const copyToWorkspace = async (
// BFS clone — parent inserted before children, so we always know the
// new parentTaskId by the time we reach the child.
const idMap = new Map<string, string>();
+ const relocations: CheckpointTaskRelocation[] = [];
const byId = new Map(subtree.map((t) => [t.id, t]));
const queue: string[] = [taskId];
const seen = new Set<string>();
@@ -193,9 +200,13 @@ export const copyToWorkspace = async (
workspaceId: targetWorkspaceId,
...visibilityOverride,
} as NewTask)
- .returning({ id: tasks.id })) as { id: string }[];
+ .returning({ id: tasks.id, identifier: tasks.identifier })) as {
+ id: string;
+ identifier: string;
+ }[];
idMap.set(original.id, inserted[0]!.id);
+ relocations.push({ source: original, target: inserted[0]! });
seq++;
for (const c of subtree) {
@@ -203,6 +214,17 @@ export const copyToWorkspace = async (
}
}
+ for (const original of subtree) {
+ await (trx as LobeChatDatabase)
+ .update(tasks)
+ .set({
+ config: remapCheckpointConfig(
+ withoutTaskExecutionSelection(original.config as Record<string, unknown> | null),
+ relocations,
+ ),
+ })
+ .where(eq(tasks.id, idMap.get(original.id)!));
+ }
return { rootId: idMap.get(taskId)! };
});
};
diff --git a/packages/database/src/models/work/task.ts b/packages/database/src/models/work/task.ts
index 1016803a17f..1251ddfa72e 100644
--- a/packages/database/src/models/work/task.ts
+++ b/packages/database/src/models/work/task.ts
@@ -4,12 +4,12 @@ import type {
TaskWorkListItem,
TaskWorkSummaryItem,
} from '@lobechat/types';
-import type { SQL } from 'drizzle-orm';
-import { and, desc, eq, or } from 'drizzle-orm';
+import { and, desc, eq } from 'drizzle-orm';
import { tasks } from '../../schemas/task';
import { works, workVersions } from '../../schemas/work';
-import { taskOwnership, type WorkContext, workOwnership } from './context';
+import { TaskModel } from '../task';
+import { type WorkContext, workOwnership } from './context';
import {
currentTaskSummaryFields,
currentWorkListFields,
@@ -25,12 +25,6 @@ import {
} from './internal';
import { registerWorkVersion } from './writes';
-const normalizeTaskLookup = (value?: string) => {
- const trimmed = value?.trim();
- if (!trimmed) return undefined;
- return trimmed.startsWith('task_') ? trimmed : trimmed.toUpperCase();
-};
-
/**
* Task display fields captured by each immutable version. Live data stays on
* the `tasks` row (joined by every query); snapshots provide the deletion
@@ -48,31 +42,9 @@ const resolveTask = async (
ctx: WorkContext,
params: RegisterTaskWorkParams,
): Promise<TaskItem | null> => {
- const filters: SQL[] = [];
- const taskId = normalizeTaskLookup(params.taskId);
- const taskIdentifier = normalizeTaskLookup(params.taskIdentifier);
-
- if (taskId) {
- filters.push(taskId.startsWith('task_') ? eq(tasks.id, taskId) : eq(tasks.identifier, taskId));
- }
-
- if (taskIdentifier) {
- filters.push(
- taskIdentifier.startsWith('task_')
- ? eq(tasks.id, taskIdentifier)
- : eq(tasks.identifier, taskIdentifier),
- );
- }
-
- if (filters.length === 0) return null;
-
- const [task] = await ctx.db
- .select()
- .from(tasks)
- .where(and(taskOwnership(ctx), filters.length === 1 ? filters[0] : or(...filters)))
- .limit(1);
-
- return task ?? null;
+ const ref = params.taskId ?? params.taskIdentifier;
+ if (!ref) return null;
+ return new TaskModel(ctx.db, ctx.userId, ctx.workspaceId).resolve(ref);
};
export const registerTaskWork = async (ctx: WorkContext, params: RegisterTaskWorkParams) => {
diff --git a/packages/openapi/src/services/task.service.test.ts b/packages/openapi/src/services/task.service.test.ts
index 5d7f7ba0a4c..137da0e967e 100644
--- a/packages/openapi/src/services/task.service.test.ts
+++ b/packages/openapi/src/services/task.service.test.ts
@@ -13,6 +13,7 @@ const {
hasAnyPermissionMock,
notifyAssignedMock,
resolveMock,
+ resolveRefsMock,
resolveTaskPatchInvariantsMock,
runTaskMock,
updateTaskMock,
@@ -23,6 +24,7 @@ const {
hasAnyPermissionMock: vi.fn(),
notifyAssignedMock: vi.fn(),
resolveMock: vi.fn(),
+ resolveRefsMock: vi.fn(),
resolveTaskPatchInvariantsMock: vi.fn(),
runTaskMock: vi.fn(),
updateTaskMock: vi.fn(),
@@ -57,6 +59,7 @@ vi.mock('@/database/models/agent', () => ({
vi.mock('@/database/models/task', () => ({
TaskModel: class {
resolve = resolveMock;
+ resolveRefs = resolveRefsMock;
},
}));
vi.mock('@/database/models/taskTopic', () => ({
@@ -144,6 +147,59 @@ describe('TaskRestService patch runs the shared invariants', () => {
updateTaskMock.mockResolvedValue({ id: 'task-1' });
});
+ it('preserves unchanged legacy checkpoint selections after a selected task is deleted', async () => {
+ const tasks = { beforeIds: ['T-2'], afterIds: ['T-2'] };
+ resolveTaskPatchInvariantsMock.mockImplementation(async (_, { data }) => ({
+ data,
+ resolved: { id: 'task-1', config: { checkpoint: { tasks } } },
+ }));
+ resolveRefsMock.mockImplementation(async (refs) => ({
+ ambiguous: [],
+ byRef: new Map(),
+ missing: refs,
+ tasks: [],
+ }));
+ updateTaskMock.mockImplementation(async (id, data) => ({ id, ...data }));
+ const config = { checkpoint: { tasks, topic: { before: true } } };
+
+ await expect(service().updateTask('T-1', { config })).resolves.toEqual({
+ id: 'task-1',
+ config,
+ });
+ expect(resolveRefsMock).not.toHaveBeenCalled();
+
+ updateTaskMock.mockClear();
+ await expect(
+ service().updateTask('T-1', {
+ config: { checkpoint: { tasks: { beforeIds: ['MISSING'] } } },
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: expect.stringContaining('MISSING') });
+ expect(updateTaskMock).not.toHaveBeenCalled();
+ });
+
+ it('dual-writes explicitly replaced checkpoint selections', async () => {
+ resolveTaskPatchInvariantsMock.mockImplementation(async (_, { data }) => ({
+ data,
+ resolved: { id: 'task-1', config: { checkpoint: { tasks: { beforeIds: ['T-2'] } } } },
+ }));
+ const selected = { id: 'task_3', identifier: 'T-3' };
+ resolveRefsMock.mockResolvedValue({
+ ambiguous: [],
+ byRef: new Map([['t-3', selected]]),
+ missing: [],
+ tasks: [selected],
+ });
+ updateTaskMock.mockImplementation(async (id, data) => ({ id, ...data }));
+
+ await expect(
+ service().updateTask('T-1', {
+ config: { checkpoint: { tasks: { beforeIds: ['t-3'] } } },
+ }),
+ ).resolves.toMatchObject({
+ config: { checkpoint: { tasks: { beforeIds: ['T-3'], beforeTasks: [selected] } } },
+ });
+ });
+
it('writes the row the invariants resolved, not the raw path id', async () => {
await expect(service().updateTask('TASK-1', { parentTaskId: 'parent-1' })).resolves.toEqual({
id: 'task-1',
diff --git a/packages/openapi/src/services/task.service.ts b/packages/openapi/src/services/task.service.ts
index 2ef874c3c70..74a4f350377 100644
--- a/packages/openapi/src/services/task.service.ts
+++ b/packages/openapi/src/services/task.service.ts
@@ -9,6 +9,7 @@ import { TaskService } from '@/server/services/task';
import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';
import { resolveTaskPatchInvariants } from '@/server/services/task/patchValidation';
import { assertResultingScheduleValid } from '@/server/services/task/scheduleValidation';
+import { normalizeTaskConfig, resolveTaskOrThrow } from '@/server/services/task/utils';
import { TaskRunnerService } from '@/server/services/taskRunner';
import { BaseService } from '../common/base.service';
@@ -79,7 +80,9 @@ export class TaskRestService extends BaseService {
}
async getTask(id: string): ServiceResult<unknown> {
- const detail = await this.taskService.getTaskDetail(id);
+ const detail = await this.taskService.getTaskDetail(
+ (await resolveTaskOrThrow(this.taskModel, id)).id,
+ );
if (!detail) throw this.createNotFoundError('Task not found');
return detail;
}
@@ -90,7 +93,13 @@ export class TaskRestService extends BaseService {
// create boundary, so a schedule the dispatcher cannot evaluate is refused
// here instead of being stored and silently never firing.
assertResultingScheduleValid(null, input);
- const task = await this.taskService.createTask(input);
+ const task = await this.taskService.createTask({
+ ...input,
+ config: await normalizeTaskConfig(this.taskModel, input.config),
+ parentTaskId: input.parentTaskId
+ ? (await resolveTaskOrThrow(this.taskModel, input.parentTaskId)).id
+ : undefined,
+ });
// Creating a task already assigned to another member notifies them, the way
// the tRPC create boundary does; self-assignment is filtered inside the
// helper, so this stays silent for the caller's own task.
@@ -113,8 +122,11 @@ export class TaskRestService extends BaseService {
userId: this.userId,
workspaceId: this.workspaceId,
},
- { data: input, id, parentTaskId: input.parentTaskId },
+ { data: { ...input }, id, parentTaskId: input.parentTaskId },
);
+ if (data.config) {
+ data.config = await normalizeTaskConfig(this.taskModel, data.config, resolved.config);
+ }
// The patch is a partial row update; the model owns which columns are
// accepted and normalises the null-vs-undefined distinction itself.
@@ -138,7 +150,11 @@ export class TaskRestService extends BaseService {
// A person (or their agent) made this change, so it belongs in the feed —
// the service treats a missing actor as a system transition.
return this.taskService.updateStatus(
- { error: input.error, id, status: input.status },
+ {
+ error: input.error,
+ id: (await resolveTaskOrThrow(this.taskModel, id)).id,
+ status: input.status,
+ },
{ userId: this.userId },
);
}
diff --git a/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap
index ed5d6674104..15713a7dd78 100644
--- a/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap
+++ b/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap
@@ -13,8 +13,8 @@ exports[`buildProjectContextPrompt > gives the coordinator the roster, knowledge
- Research (kb_research)
</knowledge_bases>
<open_tasks total="5">
- APO-2 ● running [high] Draft post — Writer (agt_writer)
- APO-3 ○ backlog [-] (unnamed) — unassigned
+ APO-2 (id: undefined) ● running [high] Draft post — Writer (agt_writer)
+ APO-3 (id: undefined) ○ backlog [-] (unnamed) — unassigned
… and 3 more
</open_tasks>
<coordination_rules>
diff --git a/packages/prompts/src/prompts/project/index.ts b/packages/prompts/src/prompts/project/index.ts
index 66b9c618205..5d10c6bf7b1 100644
--- a/packages/prompts/src/prompts/project/index.ts
+++ b/packages/prompts/src/prompts/project/index.ts
@@ -114,7 +114,7 @@ export const buildProjectContextPrompt = (input: ProjectContextPromptInput): str
? (memberLabel(membersById.get(task.assigneeAgentId)) ?? task.assigneeAgentId)
: 'unassigned';
lines.push(
- ` ${task.identifier} ${statusIcon(task.status)} ${task.status} [${priorityLabel(task.priority)}] ${task.name || '(unnamed)'} — ${assignee}`,
+ ` ${task.identifier} (id: ${task.id}) ${statusIcon(task.status)} ${task.status} [${priorityLabel(task.priority)}] ${task.name || '(unnamed)'} — ${assignee}`,
);
}
if (totalOpenTasks > openTasks.length) {
diff --git a/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap
index 6dbd81fe1d1..bb389c6dde7 100644
--- a/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap
+++ b/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap
@@ -3,7 +3,7 @@
exports[`buildTaskRunPrompt > should build prompt with only task instruction 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 帮我写一本 AI Agent 技术书籍
@@ -14,7 +14,7 @@ Review: (not configured)
exports[`buildTaskRunPrompt > should build prompt with task description + instruction 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 帮我写一本 AI Agent 技术书籍,目标 8 章
Description: 面向开发者的技术书籍
@@ -26,7 +26,7 @@ Review: (not configured)
exports[`buildTaskRunPrompt > should handle empty activities gracefully 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
@@ -45,7 +45,7 @@ exports[`buildTaskRunPrompt > should handle full scenario with all sections 1`]
<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写一本 AI Agent 书,目标 8 章
Description: 面向开发者的 AI Agent 技术书籍
@@ -65,7 +65,7 @@ Activities:
exports[`buildTaskRunPrompt > should include activity history with topics and briefs in CLI style 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
Topics: 2
@@ -89,7 +89,7 @@ exports[`buildTaskRunPrompt > should include agent comments with author label an
<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
@@ -104,7 +104,7 @@ Activities:
exports[`buildTaskRunPrompt > should include parentTask context for subtasks 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-4 第2章 核心架构
+TASK-4 (id: task_004) 第2章 核心架构
Status: ● running Priority: -
Instruction: 撰写第2章
Parent: TASK-1
@@ -124,7 +124,7 @@ Review: (not configured)
exports[`buildTaskRunPrompt > should include subtasks in task section 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_root) 写一本书
Status: ● running Priority: -
Instruction: 写书
@@ -139,7 +139,7 @@ Review: (not configured)
exports[`buildTaskRunPrompt > should include subtasks in task tag when provided 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_001) 写一本书
Status: ● running Priority: -
Instruction: 写一本 AI Agent 书,目标 8 章
@@ -159,7 +159,7 @@ exports[`buildTaskRunPrompt > should only include user comments in user_feedback
<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
@@ -182,7 +182,7 @@ exports[`buildTaskRunPrompt > should place high_priority_instruction first, then
<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
@@ -201,7 +201,7 @@ exports[`buildTaskRunPrompt > should prioritize user feedback at the top 1`] = `
<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
@@ -216,7 +216,7 @@ Activities:
exports[`buildTaskRunPrompt > should show resolved action and comment on briefs 1`] = `
"<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-2 第2章
+TASK-2 (id: task_test) 第2章
Status: ● running Priority: -
Instruction: 写第2章
@@ -234,7 +234,7 @@ exports[`buildTaskRunPrompt > should truncate comments to 80 chars in activities
<task>
<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>
-TASK-1 写一本书
+TASK-1 (id: task_test) 写一本书
Status: ● running Priority: -
Instruction: 写书
diff --git a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts
index a068f4ffd52..378125bb958 100644
--- a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts
+++ b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts
@@ -5,6 +5,7 @@ import {
formatPropertyValue,
priorityLabel,
statusIcon,
+ taskIdentity,
timeAgo,
} from './index';
import type { TaskManagerPromptDefaults } from './taskManagerDefaults';
@@ -23,22 +24,22 @@ export const buildTaskDetailPrompt = (input: BuildTaskDetailPromptInput, now?: D
const { activities, workspace } = task;
const lines: string[] = [
- `<page_context>The user is currently viewing the detail page of task ${task.identifier}. When the user says "this task" or refers ambiguously, it means ${task.identifier}.</page_context>`,
+ `<page_context>The user is currently viewing the detail page of task ${taskIdentity(task)}. When the user says "this task" or refers ambiguously, it means ${task.identifier}.</page_context>`,
...buildTaskManagerDefaultsBlock(input),
'<task>',
`<hint>This tag contains the complete context of the task the user is viewing. Do NOT call viewTask to re-fetch it.</hint>`,
- `${task.identifier} ${task.name || '(unnamed)'}`,
+ `${taskIdentity(task)} ${task.name || '(unnamed)'}`,
`Status: ${statusIcon(task.status)} ${task.status} Priority: ${priorityLabel(task.priority)}`,
`Instruction: ${task.instruction}`,
];
if (task.description) lines.push(`Description: ${task.description}`);
if (task.agentId) lines.push(`Agent: ${task.agentId}`);
- if (task.parent) lines.push(`Parent: ${task.parent.identifier}`);
+ if (task.parent) lines.push(`Parent: ${taskIdentity(task.parent)}`);
if (task.topicCount) lines.push(`Topics: ${task.topicCount}`);
if (task.dependencies && task.dependencies.length > 0) {
lines.push(
- `Dependencies: ${task.dependencies.map((d) => `${d.type}: ${d.dependsOn}`).join(', ')}`,
+ `Dependencies: ${task.dependencies.map((d) => `${d.type}: ${d.dependsOn}${d.dependsOnId ? ` (id: ${d.dependsOnId})` : ''}`).join(', ')}`,
);
}
@@ -47,9 +48,11 @@ export const buildTaskDetailPrompt = (input: BuildTaskDetailPromptInput, now?: D
lines.push('Subtasks:');
const renderSubtasks = (nodes: NonNullable<typeof task.subtasks>, indent: string) => {
for (const s of nodes) {
- const dep = s.blockedBy ? ` ← blocks: ${s.blockedBy}` : '';
+ const dep = s.blockedBy
+ ? ` ← blocks: ${taskIdentity({ id: s.blockedById, identifier: s.blockedBy })}`
+ : '';
lines.push(
- `${indent}${s.identifier} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}`,
+ `${indent}${taskIdentity(s)} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}`,
);
if (s.children && s.children.length > 0) {
renderSubtasks(s.children, indent + ' ');
diff --git a/packages/prompts/src/prompts/task/buildTaskListPrompt.ts b/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
index 153c173c1f8..b5aad9e3348 100644
--- a/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
+++ b/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
@@ -1,5 +1,5 @@
import type { TaskSummary } from './index';
-import { priorityLabel, statusIcon, timeAgo } from './index';
+import { priorityLabel, statusIcon, taskIdentity, timeAgo } from './index';
import type { TaskManagerPromptDefaults } from './taskManagerDefaults';
import { buildTaskManagerDefaultsBlock } from './taskManagerDefaults';
@@ -33,7 +33,7 @@ export const buildTaskListPrompt = (input: BuildTaskListPromptInput, now?: Date)
? ` ${timeAgo(typeof t.createdAt === 'string' ? t.createdAt : t.createdAt.toISOString(), now)}`
: '';
lines.push(
- ` ${t.identifier} ${statusIcon(t.status)} ${t.status} [${priorityLabel(t.priority)}] ${t.name || '(unnamed)'}${ago}`,
+ ` ${taskIdentity(t)} ${statusIcon(t.status)} ${t.status} [${priorityLabel(t.priority)}] ${t.name || '(unnamed)'}${ago}`,
);
}
if (total > shown) {
diff --git a/packages/prompts/src/prompts/task/index.refs.test.ts b/packages/prompts/src/prompts/task/index.refs.test.ts
new file mode 100644
index 00000000000..91884ed6f81
--- /dev/null
+++ b/packages/prompts/src/prompts/task/index.refs.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildTaskDetailPrompt } from './buildTaskDetailPrompt';
+import { buildTaskListPrompt } from './buildTaskListPrompt';
+import { buildTaskRunPrompt, formatTaskCreated, formatTaskDetail, taskRef } from './index';
+
+describe('task identity in model output', () => {
+ const task = {
+ id: 'task_AbC',
+ identifier: 'T-12',
+ instruction: 'Ship it',
+ name: 'Ship',
+ status: 'backlog',
+ };
+ it('links using public identifiers while retaining stable ids as metadata', () => {
+ expect(taskRef(task)).toBe('[T-12](/task/T-12) (id: task_AbC)');
+ expect(formatTaskCreated(task)).toContain('[T-12](/task/T-12) (id: task_AbC)');
+ });
+ it('includes stable ids in list and detail contexts', () => {
+ expect(buildTaskListPrompt({ tasks: [task], total: 1 })).toContain('T-12 (id: task_AbC)');
+ expect(buildTaskDetailPrompt({ task })).toContain('T-12 (id: task_AbC)');
+ });
+ it('includes stable ids for related tasks in tool detail output', () => {
+ const result = formatTaskDetail({
+ ...task,
+ parent: { id: 'task_parent', identifier: 'T-1', name: 'Parent' },
+ dependencies: [{ dependsOn: 'T-2', dependsOnId: 'task_dependency', type: 'blocks' }],
+ });
+ expect(result).toContain('Parent: T-1 (id: task_parent)');
+ expect(result).toContain('blocks: T-2 (id: task_dependency)');
+ });
+ it('keeps related ids in run context and marks the current sibling by id', () => {
+ const result = buildTaskRunPrompt({
+ task: {
+ ...task,
+ parentIdentifier: 'T-1',
+ parentTaskId: 'task_parent',
+ dependencies: [{ dependsOn: 'T-2', dependsOnId: 'task_dependency', type: 'blocks' }],
+ },
+ parentTask: {
+ id: 'task_parent',
+ identifier: 'T-1',
+ instruction: 'Parent',
+ subtasks: [{ ...task, id: 'task_other', name: 'Other' }, task],
+ },
+ });
+ expect(result).toContain('Parent: T-1 (id: task_parent)');
+ expect(result).toContain('blocks: T-2 (id: task_dependency)');
+ expect(result.split('\n').find((line) => line.includes('task_other'))).not.toContain(
+ '◀ current',
+ );
+ expect(result.match(/◀ current/g)).toHaveLength(1);
+ });
+});
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 285e329cb46..f910d176573 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -49,6 +49,7 @@ const statusIcon = (s: string): string => {
};
export interface TaskSummary {
+ id?: string;
identifier: string;
name?: string | null;
priority?: number | null;
@@ -110,14 +111,22 @@ export const formatPropertyValue = (field: string | undefined, value: unknown):
return String(value);
};
-export const taskDetailHref = (identifier: string, baseUrl?: string): string => {
- const path = `/task/${identifier}`;
+export const taskDetailHref = (taskRef: string, baseUrl?: string): string => {
+ const path = `/task/${taskRef}`;
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)})`;
+/** Public links use the display alias; stable identity stays in explicit metadata. */
+export const taskRef = (
+ task: string | { id?: string; identifier: string },
+ baseUrl?: string,
+): string => {
+ const { id, identifier } = typeof task === 'string' ? { id: undefined, identifier: task } : task;
+ return `[${identifier}](${taskDetailHref(identifier, baseUrl)})${id ? ` (id: ${id})` : ''}`;
+};
+
+export const taskIdentity = (task: { id?: string | null; identifier: string }) =>
+ `${task.identifier}${task.id ? ` (id: ${task.id})` : ''}`;
// Re-export shared types from @lobechat/types for backward compatibility
export type {
@@ -131,7 +140,7 @@ export type {
* Format a single task as a one-line summary
*/
export const formatTaskLine = (t: TaskSummary): string =>
- `${t.identifier} ${statusIcon(t.status)} ${t.status} ${t.name || '(unnamed)'} [${priorityLabel(t.priority)}]`;
+ `${taskIdentity(t)} ${statusIcon(t.status)} ${t.status} ${t.name || '(unnamed)'} [${priorityLabel(t.priority)}]`;
/**
* Format createTask response
@@ -143,15 +152,19 @@ export const formatTaskCreated = (
baseUrl?: string;
instruction: string;
parentLabel?: string;
+ parentTaskId?: string;
},
): string => {
const lines = [
- `Task created: ${taskRef(t.identifier, t.baseUrl)} "${t.name}"`,
+ `Task created: ${taskRef(t, t.baseUrl)} "${t.name}"`,
` Status: ${statusIcon(t.status)} ${t.status}`,
` Priority: ${priorityLabel(t.priority)}`,
];
if (t.assigneeLabel) lines.push(` Assignee: ${t.assigneeLabel}`);
- if (t.parentLabel) lines.push(` Parent: ${taskRef(t.parentLabel, t.baseUrl)}`);
+ if (t.parentLabel)
+ lines.push(
+ ` Parent: ${taskRef({ id: t.parentTaskId, identifier: t.parentLabel }, t.baseUrl)}`,
+ );
lines.push(` Instruction: ${t.instruction}`);
return lines.join('\n');
};
@@ -161,6 +174,7 @@ export interface TaskCreatedItem {
identifier?: string;
name: string;
success: boolean;
+ taskId?: string;
}
/**
@@ -174,7 +188,9 @@ export interface TaskCreatedItem {
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)';
+ const ref = r.identifier
+ ? taskRef({ id: r.taskId, identifier: r.identifier }, baseUrl)
+ : '(unknown id)';
return `${index + 1}. ${ref} "${r.name}" — created`;
}
return `${index + 1}. "${r.name}" — failed: ${r.error ?? 'Unknown error'}`;
@@ -241,7 +257,7 @@ export const formatTaskList = (tasks: TaskSummary[], filters: TaskListFilters):
*/
export const formatTaskDetail = (t: TaskDetailData): string => {
const lines = [
- `${t.identifier} ${t.name || '(unnamed)'}`,
+ `${taskIdentity(t)} ${t.name || '(unnamed)'}`,
`Status: ${statusIcon(t.status)} ${t.status} Priority: ${priorityLabel(t.priority)}`,
`Instruction: ${t.instruction}`,
];
@@ -249,13 +265,13 @@ export const formatTaskDetail = (t: TaskDetailData): string => {
if (t.agentId) lines.push(`Agent: ${t.agentId}`);
// `userId` on the detail payload is the human assignee (workspace member).
if (t.userId) lines.push(`Assignee (member): ${t.userId}`);
- if (t.parent) lines.push(`Parent: ${t.parent.identifier}`);
+ if (t.parent) lines.push(`Parent: ${taskIdentity(t.parent)}`);
if (t.topicCount) lines.push(`Topics: ${t.topicCount}`);
if (t.createdAt) lines.push(`Created: ${t.createdAt}`);
if (t.dependencies && t.dependencies.length > 0) {
lines.push(
- `Dependencies: ${t.dependencies.map((d) => `${d.type}: ${d.dependsOn}`).join(', ')}`,
+ `Dependencies: ${t.dependencies.map((d) => `${d.type}: ${taskIdentity({ id: d.dependsOnId, identifier: d.dependsOn })}`).join(', ')}`,
);
}
@@ -265,9 +281,11 @@ export const formatTaskDetail = (t: TaskDetailData): string => {
lines.push('Subtasks:');
const renderSubtasks = (nodes: NonNullable<typeof t.subtasks>, indent: string) => {
for (const s of nodes) {
- const dep = s.blockedBy ? ` ← blocks: ${s.blockedBy}` : '';
+ const dep = s.blockedBy
+ ? ` ← blocks: ${taskIdentity({ id: s.blockedById, identifier: s.blockedBy })}`
+ : '';
lines.push(
- `${indent}${s.identifier} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}`,
+ `${indent}${taskIdentity(s)} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}`,
);
if (s.children && s.children.length > 0) {
renderSubtasks(s.children, indent + ' ');
@@ -569,16 +587,17 @@ export interface TaskRunPromptInput {
goalLoop?: TaskRunPromptGoalLoop;
/** Parent task context (when current task is a subtask) */
parentTask?: {
+ id?: string;
identifier: string;
instruction: string;
name?: string | null;
- subtasks?: Array<TaskSummary & { blockedBy?: string }>;
+ subtasks?: Array<TaskSummary & { blockedBy?: string; blockedById?: string }>;
};
/** Task data */
task: {
assigneeAgentId?: string | null;
automationMode?: 'heartbeat' | 'schedule' | null;
- dependencies?: Array<{ dependsOn: string; type: string }>;
+ dependencies?: Array<{ dependsOn: string; dependsOnId?: string; type: string }>;
description?: string | null;
/** Lightweight metadata of files attached to the task instruction. Actual
* content is forwarded to the agent runtime via `fileIds` on execAgent. */
@@ -589,6 +608,7 @@ export interface TaskRunPromptInput {
instruction: string;
name?: string | null;
parentIdentifier?: string | null;
+ parentTaskId?: string | null;
priority?: number | null;
review?: {
enabled?: boolean;
@@ -598,7 +618,7 @@ export interface TaskRunPromptInput {
schedulePattern?: string | null;
scheduleTimezone?: string | null;
status: string;
- subtasks?: Array<TaskSummary & { blockedBy?: string }>;
+ subtasks?: Array<TaskSummary & { blockedBy?: string; blockedById?: string }>;
/** Delivery-acceptance criteria the builder must self-evidence while working. */
verify?: {
criteria?: Array<{
@@ -698,7 +718,7 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
const taskLines = [
`<task>`,
`<hint>This tag contains the complete task context. Do NOT call viewTask to re-fetch it.</hint>`,
- `${task.identifier} ${task.name || task.identifier}`,
+ `${taskIdentity(task)} ${task.name || task.identifier}`,
`Status: ${statusIcon(task.status)} ${task.status} Priority: ${priorityLabel(task.priority)}`,
];
if (task.automationMode) {
@@ -721,14 +741,17 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
}
}
if (task.assigneeAgentId) taskLines.push(`Agent: ${task.assigneeAgentId}`);
- if (task.parentIdentifier) taskLines.push(`Parent: ${task.parentIdentifier}`);
+ if (task.parentIdentifier)
+ taskLines.push(
+ `Parent: ${taskIdentity({ id: task.parentTaskId, identifier: task.parentIdentifier })}`,
+ );
const topicCount = activities?.topics?.length ?? 0;
if (topicCount > 0) taskLines.push(`Topics: ${topicCount}`);
if (task.dependencies && task.dependencies.length > 0) {
taskLines.push(
- `Dependencies: ${task.dependencies.map((d) => `${d.type}: ${d.dependsOn}`).join(', ')}`,
+ `Dependencies: ${task.dependencies.map((d) => `${d.type}: ${taskIdentity({ id: d.dependsOnId, identifier: d.dependsOn })}`).join(', ')}`,
);
}
@@ -737,9 +760,11 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
taskLines.push('');
taskLines.push('Subtasks:');
for (const s of task.subtasks) {
- const dep = s.blockedBy ? ` ← blocks: ${s.blockedBy}` : '';
+ const dep = s.blockedBy
+ ? ` ← blocks: ${taskIdentity({ id: s.blockedById, identifier: s.blockedBy })}`
+ : '';
taskLines.push(
- ` ${s.identifier} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}`,
+ ` ${taskIdentity(s)} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}`,
);
}
}
@@ -965,16 +990,20 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
if (parentTask) {
taskLines.push('');
taskLines.push(
- `<parentTask identifier="${parentTask.identifier}" name="${parentTask.name || parentTask.identifier}">`,
+ `<parentTask${parentTask.id ? ` id="${parentTask.id}"` : ''} identifier="${parentTask.identifier}" name="${parentTask.name || parentTask.identifier}">`,
);
taskLines.push(` Instruction: ${parentTask.instruction}`);
if (parentTask.subtasks && parentTask.subtasks.length > 0) {
taskLines.push(` Subtasks (${parentTask.subtasks.length}):`);
for (const s of parentTask.subtasks) {
- const dep = s.blockedBy ? ` ← blocks: ${s.blockedBy}` : '';
- const marker = s.identifier === task.identifier ? ' ◀ current' : '';
+ const dep = s.blockedBy
+ ? ` ← blocks: ${taskIdentity({ id: s.blockedById, identifier: s.blockedBy })}`
+ : '';
+ const marker = (s.id ? s.id === task.id : s.identifier === task.identifier)
+ ? ' ◀ current'
+ : '';
taskLines.push(
- ` ${s.identifier} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}${marker}`,
+ ` ${taskIdentity(s)} ${statusIcon(s.status)} ${s.status} ${s.name || '(unnamed)'}${dep}${marker}`,
);
}
}
diff --git a/packages/prompts/src/prompts/workspaceContext/index.test.ts b/packages/prompts/src/prompts/workspaceContext/index.test.ts
index 114434a2f23..fea284a8bc4 100644
--- a/packages/prompts/src/prompts/workspaceContext/index.test.ts
+++ b/packages/prompts/src/prompts/workspaceContext/index.test.ts
@@ -18,7 +18,7 @@ describe('workspaceContextPrompt', () => {
'MUST start with the workspace slug prefix "https://app.lobehub.com/lobehub/"',
);
expect(result).toContain(
- 'agent task detail: https://app.lobehub.com/lobehub/agent/<agentId>/task/<T-123>',
+ 'agent task detail: https://app.lobehub.com/lobehub/agent/<agentId>/task/<taskIdentifier>',
);
expect(result).toContain(
'knowledge base: https://app.lobehub.com/lobehub/resource/library/<knowledgeBaseId>',
diff --git a/packages/prompts/src/prompts/workspaceContext/index.ts b/packages/prompts/src/prompts/workspaceContext/index.ts
index 8e09317e151..2fa7d64c4bb 100644
--- a/packages/prompts/src/prompts/workspaceContext/index.ts
+++ b/packages/prompts/src/prompts/workspaceContext/index.ts
@@ -31,7 +31,7 @@ const trimTrailingSlashes = (value: string): string => {
*/
const ROUTE_HINTS: [label: string, path: string][] = [
['agent chat', '/agent/<agentId>'],
- ['agent task detail', '/agent/<agentId>/task/<T-123>'],
+ ['agent task detail', '/agent/<agentId>/task/<taskIdentifier>'],
['agent document', '/agent/<agentId>/docs/<docId>'],
['page (workspace document)', '/page/<documentId>'],
['knowledge base', '/resource/library/<knowledgeBaseId>'],
diff --git a/packages/types/src/recent.ts b/packages/types/src/recent.ts
index 63fd09d7a84..cf8e32a0cc4 100644
--- a/packages/types/src/recent.ts
+++ b/packages/types/src/recent.ts
@@ -16,6 +16,7 @@ export interface RecentItem {
slugTitle?: string | null;
/** Task lifecycle status when `type === 'task'`; null for topic/document. */
status: TaskStatus | null;
+ taskIdentifier?: string | null;
title: string;
type: 'topic' | 'document' | 'task';
updatedAt: Date;
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 4b454d703fc..bc74d31ccd7 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -121,11 +121,21 @@ export interface TaskInstructionSynthesis {
// ── Config types ──
+/** Stable identity with the label snapshot written to the legacy selection. */
+export interface CheckpointTaskRef {
+ id: string;
+ identifier: string;
+}
+
export interface CheckpointConfig {
onAgentRequest?: boolean;
tasks?: {
+ /** Persisted identifiers for old readers; write boundaries accept TaskRefs. */
afterIds?: string[];
+ afterTasks?: CheckpointTaskRef[];
+ /** Persisted identifiers for old readers; write boundaries accept TaskRefs. */
beforeIds?: string[];
+ beforeTasks?: CheckpointTaskRef[];
};
topic?: {
after?: boolean;
@@ -442,10 +452,12 @@ export interface TaskDetailSubtask {
assigneeUserId?: string | null;
automationMode?: TaskAutomationMode | null;
blockedBy?: string;
+ blockedById?: string;
children?: TaskDetailSubtask[];
/** Creator of the subtask; with `visibility`, gates who it can be assigned to. */
createdByUserId?: string;
heartbeat?: { interval?: number | null };
+ id?: string;
identifier: string;
name?: string | null;
priority?: number | null;
@@ -615,7 +627,7 @@ export interface TaskDetailData {
createdAt?: string;
/** Creator of the task; used by the UI to gate creator-only actions (e.g. make private). */
createdByUserId?: string | null;
- dependencies?: Array<{ dependsOn: string; type: string }>;
+ dependencies?: Array<{ dependsOn: string; dependsOnId?: string; type: string }>;
description?: string | null;
/** Rich-editor JSON state for the instruction; preserves details markdown drops (image size, etc.). */
editorData?: unknown;
@@ -637,7 +649,7 @@ export interface TaskDetailData {
identifier: string;
instruction: string;
name?: string | null;
- parent?: { agentId?: string | null; identifier: string; name: string | null } | null;
+ parent?: { id?: string; agentId?: string | null; identifier: string; name: string | null } | null;
priority?: number | null;
schedule?: {
maxExecutions?: number | null;
diff --git a/src/features/Acceptance/Viewer/Review/AcceptanceRepair.tsx b/src/features/Acceptance/Viewer/Review/AcceptanceRepair.tsx
index 51542f8dd93..de59c1442c8 100644
--- a/src/features/Acceptance/Viewer/Review/AcceptanceRepair.tsx
+++ b/src/features/Acceptance/Viewer/Review/AcceptanceRepair.tsx
@@ -145,7 +145,7 @@ export const AcceptanceRepair = () => {
)}
<Flexbox horizontal gap={16} style={{ flexWrap: 'wrap' }}>
{repair.taskId && (
- <WorkspaceLink to={taskDetailPath(repair.taskId)}>
+ <WorkspaceLink to={taskDetailPath(repair.taskIdentifier ?? repair.taskId)}>
{t('acceptance.repair.openTask')}
</WorkspaceLink>
)}
diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsx
index b536d661a48..cb7cb705f0d 100644
--- a/src/features/AgentSidebar/Topic/List/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx
@@ -24,6 +24,10 @@ const chatStoreStateMock = vi.hoisted(() => ({
topics: [],
}));
const skeletonRenderCount = vi.hoisted(() => ({ value: 0 }));
+const userStoreStateMock = vi.hoisted(() => ({
+ topicIncludeCompleted: false,
+ topicSortBy: 'updatedAt',
+}));
vi.mock('./TopicListSkeleton', () => ({
default: () => {
@@ -109,9 +113,9 @@ vi.mock('@/store/global/selectors', () => ({
}));
vi.mock('@/store/user', () => ({
- useUserStore: (
- selector: (state: { topicIncludeCompleted: boolean; topicSortBy: string }) => unknown,
- ) => selector({ topicIncludeCompleted: false, topicSortBy: 'updatedAt' }),
+ getUserStoreState: () => userStoreStateMock,
+ useUserStore: (selector: (state: typeof userStoreStateMock) => unknown) =>
+ selector(userStoreStateMock),
}));
vi.mock('@/store/user/selectors', () => ({
diff --git a/src/features/AgentTaskManager/TaskAgentProvider.test.tsx b/src/features/AgentTaskManager/TaskAgentProvider.test.tsx
index c75d3e07d63..eaa861d4d0d 100644
--- a/src/features/AgentTaskManager/TaskAgentProvider.test.tsx
+++ b/src/features/AgentTaskManager/TaskAgentProvider.test.tsx
@@ -61,6 +61,11 @@ vi.mock('@/hooks/useOperationState', () => ({
useOperationState: () => mocks.operationState,
}));
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: (state: unknown) => unknown) =>
+ selector({ taskRefIndex: { 'T-1': 'task_1', 'task_1': 'task_1' } }),
+}));
+
vi.mock('@/store/agent', () => ({
useAgentStore: Object.assign(
(selector: (state: typeof mocks.agentState) => unknown) => {
@@ -142,7 +147,7 @@ describe('TaskAgentProvider', () => {
</TaskAgentProvider>,
);
- expect(mocks.providerContexts.at(-1)?.viewedTask).toEqual({ taskId: 'T-1', type: 'detail' });
+ expect(mocks.providerContexts.at(-1)?.viewedTask).toEqual({ taskId: 'task_1', type: 'detail' });
});
it('uses the route agent as the default in an agent-scoped task detail', async () => {
@@ -293,7 +298,7 @@ describe('TaskAgentProvider', () => {
await waitFor(() => {
expect(mocks.providerContexts.at(-1)?.topicId).toBe('tpc_created');
});
- expect(mocks.providerContexts.at(-1)?.viewedTask).toEqual({ taskId: 'T-1', type: 'detail' });
+ expect(mocks.providerContexts.at(-1)?.viewedTask).toEqual({ taskId: 'task_1', type: 'detail' });
expect(mocks.chatState.switchTopic).not.toHaveBeenCalled();
});
diff --git a/src/features/AgentTaskManager/TaskAgentProvider.tsx b/src/features/AgentTaskManager/TaskAgentProvider.tsx
index 0fb9f58b631..74b0568a41b 100644
--- a/src/features/AgentTaskManager/TaskAgentProvider.tsx
+++ b/src/features/AgentTaskManager/TaskAgentProvider.tsx
@@ -12,6 +12,7 @@ import { useOperationState } from '@/hooks/useOperationState';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { useTaskStore } from '@/store/task';
import { resolveTaskHandoffTopic } from './taskHandoff';
@@ -51,7 +52,10 @@ export const TaskAgentProvider = memo<TaskAgentProviderProps>((props) => {
// `:slug?` is the readable title tail the detail route appends; it never
// participates in resolution, so the match must tolerate it being absent.
const detailMatch = useMatch('/task/:taskId/:slug?');
- const resolvedViewedTaskId = viewedTaskId || detailMatch?.params.taskId;
+ const viewedTaskRef = viewedTaskId || detailMatch?.params.taskId;
+ const resolvedViewedTaskId = useTaskStore((s) =>
+ viewedTaskRef ? s.taskRefIndex?.[viewedTaskRef] : undefined,
+ );
const scopedSelectedAgentId =
scopedSelection.scopeAgentId === preferredAgentId
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
index cd731fb7cc7..2da60d5d3e2 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
@@ -16,6 +16,7 @@ const createState = (parent: any) => ({
activeTaskId: 'T-child',
taskDetailMap: {
'T-child': {
+ id: 'T-child',
identifier: 'T-child',
instruction: 'Child instruction',
parent,
@@ -71,12 +72,14 @@ describe('TaskParentBar', () => {
mocks.getDetail.mockReset();
mocks.taskState = createState({
agentId: 'agt_parent',
+ id: 'T-parent',
identifier: 'T-parent',
name: 'Parent task',
});
mocks.getDetail.mockResolvedValue({
data: {
agentId: 'agt_parent',
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent instruction',
status: 'running',
@@ -100,12 +103,14 @@ describe('TaskParentBar', () => {
it('falls back to the global route when the parent task owner is unknown', async () => {
mocks.taskState = createState({
+ id: 'T-parent',
identifier: 'T-parent',
name: 'Parent task',
});
mocks.getDetail.mockResolvedValue({
data: {
agentId: null,
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent instruction',
status: 'running',
@@ -125,12 +130,14 @@ describe('TaskParentBar', () => {
mocks.getDetail.mockResolvedValue({
data: {
agentId: 'agt_parent',
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent instruction',
status: 'running',
subtasks: [
{
assignee: { id: 'agt_sibling' },
+ id: 'T-sibling',
identifier: 'T-sibling',
status: 'backlog',
},
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
index e3581cb75cf..aab1b8b02fd 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
@@ -46,7 +46,7 @@ const TaskParentBar = memo(() => {
if (!parent?.identifier) return;
taskService
- .getDetail(parent.identifier)
+ .getDetail(parent.id!)
.then((res) => {
if (!isActive) return;
const detail = res.data as TaskDetailData;
@@ -62,7 +62,7 @@ const TaskParentBar = memo(() => {
return () => {
isActive = false;
};
- }, [parent?.identifier]);
+ }, [parent?.id, parent?.identifier]);
if (!parent) return null;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
index cb8b1749319..b4ced35d7a3 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
@@ -19,12 +19,14 @@ const mocks = vi.hoisted(() => ({
taskDetailMap: {
'T-parent': {
agentId: 'agt_parent',
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent instruction',
status: 'running',
subtasks: [
{
assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ id: 'T-child',
identifier: 'T-child',
name: 'Child task',
status: 'backlog',
@@ -190,6 +192,7 @@ describe('TaskSubtasks', () => {
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ id: 'T-child',
identifier: 'T-child',
name: 'Child task',
status: 'backlog',
@@ -221,6 +224,7 @@ describe('TaskSubtasks', () => {
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
assigneeUserId: 'member-1',
+ id: 'T-child',
identifier: 'T-child',
name: 'Child task',
status: 'backlog',
@@ -232,6 +236,7 @@ describe('TaskSubtasks', () => {
const expectedTarget = expect.objectContaining({
assigneeUserId: 'member-1',
+ id: 'T-child',
identifier: 'T-child',
});
expect(mocks.buildContextMenuItems).toHaveBeenCalledWith(expectedTarget);
@@ -243,6 +248,7 @@ describe('TaskSubtasks', () => {
{
assigneeUserId: 'member-1',
automationMode: 'schedule',
+ id: 'T-child',
identifier: 'T-child',
name: 'Scheduled child task',
status: 'scheduled',
@@ -259,6 +265,7 @@ describe('TaskSubtasks', () => {
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
assigneeUserId: 'member-1',
+ id: 'T-child',
identifier: 'T-child',
name: 'Child task',
status: 'backlog',
@@ -273,6 +280,7 @@ describe('TaskSubtasks', () => {
it('falls back to the global task route when the selected subtask has no assignee', () => {
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
+ id: 'T-child',
identifier: 'T-child',
name: 'Child task',
status: 'backlog',
@@ -290,6 +298,7 @@ describe('TaskSubtasks', () => {
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ id: 'T-child',
identifier: 'T-child',
name: 'Child task',
runningTopic: { id: 'topic-running', operationId: 'op-running' },
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
index 84f1015d819..1f89577042f 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
@@ -87,13 +87,13 @@ const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {
style={{ alignItems: 'center', display: 'inline-flex', flex: 'none' }}
onClick={(e) => e.stopPropagation()}
>
- <TaskPriorityTag priority={task.priority} size={14} taskIdentifier={task.identifier} />
+ <TaskPriorityTag priority={task.priority} size={14} taskIdentifier={task.id} />
</span>
<span
style={{ alignItems: 'center', display: 'inline-flex', flex: 'none' }}
onClick={(e) => e.stopPropagation()}
>
- <TaskStatusTag size={14} status={status} taskIdentifier={task.identifier}>
+ <TaskStatusTag size={14} status={status} taskIdentifier={task.id}>
{hasRunningTopic ? <TopicStatusIcon size={14} status="running" /> : undefined}
</TaskStatusTag>
</span>
@@ -125,7 +125,7 @@ const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {
currentUserId={task.assigneeUserId ?? null}
disabled={isRunning}
taskCreatorId={task.createdByUserId}
- taskIdentifier={task.identifier}
+ taskIdentifier={task.id}
taskVisibility={task.visibility}
>
<span
@@ -147,7 +147,7 @@ const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {
<AssigneeAgentSelector
currentAgentId={task.assignee?.id ?? null}
disabled={isRunning}
- taskIdentifier={task.identifier}
+ taskIdentifier={task.id}
taskVisibility={task.visibility}
>
<span
@@ -169,7 +169,7 @@ const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {
const toTreeData = (tree: TaskTreeNode[]): TreeDataNode[] => {
return tree.map((node) => ({
children: toTreeData(node.children),
- key: node.task.identifier,
+ key: node.task.id!,
title: <SubtaskTitle task={node.task} />,
}));
};
@@ -198,7 +198,7 @@ const TaskSubtasks = memo(() => {
const map = new Map<string, TaskDetailSubtask>();
const walk = (items: TaskDetailSubtask[]) => {
for (const item of items) {
- map.set(item.identifier, item);
+ if (item.id) map.set(item.id, item);
if (item.children?.length) walk(item.children);
}
};
@@ -207,9 +207,12 @@ const TaskSubtasks = memo(() => {
}, [subtasks]);
const handleNavigate = useCallback(
- (identifier: string) => {
- const subtask = subtaskMap.get(identifier);
- navigate(taskDetailPath(identifier, subtask?.assignee?.id ?? undefined, subtask?.name));
+ (id: string) => {
+ const subtask = subtaskMap.get(id);
+ if (!subtask?.id) return;
+ navigate(
+ taskDetailPath(subtask.identifier, subtask?.assignee?.id ?? undefined, subtask?.name),
+ );
},
[navigate, subtaskMap],
);
@@ -227,6 +230,7 @@ const TaskSubtasks = memo(() => {
event.preventDefault();
showContextMenu(
buildItems({
+ id: subtask.id!,
archivedAt: subtask.archivedAt ?? null,
assigneeAgentId: subtask.assignee?.id,
assigneeUserId: subtask.assigneeUserId,
@@ -239,6 +243,7 @@ const TaskSubtasks = memo(() => {
}),
);
installKeyboardHandlers({
+ id: subtask.id!,
archivedAt: subtask.archivedAt ?? null,
assigneeAgentId: subtask.assignee?.id,
assigneeUserId: subtask.assigneeUserId,
diff --git a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts
index 047c8964327..cd15a2e81f7 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts
@@ -37,11 +37,15 @@ export const useActiveTaskDetail = (taskId?: string): ActiveTaskDetailState => {
const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
const useHydrateAgentConfig = useAgentStore((s) => s.useHydrateAgentConfig);
- const hasTaskDetail = useTaskStore((s) => (taskId ? !!s.taskDetailMap[taskId] : false));
+ const hasTaskDetail = useTaskStore((s) =>
+ taskId ? !!s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId] : false,
+ );
// The assignee comes from the loaded task detail, so this stays undefined
// until the first fetch resolves — which is exactly when its hydration kicks in.
const assigneeAgentId = useTaskStore((s) =>
- taskId ? (s.taskDetailMap[taskId]?.agentId ?? undefined) : undefined,
+ taskId
+ ? (s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.agentId ?? undefined)
+ : undefined,
);
const assigneeInMap = useAgentStore((s) => !!(assigneeAgentId && s.agentMap[assigneeAgentId]));
diff --git a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskResult.ts b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskResult.ts
index 267924e4bf7..b4e57aaf6aa 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskResult.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskResult.ts
@@ -15,7 +15,7 @@ export const useActiveTaskResult = (taskId?: string): ActiveTaskResultState => {
const setActiveTaskId = useTaskStore((state) => state.setActiveTaskId);
const useFetchTaskDetail = useTaskStore((state) => state.useFetchTaskDetail);
const hasTaskDetail = useTaskStore((state) =>
- taskId ? Boolean(state.taskDetailMap[taskId]) : false,
+ taskId ? Boolean(state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]) : false,
);
useEffect(() => {
diff --git a/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.test.ts b/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.test.ts
index e9982989aef..e17aaffa17c 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.test.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.test.ts
@@ -9,12 +9,17 @@ import { useTaskCopyActions } from './useTaskCopyActions';
const mocks = vi.hoisted(() => ({
copyToClipboard: vi.fn(),
taskState: {
- activeTaskId: 'T-1' as string | undefined,
+ activeTaskId: 'task_1' as string | undefined,
taskDetailMap: {
- 'T-1': { agentId: 'agt_1', name: 'Ship the thing' },
+ task_1: { identifier: 'T-1', agentId: 'agt_1', name: 'Ship the thing' },
} as Record<
string,
- { agentId?: string | null; instruction?: string | null; name?: string | null }
+ {
+ identifier?: string;
+ agentId?: string | null;
+ instruction?: string | null;
+ name?: string | null;
+ }
>,
},
toastSuccess: vi.fn(),
@@ -57,8 +62,10 @@ vi.mock('@/store/task', () => ({
describe('useTaskCopyActions', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.taskState.activeTaskId = 'T-1';
- mocks.taskState.taskDetailMap = { 'T-1': { agentId: 'agt_1', name: 'Ship the thing' } };
+ mocks.taskState.activeTaskId = 'task_1';
+ mocks.taskState.taskDetailMap = {
+ task_1: { identifier: 'T-1', agentId: 'agt_1', name: 'Ship the thing' },
+ };
mocks.workspaceSlug = 'ws-slug';
});
@@ -71,6 +78,7 @@ describe('useTaskCopyActions', () => {
'https://example.com/ws-slug/agent/agt_1/task/T-1/ship-the-thing',
);
expect(mocks.toastSuccess).toHaveBeenCalledWith('taskList.contextMenu.copyLinkSuccess');
+ expect(result.current.taskId).toBe('task_1');
});
it('drops the workspace prefix in personal mode', async () => {
@@ -95,7 +103,12 @@ describe('useTaskCopyActions', () => {
it('copies the task instruction as markdown', async () => {
mocks.taskState.taskDetailMap = {
- 'T-1': { agentId: 'agt_1', instruction: '## Goal\n\nShip it', name: 'Ship the thing' },
+ task_1: {
+ identifier: 'T-1',
+ agentId: 'agt_1',
+ instruction: '## Goal\n\nShip it',
+ name: 'Ship the thing',
+ },
};
const { result } = renderHook(() => useTaskCopyActions());
@@ -108,7 +121,7 @@ describe('useTaskCopyActions', () => {
it('reports no content and skips copying when the instruction is blank', async () => {
mocks.taskState.taskDetailMap = {
- 'T-1': { agentId: 'agt_1', instruction: ' \n ', name: 'Ship the thing' },
+ task_1: { identifier: 'T-1', agentId: 'agt_1', instruction: ' \n ', name: 'Ship the thing' },
};
const { result } = renderHook(() => useTaskCopyActions());
diff --git a/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts b/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts
index c96feef9a9d..660fc063856 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts
@@ -21,26 +21,29 @@ export const useTaskCopyActions = () => {
const activeWorkspaceSlug = useActiveWorkspaceSlug();
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const taskAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
+ const identifier = useTaskStore((s) =>
+ taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.identifier : undefined,
+ );
const taskTitle = useTaskStore(taskDetailSelectors.activeTaskName);
const instruction = useTaskStore(taskDetailSelectors.activeTaskInstruction);
const copyId = useCallback(async () => {
- if (!taskId) return;
+ if (!identifier) return;
- await copyToClipboard(taskId);
+ await copyToClipboard(identifier);
toast.success(t('taskList.contextMenu.copyIdSuccess'));
- }, [taskId, t]);
+ }, [identifier, t]);
// Carry the title into the link so a pasted URL says what the task is.
const link = useMemo(
() =>
- taskId
+ identifier
? `${appOrigin}${buildWorkspaceAwarePath(
- taskDetailPath(taskId, taskAgentId ?? undefined, taskTitle),
+ taskDetailPath(identifier, taskAgentId ?? undefined, taskTitle),
activeWorkspaceSlug,
)}`
: undefined,
- [taskId, taskAgentId, taskTitle, appOrigin, activeWorkspaceSlug],
+ [identifier, taskAgentId, taskTitle, appOrigin, activeWorkspaceSlug],
);
const copyLink = useCallback(async () => {
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
index e2cdc4273c2..77da3aa9a62 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
@@ -572,7 +572,11 @@ describe('CreateTaskInlineEntry', () => {
it('confirms the task exists once it is created, and offers a way to open it', async () => {
editorMarkdownMock.value = 'Write a project plan';
analyzeIntentMock.mockResolvedValue(clearReading);
- createTaskMock.mockResolvedValue({ identifier: 'TASK-9', name: 'Write the Q3 project plan' });
+ createTaskMock.mockResolvedValue({
+ id: 'task_9',
+ identifier: 'TASK-9',
+ name: 'Write the Q3 project plan',
+ });
render(<CreateTaskInlineEntry variant="hero" />);
fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });
@@ -591,12 +595,16 @@ describe('CreateTaskInlineEntry', () => {
render(description as ReactNode);
fireEvent.click(screen.getByText('taskIntent.openCreated'));
- expect(navigateMock).toHaveBeenCalledWith(expect.stringContaining('TASK-9'));
+ expect(navigateMock).toHaveBeenCalledWith(expect.stringContaining('/task/TASK-9/'));
});
it('confirms every creation path, not only the straight-through one', async () => {
editorMarkdownMock.value = 'Write a project plan';
- createTaskMock.mockResolvedValue({ identifier: 'TASK-9', name: 'Write the Q3 project plan' });
+ createTaskMock.mockResolvedValue({
+ id: 'task_9',
+ identifier: 'TASK-9',
+ name: 'Write the Q3 project plan',
+ });
analyzeIntentMock.mockResolvedValue({
...clearReading,
clarifications: [{ options: ['lobe-chat'], question: 'Which repo?' }],
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index 23ffb508a07..433954e9f35 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -72,7 +72,7 @@ interface CreateTaskInlineEntryProps {
*/
lockAssignee?: boolean;
onCollapse?: () => void;
- onCreated?: (task: { agentId?: string; identifier: string }) => void;
+ onCreated?: (task: { id: string; agentId?: string; identifier: string }) => void;
parentTaskId?: string;
placeholder?: string;
projectId?: string;
@@ -460,6 +460,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
title: t('taskIntent.created'),
});
onCreated?.({
+ id: result.id,
agentId: result.assigneeAgentId ?? undefined,
identifier: result.identifier,
});
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index 8236e8d7062..198b657e789 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -58,7 +58,7 @@ export interface CreateTaskContentProps {
* agent-scoped task list where every task belongs to that agent.
*/
lockAssignee?: boolean;
- onCreated?: (task: { agentId?: string; identifier: string; name?: string }) => void;
+ onCreated?: (task: { id: string; agentId?: string; identifier: string; name?: string }) => void;
projectId?: string;
/**
* Creates a scheduled task: the form gains a schedule chip and the task is
@@ -196,6 +196,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
if (result) {
close();
onCreated?.({
+ id: result.id,
agentId: result.assigneeAgentId ?? undefined,
identifier: result.identifier,
name: result.name ?? undefined,
@@ -261,7 +262,6 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
fontWeight: 600,
lineHeight: 1.4,
minWidth: 0,
- outline: 'none',
padding: '4px 0',
}}
onChange={(e) => setTitle(e.target.value)}
diff --git a/src/features/AgentTasks/features/AgentTaskItem.test.tsx b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
index d434487e6f9..3538800ff40 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.test.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
@@ -103,6 +103,7 @@ const createTask = (assigneeAgentId?: string | null) =>
({
assigneeAgentId,
createdAt: new Date('2026-05-18T00:00:00.000Z'),
+ id: 'task_22',
identifier: 'T-22',
name: 'Hourly trend update',
priority: 2,
@@ -217,12 +218,12 @@ describe('AgentTaskItem', () => {
fireEvent.click(screen.getByTestId('subtask-progress'));
- await waitFor(() => expect(mocks.fetchTaskDetail).toHaveBeenCalledWith('T-22'));
+ await waitFor(() => expect(mocks.fetchTaskDetail).toHaveBeenCalledWith('task_22'));
});
it('revalidates subtask navigation when an earlier detail is cached', async () => {
mocks.taskDetailMap = {
- 'T-22': { subtasks: [{ identifier: 'T-stale', status: 'completed' }] },
+ task_22: { subtasks: [{ identifier: 'T-stale', status: 'completed' }] },
};
mocks.fetchTaskDetail.mockResolvedValue({
subtasks: [{ identifier: 'T-current', status: 'backlog' }],
@@ -239,6 +240,6 @@ describe('AgentTaskItem', () => {
fireEvent.click(screen.getByTestId('subtask-progress'));
- await waitFor(() => expect(mocks.fetchTaskDetail).toHaveBeenCalledWith('T-22'));
+ await waitFor(() => expect(mocks.fetchTaskDetail).toHaveBeenCalledWith('task_22'));
});
});
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index d33949dfed4..5efc5ebbaa5 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -50,7 +50,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
const { t, i18n } = useTranslation('common');
const { t: tChat } = useTranslation('chat');
const fetchTaskDetail = useTaskStore((s) => s.fetchTaskDetail);
- const taskDetail = useTaskStore((s) => s.taskDetailMap[task.identifier]);
+ const taskDetail = useTaskStore((s) => s.taskDetailMap[task.id]);
const { items: contextMenuItems, onContextMenu: handleContextMenuOpen } = useTaskItemContextMenu(
task,
routeScope,
@@ -77,9 +77,9 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
}, [navigate, routeScope, task.assigneeAgentId, task.identifier, task.name]);
const handleRequestSubtasks = useCallback(async () => {
- const detail = await fetchTaskDetail(task.identifier);
+ const detail = await fetchTaskDetail(task.id);
return detail.subtasks ?? [];
- }, [fetchTaskDetail, task.identifier]);
+ }, [fetchTaskDetail, task.id]);
const handleSubtaskClick = useCallback(
(identifier: string, assigneeAgentId?: string, name?: string) => {
@@ -122,8 +122,8 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
const titleRow = (
<Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <TaskPriorityTag priority={task.priority} taskIdentifier={task.identifier} />
- <TaskStatusTag status={status} taskIdentifier={task.identifier} />
+ <TaskPriorityTag priority={task.priority} taskIdentifier={task.id} />
+ <TaskStatusTag status={status} taskIdentifier={task.id} />
{privacyBadge}
{archivedBadge}
{hasName ? (
@@ -158,7 +158,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
currentUserId={task.assigneeUserId}
disabled={status === 'running'}
taskCreatorId={task.createdByUserId}
- taskIdentifier={task.identifier}
+ taskIdentifier={task.id}
taskVisibility={task.visibility}
>
{task.assigneeUserId ? (
@@ -173,7 +173,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
<AssigneeAgentSelector
currentAgentId={task.assigneeAgentId}
disabled={status === 'running'}
- taskIdentifier={task.identifier}
+ taskIdentifier={task.id}
taskVisibility={task.visibility}
>
{task.assigneeAgentId ? (
@@ -221,7 +221,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
{assigneeNode}
</Flexbox>
<Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <TaskStatusTag status={status} taskIdentifier={task.identifier} />
+ <TaskStatusTag status={status} taskIdentifier={task.id} />
<Text ellipsis style={{ minWidth: 0 }} weight={500}>
{hasName ? task.name : task.identifier}
</Text>
@@ -235,7 +235,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant
/>
</Flexbox>
<Flexbox horizontal align={'center'} gap={8} style={FLEX_MIN_WIDTH_0}>
- <TaskPriorityTag priority={task.priority} taskIdentifier={task.identifier} />
+ <TaskPriorityTag priority={task.priority} taskIdentifier={task.id} />
{scheduleNode}
{timeNode}
</Flexbox>
diff --git a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
index 4e723f88948..b79b0d8f3f7 100644
--- a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
+++ b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
@@ -63,6 +63,7 @@ describe('TaskSubtaskProgressTag', () => {
subtasks={[
{
assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ id: 'task_child',
identifier: 'T-2',
name: 'Child task',
status: 'backlog',
@@ -72,7 +73,7 @@ describe('TaskSubtaskProgressTag', () => {
/>,
);
- fireEvent.click(screen.getByTestId('subtask-T-2'));
+ fireEvent.click(screen.getByTestId('subtask-task_child'));
expect(onSubtaskClick).toHaveBeenCalledWith('T-2', 'agt_child', 'Child task');
});
@@ -96,12 +97,16 @@ describe('TaskSubtaskProgressTag', () => {
it('uses the list summary until detail is refreshed, then yields to a newer list summary', async () => {
const onRequestSubtasks = vi
.fn()
- .mockResolvedValue([{ identifier: 'T-current', name: 'Current child', status: 'completed' }]);
+ .mockResolvedValue([
+ { id: 'T-current', identifier: 'T-current', name: 'Current child', status: 'completed' },
+ ]);
const { rerender } = render(
<TaskSubtaskProgressTag
progress={{ completed: 1, total: 2 }}
- subtasks={[{ identifier: 'T-stale', name: 'Stale child', status: 'completed' }]}
+ subtasks={[
+ { id: 'T-stale', identifier: 'T-stale', name: 'Stale child', status: 'completed' },
+ ]}
onRequestSubtasks={onRequestSubtasks}
onSubtaskClick={vi.fn()}
/>,
@@ -114,7 +119,9 @@ describe('TaskSubtaskProgressTag', () => {
rerender(
<TaskSubtaskProgressTag
progress={{ completed: 2, total: 3 }}
- subtasks={[{ identifier: 'T-stale', name: 'Stale child', status: 'completed' }]}
+ subtasks={[
+ { id: 'T-stale', identifier: 'T-stale', name: 'Stale child', status: 'completed' },
+ ]}
onRequestSubtasks={onRequestSubtasks}
onSubtaskClick={vi.fn()}
/>,
@@ -127,7 +134,7 @@ describe('TaskSubtaskProgressTag', () => {
const onParentClick = vi.fn();
const onRequestSubtasks = vi
.fn()
- .mockResolvedValue([{ identifier: 'T-2', name: 'Child task', status: 'backlog' }]);
+ .mockResolvedValue([{ id: 'T-2', identifier: 'T-2', name: 'Child task', status: 'backlog' }]);
const onSubtaskClick = vi.fn();
render(
@@ -150,7 +157,7 @@ describe('TaskSubtaskProgressTag', () => {
it('keeps a hover-opened static menu open when the tag is clicked', async () => {
render(
<TaskSubtaskProgressTag
- subtasks={[{ identifier: 'T-2', name: 'Child task', status: 'backlog' }]}
+ subtasks={[{ id: 'T-2', identifier: 'T-2', name: 'Child task', status: 'backlog' }]}
onSubtaskClick={vi.fn()}
/>,
);
@@ -166,12 +173,12 @@ describe('TaskSubtaskProgressTag', () => {
it('closes an open subtask menu without refreshing it again', async () => {
const onRequestSubtasks = vi
.fn()
- .mockResolvedValue([{ identifier: 'T-2', name: 'Child task', status: 'backlog' }]);
+ .mockResolvedValue([{ id: 'T-2', identifier: 'T-2', name: 'Child task', status: 'backlog' }]);
render(
<TaskSubtaskProgressTag
progress={{ completed: 0, total: 1 }}
- subtasks={[{ identifier: 'T-2', name: 'Child task', status: 'backlog' }]}
+ subtasks={[{ id: 'T-2', identifier: 'T-2', name: 'Child task', status: 'backlog' }]}
onRequestSubtasks={onRequestSubtasks}
onSubtaskClick={vi.fn()}
/>,
@@ -192,7 +199,9 @@ describe('TaskSubtaskProgressTag', () => {
const { rerender } = render(
<TaskSubtaskProgressTag
progress={{ completed: 0, total: 1 }}
- subtasks={[{ identifier: 'T-stale', name: 'Removed child', status: 'backlog' }]}
+ subtasks={[
+ { id: 'T-stale', identifier: 'T-stale', name: 'Removed child', status: 'backlog' },
+ ]}
onRequestSubtasks={onRequestSubtasks}
onSubtaskClick={vi.fn()}
/>,
@@ -206,7 +215,9 @@ describe('TaskSubtaskProgressTag', () => {
rerender(
<TaskSubtaskProgressTag
progress={{ completed: 0, total: 1 }}
- subtasks={[{ identifier: 'T-stale', name: 'Removed child', status: 'backlog' }]}
+ subtasks={[
+ { id: 'T-stale', identifier: 'T-stale', name: 'Removed child', status: 'backlog' },
+ ]}
onRequestSubtasks={onRequestSubtasks}
onSubtaskClick={vi.fn()}
/>,
diff --git a/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx b/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx
index 9e85a08dfc3..36473f0770e 100644
--- a/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx
+++ b/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx
@@ -43,7 +43,7 @@ const flattenSubtasks = (nodes: TaskDetailSubtask[]) => {
return list;
}
- const taskMap = new Map(nodes.map((item) => [item.identifier, item]));
+ const taskMap = new Map(nodes.map((item) => [item.id!, item]));
const depthMemo = new Map<string, number>();
const getDepth = (identifier: string, stack: Set<string>): number => {
@@ -53,7 +53,7 @@ const flattenSubtasks = (nodes: TaskDetailSubtask[]) => {
if (stack.has(identifier)) return 0;
const node = taskMap.get(identifier);
- const parentIdentifier = node?.blockedBy;
+ const parentIdentifier = node?.blockedById;
if (!node || !parentIdentifier || !taskMap.has(parentIdentifier)) {
depthMemo.set(identifier, 0);
return 0;
@@ -68,7 +68,7 @@ const flattenSubtasks = (nodes: TaskDetailSubtask[]) => {
};
return nodes.map((task) => ({
- depth: getDepth(task.identifier, new Set<string>()),
+ depth: getDepth(task.id!, new Set<string>()),
task,
}));
};
@@ -129,7 +129,7 @@ const TaskSubtaskProgressTag = memo<TaskSubtaskProgressTagProps>(
const itemStatus = toTaskStatus(subtask.task.status);
return {
- key: subtask.task.identifier,
+ key: subtask.task.id!,
label: (
<Flexbox horizontal align="center" gap={8}>
{subtask.depth > 0 && <div style={{ flex: 'none', width: subtask.depth * 16 }} />}
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
index 755107dd426..3a7c99a528e 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
@@ -108,6 +108,7 @@ describe('useTaskItemContextMenu', () => {
it('does not render adjacent dividers around transfer actions', () => {
const { result } = renderHook(() =>
useTaskItemContextMenu({
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
@@ -126,7 +127,13 @@ describe('useTaskItemContextMenu', () => {
describe('archive action', () => {
const findArchiveItem = (archivedAt?: Date | null) => {
const { result } = renderHook(() =>
- useTaskItemContextMenu({ archivedAt, identifier: 'T-1', priority: 0, status: 'completed' }),
+ useTaskItemContextMenu({
+ archivedAt,
+ id: 'task_1',
+ identifier: 'T-1',
+ priority: 0,
+ status: 'completed',
+ }),
);
return result.current.items.find(
(item) => item && typeof item === 'object' && 'key' in item && item.key === 'archive',
@@ -141,7 +148,7 @@ describe('useTaskItemContextMenu', () => {
await click(item);
- expect(mocks.archiveTask).toHaveBeenCalledWith('T-1', true);
+ expect(mocks.archiveTask).toHaveBeenCalledWith('task_1', true);
});
it('restores an archived task', async () => {
@@ -150,13 +157,14 @@ describe('useTaskItemContextMenu', () => {
await click(item);
- expect(mocks.archiveTask).toHaveBeenCalledWith('T-1', false);
+ expect(mocks.archiveTask).toHaveBeenCalledWith('task_1', false);
});
it('keeps restore available on an archived task whose work could still run', async () => {
const { result } = renderHook(() =>
useTaskItemContextMenu({
archivedAt: new Date(),
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'running',
@@ -169,7 +177,7 @@ describe('useTaskItemContextMenu', () => {
expect(item.disabled).toBe(false);
expect(item.desc).toBeUndefined();
await item.onClick({ domEvent: { stopPropagation: vi.fn() } });
- expect(mocks.archiveTask).toHaveBeenCalledWith('T-1', false);
+ expect(mocks.archiveTask).toHaveBeenCalledWith('task_1', false);
});
it('disables archiving work that can still run and says why', async () => {
@@ -178,6 +186,7 @@ describe('useTaskItemContextMenu', () => {
archivedAt: null,
automationMode: 'heartbeat',
heartbeatInterval: 600,
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
@@ -213,13 +222,14 @@ describe('useTaskItemContextMenu', () => {
expect(item.disabled).toBe(false);
expect(item.desc).toBeUndefined();
await click(item);
- expect(mocks.archiveTask).toHaveBeenCalledWith('T-1', true);
+ expect(mocks.archiveTask).toHaveBeenCalledWith('task_1', true);
});
it('offers no Run now on an archived task', () => {
const { result } = renderHook(() =>
useTaskItemContextMenu({
archivedAt: new Date(),
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
@@ -241,6 +251,7 @@ describe('useTaskItemContextMenu', () => {
useTaskItemContextMenu(
{
assigneeAgentId: 'agent-1',
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
@@ -264,6 +275,7 @@ describe('useTaskItemContextMenu', () => {
const { result } = renderHook(() =>
useTaskItemContextMenu({
assigneeUserId: 'user-1',
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
@@ -279,12 +291,13 @@ describe('useTaskItemContextMenu', () => {
});
expect(mocks.updateTask).not.toHaveBeenCalled();
- expect(mocks.runTask).toHaveBeenCalledWith('T-1');
+ expect(mocks.runTask).toHaveBeenCalledWith('task_1');
});
it('routes the keyboard-shortcut submenu selection through @/libs/contextMenu', () => {
const { result } = renderHook(() =>
useTaskItemContextMenu({
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
@@ -319,6 +332,7 @@ describe('menu ownership', () => {
it('must stay web because the status/priority submenus depend on number-shortcut extra badges', () => {
const { result } = renderHook(() =>
useTaskItemContextMenu({
+ id: 'task_1',
identifier: 'T-1',
priority: 0,
status: 'backlog',
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
index ec7123732ea..6763f60a022 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
@@ -51,6 +51,7 @@ export interface TaskContextMenuTarget {
assigneeUserId?: string | null;
automationMode?: string | null;
heartbeatInterval?: number | null;
+ id: string;
identifier: string;
/** Only feeds the copied link's readable slug tail. */
name?: string | null;
@@ -120,7 +121,7 @@ export const useTaskContextMenuActions = (
domEvent.stopPropagation();
if (!canEditTask) return;
if (status === currentStatus) return;
- void changeTaskStatus(task.identifier, status);
+ void changeTaskStatus(task.id, status);
},
} as ContextMenuItem;
});
@@ -142,7 +143,7 @@ export const useTaskContextMenuActions = (
domEvent.stopPropagation();
if (!canEditTask) return;
if (level === currentPriority) return;
- await updateTask(task.identifier, { priority: level });
+ await updateTask(task.id, { priority: level });
await refreshTaskList();
},
} as ContextMenuItem;
@@ -180,7 +181,7 @@ export const useTaskContextMenuActions = (
domEvent.stopPropagation();
if (!canArchive) return;
try {
- await archiveTask(task.identifier, !isArchived);
+ await archiveTask(task.id, !isArchived);
} catch (error) {
toast.error(t(getArchiveErrorKey(error)));
return;
@@ -209,9 +210,9 @@ export const useTaskContextMenuActions = (
domEvent.stopPropagation();
if (!canEditTask) return;
if (!task.assigneeAgentId && !task.assigneeUserId && inboxAgentId) {
- await updateTask(task.identifier, { assigneeAgentId: inboxAgentId });
+ await updateTask(task.id, { assigneeAgentId: inboxAgentId });
}
- await runTask(task.identifier);
+ await runTask(task.id);
},
sfSymbol: 'play.fill',
},
@@ -272,7 +273,7 @@ export const useTaskContextMenuActions = (
onClick: ({ domEvent }: MenuInfo) => {
domEvent.stopPropagation();
if (!canEditTask) return;
- triggerDelete(task.identifier);
+ triggerDelete(task.id);
},
sfSymbol: 'trash',
},
@@ -315,7 +316,7 @@ export const useTaskContextMenuActions = (
const nextLevel = PRIORITY_LEVELS[idx];
if (nextLevel !== currentPriority) {
void (async () => {
- await updateTask(task.identifier, { priority: nextLevel });
+ await updateTask(task.id, { priority: nextLevel });
await refreshTaskList();
})();
}
@@ -330,7 +331,7 @@ export const useTaskContextMenuActions = (
event.stopPropagation();
const nextStatus = USER_SELECTABLE_STATUSES[idx];
if (nextStatus !== currentStatus) {
- void changeTaskStatus(task.identifier, nextStatus);
+ void changeTaskStatus(task.id, nextStatus);
}
closeContextMenu();
cleanup();
@@ -375,7 +376,7 @@ export const useTaskItemContextMenu = (
routeScope?: TaskItemRouteScope,
): TaskItemContextMenu => {
const { buildItems, installKeyboardHandlers } = useTaskContextMenuActions(routeScope);
- const transferItems = useTaskTransferMenuItem(task.identifier) as ContextMenuItem[] | null;
+ const transferItems = useTaskTransferMenuItem(task.id) as ContextMenuItem[] | null;
const items = useMemo(() => {
const base = buildItems(task);
if (!transferItems || transferItems.length === 0) return base;
diff --git a/src/features/AgentTasks/shared/Breadcrumb.test.tsx b/src/features/AgentTasks/shared/Breadcrumb.test.tsx
index b63fd3094bc..59ed556b205 100644
--- a/src/features/AgentTasks/shared/Breadcrumb.test.tsx
+++ b/src/features/AgentTasks/shared/Breadcrumb.test.tsx
@@ -47,18 +47,25 @@ describe('Breadcrumb', () => {
beforeEach(() => {
mocks.taskState = createState({
'T-child': {
+ id: 'T-child',
identifier: 'T-child',
instruction: 'Child instruction',
name: 'Child task',
- parent: { agentId: 'agt_parent', identifier: 'T-parent', name: 'Parent task' },
+ parent: {
+ agentId: 'agt_parent',
+ id: 'T-parent',
+ identifier: 'T-parent',
+ name: 'Parent task',
+ },
status: 'running',
},
'T-parent': {
agentId: 'agt_parent',
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent instruction',
name: 'Parent task',
- parent: { agentId: null, identifier: 'T-root', name: 'Root task' },
+ parent: { agentId: null, id: 'T-root', identifier: 'T-root', name: 'Root task' },
status: 'running',
},
});
@@ -99,10 +106,11 @@ describe('Breadcrumb', () => {
it('falls back to the global route when an ancestor owner is unknown', () => {
mocks.taskState = createState({
'T-child': {
+ id: 'T-child',
identifier: 'T-child',
instruction: 'Child instruction',
name: 'Child task',
- parent: { identifier: 'T-parent', name: 'Parent task' },
+ parent: { id: 'T-parent', identifier: 'T-parent', name: 'Parent task' },
status: 'running',
},
});
diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsx
index 3ea7dabac98..347f635e6af 100644
--- a/src/features/AgentTasks/shared/Breadcrumb.tsx
+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx
@@ -22,21 +22,28 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
const { t } = useTranslation('chat');
const { aid } = useParams<{ aid?: string }>();
const agentMeta = useAgentDisplayMeta(aid);
- const taskTitle = useTaskStore((s) => (taskId ? s.taskDetailMap[taskId]?.name : undefined));
+ const taskTitle = useTaskStore((s) =>
+ taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.name : undefined,
+ );
const taskIdentifier = useTaskStore((s) =>
- taskId ? s.taskDetailMap[taskId]?.identifier : undefined,
+ taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.identifier : undefined,
);
const ancestors = useTaskStore(
useShallow((s) => {
if (!taskId) return [];
- const chain: Array<{ agentId?: string | null; identifier: string; name?: string | null }> =
- [];
+ const chain: Array<{
+ id: string;
+ agentId?: string | null;
+ identifier: string;
+ name?: string | null;
+ }> = [];
const visited = new Set<string>([taskId]);
- let cursor = s.taskDetailMap[taskId]?.parent;
- while (cursor?.identifier && !visited.has(cursor.identifier)) {
- const detail = s.taskDetailMap[cursor.identifier];
- visited.add(cursor.identifier);
+ let cursor = s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.parent;
+ while (cursor?.id && !visited.has(cursor.id)) {
+ const detail = s.taskDetailMap[cursor.id];
+ visited.add(cursor.id);
chain.push({
+ id: cursor.id,
agentId: cursor.agentId === undefined ? detail?.agentId : cursor.agentId,
identifier: cursor.identifier,
name: cursor.name ?? detail?.name,
@@ -81,8 +88,8 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
}
: agentCrumb;
- const ancestorCrumbs = ancestors.map(({ identifier, agentId, name }) => ({
- key: identifier,
+ const ancestorCrumbs = ancestors.map(({ id, identifier, agentId, name }) => ({
+ key: id,
title: (
<WorkspaceLink to={taskDetailPath(identifier, agentId ?? undefined, name)}>
<Text color={'inherit'} weight={500}>
diff --git a/src/features/AgentTasks/shared/canonicalTaskPath.test.ts b/src/features/AgentTasks/shared/canonicalTaskPath.test.ts
new file mode 100644
index 00000000000..e07803d4ba4
--- /dev/null
+++ b/src/features/AgentTasks/shared/canonicalTaskPath.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { canonicalTaskPath } from './canonicalTaskPath';
+
+describe('canonical task location', () => {
+ it('uses the public identifier and preserves workspace, agent, query, and hash', () => {
+ expect(
+ canonicalTaskPath({
+ taskRef: 'T-3',
+ aid: 'agt_1',
+ workspaceSlug: 'team',
+ title: 'Ship it',
+ search: '?tab=runs',
+ hash: '#activity',
+ }),
+ ).toBe('/team/agent/agt_1/task/T-3/ship-it?tab=runs#activity');
+ });
+ it('supports a global task with an empty title', () => {
+ expect(canonicalTaskPath({ taskRef: 'T-3', title: '', search: '', hash: '' })).toBe(
+ '/task/T-3',
+ );
+ });
+});
diff --git a/src/features/AgentTasks/shared/canonicalTaskPath.ts b/src/features/AgentTasks/shared/canonicalTaskPath.ts
new file mode 100644
index 00000000000..d11378e0a15
--- /dev/null
+++ b/src/features/AgentTasks/shared/canonicalTaskPath.ts
@@ -0,0 +1,11 @@
+import { taskDetailPath } from './taskDetailPath';
+
+export const canonicalTaskPath = (input: {
+ aid?: string;
+ hash: string;
+ taskRef: string;
+ search: string;
+ title?: string | null;
+ workspaceSlug?: string;
+}) =>
+ `${input.workspaceSlug ? `/${input.workspaceSlug}` : ''}${taskDetailPath(input.taskRef, input.aid, input.title)}${input.search}${input.hash}`;
diff --git a/src/features/AgentTasks/shared/taskDetailPath.ts b/src/features/AgentTasks/shared/taskDetailPath.ts
index ebf7ef855d0..ba3743a0996 100644
--- a/src/features/AgentTasks/shared/taskDetailPath.ts
+++ b/src/features/AgentTasks/shared/taskDetailPath.ts
@@ -10,8 +10,8 @@ import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
* accept but never resolve against, so a caller without the title in hand still
* produces a working link.
*/
-export const taskDetailPath = (taskId: string, agentId?: string, title?: string | null) => {
- const base = agentId ? `/agent/${agentId}/task/${taskId}` : `/task/${taskId}`;
+export const taskDetailPath = (taskRef: string, agentId?: string, title?: string | null) => {
+ const base = agentId ? `/agent/${agentId}/task/${taskRef}` : `/task/${taskRef}`;
const slug = taskTitleSlug(title);
return slug ? `${base}/${slug}` : base;
@@ -21,8 +21,8 @@ export const useTaskDetailPath = () => {
const { aid } = useActiveRouteParams<{ aid?: string }>();
return useCallback(
- (taskId: string, agentId?: string, title?: string | null) =>
- taskDetailPath(taskId, agentId ?? aid, title),
+ (taskRef: string, agentId?: string, title?: string | null) =>
+ taskDetailPath(taskRef, agentId ?? aid, title),
[aid],
);
};
@@ -32,8 +32,8 @@ export const useNavigateToTaskDetail = () => {
const getTaskDetailPath = useTaskDetailPath();
return useCallback(
- (taskId: string, agentId?: string, title?: string | null) => {
- navigate(getTaskDetailPath(taskId, agentId, title));
+ (taskRef: string, agentId?: string, title?: string | null) => {
+ navigate(getTaskDetailPath(taskRef, agentId, title));
},
[getTaskDetailPath, navigate],
);
diff --git a/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts b/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts
index 4369fab99e1..ac95a791f48 100644
--- a/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts
+++ b/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts
@@ -27,7 +27,11 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
const setTaskDetail = (detail?: { instruction?: string; name?: string | null }) => {
useTaskStore.setState({
- taskDetailMap: detail === undefined ? {} : ({ 'T-1': detail } as never),
+ taskRefIndex: { 'T-1': 'task_1', 'task_1': 'task_1' },
+ taskDetailMap:
+ detail === undefined
+ ? {}
+ : ({ task_1: { ...detail, id: 'task_1', identifier: 'T-1' } } as never),
});
};
@@ -104,7 +108,7 @@ describe('useCanonicalTaskSlug', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/task/T-1', { replace: true });
});
- it('leaves a nameless task at its bare id instead of slugging the instruction', () => {
+ it('leaves a nameless task at its bare identifier instead of slugging the instruction', () => {
// A task's instruction is a prompt body: putting it in the path would leak
// it into history, analytics page views and every copied link. A task with
// no name simply has no slug.
@@ -124,6 +128,17 @@ describe('useCanonicalTaskSlug', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/task/T-1', { replace: true });
});
+ it('preserves a stable id URL even when cached label metadata may be stale', () => {
+ mocks.params = { slug: 'stale-title', aid: 'agt_owner', workspaceSlug: 'team' };
+ mocks.location = { hash: '#activity', search: '?tab=runs' };
+ setTaskName('Ship the Thing');
+ renderHook(() => useCanonicalTaskSlug('task_1'));
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ '/team/agent/agt_owner/task/task_1/ship-the-thing?tab=runs#activity',
+ { replace: true },
+ );
+ });
+
it('leaves the URL alone while the title is still unknown', () => {
mocks.params = { slug: 'an-incoming-slug' };
diff --git a/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts b/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts
index f0966669d43..56e529e5fca 100644
--- a/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts
+++ b/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts
@@ -8,7 +8,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useTaskStore } from '@/store/task';
-import { taskDetailPath } from './taskDetailPath';
+import { canonicalTaskPath } from './canonicalTaskPath';
type CanonicalTaskSlugParams = {
aid?: string;
@@ -17,12 +17,13 @@ type CanonicalTaskSlugParams = {
};
/**
- * Keep the readable tail of a task URL in sync with the task title.
+ * Keep the readable title tail in sync without changing the route's task reference.
*
* Upgrades a bare `/task/:taskId` link to `/task/:taskId/:slug` once the title
* lands, and repairs a slug left stale by a rename or hand-edited by whoever
- * pasted the link. The slug is cosmetic — `taskId` remains the only resolution
- * key — so this never gates rendering or re-fetches, and `replace` keeps the
+ * pasted the link. Identifier and stable-id URLs both keep their reference.
+ * A cached display alias must never redirect a stable-id URL to another task.
+ * The slug is cosmetic, so this never gates rendering or re-fetches; `replace` keeps the
* correction out of the back stack.
*
* Only route components may call this: the same detail body also renders inside
@@ -35,10 +36,14 @@ export const useCanonicalTaskSlug = (taskId?: string) => {
// Loaded-ness and the title are read separately: an empty title is a real,
// resolved state (clearing the input persists `name: ''`), and folding it in
// with "not loaded yet" would pin the URL to the slug of the old title.
- const isLoaded = useTaskStore((s) => (taskId ? Boolean(s.taskDetailMap[taskId]) : false));
+ const isLoaded = useTaskStore((s) =>
+ taskId ? Boolean(s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]) : false,
+ );
// `name` only, and the link builders agree: a task's instruction is a prompt
// body, not a title, and must never reach a URL (see `taskTitleSlug`).
- const title = useTaskStore((s) => (taskId ? (s.taskDetailMap[taskId]?.name ?? '') : ''));
+ const title = useTaskStore((s) =>
+ taskId ? (s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.name ?? '') : '',
+ );
useEffect(() => {
// Before the detail resolves the title is unknown — leaving the URL alone
@@ -52,8 +57,7 @@ export const useCanonicalTaskSlug = (taskId?: string) => {
// Rebuild from the route params rather than the raw pathname so the
// workspace prefix and agent scope of the current URL survive untouched;
// `escape` then stops the workspace-aware navigate re-prefixing them.
- const prefix = workspaceSlug ? `/${workspaceSlug}` : '';
- navigate(`${prefix}${taskDetailPath(taskId, aid, title)}${search}${hash}`, {
+ navigate(canonicalTaskPath({ taskRef: taskId, aid, title, workspaceSlug, search, hash }), {
escape: true,
replace: true,
});
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index b19ce8c0014..4cf588cd7b8 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -174,7 +174,7 @@ const SearchResults = memo<SearchResultsProps>(
break;
}
case 'task': {
- navigate(taskDetailPath(result.identifier, undefined, result.title));
+ navigate(taskDetailPath(result.identifier ?? result.id, undefined, result.title));
break;
}
}
diff --git a/src/features/Conversation/Messages/TaskCallback/index.tsx b/src/features/Conversation/Messages/TaskCallback/index.tsx
index f6440df36f1..94718cc44d3 100644
--- a/src/features/Conversation/Messages/TaskCallback/index.tsx
+++ b/src/features/Conversation/Messages/TaskCallback/index.tsx
@@ -67,7 +67,7 @@ const TaskCallbackMessage = memo<TaskCallbackMessageProps>(({ id }) => {
const reason = (callback.reason ?? 'done') as CallbackReason;
const { color, i18nKey, icon } = reasonMeta[reason] ?? reasonMeta.done;
const content = typeof item?.content === 'string' ? item.content : '';
- const openTask = () => openTaskDetail(callback.identifier);
+ const openTask = () => openTaskDetail(callback.taskId ?? callback.identifier);
const viewTaskButton = (
<Button icon={SquareArrowOutUpRight} size={'small'} type={'text'} onClick={openTask}>
diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
index 17d154f8cb0..601dc261ebb 100644
--- a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
+++ b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
@@ -102,7 +102,7 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
case 'task': {
return resourceDeleted
? () => promptResourceDeleted(work)
- : () => openTaskDetail(openTarget.identifier);
+ : () => openTaskDetail(openTarget.taskId);
}
}
})();
diff --git a/src/features/DailyBrief/BriefActionLink.tsx b/src/features/DailyBrief/BriefActionLink.tsx
index 92f6c80b3fc..8cf4f3fd3f9 100644
--- a/src/features/DailyBrief/BriefActionLink.tsx
+++ b/src/features/DailyBrief/BriefActionLink.tsx
@@ -24,6 +24,7 @@ interface BriefActionLinkProps {
/** Renders the filled primary variant used for a card's leading action. */
primary?: boolean;
taskId?: string | null;
+ taskIdentifier?: string | null;
url?: string;
/**
* `quiet`: a small secondary text button, the same as the card's "View run"
@@ -48,7 +49,7 @@ interface BriefActionLinkProps {
* click is already claimed.
*/
export const BriefActionLink = memo<BriefActionLinkProps>(
- ({ agentId, children, className, icon, primary, taskId, url, variant }) => {
+ ({ agentId, children, className, icon, primary, taskId, taskIdentifier, url, variant }) => {
const navigate = useWorkspaceAwareNavigate();
const workspaces = useWorkspaces();
const openAcceptance = useChatStore((s) => s.openAcceptance);
@@ -84,7 +85,7 @@ export const BriefActionLink = memo<BriefActionLinkProps>(
// page and reads this state on its first render.
toggleTaskAgentPanel(true);
openAcceptance(reference.acceptanceId);
- navigate(taskDetailPath(taskId, agentId ?? undefined));
+ navigate(taskDetailPath(taskIdentifier ?? taskId, agentId ?? undefined));
return;
}
@@ -101,6 +102,7 @@ export const BriefActionLink = memo<BriefActionLinkProps>(
openAcceptance,
reference,
taskId,
+ taskIdentifier,
toggleTaskAgentPanel,
],
);
diff --git a/src/features/DailyBrief/BriefCardActions.tsx b/src/features/DailyBrief/BriefCardActions.tsx
index 5e02cfa76b5..b4d3670b28e 100644
--- a/src/features/DailyBrief/BriefCardActions.tsx
+++ b/src/features/DailyBrief/BriefCardActions.tsx
@@ -38,6 +38,7 @@ export interface BriefCardActionsProps {
recommendedActionKey?: string;
resolvedAction?: string | null;
taskId?: string | null;
+ taskIdentifier?: string | null;
/** Parent task's runtime status — `scheduled` flips the result action to a plain "Confirm" since approving must NOT terminate a task parked between automated runs. */
taskStatus?: TaskStatus | null;
/** When set together with taskId, renders a "View run" shortcut to the topic drawer. */
@@ -67,6 +68,7 @@ const BriefCardActions = memo<BriefCardActionsProps>(
onAfterResolve,
resolvedAction,
taskId,
+ taskIdentifier,
taskStatus,
topicId,
topicTitle,
@@ -308,6 +310,7 @@ const BriefCardActions = memo<BriefCardActionsProps>(
icon={Target}
key={action.key}
taskId={taskId}
+ taskIdentifier={taskIdentifier}
url={action.url}
variant={'quiet'}
>
@@ -357,6 +360,7 @@ const BriefCardActions = memo<BriefCardActionsProps>(
className={styles.actionBtn}
key={action.key}
taskId={taskId}
+ taskIdentifier={taskIdentifier}
url={action.url}
>
{getActionLabel(action)}
@@ -396,6 +400,7 @@ const BriefCardActions = memo<BriefCardActionsProps>(
agentId={agentId}
className={styles.actionBtnPrimary}
taskId={taskId}
+ taskIdentifier={taskIdentifier}
url={primaryActions.url}
>
{getActionLabel(primaryActions)}
diff --git a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts
index 186209795ab..15977d49857 100644
--- a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts
+++ b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts
@@ -69,6 +69,7 @@ describe('resolveTrayNavigationSnapshot', () => {
recent({
agentId: 'agent-1',
id: 'task-1',
+ taskIdentifier: 'T-3',
routePath: '/agent/agent-1/task/task-1',
slugTitle: 'Ship it',
title: 'Ship it',
@@ -84,7 +85,7 @@ describe('resolveTrayNavigationSnapshot', () => {
{
subtitle: 'Researcher',
title: 'Ship it',
- url: '/acme/agent/agent-1/task/task-1/ship-it',
+ url: '/acme/agent/agent-1/task/T-3/ship-it',
},
]);
});
diff --git a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts
index ee041d67451..af7785e6b57 100644
--- a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts
+++ b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts
@@ -47,7 +47,7 @@ const activeTopicUrl = (scope: TabScope, { agentId, groupId, topicId }: ActiveTo
const recentRoute = (item: RecentItem) =>
item.type === 'task'
- ? taskDetailPath(item.id, item.agentId ?? undefined, item.slugTitle)
+ ? taskDetailPath(item.taskIdentifier ?? item.id, item.agentId ?? undefined, item.slugTitle)
: item.routePath;
export const resolveTrayNavigationSnapshot = ({
diff --git a/src/features/Home/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.ts
index 4aaeb3be723..5082bd38e9a 100644
--- a/src/features/Home/InputArea/useSend.test.ts
+++ b/src/features/Home/InputArea/useSend.test.ts
@@ -216,6 +216,7 @@ describe('Home InputArea useSend', () => {
agentState.agentMap.agt_custom = {};
createTaskMock.mockResolvedValue({
assigneeAgentId: 'agt_custom',
+ id: 'task_26',
identifier: 'T-26',
});
const { result } = renderHook(() => useSend('task'));
diff --git a/src/features/Home/Recents/ConnectedItem.tsx b/src/features/Home/Recents/ConnectedItem.tsx
index 668fbd1b125..8717daa748b 100644
--- a/src/features/Home/Recents/ConnectedItem.tsx
+++ b/src/features/Home/Recents/ConnectedItem.tsx
@@ -24,7 +24,7 @@ const ConnectedItem = memo<ConnectedItemProps>(({ itemRef, queryKey }) => {
// this link carries survives arrival instead of being rewritten.
const route =
item.type === 'task'
- ? taskDetailPath(item.id, item.agentId ?? undefined, item.slugTitle)
+ ? taskDetailPath(item.taskIdentifier ?? item.id, item.agentId ?? undefined, item.slugTitle)
: item.routePath;
return (
diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsx
index accd8db3753..769e5490cc9 100644
--- a/src/features/HomeInbox/InboxBriefCard.tsx
+++ b/src/features/HomeInbox/InboxBriefCard.tsx
@@ -91,7 +91,13 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {
const openTask = () => {
if (!brief.taskId) return;
- navigate(taskDetailPath(brief.taskId, brief.agentId ?? undefined, brief.taskName));
+ navigate(
+ taskDetailPath(
+ brief.taskIdentifier ?? brief.taskId,
+ brief.agentId ?? undefined,
+ brief.taskName,
+ ),
+ );
};
const content = (
@@ -194,6 +200,7 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {
recommendedActionKey={goal?.recommendedAction}
resolvedAction={brief.resolvedAction}
taskId={brief.taskId}
+ taskIdentifier={brief.taskIdentifier}
taskStatus={brief.taskStatus}
topicId={brief.topicId}
topicTitle={brief.taskName}
diff --git a/src/features/Portal/TaskDetail/Header.tsx b/src/features/Portal/TaskDetail/Header.tsx
index ee61b23ca39..c31a940413b 100644
--- a/src/features/Portal/TaskDetail/Header.tsx
+++ b/src/features/Portal/TaskDetail/Header.tsx
@@ -21,15 +21,21 @@ const TaskDetailHeader = memo<{ onClose?: () => void }>(({ onClose }) => {
const activeWorkspaceSlug = useActiveWorkspaceSlug();
const taskId = useChatStore(chatPortalSelectors.taskDetailId);
const agentId = useTaskStore((state) =>
- taskId ? (state.taskDetailMap[taskId]?.agentId ?? undefined) : undefined,
+ taskId
+ ? (state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]?.agentId ?? undefined)
+ : undefined,
);
const taskTitle = useTaskStore((state) =>
- taskId ? (state.taskDetailMap[taskId]?.name ?? undefined) : undefined,
+ taskId
+ ? (state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]?.name ?? undefined)
+ : undefined,
);
const pageUrl = getTaskDetailPageUrl({
agentId,
appOrigin,
- taskId,
+ identifier: useTaskStore((state) =>
+ taskId ? state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]?.identifier : undefined,
+ ),
title: taskTitle,
workspaceSlug: activeWorkspaceSlug,
});
diff --git a/src/features/Portal/TaskDetail/Title.tsx b/src/features/Portal/TaskDetail/Title.tsx
index e40781a3efa..a6cfa86440b 100644
--- a/src/features/Portal/TaskDetail/Title.tsx
+++ b/src/features/Portal/TaskDetail/Title.tsx
@@ -24,7 +24,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const Title = memo(() => {
const taskId = useChatStore(chatPortalSelectors.taskDetailId);
- const detail = useTaskStore((s) => (taskId ? s.taskDetailMap[taskId] : undefined));
+ const detail = useTaskStore((s) =>
+ taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId] : undefined,
+ );
const identifier = detail?.identifier ?? taskId;
const name = detail?.name;
diff --git a/src/features/Portal/TaskDetail/url.test.ts b/src/features/Portal/TaskDetail/url.test.ts
index 3423d431e20..127de793ef9 100644
--- a/src/features/Portal/TaskDetail/url.test.ts
+++ b/src/features/Portal/TaskDetail/url.test.ts
@@ -3,6 +3,17 @@ import { describe, expect, it } from 'vitest';
import { getTaskDetailPageUrl } from './url';
describe('getTaskDetailPageUrl', () => {
+ it('uses a public short link while the portal keeps a stable task id', () => {
+ expect(
+ getTaskDetailPageUrl({
+ appOrigin: 'https://app.example.com',
+ taskId: 'task_stable',
+ identifier: 'T-3',
+ workspaceSlug: 'team',
+ agentId: 'agt_1',
+ }),
+ ).toBe('https://app.example.com/team/agent/agt_1/task/T-3');
+ });
it('builds a workspace-aware agent task URL', () => {
expect(
getTaskDetailPageUrl({
diff --git a/src/features/Portal/TaskDetail/url.ts b/src/features/Portal/TaskDetail/url.ts
index f3b0438f12a..0c3ef693a53 100644
--- a/src/features/Portal/TaskDetail/url.ts
+++ b/src/features/Portal/TaskDetail/url.ts
@@ -4,6 +4,7 @@ import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath
interface TaskDetailPageUrlOptions {
agentId?: string;
appOrigin?: string;
+ identifier?: string;
taskId?: string;
/** Optional readable slug source; omitting it still yields a working link. */
title?: string | null;
@@ -14,11 +15,13 @@ export const getTaskDetailPageUrl = ({
agentId,
appOrigin,
taskId,
+ identifier,
title,
workspaceSlug,
}: TaskDetailPageUrlOptions): string | undefined => {
- if (!appOrigin || !taskId) return;
+ const taskRef = identifier ?? taskId;
+ if (!appOrigin || !taskRef) return;
- const path = buildWorkspaceAwarePath(taskDetailPath(taskId, agentId, title), workspaceSlug);
+ const path = buildWorkspaceAwarePath(taskDetailPath(taskRef, agentId, title), workspaceSlug);
return `${appOrigin}${path}`;
};
diff --git a/src/features/Portal/TaskDetail/useMoreMenu.ts b/src/features/Portal/TaskDetail/useMoreMenu.ts
index 31ed835909f..59224f8e1c2 100644
--- a/src/features/Portal/TaskDetail/useMoreMenu.ts
+++ b/src/features/Portal/TaskDetail/useMoreMenu.ts
@@ -13,7 +13,9 @@ export const useTaskDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {
// The body marks this task active while the panel is open, so the copied
// link is byte-for-byte the one the task page's own header copies.
const { link, taskId } = useTaskCopyActions();
- const name = useTaskStore((s) => (taskId ? s.taskDetailMap[taskId]?.name : undefined));
+ const name = useTaskStore((s) =>
+ taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.name : undefined,
+ );
const [updateTask, deleteTask, refreshTaskDetail] = useTaskStore((s) => [
s.updateTask,
s.deleteTask,
diff --git a/src/features/Portal/TaskResult/Title.tsx b/src/features/Portal/TaskResult/Title.tsx
index 6e09488283a..05a25b6f123 100644
--- a/src/features/Portal/TaskResult/Title.tsx
+++ b/src/features/Portal/TaskResult/Title.tsx
@@ -14,7 +14,9 @@ import { useLiveRun } from './useLiveRun';
const Title = memo(() => {
const { t } = useTranslation('chat');
const taskId = useChatStore(chatPortalSelectors.taskResultId);
- const detail = useTaskStore((state) => (taskId ? state.taskDetailMap[taskId] : undefined));
+ const detail = useTaskStore((state) =>
+ taskId ? state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId] : undefined,
+ );
const liveRun = useLiveRun();
const agentMeta = useAgentDisplayMeta(liveRun?.agentId);
diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsx
index f5ecce8b580..bd0561366b9 100644
--- a/src/features/Projects/Workspace/ProjectDashboard.tsx
+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx
@@ -276,7 +276,7 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =>
{t(`goals.status.${task.status}`, { defaultValue: task.status })}
</Tag>
}
- onClick={() => navigate(taskDetailPath(task.id, undefined, task.name))}
+ onClick={() => navigate(taskDetailPath(task.identifier, undefined, task.name))}
/>
))
)}
diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.ts
index f1afa97fba8..38c766ffcb6 100644
--- a/src/features/Projects/Workspace/useProjectComposer.test.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts
@@ -174,7 +174,7 @@ describe('useProjectComposer', () => {
});
it('assigns a task to the picked project agent', async () => {
- mocks.createTask.mockResolvedValue({ id: 'task_1', name: 'Ship it' });
+ mocks.createTask.mockResolvedValue({ id: 'task_1', identifier: 'T-1', name: 'Ship it' });
const { result } = renderHook(() => useProjectComposer(project, 'task', 'reviewer'));
await act(async () => {
@@ -255,7 +255,7 @@ describe('useProjectComposer', () => {
});
it('records a project task with its attachments in task mode', async () => {
- mocks.createTask.mockResolvedValue({ id: 'task_1', name: 'Ship it' });
+ mocks.createTask.mockResolvedValue({ id: 'task_1', identifier: 'T-1', name: 'Ship it' });
mocks.fileList = [image];
const { result } = renderHook(() => useProjectComposer(project, 'task', 'coordinator'));
@@ -272,7 +272,7 @@ describe('useProjectComposer', () => {
}),
);
expect(mocks.clearChatUploadFileList).toHaveBeenCalledWith(['file_1']);
- expect(mocks.navigate).toHaveBeenCalledWith('/task/task_1/ship-it');
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-1/ship-it');
expect(mocks.createProjectTopic).not.toHaveBeenCalled();
expect(mocks.sendMessage).not.toHaveBeenCalled();
});
diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.ts
index 997846de246..018317117d0 100644
--- a/src/features/Projects/Workspace/useProjectComposer.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.ts
@@ -92,7 +92,7 @@ export const useProjectComposer = (
});
clearContent();
clearChatUploadFileList(files.map((file) => file.id));
- if (task) navigate(taskDetailPath(task.id, undefined, task.name));
+ if (task) navigate(taskDetailPath(task.identifier, undefined, task.name));
return;
}
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
index 6e0c764b1f7..a00b9d648a8 100644
--- a/src/features/Work/WorkSummaryCard.tsx
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -203,7 +203,7 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
return;
}
case 'task': {
- openTaskDetail(openTarget.identifier);
+ openTaskDetail(openTarget.taskId);
}
}
};
diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsx
index 17a78a23c1c..d0185f3bd82 100644
--- a/src/features/Work/descriptors.tsx
+++ b/src/features/Work/descriptors.tsx
@@ -45,7 +45,7 @@ const PROVIDER_ICONS: Record<WorkSkillProvider, WorkIcon> = {
*/
export type WorkOpenTarget =
| { agentDocumentId?: string; documentId: string; kind: 'document' }
- | { identifier: string; kind: 'task'; name?: string | null }
+ | { taskId: string; identifier?: string; kind: 'task'; name?: string | null }
| { kind: 'external'; url: string }
/**
* In-app preview of a cloud-persisted file (the FilePreview chat portal).
@@ -256,16 +256,15 @@ export const WORK_TYPE_DESCRIPTORS: {
getDescription: (item) => item.task.instruction?.trim() ?? null,
getIcon: () => ClipboardListIcon,
getIdentifier: (item) => item.task.identifier,
- // Resolve the task detail by its human identifier (`TASK-1`, live-coalesced
- // with the persisted works column) when present, else its id — the same
- // identifier the chat portal and standalone route both accept. The
- // task-deleted orphan case is gated by the call site (it also renders a
- // badge), not stripped here. A task Work always has a resourceId, but it is
- // nullable on the base type, so drop the affordance when both are missing.
- getOpenTarget: (item) => {
- const identifier = item.task.identifier ?? item.resourceId;
- return identifier ? { identifier, kind: 'task', name: item.task.name } : null;
- },
+ getOpenTarget: (item) =>
+ item.resourceId
+ ? {
+ taskId: item.resourceId,
+ identifier: item.resourceDeleted ? undefined : (item.task.identifier ?? undefined),
+ kind: 'task',
+ name: item.task.name,
+ }
+ : null,
getTitle: (item) => item.task.name,
},
};
diff --git a/src/features/WorkGallery/useOpenWork.ts b/src/features/WorkGallery/useOpenWork.ts
index b2ad8cff633..21d9577b742 100644
--- a/src/features/WorkGallery/useOpenWork.ts
+++ b/src/features/WorkGallery/useOpenWork.ts
@@ -40,7 +40,9 @@ export const useOpenWork = () => {
return;
}
case 'task': {
- navigate(taskDetailPath(openTarget.identifier, undefined, openTarget.name));
+ navigate(
+ taskDetailPath(openTarget.identifier ?? openTarget.taskId, undefined, openTarget.name),
+ );
}
}
},
diff --git a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts
index 7003d8badc4..1510122c9dd 100644
--- a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts
@@ -30,7 +30,8 @@ export const buildViewedTaskPrompt = (
});
}
- const task = taskState.taskDetailMap[viewedTask.taskId];
+ const task =
+ taskState.taskDetailMap[taskState.taskRefIndex[viewedTask.taskId] ?? viewedTask.taskId];
if (task) return buildTaskDetailPrompt({ defaultAssigneeAgentId, task });
};
diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.ts
index 95c26d34a7f..37af205d4db 100644
--- a/src/store/task/selectors/detailSelectors.ts
+++ b/src/store/task/selectors/detailSelectors.ts
@@ -17,7 +17,8 @@ const activeTaskDetail = (s: TaskStoreState): TaskDetailData | undefined =>
const activeTaskDatabaseId = (s: TaskStoreState) => activeTaskDetail(s)?.id;
-const taskDetailById = (id: string) => (s: TaskStoreState) => s.taskDetailMap[id];
+const taskDetailById = (ref: string) => (s: TaskStoreState) =>
+ s.taskDetailMap[s.taskRefIndex?.[ref] ?? ref];
const isTaskDetailLoading = (s: TaskStoreState): boolean =>
!s.activeTaskId || !s.taskDetailMap[s.activeTaskId];
diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.ts
index c01299b5fde..62c53cdb0c4 100644
--- a/src/store/task/slices/config/action.test.ts
+++ b/src/store/task/slices/config/action.test.ts
@@ -10,6 +10,7 @@ import { taskDetailRefreshes } from '../detail/testUtils';
vi.mock('@/services/task', () => ({
taskService: {
+ find: vi.fn(),
markBriefRead: vi.fn(),
resolveBrief: vi.fn(),
runReview: vi.fn(),
@@ -40,8 +41,12 @@ const mockDetail = {
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(taskService.find).mockImplementation(
+ async (id) => ({ data: { id, identifier: id }, success: true }) as never,
+ );
useTaskStore.setState({
activeTaskId: 'T-1',
+ taskRefIndex: {},
taskDetailMap: { 'T-1': { ...mockDetail } },
});
});
diff --git a/src/store/task/slices/detail/action.stableId.test.ts b/src/store/task/slices/detail/action.stableId.test.ts
new file mode 100644
index 00000000000..7cfc433a2b7
--- /dev/null
+++ b/src/store/task/slices/detail/action.stableId.test.ts
@@ -0,0 +1,140 @@
+import { cleanup, renderHook, waitFor } from '@testing-library/react';
+import useSWR from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, createReplicaState } from '@/libs/replica';
+import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';
+import { useClientDataSWR } from '@/libs/swr';
+import { taskService } from '@/services/task';
+
+import { useTaskStore } from '../../store';
+import { taskGroupListEntity, taskListEntity } from '../list/projection';
+import { taskDetailResource } from './projection';
+
+vi.mock('@/services/task', () => ({
+ taskService: { find: vi.fn(), getDetail: vi.fn(), updateStatus: vi.fn(), update: vi.fn() },
+}));
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn().mockResolvedValue(undefined),
+ useClientDataSWR: vi.fn(),
+}));
+const detail = {
+ id: 'task_1',
+ identifier: 'T-1',
+ instruction: 'test',
+ status: 'backlog',
+ name: 'Before',
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ resetCacheScopeBroadcast();
+ useTaskStore.setState({
+ activeTaskId: undefined,
+ activeTaskRef: undefined,
+ taskRefIndex: {},
+ taskDetailMap: {},
+ taskDetailReplica: createReplicaState(),
+ taskListMap: {},
+ taskListReplica: createReplicaState(),
+ taskGroupListMap: {},
+ taskGroupListReplica: createReplicaState(),
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('canonical task cache', () => {
+ it('hydrates a canonical route from persisted detail without an online alias lookup', async () => {
+ const scope = `task-offline-${crypto.randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'use').mockReturnValue(scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ // Run the real hydration query while the network sync is unavailable.
+ vi.mocked(useClientDataSWR).mockImplementation(
+ (key, fetcher) =>
+ useSWR(Array.isArray(key) && key[0] === 'replica:hydrate' ? key : null, fetcher) as never,
+ );
+ vi.mocked(taskService.find).mockRejectedValue(new Error('offline'));
+ await taskDetailResource.storage!.set(
+ { scope, queryKey: 'task_1' },
+ { data: detail, updatedAt: 1 },
+ );
+ useTaskStore.getState().setActiveTaskId('task_1');
+ const { result } = renderHook(() => useTaskStore.getState().useFetchTaskDetail('task_1'));
+ await waitFor(() => expect(useTaskStore.getState().taskDetailMap.task_1).toMatchObject(detail));
+ expect(useTaskStore.getState().activeTaskId).toBe('task_1');
+ expect(result.current.error).toBeUndefined();
+ expect(taskService.find).not.toHaveBeenCalled();
+ });
+
+ it('resolves an old route once and stores only the stable id', async () => {
+ vi.mocked(taskService.find).mockResolvedValue({ data: detail, success: true } as never);
+ vi.mocked(taskService.getDetail).mockResolvedValue({ data: detail, success: true } as never);
+ useTaskStore.getState().setActiveTaskId('T-1');
+ await useTaskStore.getState().fetchTaskDetail('T-1');
+ expect(Object.keys(useTaskStore.getState().taskDetailMap)).toEqual(['task_1']);
+ expect(useTaskStore.getState().activeTaskId).toBe('task_1');
+ expect(useTaskStore.getState().activeTaskRef).toBe('T-1');
+ expect(useTaskStore.getState().taskRefIndex['T-1']).toBe('task_1');
+ });
+
+ it('updates loaded list and board rows when an id route changes status or name', async () => {
+ const store = useTaskStore.getState();
+ store.internal_dispatchTaskDetail({ id: 'task_1', type: 'setTaskDetail', value: detail });
+ useTaskStore.setState({
+ taskListMap: { list: { items: [detail as never], total: 1 } },
+ taskGroupListMap: {
+ board: {
+ groupBy: 'status',
+ groups: [
+ { key: 'backlog', tasks: [detail as never], total: 1 },
+ { key: 'done', tasks: [], total: 0 },
+ ],
+ },
+ },
+ });
+ vi.mocked(taskService.updateStatus).mockImplementation(async () => {
+ expect(useTaskStore.getState().taskListMap.list.items[0].status).toBe('completed');
+ expect(useTaskStore.getState().taskGroupListMap.board.groups[1].tasks[0].id).toBe('task_1');
+ return { success: true } as never;
+ });
+ await store.updateTaskStatus('task_1', 'completed');
+ vi.mocked(taskService.update).mockImplementation(async () => {
+ expect(useTaskStore.getState().taskListMap.list.items[0].name).toBe('After');
+ return { success: true } as never;
+ });
+ await store.updateTask('task_1', { name: 'After' });
+ });
+
+ it('matches collection rows by id even when identifiers collide', () => {
+ const list = { items: [detail, { ...detail, id: 'task_2' }], total: 2 } as never;
+ const next = taskListEntity.map(list, 'task_1', (row) => ({ ...row, status: 'completed' }));
+ expect(next.items.map((row) => row.status)).toEqual(['completed', 'backlog']);
+ expect(
+ taskGroupListEntity.has(
+ { groups: [{ key: 'backlog', tasks: [detail], total: 1 }], groupBy: 'status' } as never,
+ 'task_1',
+ ),
+ ).toBe(true);
+ });
+
+ it('clears aliases on a scope switch and drops a late alias lookup', async () => {
+ let scope = 'user:personal';
+ const spy = vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ let resolve!: (value: never) => void;
+ vi.mocked(taskService.find).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const pending = useTaskStore.getState().internal_resolveTaskId('T-1');
+ scope = 'user:workspace';
+ broadcastCacheScope(scope);
+ resolve({ data: detail, success: true } as never);
+ await expect(pending).rejects.toThrow('Task scope changed');
+ expect(useTaskStore.getState().taskRefIndex).toEqual({});
+ spy.mockRestore();
+ });
+});
diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.ts
index b38940df35c..a3d25c2dc34 100644
--- a/src/store/task/slices/detail/action.test.ts
+++ b/src/store/task/slices/detail/action.test.ts
@@ -4,11 +4,11 @@ import {
toTaskExecutionConfigPatch,
} from '@lobechat/types';
import { toast } from '@lobehub/ui';
-import { renderHook } from '@testing-library/react';
+import { cleanup, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheScope, createReplicaState } from '@/libs/replica';
-import { useClientDataSWR } from '@/libs/swr';
+import { mutate, useClientDataSWR } from '@/libs/swr';
import { taskService } from '@/services/task';
import { workService } from '@/services/work';
import { goalGraphResource } from '@/store/goal/projection';
@@ -35,6 +35,7 @@ vi.mock('@/services/task', () => ({
addDependency: vi.fn(),
create: vi.fn(),
delete: vi.fn(),
+ find: vi.fn(),
getDetail: vi.fn(),
pinDocument: vi.fn(),
removeDependency: vi.fn(),
@@ -51,7 +52,7 @@ vi.mock('@/services/work', () => ({
}));
vi.mock('@/libs/swr', () => ({
- mutate: vi.fn(),
+ mutate: vi.fn().mockResolvedValue(undefined),
useClientDataSWR: vi.fn(),
}));
@@ -60,8 +61,15 @@ vi.mock('@lobehub/ui', async (importOriginal) => ({
...(await import('~base-ui-stubs')).baseUiStubs,
}));
+afterEach(cleanup);
+
beforeEach(() => {
vi.resetAllMocks();
+ vi.mocked(mutate).mockResolvedValue(undefined);
+ vi.spyOn(cacheScope, 'use').mockReturnValue(cacheScope.get());
+ vi.mocked(taskService.find).mockImplementation(
+ async (id) => ({ data: { id, identifier: id }, success: true }) as any,
+ );
useTaskStore.setState({
activeTaskId: undefined,
activeTopicDrawerAgentId: undefined,
@@ -71,6 +79,10 @@ beforeEach(() => {
isCreatingTask: false,
isDeletingTask: false,
taskDetailMap: {},
+ activeTaskRef: undefined,
+ taskRefIndex: Object.fromEntries(
+ ['T-1', 'T-2', 'T-3', 'T-4', 'T-5', 'T-parent', 'T-child', 'task_1'].map((id) => [id, id]),
+ ),
taskDetailReplica: createReplicaState(),
taskInstructionRevisionMap: {},
taskSaveStatusMap: {},
@@ -91,7 +103,7 @@ describe('TaskDetailSliceAction', () => {
it('polls while the task is in flight and stops once it settles', () => {
vi.mocked(useClientDataSWR).mockReturnValue({ isValidating: false, mutate: vi.fn() } as any);
useTaskStore.setState({
- taskDetailMap: { 'T-1': { identifier: 'T-1', status: 'running' } as any },
+ taskDetailMap: { 'T-1': { id: 'T-1', identifier: 'T-1', status: 'running' } as any },
});
const { rerender } = renderHook(() => useTaskStore.getState().useFetchTaskDetail('T-1'));
@@ -99,7 +111,7 @@ describe('TaskDetailSliceAction', () => {
vi.mocked(useClientDataSWR).mockClear();
useTaskStore.setState({
- taskDetailMap: { 'T-1': { identifier: 'T-1', status: 'completed' } as any },
+ taskDetailMap: { 'T-1': { id: 'T-1', identifier: 'T-1', status: 'completed' } as any },
});
rerender();
expect(syncCall()?.[2]).toMatchObject({ refreshInterval: 0 });
@@ -109,8 +121,8 @@ describe('TaskDetailSliceAction', () => {
vi.mocked(useClientDataSWR).mockReturnValue({ isValidating: false, mutate: vi.fn() } as any);
useTaskStore.setState({
taskDetailMap: {
- 'T-1': { identifier: 'T-1', status: 'backlog' } as any,
- 'T-2': { identifier: 'T-2', status: 'backlog' } as any,
+ 'T-1': { id: 'T-1', identifier: 'T-1', status: 'backlog' } as any,
+ 'T-2': { id: 'T-2', identifier: 'T-2', status: 'backlog' } as any,
},
});
renderHook(() => {
@@ -138,23 +150,28 @@ describe('TaskDetailSliceAction', () => {
expect(useTaskStore.getState().taskDetailMap['T-2']).toBeDefined();
});
- it('stores a raw-id lookup under both the raw id and the identifier', async () => {
+ it('stores a lookup only under its canonical id and indexes aliases', async () => {
vi.mocked(taskService.getDetail).mockResolvedValue({
- data: { identifier: 'T-7', instruction: 'x' },
+ data: { id: 'T-7', identifier: 'T-7', instruction: 'x' },
} as any);
- await useTaskStore.getState().fetchTaskDetail('task_raw');
+ vi.mocked(taskService.find).mockResolvedValue({
+ data: { id: 'T-7', identifier: 'T-7' },
+ success: true,
+ } as any);
+ await useTaskStore.getState().fetchTaskDetail('old-7');
const { taskDetailMap } = useTaskStore.getState();
- expect(taskDetailMap.task_raw).toMatchObject({ identifier: 'T-7' });
- expect(taskDetailMap['T-7']).toMatchObject({ identifier: 'T-7' });
+ expect(taskDetailMap['old-7']).toBeUndefined();
+ expect(useTaskStore.getState().taskRefIndex['old-7']).toBe('T-7');
+ expect(taskDetailMap['T-7']).toMatchObject({ id: 'T-7', identifier: 'T-7' });
});
it('restores the persisted row when a delete fails', async () => {
const scope = `task-delete-${crypto.randomUUID()}:personal`;
vi.spyOn(cacheScope, 'get').mockReturnValue(scope);
vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
- const detail = { identifier: 'T-9', name: 'Keep me' } as any;
+ const detail = { id: 'T-9', identifier: 'T-9', name: 'Keep me' } as any;
useTaskStore.getState().internal_dispatchTaskDetail({
id: 'T-9',
type: 'setTaskDetail',
@@ -184,7 +201,7 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.getState().internal_dispatchTaskDetail({
id: 'T-3',
type: 'setTaskDetail',
- value: { identifier: 'T-3', name: 'Before' } as any,
+ value: { id: 'T-3', identifier: 'T-3', name: 'Before' } as any,
});
vi.mocked(taskService.update).mockResolvedValue({} as any);
@@ -205,7 +222,7 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.getState().internal_dispatchTaskDetail({
id: 'T-1',
type: 'setTaskDetail',
- value: { identifier: 'T-1', name: 'Draft' } as any,
+ value: { id: 'T-1', identifier: 'T-1', name: 'Draft' } as any,
});
expect(useTaskStore.getState().taskDetailMap['T-1']).toMatchObject({ name: 'Draft' });
@@ -220,7 +237,7 @@ describe('TaskDetailSliceAction', () => {
});
it('should not update if same id', () => {
- useTaskStore.setState({ activeTaskId: 'T-1' });
+ useTaskStore.setState({ activeTaskId: 'T-1', activeTaskRef: 'T-1' });
const spy = vi.fn();
useTaskStore.subscribe(spy);
@@ -272,7 +289,7 @@ describe('TaskDetailSliceAction', () => {
describe('createTask', () => {
it('should call service and return identifier', async () => {
vi.mocked(taskService.create).mockResolvedValue({
- data: { identifier: 'T-1' },
+ data: { id: 'T-1', identifier: 'T-1' },
message: 'ok',
success: true,
} as any);
@@ -292,7 +309,7 @@ describe('TaskDetailSliceAction', () => {
it('should set isCreatingTask during creation', async () => {
vi.mocked(taskService.create).mockImplementation(async () => {
expect(useTaskStore.getState().isCreatingTask).toBe(true);
- return { data: { identifier: 'T-1' }, success: true } as any;
+ return { data: { id: 'T-1', identifier: 'T-1' }, success: true } as any;
});
await useTaskStore.getState().createTask({ instruction: 'Test' });
@@ -321,7 +338,13 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.setState({
activeTaskId: 'T-1',
taskDetailMap: {
- 'T-1': { activities: [], identifier: 'T-1', instruction: 'x', status: 'backlog' },
+ 'T-1': {
+ activities: [],
+ id: 'T-1',
+ identifier: 'T-1',
+ instruction: 'x',
+ status: 'backlog',
+ },
},
});
};
@@ -389,7 +412,13 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.setState({
activeTaskId: 'T-1',
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'Old', name: 'Old Name', status: 'backlog' },
+ 'T-1': {
+ id: 'T-1',
+ identifier: 'T-1',
+ instruction: 'Old',
+ name: 'Old Name',
+ status: 'backlog',
+ },
},
});
@@ -413,6 +442,7 @@ describe('TaskDetailSliceAction', () => {
'T-1': {
activities: [],
agentId: null,
+ id: 'T-1',
identifier: 'T-1',
instruction: 'x',
status: 'backlog',
@@ -458,6 +488,7 @@ describe('TaskDetailSliceAction', () => {
),
model: 'claude-code',
},
+ id: 'T-1',
identifier: 'T-1',
instruction: 'x',
status: 'backlog',
@@ -495,6 +526,7 @@ describe('TaskDetailSliceAction', () => {
workingDirectory: '/srv/app',
}),
},
+ id: 'T-1',
identifier: 'T-1',
instruction: 'x',
status: 'backlog',
@@ -522,6 +554,7 @@ describe('TaskDetailSliceAction', () => {
applyTaskReposSelection(undefined, ['lobehub/lobehub']),
),
},
+ id: 'T-1',
identifier: 'T-1',
instruction: 'x',
status: 'backlog',
@@ -541,7 +574,9 @@ describe('TaskDetailSliceAction', () => {
it('revalidates goal graphs when the assignee changes, so a goal page shows the new executor', async () => {
useTaskStore.setState({
- taskDetailMap: { 'T-1': { identifier: 'T-1', instruction: 'x', status: 'backlog' } },
+ taskDetailMap: {
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'x', status: 'backlog' },
+ },
});
vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
const { mutate } = await import('@/libs/swr');
@@ -563,7 +598,9 @@ describe('TaskDetailSliceAction', () => {
it('leaves goal graphs alone when the assignee does not change', async () => {
useTaskStore.setState({
- taskDetailMap: { 'T-1': { identifier: 'T-1', instruction: 'x', status: 'backlog' } },
+ taskDetailMap: {
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'x', status: 'backlog' },
+ },
});
vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
const { mutate } = await import('@/libs/swr');
@@ -583,6 +620,7 @@ describe('TaskDetailSliceAction', () => {
taskDetailMap: {
'T-1': {
editorData: { root: { children: [{ text: 'Old instruction' }] } },
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Old instruction',
status: 'backlog',
@@ -619,6 +657,7 @@ describe('TaskDetailSliceAction', () => {
taskDetailMap: {
'T-1': {
editorData,
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Old instruction',
status: 'backlog',
@@ -636,6 +675,7 @@ describe('TaskDetailSliceAction', () => {
vi.mocked(taskService.getDetail).mockResolvedValue({
data: {
editorData: { root: { children: [{ text: 'Old instruction' }] } },
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Old instruction',
status: 'backlog',
@@ -654,6 +694,7 @@ describe('TaskDetailSliceAction', () => {
taskDetailMap: {
'T-1': {
editorData: { root: { children: [{ text: 'Old instruction' }] } },
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Old instruction',
status: 'running',
@@ -663,6 +704,7 @@ describe('TaskDetailSliceAction', () => {
vi.mocked(taskService.getDetail).mockResolvedValue({
data: {
editorData: null,
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Tool instruction',
status: 'running',
@@ -689,7 +731,7 @@ describe('TaskDetailSliceAction', () => {
const { toast } = await import('@lobehub/ui');
useTaskStore.setState({
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'Test', status: 'backlog' },
},
});
@@ -714,6 +756,7 @@ describe('TaskDetailSliceAction', () => {
taskDetailMap: {
'T-1': {
editorData: { root: { children: [{ text: 'Persisted' }] } },
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Persisted',
status: 'backlog',
@@ -723,14 +766,15 @@ describe('TaskDetailSliceAction', () => {
vi.mocked(taskService.getDetail).mockResolvedValue({
data: {
editorData: { root: { children: [{ text: 'Persisted' }] } },
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Persisted',
status: 'backlog',
},
success: true,
} as any);
- vi.mocked(mutate).mockImplementation(async () => {
- await useTaskStore.getState().fetchTaskDetail('T-1');
+ vi.mocked(mutate).mockImplementation(async (key) => {
+ if (typeof key === 'function') await useTaskStore.getState().fetchTaskDetail('T-1');
});
vi.mocked(taskService.update).mockRejectedValueOnce(new Error('fail'));
@@ -764,7 +808,9 @@ describe('TaskDetailSliceAction', () => {
it('lets the caller replace the failure toast Retry with its whole action', async () => {
useTaskStore.setState({
activeTaskId: 'T-1',
- taskDetailMap: { 'T-1': { identifier: 'T-1', instruction: 'x', status: 'backlog' } },
+ taskDetailMap: {
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'x', status: 'backlog' },
+ },
});
vi.mocked(taskService.update).mockRejectedValueOnce(new Error('fail'));
const retry = vi.fn();
@@ -788,12 +834,15 @@ describe('TaskDetailSliceAction', () => {
activeTaskId: 'T-sub',
taskDetailMap: {
'T-parent': {
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent',
status: 'backlog',
- subtasks: [{ assignee: null, identifier: 'T-sub', name: 'Sub', status: 'backlog' }],
+ subtasks: [
+ { assignee: null, id: 'T-sub', identifier: 'T-sub', name: 'Sub', status: 'backlog' },
+ ],
},
- 'T-sub': { identifier: 'T-sub', instruction: 'Sub', status: 'backlog' },
+ 'T-sub': { id: 'T-sub', identifier: 'T-sub', instruction: 'Sub', status: 'backlog' },
},
});
@@ -812,7 +861,7 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.setState({
activeTaskId: 'T-1',
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'Test', status: 'backlog' },
},
});
@@ -830,12 +879,15 @@ describe('TaskDetailSliceAction', () => {
activeTaskId: 'T-sub',
taskDetailMap: {
'T-parent': {
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent',
status: 'backlog',
- subtasks: [{ assignee: null, identifier: 'T-sub', name: 'Sub', status: 'backlog' }],
+ subtasks: [
+ { assignee: null, id: 'T-sub', identifier: 'T-sub', name: 'Sub', status: 'backlog' },
+ ],
},
- 'T-sub': { identifier: 'T-sub', instruction: 'Sub', status: 'backlog' },
+ 'T-sub': { id: 'T-sub', identifier: 'T-sub', instruction: 'Sub', status: 'backlog' },
},
});
@@ -868,10 +920,13 @@ describe('TaskDetailSliceAction', () => {
activeTaskId: 'T-parent',
taskDetailMap: {
'T-parent': {
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent',
status: 'backlog',
- subtasks: [{ assignee: null, identifier: 'T-sub', name: 'Sub', status: 'backlog' }],
+ subtasks: [
+ { assignee: null, id: 'T-sub', identifier: 'T-sub', name: 'Sub', status: 'backlog' },
+ ],
},
},
});
@@ -893,8 +948,8 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.setState({
activeTaskId: 'T-1',
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'One', status: 'backlog' },
- 'T-2': { identifier: 'T-2', instruction: 'Two', status: 'backlog' },
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'One', status: 'backlog' },
+ 'T-2': { id: 'T-2', identifier: 'T-2', instruction: 'Two', status: 'backlog' },
},
});
@@ -919,12 +974,12 @@ describe('TaskDetailSliceAction', () => {
useTaskStore.setState({
activeTaskId: 'T-1',
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'Test', status: 'backlog' },
},
});
vi.mocked(taskService.delete).mockResolvedValue({
- data: { identifier: 'T-1', name: 'Test Task' },
+ data: { id: 'T-1', identifier: 'T-1', name: 'Test Task' },
success: true,
} as any);
@@ -940,13 +995,13 @@ describe('TaskDetailSliceAction', () => {
it('should set isDeletingTask during deletion', async () => {
useTaskStore.setState({
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'Test', status: 'backlog' },
},
});
vi.mocked(taskService.delete).mockImplementation(async () => {
expect(useTaskStore.getState().isDeletingTask).toBe(true);
- return { data: { identifier: 'T-1' }, success: true } as any;
+ return { data: { id: 'T-1', identifier: 'T-1' }, success: true } as any;
});
await useTaskStore.getState().deleteTask('T-1');
@@ -957,12 +1012,12 @@ describe('TaskDetailSliceAction', () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
useTaskStore.setState({
taskDetailMap: {
- 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },
+ 'T-1': { id: 'T-1', identifier: 'T-1', instruction: 'Test', status: 'backlog' },
},
});
vi.mocked(taskService.delete).mockResolvedValue({
- data: { identifier: 'T-1' },
+ data: { id: 'T-1', identifier: 'T-1' },
success: true,
} as any);
vi.mocked(workService.refreshAllConversations).mockRejectedValue(new Error('refresh failed'));
@@ -977,6 +1032,7 @@ describe('TaskDetailSliceAction', () => {
it('should rollback optimistic delete and propagate error on failure', async () => {
const snapshot = {
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Test',
name: 'Original',
@@ -1040,7 +1096,7 @@ describe('TaskDetailSliceAction', () => {
vi.mocked(taskService.unpinDocument).mockResolvedValue({ success: true } as any);
// Detail page is open at parent identifier; doc is owned by a child DB id.
- useTaskStore.setState({ activeTaskId: 'T-1' });
+ useTaskStore.setState({ activeTaskId: 'T-1', activeTaskRef: 'T-1' });
await useTaskStore.getState().unpinDocument('task_child', 'doc_1');
@@ -1053,7 +1109,7 @@ describe('TaskDetailSliceAction', () => {
const { mutate } = await import('@/libs/swr');
vi.mocked(taskService.unpinDocument).mockResolvedValue({ success: true } as any);
- useTaskStore.setState({ activeTaskId: 'T-1' });
+ useTaskStore.setState({ activeTaskId: 'T-1', activeTaskRef: 'T-1' });
await useTaskStore.getState().unpinDocument('T-1', 'doc_1');
@@ -1064,7 +1120,12 @@ describe('TaskDetailSliceAction', () => {
describe('internal_dispatchTaskDetail', () => {
it('should set task detail via reducer', () => {
- const detail = { identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;
+ const detail = {
+ id: 'T-1',
+ identifier: 'T-1',
+ instruction: 'Test',
+ status: 'backlog',
+ } as any;
useTaskStore.getState().internal_dispatchTaskDetail({
id: 'T-1',
@@ -1076,7 +1137,12 @@ describe('TaskDetailSliceAction', () => {
});
it('should not update state if reducer returns same reference', () => {
- const detail = { identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;
+ const detail = {
+ id: 'T-1',
+ identifier: 'T-1',
+ instruction: 'Test',
+ status: 'backlog',
+ } as any;
useTaskStore.setState({ taskDetailMap: { 'T-1': detail } });
const spy = vi.fn();
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index c6aecccc71e..8de3084f375 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -8,7 +8,9 @@ import { toast } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
-import { createReplicaSlice, recordLens, revalidateReplica } from '@/libs/replica';
+import { cacheScope, createReplicaSlice, recordLens, revalidateReplica } from '@/libs/replica';
+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
+import { useClientDataSWR } from '@/libs/swr';
import { taskService } from '@/services/task';
import { workService } from '@/services/work';
import { goalGraphResource } from '@/store/goal/projection';
@@ -18,6 +20,7 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { runMutation } from '@/store/utils/runMutation';
import { saveToast } from '@/store/utils/saveToast';
import type { SaveStatus } from '@/types/saveState';
+import { isTrpcErrorCode } from '@/utils/trpcError';
import type { TaskStore } from '../../store';
import { useTaskStore } from '../../store';
@@ -114,6 +117,9 @@ const hasInstructionSnapshotChanged = (
type Setter = StoreSetter<TaskStore>;
+const cachedTaskId = (ref: string | undefined, index: Record<string, string>) =>
+ ref?.trim().startsWith('task_') ? ref.trim() : ref ? index[ref] : undefined;
+
export const createTaskDetailSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>
new TaskDetailSliceActionImpl(set, get, _api);
@@ -121,6 +127,8 @@ export class TaskDetailSliceActionImpl {
readonly #get: () => TaskStore;
readonly #set: Setter;
readonly #detail;
+ readonly #reconciliations = new WeakMap<TaskDetailData, Promise<void>>();
+ readonly #previous = new WeakMap<TaskDetailData, TaskDetailData | undefined>();
constructor(set: Setter, get: () => TaskStore, _api?: unknown) {
void _api;
@@ -128,16 +136,46 @@ export class TaskDetailSliceActionImpl {
this.#get = get;
this.#detail = createReplicaSlice(taskDetailResource, {
actionPrefix: 'taskDetail',
- // Writes the entry (and its identifier alias) through
- // `internal_dispatchTaskDetail`, which also tracks instruction revisions;
- // the sync then confirms and persists the same value.
- fetcher: (id) => this.fetchTaskDetail(id),
+ // Persist canonical entries through the replica; applied responses also
+ // refresh aliases, instruction revisions and completed-run reconciliation.
+ fetcher: (id) => this.#loadTaskDetail(id),
+ effects: {
+ onApplied: (detail, id) => {
+ this.#rememberTask({ id: detail.id!, identifier: detail.identifier }, id);
+ if (hasInstructionSnapshotChanged(this.#previous.get(detail), detail)) {
+ const state = this.#get();
+ this.#set(
+ {
+ taskInstructionRevisionMap: {
+ ...state.taskInstructionRevisionMap,
+ [id]: (state.taskInstructionRevisionMap[id] ?? 0) + 1,
+ },
+ },
+ false,
+ 'taskDetail/instructionChanged',
+ );
+ }
+ const reconciliation = this.#reconcileRuns(detail);
+ this.#reconciliations.set(detail, reconciliation);
+ void reconciliation.catch((error) => console.error('[taskDetail:reconcile]', error));
+ },
+ onError: (error, id) => {
+ if ((error as { code?: string })?.code === 'TASK_NOT_FOUND') {
+ this.#detail.remove(id);
+ this.#forgetTask(id);
+ }
+ },
+ },
get,
merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
set,
stateKey: 'taskDetailReplica',
view: recordLens<TaskStore, TaskDetailData>('taskDetailMap'),
});
+ subscribeCacheScope((scope) => {
+ this.#set({ taskRefIndex: {}, activeTaskId: undefined }, false, 'taskDetail/scopeChanged');
+ this.#detail.ensureScope(scope);
+ });
}
// ── Public Actions ──
@@ -235,48 +273,25 @@ export class TaskDetailSliceActionImpl {
await this.internal_refreshTaskDetail(taskId);
};
- fetchTaskDetail = async (taskId?: string): Promise<TaskDetailData> => {
- const resolvedId = taskId ?? this.#get().activeTaskId;
-
- if (!resolvedId) {
- throw new Error('No task identifier provided and no current task context.');
- }
-
- const result = await taskService.getDetail(resolvedId);
- const detail = result.data;
-
- if (!detail) {
- // Mark the *resolved* not-found so the read side can tell it apart from a
- // network / 500 rejection (which propagates from `taskService.getDetail`
- // above with an HTTP status). Without this tag both would render the same
- // terminal 404, telling the user a merely-errored task was deleted.
- const notFound = new Error(`Task not found: ${resolvedId}`) as Error & { code?: string };
- notFound.code = 'TASK_NOT_FOUND';
- throw notFound;
- }
-
- this.internal_dispatchTaskDetail(
- {
- id: detail.identifier,
- type: 'setTaskDetail',
- value: detail,
- },
- { instructionSource: 'external' },
- );
-
- // When looked up by raw DB id (e.g. `task_xxx`), also store under that key
- // so `activeTaskId` → `taskDetailMap[activeTaskId]` resolves correctly.
- if (resolvedId !== detail.identifier) {
- this.internal_dispatchTaskDetail(
- {
- id: resolvedId,
- type: 'setTaskDetail',
- value: detail,
- },
- { instructionSource: 'external' },
- );
+ #loadTaskDetail = async (taskId: string): Promise<TaskDetailData> => {
+ const result = await taskService.getDetail(taskId).catch((error) => {
+ if (isTrpcErrorCode(error, 'NOT_FOUND')) {
+ const missing = new Error('Task not found') as Error & { code: string };
+ missing.code = 'TASK_NOT_FOUND';
+ throw missing;
+ }
+ throw error;
+ });
+ if (!result.data?.id) {
+ const error = new Error('Task not found') as Error & { code: string };
+ error.code = 'TASK_NOT_FOUND';
+ throw error;
}
+ this.#previous.set(result.data, this.#get().taskDetailMap[taskId]);
+ return result.data;
+ };
+ #reconcileRuns = async (detail: TaskDetailData) => {
// Reconcile at the server-read boundary, even when the live chat panel has
// unmounted. A missing running marker alone is not proof of completion.
const terminalActivities = detail.activities?.filter(
@@ -302,8 +317,26 @@ export class TaskDetailSliceActionImpl {
});
}
}
+ };
- return detail;
+ internal_resolveTaskId = async (ref: string): Promise<string> => {
+ const known = cachedTaskId(ref, this.#get().taskRefIndex);
+ if (known) return known;
+ const scope = cacheScope.get();
+ const { data } = await taskService.find(ref);
+ if (cacheScope.get() !== scope) throw new Error('Task scope changed while resolving reference');
+ this.#rememberTask(data, ref);
+ return data.id;
+ };
+
+ fetchTaskDetail = async (ref?: string): Promise<TaskDetailData> => {
+ ref ??= this.#get().activeTaskId ?? this.#get().activeTaskRef;
+ if (!ref) throw new Error('No task identifier provided and no current task context.');
+ const id = await this.internal_resolveTaskId(ref);
+ const { data, applied } = await this.#detail.fetch(id);
+ if (!data || !applied) throw new Error('Task detail request was superseded');
+ await this.#reconciliations.get(data);
+ return data;
};
createTask = async (params: {
@@ -337,13 +370,15 @@ export class TaskDetailSliceActionImpl {
}
};
- deleteTask = async (identifier: string): Promise<DeletedTask | null> => {
+ deleteTask = async (ref: string): Promise<DeletedTask | null> => {
+ const identifier = this.#get().taskRefIndex[ref] ?? ref;
const snapshot = this.#get().taskDetailMap[identifier];
this.#set({ isDeletingTask: true }, false, 'deleteTask/start');
try {
this.internal_dispatchTaskDetail({ id: identifier, type: 'deleteTaskDetail' });
const result = await taskService.delete(identifier);
+ this.#forgetTask(identifier);
if (this.#get().activeTaskId === identifier) {
this.#set({ activeTaskId: undefined }, false, 'deleteTask/clearActive');
@@ -385,10 +420,11 @@ export class TaskDetailSliceActionImpl {
};
setActiveTaskId = (taskId?: string): void => {
- if (this.#get().activeTaskId === taskId) return;
+ if (this.#get().activeTaskRef === taskId) return;
this.#set(
{
- activeTaskId: taskId,
+ activeTaskRef: taskId,
+ activeTaskId: cachedTaskId(taskId, this.#get().taskRefIndex),
activeTopicDrawerAgentId: undefined,
activeTopicDrawerFocusRequest: undefined,
activeTopicDrawerTitle: undefined,
@@ -485,6 +521,7 @@ export class TaskDetailSliceActionImpl {
data: TaskUpdatePayload,
options?: TaskUpdateOptions,
): Promise<void> => {
+ id = this.#get().taskRefIndex[id] ?? id;
const { assigneeAgentId, assigneeUserId, ...rest } = data;
const optimisticRest = { ...rest };
delete optimisticRest.parentTaskId;
@@ -575,6 +612,14 @@ export class TaskDetailSliceActionImpl {
);
};
+ const collections = this.#get().internal_beginCollectionTaskOptimistic(id, (task) => ({
+ ...task,
+ ...(data.name !== undefined ? { name: data.name } : {}),
+ ...(data.priority !== undefined ? { priority: data.priority } : {}),
+ ...(data.assigneeAgentId !== undefined ? { assigneeAgentId: data.assigneeAgentId } : {}),
+ ...(data.assigneeUserId !== undefined ? { assigneeUserId: data.assigneeUserId } : {}),
+ }));
+
this.internal_dispatchTaskDetail(
{ id, type: 'updateTaskDetail', value: optimistic },
options?.source === 'editor' ? undefined : { instructionSource: 'external' },
@@ -586,6 +631,7 @@ export class TaskDetailSliceActionImpl {
// Rollback is a server-truth refetch (not a local snapshot), so the
// optimistic dispatch above is reconciled from the source of record.
onError: async (error) => {
+ collections.rollback();
await refreshPatchedTargets();
/**
* The rollback refetch has already replaced the editor's failed local
@@ -604,6 +650,8 @@ export class TaskDetailSliceActionImpl {
setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),
});
+ collections.commit();
+
// Saved: the edited detail is now the server's value, so a reload must
// paint it rather than the pre-edit snapshot.
this.internal_persistTaskDetail(id);
@@ -627,27 +675,69 @@ export class TaskDetailSliceActionImpl {
}
};
- useFetchTaskDetail = (taskId?: string) => {
- // Drive polling from a reactive boolean. SWR's function-form refreshInterval
- // is a trap here: it's only re-evaluated after a timer fires, so if the first
- // call (with undefined cache data) returns 0, no timer is ever scheduled and
- // polling never starts — even once real data arrives.
- const shouldPoll = useTaskStore((s) => {
- const detail = taskId ? s.taskDetailMap[taskId] : undefined;
- return hasInFlightActivity(detail);
- });
-
+ useFetchTaskDetail = (taskRef?: string) => {
+ const scope = cacheScope.use();
+ const knownId = useTaskStore((state) => cachedTaskId(taskRef, state.taskRefIndex));
+ const resolution = useClientDataSWR(
+ taskRef && !knownId ? ['taskRef', scope, taskRef] : null,
+ async () => {
+ try {
+ return await this.internal_resolveTaskId(taskRef!);
+ } catch (error) {
+ if ((error as { data?: { code?: string } })?.data?.code === 'NOT_FOUND') {
+ const missing = new Error('Task not found') as Error & { code: string };
+ missing.code = 'TASK_NOT_FOUND';
+ throw missing;
+ }
+ throw error;
+ }
+ },
+ );
+ const taskId = knownId;
+ const shouldPoll = useTaskStore((state) =>
+ hasInFlightActivity(taskId ? state.taskDetailMap[taskId] : undefined),
+ );
const sync = this.#detail.useSync(taskId, {
- // A resolved not-found is definitive (the task was deleted elsewhere):
- // drop the cached copy so the page can settle on its 404. Transient
- // failures keep the cached detail on screen.
onError: (error) => {
if (taskId && (error as { code?: string } | undefined)?.code === 'TASK_NOT_FOUND')
this.internal_dispatchTaskDetail({ id: taskId, type: 'deleteTaskDetail' });
},
refreshInterval: shouldPoll ? TASK_DETAIL_POLL_INTERVAL : 0,
});
- return { ...sync, mutate: sync.revalidate };
+ return {
+ ...sync,
+ error: resolution.error ?? sync.error,
+ isValidating: resolution.isLoading || sync.isValidating,
+ mutate: taskId ? sync.revalidate : resolution.mutate,
+ };
+ };
+
+ #forgetTask = (id: string) => {
+ const taskRefIndex = Object.fromEntries(
+ Object.entries(this.#get().taskRefIndex).filter(([, taskId]) => taskId !== id),
+ );
+ this.#set({ taskRefIndex }, false, 'taskDetail/forgetRef');
+ };
+
+ #rememberTask = (task: { id: string; identifier: string }, ref: string) => {
+ const state = this.#get();
+ this.#set(
+ {
+ taskRefIndex: {
+ ...state.taskRefIndex,
+ [ref]: task.id,
+ [task.id]: task.id,
+ [task.identifier]: task.id,
+ },
+ ...(state.activeTaskRef === ref ||
+ state.activeTaskRef === task.id ||
+ state.activeTaskRef === task.identifier
+ ? { activeTaskId: task.id }
+ : {}),
+ },
+ false,
+ 'taskDetail/resolveRef',
+ );
};
// ── Internal Actions ──
@@ -672,6 +762,18 @@ export class TaskDetailSliceActionImpl {
payload: TaskDetailDispatch,
options?: { instructionSource?: 'external' },
): void => {
+ const ref = payload.id;
+ if (payload.type === 'setTaskDetail') {
+ if (!payload.value.id) return;
+ this.#rememberTask({ ...payload.value, id: payload.value.id }, ref);
+ }
+ payload = {
+ ...payload,
+ id:
+ payload.type === 'setTaskDetail'
+ ? payload.value.id!
+ : (this.#get().taskRefIndex[ref] ?? ref),
+ };
const state = this.#get();
const currentMap = state.taskDetailMap;
const nextMap = taskDetailReducer(currentMap, payload);
@@ -721,7 +823,8 @@ export class TaskDetailSliceActionImpl {
this.#detail.update(id, (detail) => detail && { ...detail });
};
- internal_refreshTaskDetail = async (id: string): Promise<void> => {
+ internal_refreshTaskDetail = async (ref: string): Promise<void> => {
+ const id = await this.internal_resolveTaskId(ref);
await this.#detail.revalidate(id);
};
}
diff --git a/src/store/task/slices/detail/initialState.ts b/src/store/task/slices/detail/initialState.ts
index 99f9458e56d..a570a2b3d7d 100644
--- a/src/store/task/slices/detail/initialState.ts
+++ b/src/store/task/slices/detail/initialState.ts
@@ -5,6 +5,7 @@ import { type SaveStatus } from '@/types/saveState';
export interface TaskDetailSliceState {
activeTaskId?: string;
+ activeTaskRef?: string;
/**
* Topic-scoped fallbacks for a drawer opened outside a task detail — the home
* inbox opens runs that may have no parent task at all, so there is no
@@ -28,6 +29,7 @@ export interface TaskDetailSliceState {
* explicit reload signal instead of comparing against live, unsaved content.
*/
taskInstructionRevisionMap: Record<string, number>;
+ taskRefIndex: Record<string, string>;
// Save status is scoped per task id (mirrors `taskDetailMap`). A store-wide
// field would leak one task's `failed` state across navigation, since
// `setActiveTaskId` only swaps `activeTaskId` and never clears the status.
@@ -38,6 +40,7 @@ export const initialTaskDetailSliceState: TaskDetailSliceState = {
isCreatingTask: false,
isDeletingTask: false,
taskDetailMap: {},
+ taskRefIndex: {},
taskDetailReplica: createReplicaState(),
taskInstructionRevisionMap: {},
taskSaveStatusMap: {},
diff --git a/src/store/task/slices/detail/projection.ts b/src/store/task/slices/detail/projection.ts
index 45c0784048c..b74cdae9f94 100644
--- a/src/store/task/slices/detail/projection.ts
+++ b/src/store/task/slices/detail/projection.ts
@@ -2,14 +2,10 @@ import type { TaskDetailData } from '@lobechat/types';
import { defineReplica } from '@/libs/replica';
-/**
- * One task detail per entry, keyed by the id it was opened with — the
- * identifier (`T-12`) or a raw row id (`task_xxx`); a raw-id fetch also writes
- * the identifier entry.
- */
+/** Canonical task ids only. Display aliases live in the in-memory ref index. */
export const taskDetailResource = defineReplica<string, TaskDetailData>({
key: (id) => id,
name: 'taskDetail',
storage: 'indexedDB',
- version: 1,
+ version: 2,
});
diff --git a/src/store/task/slices/detail/reducer.test.ts b/src/store/task/slices/detail/reducer.test.ts
index a77b11e742f..d2dda49e7ac 100644
--- a/src/store/task/slices/detail/reducer.test.ts
+++ b/src/store/task/slices/detail/reducer.test.ts
@@ -5,6 +5,7 @@ import type { TaskDetailDispatch } from './reducer';
import { findSubtaskParentId, taskDetailReducer } from './reducer';
const mockDetail: TaskDetailData = {
+ id: 'T-1',
identifier: 'T-1',
instruction: 'Test instruction',
name: 'Test Task',
@@ -13,6 +14,7 @@ const mockDetail: TaskDetailData = {
};
const mockDetail2: TaskDetailData = {
+ id: 'T-2',
identifier: 'T-2',
instruction: 'Another instruction',
name: 'Another Task',
@@ -84,6 +86,7 @@ describe('taskDetailReducer', () => {
describe('nested subtasks', () => {
const buildParentWithSubtasks = (): TaskDetailData => ({
+ id: 'T-3',
identifier: 'T-3',
instruction: 'Parent',
name: 'Parent',
@@ -96,6 +99,7 @@ describe('taskDetailReducer', () => {
id: 'agent-old',
title: 'Old Agent',
},
+ id: 'T-3.1',
identifier: 'T-3.1',
name: 'Sub 1',
priority: 2,
@@ -105,11 +109,13 @@ describe('taskDetailReducer', () => {
children: [
{
assignee: null,
+ id: 'T-3.2.1',
identifier: 'T-3.2.1',
name: 'Nested',
status: 'backlog',
},
],
+ id: 'T-3.2',
identifier: 'T-3.2',
name: 'Sub 2',
status: 'backlog',
@@ -214,16 +220,24 @@ describe('taskDetailReducer', () => {
describe('findSubtaskParentId', () => {
const buildParent = (): TaskDetailData => ({
+ id: 'T-parent',
identifier: 'T-parent',
instruction: 'Parent',
name: 'Parent',
status: 'backlog',
subtasks: [
- { assignee: null, identifier: 'T-sub-1', name: 'Sub 1', status: 'backlog' },
+ { assignee: null, id: 'T-sub-1', identifier: 'T-sub-1', name: 'Sub 1', status: 'backlog' },
{
children: [
- { assignee: null, identifier: 'T-sub-2-1', name: 'Nested', status: 'backlog' },
+ {
+ assignee: null,
+ id: 'T-sub-2-1',
+ identifier: 'T-sub-2-1',
+ name: 'Nested',
+ status: 'backlog',
+ },
],
+ id: 'T-sub-2',
identifier: 'T-sub-2',
name: 'Sub 2',
status: 'backlog',
@@ -251,6 +265,7 @@ describe('taskDetailReducer', () => {
'T-parent': buildParent(),
// The subtask is also cached under its own key (e.g. user opened it as a detail page).
'T-sub-1': {
+ id: 'T-sub-1',
identifier: 'T-sub-1',
instruction: 'Sub',
name: 'Sub 1',
diff --git a/src/store/task/slices/detail/reducer.ts b/src/store/task/slices/detail/reducer.ts
index 876f0e7f589..d758178b3b3 100644
--- a/src/store/task/slices/detail/reducer.ts
+++ b/src/store/task/slices/detail/reducer.ts
@@ -8,7 +8,7 @@ export type TaskDetailDispatch =
const containsSubtaskInTree = (subtasks: TaskDetailSubtask[], id: string): boolean => {
for (const subtask of subtasks) {
- if (subtask.identifier === id) return true;
+ if (subtask.id === id) return true;
if (subtask.children && containsSubtaskInTree(subtask.children, id)) return true;
}
return false;
@@ -36,7 +36,8 @@ const patchSubtaskInTree = (
value: Partial<TaskDetailData>,
): boolean => {
for (const subtask of subtasks) {
- if (subtask.identifier === id) {
+ if (subtask.id === id) {
+ if (value.status !== undefined) subtask.status = value.status;
if (value.name !== undefined) subtask.name = value.name;
if (value.priority !== undefined) subtask.priority = value.priority;
if (value.userId !== undefined) subtask.assigneeUserId = value.userId;
@@ -68,7 +69,7 @@ export const taskDetailReducer = (
switch (payload.type) {
case 'setTaskDetail': {
return produce(state, (draft) => {
- draft[payload.id] = payload.value;
+ if (payload.value.id) draft[payload.value.id] = payload.value;
});
}
diff --git a/src/store/task/slices/detail/runReconciliation.test.ts b/src/store/task/slices/detail/runReconciliation.test.ts
index f00286f7681..0c0f61dc574 100644
--- a/src/store/task/slices/detail/runReconciliation.test.ts
+++ b/src/store/task/slices/detail/runReconciliation.test.ts
@@ -31,6 +31,7 @@ const fetchDetail = async (activity: Partial<TaskDetailActivity> = {}) => {
...activity,
},
],
+ id: 'task_3',
identifier: 'T-3',
status: 'scheduled',
} as TaskDetailData,
@@ -50,7 +51,10 @@ describe('task run terminal reconciliation', () => {
topicDataMap: {},
toolCallingStreamIds: {},
});
- useTaskStore.setState({ taskDetailMap: {} });
+ useTaskStore.setState({
+ taskDetailMap: {},
+ taskRefIndex: { 'T-3': 'task_3', 'task_3': 'task_3' },
+ });
const server = createServerConfigStore();
server.setState({
serverConfig: {
diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.ts
index 2e069385a7a..b17c46e4559 100644
--- a/src/store/task/slices/lifecycle/action.test.ts
+++ b/src/store/task/slices/lifecycle/action.test.ts
@@ -28,12 +28,15 @@ vi.mock('@/libs/swr', () => ({
useClientDataSWR: vi.fn(),
}));
-const mockDetail = { identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;
+const mockDetail = { id: 'T-1', identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;
beforeEach(() => {
vi.clearAllMocks();
useTaskStore.setState({
activeTaskId: 'T-1',
+ taskRefIndex: Object.fromEntries(
+ ['T-1', 'T-2', 'T-3', 'T-parent', 'T-child'].map((id) => [id, id]),
+ ),
taskDetailMap: { 'T-1': { ...mockDetail } },
taskGroupListMap: {},
taskGroupListReplica: createReplicaState(),
@@ -169,10 +172,14 @@ describe('TaskLifecycleSliceAction', () => {
it('should immediately synchronize list and kanban collections', async () => {
seedCollections(
[
- { key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },
+ {
+ key: 'backlog',
+ tasks: [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
+ total: 1,
+ },
{ key: 'done', tasks: [], total: 0 },
],
- [{ identifier: 'T-1', status: 'backlog' }],
+ [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
);
vi.mocked(taskService.updateStatus).mockImplementation(async () => {
const state = useTaskStore.getState();
@@ -185,7 +192,7 @@ describe('TaskLifecycleSliceAction', () => {
total: 0,
});
expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({
- tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],
+ tasks: [expect.objectContaining({ id: 'T-1', identifier: 'T-1', status: 'completed' })],
total: 1,
});
@@ -201,17 +208,19 @@ describe('TaskLifecycleSliceAction', () => {
{
assigneeAgentId: 'agent-1',
key: 'assignee:agent-1',
- tasks: [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }],
+ tasks: [
+ { assigneeAgentId: 'agent-1', id: 'T-1', identifier: 'T-1', status: 'backlog' },
+ ],
total: 1,
},
],
- [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }],
+ [{ assigneeAgentId: 'agent-1', id: 'T-1', identifier: 'T-1', status: 'backlog' }],
'assignee',
);
vi.mocked(taskService.updateStatus).mockImplementation(async () => {
expect(boardGroups()[0]).toMatchObject({
key: 'assignee:agent-1',
- tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],
+ tasks: [expect.objectContaining({ id: 'T-1', identifier: 'T-1', status: 'completed' })],
total: 1,
});
return { success: true } as any;
@@ -223,10 +232,14 @@ describe('TaskLifecycleSliceAction', () => {
it('should roll list and kanban collections back when the status update fails', async () => {
seedCollections(
[
- { key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },
+ {
+ key: 'backlog',
+ tasks: [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
+ total: 1,
+ },
{ key: 'done', tasks: [], total: 0 },
],
- [{ identifier: 'T-1', status: 'backlog' }],
+ [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
);
vi.mocked(taskService.updateStatus).mockRejectedValue(new Error('fail'));
@@ -237,7 +250,7 @@ describe('TaskLifecycleSliceAction', () => {
const state = useTaskStore.getState();
expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe('backlog');
expect(boardGroups(state).find((group) => group.key === 'backlog')).toMatchObject({
- tasks: [expect.objectContaining({ identifier: 'T-1', status: 'backlog' })],
+ tasks: [expect.objectContaining({ id: 'T-1', identifier: 'T-1', status: 'backlog' })],
total: 1,
});
expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({
@@ -252,15 +265,15 @@ describe('TaskLifecycleSliceAction', () => {
{
key: 'backlog',
tasks: [
- { identifier: 'T-4', status: 'backlog' },
- { identifier: 'T-1', status: 'backlog' },
- { identifier: 'T-2', status: 'backlog' },
+ { id: 'T-4', identifier: 'T-4', status: 'backlog' },
+ { id: 'T-1', identifier: 'T-1', status: 'backlog' },
+ { id: 'T-2', identifier: 'T-2', status: 'backlog' },
],
total: 3,
},
{ key: 'done', tasks: [], total: 0 },
],
- [{ identifier: 'T-1', status: 'backlog' }],
+ [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
);
vi.mocked(taskService.updateStatus).mockRejectedValue(new Error('fail'));
@@ -279,10 +292,14 @@ describe('TaskLifecycleSliceAction', () => {
const { mutate } = await import('@/libs/swr');
seedCollections(
[
- { key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },
+ {
+ key: 'backlog',
+ tasks: [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
+ total: 1,
+ },
{ key: 'done', tasks: [], total: 0 },
],
- [{ identifier: 'T-1', status: 'backlog' }],
+ [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
);
vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);
vi.mocked(mutate)
@@ -297,7 +314,7 @@ describe('TaskLifecycleSliceAction', () => {
const state = useTaskStore.getState();
expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe('completed');
expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({
- tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],
+ tasks: [expect.objectContaining({ id: 'T-1', identifier: 'T-1', status: 'completed' })],
total: 1,
});
});
@@ -308,8 +325,8 @@ describe('TaskLifecycleSliceAction', () => {
taskListMap: {
recent: {
items: [
- { identifier: 'T-1', status: 'running' },
- { identifier: 'T-2', status: 'running' },
+ { id: 'T-1', identifier: 'T-1', status: 'running' },
+ { id: 'T-2', identifier: 'T-2', status: 'running' },
] as any,
statuses: ['running', 'paused'],
total: 2,
@@ -322,7 +339,7 @@ describe('TaskLifecycleSliceAction', () => {
await useTaskStore.getState().updateTaskStatus('T-1', 'completed');
expect(useTaskStore.getState().taskListMap.recent).toMatchObject({
- items: [{ identifier: 'T-2' }],
+ items: [{ id: 'T-2', identifier: 'T-2' }],
total: 1,
});
vi.mocked(mutate).mockReset();
@@ -336,7 +353,11 @@ describe('TaskLifecycleSliceAction', () => {
excludeStatuses: ['canceled', 'completed'],
groupBy: 'status',
groups: [
- { key: 'running', tasks: [{ identifier: 'T-1', status: 'running' }], total: 1 },
+ {
+ key: 'running',
+ tasks: [{ id: 'T-1', identifier: 'T-1', status: 'running' }],
+ total: 1,
+ },
// The server still returns the hidden status's empty column.
{ key: 'done', tasks: [], total: 0 },
] as any,
@@ -369,13 +390,17 @@ describe('TaskLifecycleSliceAction', () => {
);
};
await seed(taskListResource, listKey, {
- items: [{ identifier: 'T-1', status: 'backlog' }],
+ items: [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
total: 1,
});
await seed(taskGroupListResource, boardKey, {
groupBy: 'status',
groups: [
- { key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },
+ {
+ key: 'backlog',
+ tasks: [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
+ total: 1,
+ },
{ key: 'done', tasks: [], total: 0 },
],
});
@@ -390,7 +415,7 @@ describe('TaskLifecycleSliceAction', () => {
const board = await taskGroupListResource.storage!.get({ queryKey: boardKey, scope });
expect(board?.data.groups).toMatchObject([
{ key: 'backlog', tasks: [], total: 0 },
- { key: 'done', tasks: [{ identifier: 'T-1', status: 'completed' }], total: 1 },
+ { key: 'done', tasks: [{ id: 'T-1', identifier: 'T-1', status: 'completed' }], total: 1 },
]);
});
vi.restoreAllMocks();
@@ -400,11 +425,15 @@ describe('TaskLifecycleSliceAction', () => {
let rejectFirstRequest: (reason: Error) => void = () => {};
seedCollections(
[
- { key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },
+ {
+ key: 'backlog',
+ tasks: [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
+ total: 1,
+ },
{ key: 'done', tasks: [], total: 0 },
{ key: 'canceled', tasks: [], total: 0 },
],
- [{ identifier: 'T-1', status: 'backlog' }],
+ [{ id: 'T-1', identifier: 'T-1', status: 'backlog' }],
);
vi.mocked(taskService.updateStatus)
.mockImplementationOnce(
@@ -425,7 +454,7 @@ describe('TaskLifecycleSliceAction', () => {
const state = useTaskStore.getState();
expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe('canceled');
expect(boardGroups(state).find((group) => group.key === 'canceled')).toMatchObject({
- tasks: [expect.objectContaining({ identifier: 'T-1', status: 'canceled' })],
+ tasks: [expect.objectContaining({ id: 'T-1', identifier: 'T-1', status: 'canceled' })],
total: 1,
});
expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({
diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.ts
index 804d4b1c779..e22accacff7 100644
--- a/src/store/task/slices/lifecycle/action.ts
+++ b/src/store/task/slices/lifecycle/action.ts
@@ -120,7 +120,8 @@ export class TaskLifecycleSliceActionImpl {
options?: { actorAgentId?: string; error?: string },
): Promise<string> => {
const { actorAgentId, error } = options ?? {};
- const resolvedId = id ?? this.#get().activeTaskId;
+ const ref = id ?? this.#get().activeTaskId;
+ const resolvedId = ref ? (this.#get().taskRefIndex[ref] ?? ref) : undefined;
if (!resolvedId) {
throw new Error('No task identifier provided and no current task context.');
diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.ts
index bfe60b6d808..b3a5df10c08 100644
--- a/src/store/task/slices/list/action.test.ts
+++ b/src/store/task/slices/list/action.test.ts
@@ -152,7 +152,9 @@ describe('TaskListSliceAction', () => {
taskGroupListMap: {
[result.current.queryKey!]: {
groupBy: 'status',
- groups: [{ key: 'backlog', tasks: [{ identifier: 'T-1' }], total: 1 }] as any,
+ groups: [
+ { key: 'backlog', tasks: [{ id: 'T-1', identifier: 'T-1' }], total: 1 },
+ ] as any,
},
},
});
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 1a037745d6b..4accaf4f34f 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -210,15 +210,15 @@ export class TaskListSliceActionImpl {
});
/** The task (by identifier) as any loaded list or board holds it. */
- internal_findCollectionTask = (identifier: string): CollectionTask | undefined => {
+ internal_findCollectionTask = (taskId: string): CollectionTask | undefined => {
const { taskGroupListMap, taskListMap } = this.#get();
for (const value of Object.values(taskListMap)) {
- const task = value.items.find((item) => item.identifier === identifier);
+ const task = value.items.find((item) => item.id === taskId);
if (task) return task;
}
for (const value of Object.values(taskGroupListMap)) {
for (const group of value.groups) {
- const task = group.tasks.find((item) => item.identifier === identifier);
+ const task = group.tasks.find((item) => item.id === taskId);
if (task) return task;
}
}
@@ -233,18 +233,18 @@ export class TaskListSliceActionImpl {
* every loaded collection exactly, card order included.
*/
internal_beginCollectionTaskOptimistic = (
- identifier: string,
+ taskId: string,
fn: <T extends CollectionTask>(task: T) => T,
) => {
const tokens = [
- ...this.#taskList.beginEntityOptimistic<CollectionTask>(identifier, fn),
- ...this.#taskGroupList.beginEntityOptimistic<CollectionTask>(identifier, fn),
+ ...this.#taskList.beginEntityOptimistic<CollectionTask>(taskId, fn),
+ ...this.#taskGroupList.beginEntityOptimistic<CollectionTask>(taskId, fn),
];
return {
commit: () => {
tokens.forEach((token) => token.commit());
- void this.#taskList.patchStoredEntity<CollectionTask>(identifier, fn);
- void this.#taskGroupList.patchStoredEntity<CollectionTask>(identifier, fn);
+ void this.#taskList.patchStoredEntity<CollectionTask>(taskId, fn);
+ void this.#taskGroupList.patchStoredEntity<CollectionTask>(taskId, fn);
},
rollback: () => tokens.forEach((token) => token.rollback()),
};
diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.ts
index f6749de1eb2..8a7017f9c1c 100644
--- a/src/store/task/slices/list/projection.ts
+++ b/src/store/task/slices/list/projection.ts
@@ -111,15 +111,15 @@ export const taskGroupKeyByStatus: Record<TaskStatus, string> = {
scheduled: 'running',
};
-/** Tasks are addressed by `identifier` (e.g. `T-12`) across the task store. */
+/** Tasks are addressed by stable database id across the task store. */
export const taskListEntity: ReplicaEntityAdapter<TaskListValue, TaskListItem> = {
- has: (data, id) => data.items.some((task) => task.identifier === id),
+ has: (data, id) => data.items.some((task) => task.id === id),
map: (data, id, fn) => {
let removed = 0;
let changed = false;
const items: TaskListItem[] = [];
for (const task of data.items) {
- if (task.identifier !== id) {
+ if (task.id !== id) {
items.push(task);
continue;
}
@@ -140,12 +140,9 @@ export const taskListEntity: ReplicaEntityAdapter<TaskListValue, TaskListItem> =
* the card to its new column (appended), keeping each column's `total` right.
*/
export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskGroupTask> = {
- has: (data, id) =>
- data.groups.some((group) => group.tasks.some((task) => task.identifier === id)),
+ has: (data, id) => data.groups.some((group) => group.tasks.some((task) => task.id === id)),
map: (data, id, fn) => {
- const current = data.groups
- .flatMap((group) => group.tasks)
- .find((task) => task.identifier === id);
+ const current = data.groups.flatMap((group) => group.tasks).find((task) => task.id === id);
if (!current) return data;
let next = fn(current);
if (next === current) return data;
@@ -157,11 +154,11 @@ export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskG
const moves = data.groupBy === 'status' && next !== undefined && status !== current.status;
const targetKey = moves && status ? taskGroupKeyByStatus[status] : undefined;
const groups = data.groups.map((group) => {
- const contains = group.tasks.some((task) => task.identifier === id);
+ const contains = group.tasks.some((task) => task.id === id);
if (moves) {
const isTarget = group.key === targetKey;
if (!contains && !isTarget) return group;
- const rest = group.tasks.filter((task) => task.identifier !== id);
+ const rest = group.tasks.filter((task) => task.id !== id);
return {
...group,
tasks: isTarget ? [...rest, next!] : rest,
@@ -172,7 +169,7 @@ export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskG
return {
...group,
tasks: group.tasks.flatMap((task) =>
- task.identifier !== id ? [task] : next === undefined ? [] : [next],
+ task.id !== id ? [task] : next === undefined ? [] : [next],
),
total: next === undefined ? group.total - 1 : group.total,
};
diff --git a/src/store/tool/slices/builtin/executors/workRegistration.test.ts b/src/store/tool/slices/builtin/executors/workRegistration.test.ts
index b590b934319..8e7ec842691 100644
--- a/src/store/tool/slices/builtin/executors/workRegistration.test.ts
+++ b/src/store/tool/slices/builtin/executors/workRegistration.test.ts
@@ -48,7 +48,7 @@ describe('stashBuiltinToolWorkIntent (client dispatch)', () => {
expect(takeWorkIntent(ctx.toolCallId)).toEqual({
action: 'create',
changeType: 'created',
- targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ targets: [{ taskId: 'task_1', taskIdentifier: undefined }],
type: 'task',
});
});
@@ -104,7 +104,7 @@ describe('stashBuiltinToolWorkIntent (client dispatch)', () => {
expect(takeWorkIntent(ctx.toolCallId)).toEqual({
action: 'delete',
- targets: [{ taskId: 'task_1', taskIdentifier: 'T-1' }],
+ targets: [{ taskId: 'task_1', taskIdentifier: undefined }],
type: 'task',
});
});