Skip to content

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

✨ feat(cli): assign tasks to workspace members and show the task URL in view (#19933)

Arvin Xue3bb39ea758d
diff --git a/apps/cli/src/commands/task/assignee.test.ts b/apps/cli/src/commands/task/assignee.test.ts
new file mode 100644
index 00000000000..cebfb9cd524
--- /dev/null
+++ b/apps/cli/src/commands/task/assignee.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveAssigneeUserId } from './assignee';
+
+vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));
+
+const { resolveWorkspaceId } = await import('../../api/workspace');
+
+const members = [
+ { role: 'member', user: { email: '[email protected]', username: 'neko' }, userId: 'user_neko' },
+ {
+ role: 'owner',
+ user: { email: '[email protected]', username: 'arvinxx' },
+ userId: 'user_arvin',
+ },
+];
+
+const clientWith = (list = members) => {
+ const query = vi.fn().mockResolvedValue(list);
+ return { client: { workspaceMember: { list: { query } } } as never, query };
+};
+
+describe('resolveAssigneeUserId', () => {
+ afterEach(() => {
+ vi.mocked(resolveWorkspaceId).mockReset();
+ });
+
+ it('passes a raw user id through in personal scope, where there is no member list', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue(undefined);
+ const { client, query } = clientWith();
+
+ await expect(resolveAssigneeUserId(client, 'user_neko')).resolves.toBe('user_neko');
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('matches a member by user id under a workspace scope', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+
+ await expect(resolveAssigneeUserId(clientWith().client, 'user_neko')).resolves.toBe(
+ 'user_neko',
+ );
+ });
+
+ it('resolves a username that happens to start with user_ instead of treating it as an id', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+ const list = [
+ ...members,
+ {
+ role: 'member',
+ user: { email: '[email protected]', username: 'user_ops' },
+ userId: 'user_real_ops',
+ },
+ ];
+
+ await expect(resolveAssigneeUserId(clientWith(list).client, 'user_ops')).resolves.toBe(
+ 'user_real_ops',
+ );
+ });
+
+ it('resolves a member by email or username, case-insensitively', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+ const { client } = clientWith();
+
+ await expect(resolveAssigneeUserId(client, '[email protected]')).resolves.toBe('user_neko');
+ await expect(resolveAssigneeUserId(client, 'arvinxx')).resolves.toBe('user_arvin');
+ });
+
+ it('refuses a non-id value outside a workspace scope', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue(undefined);
+ const { client, query } = clientWith();
+
+ await expect(resolveAssigneeUserId(client, 'neko')).rejects.toThrow(/outside a workspace/);
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('reports no match and ambiguous matches instead of guessing', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+
+ await expect(resolveAssigneeUserId(clientWith().client, 'ghost')).rejects.toThrow(
+ /No workspace member/,
+ );
+
+ const dup = [
+ ...members,
+ { role: 'admin', user: { email: '[email protected]', username: 'neko' }, userId: 'user_other' },
+ ];
+ await expect(resolveAssigneeUserId(clientWith(dup).client, 'neko')).rejects.toThrow(
+ /matches 2 members/,
+ );
+ });
+
+ it('rejects a viewer, who cannot own tasks, instead of letting the mutation fail', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+ const list = [
+ ...members,
+ { role: 'viewer', user: { email: '[email protected]', username: 'viewer' }, userId: 'user_v' },
+ ];
+
+ await expect(resolveAssigneeUserId(clientWith(list).client, 'viewer')).rejects.toThrow(
+ /is a viewer .* can't be assigned tasks/,
+ );
+ await expect(resolveAssigneeUserId(clientWith(list).client, 'user_v')).rejects.toThrow(
+ /is a viewer/,
+ );
+ });
+
+ it('does not let a viewer sharing a username make an eligible match ambiguous', async () => {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+ const list = [
+ ...members,
+ { role: 'viewer', user: { email: '[email protected]', username: 'neko' }, userId: 'user_v' },
+ ];
+
+ await expect(resolveAssigneeUserId(clientWith(list).client, 'neko')).resolves.toBe('user_neko');
+ });
+});
diff --git a/apps/cli/src/commands/task/assignee.ts b/apps/cli/src/commands/task/assignee.ts
new file mode 100644
index 00000000000..83d58336be0
--- /dev/null
+++ b/apps/cli/src/commands/task/assignee.ts
@@ -0,0 +1,51 @@
+import { canWorkspaceRoleBeTaskAssignee } from '@lobechat/const/rbac';
+
+import type { TrpcClient } from '../../api/client';
+import { resolveWorkspaceId } from '../../api/workspace';
+
+/**
+ * Resolve `--user` to a member's user id. Under a workspace scope the value is
+ * matched against members by user id, email or username β€” usernames may start
+ * with `user_` too, so the prefix alone never decides. Personal scope has no
+ * member list, so only a raw `user_…` id is accepted there.
+ *
+ * Only members whose role can own tasks are candidates, mirroring the server's
+ * assignee check, so a viewer neither resolves nor makes an eligible match
+ * ambiguous.
+ */
+export const resolveAssigneeUserId = async (client: TrpcClient, value: string) => {
+ const needle = value.trim();
+
+ if (!resolveWorkspaceId()) {
+ if (needle.startsWith('user_')) return needle;
+ throw new Error(
+ `Cannot resolve "${needle}" outside a workspace β€” pass a user id (user_…) or run under a workspace scope.`,
+ );
+ }
+
+ const members = await client.workspaceMember.list.query({});
+ const lower = needle.toLowerCase();
+ const matches = members.filter(
+ (m) =>
+ m.userId === needle ||
+ m.user?.email?.toLowerCase() === lower ||
+ m.user?.username?.toLowerCase() === lower,
+ );
+ // An exact user id wins over an email/username that happens to equal it.
+ const byId = matches.find((m) => m.userId === needle);
+ const candidates = byId ? [byId] : matches;
+ const eligible = candidates.filter((m) => canWorkspaceRoleBeTaskAssignee(m.role));
+
+ if (eligible.length === 1) return eligible[0].userId;
+ if (eligible.length > 1) {
+ throw new Error(`"${needle}" matches ${eligible.length} members β€” pass the user id instead.`);
+ }
+ if (candidates.length > 0) {
+ throw new Error(
+ `"${needle}" is a ${candidates[0].role} in this workspace and can't be assigned tasks.`,
+ );
+ }
+ throw new Error(
+ `No workspace member matches "${needle}". Run \`lh workspace members\` to see who can be assigned.`,
+ );
+};
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index 6a630378f2c..983dc32bb61 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -1,4 +1,3 @@
-import { taskTitleSlug } from '@lobechat/utils/taskSlug';
import type { Command } from 'commander';
import pc from 'picocolors';
@@ -14,6 +13,7 @@ import {
truncate,
} from '../../utils/format';
import { log } from '../../utils/logger';
+import { resolveAssigneeUserId } from './assignee';
import { registerCheckpointCommands } from './checkpoint';
import { registerDepCommands } from './dep';
import { registerDocCommands } from './doc';
@@ -21,7 +21,7 @@ import { briefIcon, priorityLabel, statusBadge } from './helpers';
import { registerLifecycleCommands } from './lifecycle';
import { registerReviewCommands } from './review';
import { registerTopicCommands } from './topic';
-import { resolveAppUrlBuilder } from './url';
+import { resolveAppUrl, resolveAppUrlBuilder, taskPath } from './url';
export function registerTaskCommand(program: Command) {
const task = program.command('task').description('Manage agent tasks');
@@ -264,16 +264,17 @@ export function registerTaskCommand(program: Command) {
// Default: task detail
const result = await client.task.detail.query({ id });
+ const t = result.data;
+ const url = await resolveAppUrl(client, taskPath(t.identifier, t.name));
if (options.json !== undefined) {
- outputJson(result.data, options.json);
+ outputJson({ ...t, url }, options.json);
return;
}
- const t = result.data;
-
// ── Header ──
console.log(`\n${pc.bold(t.identifier)} ${t.name || ''}`);
+ console.log(`${pc.dim('URL:')} ${url}`);
console.log(
`${pc.dim('Status:')} ${statusBadge(t.status)} ${pc.dim('Priority:')} ${priorityLabel(t.priority)}`,
);
@@ -523,6 +524,7 @@ export function registerTaskCommand(program: Command) {
.requiredOption('-i, --instruction <text>', 'Task instruction')
.option('-n, --name <name>', 'Task name')
.option('--agent <id>', 'Assign to agent')
+ .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('--prefix <prefix>', 'Identifier prefix', 'T')
@@ -536,24 +538,25 @@ export function registerTaskCommand(program: Command) {
parent?: string;
prefix?: string;
priority?: string;
+ user?: string;
}) => {
const client = await getTrpcClient();
const buildUrl = await resolveAppUrlBuilder(client);
+ const assigneeUserId = await resolveUserOption(client, options.user);
+ if (assigneeUserId === false) return;
const input: Record<string, any> = {
instruction: options.instruction,
};
if (options.name) input.name = options.name;
if (options.agent) input.assigneeAgentId = options.agent;
+ if (assigneeUserId) input.assigneeUserId = assigneeUserId;
if (options.parent) input.parentTaskId = options.parent;
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
if (options.prefix) input.identifierPrefix = options.prefix;
const result = await client.task.create.mutate(input as any);
- const slug = taskTitleSlug(result.data.name);
- const url = buildUrl(
- `/task/${encodeURIComponent(result.data.identifier)}${slug ? `/${slug}` : ''}`,
- );
+ const url = buildUrl(taskPath(result.data.identifier, result.data.name));
if (options.json !== undefined) {
outputJson({ ...result.data, url }, options.json);
@@ -573,6 +576,7 @@ export function registerTaskCommand(program: Command) {
.option('-n, --name <name>', 'Task name')
.option('-i, --instruction <text>', 'Task instruction')
.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('--heartbeat-interval <n>', 'Heartbeat interval in seconds')
.option('--heartbeat-timeout <n>', 'Heartbeat timeout in seconds (0 to disable)')
@@ -595,15 +599,19 @@ export function registerTaskCommand(program: Command) {
name?: string;
priority?: string;
status?: string;
+ user?: string;
},
) => {
const client = await getTrpcClient();
+ const assigneeUserId = await resolveUserOption(client, options.user);
+ if (assigneeUserId === false) return;
const input: Record<string, any> = { id };
if (options.name) input.name = options.name;
if (options.instruction) input.instruction = options.instruction;
if (options.description) input.description = options.description;
if (options.agent) input.assigneeAgentId = options.agent;
+ if (assigneeUserId) input.assigneeUserId = assigneeUserId;
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
if (options.heartbeatInterval)
input.heartbeatInterval = Number.parseInt(options.heartbeatInterval, 10);
@@ -736,3 +744,21 @@ export function registerTaskCommand(program: Command) {
registerTopicCommands(task);
registerDocCommands(task);
}
+
+/**
+ * `undefined` = flag not passed; `false` = resolution failed and was reported,
+ * so the caller should stop without sending a half-applied edit.
+ */
+const resolveUserOption = async (
+ client: Awaited<ReturnType<typeof getTrpcClient>>,
+ value: string | undefined,
+): Promise<string | undefined | false> => {
+ if (!value) return undefined;
+ try {
+ return await resolveAssigneeUserId(client, value);
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exitCode = 1;
+ return false;
+ }
+};
diff --git a/apps/cli/src/commands/task/url.ts b/apps/cli/src/commands/task/url.ts
index ca8e7eace13..6205ed0e8a8 100644
--- a/apps/cli/src/commands/task/url.ts
+++ b/apps/cli/src/commands/task/url.ts
@@ -23,20 +23,19 @@ export const buildAppUrl = ({ pathname, serverUrl, workspaceSlug }: AppUrlOption
* `name` only adds the readable slug tail (`/task/T-501/ship-the-thing`); the
* identifier alone still resolves the task, so omitting it stays valid.
*/
+export const taskPath = (identifier: string, name?: string | null) => {
+ const slug = taskTitleSlug(name);
+
+ return `/task/${encodeURIComponent(identifier)}${slug ? `/${slug}` : ''}`;
+};
+
export const buildTaskUrl = ({
identifier,
name,
serverUrl,
workspaceSlug,
-}: Omit<AppUrlOptions, 'pathname'> & { identifier: string; name?: string | null }) => {
- const slug = taskTitleSlug(name);
-
- return buildAppUrl({
- pathname: `/task/${encodeURIComponent(identifier)}${slug ? `/${slug}` : ''}`,
- serverUrl,
- workspaceSlug,
- });
-};
+}: Omit<AppUrlOptions, 'pathname'> & { identifier: string; name?: string | null }) =>
+ buildAppUrl({ pathname: taskPath(identifier, name), serverUrl, workspaceSlug });
export const resolveAppUrlBuilder = async (client: TrpcClient) => {
const workspace = resolveWorkspaceId() ? await client.workspace.getById.query() : null;