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): add --visibility to lh task create and edit (#23539)

Rdmclin20ec5b27c1f61
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index f49415e89f0..e27d0d13114 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -3,6 +3,7 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
+import { formatError } from '../../utils/error';
import type { KanbanColumn } from '../../utils/format';
import {
confirm,
@@ -34,6 +35,13 @@ import { type TaskOriginInput, toCreateOrigin } from './origin';
import { registerReviewCommands } from './review';
import { registerTopicCommands } from './topic';
import { resolveAppUrl, resolveAppUrlBuilder, taskPath } from './url';
+import {
+ describeVisibilityError,
+ parseVisibility,
+ type TaskVisibility,
+ VISIBILITY_OPTION_DESCRIPTION,
+ withVisibilityHint,
+} from './visibility';
export function registerTaskCommand(program: Command) {
const task = program.command('task').description('Manage agent tasks');
@@ -578,6 +586,10 @@ 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(
+ '--visibility <visibility>',
+ `${VISIBILITY_OPTION_DESCRIPTION}. Default: inherited from --parent, private for a private --agent, otherwise public`,
+ )
.option(
'--label <name>',
'Attach an existing label (repeatable or comma-separated; "Group/Label" also works)',
@@ -614,10 +626,13 @@ export function registerTaskCommand(program: Command) {
priority?: string;
provider?: string;
user?: string;
+ visibility?: string;
}) => {
let origin: TaskOriginInput | undefined;
+ let visibility: TaskVisibility | undefined;
try {
origin = toCreateOrigin(options);
+ visibility = parseVisibility(options.visibility);
} catch (error) {
log.error((error as Error).message);
process.exitCode = 1;
@@ -643,8 +658,11 @@ export function registerTaskCommand(program: Command) {
const modelConfig = toCreateModelConfig(options);
if (modelConfig) input.config = modelConfig;
if (origin) input.context = { origin };
+ if (visibility) input.visibility = visibility;
- const result = await client.task.create.mutate(input);
+ const result = await client.task.create.mutate(input).catch((error: unknown) => {
+ throw withVisibilityHint(error, { command: 'create' });
+ });
const url = buildUrl(taskPath(result.data.identifier, result.data.name));
if (options.json !== undefined) {
@@ -668,6 +686,10 @@ 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(
+ '--visibility <visibility>',
+ `${VISIBILITY_OPTION_DESCRIPTION}. Only the task creator can make a task private`,
+ )
.option('--project <id>', 'Move to a project ("null" to remove it from its project)')
.option(
'--label <name>',
@@ -708,8 +730,18 @@ export function registerTaskCommand(program: Command) {
removeLabel?: string[];
status?: string;
user?: string;
+ visibility?: string;
},
) => {
+ let visibility: TaskVisibility | undefined;
+ try {
+ visibility = parseVisibility(options.visibility);
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exitCode = 1;
+ return;
+ }
+
const client = await getTrpcClient();
const assigneeUserId = await resolveUserOption(client, options.user);
if (assigneeUserId === false) return;
@@ -748,6 +780,42 @@ export function registerTaskCommand(program: Command) {
return;
}
+ // Visibility has its own endpoint, gated by the server (only the
+ // creator can make a task private). Going private runs before every
+ // other change, so a private `--agent` in the same command passes the
+ // "public task cannot use a private agent" check; going public runs
+ // after them, once the task has moved off a private agent.
+ const changeVisibility = (target: TaskVisibility, appliedOtherEdits: boolean) =>
+ client.task.updateVisibility
+ .mutate({ id, visibility: target })
+ .catch((error: unknown) => {
+ throw describeVisibilityError(error, id, target, appliedOtherEdits);
+ });
+ // Returns the promoted row, merged over the pre-promotion row in JSON output.
+ const applyPublic = async () =>
+ visibility === 'public' ? (await changeVisibility('public', true)).data : {};
+ // The private flip is not undone when a later step fails; say so.
+ const afterPrivate = (error: unknown): never => {
+ if (visibility !== 'private') throw error;
+ throw new Error(`${formatError(error)} (${id} was already made private)`);
+ };
+
+ if (visibility && !(hasLabelEdits || hasFieldEdits || options.status)) {
+ const result = await changeVisibility(visibility, false);
+ if (options.json !== undefined) {
+ outputJson(
+ withUrl(result.data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
+ typeof options.json === 'string' ? options.json : undefined,
+ );
+ } else {
+ log.info(`${pc.bold(result.data.identifier)} is now ${visibility}`);
+ console.log(`ID: ${result.data.id}`);
+ }
+ return;
+ }
+
+ if (visibility === 'private') await changeVisibility('private', false);
+
// 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 /
@@ -778,13 +846,16 @@ export function registerTaskCommand(program: Command) {
throw error;
};
if (hasLabelEdits) {
- labels = await client.taskLabel.changeForTask.mutate({
- add: addLabelIds,
- remove: removeLabelIds,
- taskId: id,
- });
+ labels = await client.taskLabel.changeForTask
+ .mutate({
+ add: addLabelIds,
+ remove: removeLabelIds,
+ taskId: id,
+ })
+ .catch(afterPrivate);
}
if (hasLabelEdits && !hasOtherEdits) {
+ await applyPublic();
if (options.json !== undefined) {
// Same task-shaped JSON as any other `task edit --json`.
const { data } = await client.task.find.query({ id });
@@ -811,11 +882,13 @@ export function registerTaskCommand(program: Command) {
if (!hasFieldEdits) {
const result = await client.task.updateStatus
.mutate({ id, status: options.status })
- .catch(restoreLabelsOnFailure);
+ .catch(restoreLabelsOnFailure)
+ .catch(afterPrivate);
+ const promoted = await applyPublic();
if (options.json !== undefined) {
outputJson(
withUrl(
- result.data,
+ { ...result.data, ...promoted },
await resolveUrlBuilder(client),
resourcePath.task(result.data),
),
@@ -831,11 +904,18 @@ export function registerTaskCommand(program: Command) {
input.status = options.status;
}
- const result = await client.task.update.mutate(input as any).catch(restoreLabelsOnFailure);
+ const result = await client.task.update
+ .mutate(input as any)
+ .catch(restoreLabelsOnFailure)
+ .catch((error: unknown) => {
+ throw withVisibilityHint(error, { command: 'edit', id });
+ })
+ .catch(afterPrivate);
+ const promoted = await applyPublic();
if (options.json !== undefined) {
// task.update returns the bare row; overlay the post-edit labels.
- const data = labels ? { ...result.data, labels } : result.data;
+ const data = { ...result.data, ...promoted, ...(labels ? { labels } : {}) };
outputJson(
withUrl(data, await resolveUrlBuilder(client), resourcePath.task(result.data)),
typeof options.json === 'string' ? options.json : undefined,
diff --git a/apps/cli/src/commands/task/visibility.test.ts b/apps/cli/src/commands/task/visibility.test.ts
new file mode 100644
index 00000000000..a60e50ddf1e
--- /dev/null
+++ b/apps/cli/src/commands/task/visibility.test.ts
@@ -0,0 +1,284 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerTaskCommand } from './index';
+import { describeVisibilityError, parseVisibility, withVisibilityHint } from './visibility';
+
+const { mockGetTrpcClient, mockLogError, mockLogInfo } = vi.hoisted(() => ({
+ mockGetTrpcClient: vi.fn(),
+ mockLogError: vi.fn(),
+ mockLogInfo: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: () => undefined }));
+vi.mock('../../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));
+vi.mock('../../utils/logger', () => ({
+ log: { debug: vi.fn(), error: mockLogError, info: mockLogInfo, warn: vi.fn() },
+}));
+
+const PRIVATE_AGENT_ERROR =
+ 'A public task cannot be assigned to a private agent. Either pick a workspace agent or make the task private first.';
+
+const row = (extra: Record<string, unknown> = {}) => ({
+ data: { id: 'task_1', identifier: 'T-1', name: 'Task', ...extra },
+ success: true,
+});
+
+const mocks = {
+ changeLabels: vi.fn(),
+ create: vi.fn(),
+ find: vi.fn(),
+ update: vi.fn(),
+ updateStatus: vi.fn(),
+ updateVisibility: vi.fn(),
+};
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'test', 'task', ...args]);
+};
+
+describe('parseVisibility', () => {
+ it('accepts private and public, case-insensitively', () => {
+ expect(parseVisibility('private')).toBe('private');
+ expect(parseVisibility(' Public ')).toBe('public');
+ expect(parseVisibility(undefined)).toBeUndefined();
+ });
+
+ it('rejects anything else with the accepted values', () => {
+ expect(() => parseVisibility('secret')).toThrow(
+ 'Invalid visibility "secret". Must be one of: private, public',
+ );
+ });
+});
+
+describe('withVisibilityHint', () => {
+ it('keeps the server message and points create at --visibility private', () => {
+ const error = withVisibilityHint(new Error(PRIVATE_AGENT_ERROR), { command: 'create' });
+
+ expect((error as Error).message).toBe(
+ `${PRIVATE_AGENT_ERROR}\nHint: Create it with \`--visibility private\` instead.`,
+ );
+ });
+
+ it('points edit at making the task private first', () => {
+ const error = withVisibilityHint(new Error(PRIVATE_AGENT_ERROR), {
+ command: 'edit',
+ id: 'T-1',
+ });
+
+ expect((error as Error).message).toContain('lh task edit T-1 --visibility private');
+ });
+
+ it('passes unrelated errors through untouched', () => {
+ const original = new Error('Task not found');
+
+ expect(withVisibilityHint(original, { command: 'create' })).toBe(original);
+ });
+});
+
+describe('describeVisibilityError', () => {
+ it('keeps the server reason verbatim and says what was attempted', () => {
+ const error = describeVisibilityError(
+ new Error('Only the task creator can make this task private'),
+ 'T-1',
+ 'private',
+ );
+
+ expect(error.message).toBe(
+ 'Could not make T-1 private: Only the task creator can make this task private',
+ );
+ });
+});
+
+describe('task create --visibility', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mocks.create.mockReset().mockResolvedValue(row());
+ mockGetTrpcClient.mockResolvedValue({ task: { create: { mutate: mocks.create } } });
+ mockLogError.mockReset();
+ process.exitCode = undefined;
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ process.exitCode = undefined;
+ });
+
+ it('sends the visibility to the server', async () => {
+ await run('create', '-i', 'Do it', '--visibility', 'private', '--agent', 'agt_private');
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ assigneeAgentId: 'agt_private', visibility: 'private' }),
+ );
+ });
+
+ it('leaves visibility to the server when the flag is omitted', async () => {
+ await run('create', '-i', 'Do it');
+
+ expect(mocks.create.mock.calls[0][0]).not.toHaveProperty('visibility');
+ });
+
+ it('rejects an invalid value before calling the server', async () => {
+ await run('create', '-i', 'Do it', '--visibility', 'team');
+
+ expect(mocks.create).not.toHaveBeenCalled();
+ expect(mockLogError).toHaveBeenCalledWith(expect.stringContaining('Invalid visibility'));
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('suggests --visibility private when a public task gets a private agent', async () => {
+ mocks.create.mockRejectedValue(new Error(PRIVATE_AGENT_ERROR));
+
+ await expect(
+ run('create', '-i', 'Do it', '--visibility', 'public', '--agent', 'agt_private'),
+ ).rejects.toThrow('Hint: Create it with `--visibility private` instead.');
+ });
+});
+
+describe('task edit --visibility', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let order: string[];
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ order = [];
+ mocks.update.mockReset().mockImplementation(async () => {
+ order.push('update');
+ return row();
+ });
+ mocks.updateStatus.mockReset().mockImplementation(async () => {
+ order.push('updateStatus');
+ return row();
+ });
+ mocks.updateVisibility.mockReset().mockImplementation(async ({ visibility }) => {
+ order.push(`visibility:${visibility}`);
+ return row({ visibility });
+ });
+ mocks.changeLabels.mockReset().mockImplementation(async () => {
+ order.push('labels');
+ return [{ id: 'lbl_bug', name: 'bug' }];
+ });
+ mocks.find.mockReset().mockResolvedValue(row({ visibility: 'public' }));
+ mockGetTrpcClient.mockResolvedValue({
+ task: {
+ find: { query: mocks.find },
+ update: { mutate: mocks.update },
+ updateStatus: { mutate: mocks.updateStatus },
+ updateVisibility: { mutate: mocks.updateVisibility },
+ },
+ taskLabel: {
+ changeForTask: { mutate: mocks.changeLabels },
+ list: { query: async () => [{ id: 'lbl_bug', name: 'bug' }] },
+ },
+ });
+ mockLogError.mockReset();
+ mockLogInfo.mockReset();
+ process.exitCode = undefined;
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ process.exitCode = undefined;
+ });
+
+ it('changes only the visibility through its own endpoint', async () => {
+ await run('edit', 'T-1', '--visibility', 'private');
+
+ expect(mocks.updateVisibility).toHaveBeenCalledWith({ id: 'T-1', visibility: 'private' });
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mockLogInfo).toHaveBeenCalledWith(expect.stringContaining('is now private'));
+ });
+
+ it('prints the changed task as JSON for a visibility-only edit', async () => {
+ await run('edit', 'T-1', '--visibility', 'private', '--json', 'identifier,visibility');
+
+ expect(JSON.parse(consoleSpy.mock.calls[0][0] as string)).toEqual({
+ identifier: 'T-1',
+ visibility: 'private',
+ });
+ });
+
+ it('orders the visibility change around a label-only edit', async () => {
+ await run('edit', 'T-1', '--label', 'bug', '--visibility', 'public');
+ expect(order).toEqual(['labels', 'visibility:public']);
+
+ order = [];
+ await run('edit', 'T-1', '--label', 'bug', '--visibility', 'private');
+ expect(order).toEqual(['visibility:private', 'labels']);
+ });
+
+ it('says the task was already made private when a later edit fails', async () => {
+ mocks.update.mockRejectedValue(new Error('Task is being edited by another user'));
+
+ await expect(
+ run('edit', 'T-1', '--visibility', 'private', '--agent', 'agt_private'),
+ ).rejects.toThrow('Task is being edited by another user (T-1 was already made private)');
+ });
+
+ it('makes the task private before assigning a private agent in the same command', async () => {
+ await run('edit', 'T-1', '--visibility', 'private', '--agent', 'agt_private');
+
+ expect(order).toEqual(['visibility:private', 'update']);
+ expect(mocks.update).toHaveBeenCalledWith(
+ expect.objectContaining({ assigneeAgentId: 'agt_private', id: 'T-1' }),
+ );
+ });
+
+ it('makes the task public after moving it to another agent', async () => {
+ await run('edit', 'T-1', '--agent', 'agt_workspace', '--visibility', 'public', '--json');
+
+ expect(order).toEqual(['update', 'visibility:public']);
+ const printed = JSON.parse(consoleSpy.mock.calls[0][0] as string);
+ expect(printed.visibility).toBe('public');
+ });
+
+ it('makes the task public after a status-only change', async () => {
+ await run('edit', 'T-1', '--status', 'paused', '--visibility', 'public');
+
+ expect(order).toEqual(['updateStatus', 'visibility:public']);
+ });
+
+ it('stops before other edits when the server refuses to make the task private', async () => {
+ mocks.updateVisibility.mockRejectedValue(
+ new Error('Only the task creator can make this task private'),
+ );
+
+ await expect(
+ run('edit', 'T-1', '--visibility', 'private', '--agent', 'agt_private'),
+ ).rejects.toThrow(
+ 'Could not make T-1 private: Only the task creator can make this task private',
+ );
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+
+ it('says the other edits landed when making the task public fails afterwards', async () => {
+ mocks.updateVisibility.mockRejectedValue(new Error(PRIVATE_AGENT_ERROR));
+
+ await expect(run('edit', 'T-1', '--name', 'New', '--visibility', 'public')).rejects.toThrow(
+ 'Could not make T-1 public (the other changes in this command were applied)',
+ );
+ expect(mocks.update).toHaveBeenCalled();
+ });
+
+ it('suggests --visibility private when assigning a private agent to a public task', async () => {
+ mocks.update.mockRejectedValue(new Error(PRIVATE_AGENT_ERROR));
+
+ await expect(run('edit', 'T-1', '--agent', 'agt_private')).rejects.toThrow(
+ 'lh task edit T-1 --visibility private',
+ );
+ });
+
+ it('rejects an invalid value before calling the server', async () => {
+ await run('edit', 'T-1', '--visibility', 'team', '--agent', 'agt_private');
+
+ expect(mocks.updateVisibility).not.toHaveBeenCalled();
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+});
diff --git a/apps/cli/src/commands/task/visibility.ts b/apps/cli/src/commands/task/visibility.ts
new file mode 100644
index 00000000000..1647a4aaced
--- /dev/null
+++ b/apps/cli/src/commands/task/visibility.ts
@@ -0,0 +1,58 @@
+import { formatError } from '../../utils/error';
+
+export type TaskVisibility = 'private' | 'public';
+
+export const TASK_VISIBILITIES: readonly TaskVisibility[] = ['private', 'public'];
+
+export const VISIBILITY_OPTION_DESCRIPTION =
+ 'Task visibility: private (only you) or public (the whole workspace)';
+
+/** Validate `--visibility`; throws a message listing the accepted values. */
+export const parseVisibility = (value: string | undefined): TaskVisibility | undefined => {
+ if (value === undefined) return undefined;
+ const normalized = value.trim().toLowerCase();
+ if ((TASK_VISIBILITIES as readonly string[]).includes(normalized)) {
+ return normalized as TaskVisibility;
+ }
+ throw new Error(`Invalid visibility "${value}". Must be one of: ${TASK_VISIBILITIES.join(', ')}`);
+};
+
+// Matches the message of `TaskService.assertAgentVisibilityCompat`
+// (apps/server/src/services/task/index.ts), which carries no error code.
+const PRIVATE_AGENT_ON_PUBLIC_TASK = /public task cannot be assigned to a private agent/i;
+
+/**
+ * Append how to fix a failed create / edit when the server's message has a
+ * CLI-side remedy. The server message itself is kept verbatim; other errors
+ * pass through unchanged so the global handler still recognizes them.
+ */
+export const withVisibilityHint = (
+ error: unknown,
+ context: { command: 'create' } | { command: 'edit'; id: string },
+): unknown => {
+ const message = formatError(error);
+ if (!PRIVATE_AGENT_ON_PUBLIC_TASK.test(message)) return error;
+
+ const hint =
+ context.command === 'create'
+ ? 'Create it with `--visibility private` instead.'
+ : `Add \`--visibility private\` to this command, or run \`lh task edit ${context.id} --visibility private\` first (only the task creator can make it private).`;
+ // No `cause`: the global handler prints the whole cause chain, which would
+ // repeat the server message.
+ return new Error(`${message}\nHint: ${hint}`);
+};
+
+/**
+ * Prefix a failed `updateVisibility` call with what was being attempted; the
+ * server's reason (e.g. only the creator can make a task private) stays
+ * verbatim. `appliedOtherEdits` notes that the rest of the edit already landed.
+ */
+export const describeVisibilityError = (
+ error: unknown,
+ id: string,
+ visibility: TaskVisibility,
+ appliedOtherEdits = false,
+): Error => {
+ const applied = appliedOtherEdits ? ' (the other changes in this command were applied)' : '';
+ return new Error(`Could not make ${id} ${visibility}${applied}: ${formatError(error)}`);
+};
diff --git a/packages/builtin-skills/src/lobehub/references/task.md b/packages/builtin-skills/src/lobehub/references/task.md
index 06845a7b831..3fa1b506008 100644
--- a/packages/builtin-skills/src/lobehub/references/task.md
+++ b/packages/builtin-skills/src/lobehub/references/task.md
@@ -8,10 +8,12 @@
- `--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>] [--user <idOrEmail>] [--parent <id>] [--priority <0-4>] [--label <name>] [--origin-agent <id> --origin-topic <id>]` - Create task
+- `lh task create -i <instruction> [-n <name>] [--agent <id>] [--user <idOrEmail>] [--parent <id>] [--priority <0-4>] [--label <name>] [--visibility <private|public>] [--origin-agent <id> --origin-topic <id>]` - Create task
- Priority: 0=none, 1=urgent, 2=high, 3=normal, 4=low
+ - `--visibility`: `private` (only you) or `public` (whole workspace). Default: inherited from `--parent`, private for a private `--agent`, otherwise public. A public task cannot be assigned to a private agent.
- `--origin-agent` / `--origin-topic` (optional): the conversation to report back to when the task finishes (a result card is posted there and that agent continues). Pass both together; to be notified in your current conversation, use `$LOBEHUB_AGENT_ID` and `$LOBEHUB_TOPIC_ID`. The topic must be your own conversation.
-- `lh task edit <id> [-n <name>] [-i <instruction>] [--status <status>] [--priority <0-4>] [--agent <id>] [--user <idOrEmail>] [--label <name>] [--remove-label <name>]` - Update task
+- `lh task edit <id> [-n <name>] [-i <instruction>] [--status <status>] [--priority <0-4>] [--agent <id>] [--user <idOrEmail>] [--label <name>] [--remove-label <name>] [--visibility <private|public>]` - Update task
+ - `--visibility`: only the task creator can make a task private. To give a public task to a private agent, pass `--visibility private` with `--agent` (or make it private first).
- `lh task delete <id> [--yes]` - Delete task
- `lh task clear [--yes]` - Delete all tasks
- `lh task tree <id>` - Show subtask tree with dependencies