Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(task): task labels — router, filter, group-by-label views, Web UI, agent tools and CLI (#22176)

Rdmclin2dbc04e391616
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index d7ce5ca315c..5b050b10712 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -1,3 +1,4 @@
+import { invertTaskLabelChange, TASK_LIST_FILTER_NONE } from '@lobechat/types';
import type { Command } from 'commander';
import pc from 'picocolors';
@@ -20,6 +21,13 @@ import { registerCheckpointCommands } from './checkpoint';
import { registerDepCommands } from './dep';
import { registerDocCommands } from './doc';
import { briefIcon, priorityLabel, statusBadge } from './helpers';
+import {
+ collectLabels,
+ expandLabelRefs,
+ formatTaskLabels,
+ registerLabelCommands,
+ resolveLabelIds,
+} from './label';
import { registerLifecycleCommands } from './lifecycle';
import { formatTaskModel, toCreateModelConfig, toModelConfigPatch } from './model';
import { registerReviewCommands } from './review';
@@ -41,6 +49,12 @@ export function registerTaskCommand(program: Command) {
.option('--root', 'Only show root tasks (no parent)')
.option('--parent <id>', 'Filter by parent task ID')
.option('--agent <id>', 'Filter by assignee agent ID')
+ .option(
+ '--label <name>',
+ 'Only tasks with this label (repeatable or comma-separated; a group name matches any of its labels)',
+ collectLabels,
+ )
+ .option('--unlabeled', 'Only tasks without labels')
.option('--archived', 'Include archived tasks')
.option('-L, --limit <n>', 'Page size', '50')
.option('--offset <n>', 'Offset', '0')
@@ -53,12 +67,14 @@ export function registerTaskCommand(program: Command) {
archived?: boolean;
board?: boolean;
json?: string | boolean;
+ label?: string[];
limit?: string;
offset?: string;
parent?: string;
root?: boolean;
status?: string;
tree?: boolean;
+ unlabeled?: boolean;
}) => {
const client = await getTrpcClient();
@@ -70,6 +86,14 @@ export function registerTaskCommand(program: Command) {
if (options.archived) input.includeArchived = true;
if (options.limit) input.limit = Number.parseInt(options.limit, 10);
if (options.offset) input.offset = Number.parseInt(options.offset, 10);
+ if (options.label?.length || options.unlabeled) {
+ const values = options.label?.length
+ ? await resolveListLabelValues(client, options.label)
+ : [];
+ if (values === false) return;
+ if (options.unlabeled) values.push(TASK_LIST_FILTER_NONE);
+ input.filter = { label: { operator: 'is', values } };
+ }
// For tree/board mode, fetch all tasks (no pagination limit)
if (options.tree || options.board) {
@@ -194,10 +218,11 @@ export function registerTaskCommand(program: Command) {
priorityLabel(t.priority),
t.assigneeAgentId ? pc.dim(t.assigneeAgentId) : '-',
t.parentTaskId ? pc.dim('↳ subtask') : '',
+ formatTaskLabels(t.labels),
timeAgo(t.createdAt),
]);
- printTable(rows, ['ID', 'NAME', 'STATUS', 'PRI', 'AGENT', 'TYPE', 'CREATED']);
+ printTable(rows, ['ID', 'NAME', 'STATUS', 'PRI', 'AGENT', 'TYPE', 'LABELS', 'CREATED']);
log.info(`Total: ${result.total}`);
},
);
@@ -304,6 +329,9 @@ export function registerTaskCommand(program: Command) {
: null;
console.log(`${pc.dim('Model:')} ${formatTaskModel(t.config, agentConfig)}`);
if (t.userId) console.log(`${pc.dim('User:')} ${t.userId}`);
+ if (t.labels?.length) {
+ console.log(`${pc.dim('Labels:')} ${formatTaskLabels(t.labels, t.labels.length)}`);
+ }
if (t.parent) {
console.log(`${pc.dim('Parent:')} ${t.parent.identifier} ${t.parent.name || ''}`);
}
@@ -549,6 +577,11 @@ export function registerTaskCommand(program: Command) {
.option('--user <idOrEmail>', 'Assign to a workspace member (user id, email or username)')
.option('--parent <id>', 'Parent task ID')
.option('--priority <n>', 'Priority (0=none, 1=urgent, 2=high, 3=normal, 4=low)', '0')
+ .option(
+ '--label <name>',
+ 'Attach an existing label (repeatable or comma-separated; "Group/Label" also works)',
+ collectLabels,
+ )
.option('--model <model>', "Model to run with (default: the assignee agent's model)")
.option('--provider <provider>', 'Provider for --model (default: resolved from the agent)')
.option('--json [fields]', 'Output JSON')
@@ -557,6 +590,7 @@ export function registerTaskCommand(program: Command) {
agent?: string;
instruction: string;
json?: string | boolean;
+ label?: string[];
model?: string;
name?: string;
parent?: string;
@@ -568,10 +602,13 @@ export function registerTaskCommand(program: Command) {
const buildUrl = await resolveAppUrlBuilder(client);
const assigneeUserId = await resolveUserOption(client, options.user);
if (assigneeUserId === false) return;
+ const labelIds = await resolveLabelOption(client, options.label);
+ if (labelIds === false) return;
const input: Parameters<typeof client.task.create.mutate>[0] = {
instruction: options.instruction,
};
+ if (labelIds.length > 0) input.labelIds = labelIds;
if (options.name) input.name = options.name;
if (options.agent) input.assigneeAgentId = options.agent;
if (assigneeUserId) input.assigneeUserId = assigneeUserId;
@@ -604,6 +641,16 @@ export function registerTaskCommand(program: Command) {
.option('--agent <id>', 'Assign to agent')
.option('--user <idOrEmail>', 'Assign to a workspace member (user id, email or username)')
.option('--priority <n>', 'Priority (0-4)')
+ .option(
+ '--label <name>',
+ "Add a label (repeatable or comma-separated; replaces the task's other label of the same group)",
+ collectLabels,
+ )
+ .option(
+ '--remove-label <name>',
+ 'Remove a label (repeatable or comma-separated)',
+ collectLabels,
+ )
.option('--heartbeat-interval <n>', 'Heartbeat interval in seconds')
.option('--heartbeat-timeout <n>', 'Heartbeat timeout in seconds (0 to disable)')
.option('--description <text>', 'Task description')
@@ -624,10 +671,12 @@ export function registerTaskCommand(program: Command) {
heartbeatTimeout?: string;
instruction?: string;
json?: string | boolean;
+ label?: string[];
model?: string;
name?: string;
priority?: string;
provider?: string;
+ removeLabel?: string[];
status?: string;
user?: string;
},
@@ -635,6 +684,11 @@ export function registerTaskCommand(program: Command) {
const client = await getTrpcClient();
const assigneeUserId = await resolveUserOption(client, options.user);
if (assigneeUserId === false) return;
+ const addLabelIds = await resolveLabelOption(client, options.label);
+ if (addLabelIds === false) return;
+ const removeLabelIds = await resolveLabelOption(client, options.removeLabel);
+ if (removeLabelIds === false) return;
+ const hasLabelEdits = addLabelIds.length > 0 || removeLabelIds.length > 0;
const input: Record<string, any> = { id };
if (options.name) input.name = options.name;
@@ -654,17 +708,79 @@ export function registerTaskCommand(program: Command) {
if (configPatch) input.configPatch = configPatch;
const hasFieldEdits = Object.keys(input).length > 1;
+ const validStatuses = ['backlog', 'running', 'paused', 'completed', 'failed', 'canceled'];
+ if (options.status && !validStatuses.includes(options.status)) {
+ log.error(
+ `Invalid status "${options.status}". Must be one of: ${validStatuses.join(', ')}`,
+ );
+ process.exitCode = 1;
+ return;
+ }
+
+ // Labels have their own endpoint; apply them (in one transaction)
+ // after input validation and before any field / status edit, so a bad
+ // label fails the command before anything moves. When the field /
+ // status edit then fails, this command's own label change is undone
+ // (not the whole set replaced), so a teammate's concurrent label edit
+ // survives and the command never half-applies.
+ const hasOtherEdits = hasFieldEdits || !!options.status;
+ const readLabels = async () => (await client.task.detail.query({ id })).data?.labels ?? [];
+ const previousLabels = hasLabelEdits && hasOtherEdits ? await readLabels() : undefined;
+ let labels: Awaited<ReturnType<typeof client.taskLabel.changeForTask.mutate>> | undefined;
+ const restoreLabelsOnFailure = async (error: unknown): Promise<never> => {
+ if (previousLabels && labels) {
+ try {
+ // Re-read so a teammate's change made since is not rolled over.
+ const undo = invertTaskLabelChange(
+ previousLabels,
+ { add: addLabelIds, remove: removeLabelIds },
+ labels.map((label) => label.id),
+ await readLabels(),
+ );
+ if (undo.add.length > 0 || undo.remove.length > 0) {
+ await client.taskLabel.changeForTask.mutate({ ...undo, taskId: id });
+ }
+ } catch {
+ log.warn(`Labels on ${id} were changed but could not be restored.`);
+ }
+ }
+ throw error;
+ };
+ if (hasLabelEdits) {
+ labels = await client.taskLabel.changeForTask.mutate({
+ add: addLabelIds,
+ remove: removeLabelIds,
+ taskId: id,
+ });
+ }
+ if (hasLabelEdits && !hasOtherEdits) {
+ if (options.json !== undefined) {
+ // Same task-shaped JSON as any other `task edit --json`.
+ const { data } = await client.task.find.query({ id });
+ outputJson(
+ withUrl(
+ { ...data, labels },
+ await resolveUrlBuilder(client),
+ resourcePath.task(data),
+ ),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
+ } else {
+ log.info(
+ `Labels on ${pc.bold(id)}: ${labels?.length ? formatTaskLabels(labels, labels.length) : pc.dim('none')}`,
+ );
+ }
+ return;
+ }
+
// Status-only edits use the lifecycle API. Combined edits go through
// task.update so the server can apply the fields and lifecycle change
// atomically.
if (options.status) {
- const valid = ['backlog', 'running', 'paused', 'completed', 'failed', 'canceled'];
- if (!valid.includes(options.status)) {
- log.error(`Invalid status "${options.status}". Must be one of: ${valid.join(', ')}`);
- return;
- }
if (!hasFieldEdits) {
- const result = await client.task.updateStatus.mutate({ id, status: options.status });
+ const result = await client.task.updateStatus
+ .mutate({ id, status: options.status })
+ .catch(restoreLabelsOnFailure);
if (options.json !== undefined) {
outputJson(
withUrl(
@@ -684,11 +800,13 @@ export function registerTaskCommand(program: Command) {
input.status = options.status;
}
- const result = await client.task.update.mutate(input as any);
+ const result = await client.task.update.mutate(input as any).catch(restoreLabelsOnFailure);
if (options.json !== undefined) {
+ // task.update returns the bare row; overlay the post-edit labels.
+ const data = labels ? { ...result.data, labels } : result.data;
outputJson(
- withUrl(result.data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
+ withUrl(data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
typeof options.json === 'string' ? options.json : undefined,
);
return;
@@ -823,6 +941,7 @@ export function registerTaskCommand(program: Command) {
registerDepCommands(task);
registerTopicCommands(task);
registerDocCommands(task);
+ registerLabelCommands(task);
}
/**
@@ -842,3 +961,45 @@ const resolveUserOption = async (
return false;
}
};
+
+/** `--label` values for create / edit: assignable labels only; errors are printed. */
+const resolveLabelOption = async (
+ client: Awaited<ReturnType<typeof getTrpcClient>>,
+ names: string[] | undefined,
+): Promise<string[] | false> => {
+ if (!names?.length) return [];
+ try {
+ return await resolveLabelIds(client, names);
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exitCode = 1;
+ return false;
+ }
+};
+
+/**
+ * `lh task list --label` values: a label group name is accepted too and
+ * matches every label in the group, mirroring the Tasks page filter.
+ */
+const resolveListLabelValues = async (
+ client: Awaited<ReturnType<typeof getTrpcClient>>,
+ names: string[],
+): Promise<string[] | false> => {
+ try {
+ const registry = await client.taskLabel.list.query();
+ const groupIds: string[] = [];
+ const labelNames: string[] = [];
+ for (const name of expandLabelRefs(registry, names)) {
+ const group = registry.find(
+ (label) => label.isGroup && label.name.toLowerCase() === name.trim().toLowerCase(),
+ );
+ if (group) groupIds.push(group.id);
+ else labelNames.push(name);
+ }
+ return [...groupIds, ...(await resolveLabelIds(client, labelNames, registry))];
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exitCode = 1;
+ return false;
+ }
+};
diff --git a/apps/cli/src/commands/task/label.test.ts b/apps/cli/src/commands/task/label.test.ts
new file mode 100644
index 00000000000..66bb6deff72
--- /dev/null
+++ b/apps/cli/src/commands/task/label.test.ts
@@ -0,0 +1,287 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerTaskCommand } from './index';
+
+const registry = [
+ { id: 'g-type', isGroup: true, name: 'Type', parentId: null, sortOrder: 0, usageCount: 0 },
+ { id: 'bug', isGroup: false, name: 'Bug', parentId: 'g-type', sortOrder: 0, usageCount: 2 },
+ { id: 'feat', isGroup: false, name: 'Feature', parentId: 'g-type', sortOrder: 0, usageCount: 0 },
+ { id: 'fe', isGroup: false, name: 'Frontend', parentId: null, sortOrder: 0, usageCount: 1 },
+ { id: 'nr', isGroup: false, name: 'Needs, Review', parentId: null, sortOrder: 0, usageCount: 0 },
+];
+
+const { client } = vi.hoisted(() => ({
+ client: {
+ task: {
+ create: { mutate: vi.fn() },
+ detail: { query: vi.fn() },
+ find: { query: vi.fn() },
+ list: { query: vi.fn() },
+ update: { mutate: vi.fn() },
+ updateStatus: { mutate: vi.fn() },
+ },
+ taskLabel: {
+ addToTask: { mutate: vi.fn() },
+ changeForTask: { mutate: vi.fn() },
+ create: { mutate: vi.fn() },
+ delete: { mutate: vi.fn() },
+ list: { query: vi.fn() },
+ removeFromTask: { mutate: vi.fn() },
+ setForTask: { mutate: vi.fn() },
+ update: { mutate: vi.fn() },
+ },
+ },
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn(async () => client) }));
+vi.mock('./url', () => ({
+ resolveAppUrl: vi.fn(async () => 'https://app/task'),
+ resolveAppUrlBuilder: vi.fn(async () => () => 'https://app/task'),
+ taskPath: vi.fn(() => '/task'),
+}));
+vi.mock('../../utils/logger', () => ({
+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+const { log } = await import('../../utils/logger');
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'lh', 'task', ...args]);
+};
+
+describe('lh task --label', () => {
+ beforeEach(() => {
+ client.taskLabel.list.query.mockResolvedValue(registry);
+ client.task.create.mutate.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ client.task.list.query.mockResolvedValue({ data: [], total: 0 });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ process.exitCode = undefined;
+ });
+
+ it('create resolves names and paths to label ids', async () => {
+ await run('create', '-i', 'do it', '--label', 'bug', '--label', 'Frontend');
+
+ expect(client.task.create.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ labelIds: ['bug', 'fe'] }),
+ );
+ });
+
+ it('keeps a label whose name contains a comma whole, and still splits lists', async () => {
+ await run('create', '-i', 'do it', '--label', 'Needs, Review', '--label', 'bug,Frontend');
+
+ expect(client.task.create.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ labelIds: ['nr', 'bug', 'fe'] }),
+ );
+ });
+
+ it('create fails on an unknown label with suggestions and writes nothing', async () => {
+ await run('create', '-i', 'do it', '--label', 'Frontnd');
+
+ expect(client.task.create.mutate).not.toHaveBeenCalled();
+ expect(vi.mocked(log.error).mock.calls[0][0]).toContain('did you mean: Frontend');
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('create refuses a label group', async () => {
+ await run('create', '-i', 'do it', '--label', 'Type');
+
+ expect(client.task.create.mutate).not.toHaveBeenCalled();
+ expect(vi.mocked(log.error).mock.calls[0][0]).toContain('is a label group');
+ });
+
+ it('edit adds and removes labels in one label request only', async () => {
+ client.taskLabel.changeForTask.mutate.mockResolvedValue([{ id: 'feat', name: 'Feature' }]);
+ await run('edit', 'T-1', '--label', 'Type/Feature', '--remove-label', 'Frontend');
+
+ expect(client.taskLabel.changeForTask.mutate).toHaveBeenCalledWith({
+ add: ['feat'],
+ remove: ['fe'],
+ taskId: 'T-1',
+ });
+ expect(client.taskLabel.addToTask.mutate).not.toHaveBeenCalled();
+ expect(client.taskLabel.removeFromTask.mutate).not.toHaveBeenCalled();
+ expect(client.task.update.mutate).not.toHaveBeenCalled();
+ });
+
+ it('edit rejects an invalid status before touching labels', async () => {
+ await run('edit', 'T-1', '--label', 'Bug', '--status', 'typo');
+
+ expect(vi.mocked(log.error).mock.calls[0][0]).toContain('Invalid status "typo"');
+ expect(client.taskLabel.changeForTask.mutate).not.toHaveBeenCalled();
+ expect(client.task.update.mutate).not.toHaveBeenCalled();
+ expect(client.task.updateStatus.mutate).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('label-only edit --json prints the task, not the label array', async () => {
+ client.taskLabel.changeForTask.mutate.mockResolvedValue([{ id: 'bug', name: 'Bug' }]);
+ client.task.find.query.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ const write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+
+ await run('edit', 'T-1', '--label', 'Bug', '--json');
+
+ const printed = [...vi.mocked(console.log).mock.calls.flat(), ...write.mock.calls.flat()]
+ .map(String)
+ .join('');
+ write.mockRestore();
+ expect(printed).toContain('"id": "task_1"');
+ expect(printed).toContain('"labels"');
+ });
+
+ it('combined edit --json includes the post-edit labels', async () => {
+ client.task.detail.query.mockResolvedValue({ data: { labels: [] } });
+ client.taskLabel.changeForTask.mutate.mockResolvedValue([{ id: 'bug', name: 'Bug' }]);
+ client.task.update.mutate.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+ const write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+
+ await run('edit', 'T-1', '--label', 'Bug', '--name', 'X', '--json');
+
+ const printed = [...vi.mocked(console.log).mock.calls.flat(), ...write.mock.calls.flat()]
+ .map(String)
+ .join('');
+ write.mockRestore();
+ expect(printed).toContain('"id": "task_1"');
+ expect(printed).toContain('"name": "Bug"');
+ });
+
+ it('edit undoes only its own label change when the field edit fails', async () => {
+ client.task.detail.query
+ .mockResolvedValueOnce({
+ data: {
+ labels: [
+ { id: 'bug', name: 'Bug', parentId: 'g-type' },
+ { id: 'fe', name: 'Frontend', parentId: null },
+ ],
+ },
+ })
+ .mockResolvedValueOnce({
+ data: {
+ labels: [
+ { id: 'feat', name: 'Feature', parentId: 'g-type' },
+ { id: 'fe', name: 'Frontend', parentId: null },
+ { id: 'other', name: 'Other', parentId: null },
+ ],
+ },
+ });
+ // Feature swaps out Bug; `other` was added meanwhile by someone else.
+ client.taskLabel.changeForTask.mutate
+ .mockResolvedValueOnce([
+ { id: 'feat', name: 'Feature' },
+ { id: 'fe', name: 'Frontend' },
+ { id: 'other', name: 'Other' },
+ ])
+ .mockResolvedValueOnce([]);
+ client.task.update.mutate.mockRejectedValue(new Error('heartbeatInterval too small'));
+
+ await expect(
+ run('edit', 'T-1', '--label', 'Type/Feature', '--heartbeat-interval', '1'),
+ ).rejects.toThrow('heartbeatInterval too small');
+
+ expect(client.taskLabel.changeForTask.mutate).toHaveBeenLastCalledWith({
+ add: ['bug'],
+ remove: ['feat'],
+ taskId: 'T-1',
+ });
+ expect(client.taskLabel.setForTask.mutate).not.toHaveBeenCalled();
+ });
+
+ it('edit does not touch labels again when the combined edit succeeds', async () => {
+ client.task.detail.query.mockResolvedValue({ data: { labels: [] } });
+ client.taskLabel.changeForTask.mutate.mockResolvedValue([{ id: 'bug', name: 'Bug' }]);
+ client.task.update.mutate.mockResolvedValue({ data: { id: 'task_1', identifier: 'T-1' } });
+
+ await run('edit', 'T-1', '--label', 'Bug', '--heartbeat-interval', '600');
+
+ expect(client.task.update.mutate).toHaveBeenCalled();
+ expect(client.taskLabel.setForTask.mutate).not.toHaveBeenCalled();
+ });
+
+ it('list filters by label, by group and by "no labels"', async () => {
+ await run('list', '--label', 'Type,Frontend', '--unlabeled');
+
+ expect(client.task.list.query).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filter: { label: { operator: 'is', values: ['g-type', 'fe', '__none__'] } },
+ }),
+ );
+ });
+});
+
+describe('lh task label', () => {
+ beforeEach(() => {
+ client.taskLabel.list.query.mockResolvedValue(registry);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('create puts a label into a group by name', async () => {
+ client.taskLabel.create.mutate.mockResolvedValue({ id: 'chore', name: 'Chore' });
+ await run('label', 'create', 'Chore', '--parent', 'Type', '--color', '#EB5757');
+
+ expect(client.taskLabel.create.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ color: '#EB5757', name: 'Chore', parentId: 'g-type' }),
+ );
+ });
+
+ it('create rejects a non-hex color', async () => {
+ await expect(run('label', 'create', 'X', '--color', 'red')).rejects.toThrow('Invalid color');
+ expect(client.taskLabel.create.mutate).not.toHaveBeenCalled();
+ });
+
+ it('edit moves a label out of its group', async () => {
+ client.taskLabel.update.mutate.mockResolvedValue({ id: 'bug', name: 'Bug' });
+ await run('label', 'edit', 'Type/Bug', '--parent', 'none');
+
+ expect(client.taskLabel.update.mutate).toHaveBeenCalledWith({
+ id: 'bug',
+ value: { parentId: null },
+ });
+ });
+
+ it('delete with --yes deletes by name', async () => {
+ await run('label', 'delete', 'frontend', '--yes');
+
+ expect(client.taskLabel.delete.mutate).toHaveBeenCalledWith({ id: 'fe' });
+ });
+});
+
+describe('formatTaskLabels', () => {
+ afterEach(() => {
+ vi.resetModules();
+ vi.doUnmock('picocolors');
+ });
+
+ const load = async (isColorSupported: boolean) => {
+ vi.resetModules();
+ vi.doMock('picocolors', async (importOriginal) => {
+ const actual = (await importOriginal<{ default: object }>()).default;
+ return { default: { ...actual, isColorSupported } };
+ });
+ return (await import('./label')).formatTaskLabels;
+ };
+
+ it('writes no true-color escape when color output is off', async () => {
+ const format = await load(false);
+ expect(format([{ color: '#EB5757', id: 'bug', name: 'Bug', parentId: null }])).not.toContain(
+ '\u001B[38;2;',
+ );
+ });
+
+ it('colors the dot with the label color when supported', async () => {
+ const format = await load(true);
+ expect(format([{ color: '#EB5757', id: 'bug', name: 'Bug', parentId: null }])).toContain(
+ '\u001B[38;2;235;87;87m',
+ );
+ });
+});
diff --git a/apps/cli/src/commands/task/label.ts b/apps/cli/src/commands/task/label.ts
new file mode 100644
index 00000000000..feb1eb73373
--- /dev/null
+++ b/apps/cli/src/commands/task/label.ts
@@ -0,0 +1,263 @@
+import {
+ DEFAULT_TASK_LABEL_COLOR,
+ describeUnresolvedTaskLabels,
+ formatTaskLabelPath,
+ resolveTaskLabelRefs,
+ type TaskLabelRef,
+ type TaskLabelWithUsage,
+} from '@lobechat/types';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import type { TrpcClient } from '../../api/client';
+import { getTrpcClient } from '../../api/client';
+import { confirm, outputJson, printTable } from '../../utils/format';
+import { log } from '../../utils/logger';
+
+/**
+ * Commander collector for a repeatable option: `--label a --label b,c`. Values
+ * are kept whole here; {@link expandLabelRefs} splits commas once the registry
+ * is known, so a label actually named `Needs, Review` still resolves.
+ */
+export const collectLabels = (value: string, previous: string[] = []) => {
+ const trimmed = value.trim();
+ return trimmed ? [...previous, trimmed] : previous;
+};
+
+/** A value naming an existing label (or group) is one ref; otherwise split on commas. */
+export const expandLabelRefs = (labels: TaskLabelWithUsage[], values: string[]): string[] =>
+ values.flatMap((value) => {
+ if (!value.includes(',')) return [value];
+ const needle = value.toLowerCase();
+ const isWhole =
+ labels.some((label) => label.name.toLowerCase() === needle) ||
+ resolveTaskLabelRefs(labels, [value]).ids.length === 1;
+ return isWhole
+ ? [value]
+ : value
+ .split(',')
+ .map((item) => item.trim())
+ .filter(Boolean);
+ });
+
+const HEX_COLOR = /^#(?:[\da-f]{3}|[\da-f]{6}|[\da-f]{8})$/i;
+
+/**
+ * Resolve `--label` values against the scope's registry. Unknown names fail
+ * with suggestions instead of creating labels, so a typo (by a person or an
+ * agent) never grows the shared registry — `lh task label create` does that.
+ */
+export const resolveLabelIds = async (
+ client: TrpcClient,
+ names: string[],
+ registry?: TaskLabelWithUsage[],
+): Promise<string[]> => {
+ if (names.length === 0) return [];
+ const labels = registry ?? (await client.taskLabel.list.query());
+ const { ids, unresolved } = resolveTaskLabelRefs(labels, expandLabelRefs(labels, names));
+ if (unresolved.length > 0) {
+ throw new Error(
+ `${describeUnresolvedTaskLabels(unresolved)}\nRun \`lh task label list\` to see labels, or \`lh task label create <name>\` to add one.`,
+ );
+ }
+ return ids;
+};
+
+/** Resolve a single label or label group by name or `Group/Label` path. */
+const resolveOne = (labels: TaskLabelWithUsage[], ref: string): TaskLabelWithUsage => {
+ const needle = ref.trim().toLowerCase();
+ const byName = labels.find((label) => label.name.toLowerCase() === needle);
+ if (byName) return byName;
+ const { ids, unresolved } = resolveTaskLabelRefs(labels, [ref]);
+ if (ids.length === 1) return labels.find((label) => label.id === ids[0])!;
+ throw new Error(describeUnresolvedTaskLabels(unresolved));
+};
+
+const colorDot = (color?: string | null) => {
+ // picocolors' detection covers NO_COLOR, FORCE_COLOR and non-TTY output.
+ if (!pc.isColorSupported || !color || !HEX_COLOR.test(color)) return pc.dim('●');
+ const hex =
+ color.length === 4 ? color.replaceAll(/[\da-f]/gi, (c) => c + c).slice(1) : color.slice(1, 7);
+ const [r, g, b] = [0, 2, 4].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
+ return `\u001B[38;2;${r};${g};${b}m●\u001B[39m`;
+};
+
+/** Inline rendering of a task's labels for tables and detail views. */
+export const formatTaskLabels = (labels: TaskLabelRef[] | undefined, max = 3): string => {
+ if (!labels || labels.length === 0) return '';
+ const shown = labels.slice(0, max).map((label) => `${colorDot(label.color)} ${label.name}`);
+ const rest = labels.length - max;
+ return rest > 0 ? `${shown.join(' ')} ${pc.dim(`+${rest}`)}` : shown.join(' ');
+};
+
+const assertColor = (color: string | undefined) => {
+ if (color !== undefined && !HEX_COLOR.test(color)) {
+ throw new Error(`Invalid color "${color}" — use a hex value such as #EB5757.`);
+ }
+};
+
+export function registerLabelCommands(task: Command) {
+ const label = task.command('label').description('Manage task labels (workspace-shared)');
+
+ label
+ .command('list')
+ .description('List task labels and label groups')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (options: { json?: string | boolean }) => {
+ const client = await getTrpcClient();
+ const labels = await client.taskLabel.list.query();
+
+ if (options.json !== undefined) {
+ outputJson(labels, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (labels.length === 0) {
+ log.info('No task labels yet. Create one with `lh task label create <name>`.');
+ return;
+ }
+
+ // Top-level labels and groups first, each group followed by its labels.
+ const rows: string[][] = [];
+ for (const entry of labels.filter((l) => !l.parentId)) {
+ rows.push([
+ `${colorDot(entry.color)} ${entry.isGroup ? pc.bold(entry.name) : entry.name}`,
+ entry.isGroup ? pc.dim('group') : 'label',
+ entry.isGroup ? '' : String(entry.usageCount),
+ ]);
+ for (const child of labels.filter((l) => l.parentId === entry.id)) {
+ rows.push([
+ ` ${colorDot(child.color)} ${formatTaskLabelPath(child, labels)}`,
+ 'label',
+ String(child.usageCount),
+ ]);
+ }
+ }
+ printTable(rows, ['NAME', 'KIND', 'TASKS']);
+ });
+
+ label
+ .command('create <name>')
+ .description('Create a task label (or a label group with --group)')
+ .option('--color <hex>', `Label color (default ${DEFAULT_TASK_LABEL_COLOR})`)
+ .option('--description <text>', 'Label description')
+ .option('--group', 'Create a label group; a task carries at most one label per group')
+ .option('--parent <group>', 'Put the label inside this label group')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ name: string,
+ options: {
+ color?: string;
+ description?: string;
+ group?: boolean;
+ json?: string | boolean;
+ parent?: string;
+ },
+ ) => {
+ assertColor(options.color);
+ const client = await getTrpcClient();
+ let parentId: string | undefined;
+ if (options.parent) {
+ if (options.group) throw new Error('A label group cannot be nested in another group.');
+ const parent = resolveOne(await client.taskLabel.list.query(), options.parent);
+ if (!parent.isGroup) throw new Error(`"${parent.name}" is not a label group.`);
+ parentId = parent.id;
+ }
+
+ const created = await client.taskLabel.create.mutate({
+ color: options.color ?? DEFAULT_TASK_LABEL_COLOR,
+ description: options.description,
+ isGroup: options.group,
+ name,
+ parentId,
+ });
+
+ if (options.json !== undefined) {
+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ log.info(`${options.group ? 'Label group' : 'Label'} created: ${pc.bold(created.name)}`);
+ console.log(`ID: ${created.id}`);
+ },
+ );
+
+ label
+ .command('edit <label>')
+ .description('Rename, recolor or move a task label')
+ .option('-n, --name <name>', 'New name')
+ .option('--color <hex>', 'New color')
+ .option('--description <text>', 'New description')
+ .option('--parent <group>', 'Move into this label group ("none" to move out)')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ ref: string,
+ options: {
+ color?: string;
+ description?: string;
+ json?: string | boolean;
+ name?: string;
+ parent?: string;
+ },
+ ) => {
+ assertColor(options.color);
+ const client = await getTrpcClient();
+ const labels = await client.taskLabel.list.query();
+ const target = resolveOne(labels, ref);
+
+ const value: Parameters<typeof client.taskLabel.update.mutate>[0]['value'] = {};
+ if (options.name) value.name = options.name;
+ if (options.color) value.color = options.color;
+ if (options.description !== undefined) value.description = options.description;
+ if (options.parent !== undefined) {
+ if (options.parent.toLowerCase() === 'none') {
+ value.parentId = null;
+ } else {
+ const parent = resolveOne(labels, options.parent);
+ if (!parent.isGroup) throw new Error(`"${parent.name}" is not a label group.`);
+ value.parentId = parent.id;
+ }
+ }
+ if (Object.keys(value).length === 0) {
+ log.error('Nothing to change — pass --name, --color, --description or --parent.');
+ return;
+ }
+
+ const updated = await client.taskLabel.update.mutate({ id: target.id, value });
+ if (options.json !== undefined) {
+ outputJson(updated, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ log.info(`Label updated: ${pc.bold(updated?.name ?? target.name)}`);
+ },
+ );
+
+ label
+ .command('delete <label>')
+ .description('Delete a task label (deleting a group deletes its labels)')
+ .option('-y, --yes', 'Skip confirmation')
+ .action(async (ref: string, options: { yes?: boolean }) => {
+ const client = await getTrpcClient();
+ const labels = await client.taskLabel.list.query();
+ const target = resolveOne(labels, ref);
+ const children = labels.filter((l) => l.parentId === target.id);
+ const usage = target.isGroup
+ ? children.reduce((sum, child) => sum + child.usageCount, 0)
+ : target.usageCount;
+
+ if (!options.yes) {
+ const what = target.isGroup
+ ? `label group "${target.name}" and its ${children.length} label(s)`
+ : `label "${target.name}"`;
+ const ok = await confirm(
+ // `usageCount` only covers unarchived tasks the caller can see; the
+ // delete itself reaches every task carrying the label.
+ `Delete ${what}? It is removed from every task that carries it (${usage} unarchived task(s) visible to you). This cannot be undone.`,
+ );
+ if (!ok) return;
+ }
+
+ await client.taskLabel.delete.mutate({ id: target.id });
+ log.info(`Deleted ${target.isGroup ? 'label group' : 'label'}: ${pc.bold(target.name)}`);
+ });
+}
diff --git a/apps/server/src/routers/lambda/__tests__/taskLabel.test.ts b/apps/server/src/routers/lambda/__tests__/taskLabel.test.ts
new file mode 100644
index 00000000000..c2bf88cae47
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/taskLabel.test.ts
@@ -0,0 +1,132 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as TaskLabelModule from '@/database/models/taskLabel';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+const mockCreate = vi.fn();
+const mockAddTaskLabels = vi.fn();
+const mockChangeTaskLabels = vi.fn();
+const mockUpdate = vi.fn();
+
+vi.mock('@/database/models/taskLabel', async (importOriginal) => {
+ const actual = await importOriginal<typeof TaskLabelModule>();
+ return {
+ ...actual,
+ TaskLabelModel: vi.fn(function () {
+ return {
+ addTaskLabels: mockAddTaskLabels,
+ changeTaskLabels: mockChangeTaskLabels,
+ create: mockCreate,
+ update: mockUpdate,
+ };
+ }),
+ };
+});
+
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/server/services/task/utils', () => ({
+ resolveTaskOrThrow: vi.fn(async (_model: unknown, id: string) => ({ id: `resolved-${id}` })),
+}));
+
+const { TaskLabelError } = await import('@/database/models/taskLabel');
+const { taskLabelRouter } = await import('../taskLabel');
+
+const uniqueViolation = (constraint: string) => {
+ const error = new Error('duplicate key value violates unique constraint');
+ (error as any).cause = { code: '23505', constraint };
+ return error;
+};
+
+describe('taskLabelRouter', () => {
+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it.each([['task_labels_user_id_name_unique'], ['task_labels_workspace_id_name_unique']])(
+ 'maps a %s violation to CONFLICT',
+ async (constraint) => {
+ mockCreate.mockRejectedValue(uniqueViolation(constraint));
+ const caller = taskLabelRouter.createCaller(ctx);
+
+ await expect(caller.create({ name: 'Bug' })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ message: 'DUPLICATE_LABEL_NAME',
+ });
+ },
+ );
+
+ it('rejects a non-hex color before it reaches the model', async () => {
+ const caller = taskLabelRouter.createCaller(ctx);
+
+ await expect(caller.create({ color: 'url(https://x)', name: 'Bug' })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(mockCreate).not.toHaveBeenCalled();
+ });
+
+ it('resolves the task identifier and maps model rule errors', async () => {
+ const caller = taskLabelRouter.createCaller(ctx);
+ mockAddTaskLabels.mockResolvedValueOnce([{ id: 'l1', name: 'Bug' }]);
+
+ await expect(caller.addToTask({ labelIds: ['l1'], taskId: 'T-1' })).resolves.toEqual([
+ { id: 'l1', name: 'Bug' },
+ ]);
+ expect(mockAddTaskLabels).toHaveBeenCalledWith('resolved-T-1', ['l1']);
+
+ mockAddTaskLabels.mockRejectedValueOnce(new TaskLabelError('GROUP_CONFLICT', 'one per group'));
+ await expect(caller.addToTask({ labelIds: ['l1', 'l2'], taskId: 'T-1' })).rejects.toMatchObject(
+ { code: 'BAD_REQUEST' },
+ );
+
+ mockAddTaskLabels.mockRejectedValueOnce(new TaskLabelError('LABEL_NOT_FOUND', 'missing'));
+ await expect(caller.addToTask({ labelIds: ['x'], taskId: 'T-1' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it('applies an add + remove delta through one model call', async () => {
+ const caller = taskLabelRouter.createCaller(ctx);
+ mockChangeTaskLabels.mockResolvedValueOnce([{ id: 'l2', name: 'Backend' }]);
+
+ await expect(
+ caller.changeForTask({ add: ['l2'], remove: ['l1'], taskId: 'T-1' }),
+ ).resolves.toEqual([{ id: 'l2', name: 'Backend' }]);
+ expect(mockChangeTaskLabels).toHaveBeenCalledWith('resolved-T-1', {
+ add: ['l2'],
+ remove: ['l1'],
+ });
+
+ mockChangeTaskLabels.mockRejectedValueOnce(new TaskLabelError('LABEL_NOT_FOUND', 'missing'));
+ await expect(caller.changeForTask({ add: ['x'], taskId: 'T-1' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it('passes only the provided fields to update', async () => {
+ mockUpdate.mockResolvedValue({ id: 'l1' });
+ const caller = taskLabelRouter.createCaller(ctx);
+
+ await caller.update({ id: 'l1', value: { parentId: null } });
+
+ expect(mockUpdate).toHaveBeenCalledWith('l1', { parentId: null });
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
index b61cb14779a..1f46445732b 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
@@ -40,6 +40,8 @@ export const taskListFilterSchema = z.object({
content: z.string().trim().max(TASK_LIST_FILTER_CONTENT_MAX_LENGTH).optional(),
createdAt: filterDate.optional(),
creator: filterSet(filterId.refine((id) => id !== TASK_LIST_FILTER_NONE)).optional(),
+ // Label or label-group ids; `TASK_LIST_FILTER_NONE` = no labels.
+ label: filterSet(filterId).optional(),
priority: filterSet(z.number().int().min(0).max(4)).optional(),
project: filterSet(filterId).optional(),
status: filterSet(z.enum(TASK_STATUSES)).optional(),
@@ -90,7 +92,7 @@ export const groupListSchema = z
completedWithin: z.enum(TASK_COMPLETED_WINDOWS).optional(),
excludeStatuses: z.array(z.enum(TASK_STATUSES)).max(10).optional(),
filter: taskListFilterSchema.optional(),
- groupBy: z.enum(['agent', 'assignee', 'member', 'priority']).optional(),
+ groupBy: z.enum(['agent', 'assignee', 'label', 'member', 'priority']).optional(),
groups: z
.array(
z.object({
@@ -106,6 +108,8 @@ export const groupListSchema = z
.max(10)
.optional(),
includeArchived: z.boolean().optional(),
+ // The label group whose labels are the columns when `groupBy` is 'label'.
+ labelGroupId: z.string().min(1).max(64).optional(),
parentIdentifier: z.string().trim().min(1).optional(),
parentTaskId: z.string().trim().min(1).nullish(),
projectId: z.string().optional(),
@@ -116,6 +120,9 @@ export const groupListSchema = z
})
.refine(({ groupBy, groups }) => Boolean(groupBy) !== Boolean(groups), {
message: 'Provide either groups or groupBy',
+ })
+ .refine(({ groupBy, labelGroupId }) => groupBy !== 'label' || Boolean(labelGroupId), {
+ message: 'Grouping by label requires labelGroupId',
});
/** The model's `closedAfter` cut for a `completedWithin` window. */
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 8b546e09860..8719034e7bf 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -105,6 +105,7 @@ import { sessionGroupRouter } from './sessionGroup';
import { shareRouter } from './share';
import { shareChatRouter } from './shareChat';
import { taskRouter } from './task';
+import { taskLabelRouter } from './taskLabel';
import { threadRouter } from './thread';
import { topicRouter } from './topic';
import { topicCommentRouter } from './topicComment';
@@ -210,6 +211,7 @@ export const lambdaRouter = router({
share: shareRouter,
shareChat: shareChatRouter,
task: taskRouter,
+ taskLabel: taskLabelRouter,
thread: threadRouter,
topic: topicRouter,
trash: trashRouter,
diff --git a/apps/server/src/routers/lambda/task/lifecycle.ts b/apps/server/src/routers/lambda/task/lifecycle.ts
index 89631054b12..21e83dac88d 100644
--- a/apps/server/src/routers/lambda/task/lifecycle.ts
+++ b/apps/server/src/routers/lambda/task/lifecycle.ts
@@ -3,6 +3,7 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { TaskArchiveModel } from '@/database/models/taskArchive';
+import { TaskLabelError, TaskLabelModel } from '@/database/models/taskLabel';
import { router } from '@/libs/trpc/lambda';
import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
import { assertNotInOpenGoal } from '@/server/services/task/archiveGuard';
@@ -35,6 +36,8 @@ const createSchema = z.object({
description: z.string().optional(),
editorData: z.unknown().optional(),
instruction: z.string().min(1),
+ // Labels to attach on creation; validated before the task row is written.
+ labelIds: z.array(z.string().min(1).max(64)).max(50).optional(),
name: z.string().optional(),
parentTaskId: z.string().optional(),
priority: z.number().min(0).max(4).optional(),
@@ -118,7 +121,7 @@ export const lifecycleRouter = router({
}
}),
create: taskProcedureWrite.input(createSchema).mutation(async ({ input, ctx }) => {
- const { goal: legacyGoal, ...createInput } = input;
+ const { goal: legacyGoal, labelIds, ...createInput } = input;
if (legacyGoal !== undefined) {
throw new TRPCError({
code: 'BAD_REQUEST',
@@ -127,6 +130,16 @@ export const lifecycleRouter = router({
});
}
assertResultingScheduleValid(null, createInput);
+ const labelModel = new TaskLabelModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ if (labelIds?.length) {
+ // Reject unknown / group / conflicting labels before anything is written.
+ await labelModel.assertAssignable(labelIds).catch((error) => {
+ if (error instanceof TaskLabelError) {
+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });
+ }
+ throw error;
+ });
+ }
try {
const parsedVerify = taskVerifyConfigPatchSchema.safeParse(createInput.config?.verify);
const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};
@@ -141,6 +154,11 @@ export const lifecycleRouter = router({
),
});
try {
+ // Labels first: their links cascade with the task on rollback, while an
+ // acceptance (no FK to its subject) would outlive a later failure here.
+ if (labelIds?.length) {
+ task.labels = await labelModel.addTaskLabels(task.id, labelIds);
+ }
if (parsedVerify.success) {
const { requirement, ...rawConfig } = parsedVerify.data;
const config = Object.fromEntries(
diff --git a/apps/server/src/routers/lambda/task/queries.ts b/apps/server/src/routers/lambda/task/queries.ts
index 14d0b7403f6..414e2aeda4f 100644
--- a/apps/server/src/routers/lambda/task/queries.ts
+++ b/apps/server/src/routers/lambda/task/queries.ts
@@ -1,6 +1,7 @@
import type { TaskListItem, TaskParticipant } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
+import { TaskLabelModel } from '@/database/models/taskLabel';
import { UserModel } from '@/database/models/user';
import { router } from '@/libs/trpc/lambda';
import { resolveTaskOrThrow } from '@/server/services/task/utils';
@@ -132,6 +133,16 @@ export const queriesRouter = router({
try {
const model = ctx.taskModel;
const { completedWithin, parentIdentifier, scope, ...query } = input;
+ if (query.groupBy === 'label') {
+ const group = await new TaskLabelModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).findById(query.labelGroupId!);
+ if (!group?.isGroup) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Label group not found' });
+ }
+ }
const parentRef = query.parentTaskId !== undefined ? query.parentTaskId : parentIdentifier;
const parentTaskId =
typeof parentRef === 'string'
diff --git a/apps/server/src/routers/lambda/taskLabel.ts b/apps/server/src/routers/lambda/taskLabel.ts
new file mode 100644
index 00000000000..3bffdec9258
--- /dev/null
+++ b/apps/server/src/routers/lambda/taskLabel.ts
@@ -0,0 +1,167 @@
+import { TASK_LABEL_NAME_MAX_LENGTH } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { TaskModel } from '@/database/models/task';
+import { TaskLabelError, TaskLabelModel } from '@/database/models/taskLabel';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { resolveTaskOrThrow } from '@/server/services/task/utils';
+
+/**
+ * `color` is rendered straight into an inline `background` on label chips, so
+ * an arbitrary string is a CSS injection point (`url(https://…)` would make
+ * every member who sees the shared label fetch an attacker resource).
+ * Constrain it to a hex literal wherever it can be written.
+ */
+const hexColor = z
+ .string()
+ .regex(/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i, 'INVALID_LABEL_COLOR');
+
+const labelName = z.string().trim().min(1).max(TASK_LABEL_NAME_MAX_LENGTH);
+const labelIds = z.array(z.string().min(1).max(64)).max(50);
+
+const LABEL_NAME_CONSTRAINTS = new Set([
+ 'task_labels_user_id_name_unique',
+ 'task_labels_workspace_id_name_unique',
+]);
+
+/** Postgres surfaces the driver error somewhere down the `cause` chain. */
+const getPostgresErrorField = (error: unknown, field: string): string | undefined => {
+ let current: unknown = error;
+ while (current && typeof current === 'object') {
+ const value = (current as Record<string, unknown>)[field];
+ if (typeof value === 'string') return value;
+ current = (current as { cause?: unknown }).cause;
+ }
+};
+
+/**
+ * Turn the model's expected failures into client-recoverable TRPC errors: a
+ * duplicate name is CONFLICT (the UI prompts a rename), the label/group rule
+ * violations are BAD_REQUEST, a task or label outside the scope is NOT_FOUND.
+ */
+const rethrowLabelError = (error: unknown): never => {
+ if (error instanceof TRPCError) throw error;
+ if (
+ getPostgresErrorField(error, 'code') === '23505' &&
+ LABEL_NAME_CONSTRAINTS.has(getPostgresErrorField(error, 'constraint') ?? '')
+ ) {
+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'DUPLICATE_LABEL_NAME' });
+ }
+ if (error instanceof TaskLabelError) {
+ const code =
+ error.code === 'LABEL_NOT_FOUND' || error.code === 'TASK_NOT_FOUND'
+ ? 'NOT_FOUND'
+ : 'BAD_REQUEST';
+ throw new TRPCError({ cause: error, code, message: error.message });
+ }
+ throw error;
+};
+
+const labelProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+ return opts.next({
+ ctx: {
+ taskLabelModel: new TaskLabelModel(ctx.serverDB, ctx.userId, wsId),
+ taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
+
+/**
+ * The registry and the assignments are task organization, gated exactly like
+ * task writes (`taskProcedureWrite`): members who can edit tasks may manage
+ * the shared labels, viewers only read them.
+ */
+const labelWriteProcedure = labelProcedure.use(withScopedPermission('agent:update'));
+
+const taskLabelsInput = z.object({ labelIds, taskId: z.string().trim().min(1) });
+
+export const taskLabelRouter = router({
+ addToTask: labelWriteProcedure.input(taskLabelsInput).mutation(async ({ input, ctx }) => {
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.taskId);
+ return ctx.taskLabelModel.addTaskLabels(task.id, input.labelIds).catch(rethrowLabelError);
+ }),
+
+ /** Apply an add + remove delta in one transaction (an edit that swaps labels). */
+ changeForTask: labelWriteProcedure
+ .input(
+ z.object({
+ add: labelIds.optional(),
+ remove: labelIds.optional(),
+ taskId: z.string().trim().min(1),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.taskId);
+ return ctx.taskLabelModel
+ .changeTaskLabels(task.id, { add: input.add, remove: input.remove })
+ .catch(rethrowLabelError);
+ }),
+
+ create: labelWriteProcedure
+ .input(
+ z.object({
+ color: hexColor.nullish(),
+ description: z.string().max(255).nullish(),
+ isGroup: z.boolean().optional(),
+ name: labelName,
+ parentId: z.string().nullish(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.taskLabelModel.create(input).catch(rethrowLabelError);
+ }),
+
+ delete: labelWriteProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await ctx.taskLabelModel.delete(input.id);
+ return { success: true };
+ }),
+
+ list: labelProcedure.query(async ({ ctx }) => ctx.taskLabelModel.query()),
+
+ removeFromTask: labelWriteProcedure.input(taskLabelsInput).mutation(async ({ input, ctx }) => {
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.taskId);
+ return ctx.taskLabelModel.removeTaskLabels(task.id, input.labelIds).catch(rethrowLabelError);
+ }),
+
+ setForTask: labelWriteProcedure.input(taskLabelsInput).mutation(async ({ input, ctx }) => {
+ const task = await resolveTaskOrThrow(ctx.taskModel, input.taskId);
+ return ctx.taskLabelModel.setTaskLabels(task.id, input.labelIds).catch(rethrowLabelError);
+ }),
+
+ update: labelWriteProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ value: z.object({
+ color: hexColor.nullish(),
+ description: z.string().max(255).nullish(),
+ name: labelName.optional(),
+ parentId: z.string().nullish(),
+ sortOrder: z.number().int().min(0).max(100_000).optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { color, description, name, parentId, sortOrder } = input.value;
+ const row = await ctx.taskLabelModel
+ .update(input.id, {
+ ...(color !== undefined ? { color } : {}),
+ ...(description !== undefined ? { description } : {}),
+ ...(name !== undefined ? { name } : {}),
+ ...(parentId !== undefined ? { parentId } : {}),
+ ...(sortOrder !== undefined ? { sortOrder } : {}),
+ })
+ .catch(rethrowLabelError);
+ return row;
+ }),
+});
+
+export type TaskLabelRouter = typeof taskLabelRouter;
diff --git a/apps/server/src/services/task/detail.ts b/apps/server/src/services/task/detail.ts
index bfd4fb92014..ce915eda012 100644
--- a/apps/server/src/services/task/detail.ts
+++ b/apps/server/src/services/task/detail.ts
@@ -16,6 +16,7 @@ import pMap from 'p-map';
import { AgentModel } from '@/database/models/agent';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
+import { TaskLabelModel } from '@/database/models/taskLabel';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { UserModel } from '@/database/models/user';
import { VerifyRunModel } from '@/database/models/verifyRun';
@@ -107,6 +108,7 @@ export class TaskDetailService {
workspace,
acceptance,
goal,
+ labels,
] = await Promise.all([
this.taskModel.findAllDescendants(task.id),
this.taskModel.getDependencies(task.id),
@@ -119,6 +121,7 @@ export class TaskDetailService {
new GoalGraphModel(this.db, this.userId, this.workspaceId)
.findGoalByTaskId(task.id)
.catch(() => undefined),
+ new TaskLabelModel(this.db, this.userId, this.workspaceId).getTaskLabels(task.id),
]);
// What the reader is shown, not what was written: a burst of edits to one
@@ -523,6 +526,7 @@ export class TaskDetailService {
id: task.id,
identifier: task.identifier,
instruction: task.instruction,
+ labels,
name: task.name,
parent,
priority: task.priority,
diff --git a/apps/server/src/services/task/index.detailState.test.ts b/apps/server/src/services/task/index.detailState.test.ts
index 7e84892cadd..464cf5397ec 100644
--- a/apps/server/src/services/task/index.detailState.test.ts
+++ b/apps/server/src/services/task/index.detailState.test.ts
@@ -24,6 +24,12 @@ vi.mock('@/database/models/agent', () => ({
}));
vi.mock('@/database/models/project', () => ({ ProjectModel: vi.fn() }));
vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));
+vi.mock('@/database/models/taskLabel', () => ({
+ TaskLabelModel: vi.fn(function () {
+ return { getTaskLabels: vi.fn().mockResolvedValue([]) };
+ }),
+}));
+
vi.mock('@/database/models/user', () => ({
UserModel: { findByIds: vi.fn().mockResolvedValue([]) },
}));
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 6c3a0c8efb2..11feeefdc9c 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -63,6 +63,12 @@ vi.mock('@/database/models/workspaceMember', () => ({
WorkspaceMemberModel: vi.fn(),
}));
+vi.mock('@/database/models/taskLabel', () => ({
+ TaskLabelModel: vi.fn(function () {
+ return { getTaskLabels: vi.fn().mockResolvedValue([]) };
+ }),
+}));
+
vi.mock('@/database/models/user', () => ({
UserModel: { findByIds: vi.fn().mockResolvedValue([]) },
}));
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.labels.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.labels.test.ts
new file mode 100644
index 00000000000..23f50d794cd
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.labels.test.ts
@@ -0,0 +1,202 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createTaskRuntime } from '../task';
+
+vi.mock('@/business/server/task/notifyTaskAssigned', () => ({ notifyTaskAssigned: vi.fn() }));
+vi.mock('@/server/routers/lambda/task', () => ({ taskRouter: { createCaller: vi.fn() } }));
+vi.mock('@/server/routers/lambda/taskLabel', () => ({
+ taskLabelRouter: { createCaller: vi.fn() },
+}));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const registry = [
+ { id: 'g', isGroup: true, name: 'Type', parentId: null },
+ { id: 'bug', isGroup: false, name: 'Bug', parentId: 'g' },
+ { id: 'feat', isGroup: false, name: 'Feature', parentId: 'g' },
+ { id: 'fe', isGroup: false, name: 'Frontend', parentId: null },
+];
+
+const task = { id: 'task-1', identifier: 'T-1', name: 'Ship', priority: 0, status: 'backlog' };
+
+const setup = () => {
+ const taskLabelCaller = {
+ addToTask: vi.fn().mockResolvedValue([{ id: 'bug', name: 'Bug' }]),
+ changeForTask: vi.fn().mockResolvedValue([{ id: 'feat', name: 'Feature' }]),
+ list: vi.fn().mockResolvedValue(registry),
+ removeFromTask: vi.fn().mockResolvedValue([]),
+ };
+ const taskCaller = {
+ detail: vi.fn().mockResolvedValue({ data: { labels: [] } }),
+ list: vi.fn().mockResolvedValue({ data: [], total: 0 }),
+ update: vi.fn().mockResolvedValue({ data: task }),
+ };
+ const taskService = { createTask: vi.fn().mockResolvedValue(task) };
+ const taskModel = {
+ delete: vi.fn().mockResolvedValue(undefined),
+ resolve: vi.fn().mockResolvedValue(task),
+ };
+ const agentModel = { existsById: vi.fn().mockResolvedValue(true) };
+ const runtime = createTaskRuntime({
+ agentModel: agentModel as any,
+ taskCaller: taskCaller as any,
+ taskLabelCaller: taskLabelCaller as any,
+ taskModel: taskModel as any,
+ taskService: taskService as any,
+ });
+ return { agentModel, runtime, taskCaller, taskLabelCaller, taskModel, taskService };
+};
+
+describe('task tool labels', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('createTask attaches resolved labels and reports them', async () => {
+ const { runtime, taskLabelCaller } = setup();
+
+ const result = await runtime.createTask({
+ instruction: 'x',
+ labels: ['Type/Bug'],
+ name: 'Ship',
+ });
+
+ expect(result.success).toBe(true);
+ expect(taskLabelCaller.addToTask).toHaveBeenCalledWith({ labelIds: ['bug'], taskId: 'task-1' });
+ expect(result.content).toContain('Labels: Bug');
+ });
+
+ it('createTask rolls the task back when its labels cannot be attached', async () => {
+ const { runtime, taskLabelCaller, taskModel } = setup();
+ taskLabelCaller.addToTask.mockRejectedValueOnce(new Error('Labels not found: bug'));
+
+ const result = await runtime.createTask({
+ instruction: 'x',
+ labels: ['Type/Bug'],
+ name: 'Ship',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Nothing was created');
+ expect(taskModel.delete).toHaveBeenCalledWith('task-1');
+ });
+
+ it('createTask with an unknown label creates nothing and suggests names', async () => {
+ const { runtime, taskService } = setup();
+
+ const result = await runtime.createTask({
+ instruction: 'x',
+ labels: ['Frontnd'],
+ name: 'Ship',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('did you mean: Frontend');
+ expect(taskService.createTask).not.toHaveBeenCalled();
+ });
+
+ it('editTask swaps labels in one atomic call', async () => {
+ const { runtime, taskLabelCaller } = setup();
+
+ const result = await runtime.editTask({
+ addLabels: ['Feature'],
+ identifier: 'T-1',
+ removeLabels: ['Frontend'],
+ });
+
+ expect(result.success).toBe(true);
+ expect(taskLabelCaller.changeForTask).toHaveBeenCalledWith({
+ add: ['feat'],
+ remove: ['fe'],
+ taskId: 'task-1',
+ });
+ expect(taskLabelCaller.addToTask).not.toHaveBeenCalled();
+ expect(taskLabelCaller.removeFromTask).not.toHaveBeenCalled();
+ });
+
+ it('editTask writes nothing else when the label change fails', async () => {
+ const { runtime, taskCaller, taskLabelCaller } = setup();
+ taskLabelCaller.changeForTask.mockRejectedValueOnce(new Error('label deleted'));
+
+ await expect(
+ runtime.editTask({ addLabels: ['Feature'], identifier: 'T-1', name: 'Renamed' }),
+ ).rejects.toThrow('label deleted');
+ expect(taskCaller.update).not.toHaveBeenCalled();
+ });
+
+ it('editTask undoes only its own label change when a later write fails', async () => {
+ const { runtime, taskCaller, taskLabelCaller } = setup();
+ // Feature swaps out Bug; `other` was added concurrently by someone else.
+ taskCaller.detail
+ .mockResolvedValueOnce({
+ data: {
+ labels: [
+ { id: 'bug', parentId: 'g' },
+ { id: 'fe', parentId: null },
+ ],
+ },
+ })
+ .mockResolvedValueOnce({
+ data: {
+ labels: [
+ { id: 'feat', parentId: 'g' },
+ { id: 'fe', parentId: null },
+ { id: 'other', parentId: null },
+ ],
+ },
+ });
+ taskLabelCaller.changeForTask
+ .mockResolvedValueOnce([{ id: 'feat' }, { id: 'fe' }, { id: 'other' }])
+ .mockResolvedValueOnce([]);
+ taskCaller.update.mockRejectedValueOnce(new Error('update failed'));
+
+ await expect(
+ runtime.editTask({ addLabels: ['Feature'], identifier: 'T-1', name: 'Renamed' }),
+ ).rejects.toThrow('update failed');
+ expect(taskLabelCaller.changeForTask).toHaveBeenLastCalledWith({
+ add: ['bug'],
+ remove: ['feat'],
+ taskId: 'task-1',
+ });
+ });
+
+ it('editTask undoes its label change when a later input fails validation', async () => {
+ const { agentModel, runtime, taskCaller, taskLabelCaller } = setup();
+ agentModel.existsById.mockResolvedValue(false);
+ taskCaller.detail
+ .mockResolvedValueOnce({ data: { labels: [] } })
+ .mockResolvedValueOnce({ data: { labels: [{ id: 'feat', parentId: 'g' }] } });
+ taskLabelCaller.changeForTask.mockResolvedValueOnce([{ id: 'feat' }]).mockResolvedValueOnce([]);
+
+ const result = await runtime.editTask({
+ addLabels: ['Feature'],
+ assigneeAgentId: 'agt_missing',
+ identifier: 'T-1',
+ });
+
+ expect(result.success).toBe(false);
+ expect(taskCaller.update).not.toHaveBeenCalled();
+ expect(taskLabelCaller.changeForTask).toHaveBeenLastCalledWith({
+ add: [],
+ remove: ['feat'],
+ taskId: 'task-1',
+ });
+ });
+
+ it('editTask with only labels does not read the task first', async () => {
+ const { runtime, taskCaller } = setup();
+
+ const result = await runtime.editTask({ addLabels: ['Feature'], identifier: 'T-1' });
+
+ expect(result.success).toBe(true);
+ expect(taskCaller.detail).not.toHaveBeenCalled();
+ });
+
+ it('listTasks filters by label and group names', async () => {
+ const { runtime, taskCaller } = setup();
+
+ await runtime.listTasks({ labels: ['Type', 'Frontend'] });
+
+ expect(taskCaller.list).toHaveBeenCalledWith(
+ expect.objectContaining({ filter: { label: { operator: 'is', values: ['g', 'fe'] } } }),
+ );
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 3c1a93edbda..d80e5f67d0a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -1,10 +1,11 @@
-import type { ListWorkspaceMembersParams } from '@lobechat/builtin-tool-task';
+import type { ListWorkspaceMembersParams, ToolLabelResolution } from '@lobechat/builtin-tool-task';
import {
describeTaskModelChange,
MISSING_TASK_NAME_ERROR,
normalizeListTasksParams,
normalizeListWorkspaceMembersParams,
normalizeSetTaskVerifyParams,
+ resolveToolLabelIds,
selectAssignableMembers,
TaskIdentifier,
toCreateTaskModelConfig,
@@ -25,6 +26,7 @@ import {
priorityLabel,
} from '@lobechat/prompts';
import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';
+import { invertTaskLabelChange } from '@lobechat/types';
import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';
import pMap from 'p-map';
@@ -37,6 +39,7 @@ import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import { appEnv } from '@/envs/app';
import { formatPgError, unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { taskRouter } from '@/server/routers/lambda/task';
+import { taskLabelRouter } from '@/server/routers/lambda/taskLabel';
import { TaskService } from '@/server/services/task';
import { resolveTaskOrThrow, resolveTasksOrThrow } from '@/server/services/task/utils';
@@ -69,6 +72,7 @@ export interface TaskRuntimeDeps {
scope?: string | null;
taskCaller: ReturnType<typeof taskRouter.createCaller>;
taskId?: string;
+ taskLabelCaller?: ReturnType<typeof taskLabelRouter.createCaller>;
taskModel: TaskModel;
taskService: TaskService;
threadId?: string | null;
@@ -97,6 +101,18 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const taskService = () => deps.taskService;
const taskCaller = () => deps.taskCaller;
+ /** Resolve agent-supplied label names against the registry; never creates labels. */
+ const resolveLabels = async (
+ names: string[] | undefined,
+ allowGroups = false,
+ ): Promise<ToolLabelResolution> => {
+ if (!names?.some((name) => name.trim())) return { ids: [] };
+ if (!deps.taskLabelCaller) {
+ return { error: 'Task labels are unavailable in this context.', ids: [] };
+ }
+ return resolveToolLabelIds(await deps.taskLabelCaller.list(), names, { allowGroups });
+ };
+
// Base URL for task deep-links embedded in tool results. These results can be
// pushed to IM / bot channels and mobile, so the link must be ABSOLUTE — and
// workspace-scoped tasks live under `/{slug}/task/...`, so the slug has to be
@@ -119,6 +135,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
requirement?: string | null;
title?: string;
};
+ labels?: string[];
model?: string;
name: string;
parentIdentifier?: string;
@@ -165,6 +182,9 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, projectId);
if (!assigneeResult.success) return { content: assigneeResult.content, success: false };
+ // Resolved before the insert so a bad label name creates nothing.
+ const labelResult = await resolveLabels(args.labels);
+ if (labelResult.error) return { content: labelResult.error, success: false };
// Capture where this task was spawned from so the lifecycle can later
// bridge the handoff result back to the creator conversation.
@@ -211,6 +231,28 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
return { content: `Failed to create task: ${formatPgError(pgError)}`, success: false };
}
+ let labels: { name: string }[] | undefined;
+ if (labelResult.ids.length > 0) {
+ try {
+ labels = await deps.taskLabelCaller!.addToTask({
+ labelIds: labelResult.ids,
+ taskId: task.id,
+ });
+ } catch (error) {
+ // Roll the task back (as task.create does) so a failed call leaves
+ // nothing behind and a retry cannot produce a duplicate.
+ await taskModel()
+ .delete(task.id)
+ .catch(() => {});
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ content: `Failed to create task: its labels could not be attached (${message}). Nothing was created.`,
+ success: false,
+ };
+ }
+ }
+
+ // Only once the task is complete, so a rolled-back task never notifies.
notifyMemberAssigned(task);
return {
@@ -225,6 +267,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
id: task.id,
identifier: task.identifier,
instruction: args.instruction,
+ labels,
name: task.name,
parentLabel,
parentTaskId,
@@ -360,6 +403,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
editTask: async (args: {
addDependencies?: string[];
+ addLabels?: string[];
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
description?: string;
@@ -371,126 +415,196 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
priority?: number;
provider?: string | null;
removeDependencies?: string[];
+ removeLabels?: string[];
}) => {
const task = await taskModel().resolve(args.identifier);
if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
-
- const updateData: {
- assigneeAgentId?: string | null;
- assigneeUserId?: string | null;
- description?: string;
- instruction?: string;
- name?: string;
- parentTaskId?: string | null;
- priority?: number;
- } = {};
- const changes: string[] = [];
- const ops: Promise<unknown>[] = [];
-
- if (args.name !== undefined) {
- updateData.name = args.name;
- changes.push(`name → "${args.name}"`);
- }
- if (args.assigneeAgentId !== undefined) {
- const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, task.projectId);
- if (!assigneeResult.success) return assigneeResult;
-
- updateData.assigneeAgentId = args.assigneeAgentId;
- changes.push(
- args.assigneeAgentId ? `assignee agent → ${args.assigneeAgentId}` : 'assignee cleared',
- );
- }
- // Independent of the agent side: the member is the human owner and the
- // two assignees coexist, so touching one never clears the other.
- if (args.assigneeUserId !== undefined) {
- updateData.assigneeUserId = args.assigneeUserId;
- changes.push(
- args.assigneeUserId
- ? `assignee member → ${await resolveMemberLabel(args.assigneeUserId)}`
- : 'assignee member cleared',
+ const addLabels = await resolveLabels(args.addLabels);
+ if (addLabels.error) return { content: addLabels.error, success: false };
+ const removeLabels = await resolveLabels(args.removeLabels);
+ if (removeLabels.error) return { content: removeLabels.error, success: false };
+
+ // Labels first, in one transaction (removals apply first, so "swap Bug
+ // for Feature" ends with Feature): a label failure then writes nothing
+ // else. If a later write of this edit fails, only this label change is
+ // undone — not the whole set replaced — so a concurrent edit survives.
+ const labelDelta = { add: addLabels.ids, remove: removeLabels.ids };
+ let undoLabels = async () => {};
+ if (labelDelta.add.length > 0 || labelDelta.remove.length > 0) {
+ const labelCaller = deps.taskLabelCaller!;
+ const { addLabels: _a, identifier: _i, removeLabels: _r, ...otherArgs } = args;
+ const hasOtherEdits = Object.values(otherArgs).some((value) => value !== undefined);
+ const readLabels = async () =>
+ (await taskCaller().detail({ id: task.id })).data?.labels ?? [];
+ const before = hasOtherEdits ? await readLabels() : undefined;
+ const after = (await labelCaller.changeForTask({ ...labelDelta, taskId: task.id })).map(
+ (label) => label.id,
);
- }
- if (args.instruction !== undefined) {
- updateData.instruction = args.instruction;
- changes.push(`instruction updated`);
- }
- if (args.description !== undefined) {
- updateData.description = args.description;
- changes.push('description updated');
- }
- if (args.parentIdentifier !== undefined) {
- const parentIdentifier = args.parentIdentifier?.trim() || null;
- updateData.parentTaskId = parentIdentifier
- ? (await resolveTaskOrThrow(taskModel(), parentIdentifier)).id
- : null;
- changes.push(parentIdentifier ? `parent → ${parentIdentifier}` : 'parent cleared');
- }
- if (args.priority !== undefined) {
- updateData.priority = args.priority;
- changes.push(`priority → ${priorityLabel(args.priority)}`);
+ if (before) {
+ undoLabels = async () => {
+ try {
+ // Re-read so a teammate's change made since is not rolled over.
+ const undo = invertTaskLabelChange(before, labelDelta, after, await readLabels());
+ if (undo.add.length === 0 && undo.remove.length === 0) return;
+ await labelCaller.changeForTask({ ...undo, taskId: task.id });
+ } catch {
+ /* best-effort: the edit already reports its own failure */
+ }
+ };
+ }
}
- // Deep-merged into `config` so checkpoint / review / execution keys survive.
- const configPatch = toTaskModelConfigPatch(args);
- if (configPatch) changes.push(describeTaskModelChange(configPatch));
+ // Every failure from here on — a validation exit or a rejected write —
+ // undoes this edit's label change, so the edit never half-applies.
+ try {
+ const result = await (async () => {
+ const updateData: {
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ description?: string;
+ instruction?: string;
+ name?: string;
+ parentTaskId?: string | null;
+ priority?: number;
+ } = {};
+ const changes: string[] = [];
+ const ops: Promise<unknown>[] = [];
+
+ if (args.name !== undefined) {
+ updateData.name = args.name;
+ changes.push(`name → "${args.name}"`);
+ }
+ if (args.assigneeAgentId !== undefined) {
+ const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, task.projectId);
+ if (!assigneeResult.success) return assigneeResult;
+
+ updateData.assigneeAgentId = args.assigneeAgentId;
+ changes.push(
+ args.assigneeAgentId
+ ? `assignee agent → ${args.assigneeAgentId}`
+ : 'assignee cleared',
+ );
+ }
+ // Independent of the agent side: the member is the human owner and the
+ // two assignees coexist, so touching one never clears the other.
+ if (args.assigneeUserId !== undefined) {
+ updateData.assigneeUserId = args.assigneeUserId;
+ changes.push(
+ args.assigneeUserId
+ ? `assignee member → ${await resolveMemberLabel(args.assigneeUserId)}`
+ : 'assignee member cleared',
+ );
+ }
+ if (args.instruction !== undefined) {
+ updateData.instruction = args.instruction;
+ changes.push(`instruction updated`);
+ }
+ if (args.description !== undefined) {
+ updateData.description = args.description;
+ changes.push('description updated');
+ }
+ if (args.parentIdentifier !== undefined) {
+ const parentIdentifier = args.parentIdentifier?.trim() || null;
+ updateData.parentTaskId = parentIdentifier
+ ? (await resolveTaskOrThrow(taskModel(), parentIdentifier)).id
+ : null;
+ changes.push(parentIdentifier ? `parent → ${parentIdentifier}` : 'parent cleared');
+ }
+ if (args.priority !== undefined) {
+ updateData.priority = args.priority;
+ changes.push(`priority → ${priorityLabel(args.priority)}`);
+ }
- if (Object.keys(updateData).length > 0 || configPatch) {
- // Attribution rides the caller's context, not this payload — see
- // `AuthContext.actingAgentId`.
- ops.push(
- taskCaller().update({
- id: task.id,
- ...updateData,
- ...(configPatch && { configPatch }),
- }),
- );
- }
+ // Deep-merged into `config` so checkpoint / review / execution keys survive.
+ const configPatch = toTaskModelConfigPatch(args);
+ if (configPatch) changes.push(describeTaskModelChange(configPatch));
+
+ if (Object.keys(updateData).length > 0 || configPatch) {
+ // Attribution rides the caller's context, not this payload — see
+ // `AuthContext.actingAgentId`.
+ ops.push(
+ taskCaller().update({
+ id: task.id,
+ ...updateData,
+ ...(configPatch && { configPatch }),
+ }),
+ );
+ }
- const applyDeps = async (
- ids: string[],
- apply: (depId: string) => Promise<unknown>,
- onChange: (depIdentifier: string) => void,
- ): Promise<string | undefined> => {
- 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 applyDeps = async (
+ ids: string[],
+ apply: (depId: string) => Promise<unknown>,
+ onChange: (depIdentifier: string) => void,
+ ): Promise<string | undefined> => {
+ 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>[] = [];
- if (args.addDependencies?.length) {
- depResults.push(
- applyDeps(
- args.addDependencies,
- (depId) => taskModel().addDependency(task.id, depId),
- (depIdentifier) => changes.push(formatDependencyAdded(task.identifier, depIdentifier)),
- ),
- );
- }
- if (args.removeDependencies?.length) {
- depResults.push(
- applyDeps(
- args.removeDependencies,
- (depId) => taskModel().removeDependency(task.id, depId),
- (depIdentifier) =>
- changes.push(formatDependencyRemoved(task.identifier, depIdentifier)),
- ),
- );
- }
+ const depResults: Promise<string | undefined>[] = [];
+ if (args.addDependencies?.length) {
+ depResults.push(
+ applyDeps(
+ args.addDependencies,
+ (depId) => taskModel().addDependency(task.id, depId),
+ (depIdentifier) =>
+ changes.push(formatDependencyAdded(task.identifier, depIdentifier)),
+ ),
+ );
+ }
+ if (args.removeDependencies?.length) {
+ depResults.push(
+ applyDeps(
+ args.removeDependencies,
+ (depId) => taskModel().removeDependency(task.id, depId),
+ (depIdentifier) =>
+ changes.push(formatDependencyRemoved(task.identifier, depIdentifier)),
+ ),
+ );
+ }
- if (ops.length === 0 && depResults.length === 0) {
- return { content: 'No fields provided; nothing to update.', success: false };
- }
+ if (removeLabels.ids.length > 0) {
+ changes.push(`labels removed: ${args.removeLabels!.join(', ')}`);
+ }
+ if (addLabels.ids.length > 0) changes.push(`labels added: ${args.addLabels!.join(', ')}`);
- const [, depErrors] = await Promise.all([Promise.all(ops), Promise.all(depResults)]);
- const firstDepError = depErrors.find((e) => e);
- if (firstDepError) return { content: firstDepError, success: false };
+ const hasLabelEdit = labelDelta.add.length > 0 || labelDelta.remove.length > 0;
+ if (ops.length === 0 && depResults.length === 0 && !hasLabelEdit) {
+ return { content: 'No fields provided; nothing to update.', success: false };
+ }
- return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
+ // Settle every started write before reporting: fail-fast would return
+ // while a sibling write is still running and could commit afterwards.
+ const [opResults, depSettled] = await Promise.all([
+ Promise.allSettled(ops),
+ Promise.allSettled(depResults),
+ ]);
+ const failedOp = [...opResults, ...depSettled].find(
+ (result): result is PromiseRejectedResult => result.status === 'rejected',
+ );
+ if (failedOp) throw failedOp.reason;
+ const depErrors = depSettled.map((result) =>
+ result.status === 'fulfilled' ? result.value : undefined,
+ );
+ const firstDepError = depErrors.find((e) => e);
+ if (firstDepError) return { content: firstDepError, success: false };
+
+ return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
+ })();
+ if (!result.success) await undoLabels();
+ return result;
+ } catch (error) {
+ await undoLabels();
+ throw error;
+ }
},
listTasks: async (args: {
assigneeAgentId?: string;
+ labels?: string[];
limit?: number;
offset?: number;
parentIdentifier?: string;
@@ -503,6 +617,11 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
});
try {
+ const labelFilter = await resolveLabels(args.labels, true);
+ if (labelFilter.error) return { content: labelFilter.error, success: false };
+ if (labelFilter.ids.length > 0) {
+ normalized.query.filter = { label: { operator: 'is', values: labelFilter.ids } };
+ }
const result = await taskCaller().list(normalized.query);
return {
@@ -1027,6 +1146,7 @@ export const taskRuntime: ServerRuntimeRegistration = {
// reassignment activity). Server-side only by contract — it must never
// reach the router through a client-supplied field.
taskCaller: taskRouter.createCaller({ actingAgentId: agentId, userId }),
+ taskLabelCaller: taskLabelRouter.createCaller({ userId }),
} as TaskRuntimeDeps;
let modelsPromise: Promise<void> | undefined;
@@ -1048,6 +1168,7 @@ export const taskRuntime: ServerRuntimeRegistration = {
userId,
workspaceId: wsId,
});
+ deps.taskLabelCaller = taskLabelRouter.createCaller({ userId, workspaceId: wsId });
})());
const baseRuntime = createTaskRuntime(deps);
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index ebc4cc693c8..00b43b98b02 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2658,6 +2658,15 @@
"taskIntent.openCreated": "Open",
"taskIntent.reviewStep": "Confirm what I understood",
"taskIntent.skipQuestions": "Skip and create",
+ "taskLabel.add": "Add labels",
+ "taskLabel.anyInGroup": "Any {{name}}",
+ "taskLabel.createFailed": "Failed to create label",
+ "taskLabel.createNamed": "Create label “{{name}}”",
+ "taskLabel.empty": "No labels yet. Type a name to create one.",
+ "taskLabel.label": "Labels",
+ "taskLabel.noLabel": "No label",
+ "taskLabel.noLabels": "No labels",
+ "taskLabel.searchPlaceholder": "Search or create labels…",
"taskList.activeTasks": "Active Tasks",
"taskList.all": "All tasks",
"taskList.archived": "Archived",
@@ -2780,6 +2789,7 @@
"taskList.filter.field.createdAt": "Created",
"taskList.filter.field.creator": "Creator",
"taskList.filter.field.dates": "Dates",
+ "taskList.filter.field.label": "Label",
"taskList.filter.field.priority": "Priority",
"taskList.filter.field.project": "Project",
"taskList.filter.field.status": "Status",
@@ -2816,6 +2826,7 @@
"taskList.form.subGrouping": "Sub-grouping",
"taskList.groupBy.assignee": "Agent",
"taskList.groupBy.heartbeat": "Heartbeat",
+ "taskList.groupBy.labelGroup": "Label: {{name}}",
"taskList.groupBy.member": "Assignee",
"taskList.groupBy.none": "No grouping",
"taskList.groupBy.priority": "Priority",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 8f6f300bcaf..f9ac31572ea 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2052,6 +2052,33 @@
"tab.uploadZip": "Upload Zip",
"tab.uploadZip.desc": "Upload a local .zip or .skill file",
"tab.usage": "Usage",
+ "taskLabels.actions.addToGroup": "Add label to group",
+ "taskLabels.actions.create": "New label",
+ "taskLabels.actions.createGroup": "New group",
+ "taskLabels.actions.more": "More actions",
+ "taskLabels.delete.desc": "Removes this label from every task that carries it, including {{count}} unarchived tasks you can see. This cannot be undone.",
+ "taskLabels.delete.groupDesc": "Deletes the group and every label in it, and removes them from tasks. This cannot be undone.",
+ "taskLabels.delete.title": "Delete “{{name}}”?",
+ "taskLabels.empty": "No task labels yet. Create one to organize your tasks.",
+ "taskLabels.filterEmpty": "No labels match your search",
+ "taskLabels.filterPlaceholder": "Filter labels…",
+ "taskLabels.form.color": "Color",
+ "taskLabels.form.createGroupTitle": "New label group",
+ "taskLabels.form.createTitle": "New label",
+ "taskLabels.form.duplicateName": "A label with this name already exists",
+ "taskLabels.form.editGroupTitle": "Edit label group",
+ "taskLabels.form.editTitle": "Edit label",
+ "taskLabels.form.group": "Group",
+ "taskLabels.form.groupConflict": "Some tasks already carry another label from this group. Remove it from them first.",
+ "taskLabels.form.groupNamePlaceholder": "e.g. Type",
+ "taskLabels.form.name": "Name",
+ "taskLabels.form.namePlaceholder": "e.g. Bug",
+ "taskLabels.form.noGroup": "No group",
+ "taskLabels.groupBadge": "Group",
+ "taskLabels.loadFailed": "Failed to load labels",
+ "taskLabels.tabs.agent": "Agent labels",
+ "taskLabels.tabs.task": "Task labels",
+ "taskLabels.usage": "{{count}} tasks",
"tools.activation.action.auto": "Auto",
"tools.activation.action.disable": "Disable",
"tools.activation.action.pin": "Pin",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index bd8c609d09c..7167f5fb7b3 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2658,6 +2658,15 @@
"taskIntent.openCreated": "打开",
"taskIntent.reviewStep": "先确认一下我的理解",
"taskIntent.skipQuestions": "跳过,直接创建",
+ "taskLabel.add": "添加标签",
+ "taskLabel.anyInGroup": "任意{{name}}",
+ "taskLabel.createFailed": "创建标签失败",
+ "taskLabel.createNamed": "创建标签「{{name}}」",
+ "taskLabel.empty": "还没有标签,输入名称即可创建",
+ "taskLabel.label": "标签",
+ "taskLabel.noLabel": "无标签",
+ "taskLabel.noLabels": "无标签",
+ "taskLabel.searchPlaceholder": "搜索或创建标签…",
"taskList.activeTasks": "进行中的任务",
"taskList.all": "全部任务",
"taskList.archived": "已归档",
@@ -2780,6 +2789,7 @@
"taskList.filter.field.createdAt": "创建时间",
"taskList.filter.field.creator": "创建者",
"taskList.filter.field.dates": "日期",
+ "taskList.filter.field.label": "标签",
"taskList.filter.field.priority": "优先级",
"taskList.filter.field.project": "项目",
"taskList.filter.field.status": "状态",
@@ -2816,6 +2826,7 @@
"taskList.form.subGrouping": "子分组",
"taskList.groupBy.assignee": "助理",
"taskList.groupBy.heartbeat": "心跳",
+ "taskList.groupBy.labelGroup": "标签:{{name}}",
"taskList.groupBy.member": "负责人",
"taskList.groupBy.none": "不分组",
"taskList.groupBy.priority": "优先级",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index f6d4584ec8c..2178830b356 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2052,6 +2052,33 @@
"tab.uploadZip": "上传 Zip",
"tab.uploadZip.desc": "上传本地 .zip 或 .skill 文件",
"tab.usage": "用量",
+ "taskLabels.actions.addToGroup": "在组内添加标签",
+ "taskLabels.actions.create": "新建标签",
+ "taskLabels.actions.createGroup": "新建标签组",
+ "taskLabels.actions.more": "更多操作",
+ "taskLabels.delete.desc": "将从所有带有此标签的任务上移除它,其中你可见的未归档任务有 {{count}} 个。此操作无法撤销。",
+ "taskLabels.delete.groupDesc": "将删除该标签组及组内所有标签,并从任务上移除,且无法恢复。",
+ "taskLabels.delete.title": "删除「{{name}}」?",
+ "taskLabels.empty": "还没有任务标签,新建一个来整理任务吧",
+ "taskLabels.filterEmpty": "没有匹配的标签",
+ "taskLabels.filterPlaceholder": "筛选标签…",
+ "taskLabels.form.color": "颜色",
+ "taskLabels.form.createGroupTitle": "新建标签组",
+ "taskLabels.form.createTitle": "新建标签",
+ "taskLabels.form.duplicateName": "已存在同名标签",
+ "taskLabels.form.editGroupTitle": "编辑标签组",
+ "taskLabels.form.editTitle": "编辑标签",
+ "taskLabels.form.group": "所属标签组",
+ "taskLabels.form.groupConflict": "部分任务已带有该组的其他标签,请先从这些任务上移除。",
+ "taskLabels.form.groupNamePlaceholder": "例如:类型",
+ "taskLabels.form.name": "名称",
+ "taskLabels.form.namePlaceholder": "例如:Bug",
+ "taskLabels.form.noGroup": "不分组",
+ "taskLabels.groupBadge": "标签组",
+ "taskLabels.loadFailed": "标签加载失败",
+ "taskLabels.tabs.agent": "助理标签",
+ "taskLabels.tabs.task": "任务标签",
+ "taskLabels.usage": "{{count}} 个任务",
"tools.activation.action.auto": "自动",
"tools.activation.action.disable": "禁用",
"tools.activation.action.pin": "固定",
diff --git a/packages/builtin-skills/src/task/SKILL.md b/packages/builtin-skills/src/task/SKILL.md
index c20bf7d231b..60102711413 100644
--- a/packages/builtin-skills/src/task/SKILL.md
+++ b/packages/builtin-skills/src/task/SKILL.md
@@ -3,13 +3,13 @@ You are executing a task within the LobeHub task system. Use the `lh task` CLI v
# Task Lifecycle
-| Command | Description |
-| ------------------------------- | ----------------------------------------------------- |
-| `lh task view <id>` | View task details, instruction, documents, activities |
-| `lh task edit <id>` | Update task name, instruction, status, priority |
-| `lh task complete <id>` | Mark task as completed |
-| `lh task comment <id> -m "..."` | Add a progress comment |
-| `lh task tree <id>` | View subtask tree with dependencies |
+| Command | Description |
+| ------------------------------- | ------------------------------------------------------- |
+| `lh task view <id>` | View task details, instruction, documents, activities |
+| `lh task edit <id>` | Update task name, instruction, status, priority, labels |
+| `lh task complete <id>` | Mark task as completed |
+| `lh task comment <id> -m "..."` | Add a progress comment |
+| `lh task tree <id>` | View subtask tree with dependencies |
# Working with Subtasks
diff --git a/packages/builtin-skills/src/task/references/commands.md b/packages/builtin-skills/src/task/references/commands.md
index a9725c4fd3a..0d36afecea4 100644
--- a/packages/builtin-skills/src/task/references/commands.md
+++ b/packages/builtin-skills/src/task/references/commands.md
@@ -2,14 +2,15 @@
## Core Commands
-- `lh task list [--status <status>] [--root] [--parent <id>] [--agent <id>] [-L <limit>] [--tree]` - List tasks
+- `lh task list [--status <status>] [--root] [--parent <id>] [--agent <id>] [--label <name>] [--unlabeled] [-L <limit>] [--tree]` - List tasks
- `--status`: pending, running, paused, completed, failed, canceled
- `--root`: Only root tasks (no parent)
+ - `--label`: Tasks carrying any of these labels (repeatable / comma-separated; a label group name matches any label in it)
- `--tree`: Display as tree structure
- `lh task view <id>` - View task details (instruction, documents, activities)
-- `lh task create -i <instruction> [-n <name>] [--agent <id>] [--parent <id>] [--priority <0-4>]` - Create task
+- `lh task create -i <instruction> [-n <name>] [--agent <id>] [--parent <id>] [--priority <0-4>] [--label <name>]` - Create task
- Priority: 0=none, 1=urgent, 2=high, 3=normal, 4=low
-- `lh task edit <id> [-n <name>] [-i <instruction>] [--status <status>] [--priority <0-4>] [--agent <id>]` - Update task
+- `lh task edit <id> [-n <name>] [-i <instruction>] [--status <status>] [--priority <0-4>] [--agent <id>] [--label <name>] [--remove-label <name>]` - Update task
- `lh task delete <id> [--yes]` - Delete task
- `lh task clear [--yes]` - Delete all tasks
- `lh task tree <id>` - Show subtask tree with dependencies
@@ -57,6 +58,15 @@
- `lh task dep rm <taskId> <dependsOnId>` - Remove dependency
- `lh task dep list <taskId>` - List dependencies
+## Label Commands
+
+Labels are shared by the workspace. `--label` only takes existing names (`Bug`, or `Type/Bug` for a label in a group); an unknown name fails with suggestions instead of creating a label. A task carries at most one label per label group — adding another one from the same group replaces it.
+
+- `lh task label list` - List labels and label groups with task counts
+- `lh task label create <name> [--color <hex>] [--group] [--parent <group>]` - Create a label (or a group with `--group`)
+- `lh task label edit <label> [-n <name>] [--color <hex>] [--parent <group|none>]` - Rename, recolor or move a label
+- `lh task label delete <label> [--yes]` - Delete a label (a group deletes its labels too)
+
## Topic Commands
- `lh task topic list <id>` - List topics for task
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index 0733067b02e..70a92ea0457 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -54,6 +54,8 @@ import type {
UpdateTaskCommentParams,
} from '../../types';
import { TaskApiName } from '../../types';
+import { applyTaskLabelDelta, resolveLabelIdsOrThrow } from './labelIds';
+import { settleAll } from './settleAll';
const log = debug('lobe-task:executor');
@@ -207,6 +209,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
instruction: string;
assigneeAgentId?: string;
assigneeUserId?: string;
+ labels?: string[];
model?: string;
name: string;
parentIdentifier?: string;
@@ -235,12 +238,14 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
// 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 labelIds = await resolveLabelIdsOrThrow(params.labels);
const task = await getTaskStoreState().createTask({
assigneeAgentId: assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),
assigneeUserId,
config: toCreateTaskModelConfig(params),
createdByAgentId: ctx?.agentId,
instruction: params.instruction,
+ labelIds, // attached in the same request; the task is rolled back on failure
name: params.name,
parentTaskId: parent?.id,
priority: params.priority,
@@ -261,6 +266,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
id: task.id,
identifier: task.identifier,
instruction: params.instruction,
+ labels: task.labels ?? [],
name: task.name,
parentLabel: parent?.identifier,
parentTaskId: parent?.id,
@@ -417,6 +423,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
editTask = async (
params: {
addDependencies?: string[];
+ addLabels?: string[];
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
description?: string;
@@ -428,11 +435,17 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
priority?: number;
provider?: string | null;
removeDependencies?: string[];
+ removeLabels?: string[];
},
ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
+ let undoLabels: (() => Promise<void>) | undefined;
try {
log('[TaskExecutor] editTask - params:', params);
+ const [add, remove] = await Promise.all([
+ resolveLabelIdsOrThrow(params.addLabels),
+ resolveLabelIdsOrThrow(params.removeLabels),
+ ]);
const { addDependencies, removeDependencies } = params;
const target = (await taskService.find(params.identifier)).data;
@@ -440,6 +453,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const store = getTaskStoreState();
const changes: string[] = [];
const ops: Promise<unknown>[] = [];
+ // Labels first: a label failure then writes nothing else, and a later
+ // failure undoes just this label change (see the catch below).
+ const { addLabels: _a, identifier: _i, removeLabels: _r, ...otherEdits } = params;
+ const hasOtherEdits = Object.values(otherEdits).some((value) => value !== undefined);
+ undoLabels = await applyTaskLabelDelta(identifier, { add, remove }, hasOtherEdits);
const updateData: {
description?: string;
@@ -534,8 +552,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
};
if (addDependencies?.length) await applyDependencies(addDependencies, false);
if (removeDependencies?.length) await applyDependencies(removeDependencies, true);
+ if (remove.length || add.length) ops.push(store.refreshTaskList());
+ if (remove.length) changes.push(`labels removed: ${params.removeLabels!.join(', ')}`);
+ if (add.length) changes.push(`labels added: ${params.addLabels!.join(', ')}`);
- await Promise.all(ops);
+ await settleAll(ops);
return {
content: formatTaskEdited(`${target.identifier} (id: ${target.id})`, changes),
@@ -543,6 +564,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
success: true,
};
} catch (error) {
+ await undoLabels?.();
log('[TaskExecutor] editTask - error:', error);
const message = error instanceof Error ? error.message : 'Failed to edit task';
return {
@@ -870,6 +892,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
listTasks = async (
params: {
assigneeAgentId?: string;
+ labels?: string[];
limit?: number;
offset?: number;
parentIdentifier?: string;
@@ -886,6 +909,9 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
defaultScope: ctx?.scope === 'task' ? 'allAgents' : 'currentAgent',
});
+ const labelIds = await resolveLabelIdsOrThrow(params.labels, true);
+ if (labelIds.length)
+ normalized.query.filter = { label: { operator: 'is', values: labelIds } };
const result = await getTaskStoreState().fetchTaskList(normalized.query);
const tasks = result.data ?? [];
diff --git a/packages/builtin-tool-task/src/client/executor/labelIds.test.ts b/packages/builtin-tool-task/src/client/executor/labelIds.test.ts
new file mode 100644
index 00000000000..16f1797acdd
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/executor/labelIds.test.ts
@@ -0,0 +1,57 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { taskService } from '@/services/task';
+import { taskLabelService } from '@/services/taskLabel';
+
+import { applyTaskLabelDelta } from './labelIds';
+
+vi.mock('@/services/task', () => ({ taskService: { getDetail: vi.fn() } }));
+vi.mock('@/services/taskLabel', () => ({
+ taskLabelService: { changeForTask: vi.fn(), list: vi.fn() },
+}));
+
+const ref = (id: string) => ({ color: null, id, name: id, parentId: null });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(taskLabelService.changeForTask).mockResolvedValue([]);
+});
+
+describe('applyTaskLabelDelta', () => {
+ it('applies the delta and undoes only it, keeping concurrent changes', async () => {
+ vi.mocked(taskService.getDetail)
+ .mockResolvedValueOnce({ data: { labels: [ref('bug'), ref('fe')] } } as any)
+ .mockResolvedValueOnce({ data: { labels: [ref('feat'), ref('other')] } } as any);
+ vi.mocked(taskLabelService.changeForTask).mockResolvedValueOnce([
+ ref('feat'),
+ ref('other'),
+ ] as any);
+
+ const undo = await applyTaskLabelDelta('T-1', { add: ['feat'], remove: ['fe'] }, true);
+ await undo();
+
+ expect(taskLabelService.changeForTask).toHaveBeenNthCalledWith(1, 'T-1', {
+ add: ['feat'],
+ remove: ['fe'],
+ });
+ expect(taskLabelService.changeForTask).toHaveBeenNthCalledWith(2, 'T-1', {
+ add: ['bug', 'fe'],
+ remove: ['feat'],
+ });
+ });
+
+ it('skips the snapshot and the undo when nothing else follows', async () => {
+ vi.mocked(taskLabelService.changeForTask).mockResolvedValueOnce([ref('feat')] as any);
+
+ const undo = await applyTaskLabelDelta('T-1', { add: ['feat'], remove: [] }, false);
+ await undo();
+
+ expect(taskService.getDetail).not.toHaveBeenCalled();
+ expect(taskLabelService.changeForTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('writes nothing for an empty delta', async () => {
+ await applyTaskLabelDelta('T-1', { add: [], remove: [] }, true);
+ expect(taskLabelService.changeForTask).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/builtin-tool-task/src/client/executor/labelIds.ts b/packages/builtin-tool-task/src/client/executor/labelIds.ts
new file mode 100644
index 00000000000..ec73eaeb118
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/executor/labelIds.ts
@@ -0,0 +1,48 @@
+import { invertTaskLabelChange } from '@lobechat/types';
+
+import { taskService } from '@/services/task';
+import { taskLabelService } from '@/services/taskLabel';
+
+import { resolveToolLabelIds } from '../../labels';
+
+/** Label names → ids against the registry; throws a tool-readable message. */
+export const resolveLabelIdsOrThrow = async (
+ names: string[] | undefined,
+ allowGroups = false,
+): Promise<string[]> => {
+ if (!names?.some((name) => name.trim())) return [];
+ const result = resolveToolLabelIds(await taskLabelService.list(), names, { allowGroups });
+ if (result.error) throw new Error(result.error);
+ return result.ids;
+};
+
+const noop = async () => {};
+
+/**
+ * Apply a label delta ahead of a task's other edits, so a label failure stops
+ * the edit before anything else is written. Returns an undo that reverses only
+ * this delta (never a full-set replacement, so a teammate's concurrent label
+ * change survives) for when a later write of the same edit fails. Pass
+ * `withUndo: false` when nothing else follows, to skip the snapshot read.
+ */
+export const applyTaskLabelDelta = async (
+ taskId: string,
+ delta: { add: string[]; remove: string[] },
+ withUndo: boolean,
+): Promise<() => Promise<void>> => {
+ if (delta.add.length === 0 && delta.remove.length === 0) return noop;
+ const readLabels = async () => (await taskService.getDetail(taskId)).data?.labels ?? [];
+ const before = withUndo ? await readLabels() : undefined;
+ const after = (await taskLabelService.changeForTask(taskId, delta)).map((label) => label.id);
+ if (!before) return noop;
+ return async () => {
+ try {
+ // Re-read so a teammate's change made since is not rolled over.
+ const undo = invertTaskLabelChange(before, delta, after, await readLabels());
+ if (undo.add.length === 0 && undo.remove.length === 0) return;
+ await taskLabelService.changeForTask(taskId, undo);
+ } catch {
+ /* best-effort: the edit already reports its own failure */
+ }
+ };
+};
diff --git a/packages/builtin-tool-task/src/client/executor/settleAll.test.ts b/packages/builtin-tool-task/src/client/executor/settleAll.test.ts
new file mode 100644
index 00000000000..90848f7c10f
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/executor/settleAll.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { settleAll } from './settleAll';
+
+describe('settleAll', () => {
+ it('waits for every operation before rethrowing the first failure', async () => {
+ let slowDone = false;
+ const slow = new Promise<void>((resolve) =>
+ setTimeout(() => {
+ slowDone = true;
+ resolve();
+ }, 20),
+ );
+
+ await expect(
+ settleAll([Promise.reject(new Error('label write failed')), slow]),
+ ).rejects.toThrow('label write failed');
+ expect(slowDone).toBe(true);
+ });
+
+ it('resolves when every operation succeeds', async () => {
+ await expect(settleAll([Promise.resolve(1), Promise.resolve(2)])).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tool-task/src/client/executor/settleAll.ts b/packages/builtin-tool-task/src/client/executor/settleAll.ts
new file mode 100644
index 00000000000..ecdac893773
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/executor/settleAll.ts
@@ -0,0 +1,13 @@
+/**
+ * Wait for every started operation to finish, then rethrow the first failure.
+ * Unlike `Promise.all`, a rejection does not return early while sibling writes
+ * are still running (and could commit after the caller reported failure), and
+ * no rejection is left unhandled.
+ */
+export const settleAll = async (ops: Promise<unknown>[]): Promise<void> => {
+ const results = await Promise.allSettled(ops);
+ const failed = results.find((result): result is PromiseRejectedResult => {
+ return result.status === 'rejected';
+ });
+ if (failed) throw failed.reason;
+};
diff --git a/packages/builtin-tool-task/src/index.ts b/packages/builtin-tool-task/src/index.ts
index 63f56857385..11e13af1c57 100644
--- a/packages/builtin-tool-task/src/index.ts
+++ b/packages/builtin-tool-task/src/index.ts
@@ -6,6 +6,7 @@ export {
TASK_STATUSES,
UNFINISHED_TASK_STATUSES,
} from './constants';
+export { resolveToolLabelIds, type ToolLabelResolution } from './labels';
export {
DEFAULT_LIST_TASK_LIMIT,
normalizeListTasksParams,
diff --git a/packages/builtin-tool-task/src/labels.test.ts b/packages/builtin-tool-task/src/labels.test.ts
new file mode 100644
index 00000000000..6b5f21ba09e
--- /dev/null
+++ b/packages/builtin-tool-task/src/labels.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveToolLabelIds } from './labels';
+
+const registry = [
+ { id: 'g', isGroup: true, name: 'Type', parentId: null },
+ { id: 'bug', isGroup: false, name: 'Bug', parentId: 'g' },
+ { id: 'fe', isGroup: false, name: 'Frontend', parentId: null },
+];
+
+describe('resolveToolLabelIds', () => {
+ it('resolves names and ignores blanks', () => {
+ expect(resolveToolLabelIds(registry, ['bug', ' ', 'Frontend'])).toEqual({ ids: ['bug', 'fe'] });
+ expect(resolveToolLabelIds(registry, undefined)).toEqual({ ids: [] });
+ });
+
+ it('accepts group names only for filters', () => {
+ expect(resolveToolLabelIds(registry, ['Type'], { allowGroups: true })).toEqual({ ids: ['g'] });
+ expect(resolveToolLabelIds(registry, ['Type']).error).toContain('is a label group');
+ });
+
+ it('explains unknown names without creating anything', () => {
+ expect(resolveToolLabelIds(registry, ['Frontnd']).error).toContain('did you mean: Frontend');
+ expect(resolveToolLabelIds([], ['x']).error).toContain('no task labels yet');
+ });
+});
diff --git a/packages/builtin-tool-task/src/labels.ts b/packages/builtin-tool-task/src/labels.ts
new file mode 100644
index 00000000000..7c1750f6155
--- /dev/null
+++ b/packages/builtin-tool-task/src/labels.ts
@@ -0,0 +1,53 @@
+import {
+ describeUnresolvedTaskLabels,
+ resolveTaskLabelRefs,
+ type TaskLabelRegistryEntry,
+} from '@lobechat/types';
+
+/** `error` is set when any name is unknown; `ids` is then empty. */
+export interface ToolLabelResolution {
+ error?: string;
+ ids: string[];
+}
+
+/**
+ * Resolve label names an agent passed (`Bug`, `Type/Bug`) against the scope's
+ * registry. Unknown names are an error that lists close existing labels —
+ * tools never create labels, so a hallucinated or misspelled name cannot grow
+ * the shared registry.
+ *
+ * `allowGroups` is for filters: a group name there means "any label of the
+ * group", while assignment must name one concrete label.
+ */
+export const resolveToolLabelIds = (
+ registry: TaskLabelRegistryEntry[],
+ names: string[] | undefined,
+ { allowGroups = false }: { allowGroups?: boolean } = {},
+): ToolLabelResolution => {
+ const inputs = (names ?? []).map((name) => name.trim()).filter(Boolean);
+ if (inputs.length === 0) return { ids: [] };
+
+ const groupIds: string[] = [];
+ const labelNames: string[] = [];
+ for (const input of inputs) {
+ const group = allowGroups
+ ? registry.find((label) => label.isGroup && label.name.toLowerCase() === input.toLowerCase())
+ : undefined;
+ if (group) groupIds.push(group.id);
+ else labelNames.push(input);
+ }
+
+ const { ids, unresolved } = resolveTaskLabelRefs(registry, labelNames);
+ if (unresolved.length > 0) {
+ const available = registry.filter((label) => !label.isGroup).length;
+ return {
+ ids: [],
+ error: `${describeUnresolvedTaskLabels(unresolved)}\n${
+ available > 0
+ ? 'Use only existing label names; labels are created by the user in task settings.'
+ : 'This workspace has no task labels yet; omit labels.'
+ }`,
+ };
+ }
+ return { ids: [...new Set([...groupIds, ...ids])] };
+};
diff --git a/packages/builtin-tool-task/src/listTasks.ts b/packages/builtin-tool-task/src/listTasks.ts
index 40738df7063..26d515f1212 100644
--- a/packages/builtin-tool-task/src/listTasks.ts
+++ b/packages/builtin-tool-task/src/listTasks.ts
@@ -7,6 +7,8 @@ const MAX_LIST_TASK_LIMIT = 100;
export interface ListTasksParams {
assigneeAgentId?: string;
+ /** Label (or label group) names; a task matches when it carries any of them. */
+ labels?: string[];
limit?: number;
offset?: number;
parentIdentifier?: string;
@@ -16,6 +18,8 @@ export interface ListTasksParams {
export interface TaskListQuery {
assigneeAgentId?: string;
+ /** Set by the runtime once `labels` are resolved to ids. */
+ filter?: { label?: { operator: 'is'; values: string[] } };
limit: number;
offset: number;
parentIdentifier?: string;
@@ -29,6 +33,7 @@ export interface TaskListDisplayFilters {
isDefaultScope: boolean;
isForAllAgents?: boolean;
isForCurrentAgent?: boolean;
+ labels?: string[];
parentIdentifier?: string;
priorities?: number[];
statuses?: TaskStatus[];
@@ -47,6 +52,7 @@ const hasExplicitFilter = (params: ListTasksParams): boolean =>
params.parentIdentifier ||
params.statuses?.length ||
params.priorities?.length ||
+ params.labels?.length ||
params.assigneeAgentId,
);
@@ -77,6 +83,7 @@ export const normalizeListTasksParams = (
isDefaultScope,
isForAllAgents: isDefaultScope && defaultScope === 'allAgents',
isForCurrentAgent: shouldUseCurrentAgent && Boolean(currentAgentId),
+ labels: normalizeOptionalFilterValues(params.labels),
parentIdentifier: params.parentIdentifier,
priorities,
statuses,
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index 2ecc7692918..987e2e2a957 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -30,6 +30,12 @@ export const TaskManifest: BuiltinToolManifest = {
"Optional workspace member (user ID) to set as the task's human owner. Coexists with assigneeAgentId — the agent executes the task, the member owns the outcome. Resolve the ID with listWorkspaceMembers first; never guess it.",
type: 'string',
},
+ labels: {
+ description:
+ 'Optional existing task label names to attach (e.g. ["Bug", "Frontend"]; a grouped label may be written "Type/Bug"). Only use labels that already exist — unknown names fail with suggestions and nothing is created. A task carries at most one label per label group.',
+ items: { type: 'string' },
+ type: 'array',
+ },
model: {
description:
'Optional model ID this task runs with (e.g. "deepseek-chat"), instead of the assignee agent\'s default. Only set it when the user asks for a specific model. Omit to pin the assignee agent\'s current model.',
@@ -92,6 +98,12 @@ export const TaskManifest: BuiltinToolManifest = {
"Optional workspace member (user ID) to set as the task's human owner (coexists with assigneeAgentId). Resolve the ID with listWorkspaceMembers first.",
type: 'string',
},
+ labels: {
+ description:
+ 'Optional existing task label names to attach (same rules as createTask.labels).',
+ items: { type: 'string' },
+ type: 'array',
+ },
model: {
description:
'Optional model ID this task runs with (e.g. "deepseek-chat"), instead of the assignee agent\'s default. Only set it when the user asks for a specific model. Omit to pin the assignee agent\'s current model.',
@@ -147,6 +159,12 @@ export const TaskManifest: BuiltinToolManifest = {
'Restrict to tasks assigned to this agent. When omitted, no assignee filter is applied unless listTasks is called without any filters in an agent conversation, which defaults to the current agent.',
type: 'string',
},
+ labels: {
+ description:
+ 'Only tasks carrying any of these existing label names. A label group name (e.g. "Type") matches any label in that group.',
+ items: { type: 'string' },
+ type: 'array',
+ },
limit: { description: `Max 1-100. Default ${DEFAULT_LIST_TASK_LIMIT}.`, type: 'number' },
offset: { description: 'Pagination offset.', type: 'number' },
parentIdentifier: {
@@ -267,7 +285,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
{
description:
- "Edit a task's fields (name, description, instruction, priority, model/provider), assignee (agent or workspace member), parent, or dependencies (batched). Status changes go through updateTaskStatus; schedule configuration goes through setTaskSchedule.",
+ "Edit a task's fields (name, description, instruction, priority, model/provider), assignee (agent or workspace member), parent, labels, or dependencies (batched). Status changes go through updateTaskStatus; schedule configuration goes through setTaskSchedule.",
name: TaskApiName.editTask,
parameters: {
properties: {
@@ -277,6 +295,12 @@ export const TaskManifest: BuiltinToolManifest = {
items: { type: 'string' },
type: 'array',
},
+ addLabels: {
+ description:
+ 'Existing task label names to add (e.g. ["Bug"]; "Type/Bug" also works). Adding a label from a label group replaces the task\'s current label of that group. Unknown names fail with suggestions; labels are never created.',
+ items: { type: 'string' },
+ type: 'array',
+ },
assigneeAgentId: {
description:
'Assign the task to this agent ID (the executing agent; independent of the human owner). Pass null to clear the agent assignee.',
@@ -330,6 +354,11 @@ export const TaskManifest: BuiltinToolManifest = {
items: { type: 'string' },
type: 'array',
},
+ removeLabels: {
+ description: 'Task label names to remove from the task.',
+ items: { type: 'string' },
+ type: 'array',
+ },
},
required: ['identifier'],
type: 'object',
diff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.ts
index 312949e32c1..fb8d5e3c7d7 100644
--- a/packages/builtin-tool-task/src/types.ts
+++ b/packages/builtin-tool-task/src/types.ts
@@ -59,6 +59,8 @@ export interface CreateTaskParams {
/** Workspace member (user id) who owns the task outcome; coexists with `assigneeAgentId` (the executing agent). */
assigneeUserId?: string;
instruction: string;
+ /** Existing task label names to attach; unknown names fail, nothing is created. */
+ labels?: string[];
/** Model the task runs with; omitted pins the assignee agent's current model. */
model?: string;
name: string;
@@ -144,6 +146,8 @@ export interface CreateTasksState {
export interface ListTasksParams {
assigneeAgentId?: string;
+ /** Label or label group names; matches tasks carrying any of them. */
+ labels?: string[];
limit?: number;
offset?: number;
parentIdentifier?: string;
@@ -224,6 +228,8 @@ export interface DeleteTaskCommentState {
export interface EditTaskParams {
addDependencies?: string[];
+ /** Existing label names to add; a grouped label replaces its sibling. */
+ addLabels?: string[];
assigneeAgentId?: string | null;
/** Workspace member (user id) to assign the task to; `null` clears the human assignee. */
assigneeUserId?: string | null;
@@ -238,6 +244,7 @@ export interface EditTaskParams {
/** Provider for the task model; `null` clears it. */
provider?: string | null;
removeDependencies?: string[];
+ removeLabels?: string[];
}
export interface EditTaskState {
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index e1a166de898..6694ec89b7f 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -310,6 +310,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
storageOverage: 'blocked',
subscription: 'blocked',
task: rw('agent:read', 'agent:write'),
+ taskLabel: rw('agent:read', 'agent:write'),
taskTemplate: rw('agent:read', 'agent:write'),
thread: rw('chat:read', 'chat:write'),
topUp: 'blocked',
diff --git a/packages/database/src/models/__tests__/task.labels.test.ts b/packages/database/src/models/__tests__/task.labels.test.ts
new file mode 100644
index 00000000000..411baeafdde
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.labels.test.ts
@@ -0,0 +1,106 @@
+// @vitest-environment node
+import { TASK_LIST_FILTER_NONE } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+import { TaskLabelModel } from '../taskLabel';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-labels-list-user';
+const workspaceId = 'task-labels-list-ws';
+
+const tasks = new TaskModel(serverDB, userId, workspaceId);
+const labels = new TaskLabelModel(serverDB, userId, workspaceId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+ await serverDB.insert(users).values([{ id: userId }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+});
+
+const seed = async () => {
+ const type = await labels.create({ isGroup: true, name: 'Type' });
+ const bug = await labels.create({ name: 'Bug', parentId: type.id, sortOrder: 1 });
+ const feature = await labels.create({ name: 'Feature', parentId: type.id, sortOrder: 2 });
+ const frontend = await labels.create({ name: 'Frontend' });
+ const t1 = await tasks.create({ instruction: 'bug + fe', name: 't1' });
+ const t2 = await tasks.create({ instruction: 'feature', name: 't2' });
+ const t3 = await tasks.create({ instruction: 'none', name: 't3' });
+ await labels.addTaskLabels(t1.id, [bug.id, frontend.id]);
+ await labels.addTaskLabels(t2.id, [feature.id]);
+ return { bug, feature, frontend, t1, t2, t3, type };
+};
+
+const names = (rows: { name: string | null }[]) => rows.map((r) => r.name).sort();
+
+describe('task list label filter', () => {
+ it('matches labels, label groups and "no labels"', async () => {
+ const { bug, frontend, type } = await seed();
+ const list = async (values: string[], operator: 'is' | 'isNot' = 'is') =>
+ names((await tasks.list({ filter: { label: { operator, values } } })).tasks);
+
+ expect(await list([bug.id])).toEqual(['t1']);
+ expect(await list([type.id])).toEqual(['t1', 't2']);
+ expect(await list([TASK_LIST_FILTER_NONE])).toEqual(['t3']);
+ expect(await list([frontend.id, TASK_LIST_FILTER_NONE])).toEqual(['t1', 't3']);
+ expect(await list([frontend.id], 'isNot')).toEqual(['t2', 't3']);
+ expect(await list([TASK_LIST_FILTER_NONE], 'isNot')).toEqual(['t1', 't2']);
+ // a malformed id matches nothing instead of failing the query
+ expect(await list(['not-a-uuid'])).toEqual([]);
+ });
+
+ it('attaches labels to list and grouped rows', async () => {
+ const { t1 } = await seed();
+ const { tasks: rows } = await tasks.list();
+ // registry order: sortOrder, then name
+ expect(rows.find((t) => t.id === t1.id)?.labels?.map((l) => l.name)).toEqual([
+ 'Frontend',
+ 'Bug',
+ ]);
+ expect(rows.find((t) => t.name === 't3')?.labels).toEqual([]);
+ });
+});
+
+describe('task board grouped by label group', () => {
+ it('puts each task in its group label column, then "no label"', async () => {
+ const { bug, feature, type } = await seed();
+ const groups = await tasks.groupList({ groupBy: 'label', labelGroupId: type.id });
+
+ expect(groups.map((g) => g.key)).toEqual([
+ `label:${bug.id}`,
+ `label:${feature.id}`,
+ 'label:none',
+ ]);
+ expect(groups.map((g) => g.labelId)).toEqual([bug.id, feature.id, null]);
+ expect(groups.map((g) => names(g.tasks))).toEqual([['t1'], ['t2'], ['t3']]);
+ expect(groups.map((g) => g.total)).toEqual([1, 1, 1]);
+ expect(groups[0].tasks[0].labels?.map((l) => l.name)).toEqual(['Frontend', 'Bug']);
+ });
+
+ it('keeps empty label columns as drop targets', async () => {
+ const { type } = await seed();
+ const chore = await labels.create({ name: 'Chore', parentId: type.id, sortOrder: 3 });
+ const groups = await tasks.groupList({ groupBy: 'label', labelGroupId: type.id });
+
+ expect(groups.find((g) => g.labelId === chore.id)).toMatchObject({ tasks: [], total: 0 });
+ });
+
+ it('refuses a label that is not a group', async () => {
+ const { frontend } = await seed();
+ await expect(
+ tasks.groupList({ groupBy: 'label', labelGroupId: frontend.id }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index bdf8d3ff846..dcf9d029e37 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -260,13 +260,14 @@ export class TaskModel {
async groupList(
options: TaskListFilterOptions & {
excludeStatuses?: string[];
- groupBy?: 'agent' | 'assignee' | 'member' | 'priority';
+ groupBy?: 'agent' | 'assignee' | 'label' | 'member' | 'priority';
groups?: Array<{
key: string;
limit?: number;
offset?: number;
statuses: string[];
}>;
+ labelGroupId?: string;
},
): Promise<
Array<{
@@ -274,6 +275,7 @@ export class TaskModel {
assigneeUserId?: string | null;
hasMore: boolean;
key: string;
+ labelId?: string | null;
limit: number;
offset: number;
priority?: number;
diff --git a/packages/database/src/models/task/queries.ts b/packages/database/src/models/task/queries.ts
index 6dbebd4644c..f222c1d65f8 100644
--- a/packages/database/src/models/task/queries.ts
+++ b/packages/database/src/models/task/queries.ts
@@ -14,7 +14,9 @@ import {
} from 'drizzle-orm';
import { tasks, taskTopics } from '../../schemas/task';
+import { taskLabelLinks, taskLabels } from '../../schemas/taskLabel';
import { topics } from '../../schemas/topic';
+import { TaskLabelModel } from '../taskLabel';
import {
buildTaskListFilters,
type TaskListFilterOptions,
@@ -43,13 +45,15 @@ export const groupList = async (
ctx: TaskModelContext,
options: TaskListFilterOptions & {
excludeStatuses?: string[];
- groupBy?: 'agent' | 'assignee' | 'member' | 'priority';
+ groupBy?: 'agent' | 'assignee' | 'label' | 'member' | 'priority';
groups?: Array<{
key: string;
limit?: number;
offset?: number;
statuses: string[];
}>;
+ /** The label group whose labels become the columns of a `label` board. */
+ labelGroupId?: string;
},
): Promise<
Array<{
@@ -57,6 +61,8 @@ export const groupList = async (
assigneeUserId?: string | null;
hasMore: boolean;
key: string;
+ /** Label column of a `label` board; null is the "no label" column. */
+ labelId?: string | null;
limit: number;
offset: number;
priority?: number;
@@ -64,7 +70,7 @@ export const groupList = async (
total: number;
}>
> => {
- const { assigneeAgentId, excludeStatuses, groupBy, groups } = options;
+ const { assigneeAgentId, excludeStatuses, groupBy, groups, labelGroupId } = options;
if ((!groups || groups.length === 0) && !groupBy) {
throw new Error('Task groups or a grouping dimension are required');
@@ -80,6 +86,7 @@ export const groupList = async (
assigneeUserId?: string | null;
conditions: SQL[];
key: string;
+ labelId?: string | null;
limit: number;
offset: number;
prefetchedTasks?: TaskItem[];
@@ -244,6 +251,8 @@ export const groupList = async (
total,
};
});
+ } else if (groupBy === 'label') {
+ groupQueries = await buildLabelGroupQueries(ctx, baseConditions, labelGroupId);
} else if (groupBy === 'priority') {
const priorities = [1, 2, 3, 4, 0];
const countQuery = ctx.db
@@ -349,6 +358,7 @@ export const groupList = async (
return {
...(group.assigneeAgentId !== undefined ? { assigneeAgentId: group.assigneeAgentId } : {}),
...(group.assigneeUserId !== undefined ? { assigneeUserId: group.assigneeUserId } : {}),
+ ...(group.labelId !== undefined ? { labelId: group.labelId } : {}),
hasMore: group.offset + groupTasks.length < group.total,
key: group.key,
limit: group.limit,
@@ -362,9 +372,10 @@ export const groupList = async (
);
const taskIds = Array.from(new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))));
- const [runStats, subtaskProgressByTaskId] = await Promise.all([
+ const [runStats, subtaskProgressByTaskId, labelsByTaskId] = await Promise.all([
runStatsByTaskIds(ctx, taskIds),
subtaskProgressByTaskIds(ctx, taskIds),
+ labelsByTaskIds(ctx, taskIds),
]);
const runStatsByTaskId = new Map(
runStats.map((stats) => [
@@ -380,6 +391,7 @@ export const groupList = async (
...group,
tasks: group.tasks.map((task) => ({
...task,
+ labels: labelsByTaskId[task.id] ?? [],
subtaskProgress: subtaskProgressByTaskId.get(task.id),
totalRunCost: runStatsByTaskId.get(task.id)?.totalRunCost ?? 0,
totalRunDuration: runStatsByTaskId.get(task.id)?.totalRunDuration ?? 0,
@@ -387,6 +399,93 @@ export const groupList = async (
}));
};
+/** Labels per task for list rows; tasks without labels are absent from the map. */
+export const labelsByTaskIds = (ctx: TaskModelContext, taskIds: string[]) =>
+ new TaskLabelModel(ctx.db, ctx.userId, ctx.workspaceId).getLabelsForTasks(taskIds);
+
+/**
+ * Columns of a board grouped by one label group: one per label of the group
+ * (empty ones included, as drop targets) in the registry order, then "No
+ * label". A task carries at most one label per group, so each task lands in
+ * exactly one column.
+ */
+const buildLabelGroupQueries = async (
+ ctx: TaskModelContext,
+ baseConditions: SQL[],
+ labelGroupId: string | undefined,
+) => {
+ const labelModel = new TaskLabelModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const group = labelGroupId ? await labelModel.findById(labelGroupId) : undefined;
+ if (!group?.isGroup) throw new Error('A label group is required to group tasks by label');
+
+ const groupLabels = (await labelModel.query()).filter((label) => label.parentId === group.id);
+ const limit = 50;
+ const noneKey = 'label:none';
+ // The single label of this group the task carries, or NULL.
+ const labelColumn = sql<string | null>`(
+ select ${taskLabelLinks.labelId}::text from ${taskLabelLinks}
+ inner join ${taskLabels} on ${taskLabels.id} = ${taskLabelLinks.labelId}
+ where ${taskLabelLinks.taskId} = ${tasks.id} and ${taskLabels.parentId} = ${group.id}
+ order by ${taskLabelLinks.createdAt} desc
+ limit 1
+ )`;
+ const labelGroupKey = sql<string>`coalesce('label:' || ${labelColumn}, ${noneKey})`;
+
+ const rankedTasks = ctx.db
+ .select({
+ ...getTableColumns(tasks),
+ groupRank:
+ sql<number>`row_number() over (partition by ${labelGroupKey} order by ${tasks.createdAt} desc, ${tasks.seq} desc)`.as(
+ 'group_rank',
+ ),
+ labelGroupKey: labelGroupKey.as('label_group_key'),
+ })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .as('ranked_label_tasks');
+ // Grouped over a subquery: repeating the parameterized key expression in
+ // GROUP BY binds fresh parameters, which Postgres does not treat as the
+ // same expression as the one selected.
+ const keyedTasks = ctx.db
+ .select({ key: labelGroupKey.as('label_group_key') })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .as('keyed_label_tasks');
+ const [countResult, rankedTaskRows] = await Promise.all([
+ ctx.db
+ .select({ count: sql<number>`count(*)`, key: keyedTasks.key })
+ .from(keyedTasks)
+ .groupBy(keyedTasks.key),
+ ctx.db
+ .select()
+ .from(rankedTasks)
+ .where(sql`${rankedTasks.groupRank} <= ${limit}`)
+ .orderBy(rankedTasks.labelGroupKey, rankedTasks.groupRank),
+ ]);
+
+ const counts = new Map(countResult.map((row) => [row.key, Number(row.count)]));
+ const tasksByKey = new Map<string, TaskItem[]>();
+ for (const row of rankedTaskRows) {
+ const { labelGroupKey: key, groupRank: _groupRank, ...task } = row;
+ const groupTasks = tasksByKey.get(key) ?? [];
+ groupTasks.push(task);
+ tasksByKey.set(key, groupTasks);
+ }
+
+ return [...groupLabels.map((label) => label.id), null].map((labelId) => {
+ const key = labelId ? `label:${labelId}` : noneKey;
+ return {
+ conditions: [labelId ? sql`${labelColumn} = ${labelId}` : sql`${labelColumn} is null`],
+ key,
+ labelId,
+ limit,
+ offset: 0,
+ prefetchedTasks: tasksByKey.get(key) ?? [],
+ total: counts.get(key) ?? 0,
+ };
+ });
+};
+
export const runStatsByTaskIds = async (
ctx: TaskModelContext,
taskIds: string[],
@@ -493,14 +592,16 @@ export const list = async (
.limit(limit)
.offset(offset);
const [countResult, taskList] = await Promise.all([countQuery, taskListQuery]);
- const subtaskProgressByTaskId = await subtaskProgressByTaskIds(
- ctx,
- taskList.map(({ id }) => id),
- );
+ const taskIds = taskList.map(({ id }) => id);
+ const [subtaskProgressByTaskId, labelsByTaskId] = await Promise.all([
+ subtaskProgressByTaskIds(ctx, taskIds),
+ labelsByTaskIds(ctx, taskIds),
+ ]);
return {
tasks: taskList.map((task) => ({
...task,
+ labels: labelsByTaskId[task.id] ?? [],
subtaskProgress: subtaskProgressByTaskId.get(task.id),
})),
total: Number(countResult[0].count),
diff --git a/packages/database/src/models/taskListFilters.ts b/packages/database/src/models/taskListFilters.ts
index 56056ef1c56..3a3b58a0046 100644
--- a/packages/database/src/models/taskListFilters.ts
+++ b/packages/database/src/models/taskListFilters.ts
@@ -9,6 +9,7 @@ import {
import {
and,
eq,
+ exists,
gt,
gte,
ilike,
@@ -26,6 +27,7 @@ import {
import type { PgColumn } from 'drizzle-orm/pg-core';
import { tasks } from '../schemas/task';
+import { taskLabelLinks, taskLabels } from '../schemas/taskLabel';
/**
* A task the automation runtime would still act on.
@@ -202,6 +204,40 @@ const buildCreatorCondition = (set: TaskListFilterSet<string> | undefined): SQL
return set.operator === 'isNot' ? not(sql`coalesce(${matches}, false)`) : matches;
};
+/**
+ * A label value matches a task carrying that label, or — for a group id — any
+ * label of that group; "none" matches a task with no labels. Links are joined
+ * back to `tasks.id`, so the outer ownership predicate still decides which
+ * tasks are reachable. Mirrors `matchesLabels` in `@lobechat/types`.
+ */
+const buildLabelCondition = (set: TaskListFilterSet<string> | undefined): SQL | undefined => {
+ if (!set || set.values.length === 0) return undefined;
+ const includesNone = set.values.includes(TASK_LIST_FILTER_NONE);
+ const values = set.values.filter((value) => value !== TASK_LIST_FILTER_NONE);
+
+ const linked = (extra?: SQL) =>
+ exists(
+ sql`(select 1 from ${taskLabelLinks} inner join ${taskLabels} on ${taskLabels.id} = ${taskLabelLinks.labelId} where ${taskLabelLinks.taskId} = ${tasks.id}${extra ? sql` and ${extra}` : sql``})`,
+ );
+ const matches = or(
+ ...[
+ values.length > 0
+ ? linked(
+ // Compared as text: a malformed value must match nothing, not
+ // abort the query with an invalid-uuid cast error.
+ or(
+ inArray(sql`${taskLabels.id}::text`, values),
+ inArray(sql`${taskLabels.parentId}::text`, values),
+ ),
+ )
+ : undefined,
+ includesNone ? not(linked()) : undefined,
+ ].filter((condition): condition is SQL => !!condition),
+ )!;
+
+ return set.operator === 'isNot' ? not(matches) : matches;
+};
+
/** A NULL timestamp (an unfinished task's `completedAt`) matches neither side. */
const buildDateCondition = (
column: PgColumn,
@@ -228,6 +264,7 @@ export const buildTaskFilterConditions = (filter: TaskListFilter, now?: number):
buildSetCondition(tasks.assigneeUserId, filter.assignee),
buildCreatorCondition(filter.creator),
buildSetCondition(tasks.projectId, filter.project),
+ buildLabelCondition(filter.label),
buildDateCondition(tasks.createdAt, filter.createdAt, now),
buildDateCondition(tasks.updatedAt, filter.updatedAt, now),
buildDateCondition(tasks.completedAt, filter.completedAt, now),
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 30406311918..c73901068bd 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -4393,4 +4393,15 @@ export default {
'sandboxDrive.folderOnDriveDesc': '{{drive}} · {{path}}',
'input.costEstimate.hintUsd': 'Estimated cost: about {{amount}}',
'input.costEstimate.usdPerMillionTokens': '{{amount}} / 1M tokens',
+ 'taskLabel.add': 'Add labels',
+ 'taskLabel.anyInGroup': 'Any {{name}}',
+ 'taskLabel.createFailed': 'Failed to create label',
+ 'taskLabel.createNamed': 'Create label “{{name}}”',
+ 'taskLabel.empty': 'No labels yet. Type a name to create one.',
+ 'taskLabel.label': 'Labels',
+ 'taskLabel.noLabel': 'No label',
+ 'taskLabel.noLabels': 'No labels',
+ 'taskLabel.searchPlaceholder': 'Search or create labels…',
+ 'taskList.filter.field.label': 'Label',
+ 'taskList.groupBy.labelGroup': 'Label: {{name}}',
};
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index bcca20d114f..92c8bce2ecf 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4872,4 +4872,34 @@ When I am ___, I need ___
'subscriptionAccounts.updateFailed': "Couldn't update the account. Try again.",
'tab.subscriptionAccounts': 'Subscription Accounts',
'workspaceSetting.group.resource': 'Resources',
+ 'taskLabels.actions.addToGroup': 'Add label to group',
+ 'taskLabels.actions.create': 'New label',
+ 'taskLabels.actions.createGroup': 'New group',
+ 'taskLabels.delete.desc':
+ 'Removes this label from every task that carries it, including {{count}} unarchived tasks you can see. This cannot be undone.',
+ 'taskLabels.delete.groupDesc':
+ 'Deletes the group and every label in it, and removes them from tasks. This cannot be undone.',
+ 'taskLabels.delete.title': 'Delete “{{name}}”?',
+ 'taskLabels.empty': 'No task labels yet. Create one to organize your tasks.',
+ 'taskLabels.filterEmpty': 'No labels match your search',
+ 'taskLabels.filterPlaceholder': 'Filter labels…',
+ 'taskLabels.form.color': 'Color',
+ 'taskLabels.form.createGroupTitle': 'New label group',
+ 'taskLabels.form.createTitle': 'New label',
+ 'taskLabels.form.duplicateName': 'A label with this name already exists',
+ 'taskLabels.form.groupConflict':
+ 'Some tasks already carry another label from this group. Remove it from them first.',
+ 'taskLabels.form.editGroupTitle': 'Edit label group',
+ 'taskLabels.form.editTitle': 'Edit label',
+ 'taskLabels.form.group': 'Group',
+ 'taskLabels.form.groupNamePlaceholder': 'e.g. Type',
+ 'taskLabels.form.name': 'Name',
+ 'taskLabels.form.namePlaceholder': 'e.g. Bug',
+ 'taskLabels.form.noGroup': 'No group',
+ 'taskLabels.groupBadge': 'Group',
+ 'taskLabels.loadFailed': 'Failed to load labels',
+ 'taskLabels.tabs.agent': 'Agent labels',
+ 'taskLabels.tabs.task': 'Task labels',
+ 'taskLabels.usage': '{{count}} tasks',
+ 'taskLabels.actions.more': 'More actions',
};
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index f910d176573..e2d3205f643 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -51,6 +51,7 @@ const statusIcon = (s: string): string => {
export interface TaskSummary {
id?: string;
identifier: string;
+ labels?: { name: string }[] | null;
name?: string | null;
priority?: number | null;
status: string;
@@ -139,8 +140,11 @@ export type {
/**
* Format a single task as a one-line summary
*/
+const formatLabelSuffix = (labels: TaskSummary['labels']): string =>
+ labels?.length ? ` labels: ${labels.map((label) => label.name).join(', ')}` : '';
+
export const formatTaskLine = (t: TaskSummary): string =>
- `${taskIdentity(t)} ${statusIcon(t.status)} ${t.status} ${t.name || '(unnamed)'} [${priorityLabel(t.priority)}]`;
+ `${taskIdentity(t)} ${statusIcon(t.status)} ${t.status} ${t.name || '(unnamed)'} [${priorityLabel(t.priority)}]${formatLabelSuffix(t.labels)}`;
/**
* Format createTask response
@@ -160,6 +164,7 @@ export const formatTaskCreated = (
` Status: ${statusIcon(t.status)} ${t.status}`,
` Priority: ${priorityLabel(t.priority)}`,
];
+ if (t.labels?.length) lines.push(` Labels: ${t.labels.map((label) => label.name).join(', ')}`);
if (t.assigneeLabel) lines.push(` Assignee: ${t.assigneeLabel}`);
if (t.parentLabel)
lines.push(
@@ -211,6 +216,7 @@ export interface TaskListFilters {
isDefaultScope?: boolean;
isForAllAgents?: boolean;
isForCurrentAgent?: boolean;
+ labels?: string[];
parentIdentifier?: string;
priorities?: number[];
statuses?: TaskStatus[];
@@ -230,6 +236,7 @@ const buildTaskListLabel = (filters: TaskListFilters): string => {
parts.push(`priority=[${filters.priorities.map((p) => priorityLabel(p)).join(',')}]`);
}
if (filters.assigneeAgentId) parts.push(`agent=${filters.assigneeAgentId}`);
+ if (filters.labels?.length) parts.push(`label=[${filters.labels.join(',')}]`);
if (filters.parentIdentifier) {
return parts.length > 0
@@ -266,6 +273,7 @@ export const formatTaskDetail = (t: TaskDetailData): string => {
// `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: ${taskIdentity(t.parent)}`);
+ if (t.labels?.length) lines.push(`Labels: ${t.labels.map((label) => label.name).join(', ')}`);
if (t.topicCount) lines.push(`Topics: ${t.topicCount}`);
if (t.createdAt) lines.push(`Created: ${t.createdAt}`);
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 99e8a370d76..0fd9707b794 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -1,5 +1,6 @@
import type { BriefArtifacts } from '../brief';
import type { ChatFileItem } from '../message/ui/chat';
+import type { TaskLabelRef } from './label';
export * from './archive';
export * from './execution';
@@ -364,6 +365,8 @@ export interface TaskItem {
id: string;
identifier: string;
instruction: string;
+ /** Labels on the task, attached by task list and detail reads. */
+ labels?: TaskLabelRef[];
lastHeartbeatAt: Date | null;
maxTopics: number | null;
name: string | null;
@@ -650,6 +653,7 @@ export interface TaskDetailData {
id?: string;
identifier: string;
instruction: string;
+ labels?: TaskLabelRef[];
name?: string | null;
parent?: { id?: string; agentId?: string | null; identifier: string; name: string | null } | null;
priority?: number | null;
diff --git a/packages/types/src/task/label.test.ts b/packages/types/src/task/label.test.ts
new file mode 100644
index 00000000000..0f00f52a4a0
--- /dev/null
+++ b/packages/types/src/task/label.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ describeUnresolvedTaskLabels,
+ formatTaskLabelPath,
+ invertTaskLabelChange,
+ resolveTaskLabelRefs,
+} from './label';
+
+const registry = [
+ { id: 'g-type', isGroup: true, name: 'Type', parentId: null },
+ { id: 'bug', isGroup: false, name: 'Bug', parentId: 'g-type' },
+ { id: 'feature', isGroup: false, name: 'Feature', parentId: 'g-type' },
+ { id: 'fe', isGroup: false, name: 'Frontend', parentId: null },
+ { id: 'uiux', isGroup: false, name: 'UI/UX', parentId: null },
+];
+
+describe('resolveTaskLabelRefs', () => {
+ it('resolves bare names and group paths case-insensitively, de-duplicated', () => {
+ expect(resolveTaskLabelRefs(registry, ['bug', 'Type/Feature', ' FRONTEND ', 'Bug'])).toEqual({
+ ids: ['bug', 'feature', 'fe'],
+ unresolved: [],
+ });
+ });
+
+ it('prefers a label whose whole name contains the separator', () => {
+ expect(resolveTaskLabelRefs(registry, ['ui/ux']).ids).toEqual(['uiux']);
+ });
+
+ it('rejects a path naming the wrong group', () => {
+ const result = resolveTaskLabelRefs(registry, ['Other/Bug']);
+ expect(result.ids).toEqual([]);
+ expect(result.unresolved[0]).toMatchObject({ reason: 'notFound' });
+ expect(result.unresolved[0].suggestions).toContain('Type/Bug');
+ });
+
+ it('never resolves a group, and lists its labels instead', () => {
+ expect(resolveTaskLabelRefs(registry, ['type']).unresolved).toEqual([
+ { input: 'type', reason: 'group', suggestions: ['Type/Bug', 'Type/Feature'] },
+ ]);
+ });
+
+ it('suggests close names for a typo', () => {
+ const { unresolved } = resolveTaskLabelRefs(registry, ['Frontnd']);
+ expect(unresolved[0].suggestions[0]).toBe('Frontend');
+ expect(describeUnresolvedTaskLabels(unresolved)).toBe(
+ 'Label "Frontnd" not found (did you mean: Frontend?)',
+ );
+ });
+});
+
+describe('formatTaskLabelPath', () => {
+ it('prefixes the group name', () => {
+ expect(formatTaskLabelPath(registry[1], registry)).toBe('Type/Bug');
+ expect(formatTaskLabelPath(registry[3], registry)).toBe('Frontend');
+ });
+});
+
+describe('invertTaskLabelChange', () => {
+ const bug = { id: 'bug', parentId: 'type' };
+ const feat = { id: 'feat', parentId: 'type' };
+ const chore = { id: 'chore', parentId: 'type' };
+ const fe = { id: 'fe', parentId: null };
+ const other = { id: 'other', parentId: null };
+
+ it('undoes only the applied delta, including an implicit group swap', () => {
+ // Feature swapped out Bug, Frontend was removed; `other` was added meanwhile.
+ const undo = invertTaskLabelChange(
+ [bug, fe],
+ { add: ['feat'], remove: ['fe'] },
+ ['feat', 'other'],
+ [feat, other],
+ );
+
+ expect(undo).toEqual({ add: ['bug', 'fe'], remove: ['feat'] });
+ });
+
+ it('leaves a group alone once someone else replaced our sibling', () => {
+ // After our swap to Feature, a teammate picked Chore in the same group.
+ const undo = invertTaskLabelChange([bug], { add: ['feat'] }, ['feat'], [chore]);
+
+ expect(undo).toEqual({ add: [], remove: [] });
+ });
+
+ it('restores an explicitly removed grouped label while its group is still empty', () => {
+ expect(invertTaskLabelChange([bug], { remove: ['bug'] }, [], [])).toEqual({
+ add: ['bug'],
+ remove: [],
+ });
+ // ...but not once a teammate has picked another label of that group.
+ expect(invertTaskLabelChange([bug], { remove: ['bug'] }, [], [chore])).toEqual({
+ add: [],
+ remove: [],
+ });
+ });
+
+ it('does not re-add a removed label that is already back, nor remove a pre-existing one', () => {
+ expect(invertTaskLabelChange([fe], { remove: ['fe'] }, [], [fe])).toEqual({
+ add: [],
+ remove: [],
+ });
+ expect(invertTaskLabelChange([bug], { add: ['bug'] }, ['bug'], [bug])).toEqual({
+ add: [],
+ remove: [],
+ });
+ });
+});
diff --git a/packages/types/src/task/label.ts b/packages/types/src/task/label.ts
index a87ace420b3..e9d465ad87e 100644
--- a/packages/types/src/task/label.ts
+++ b/packages/types/src/task/label.ts
@@ -50,3 +50,166 @@ export const TASK_LABEL_COLORS = [
] as const;
export const DEFAULT_TASK_LABEL_COLOR = TASK_LABEL_COLORS[0];
+
+/** The registry fields `resolveTaskLabelRefs` reads. */
+export type TaskLabelRegistryEntry = Pick<TaskLabel, 'id' | 'isGroup' | 'name' | 'parentId'>;
+
+export interface TaskLabelRefResolution {
+ /** Resolved label ids, in input order, de-duplicated. */
+ ids: string[];
+ /** Inputs that resolved to nothing assignable, each with close existing names. */
+ unresolved: { input: string; reason: 'group' | 'notFound'; suggestions: string[] }[];
+}
+
+const normalizeLabelName = (value: string) => value.trim().toLowerCase();
+
+/** Display path of a label: `Group/Label` for a grouped one, the bare name otherwise. */
+export const formatTaskLabelPath = (
+ label: Pick<TaskLabel, 'name' | 'parentId'>,
+ registry: Pick<TaskLabel, 'id' | 'name'>[],
+): string => {
+ const group = label.parentId ? registry.find((entry) => entry.id === label.parentId) : undefined;
+ return group ? `${group.name}${TASK_LABEL_PATH_SEPARATOR}${label.name}` : label.name;
+};
+
+const editDistance = (a: string, b: string): number => {
+ const row = Array.from({ length: b.length + 1 }, (_, index) => index);
+ for (let i = 1; i <= a.length; i += 1) {
+ let previous = row[0];
+ row[0] = i;
+ for (let j = 1; j <= b.length; j += 1) {
+ const current = row[j];
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
+ previous = current;
+ }
+ }
+ return row[b.length];
+};
+
+/**
+ * Resolve label names typed by a person or an agent (`Bug`, `type/bug`) to
+ * label ids. Names are unique per scope, so a bare name is enough; a path
+ * must also name the right group. Nothing is created: an unknown name comes
+ * back as unresolved with the closest existing labels as suggestions, so a
+ * typo never silently grows the registry.
+ */
+export const resolveTaskLabelRefs = (
+ registry: TaskLabelRegistryEntry[],
+ inputs: string[],
+): TaskLabelRefResolution => {
+ const assignable = registry.filter((label) => !label.isGroup);
+ const ids: string[] = [];
+ const unresolved: TaskLabelRefResolution['unresolved'] = [];
+
+ for (const raw of inputs) {
+ const input = raw.trim();
+ if (!input) continue;
+
+ const separator = input.lastIndexOf(TASK_LABEL_PATH_SEPARATOR);
+ const groupName = separator > 0 ? normalizeLabelName(input.slice(0, separator)) : undefined;
+ const name = normalizeLabelName(separator > 0 ? input.slice(separator + 1) : input);
+
+ // A whole input that is itself a label name wins over the path reading,
+ // so a label literally named "UI/UX" still resolves.
+ const exact = registry.find(
+ (label) => normalizeLabelName(label.name) === normalizeLabelName(input),
+ );
+ const match =
+ exact ??
+ (groupName !== undefined
+ ? assignable.find((label) => {
+ if (normalizeLabelName(label.name) !== name || !label.parentId) return false;
+ const group = registry.find((entry) => entry.id === label.parentId);
+ return !!group && normalizeLabelName(group.name) === groupName;
+ })
+ : undefined);
+
+ if (match && !match.isGroup) {
+ if (!ids.includes(match.id)) ids.push(match.id);
+ continue;
+ }
+
+ const needle = normalizeLabelName(input);
+ const suggestions = assignable
+ .map((label) => ({ label, path: formatTaskLabelPath(label, registry) }))
+ .map(({ label, path }) => {
+ const candidate = normalizeLabelName(label.name);
+ const distance = Math.min(
+ editDistance(needle, candidate),
+ editDistance(needle, normalizeLabelName(path)),
+ );
+ const related = candidate.includes(name) || name.includes(candidate);
+ return { distance: related ? Math.min(distance, 1) : distance, path };
+ })
+ .filter(({ distance }) => distance <= Math.max(2, Math.floor(needle.length / 3)))
+ .sort((a, b) => a.distance - b.distance || a.path.localeCompare(b.path))
+ .slice(0, 5)
+ .map(({ path }) => path);
+
+ if (match?.isGroup) {
+ const children = assignable
+ .filter((label) => label.parentId === match.id)
+ .map((label) => formatTaskLabelPath(label, registry));
+ unresolved.push({ input, reason: 'group', suggestions: children });
+ } else {
+ unresolved.push({ input, reason: 'notFound', suggestions });
+ }
+ }
+
+ return { ids, unresolved };
+};
+
+/** One readable line per unresolved input, for CLI and tool error messages. */
+export const describeUnresolvedTaskLabels = (
+ unresolved: TaskLabelRefResolution['unresolved'],
+): string =>
+ unresolved
+ .map(({ input, reason, suggestions }) => {
+ const head =
+ reason === 'group'
+ ? `"${input}" is a label group; pick one of its labels`
+ : `Label "${input}" not found`;
+ return suggestions.length > 0 ? `${head} (did you mean: ${suggestions.join(', ')}?)` : head;
+ })
+ .join('\n');
+
+/**
+ * The label change that undoes one applied `changeForTask`, touching only what
+ * that call itself changed — never a full-set replacement, so labels another
+ * client changed meanwhile survive the rollback.
+ *
+ * - `before`: labels on the task right before the change
+ * - `add` / `remove`: the delta that was applied
+ * - `after`: label ids the change returned
+ * - `current`: labels on the task now, read right before rolling back
+ *
+ * What this change took away (explicitly, or as a group sibling it swapped
+ * out) comes back only if nobody has touched it since: an ungrouped label only
+ * when it is still absent, a grouped one only while its group holds nothing
+ * but this change's own label (or nothing at all). Only labels this change
+ * added that are still there are taken away.
+ */
+export const invertTaskLabelChange = (
+ before: readonly Pick<TaskLabelRef, 'id' | 'parentId'>[],
+ { add = [] }: { add?: readonly string[]; remove?: readonly string[] },
+ after: readonly string[],
+ current: readonly Pick<TaskLabelRef, 'id' | 'parentId'>[],
+): { add: string[]; remove: string[] } => {
+ const beforeIds = new Set(before.map((label) => label.id));
+ const afterIds = new Set(after);
+ const currentIds = new Set(current.map((label) => label.id));
+ const ours = new Set(add.filter((id) => !beforeIds.has(id) && afterIds.has(id)));
+ const oursStillCurrent = current.filter((label) => ours.has(label.id));
+ // Groups someone else has put a label into since this change.
+ const groupsTakenByOthers = new Set(
+ current.flatMap((label) => (label.parentId && !ours.has(label.id) ? [label.parentId] : [])),
+ );
+
+ return {
+ add: before
+ .filter((label) => !afterIds.has(label.id) && !currentIds.has(label.id))
+ .filter((label) => !label.parentId || !groupsTakenByOthers.has(label.parentId))
+ .map((label) => label.id),
+ remove: oursStillCurrent.map((label) => label.id),
+ };
+};
diff --git a/packages/types/src/task/listFilter.test.ts b/packages/types/src/task/listFilter.test.ts
index e5d7c8cf72c..3e952de5603 100644
--- a/packages/types/src/task/listFilter.test.ts
+++ b/packages/types/src/task/listFilter.test.ts
@@ -186,3 +186,37 @@ describe('matchesTaskListFilter', () => {
expect(matchesTaskListFilter(task(), { content: 'billing' }, NOW)).toBe(false);
});
});
+
+describe('matchesTaskListFilter label', () => {
+ const labeled = task({
+ labels: [
+ { id: 'bug', parentId: 'type' },
+ { id: 'fe', parentId: null },
+ ],
+ });
+ const unlabeled = task({ labels: [] });
+
+ it('matches a label, its group, or no labels', () => {
+ const is = (values: string[]) => ({ label: { operator: 'is' as const, values } });
+ expect(matchesTaskListFilter(labeled, is(['bug']), NOW)).toBe(true);
+ expect(matchesTaskListFilter(labeled, is(['type']), NOW)).toBe(true);
+ expect(matchesTaskListFilter(labeled, is(['other']), NOW)).toBe(false);
+ expect(matchesTaskListFilter(unlabeled, is([TASK_LIST_FILTER_NONE]), NOW)).toBe(true);
+ expect(matchesTaskListFilter(labeled, is([TASK_LIST_FILTER_NONE]), NOW)).toBe(false);
+ // a row without the field counts as unlabeled
+ expect(matchesTaskListFilter(task(), is([TASK_LIST_FILTER_NONE]), NOW)).toBe(true);
+ });
+
+ it('isNot excludes rows carrying any value', () => {
+ const isNot = (values: string[]) => ({ label: { operator: 'isNot' as const, values } });
+ expect(matchesTaskListFilter(labeled, isNot(['fe']), NOW)).toBe(false);
+ expect(matchesTaskListFilter(unlabeled, isNot(['fe']), NOW)).toBe(true);
+ expect(matchesTaskListFilter(labeled, isNot([TASK_LIST_FILTER_NONE]), NOW)).toBe(true);
+ });
+
+ it('normalizes the label set', () => {
+ expect(normalizeTaskListFilter({ label: { operator: 'is', values: ['b', 'a', 'b'] } })).toEqual(
+ { label: { operator: 'is', values: ['a', 'b'] } },
+ );
+ });
+});
diff --git a/packages/types/src/task/listFilter.ts b/packages/types/src/task/listFilter.ts
index 47fb6df1483..2a941cd5722 100644
--- a/packages/types/src/task/listFilter.ts
+++ b/packages/types/src/task/listFilter.ts
@@ -1,4 +1,5 @@
import type { TaskStatus } from './index';
+import type { TaskLabelRef } from './label';
/**
* The Tasks page filter (Linear-style "Add Filter"): a set of independent
@@ -62,6 +63,7 @@ export const TASK_LIST_FILTER_SET_FIELDS = [
'assignee',
'creator',
'project',
+ 'label',
] as const;
export type TaskListFilterSetField = (typeof TASK_LIST_FILTER_SET_FIELDS)[number];
@@ -84,6 +86,12 @@ export interface TaskListFilter {
* (`toTaskListFilterAgentCreator`) match `createdByAgentId`.
*/
creator?: TaskListFilterSet<string>;
+ /**
+ * Label ids. A task matches a value when it carries that label, or — for a
+ * label group's id — any label of that group. `TASK_LIST_FILTER_NONE`
+ * stands for "no labels at all". `is` matches any value, `isNot` none.
+ */
+ label?: TaskListFilterSet<string>;
/** `priority`, a missing one counting as 0 ("no priority"). */
priority?: TaskListFilterSet<number>;
/** `projectId`; may hold `TASK_LIST_FILTER_NONE`. */
@@ -136,6 +144,7 @@ export const normalizeTaskListFilter = (
content: content || undefined,
createdAt: normalizeDate(filter.createdAt),
creator: normalizeSet(filter.creator),
+ label: normalizeSet(filter.label),
priority: normalizeSet(filter.priority),
project: normalizeSet(filter.project),
status: normalizeSet(filter.status),
@@ -165,6 +174,8 @@ export interface TaskListFilterTarget {
description?: string | null;
identifier?: string | null;
instruction?: string | null;
+ /** Labels the row carries; a row without the field counts as unlabeled. */
+ labels?: Pick<TaskLabelRef, 'id' | 'parentId'>[] | null;
name?: string | null;
priority?: number | null;
projectId?: string | null;
@@ -196,6 +207,25 @@ const matchesCreator = (
return set.operator === 'isNot' ? !included : included;
};
+/**
+ * A label value matches a carried label by id, or a label group by any of its
+ * labels; "none" matches a row without labels. Mirrors `buildLabelCondition`.
+ */
+const matchesLabels = (
+ set: TaskListFilterSet<string> | undefined,
+ task: TaskListFilterTarget,
+): boolean => {
+ if (!set || set.values.length === 0) return true;
+ const labels = task.labels ?? [];
+ const included =
+ (set.values.includes(TASK_LIST_FILTER_NONE) && labels.length === 0) ||
+ labels.some(
+ (label) =>
+ set.values.includes(label.id) || (!!label.parentId && set.values.includes(label.parentId)),
+ );
+ return set.operator === 'isNot' ? !included : included;
+};
+
const toTime = (value: Date | string | null | undefined): number | undefined => {
if (!value) return undefined;
const time = new Date(value).getTime();
@@ -241,6 +271,7 @@ export const matchesTaskListFilter = (
matchesSet(filter.assignee, task.assigneeUserId, TASK_LIST_FILTER_NONE) &&
matchesCreator(filter.creator, task) &&
matchesSet(filter.project, task.projectId, TASK_LIST_FILTER_NONE) &&
+ matchesLabels(filter.label, task) &&
matchesDate(filter.createdAt, task.createdAt, now) &&
matchesDate(filter.updatedAt, task.updatedAt, now) &&
matchesDate(filter.completedAt, task.completedAt, now) &&
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
index e7d53dab3e3..09309b6e148 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
@@ -1,10 +1,12 @@
import type { TaskPriority, TaskStatus } from '@lobechat/types';
import { Block, cssVar, Icon, Text } from '@lobehub/ui';
-import { ArchiveIcon, Stamp } from 'lucide-react';
+import { ArchiveIcon, Stamp, TagIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import TaskLabelChips from '@/features/TaskLabels/TaskLabelChips';
+import TaskLabelPicker from '@/features/TaskLabels/TaskLabelPicker';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -64,6 +66,9 @@ const TaskProperties = memo(() => {
const memberMeta = useUserDisplayMeta(assigneeUserId);
const activeWorkspaceId = useActiveWorkspaceId();
const acceptanceWait = useTaskAcceptanceWait();
+ const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
+ const labels = useTaskStore(taskDetailSelectors.activeTaskLabels);
+ const setTaskLabels = useTaskStore((s) => s.setTaskLabels);
if (!taskId) return null;
@@ -166,6 +171,37 @@ const TaskProperties = memo(() => {
</AssigneeMemberSelector>
)}
+ <TaskLabelPicker
+ disabled={!taskDatabaseId}
+ value={labels}
+ onChange={(next) => {
+ if (taskDatabaseId) void setTaskLabels(taskDatabaseId, labels, next);
+ }}
+ >
+ <Block
+ clickable
+ horizontal
+ align="center"
+ className={styles.propertyItem}
+ gap={8}
+ // Property rows have a fixed height; this one grows with wrapped chips
+ // so a second line never overlaps the row below.
+ style={{ flexWrap: 'wrap', height: 'auto', minHeight: 30, paddingBlock: 4 }}
+ variant={'borderless'}
+ >
+ {labels.length > 0 ? (
+ <TaskLabelChips wrap labels={labels} max={6} />
+ ) : (
+ <>
+ <Icon color={cssVar.colorTextDescription} icon={TagIcon} size={16} />
+ <Text style={{ color: cssVar.colorTextDescription }} weight={500}>
+ {t('taskLabel.add')}
+ </Text>
+ </>
+ )}
+ </Block>
+ </TaskLabelPicker>
+
{/* Where the runs go lives in the detail header's main column, next to the
assignee it inherits from — not in this rail. See
`TaskExecutionConfig`. */}
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 9f36893f990..85b6f120eab 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -25,7 +25,7 @@ import { useGlobalStore } from '@/store/global';
import type { TaskViewMode } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
-import { taskListSelectors } from '@/store/task/selectors';
+import { taskLabelSelectors, taskListSelectors } from '@/store/task/selectors';
import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';
import { isMobileSurface } from '@/utils/mobileSurface';
@@ -45,6 +45,7 @@ import {
import KanbanBoard from './KanbanBoard';
import type { TaskListViewOptions } from './listViewOptions';
import {
+ dropMissingLabelGroupings,
getCompletedWithin,
getVisibleTaskStatuses,
normalizeTaskListViewOptions,
@@ -254,7 +255,25 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj
);
const hasFilter = !!filter;
const rawViewOptions = useGlobalStore(systemStatusSelectors.taskListViewOptions);
- const viewOptions = useMemo(() => normalizeTaskListViewOptions(rawViewOptions), [rawViewOptions]);
+ // Joined into a string so the selector returns a stable primitive.
+ const labelGroupIdsKey = useTaskStore((s) =>
+ taskLabelSelectors.isLabelsInit(s)
+ ? taskLabelSelectors
+ .labelGroups(s)
+ .map((group) => group.id)
+ .join(',')
+ : undefined,
+ );
+ const viewOptions = useMemo(
+ () =>
+ dropMissingLabelGroupings(
+ normalizeTaskListViewOptions(rawViewOptions),
+ labelGroupIdsKey === undefined
+ ? undefined
+ : new Set(labelGroupIdsKey.split(',').filter(Boolean)),
+ ),
+ [rawViewOptions, labelGroupIdsKey],
+ );
// Group headers of the ordinary list offer the board's column create entry.
const groupCreateScope = useMemo(
() => (canCreateTask ? { agentId, projectId } : undefined),
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
index 5d43f2c7fb6..41b4fa651cf 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
@@ -171,6 +171,12 @@ vi.mock('@/store/user', () => ({
selector({ preference: { lab: userStateMock.lab }, user: { id: 'self-user' } }),
}));
+// The label picker reads the label registry; its own behavior is covered by
+// `labelPickerModel.test.ts`.
+vi.mock('@/features/TaskLabels/TaskLabelPicker', () => ({
+ default: ({ children }: { children?: ReactNode }) => <div data-testid="labels">{children}</div>,
+}));
+
vi.mock('../features/TaskPriorityTag', () => ({
default: ({ children }: { children?: ReactNode }) => (
<div data-testid="priority">{children ?? 'priority'}</div>
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
index 4b3ace2310f..aba87d3107e 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx
@@ -1,11 +1,21 @@
'use client';
-import type { TaskExecutionConfig, TaskIntentAnalysis } from '@lobechat/types';
+import type { TaskExecutionConfig, TaskIntentAnalysis, TaskLabelRef } from '@lobechat/types';
import { readTaskExecutionConfig, toTaskExecutionConfigPatch } from '@lobechat/types';
import { useEditor } from '@lobehub/editor/react';
-import { ActionIcon, Block, Button, cssVar, DropdownMenu, Flexbox, Text, toast } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Block,
+ Button,
+ cssVar,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+ Text,
+ toast,
+} from '@lobehub/ui';
import { $getRoot } from 'lexical';
-import { ChevronDown, ChevronUp, Paperclip } from 'lucide-react';
+import { ChevronDown, ChevronUp, Paperclip, TagIcon } from 'lucide-react';
import { type KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,11 +27,15 @@ import {
getAttachmentFileIdsFromEditor,
pickAndInsertAttachments,
} from '@/features/EditorCanvas/editorAttachments';
+import { pickedLabelIds, resolveTaskLabelRefs } from '@/features/TaskLabels/labelPickerModel';
+import TaskLabelChips from '@/features/TaskLabels/TaskLabelChips';
+import TaskLabelPicker from '@/features/TaskLabels/TaskLabelPicker';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
import { taskService } from '@/services/task';
import { useGlobalStore } from '@/store/global';
-import { useTaskStore } from '@/store/task';
+import { getTaskStoreState, useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
import { shinyTextStyles } from '@/styles';
@@ -108,6 +122,12 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
useDefaultMemberAssignee();
const navigate = useWorkspaceAwareNavigate();
const [priority, setPriority] = useState(0);
+ const [labels, setLabels] = useState<TaskLabelRef[]>([]);
+ const isLabelsInit = useTaskStore(taskLabelSelectors.isLabelsInit);
+ const labelRegistry = useTaskStore(taskLabelSelectors.labels);
+ // Label ids read from a draft before the registry loaded; resolved (and
+ // stale ones dropped) once it has.
+ const pendingDraftLabelIdsRef = useRef<string[] | undefined>(undefined);
const [assigneeAgentId, setAssigneeAgentId] = useState<string | undefined>(agentId);
// `undefined` follows the default (the creator); `null` is an explicit "unassigned".
const [memberChoice, setMemberChoice] = useState<string | null | undefined>();
@@ -242,6 +262,10 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
// hydration only — it must not keep the previous scope's selection).
editor.cleanDocument?.();
setPriority(0);
+ // Labels belong to a workspace: one picked in the previous scope would be a
+ // foreign id here and fail the create.
+ setLabels([]);
+ pendingDraftLabelIdsRef.current = undefined;
setVisibility(defaultVisibility);
setExecution(undefined);
if (!lockAssignee) setAssigneeAgentId(agentId);
@@ -267,6 +291,16 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
setMemberChoice(draft.assigneeUserId);
}
if (draft.visibility) setVisibility(draft.visibility);
+ const labelIds = Array.isArray(draft.labelIds)
+ ? draft.labelIds.filter((id): id is string => typeof id === 'string')
+ : [];
+ if (labelIds.length > 0) {
+ if (getTaskStoreState().taskLabelsInit) {
+ setLabels(resolveTaskLabelRefs(getTaskStoreState().taskLabels, labelIds));
+ } else {
+ pendingDraftLabelIdsRef.current = labelIds;
+ }
+ }
} catch {
/* ignore a malformed draft */
}
@@ -282,6 +316,15 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
lockAssignee,
]);
+ useEffect(() => {
+ const pending = pendingDraftLabelIdsRef.current;
+ if (!isLabelsInit || !pending?.length) return;
+ pendingDraftLabelIdsRef.current = undefined;
+ setLabels((current) =>
+ current.length > 0 ? current : resolveTaskLabelRefs(labelRegistry, pending),
+ );
+ }, [isLabelsInit, labelRegistry]);
+
// Back the draft to storage on every change. Gated behind the restore pass so
// the initial render can't clobber a just-read draft. Emptying the editor
// discards the draft, but only after it has held text since hydration — so a
@@ -300,6 +343,10 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
// `undefined` (the whole selection is `undefined`) drops the key, so
// an untouched composer writes the same draft shape as before.
execution,
+ // While a restore waits for the registry, keep writing the ids it holds
+ // so a reload in that window does not drop them.
+ labelIds:
+ labels.length > 0 ? labels.map((label) => label.id) : pendingDraftLabelIdsRef.current,
markdown,
priority,
visibility,
@@ -313,6 +360,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
editor,
execution,
instruction,
+ labels,
lockAssignee,
memberChoice,
priority,
@@ -343,6 +391,9 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
const resetComposer = useCallback(() => {
setPriority(0);
+ setLabels([]);
+ // A restore still waiting for the registry belongs to the draft just sent.
+ pendingDraftLabelIdsRef.current = undefined;
setAssigneeAgentId(agentId);
setMemberChoice(undefined);
setInstruction('');
@@ -411,6 +462,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
...(execution ? { config: { execution: toTaskExecutionConfigPatch(execution) } } : {}),
editorData: draft.editorJson,
instruction: draft.instruction,
+ ...pickedLabelIds(labels, pendingDraftLabelIdsRef.current),
name: draft.name,
parentTaskId,
priority: priority || undefined,
@@ -483,6 +535,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
assigneeUserId,
createTask,
execution,
+ labels,
navigate,
onCreated,
parentTaskId,
@@ -757,6 +810,28 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {
</Block>
</TaskPriorityTag>
+ <TaskLabelPicker value={labels} onChange={setLabels}>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ gap={6}
+ height={24}
+ paddingBlock={3}
+ paddingInline={8}
+ variant={'borderless'}
+ >
+ {labels.length > 0 ? (
+ <TaskLabelChips labels={labels} max={3} />
+ ) : (
+ <>
+ <Icon color={cssVar.colorTextDescription} icon={TagIcon} size={14} />
+ <Text fontSize={12}>{t('taskLabel.label')}</Text>
+ </>
+ )}
+ </Block>
+ </TaskLabelPicker>
+
{activeWorkspaceId && (
<AssigneeMemberSelector
currentUserId={assigneeUserId}
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index cf1b63dcbc4..3bcf2fbfa53 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -10,19 +10,20 @@ import {
useSensors,
} from '@dnd-kit/core';
import { matchesTaskListFilter, type TaskListFilter } from '@lobechat/types';
-import { Center, createStaticStyles, Empty, Flexbox } from '@lobehub/ui';
+import { Center, createStaticStyles, cssVar, Empty, Flexbox } from '@lobehub/ui';
import { ClipboardCheckIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
+import { useFetchTaskLabels } from '@/hooks/useFetchTaskLabels';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
-import { taskListSelectors } from '@/store/task/selectors';
+import { taskLabelSelectors, taskListSelectors } from '@/store/task/selectors';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
import { saveToast } from '@/store/utils/saveToast';
@@ -37,13 +38,18 @@ import {
findKanbanTask,
getKanbanAssigneeUpdate,
getKanbanColumnCreateDefaults,
+ getKanbanLabelPatch,
getKanbanTaskPatch,
moveTaskBetweenKanbanGroups,
normalizeKanbanGroupBy,
} from './kanbanBoardModel';
import KanbanColumn, { COLUMN_I18N_KEYS, COLUMN_STATUS_ICON, COLUMN_WIDTH } from './KanbanColumn';
import type { TaskListViewOptions } from './listViewOptions';
-import { getCompletedWithin, HIDDEN_WHEN_COMPLETED_STATUSES } from './listViewOptions';
+import {
+ getCompletedWithin,
+ HIDDEN_WHEN_COMPLETED_STATUSES,
+ isTaskLabelGroupBy,
+} from './listViewOptions';
const styles = createStaticStyles(({ css }) => ({
board: css`
@@ -83,12 +89,20 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
const excludeStatuses =
options.completedTasks === 'none' ? HIDDEN_WHEN_COMPLETED_STATUSES : undefined;
+ // Label columns read their name and color from the registry.
+ const { error: labelsError, mutate: retryLabels } = useFetchTaskLabels();
+ const isLabelsInit = useTaskStore(taskLabelSelectors.isLabelsInit);
+
const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);
// Keep the sync handle for `error` + `mutate` (the error/Retry state) and the
// `queryKey` the groups are read by.
const { error, isLoading, mutate, queryKey } = useFetchTaskGroupList({
...buildKanbanGroupQuery({ agentId, excludeStatuses, groupBy, myTaskScope, projectId }),
completedWithin: getCompletedWithin(options),
+ // A persisted label grouping may point at a deleted group; the page only
+ // drops it once the registry is known, so wait for that (or its failure)
+ // instead of sending one doomed request after every reload.
+ enabled: !isTaskLabelGroupBy(groupBy) || isLabelsInit,
filter,
includeArchived: options.showArchived,
});
@@ -111,6 +125,7 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
});
}, [filter, storedTaskGroups]);
const updateTask = useTaskStore((s) => s.updateTask);
+ const setTaskLabels = useTaskStore((s) => s.setTaskLabels);
const runTask = useTaskStore((s) => s.runTask);
const refreshTaskList = useTaskStore((s) => s.refreshTaskList);
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
@@ -121,9 +136,11 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
const [activeTask, setActiveTask] = useState<TaskListItem | null>(null);
+ const taskLabels = useTaskStore(taskLabelSelectors.labels);
const columns = useMemo(
() => buildKanbanColumns(currentTaskGroups, groupBy),
- [currentTaskGroups, groupBy],
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- registry changes rename label columns
+ [currentTaskGroups, groupBy, taskLabels],
);
const sensors = useSensors(
@@ -186,7 +203,12 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
if (!task) return;
if (!column || !canDropTaskIntoKanbanColumn(task, groupBy, column)) return;
- const patch = getKanbanTaskPatch(groupBy, column);
+ const labelPatch = isTaskLabelGroupBy(groupBy)
+ ? getKanbanLabelPatch(task, groupBy, column)
+ : undefined;
+ if (isTaskLabelGroupBy(groupBy) && !labelPatch) return;
+ const patch: Partial<TaskListItem> | undefined =
+ labelPatch ?? getKanbanTaskPatch(groupBy, column);
if (!patch) return;
const assigneeUpdate =
groupBy === 'assignee' || groupBy === 'member'
@@ -221,6 +243,13 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
await updateTask(task.identifier, assigneeUpdate);
} else if (groupBy === 'priority') {
await updateTask(task.identifier, { priority: patch.priority ?? 0 });
+ } else if (labelPatch) {
+ // The store action toasts its own failure and reports it here.
+ const saved = await setTaskLabels(task.id, task.labels ?? [], labelPatch.labels);
+ if (!saved) {
+ move.rollback();
+ return;
+ }
}
move.commit();
} catch {
@@ -236,6 +265,7 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
groupBy,
queryKey,
refreshTaskList,
+ setTaskLabels,
startTask,
updateTask,
],
@@ -375,10 +405,10 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
{activeTask ? (
<div
style={{
- background: 'var(--lobe-color-bg-container, #fff)',
- border: '1px solid var(--lobe-color-border-secondary, #f0f0f0)',
+ background: cssVar.colorBgContainer,
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
borderRadius: 8,
- boxShadow: '0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12)',
+ boxShadow: cssVar.boxShadowSecondary,
cursor: 'grabbing',
width: COLUMN_WIDTH - 8,
}}
@@ -393,16 +423,20 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {
// Error gated ahead of empty by AsyncBoundary so a failed fetch shows Retry
// instead of the "no tasks" empty. `data` is the SWR result —
// undefined until the first fetch settles.
+ // A label board needs the registry for its columns (names, colors, order);
+ // if that failed, show it here with its own Retry rather than raw label ids.
+ const registryError = isTaskLabelGroupBy(groupBy) && !isLabelsInit ? labelsError : undefined;
+ const boardError = registryError ?? error;
return (
<AsyncBoundary
data={isTaskGroupListInit || undefined}
empty={emptyState}
- error={error}
+ error={boardError}
errorVariant={'block'}
isEmpty={totalTasks === 0}
- isLoading={isLoading || (!isTaskGroupListInit && !error)}
+ isLoading={isLoading || (!isTaskGroupListInit && !boardError)}
loading={skeletonBoard}
- onRetry={() => mutate()}
+ onRetry={() => (registryError ? retryLabels() : mutate())}
>
{board}
</AsyncBoundary>
diff --git a/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx b/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx
index a21995d314e..4bd7e25d164 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskGroupLabel.tsx
@@ -1,7 +1,9 @@
import { cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
-import { CalendarClock, HeartPulse, UserRound } from 'lucide-react';
+import { CalendarClock, HeartPulse, TagIcon, UserRound } from 'lucide-react';
import { memo } from 'react';
+import TaskLabelDot from '@/features/TaskLabels/TaskLabelDot';
+
import AssigneeAvatar from '../features/AssigneeAvatar';
import AssigneeUserAvatar from '../features/AssigneeUserAvatar';
import PriorityHighIcon from '../features/icons/PriorityHighIcon';
@@ -13,6 +15,7 @@ import TaskStatusIcon from '../features/TaskStatusIcon';
import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';
import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';
import type { TaskGroupMeta } from './listViewOptions';
+import { isTaskLabelGroupBy } from './listViewOptions';
const PRIORITY_ICON_MAP = {
0: PriorityNoneIcon,
@@ -33,6 +36,11 @@ const AssigneeUserLabel = memo<{ userId: string }>(({ userId }) => {
});
const TaskGroupPrefix = ({ group }: { group: TaskGroupMeta }) => {
+ if (isTaskLabelGroupBy(group.groupBy)) {
+ if (group.labelId) return <TaskLabelDot color={group.labelColor} size={10} />;
+ return <Icon color={cssVar.colorTextDescription} icon={TagIcon} size={14} />;
+ }
+
if (group.groupBy === 'assignee') {
if (group.assigneeId) return <AssigneeAvatar agentId={group.assigneeId} size={18} />;
return <Icon icon={UserRound} size={14} />;
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index 2a0d1d565f6..e53c5cb108b 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -42,6 +42,7 @@ import {
compareTaskItems,
groupTaskItems,
isTaskHiddenByCompletedFilter,
+ normalizeTaskGroupBy,
} from './listViewOptions';
import SelectableTaskRow, { selectableTaskItemClassName } from './selection/SelectableTaskRow';
import { useTaskSelectionStore } from './selection/store';
@@ -107,20 +108,6 @@ interface TaskListProps {
/** Row height the window sizes itself by before it has measured real rows. */
const DEFAULT_ROW_HEIGHT = 52;
-const TASK_GROUP_BY_VALUES = new Set<TaskGroupBy>([
- 'assignee',
- 'automationMode',
- 'member',
- 'none',
- 'priority',
- 'status',
-]);
-
-const normalizeGroupBy = (value: TaskGroupBy | string | undefined, fallback: TaskGroupBy) => {
- if (!value) return fallback;
- return TASK_GROUP_BY_VALUES.has(value as TaskGroupBy) ? (value as TaskGroupBy) : fallback;
-};
-
const styles = stylex.create({
// A flex box centres the icon instead of a transform on the icon itself,
// which its own pressed / focused styles would override.
@@ -257,8 +244,8 @@ const TaskList = memo<TaskListProps>((props) => {
// let the missing rows vanish silently. Alternate collections (`items`)
// paginate on their own.
const isTruncated = !items && storeTasksTotal > COMPLETE_TASK_LIST_MAX_ITEMS;
- const groupBy = normalizeGroupBy(options.groupBy, 'status');
- const subGroupBy = normalizeGroupBy(options.subGroupBy, 'none');
+ const groupBy = normalizeTaskGroupBy(options.groupBy, 'status');
+ const subGroupBy = normalizeTaskGroupBy(options.subGroupBy, 'none');
const effectiveSubGroupBy = groupBy === 'none' ? 'none' : subGroupBy;
const unfinishedTasks = useMemo(
() =>
diff --git a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
index 1306b07b26e..7dc7e0c6cf7 100644
--- a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
@@ -20,9 +20,12 @@ import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { useFetchTaskLabels } from '@/hooks/useFetchTaskLabels';
import { useGlobalStore } from '@/store/global';
import type { TaskViewMode } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
import type {
TaskCompletedFilter,
@@ -30,7 +33,7 @@ import type {
TaskListViewOptions,
TaskOrderBy,
} from './listViewOptions';
-import { TASK_COMPLETED_FILTERS } from './listViewOptions';
+import { TASK_COMPLETED_FILTERS, toTaskLabelGroupBy } from './listViewOptions';
/** A display control the active collection fixes, so it has nothing to change. */
export type TaskListPinnedOption = 'ordering' | 'showSubTasks';
@@ -65,6 +68,8 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
const viewMode = useGlobalStore(systemStatusSelectors.taskListViewMode);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
const form = useForm();
+ useFetchTaskLabels();
+ const labelGroups = useTaskStore(taskLabelSelectors.labelGroups);
const groupingOptions = useMemo<Array<{ label: string; value: TaskGroupBy }>>(
() => [
{ label: t('taskList.groupBy.none'), value: 'none' },
@@ -72,8 +77,14 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
{ label: t('taskList.groupBy.assignee'), value: 'assignee' },
{ label: t('taskList.groupBy.member'), value: 'member' },
{ label: t('taskList.groupBy.priority'), value: 'priority' },
+ // One entry per label group: a task carries at most one label per
+ // group, so each lands in exactly one group / column.
+ ...labelGroups.map((group) => ({
+ label: t('taskList.groupBy.labelGroup', { name: group.name }),
+ value: toTaskLabelGroupBy(group.id),
+ })),
],
- [t],
+ [labelGroups, t],
);
const boardGroupingOptions = useMemo(
() => groupingOptions.filter((item) => item.value !== 'none'),
diff --git a/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx b/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx
index 8ec033bf909..318a8b893eb 100644
--- a/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx
+++ b/src/features/AgentTasks/AgentTaskList/filter/useTaskFilterFields.tsx
@@ -2,6 +2,7 @@ import { TASK_STATUSES } from '@lobechat/builtin-tool-task';
import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';
import {
agentDisplayName,
+ formatTaskLabelPath,
TASK_LIST_FILTER_NONE,
type TaskListFilterDateField,
type TaskListFilterSetField,
@@ -18,6 +19,7 @@ import {
CircleDashedIcon,
FolderClosedIcon,
SignalHighIcon,
+ TagIcon,
UserRoundIcon,
UserRoundPenIcon,
} from 'lucide-react';
@@ -29,12 +31,16 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { useFetchWorkspaceMembers } from '@/business/client/hooks/useFetchWorkspaceMembers';
import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';
import UserAvatar from '@/components/UserAvatar';
+import TaskLabelDot from '@/features/TaskLabels/TaskLabelDot';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import { useFetchTaskLabels } from '@/hooks/useFetchTaskLabels';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -112,6 +118,9 @@ export const useTaskFilterFields = ({
useFetchProjectList(!projectId);
const projects = useCurrentProjectList();
+ useFetchTaskLabels();
+ const taskLabels = useTaskStore(taskLabelSelectors.labels);
+
return useMemo(() => {
const statusField: TaskFilterSetFieldDef = {
icon: CircleDashedIcon,
@@ -253,6 +262,40 @@ export const useTaskFilterFields = ({
],
};
+ // A group value matches any label of the group; groups are listed before
+ // their labels so "Type" reads as "any Type".
+ const labelOptions: TaskFilterOption[] = [
+ {
+ icon: <Icon icon={TagIcon} size={OPTION_ICON_SIZE} />,
+ label: t('taskLabel.noLabels'),
+ value: TASK_LIST_FILTER_NONE,
+ },
+ ];
+ for (const label of taskLabels) {
+ if (label.parentId) continue;
+ labelOptions.push({
+ icon: <TaskLabelDot color={label.color} />,
+ label: label.isGroup ? t('taskLabel.anyInGroup', { name: label.name }) : label.name,
+ value: label.id,
+ });
+ if (!label.isGroup) continue;
+ for (const child of taskLabels) {
+ if (child.parentId !== label.id) continue;
+ labelOptions.push({
+ icon: <TaskLabelDot color={child.color} />,
+ label: formatTaskLabelPath(child, taskLabels),
+ value: child.id,
+ });
+ }
+ }
+ const labelField: TaskFilterSetFieldDef = {
+ icon: TagIcon,
+ key: 'label',
+ kind: 'set',
+ label: t('taskList.filter.field.label'),
+ options: labelOptions,
+ };
+
const dateFields: TaskFilterDateFieldDef[] = [
{
icon: CalendarPlusIcon,
@@ -281,6 +324,7 @@ export const useTaskFilterFields = ({
assigneeField,
creatorField,
...(projectId ? [] : [projectField]),
+ labelField,
...dateFields,
];
}, [
@@ -296,5 +340,6 @@ export const useTaskFilterFields = ({
selfUserId,
sidebarAgents,
t,
+ taskLabels,
]);
};
diff --git a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.label.test.ts b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.label.test.ts
new file mode 100644
index 00000000000..67a71019341
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.label.test.ts
@@ -0,0 +1,159 @@
+import type { TaskLabelWithUsage } from '@lobechat/types';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { useTaskStore } from '@/store/task';
+import type { TaskGroupItem, TaskListItem } from '@/store/task/slices/list/initialState';
+
+import {
+ buildKanbanColumns,
+ getKanbanCreateTaskModalProps,
+ getKanbanLabelPatch,
+ getTaskGroupCreateDefaults,
+ getTaskSubGroupCreateDefaults,
+ normalizeKanbanGroupBy,
+} from './kanbanBoardModel';
+import {
+ getTaskLabelGroupId,
+ groupTaskItems,
+ normalizeTaskListViewOptions,
+ toTaskLabelGroupBy,
+} from './listViewOptions';
+
+const registryEntry = (
+ id: string,
+ name: string,
+ extra: Partial<TaskLabelWithUsage> = {},
+): TaskLabelWithUsage => ({
+ color: '#111111',
+ id,
+ isGroup: false,
+ name,
+ parentId: null,
+ sortOrder: 0,
+ usageCount: 0,
+ ...extra,
+});
+
+const registry = [
+ registryEntry('fe', 'Frontend'),
+ registryEntry('type', 'Type', { isGroup: true }),
+ registryEntry('bug', 'Bug', { color: '#EB5757', parentId: 'type' }),
+ registryEntry('feature', 'Feature', { parentId: 'type' }),
+];
+
+const groupBy = toTaskLabelGroupBy('type');
+
+const task = (identifier: string, labels: TaskListItem['labels']): TaskListItem =>
+ ({ id: identifier, identifier, labels, status: 'backlog' }) as unknown as TaskListItem;
+
+beforeEach(() => {
+ useTaskStore.setState({ taskLabels: registry, taskLabelsInit: true });
+});
+
+describe('label group-by encoding', () => {
+ it('round-trips and survives view-option normalization', () => {
+ expect(getTaskLabelGroupId(groupBy)).toBe('type');
+ expect(normalizeKanbanGroupBy(groupBy)).toBe(groupBy);
+ expect(normalizeTaskListViewOptions({ groupBy }).groupBy).toBe(groupBy);
+ expect(normalizeTaskListViewOptions({ groupBy: 'label:' as never }).groupBy).toBe('status');
+ });
+});
+
+describe('buildKanbanColumns for a label group', () => {
+ it('names columns from the registry and keeps "no label" last', () => {
+ const groups = [
+ { key: 'label:none', labelId: null, tasks: [], total: 0 },
+ { key: 'label:feature', labelId: 'feature', tasks: [], total: 0 },
+ { key: 'label:bug', labelId: 'bug', tasks: [], total: 0 },
+ ] as unknown as TaskGroupItem[];
+
+ const columns = buildKanbanColumns(groups, groupBy);
+
+ expect(columns.map((column) => column.key)).toEqual([
+ 'label:bug',
+ 'label:feature',
+ 'label:none',
+ ]);
+ expect(columns[0].groupMeta).toMatchObject({ label: 'Bug', labelColor: '#EB5757' });
+ expect(columns.every((column) => column.droppable)).toBe(true);
+ });
+});
+
+describe('getKanbanLabelPatch', () => {
+ const columns = buildKanbanColumns(
+ [
+ { key: 'label:bug', labelId: 'bug', tasks: [], total: 0 },
+ { key: 'label:feature', labelId: 'feature', tasks: [], total: 0 },
+ { key: 'label:none', labelId: null, tasks: [], total: 0 },
+ ] as unknown as TaskGroupItem[],
+ groupBy,
+ );
+ const [bugColumn, featureColumn, noneColumn] = columns;
+ const fe = { color: '#111111', id: 'fe', name: 'Frontend', parentId: null };
+ const bug = { color: '#EB5757', id: 'bug', name: 'Bug', parentId: 'type' };
+
+ it('swaps the group label and keeps the others', () => {
+ const patch = getKanbanLabelPatch(task('T-1', [fe, bug]), groupBy, featureColumn);
+ expect(patch?.labels.map((label) => label.id)).toEqual(['fe', 'feature']);
+ });
+
+ it('drops the group label on the "no label" column', () => {
+ expect(getKanbanLabelPatch(task('T-1', [fe, bug]), groupBy, noneColumn)?.labels).toEqual([fe]);
+ });
+
+ it('is a no-op on the current column', () => {
+ expect(getKanbanLabelPatch(task('T-1', [bug]), groupBy, bugColumn)).toBeUndefined();
+ expect(getKanbanLabelPatch(task('T-2', []), groupBy, noneColumn)).toBeUndefined();
+ });
+});
+
+describe('groupTaskItems by label group', () => {
+ it('buckets list rows by their label in the group', () => {
+ const bug = { id: 'bug', name: 'Bug', parentId: 'type' };
+ const feature = { id: 'feature', name: 'Feature', parentId: 'type' };
+ const grouped = groupTaskItems(
+ [task('T-1', [feature]), task('T-2', []), task('T-3', [bug]), task('T-4', [bug])],
+ groupBy,
+ );
+
+ expect(
+ grouped.map(([meta, items]) => [meta.key, items.map((item) => item.identifier)]),
+ ).toEqual([
+ ['label:bug', ['T-3', 'T-4']],
+ ['label:feature', ['T-1']],
+ ['label:none', ['T-2']],
+ ]);
+ });
+});
+
+describe('label column create entry', () => {
+ it('pins the column label on the create modal, and none for "No label"', () => {
+ const groupBy = toTaskLabelGroupBy('g');
+ const bug = getTaskGroupCreateDefaults({
+ groupBy,
+ key: 'label:bug',
+ label: 'Bug',
+ labelId: 'bug',
+ });
+ const none = getTaskGroupCreateDefaults({
+ groupBy,
+ key: 'label:none',
+ label: '-',
+ labelId: null,
+ });
+
+ expect(bug).toEqual({ labelIds: ['bug'] });
+ expect(none).toEqual({});
+ expect(getKanbanCreateTaskModalProps(bug!, {}).defaultLabelIds).toEqual(['bug']);
+ expect(getKanbanCreateTaskModalProps(none!, {}).defaultLabelIds).toBeUndefined();
+ });
+
+ it('pins both labels when grouped and sub-grouped by two label groups', () => {
+ const nested = getTaskSubGroupCreateDefaults(
+ { groupBy: toTaskLabelGroupBy('type'), key: 'label:bug', label: 'Bug', labelId: 'bug' },
+ { groupBy: toTaskLabelGroupBy('area'), key: 'label:fe', label: 'FE', labelId: 'fe' },
+ );
+
+ expect(getKanbanCreateTaskModalProps(nested!, {}).defaultLabelIds).toEqual(['bug', 'fe']);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts
index 8b3d3071407..b99dd00a0b9 100644
--- a/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts
+++ b/src/features/AgentTasks/AgentTaskList/kanbanBoardModel.ts
@@ -1,4 +1,4 @@
-import type { TaskStatus } from '@lobechat/types';
+import type { TaskLabelRef, TaskStatus } from '@lobechat/types';
import type {
TaskGroupItem,
@@ -10,8 +10,11 @@ import type { CreateTaskContentProps } from '../CreateTaskModal/CreateTaskConten
import type { TaskGroupBy, TaskGroupMeta } from './listViewOptions';
import {
getTaskAssigneeGroupMeta,
+ getTaskLabelGroupId,
+ getTaskLabelGroupMeta,
getTaskMemberGroupMeta,
getTaskPriorityGroupMeta,
+ isTaskLabelGroupBy,
sortGroupEntries,
} from './listViewOptions';
@@ -64,7 +67,12 @@ export const STATUS_KANBAN_COLUMNS: KanbanColumnDefinition[] = [
];
export const normalizeKanbanGroupBy = (groupBy: TaskGroupBy): TaskKanbanGroupBy =>
- groupBy === 'assignee' || groupBy === 'member' || groupBy === 'priority' ? groupBy : 'status';
+ groupBy === 'assignee' ||
+ groupBy === 'member' ||
+ groupBy === 'priority' ||
+ isTaskLabelGroupBy(groupBy)
+ ? groupBy
+ : 'status';
export interface KanbanGroupQueryInput {
agentId?: string;
@@ -116,8 +124,9 @@ export const buildKanbanColumns = (
if (groupBy === 'status') return STATUS_KANBAN_COLUMNS;
const groupEntries = taskGroups.map((group) => {
- const meta =
- groupBy === 'assignee'
+ const meta = isTaskLabelGroupBy(groupBy)
+ ? getTaskLabelGroupMeta(groupBy, group.labelId)
+ : groupBy === 'assignee'
? getTaskAssigneeGroupMeta(group.assigneeAgentId)
: groupBy === 'member'
? getTaskMemberGroupMeta(group.assigneeUserId)
@@ -170,9 +179,41 @@ export const getKanbanTaskPatch = (
}
};
+/**
+ * The labels a card carries after a drop on a label board: the task's label
+ * from the board's group is swapped for the column's (or dropped for "no
+ * label"); its other labels stay. `undefined` when the drop changes nothing.
+ */
+export const getKanbanLabelPatch = (
+ task: Pick<TaskListItem, 'labels'>,
+ groupBy: TaskKanbanGroupBy,
+ column: KanbanColumnDefinition,
+): { labels: TaskLabelRef[] } | undefined => {
+ const groupId = getTaskLabelGroupId(groupBy);
+ const meta = column.groupMeta;
+ if (!groupId || !meta || meta.groupBy !== groupBy) return;
+
+ const current = task.labels ?? [];
+ const currentInGroup = current.find((label) => label.parentId === groupId);
+ const targetId = meta.labelId ?? null;
+ if ((currentInGroup?.id ?? null) === targetId) return;
+
+ const rest = current.filter((label) => label.parentId !== groupId);
+ return {
+ labels: targetId
+ ? [...rest, { color: meta.labelColor, id: targetId, name: meta.label, parentId: groupId }]
+ : rest,
+ };
+};
+
/** Pinned on the new task, so it lands in the column it was created from. */
export interface KanbanColumnCreateDefaults {
assigneeAgentId?: string;
+ /**
+ * Labels of a label column (and, when nested, of its parent group); the
+ * "No label" column pins none.
+ */
+ labelIds?: string[];
priority?: number;
}
@@ -185,6 +226,9 @@ export interface KanbanColumnCreateDefaults {
export const getTaskGroupCreateDefaults = (
groupMeta: TaskGroupMeta | undefined,
): KanbanColumnCreateDefaults | undefined => {
+ if (isTaskLabelGroupBy(groupMeta?.groupBy)) {
+ return groupMeta?.labelId ? { labelIds: [groupMeta.labelId] } : {};
+ }
switch (groupMeta?.groupBy) {
// New tasks start in backlog, so only that status group can receive one.
case 'status': {
@@ -211,7 +255,9 @@ export const getTaskSubGroupCreateDefaults = (
const parent = getTaskGroupCreateDefaults(parentMeta);
const sub = getTaskGroupCreateDefaults(subMeta);
if (!parent || !sub) return undefined;
- return { ...parent, ...sub };
+ // Two label groupings each pin one label; the task needs both to sit here.
+ const labelIds = [...(parent.labelIds ?? []), ...(sub.labelIds ?? [])];
+ return { ...parent, ...sub, ...(labelIds.length > 0 ? { labelIds } : {}) };
};
/**
@@ -237,6 +283,7 @@ export const getKanbanCreateTaskModalProps = (
scope: { agentId?: string; projectId?: string },
): CreateTaskContentProps => ({
agentId: defaults.assigneeAgentId ?? scope.agentId,
+ defaultLabelIds: defaults.labelIds?.length ? defaults.labelIds : undefined,
defaultPriority: defaults.priority,
// An agent-scoped board only holds that agent's tasks.
lockAssignee: !!scope.agentId,
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
index 6ef7839a37b..2ffc36cd269 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.test.ts
@@ -7,11 +7,13 @@ import {
collapseSubTasks,
compareTaskItems,
DEFAULT_TASK_LIST_VIEW_OPTIONS,
+ dropMissingLabelGroupings,
getCompletedWithin,
getVisibleTaskStatuses,
groupTaskItems,
HIDDEN_WHEN_COMPLETED_STATUSES,
isTaskHiddenByCompletedFilter,
+ normalizeTaskGroupBy,
normalizeTaskListViewOptions,
toStoredTaskListViewOptions,
} from './listViewOptions';
@@ -338,3 +340,40 @@ describe('getVisibleTaskStatuses', () => {
expect(getVisibleTaskStatuses({ completedTasks: 'week' })).toBeUndefined();
});
});
+
+describe('dropMissingLabelGroupings', () => {
+ const options = { groupBy: 'label:g-type', subGroupBy: 'label:g-area' } as const;
+
+ it('keeps label groupings until the registry has loaded', () => {
+ expect(dropMissingLabelGroupings(options, undefined)).toBe(options);
+ });
+
+ it('keeps label groupings whose group still exists', () => {
+ expect(dropMissingLabelGroupings(options, new Set(['g-type', 'g-area']))).toBe(options);
+ });
+
+ it('falls back to the defaults for a deleted group', () => {
+ expect(dropMissingLabelGroupings(options, new Set(['g-area']))).toEqual({
+ groupBy: 'status',
+ subGroupBy: 'label:g-area',
+ });
+ expect(dropMissingLabelGroupings(options, new Set())).toEqual({
+ groupBy: 'status',
+ subGroupBy: 'none',
+ });
+ });
+
+ it('leaves non-label groupings alone', () => {
+ const plain = { groupBy: 'priority', subGroupBy: 'none' } as const;
+ expect(dropMissingLabelGroupings(plain, new Set())).toBe(plain);
+ });
+});
+
+describe('normalizeTaskGroupBy', () => {
+ it('keeps label groupings for the list, and falls back for unknown values', () => {
+ expect(normalizeTaskGroupBy('label:g-type', 'status')).toBe('label:g-type');
+ expect(normalizeTaskGroupBy('priority', 'status')).toBe('priority');
+ expect(normalizeTaskGroupBy('bogus', 'none')).toBe('none');
+ expect(normalizeTaskGroupBy(undefined, 'status')).toBe('status');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
index e7845563e2d..5aa7a0f6067 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
@@ -7,9 +7,27 @@ import {
import type { TaskStatus } from '@lobechat/types';
import { t } from 'i18next';
+import { getTaskStoreState } from '@/store/task';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
-export type TaskGroupBy = 'assignee' | 'automationMode' | 'member' | 'none' | 'priority' | 'status';
+/** Grouping by one label group: one group per label of that group, plus "no label". */
+export type TaskLabelGroupBy = `label:${string}`;
+export type TaskGroupBy =
+ 'assignee' | 'automationMode' | 'member' | 'none' | 'priority' | 'status' | TaskLabelGroupBy;
+
+const TASK_LABEL_GROUP_BY_PREFIX = 'label:';
+
+export const toTaskLabelGroupBy = (labelGroupId: string): TaskLabelGroupBy =>
+ `${TASK_LABEL_GROUP_BY_PREFIX}${labelGroupId}`;
+
+export const isTaskLabelGroupBy = (groupBy: string | undefined): groupBy is TaskLabelGroupBy =>
+ !!groupBy &&
+ groupBy.startsWith(TASK_LABEL_GROUP_BY_PREFIX) &&
+ groupBy.length > TASK_LABEL_GROUP_BY_PREFIX.length;
+
+/** The label group a `label:<groupId>` grouping groups by. */
+export const getTaskLabelGroupId = (groupBy: string | undefined): string | undefined =>
+ isTaskLabelGroupBy(groupBy) ? groupBy.slice(TASK_LABEL_GROUP_BY_PREFIX.length) : undefined;
export type TaskOrderBy = 'assignee' | 'createdAt' | 'priority' | 'status' | 'title' | 'updatedAt';
export type TaskOrderDirection = 'asc' | 'desc';
/**
@@ -90,6 +108,12 @@ export interface TaskGroupMeta {
groupBy: TaskGroupBy;
key: string;
label: string;
+ /** Label color of a label group (`groupBy` is `label:<groupId>`). */
+ labelColor?: string | null;
+ /** The label of a label group; null is the "no label" group. */
+ labelId?: string | null;
+ /** Registry position of a label group, for ordering. */
+ labelRank?: number;
priority?: number;
status?: 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running' | 'scheduled';
}
@@ -155,15 +179,59 @@ export const toStoredTaskListViewOptions = <T extends Pick<TaskListViewOptions,
hideCompleted: options.completedTasks === 'none',
});
+/**
+ * A `label:<groupId>` grouping persists in view options, so it outlives the
+ * label group it points at. Once the registry has loaded, fall back to the
+ * default for a grouping whose group is gone — otherwise every board request
+ * would keep asking the server to group by a deleted group. Before the
+ * registry loads (`labelGroupIds` undefined) the choice is kept as-is.
+ */
+export const dropMissingLabelGroupings = <
+ T extends Pick<TaskListViewOptions, 'groupBy' | 'subGroupBy'>,
+>(
+ options: T,
+ labelGroupIds: ReadonlySet<string> | undefined,
+): T => {
+ if (!labelGroupIds) return options;
+ const isMissing = (groupBy: TaskGroupBy) => {
+ const groupId = getTaskLabelGroupId(groupBy);
+ return !!groupId && !labelGroupIds.has(groupId);
+ };
+ const groupByMissing = isMissing(options.groupBy);
+ const subGroupByMissing = isMissing(options.subGroupBy);
+ if (!groupByMissing && !subGroupByMissing) return options;
+ return {
+ ...options,
+ groupBy: groupByMissing ? DEFAULT_TASK_LIST_VIEW_OPTIONS.groupBy : options.groupBy,
+ subGroupBy: subGroupByMissing ? DEFAULT_TASK_LIST_VIEW_OPTIONS.subGroupBy : options.subGroupBy,
+ };
+};
+
+/**
+ * A grouping the list can render, or `fallback`. `label:<groupId>` is
+ * open-ended; whether its group still exists is settled upstream by
+ * {@link dropMissingLabelGroupings}.
+ */
+export const normalizeTaskGroupBy = (
+ value: TaskGroupBy | string | undefined,
+ fallback: TaskGroupBy,
+): TaskGroupBy => {
+ if (!value) return fallback;
+ if (isTaskLabelGroupBy(value)) return value;
+ return TASK_GROUP_BY_SET.has(value as TaskGroupBy) ? (value as TaskGroupBy) : fallback;
+};
+
export const normalizeTaskListViewOptions = (
value?: StoredTaskListViewOptions | null,
): TaskListViewOptions => {
const next = value ?? {};
- const groupBy = TASK_GROUP_BY_SET.has(next.groupBy as TaskGroupBy)
- ? (next.groupBy as TaskGroupBy)
+ const isKnownGroupBy = (value: unknown): value is TaskGroupBy =>
+ TASK_GROUP_BY_SET.has(value as TaskGroupBy) || isTaskLabelGroupBy(value as string);
+ const groupBy = isKnownGroupBy(next.groupBy)
+ ? next.groupBy
: DEFAULT_TASK_LIST_VIEW_OPTIONS.groupBy;
- const subGroupBy = TASK_GROUP_BY_SET.has(next.subGroupBy as TaskGroupBy)
- ? (next.subGroupBy as TaskGroupBy)
+ const subGroupBy = isKnownGroupBy(next.subGroupBy)
+ ? next.subGroupBy
: DEFAULT_TASK_LIST_VIEW_OPTIONS.subGroupBy;
return {
@@ -264,6 +332,38 @@ export const getTaskMemberGroupMeta = (userId: string | null | undefined): TaskG
};
};
+/**
+ * Group meta of one label column in a `label:<groupId>` grouping. Name and
+ * color come from the registry (an empty column has no task to read them
+ * from), falling back to the task's own label ref.
+ */
+export const getTaskLabelGroupMeta = (
+ groupBy: TaskLabelGroupBy,
+ labelId: string | null | undefined,
+ fallback?: { color?: string | null; name: string },
+): TaskGroupMeta => {
+ if (!labelId) {
+ return {
+ groupBy,
+ key: 'label:none',
+ label: t('taskLabel.noLabel', { ns: 'chat' }),
+ labelId: null,
+ labelRank: Number.MAX_SAFE_INTEGER,
+ };
+ }
+ const registry = getTaskStoreState().taskLabels;
+ const index = registry.findIndex((label) => label.id === labelId);
+ const entry = index === -1 ? undefined : registry[index];
+ return {
+ groupBy,
+ key: `label:${labelId}`,
+ label: entry?.name ?? fallback?.name ?? labelId,
+ labelColor: entry?.color ?? fallback?.color,
+ labelId,
+ labelRank: index === -1 ? Number.MAX_SAFE_INTEGER - 1 : index,
+ };
+};
+
const getTaskAssigneeSortValue = (task: TaskListItem) => task.assigneeAgentId ?? '';
export const getTaskPriorityGroupMeta = (
@@ -355,6 +455,11 @@ export const compareTaskItems = (
};
export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): TaskGroupMeta => {
+ if (isTaskLabelGroupBy(groupBy)) {
+ const groupId = getTaskLabelGroupId(groupBy);
+ const label = task.labels?.find((item) => item.parentId === groupId);
+ return getTaskLabelGroupMeta(groupBy, label?.id, label);
+ }
switch (groupBy) {
case 'assignee': {
return getTaskAssigneeGroupMeta(task.assigneeAgentId);
@@ -404,6 +509,7 @@ export const getTaskGroupMeta = (task: TaskListItem, groupBy: TaskGroupBy): Task
};
const getGroupRank = (group: TaskGroupMeta, groupBy: TaskGroupBy): number => {
+ if (isTaskLabelGroupBy(groupBy)) return group.labelRank ?? Number.MAX_SAFE_INTEGER;
switch (groupBy) {
case 'automationMode': {
return group.automationMode === 'schedule' ? 0 : 1;
diff --git a/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts b/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts
index 9fd462290bb..e37a049f1f3 100644
--- a/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts
+++ b/src/features/AgentTasks/AgentTaskList/taskCreateDraft.ts
@@ -7,6 +7,8 @@ export interface TaskCreateDraft {
assigneeAgentId?: string;
assigneeUserId?: string | null;
execution?: unknown;
+ /** Picked labels, by id; resolved against the scope's registry on restore. */
+ labelIds?: unknown;
markdown?: string;
priority?: number;
visibility?: 'private' | 'public';
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index dfe75f8055e..8e61a56d813 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -1,6 +1,6 @@
'use client';
-import type { TaskExecutionConfig } from '@lobechat/types';
+import type { TaskExecutionConfig, TaskLabelRef } from '@lobechat/types';
import { toTaskExecutionConfigPatch } from '@lobechat/types';
import { useEditor } from '@lobehub/editor/react';
import {
@@ -10,11 +10,12 @@ import {
confirmModal,
cssVar,
Flexbox,
+ Icon,
Text,
toast,
useModalContext,
} from '@lobehub/ui';
-import { Minimize2, Paperclip, X } from 'lucide-react';
+import { Minimize2, Paperclip, TagIcon, X } from 'lucide-react';
import { type KeyboardEvent, memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -25,9 +26,13 @@ import {
pickAndInsertAttachments,
} from '@/features/EditorCanvas/editorAttachments';
import { releaseEditorSelection } from '@/features/EditorCanvas/releaseEditorSelection';
+import { pickedLabelIds, resolveTaskLabelRefs } from '@/features/TaskLabels/labelPickerModel';
+import TaskLabelChips from '@/features/TaskLabels/TaskLabelChips';
+import TaskLabelPicker from '@/features/TaskLabels/TaskLabelPicker';
import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
-import { useTaskStore } from '@/store/task';
+import { getTaskStoreState, useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -57,6 +62,8 @@ import { useTitleEnterToInstruction } from './useTitleEnterToInstruction';
export interface CreateTaskContentProps {
agentId?: string;
+ /** Initial labels, e.g. the label column of a board grouped by a label group. */
+ defaultLabelIds?: string[];
/** Initial priority, e.g. the Kanban priority column the modal was opened from. */
defaultPriority?: number;
/**
@@ -81,6 +88,7 @@ export interface CreateTaskContentProps {
const CreateTaskContent = memo<CreateTaskContentProps>(
({
agentId,
+ defaultLabelIds,
defaultPriority = 0,
lockAssignee,
onCreated,
@@ -100,6 +108,26 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
const [title, setTitle] = useState('');
const [priority, setPriority] = useState(defaultPriority);
+ const isLabelsInit = useTaskStore(taskLabelSelectors.isLabelsInit);
+ const labelRegistry = useTaskStore(taskLabelSelectors.labels);
+ const [labels, setLabels] = useState<TaskLabelRef[]>(() =>
+ resolveTaskLabelRefs(getTaskStoreState().taskLabels, defaultLabelIds),
+ );
+ // Opened before the registry loaded (a cold start on a label-grouped
+ // list): hold the column's labels until they can be resolved, instead of
+ // filtering them against an empty registry and losing them.
+ const pendingDefaultLabelIdsRef = useRef(
+ getTaskStoreState().taskLabelsInit ? undefined : defaultLabelIds,
+ );
+ useEffect(() => {
+ const pending = pendingDefaultLabelIdsRef.current;
+ if (!isLabelsInit || !pending?.length) return;
+ pendingDefaultLabelIdsRef.current = undefined;
+ // Keep anything the user already picked meanwhile.
+ setLabels((current) =>
+ current.length > 0 ? current : resolveTaskLabelRefs(labelRegistry, pending),
+ );
+ }, [isLabelsInit, labelRegistry]);
const [assigneeAgentId, setAssigneeAgentId] = useState<string | undefined>(agentId);
// `undefined` follows the default (the creator); `null` is an explicit "unassigned".
const [memberChoice, setMemberChoice] = useState<string | null | undefined>();
@@ -196,6 +224,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
...(isScheduled ? toScheduledCreateParams(scheduleDraft, config) : { config }),
editorData: editorJson,
instruction: instruction || title.trim(),
+ ...pickedLabelIds(labels, pendingDefaultLabelIdsRef.current),
name: title.trim() || undefined,
priority: priority || undefined,
projectId,
@@ -226,6 +255,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
editor,
isMemberPending,
isScheduled,
+ labels,
onCreated,
priority,
projectId,
@@ -376,6 +406,28 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
</Block>
</TaskPriorityTag>
+ <TaskLabelPicker value={labels} onChange={setLabels}>
+ <Block
+ clickable
+ horizontal
+ align="center"
+ gap={6}
+ height={24}
+ paddingBlock={3}
+ paddingInline={8}
+ variant={'borderless'}
+ >
+ {labels.length > 0 ? (
+ <TaskLabelChips labels={labels} max={3} />
+ ) : (
+ <>
+ <Icon color={cssVar.colorTextDescription} icon={TagIcon} size={14} />
+ <Text fontSize={12}>{t('taskLabel.label')}</Text>
+ </>
+ )}
+ </Block>
+ </TaskLabelPicker>
+
{activeWorkspaceId && (
<AssigneeMemberSelector
currentUserId={assigneeUserId}
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index 3555416872d..89f3f5decbd 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -5,6 +5,7 @@ import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import TaskLabelChips from '@/features/TaskLabels/TaskLabelChips';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useTaskStore } from '@/store/task';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
@@ -151,6 +152,7 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
onRequestSubtasks={handleRequestSubtasks}
onSubtaskClick={handleSubtaskClick}
/>
+ <TaskLabelChips labels={task.labels} />
</Flexbox>
);
@@ -246,6 +248,7 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {
</Flexbox>
<Flexbox horizontal align={'center'} gap={8} style={FLEX_MIN_WIDTH_0}>
<TaskPriorityTag priority={task.priority} taskIdentifier={task.id} />
+ <TaskLabelChips labels={task.labels} max={2} />
{scheduleNode}
{timeNode}
</Flexbox>
diff --git a/src/features/Settings/labels/index.tsx b/src/features/Settings/labels/index.tsx
index 328c4248db7..d6cbaaace3f 100644
--- a/src/features/Settings/labels/index.tsx
+++ b/src/features/Settings/labels/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import LabelsContent from '@/features/WorkspaceSetting/Labels';
+import LabelsContent from '@/features/TaskLabels/Settings/LabelsSettingsTabs';
/**
* Personal label registry. The same surface serves both scopes — it reads the
diff --git a/src/features/TaskLabels/Settings/LabelsSettingsTabs.tsx b/src/features/TaskLabels/Settings/LabelsSettingsTabs.tsx
new file mode 100644
index 00000000000..f619eee33e2
--- /dev/null
+++ b/src/features/TaskLabels/Settings/LabelsSettingsTabs.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import { Flexbox, Tabs } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useSearchParams } from 'react-router';
+
+import AgentLabelsSettings from '@/features/WorkspaceSetting/Labels';
+
+import TaskLabelsSettings from '.';
+
+type LabelKind = 'agent' | 'task';
+
+/**
+ * The Labels settings page holds both registries — agent labels and task
+ * labels — as tabs. `?kind=task` deep-links the task tab.
+ */
+const LabelsSettingsTabs = memo(() => {
+ const { t } = useTranslation('setting');
+ const [searchParams, setSearchParams] = useSearchParams();
+ const kind: LabelKind = searchParams.get('kind') === 'task' ? 'task' : 'agent';
+
+ return (
+ <Flexbox gap={16}>
+ <Tabs
+ activeKey={kind}
+ items={[
+ { key: 'agent', label: t('taskLabels.tabs.agent') },
+ { key: 'task', label: t('taskLabels.tabs.task') },
+ ]}
+ onChange={(key) => {
+ const next = new URLSearchParams(searchParams);
+ if (key === 'task') next.set('kind', 'task');
+ else next.delete('kind');
+ setSearchParams(next, { replace: true });
+ }}
+ />
+ {kind === 'task' ? <TaskLabelsSettings /> : <AgentLabelsSettings />}
+ </Flexbox>
+ );
+});
+
+LabelsSettingsTabs.displayName = 'LabelsSettingsTabs';
+
+export default LabelsSettingsTabs;
diff --git a/src/features/TaskLabels/Settings/TaskLabelFormModal.tsx b/src/features/TaskLabels/Settings/TaskLabelFormModal.tsx
new file mode 100644
index 00000000000..e731a1381bd
--- /dev/null
+++ b/src/features/TaskLabels/Settings/TaskLabelFormModal.tsx
@@ -0,0 +1,192 @@
+import {
+ DEFAULT_TASK_LABEL_COLOR,
+ TASK_LABEL_COLORS,
+ TASK_LABEL_NAME_MAX_LENGTH,
+ type TaskLabelWithUsage,
+} from '@lobechat/types';
+import {
+ Button,
+ createModal,
+ Flexbox,
+ Input,
+ ModalFooter,
+ Select,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isDuplicateLabelNameError } from '@/features/WorkspaceSetting/Labels/errors';
+import { useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({
+ swatch: {
+ cursor: 'pointer',
+ width: 20,
+ height: 20,
+ borderWidth: 2,
+ borderStyle: 'solid',
+ borderColor: 'transparent',
+ borderRadius: '50%',
+ transitionProperty: 'transform',
+ transitionDuration: cssVar.motionDurationFast,
+ transform: { 'default': null, ':hover': 'scale(1.15)' },
+ },
+ swatchActive: {
+ borderColor: cssVar.colorText,
+ },
+});
+
+export interface TaskLabelFormModalOptions {
+ /** Creating a group rather than a label. */
+ isGroup?: boolean;
+ /** Present when editing. */
+ label?: TaskLabelWithUsage;
+ /** Prefill the group when creating a label from a group row. */
+ parentId?: string | null;
+}
+
+const NO_GROUP = '__none__';
+
+const TaskLabelFormContent = memo<TaskLabelFormModalOptions>(({ isGroup, label, parentId }) => {
+ const { t } = useTranslation(['setting', 'common']);
+ const { close } = useModalContext();
+ const createTaskLabel = useTaskStore((s) => s.createTaskLabel);
+ const updateTaskLabel = useTaskStore((s) => s.updateTaskLabel);
+ const groups = useTaskStore(taskLabelSelectors.labelGroups);
+
+ const editingGroup = label?.isGroup ?? !!isGroup;
+ const [name, setName] = useState(label?.name ?? '');
+ const [color, setColor] = useState<string>(label?.color ?? DEFAULT_TASK_LABEL_COLOR);
+ const [group, setGroup] = useState<string>(label?.parentId ?? parentId ?? NO_GROUP);
+ const [loading, setLoading] = useState(false);
+
+ const handleSave = async () => {
+ const trimmed = name.trim();
+ if (!trimmed || loading) return;
+ const nextParentId = editingGroup || group === NO_GROUP ? null : group;
+
+ setLoading(true);
+ try {
+ if (label) {
+ await updateTaskLabel(label.id, {
+ color,
+ name: trimmed,
+ ...(editingGroup || nextParentId === (label.parentId ?? null)
+ ? {}
+ : { parentId: nextParentId }),
+ });
+ } else {
+ await createTaskLabel({
+ color,
+ isGroup: editingGroup,
+ name: trimmed,
+ parentId: nextParentId,
+ });
+ }
+ close();
+ } catch (error) {
+ if (isDuplicateLabelNameError(error)) {
+ toast.error(t('taskLabels.form.duplicateName'));
+ return;
+ }
+ // Server messages are English (they also serve the CLI and agents), so
+ // only map the known rule error. A BAD_REQUEST here is a regroup that
+ // collides with tasks already carrying a sibling.
+ const code = (error as { data?: { code?: string } })?.data?.code;
+ const isRegroup = !!label && !!nextParentId && nextParentId !== (label.parentId ?? null);
+ toast.error(
+ code === 'BAD_REQUEST' && isRegroup
+ ? t('taskLabels.form.groupConflict')
+ : t('operationFailed', { ns: 'common' }),
+ );
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <>
+ <Flexbox gap={16} paddingBlock={8} paddingInline={16}>
+ <Flexbox gap={8}>
+ <span>{t('taskLabels.form.name')}</span>
+ <Input
+ autoFocus
+ maxLength={TASK_LABEL_NAME_MAX_LENGTH}
+ value={name}
+ placeholder={t(
+ editingGroup
+ ? 'taskLabels.form.groupNamePlaceholder'
+ : 'taskLabels.form.namePlaceholder',
+ )}
+ onChange={(e) => setName(e.target.value)}
+ onPressEnter={handleSave}
+ />
+ </Flexbox>
+ {!editingGroup && groups.length > 0 && (
+ <Flexbox gap={8}>
+ <span>{t('taskLabels.form.group')}</span>
+ <Select
+ value={group}
+ options={[
+ { label: t('taskLabels.form.noGroup'), value: NO_GROUP },
+ ...groups.map((item) => ({ label: item.name, value: item.id })),
+ ]}
+ onChange={(value: string) => setGroup(value)}
+ />
+ </Flexbox>
+ )}
+ <Flexbox gap={8}>
+ <span>{t('taskLabels.form.color')}</span>
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ {TASK_LABEL_COLORS.map((preset) => (
+ <span
+ aria-label={preset}
+ key={preset}
+ role={'button'}
+ {...sx([styles.swatch, color === preset && styles.swatchActive], undefined, {
+ backgroundColor: preset,
+ })}
+ onClick={() => setColor(preset)}
+ />
+ ))}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button disabled={!name.trim()} loading={loading} type={'primary'} onClick={handleSave}>
+ {t('ok', { defaultValue: 'OK', ns: 'common' })}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+});
+
+TaskLabelFormContent.displayName = 'TaskLabelFormContent';
+
+export const openTaskLabelFormModal = (options: TaskLabelFormModalOptions = {}) => {
+ const isGroup = options.label?.isGroup ?? options.isGroup;
+ return createModal({
+ content: <TaskLabelFormContent {...options} />,
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate(
+ options.label
+ ? isGroup
+ ? 'taskLabels.form.editGroupTitle'
+ : 'taskLabels.form.editTitle'
+ : isGroup
+ ? 'taskLabels.form.createGroupTitle'
+ : 'taskLabels.form.createTitle',
+ { ns: 'setting' },
+ ),
+ width: 420,
+ });
+};
diff --git a/src/features/TaskLabels/Settings/index.tsx b/src/features/TaskLabels/Settings/index.tsx
new file mode 100644
index 00000000000..ec90db861b4
--- /dev/null
+++ b/src/features/TaskLabels/Settings/index.tsx
@@ -0,0 +1,244 @@
+'use client';
+
+import type { TaskLabelWithUsage } from '@lobechat/types';
+import {
+ ActionIcon,
+ Button,
+ confirmModal,
+ DropdownMenu,
+ Empty,
+ Flexbox,
+ Icon,
+ SearchBar,
+ Text,
+ toast,
+ Tooltip,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { EllipsisIcon, FolderPlusIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchTaskLabels } from '@/hooks/useFetchTaskLabels';
+import { usePermission } from '@/hooks/usePermission';
+import { useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
+import { sx } from '@/styles/sx';
+
+import TaskLabelDot from '../TaskLabelDot';
+import { openTaskLabelFormModal } from './TaskLabelFormModal';
+
+const styles = stylex.create({
+ row: {
+ paddingBlock: 10,
+ paddingInlineEnd: 12,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ },
+});
+
+const USAGE_COL_WIDTH = 88;
+const ACTION_COL_WIDTH = 32;
+
+interface RowProps {
+ canManage: boolean;
+ depth: number;
+ label: TaskLabelWithUsage;
+ manageBlockedReason?: string;
+}
+
+const TaskLabelRow = memo<RowProps>(({ canManage, depth, label, manageBlockedReason }) => {
+ const { t } = useTranslation(['setting', 'common']);
+ const deleteTaskLabel = useTaskStore((s) => s.deleteTaskLabel);
+
+ const confirmDelete = () =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t(label.isGroup ? 'taskLabels.delete.groupDesc' : 'taskLabels.delete.desc', {
+ count: label.usageCount,
+ }),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await deleteTaskLabel(label.id);
+ } catch {
+ toast.error(t('operationFailed', { ns: 'common' }));
+ }
+ },
+ title: t('taskLabels.delete.title', { name: label.name }),
+ });
+
+ const menuItems = [
+ {
+ icon: <Icon icon={PencilIcon} />,
+ key: 'edit',
+ label: t('edit', { ns: 'common' }),
+ onClick: () => openTaskLabelFormModal({ label }),
+ },
+ ...(label.isGroup
+ ? [
+ {
+ icon: <Icon icon={PlusIcon} />,
+ key: 'add',
+ label: t('taskLabels.actions.addToGroup'),
+ onClick: () => openTaskLabelFormModal({ parentId: label.id }),
+ },
+ ]
+ : []),
+ { type: 'divider' as const },
+ {
+ danger: true,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: confirmDelete,
+ },
+ ];
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ {...sx([styles.row], undefined, { paddingInlineStart: 12 + depth * 24 })}
+ >
+ <Flexbox horizontal align={'center'} flex={1} gap={12} style={{ minWidth: 0 }}>
+ <TaskLabelDot color={label.color} size={10} />
+ <Text ellipsis weight={500}>
+ {label.name}
+ </Text>
+ {label.isGroup && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskLabels.groupBadge')}
+ </Text>
+ )}
+ </Flexbox>
+ <Text
+ fontSize={12}
+ style={{ flex: 'none', textAlign: 'end', width: USAGE_COL_WIDTH }}
+ type={'secondary'}
+ >
+ {label.isGroup ? null : t('taskLabels.usage', { count: label.usageCount })}
+ </Text>
+ <Flexbox align={'center'} flex={'none'} style={{ width: ACTION_COL_WIDTH }}>
+ {canManage ? (
+ <DropdownMenu items={menuItems}>
+ <ActionIcon icon={EllipsisIcon} size={'small'} title={t('taskLabels.actions.more')} />
+ </DropdownMenu>
+ ) : (
+ <Tooltip title={manageBlockedReason}>
+ <ActionIcon
+ disabled
+ icon={EllipsisIcon}
+ size={'small'}
+ title={t('taskLabels.actions.more')}
+ />
+ </Tooltip>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+TaskLabelRow.displayName = 'TaskLabelRow';
+
+/** Rows in registry order: top-level labels and groups, each group followed by its labels. */
+const toRows = (labels: TaskLabelWithUsage[], keyword: string) => {
+ const query = keyword.trim().toLowerCase();
+ const matches = (label: TaskLabelWithUsage) => label.name.toLowerCase().includes(query);
+ const rows: { depth: number; label: TaskLabelWithUsage }[] = [];
+ for (const label of labels) {
+ if (label.parentId) continue;
+ const children = labels.filter((child) => child.parentId === label.id);
+ const shownChildren = query && !matches(label) ? children.filter(matches) : children;
+ if (query && !matches(label) && shownChildren.length === 0) continue;
+ rows.push({ depth: 0, label });
+ for (const child of shownChildren) rows.push({ depth: 1, label: child });
+ }
+ return rows;
+};
+
+/**
+ * Settings → Labels → Tasks: the task label registry. Create labels and
+ * label groups, rename, recolor, move a label into a group, delete.
+ */
+const TaskLabelsSettings = memo(() => {
+ const { t } = useTranslation(['setting', 'common']);
+ const { error, isLoading, mutate } = useFetchTaskLabels();
+ const isInit = useTaskStore(taskLabelSelectors.isLabelsInit);
+ const labels = useTaskStore(taskLabelSelectors.labels);
+
+ // Same gate as task writes: members who can create content manage the
+ // shared registry; viewers only read it. Personal mode is always allowed.
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const { allowed, reason } = usePermission('create_content');
+ const canManage = activeWorkspaceId ? allowed : true;
+ const manageBlockedReason = activeWorkspaceId ? reason : undefined;
+
+ const [keyword, setKeyword] = useState('');
+ const rows = useMemo(() => toRows(labels, keyword), [keyword, labels]);
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <SearchBar
+ allowClear
+ placeholder={t('taskLabels.filterPlaceholder')}
+ style={{ maxWidth: 240 }}
+ value={keyword}
+ onChange={(e) => setKeyword(e.target.value)}
+ />
+ <Flexbox horizontal gap={8}>
+ <Button
+ disabled={!canManage}
+ icon={FolderPlusIcon}
+ onClick={() => openTaskLabelFormModal({ isGroup: true })}
+ >
+ {t('taskLabels.actions.createGroup')}
+ </Button>
+ <Button
+ disabled={!canManage}
+ icon={PlusIcon}
+ type={'primary'}
+ onClick={() => openTaskLabelFormModal()}
+ >
+ {t('taskLabels.actions.create')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ {!isInit && isLoading ? (
+ <SkeletonList rows={4} />
+ ) : error && !isInit ? (
+ <Flexbox align={'center'} gap={12} paddingBlock={40}>
+ <Empty description={t('taskLabels.loadFailed')} />
+ <Button onClick={() => mutate()}>{t('retry', { ns: 'common' })}</Button>
+ </Flexbox>
+ ) : rows.length === 0 ? (
+ <Empty
+ description={keyword.trim() ? t('taskLabels.filterEmpty') : t('taskLabels.empty')}
+ style={{ paddingBlock: 40 }}
+ />
+ ) : (
+ <Flexbox gap={2}>
+ {rows.map(({ depth, label }) => (
+ <TaskLabelRow
+ canManage={canManage}
+ depth={depth}
+ key={label.id}
+ label={label}
+ manageBlockedReason={manageBlockedReason}
+ />
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+TaskLabelsSettings.displayName = 'TaskLabelsSettings';
+
+export default TaskLabelsSettings;
diff --git a/src/features/TaskLabels/TaskLabelChips.tsx b/src/features/TaskLabels/TaskLabelChips.tsx
new file mode 100644
index 00000000000..7d205fa234f
--- /dev/null
+++ b/src/features/TaskLabels/TaskLabelChips.tsx
@@ -0,0 +1,85 @@
+import type { TaskLabelRef } from '@lobechat/types';
+import { Flexbox, Text, Tooltip } from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+
+import TaskLabelDot from './TaskLabelDot';
+
+const styles = stylex.create({
+ chip: {
+ display: 'inline-flex',
+ flex: 'none',
+ gap: 6,
+ alignItems: 'center',
+ maxWidth: 140,
+ height: 20,
+ paddingInline: 8,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: sxVar.colorBorderSecondary,
+ borderRadius: 10,
+ fontSize: 12,
+ lineHeight: 1,
+ color: sxVar.colorTextSecondary,
+ },
+ // Named chips give up width first (ellipsis), so the "+N" count never clips.
+ shrinkable: {
+ flexGrow: '0',
+ flexShrink: '1',
+ flexBasis: 'auto',
+ minWidth: 0,
+ },
+});
+
+interface TaskLabelChipProps {
+ label: Pick<TaskLabelRef, 'color' | 'name'>;
+}
+
+export const TaskLabelChip = memo<TaskLabelChipProps>(({ label }) => (
+ <span {...stylex.props(styles.chip, styles.shrinkable)} title={label.name}>
+ <TaskLabelDot color={label.color} />
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {label.name}
+ </Text>
+ </span>
+));
+
+TaskLabelChip.displayName = 'TaskLabelChip';
+
+interface TaskLabelChipsProps {
+ labels?: TaskLabelRef[] | null;
+ /** Chips shown before the rest collapse into a "+N" chip with a tooltip. */
+ max?: number;
+ /** Wrap onto more lines instead of truncating (roomy surfaces such as task detail). */
+ wrap?: boolean;
+}
+
+/** A task's labels as colored chips, for list rows, board cards and the detail page. */
+const TaskLabelChips = memo<TaskLabelChipsProps>(({ labels, max = 3, wrap }) => {
+ if (!labels?.length) return null;
+ const shown = labels.slice(0, max);
+ const hidden = labels.slice(max);
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={{ minWidth: 0, ...(wrap ? { flexWrap: 'wrap' } : { overflow: 'hidden' }) }}
+ >
+ {shown.map((label) => (
+ <TaskLabelChip key={label.id} label={label} />
+ ))}
+ {hidden.length > 0 && (
+ <Tooltip title={hidden.map((label) => label.name).join(', ')}>
+ <span {...stylex.props(styles.chip)}>+{hidden.length}</span>
+ </Tooltip>
+ )}
+ </Flexbox>
+ );
+});
+
+TaskLabelChips.displayName = 'TaskLabelChips';
+
+export default TaskLabelChips;
diff --git a/src/features/TaskLabels/TaskLabelDot.tsx b/src/features/TaskLabels/TaskLabelDot.tsx
new file mode 100644
index 00000000000..ce2e5c64d73
--- /dev/null
+++ b/src/features/TaskLabels/TaskLabelDot.tsx
@@ -0,0 +1,35 @@
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+
+import { sx } from '@/styles/sx';
+
+const styles = stylex.create({
+ dot: {
+ flex: 'none',
+ width: 8,
+ height: 8,
+ borderRadius: '50%',
+ backgroundColor: sxVar.colorTextQuaternary,
+ },
+});
+
+interface TaskLabelDotProps {
+ /** Hex color from the registry (validated server-side); falls back to a neutral token. */
+ color?: string | null;
+ size?: number;
+}
+
+const TaskLabelDot = memo<TaskLabelDotProps>(({ color, size }) => (
+ <span
+ aria-hidden
+ {...sx([styles.dot], undefined, {
+ ...(color ? { backgroundColor: color } : undefined),
+ ...(size ? { height: size, width: size } : undefined),
+ })}
+ />
+));
+
+TaskLabelDot.displayName = 'TaskLabelDot';
+
+export default TaskLabelDot;
diff --git a/src/features/TaskLabels/TaskLabelPicker.tsx b/src/features/TaskLabels/TaskLabelPicker.tsx
new file mode 100644
index 00000000000..55f9e1d153c
--- /dev/null
+++ b/src/features/TaskLabels/TaskLabelPicker.tsx
@@ -0,0 +1,290 @@
+import { DEFAULT_TASK_LABEL_COLOR, type TaskLabel, type TaskLabelRef } from '@lobechat/types';
+import { Button, cssVar, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';
+import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckIcon, PlusIcon } from 'lucide-react';
+import type { CSSProperties, KeyboardEvent, ReactNode } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchTaskLabels } from '@/hooks/useFetchTaskLabels';
+import { usePermission } from '@/hooks/usePermission';
+import { useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
+import { saveToast } from '@/store/utils/saveToast';
+
+import {
+ buildTaskLabelPickerSections,
+ canCreateTaskLabel,
+ toggleTaskLabelSelection,
+ toTaskLabelRef,
+} from './labelPickerModel';
+import TaskLabelDot from './TaskLabelDot';
+
+const styles = stylex.create({
+ searchInput: {
+ 'width': '100%',
+ 'paddingBlock': 6,
+ 'paddingInline': 10,
+ 'borderWidth': 0,
+ 'borderBlockEndWidth': 1,
+ 'borderBlockEndStyle': 'solid',
+ 'borderBlockEndColor': sxVar.colorBorderSecondary,
+ 'fontFamily': 'inherit',
+ 'fontSize': 13,
+ 'color': sxVar.colorText,
+ 'backgroundColor': 'transparent',
+ 'outline': 'none',
+ '::placeholder': { color: sxVar.colorTextPlaceholder },
+ },
+ sectionHeader: {
+ paddingBlock: 4,
+ paddingInline: 8,
+ fontSize: 12,
+ lineHeight: 1.4,
+ color: sxVar.colorTextTertiary,
+ },
+});
+
+const triggerStyle: CSSProperties = {
+ alignItems: 'center',
+ display: 'inline-flex',
+ maxWidth: '100%',
+ minWidth: 0,
+};
+
+type PickerOption =
+ { key: string; kind: 'create' } | { key: string; kind: 'label'; label: TaskLabel };
+
+interface TaskLabelPickerProps {
+ children: ReactNode;
+ disabled?: boolean;
+ /** Called with the full next selection after every toggle. */
+ onChange: (next: TaskLabelRef[]) => void;
+ value: TaskLabelRef[];
+}
+
+/**
+ * Multi-select label picker: search, toggle, and create a label inline from
+ * the search text. Labels of a group are listed under it and are mutually
+ * exclusive — picking one swaps out its sibling, as the server enforces.
+ */
+const TaskLabelPicker = memo<TaskLabelPickerProps>(({ children, disabled, onChange, value }) => {
+ const { t } = useTranslation('chat');
+ const { allowed: canEdit, reason } = usePermission('create_content');
+ const [search, setSearch] = useState('');
+ const [activeIndex, setActiveIndex] = useState(0);
+ const [creating, setCreating] = useState(false);
+ const listRef = useRef<HTMLDivElement>(null);
+
+ const { error, isLoading, mutate } = useFetchTaskLabels();
+ const isInit = useTaskStore(taskLabelSelectors.isLabelsInit);
+ // Until the registry is known, an empty list is not "no labels": inline
+ // creation could collide with a name that already exists.
+ const loadFailed = !!error && !isInit;
+ const registry = useTaskStore(taskLabelSelectors.labels);
+ const createTaskLabel = useTaskStore((s) => s.createTaskLabel);
+ // The workspace the picker is showing now, read when a create completes.
+ const workspaceId = useActiveWorkspaceId();
+ const workspaceIdRef = useRef(workspaceId);
+ // The selection as it is now, for an inline create that resolves later.
+ const valueRef = useRef(value);
+ useEffect(() => {
+ workspaceIdRef.current = workspaceId;
+ valueRef.current = value;
+ }, [workspaceId, value]);
+
+ const sections = useMemo(
+ () => buildTaskLabelPickerSections(registry, search),
+ [registry, search],
+ );
+ const showCreate = isInit && canCreateTaskLabel(registry, search);
+ const flatOptions = useMemo<PickerOption[]>(
+ () => [
+ ...sections.flatMap((section) =>
+ section.labels.map((label) => ({ key: label.id, kind: 'label' as const, label })),
+ ),
+ ...(showCreate ? [{ key: '__create__', kind: 'create' as const }] : []),
+ ],
+ [sections, showCreate],
+ );
+ const indexByKey = useMemo(
+ () => new Map(flatOptions.map((option, index) => [option.key, index])),
+ [flatOptions],
+ );
+ const selectedIds = useMemo(() => new Set(value.map((label) => label.id)), [value]);
+
+ useEffect(() => {
+ listRef.current
+ ?.querySelector<HTMLElement>(`[data-label-index="${activeIndex}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ }, [activeIndex]);
+
+ const handleCreate = useCallback(async () => {
+ const name = search.trim();
+ if (!name || creating) return;
+ setCreating(true);
+ const startedIn = workspaceIdRef.current;
+ try {
+ const label = await createTaskLabel({ color: DEFAULT_TASK_LABEL_COLOR, name });
+ // Switched workspaces meanwhile: the label belongs to the old one.
+ if (workspaceIdRef.current !== startedIn) return;
+ setSearch('');
+ // Merge into the latest selection: other labels may have been toggled
+ // while the request was in flight.
+ onChange([...valueRef.current, toTaskLabelRef(label)]);
+ } catch (error) {
+ saveToast(error, { title: t('taskLabel.createFailed') });
+ } finally {
+ setCreating(false);
+ }
+ }, [createTaskLabel, creating, onChange, search, t]);
+
+ const handleSelect = useCallback(
+ (option: PickerOption) => {
+ if (option.kind === 'create') {
+ void handleCreate();
+ return;
+ }
+ onChange(toggleTaskLabelSelection(value, option.label));
+ },
+ [handleCreate, onChange, value],
+ );
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ if (flatOptions.length === 0) return;
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ setActiveIndex((index) => (index + 1) % flatOptions.length);
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ setActiveIndex((index) => (index - 1 + flatOptions.length) % flatOptions.length);
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ const target = flatOptions[activeIndex];
+ if (target) handleSelect(target);
+ }
+ },
+ [activeIndex, flatOptions, handleSelect],
+ );
+
+ const renderLabel = (label: TaskLabel) => {
+ const index = indexByKey.get(label.id) ?? 0;
+ const selected = selectedIds.has(label.id);
+ return (
+ <div data-label-index={index} key={label.id} onMouseEnter={() => setActiveIndex(index)}>
+ <NavItem
+ active={index === activeIndex}
+ icon={<TaskLabelDot color={label.color} />}
+ style={{ flexShrink: 0 }}
+ title={label.name}
+ extra={
+ selected ? <Icon color={cssVar.colorTextSecondary} icon={CheckIcon} size={14} /> : null
+ }
+ onClick={() => handleSelect({ key: label.id, kind: 'label', label })}
+ />
+ </div>
+ );
+ };
+
+ const createIndex = indexByKey.get('__create__');
+ const blocked = disabled || !canEdit;
+
+ const content = (
+ <Flexbox onClick={(event) => event.stopPropagation()}>
+ <input
+ autoFocus
+ {...stylex.props(styles.searchInput)}
+ placeholder={t('taskLabel.searchPlaceholder')}
+ value={search}
+ onKeyDown={handleKeyDown}
+ onChange={(event) => {
+ setSearch(event.target.value);
+ setActiveIndex(0);
+ }}
+ />
+ {isLoading ? (
+ <SkeletonList rows={4} />
+ ) : loadFailed ? (
+ <Flexbox align={'center'} gap={8} justify={'center'} padding={16}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskLabels.loadFailed', { ns: 'setting' })}
+ </Text>
+ <Button onClick={() => mutate()}>{t('retry', { ns: 'common' })}</Button>
+ </Flexbox>
+ ) : flatOptions.length === 0 ? (
+ <Flexbox align={'center'} justify={'center'} padding={16}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskLabel.empty')}
+ </Text>
+ </Flexbox>
+ ) : (
+ <Flexbox
+ gap={4}
+ padding={8}
+ ref={listRef}
+ style={{ maxHeight: '50vh', overflowY: 'auto', width: '100%' }}
+ >
+ {sections.map((section) => (
+ <Flexbox gap={4} key={section.group?.id ?? '__loose__'}>
+ {section.group && (
+ <div {...stylex.props(styles.sectionHeader)}>{section.group.name}</div>
+ )}
+ {section.labels.map(renderLabel)}
+ </Flexbox>
+ ))}
+ {createIndex !== undefined && (
+ <div data-label-index={createIndex} onMouseEnter={() => setActiveIndex(createIndex)}>
+ <NavItem
+ active={createIndex === activeIndex}
+ disabled={creating}
+ icon={PlusIcon}
+ style={{ flexShrink: 0 }}
+ title={t('taskLabel.createNamed', { name: search.trim() })}
+ onClick={() => void handleCreate()}
+ />
+ </div>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+
+ const trigger = blocked ? (
+ <Tooltip title={disabled ? undefined : reason}>
+ <div
+ style={{ ...triggerStyle, cursor: 'not-allowed', opacity: 0.5 }}
+ onClick={(event) => event.stopPropagation()}
+ >
+ {children}
+ </div>
+ </Tooltip>
+ ) : (
+ <div style={triggerStyle} onClick={(event) => event.stopPropagation()}>
+ {children}
+ </div>
+ );
+
+ return (
+ <Popover
+ content={content}
+ disabled={blocked}
+ placement={'bottomLeft'}
+ styles={{ content: { padding: 0, width: 260 } }}
+ trigger={'click'}
+ onOpenChange={(open) => {
+ if (!open) setSearch('');
+ }}
+ >
+ {trigger}
+ </Popover>
+ );
+});
+
+TaskLabelPicker.displayName = 'TaskLabelPicker';
+
+export default TaskLabelPicker;
diff --git a/src/features/TaskLabels/labelPickerModel.test.ts b/src/features/TaskLabels/labelPickerModel.test.ts
new file mode 100644
index 00000000000..a7c32e3584b
--- /dev/null
+++ b/src/features/TaskLabels/labelPickerModel.test.ts
@@ -0,0 +1,94 @@
+import type { TaskLabel } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildTaskLabelPickerSections,
+ canCreateTaskLabel,
+ pickedLabelIds,
+ resolveTaskLabelRefs,
+ toggleTaskLabelSelection,
+ toTaskLabelRef,
+} from './labelPickerModel';
+
+const label = (id: string, name: string, extra: Partial<TaskLabel> = {}): TaskLabel => ({
+ color: '#000',
+ id,
+ isGroup: false,
+ name,
+ parentId: null,
+ sortOrder: 0,
+ ...extra,
+});
+
+const registry: TaskLabel[] = [
+ label('fe', 'Frontend'),
+ label('type', 'Type', { isGroup: true }),
+ label('bug', 'Bug', { parentId: 'type' }),
+ label('feature', 'Feature', { parentId: 'type' }),
+ label('empty', 'Empty group', { isGroup: true }),
+];
+
+describe('buildTaskLabelPickerSections', () => {
+ it('lists loose labels first, then non-empty groups', () => {
+ const sections = buildTaskLabelPickerSections(registry);
+ expect(sections.map((s) => s.group?.id)).toEqual([undefined, 'type']);
+ expect(sections[1].labels.map((l) => l.id)).toEqual(['bug', 'feature']);
+ });
+
+ it('filters by label or group name', () => {
+ expect(
+ buildTaskLabelPickerSections(registry, 'bu').flatMap((s) => s.labels.map((l) => l.id)),
+ ).toEqual(['bug']);
+ expect(
+ buildTaskLabelPickerSections(registry, 'type').flatMap((s) => s.labels.map((l) => l.id)),
+ ).toEqual(['bug', 'feature']);
+ });
+});
+
+describe('toggleTaskLabelSelection', () => {
+ it('adds, removes, and swaps within a group', () => {
+ const [fe, , bug, feature] = registry;
+ let selected = toggleTaskLabelSelection([], fe);
+ selected = toggleTaskLabelSelection(selected, bug);
+ expect(selected.map((l) => l.id)).toEqual(['fe', 'bug']);
+
+ selected = toggleTaskLabelSelection(selected, feature);
+ expect(selected.map((l) => l.id)).toEqual(['fe', 'feature']);
+
+ selected = toggleTaskLabelSelection(selected, fe);
+ expect(selected).toEqual([toTaskLabelRef(feature)]);
+ });
+});
+
+describe('canCreateTaskLabel', () => {
+ it('needs a non-empty name not already taken', () => {
+ expect(canCreateTaskLabel(registry, ' ')).toBe(false);
+ expect(canCreateTaskLabel(registry, 'bug')).toBe(false);
+ expect(canCreateTaskLabel(registry, 'Backend')).toBe(true);
+ });
+});
+
+describe('resolveTaskLabelRefs', () => {
+ it('keeps id order, drops unknown ids and groups', () => {
+ const registry = [
+ label('g', 'Type', { isGroup: true }),
+ label('bug', 'Bug', { parentId: 'g' }),
+ label('fe', 'Frontend'),
+ ];
+
+ expect(resolveTaskLabelRefs(registry, ['fe', 'gone', 'g', 'bug']).map((l) => l.id)).toEqual([
+ 'fe',
+ 'bug',
+ ]);
+ expect(resolveTaskLabelRefs(registry, undefined)).toEqual([]);
+ });
+});
+
+describe('pickedLabelIds', () => {
+ it('prefers picked labels, falls back to pending ids, else omits the key', () => {
+ const bug = { color: null, id: 'bug', name: 'Bug', parentId: null };
+ expect(pickedLabelIds([bug], ['fe'])).toEqual({ labelIds: ['bug'] });
+ expect(pickedLabelIds([], ['fe'])).toEqual({ labelIds: ['fe'] });
+ expect(pickedLabelIds([], undefined)).toEqual({});
+ });
+});
diff --git a/src/features/TaskLabels/labelPickerModel.ts b/src/features/TaskLabels/labelPickerModel.ts
new file mode 100644
index 00000000000..fa481ff102a
--- /dev/null
+++ b/src/features/TaskLabels/labelPickerModel.ts
@@ -0,0 +1,99 @@
+import type { TaskLabel, TaskLabelRef } from '@lobechat/types';
+
+export interface TaskLabelPickerSection {
+ /** The group, or undefined for the top-level labels. */
+ group?: TaskLabel;
+ labels: TaskLabel[];
+}
+
+const matches = (value: string, query: string) => value.toLowerCase().includes(query);
+
+/**
+ * Picker sections: ungrouped labels first, then one section per group with
+ * its labels. A search keeps a label when its own name or its group's name
+ * matches; empty groups are left out.
+ */
+export const buildTaskLabelPickerSections = (
+ registry: TaskLabel[],
+ keyword = '',
+): TaskLabelPickerSection[] => {
+ const query = keyword.trim().toLowerCase();
+ const groups = registry.filter((label) => label.isGroup);
+ const groupIds = new Set(groups.map((group) => group.id));
+ const assignable = registry.filter((label) => !label.isGroup);
+
+ const loose = assignable.filter(
+ (label) => (!label.parentId || !groupIds.has(label.parentId)) && matches(label.name, query),
+ );
+ const sections: TaskLabelPickerSection[] = loose.length > 0 ? [{ labels: loose }] : [];
+
+ for (const group of groups) {
+ const groupMatches = !!query && matches(group.name, query);
+ const labels = assignable.filter(
+ (label) => label.parentId === group.id && (groupMatches || matches(label.name, query)),
+ );
+ if (labels.length > 0) sections.push({ group, labels });
+ }
+
+ return sections;
+};
+
+export const toTaskLabelRef = (label: TaskLabel): TaskLabelRef => ({
+ color: label.color,
+ id: label.id,
+ name: label.name,
+ parentId: label.parentId,
+});
+
+/**
+ * Resolve label ids against the registry, keeping the ids' order. Ids the
+ * registry does not hold (deleted, or from another workspace) are dropped, and
+ * group rows are never returned (they cannot be assigned).
+ */
+export const resolveTaskLabelRefs = (
+ registry: TaskLabel[],
+ ids: readonly string[] | undefined,
+): TaskLabelRef[] => {
+ if (!ids?.length) return [];
+ const byId = new Map(registry.map((label) => [label.id, label]));
+ return ids.flatMap((id) => {
+ const label = byId.get(id);
+ return label && !label.isGroup ? [toTaskLabelRef(label)] : [];
+ });
+};
+
+/**
+ * The `labelIds` to create a task with: the picked labels, or — when nothing
+ * is picked yet because the registry has not loaded — the ids still waiting to
+ * be resolved (the server validates them). Empty → no key.
+ */
+export const pickedLabelIds = (
+ picked: TaskLabelRef[],
+ pending: readonly string[] | undefined,
+): { labelIds?: string[] } => {
+ if (picked.length > 0) return { labelIds: picked.map((label) => label.id) };
+ return pending?.length ? { labelIds: [...pending] } : {};
+};
+
+/**
+ * Toggle one label in a selection. Picking a grouped label replaces the
+ * sibling from the same group (one label per group, as the server enforces).
+ */
+export const toggleTaskLabelSelection = (
+ selected: TaskLabelRef[],
+ label: TaskLabel,
+): TaskLabelRef[] => {
+ if (selected.some((item) => item.id === label.id)) {
+ return selected.filter((item) => item.id !== label.id);
+ }
+ const rest = label.parentId
+ ? selected.filter((item) => item.parentId !== label.parentId)
+ : selected;
+ return [...rest, toTaskLabelRef(label)];
+};
+
+/** Whether `keyword` would create a new label: non-empty and no exact (case-insensitive) name. */
+export const canCreateTaskLabel = (registry: TaskLabel[], keyword: string): boolean => {
+ const name = keyword.trim().toLowerCase();
+ return !!name && !registry.some((label) => label.name.toLowerCase() === name);
+};
diff --git a/src/hooks/useFetchTaskLabels.ts b/src/hooks/useFetchTaskLabels.ts
new file mode 100644
index 00000000000..17df5c2ad2a
--- /dev/null
+++ b/src/hooks/useFetchTaskLabels.ts
@@ -0,0 +1,35 @@
+import { useLayoutEffect } from 'react';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useTaskStore } from '@/store/task';
+import { taskLabelSelectors } from '@/store/task/selectors';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/slices/auth/selectors';
+
+/**
+ * Sync the task label registry into the task store, read through
+ * `taskLabelSelectors`. Mounted by every surface that renders or picks task
+ * labels; SWR dedupes concurrent mounts.
+ *
+ * @returns isLoading - not loaded yet and a fetch is in flight
+ * @returns error / mutate - for a failure state with Retry
+ */
+export const useFetchTaskLabels = () => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const workspaceId = useActiveWorkspaceId();
+ const useFetch = useTaskStore((s) => s.useFetchTaskLabels);
+ const resetScope = useTaskStore((s) => s.internal_resetTaskLabelsScope);
+ const isInit = useTaskStore(
+ (s) => taskLabelSelectors.isLabelsInit(s) && s.taskLabelsScope === workspaceId,
+ );
+
+ // Before paint, so a workspace switch never shows the previous registry —
+ // including when the new workspace's request fails.
+ useLayoutEffect(() => {
+ resetScope(workspaceId);
+ }, [resetScope, workspaceId]);
+
+ const { error, isValidating, mutate } = useFetch(!!isLogin, workspaceId);
+
+ return { error, isLoading: !isInit && isValidating, mutate };
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 89c7e724844..e0fe1d69762 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -1024,6 +1024,10 @@ export const matchDomain =
/**
* Aggregate registry — one entry point for every domain's keys.
*/
+export const taskLabelKeys = {
+ list: def('taskLabel:list', () => ['taskLabel:list'] as const),
+};
+
export const swrKeys = {
agent: agentConfigKeys,
agentDocument: agentDocumentSWRKeys,
@@ -1063,6 +1067,7 @@ export const swrKeys = {
serverConfig: serverConfigKeys,
share: shareKeys,
stats: statsKeys,
+ taskLabel: taskLabelKeys,
thread: threadKeys,
tool: toolKeys,
topic: topicKeys,
diff --git a/src/routes/(main)/[workspaceSlug]/settings/labels/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/labels/index.tsx
index 286b38a37ef..2b97c98ee00 100644
--- a/src/routes/(main)/[workspaceSlug]/settings/labels/index.tsx
+++ b/src/routes/(main)/[workspaceSlug]/settings/labels/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import WorkspaceLabelsContent from '@/features/WorkspaceSetting/Labels';
+import WorkspaceLabelsContent from '@/features/TaskLabels/Settings/LabelsSettingsTabs';
const WorkspaceLabelsSetting = () => <WorkspaceLabelsContent />;
diff --git a/src/services/task.ts b/src/services/task.ts
index fa96a783d03..92c353de0bf 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -53,7 +53,7 @@ class TaskService {
completedWithin?: TaskCompletedWindow;
excludeStatuses?: TaskStatus[];
filter?: TaskListFilter;
- groupBy?: 'assignee' | 'member' | 'priority';
+ groupBy?: 'assignee' | 'label' | 'member' | 'priority';
groups?: Array<{
key: string;
limit?: number;
@@ -61,6 +61,8 @@ class TaskService {
statuses: string[];
}>;
includeArchived?: boolean;
+ /** The label group whose labels are the columns when `groupBy` is 'label'. */
+ labelGroupId?: string;
parentTaskId?: string | null;
projectId?: string;
/** "My tasks" narrowing: assigned to the caller, or created by them. */
@@ -129,6 +131,8 @@ class TaskService {
description?: string;
editorData?: unknown;
instruction: string;
+ /** Labels attached on creation; validated before the task is written. */
+ labelIds?: string[];
name?: string;
parentTaskId?: string;
priority?: number;
diff --git a/src/services/taskLabel/index.ts b/src/services/taskLabel/index.ts
new file mode 100644
index 00000000000..ce6dd13d202
--- /dev/null
+++ b/src/services/taskLabel/index.ts
@@ -0,0 +1,49 @@
+import type { TaskLabelRef, TaskLabelWithUsage } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+export interface TaskLabelInput {
+ color?: string | null;
+ description?: string | null;
+ isGroup?: boolean;
+ name: string;
+ parentId?: string | null;
+}
+
+export interface TaskLabelPatch {
+ color?: string | null;
+ description?: string | null;
+ name?: string;
+ parentId?: string | null;
+ sortOrder?: number;
+}
+
+class TaskLabelService {
+ list = (): Promise<TaskLabelWithUsage[]> => lambdaClient.taskLabel.list.query();
+
+ create = (params: TaskLabelInput) => lambdaClient.taskLabel.create.mutate(params);
+
+ update = (id: string, value: TaskLabelPatch) =>
+ lambdaClient.taskLabel.update.mutate({ id, value });
+
+ delete = (id: string) => lambdaClient.taskLabel.delete.mutate({ id });
+
+ /** Attach labels; a grouped label replaces the sibling the task already carried. */
+ addToTask = (taskId: string, labelIds: string[]): Promise<TaskLabelRef[]> =>
+ lambdaClient.taskLabel.addToTask.mutate({ labelIds, taskId });
+
+ removeFromTask = (taskId: string, labelIds: string[]): Promise<TaskLabelRef[]> =>
+ lambdaClient.taskLabel.removeFromTask.mutate({ labelIds, taskId });
+
+ /** Add and remove labels in one transaction, so a swap never commits half-way. */
+ changeForTask = (
+ taskId: string,
+ delta: { add?: string[]; remove?: string[] },
+ ): Promise<TaskLabelRef[]> => lambdaClient.taskLabel.changeForTask.mutate({ ...delta, taskId });
+
+ /** Replace the full label set; prefer add/remove for single toggles. */
+ setForTask = (taskId: string, labelIds: string[]): Promise<TaskLabelRef[]> =>
+ lambdaClient.taskLabel.setForTask.mutate({ labelIds, taskId });
+}
+
+export const taskLabelService = new TaskLabelService();
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 46a7226371e..1a473769a24 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -478,7 +478,8 @@ export interface SystemStatus {
* `hideCompleted` it replaces before normalization could migrate it.
*/
completedTasks?: 'all' | 'day' | 'month' | 'none' | 'week';
- groupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status';
+ /** `label:<groupId>` groups by one label group. */
+ groupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status' | `label:${string}`;
/** @deprecated Replaced by `completedTasks`; read once to migrate. */
hideCompleted?: boolean;
nestedSubTasks: boolean;
@@ -486,7 +487,7 @@ export interface SystemStatus {
orderCompletedByRecency: boolean;
orderDirection: 'asc' | 'desc';
showSubTasks: boolean;
- subGroupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status';
+ subGroupBy: 'assignee' | 'member' | 'none' | 'priority' | 'status' | `label:${string}`;
};
/**
* Height of the chat bottom terminal panel. Persisted so resizing survives remounts.
diff --git a/src/store/task/initialState.ts b/src/store/task/initialState.ts
index 7d0d0d0929b..abed6c664a6 100644
--- a/src/store/task/initialState.ts
+++ b/src/store/task/initialState.ts
@@ -1,11 +1,14 @@
import type { TaskDetailSliceState } from './slices/detail/initialState';
import { initialTaskDetailSliceState } from './slices/detail/initialState';
+import type { TaskLabelSliceState } from './slices/label/initialState';
+import { initialTaskLabelSliceState } from './slices/label/initialState';
import type { TaskListSliceState } from './slices/list/initialState';
import { initialTaskListSliceState } from './slices/list/initialState';
-export type TaskStoreState = TaskDetailSliceState & TaskListSliceState;
+export type TaskStoreState = TaskDetailSliceState & TaskLabelSliceState & TaskListSliceState;
export const initialState: TaskStoreState = {
...initialTaskListSliceState,
...initialTaskDetailSliceState,
+ ...initialTaskLabelSliceState,
};
diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.ts
index 37af205d4db..341c97fcccd 100644
--- a/src/store/task/selectors/detailSelectors.ts
+++ b/src/store/task/selectors/detailSelectors.ts
@@ -29,6 +29,9 @@ const activeTaskStatus = (s: TaskStoreState) => activeTaskDetail(s)?.status;
const activeTaskPriority = (s: TaskStoreState) => activeTaskDetail(s)?.priority ?? 0;
+const EMPTY_LABELS: NonNullable<TaskDetailData['labels']> = [];
+const activeTaskLabels = (s: TaskStoreState) => activeTaskDetail(s)?.labels ?? EMPTY_LABELS;
+
const activeTaskVisibility = (s: TaskStoreState): 'private' | 'public' =>
activeTaskDetail(s)?.visibility ?? 'public';
@@ -176,6 +179,7 @@ const topicDrawerFocusRequest = (s: TaskStoreState) => s.activeTopicDrawerFocusR
export const taskDetailSelectors = {
activeTaskAgentId,
+ activeTaskLabels,
activeTaskAssigneeUserId,
activeTaskAutomationMode,
activeTaskCheckpoint,
diff --git a/src/store/task/selectors/index.ts b/src/store/task/selectors/index.ts
index d074162ffa0..fd596e59f91 100644
--- a/src/store/task/selectors/index.ts
+++ b/src/store/task/selectors/index.ts
@@ -1,3 +1,4 @@
export { taskActivitySelectors } from './activitySelectors';
export { taskDetailSelectors } from './detailSelectors';
+export { taskLabelSelectors } from './labelSelectors';
export { taskListSelectors } from './listSelectors';
diff --git a/src/store/task/selectors/labelSelectors.ts b/src/store/task/selectors/labelSelectors.ts
new file mode 100644
index 00000000000..6d04868b011
--- /dev/null
+++ b/src/store/task/selectors/labelSelectors.ts
@@ -0,0 +1,18 @@
+import type { TaskLabelWithUsage } from '@lobechat/types';
+
+import type { TaskStoreState } from '../initialState';
+
+const EMPTY: TaskLabelWithUsage[] = [];
+
+const labels = (s: TaskStoreState) => (s.taskLabelsInit ? s.taskLabels : EMPTY);
+const isLabelsInit = (s: TaskStoreState) => s.taskLabelsInit;
+const labelGroups = (s: TaskStoreState) => labels(s).filter((label) => label.isGroup);
+const labelById = (id: string | null | undefined) => (s: TaskStoreState) =>
+ id ? labels(s).find((label) => label.id === id) : undefined;
+
+export const taskLabelSelectors = {
+ isLabelsInit,
+ labelById,
+ labelGroups,
+ labels,
+};
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index 5641fff69a9..70210a557ab 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -349,6 +349,7 @@ export class TaskDetailSliceActionImpl {
editorData?: unknown;
/** Bind a goal entity (`goals` row) to the created task. */
instruction: string;
+ labelIds?: string[];
name?: string;
parentTaskId?: string;
priority?: number;
diff --git a/src/store/task/slices/label/action.test.ts b/src/store/task/slices/label/action.test.ts
new file mode 100644
index 00000000000..ad34c795d9b
--- /dev/null
+++ b/src/store/task/slices/label/action.test.ts
@@ -0,0 +1,178 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { taskLabelService } from '@/services/taskLabel';
+
+import { useTaskStore } from '../../store';
+
+vi.mock('@/services/taskLabel', () => ({
+ taskLabelService: {
+ addToTask: vi.fn(),
+ changeForTask: vi.fn(),
+ create: vi.fn(),
+ list: vi.fn(),
+ removeFromTask: vi.fn(),
+ },
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
+
+const label = (id: string, name: string) =>
+ ({ color: null, id, isGroup: false, name, parentId: null, usageCount: 0 }) as any;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useTaskStore.setState({ taskLabels: [], taskLabelsInit: false, taskLabelsScope: null });
+});
+
+describe('TaskLabelSliceAction', () => {
+ describe('workspace scope', () => {
+ it('clears the registry when the scope changes', () => {
+ useTaskStore.setState({
+ taskLabels: [label('a', 'From A')],
+ taskLabelsInit: true,
+ taskLabelsScope: 'ws-a',
+ });
+
+ useTaskStore.getState().internal_resetTaskLabelsScope('ws-b');
+
+ expect(useTaskStore.getState()).toMatchObject({
+ taskLabels: [],
+ taskLabelsInit: false,
+ taskLabelsScope: 'ws-b',
+ });
+ });
+
+ it('keeps the registry when the scope is unchanged', () => {
+ useTaskStore.setState({
+ taskLabels: [label('a', 'From A')],
+ taskLabelsInit: true,
+ taskLabelsScope: 'ws-a',
+ });
+
+ useTaskStore.getState().internal_resetTaskLabelsScope('ws-a');
+
+ expect(useTaskStore.getState().taskLabels).toHaveLength(1);
+ });
+
+ it('ignores a response for a workspace the user already left', () => {
+ useTaskStore.setState({ taskLabelsScope: 'ws-b' });
+ useTaskStore.getState().useFetchTaskLabels(true, 'ws-a');
+ const { onSuccess } = vi.mocked(useClientDataSWR).mock.calls[0][2] as any;
+
+ onSuccess([label('a', 'From A')]);
+ expect(useTaskStore.getState().taskLabelsInit).toBe(false);
+
+ useTaskStore.getState().useFetchTaskLabels(true, 'ws-b');
+ const { onSuccess: onSuccessB } = vi.mocked(useClientDataSWR).mock.calls[1][2] as any;
+ onSuccessB([label('b', 'From B')]);
+ expect(useTaskStore.getState()).toMatchObject({
+ taskLabels: [expect.objectContaining({ name: 'From B' })],
+ taskLabelsInit: true,
+ });
+ });
+ });
+
+ describe('createTaskLabel', () => {
+ it('does not add a label created in a workspace the user has since left', async () => {
+ useTaskStore.setState({ taskLabels: [], taskLabelsInit: true, taskLabelsScope: 'ws-a' });
+ vi.mocked(taskLabelService.create).mockImplementation(async () => {
+ useTaskStore.getState().internal_resetTaskLabelsScope('ws-b');
+ return label('a', 'From A');
+ });
+
+ await useTaskStore.getState().createTaskLabel({ name: 'From A' });
+
+ expect(useTaskStore.getState().taskLabels).toEqual([]);
+ });
+ });
+
+ describe('setTaskLabels', () => {
+ it('sends the add + remove delta as one request', async () => {
+ vi.mocked(taskLabelService.changeForTask).mockResolvedValue([]);
+ const frontend = label('l1', 'Frontend');
+ const backend = label('l2', 'Backend');
+
+ const ok = await useTaskStore.getState().setTaskLabels('T-1', [frontend], [backend]);
+
+ expect(ok).toBe(true);
+ expect(taskLabelService.changeForTask).toHaveBeenCalledTimes(1);
+ expect(taskLabelService.changeForTask).toHaveBeenCalledWith('T-1', {
+ add: ['l2'],
+ remove: ['l1'],
+ });
+ expect(taskLabelService.addToTask).not.toHaveBeenCalled();
+ expect(taskLabelService.removeFromTask).not.toHaveBeenCalled();
+ });
+
+ const stubCollections = (refresh: () => Promise<void>) => {
+ const overlay = { commit: vi.fn(), rollback: vi.fn() };
+ useTaskStore.setState({
+ internal_beginCollectionTaskOptimistic: vi.fn(() => overlay),
+ refreshTaskList: vi.fn(refresh),
+ } as any);
+ vi.mocked(taskLabelService.changeForTask).mockResolvedValue([]);
+ return overlay;
+ };
+
+ it('commits the list overlay only after the lists re-fetched', async () => {
+ const order: string[] = [];
+ const overlay = stubCollections(async () => {
+ order.push('refresh');
+ });
+ overlay.commit.mockImplementation(() => order.push('commit'));
+
+ await useTaskStore.getState().setTaskLabels('T-1', [], [label('l2', 'Backend')]);
+
+ expect(order).toEqual(['refresh', 'commit']);
+ expect(overlay.rollback).not.toHaveBeenCalled();
+ });
+
+ it('sends rapid edits to one task in click order', async () => {
+ stubCollections(async () => {});
+ const sent: string[] = [];
+ let releaseFirst!: () => void;
+ vi.mocked(taskLabelService.changeForTask)
+ .mockImplementationOnce(async (_id, delta) => {
+ await new Promise<void>((resolve) => (releaseFirst = resolve));
+ sent.push(`add ${delta.add}`);
+ return [];
+ })
+ .mockImplementationOnce(async (_id, delta) => {
+ sent.push(`add ${delta.add}`);
+ return [];
+ });
+ const a = label('a', 'A');
+ const b = label('b', 'B');
+
+ const first = useTaskStore.getState().setTaskLabels('T-1', [], [a]);
+ const second = useTaskStore.getState().setTaskLabels('T-1', [a], [b]);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(sent).toEqual([]);
+ releaseFirst();
+ await Promise.all([first, second]);
+
+ expect(sent).toEqual(['add a', 'add b']);
+ });
+
+ it('drops the overlay instead of persisting it when the re-fetch fails', async () => {
+ const overlay = stubCollections(async () => {
+ throw new Error('offline');
+ });
+
+ const ok = await useTaskStore.getState().setTaskLabels('T-1', [], [label('l2', 'Backend')]);
+
+ expect(ok).toBe(true);
+ expect(overlay.commit).not.toHaveBeenCalled();
+ expect(overlay.rollback).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/store/task/slices/label/action.ts b/src/store/task/slices/label/action.ts
new file mode 100644
index 00000000000..18c13bc4ec6
--- /dev/null
+++ b/src/store/task/slices/label/action.ts
@@ -0,0 +1,178 @@
+import type { TaskLabelRef, TaskLabelWithUsage } from '@lobechat/types';
+
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { taskLabelKeys } from '@/libs/swr/keys';
+import { type TaskLabelInput, type TaskLabelPatch, taskLabelService } from '@/services/taskLabel';
+import type { StoreSetter } from '@/store/types';
+import { saveToast } from '@/store/utils/saveToast';
+
+import type { TaskStore } from '../../store';
+
+type Setter = StoreSetter<TaskStore>;
+
+/** Ids added and removed going from `current` to `next`. */
+export const diffTaskLabels = (current: TaskLabelRef[], next: TaskLabelRef[]) => {
+ const currentIds = new Set(current.map((label) => label.id));
+ const nextIds = new Set(next.map((label) => label.id));
+ return {
+ added: [...nextIds].filter((id) => !currentIds.has(id)),
+ removed: [...currentIds].filter((id) => !nextIds.has(id)),
+ };
+};
+
+export const createTaskLabelSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>
+ new TaskLabelSliceActionImpl(set, get, _api);
+
+export class TaskLabelSliceActionImpl {
+ readonly #get: () => TaskStore;
+ readonly #set: Setter;
+ /**
+ * Per-task chain of label writes. Each call carries the delta the user saw
+ * when clicking; sending them one after another keeps the server in click
+ * order (its row lock orders by arrival, which rapid toggles can invert).
+ */
+ readonly #labelWrites = new Map<string, Promise<unknown>>();
+
+ constructor(set: Setter, get: () => TaskStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ /**
+ * The workspace (or personal) label registry. SWR already keys the request by
+ * workspace; `scope` is the workspace the caller rendered with, so a response
+ * that lands after the user switched away is not written into the shared slot.
+ */
+ useFetchTaskLabels = (enabled: boolean, scope: string | null) =>
+ useClientDataSWR<TaskLabelWithUsage[]>(
+ enabled ? taskLabelKeys.list() : null,
+ () => taskLabelService.list(),
+ {
+ onSuccess: (data: TaskLabelWithUsage[]) => {
+ if (this.#get().taskLabelsScope !== scope) return;
+ this.#set({ taskLabels: data, taskLabelsInit: true }, false, 'useFetchTaskLabels');
+ },
+ },
+ );
+
+ /** Point the registry at another workspace, dropping the previous one's labels. */
+ internal_resetTaskLabelsScope = (scope: string | null) => {
+ if (this.#get().taskLabelsScope === scope) return;
+ this.#set(
+ { taskLabels: [], taskLabelsInit: false, taskLabelsScope: scope },
+ false,
+ 'resetTaskLabelsScope',
+ );
+ };
+
+ refreshTaskLabels = async (): Promise<void> => {
+ await mutate(taskLabelKeys.list());
+ };
+
+ createTaskLabel = async (params: TaskLabelInput) => {
+ const scope = this.#get().taskLabelsScope;
+ const label = await taskLabelService.create(params);
+ // Show the new label right away; the refetch fills in usage counts. Skip
+ // it if the user switched workspaces meanwhile: it belongs to the old one.
+ if (this.#get().taskLabelsScope === scope) {
+ this.#set(
+ (state) => ({ taskLabels: [...state.taskLabels, { ...label, usageCount: 0 }] }),
+ false,
+ 'createTaskLabel',
+ );
+ }
+ void this.refreshTaskLabels();
+ return label;
+ };
+
+ updateTaskLabel = async (id: string, value: TaskLabelPatch) => {
+ await taskLabelService.update(id, value);
+ await this.refreshTaskLabels();
+ // Names and colors are denormalized onto task rows.
+ void this.#get().refreshTaskList();
+ };
+
+ deleteTaskLabel = async (id: string) => {
+ await taskLabelService.delete(id);
+ await this.refreshTaskLabels();
+ void this.#get().refreshTaskList();
+ };
+
+ /**
+ * Replace a task's labels with `next`, shown optimistically on the detail
+ * page and every loaded list/board. Only the delta goes over the wire (applied
+ * atomically), so a concurrent editor's change to other labels survives.
+ */
+ setTaskLabels = async (
+ taskId: string,
+ current: TaskLabelRef[],
+ next: TaskLabelRef[],
+ ): Promise<boolean> => {
+ const { added, removed } = diffTaskLabels(current, next);
+ if (added.length === 0 && removed.length === 0) return true;
+
+ const collections = this.#get().internal_beginCollectionTaskOptimistic(taskId, (task) => ({
+ ...task,
+ labels: next,
+ }));
+ const hasDetail = !!this.#get().taskDetailMap[taskId];
+ if (hasDetail) {
+ this.#get().internal_dispatchTaskDetail({
+ id: taskId,
+ type: 'updateTaskDetail',
+ value: { labels: next },
+ });
+ }
+
+ try {
+ // One request, one transaction: on failure nothing was written, so
+ // rolling the optimistic state back matches the server.
+ const previous = this.#labelWrites.get(taskId) ?? Promise.resolve();
+ const write = previous
+ .catch(() => {})
+ .then(() => taskLabelService.changeForTask(taskId, { add: added, remove: removed }));
+ this.#labelWrites.set(taskId, write);
+ try {
+ await write;
+ } finally {
+ if (this.#labelWrites.get(taskId) === write) this.#labelWrites.delete(taskId);
+ }
+ } catch (error) {
+ collections.rollback();
+ if (hasDetail) {
+ // Nothing was written, so the labels the user started from are the
+ // server's; restore them now rather than trusting a refetch to.
+ this.#get().internal_dispatchTaskDetail({
+ id: taskId,
+ type: 'updateTaskDetail',
+ value: { labels: current },
+ });
+ void this.#get()
+ .internal_refreshTaskDetail(taskId)
+ .catch(() => {});
+ }
+ saveToast(error);
+ return false;
+ }
+
+ // The overlay only swaps the row's labels; it cannot move a card to its
+ // new label column or out of a label filter it no longer matches. Commit it
+ // once the lists have re-fetched (placement then comes from the server);
+ // if that refetch fails, drop the overlay rather than persist a row in a
+ // collection it no longer belongs to — the next refetch shows it correctly.
+ try {
+ await this.#get().refreshTaskList();
+ collections.commit();
+ } catch {
+ collections.rollback();
+ }
+ await Promise.all([
+ hasDetail ? this.#get().internal_refreshTaskDetail(taskId) : undefined,
+ this.refreshTaskLabels(),
+ ]).catch(() => {});
+ return true;
+ };
+}
+
+export type TaskLabelSliceAction = Pick<TaskLabelSliceActionImpl, keyof TaskLabelSliceActionImpl>;
diff --git a/src/store/task/slices/label/index.ts b/src/store/task/slices/label/index.ts
new file mode 100644
index 00000000000..a1c5d763590
--- /dev/null
+++ b/src/store/task/slices/label/index.ts
@@ -0,0 +1,2 @@
+export type { TaskLabelSliceAction } from './action';
+export { createTaskLabelSlice, diffTaskLabels } from './action';
diff --git a/src/store/task/slices/label/initialState.ts b/src/store/task/slices/label/initialState.ts
new file mode 100644
index 00000000000..f4d95aba478
--- /dev/null
+++ b/src/store/task/slices/label/initialState.ts
@@ -0,0 +1,20 @@
+import type { TaskLabelWithUsage } from '@lobechat/types';
+
+export interface TaskLabelSliceState {
+ /** The label registry of the active scope (groups included), registry order. */
+ taskLabels: TaskLabelWithUsage[];
+ /** The registry has loaded once, so an empty array means "no labels". */
+ taskLabelsInit: boolean;
+ /**
+ * Workspace the registry belongs to (`null` = personal). Every workspace
+ * shares this one slot, so a switch must clear it before anything renders
+ * the previous workspace's labels.
+ */
+ taskLabelsScope: string | null;
+}
+
+export const initialTaskLabelSliceState: TaskLabelSliceState = {
+ taskLabels: [],
+ taskLabelsInit: false,
+ taskLabelsScope: null,
+};
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index c61ab3e157a..bfd454e7fd2 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -230,7 +230,9 @@ export class TaskListSliceActionImpl {
...(query.filter && { filter: query.filter }),
...(query.groupBy === 'status'
? { groups: DEFAULT_KANBAN_GROUPS }
- : { groupBy: query.groupBy }),
+ : query.groupBy.startsWith('label:')
+ ? { groupBy: 'label' as const, labelGroupId: query.groupBy.slice('label:'.length) }
+ : { groupBy: query.groupBy as 'assignee' | 'member' | 'priority' }),
includeArchived: query.includeArchived,
projectId: query.projectId,
scope: query.scope,
diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.ts
index 817acb249fd..003aa27d714 100644
--- a/src/store/task/slices/list/initialState.ts
+++ b/src/store/task/slices/list/initialState.ts
@@ -16,7 +16,8 @@ export type TaskGroupItem = Awaited<ReturnType<typeof taskService.groupList>>['d
* Personal mode hides the chip and treats every entry as 'all'.
*/
export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';
-export type TaskKanbanGroupBy = 'assignee' | 'member' | 'priority' | 'status';
+/** `label:<groupId>` boards one column per label of that label group, plus "no label". */
+export type TaskKanbanGroupBy = 'assignee' | 'member' | 'priority' | 'status' | `label:${string}`;
export interface TaskListSliceState {
/** The viewed list is narrowed by the page's filter, so it is not every task. */
diff --git a/src/store/task/store.ts b/src/store/task/store.ts
index 77a366826e0..280632fcafa 100644
--- a/src/store/task/store.ts
+++ b/src/store/task/store.ts
@@ -12,6 +12,8 @@ import type { TaskConfigSliceAction } from './slices/config';
import { createTaskConfigSlice } from './slices/config';
import type { TaskDetailSliceAction } from './slices/detail';
import { createTaskDetailSlice } from './slices/detail';
+import type { TaskLabelSliceAction } from './slices/label';
+import { createTaskLabelSlice } from './slices/label';
import type { TaskLifecycleSliceAction } from './slices/lifecycle';
import { createTaskLifecycleSlice } from './slices/lifecycle';
import type { TaskListSliceAction } from './slices/list';
@@ -23,6 +25,7 @@ export interface TaskStore
extends
TaskConfigSliceAction,
TaskDetailSliceAction,
+ TaskLabelSliceAction,
TaskLifecycleSliceAction,
TaskListSliceAction,
ResetableStore,
@@ -30,6 +33,7 @@ export interface TaskStore
type TaskStoreAction = TaskConfigSliceAction &
TaskDetailSliceAction &
+ TaskLabelSliceAction &
TaskLifecycleSliceAction &
TaskListSliceAction &
ResetableStore;
@@ -46,6 +50,7 @@ const createStore: StateCreator<TaskStore, [['zustand/devtools', never]]> = (
createTaskListSlice(...parameters),
createTaskDetailSlice(...parameters),
createTaskLifecycleSlice(...parameters),
+ createTaskLabelSlice(...parameters),
createTaskConfigSlice(...parameters),
new TaskStoreResetAction(...parameters),
]),