π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(cli): add `workspace member update` to set member title and responsibilities (#21959)
Lobehub Coder0168649fbae0
diff --git a/apps/cli/src/commands/workspace.test.ts b/apps/cli/src/commands/workspace.test.tsindex b79c3bcbd4a..e129870fbc4 100644--- a/apps/cli/src/commands/workspace.test.ts+++ b/apps/cli/src/commands/workspace.test.ts@@ -1,3 +1,7 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -26,6 +30,7 @@ const {invite: { mutate: vi.fn() },list: { query: vi.fn() },listInvitations: { query: vi.fn() },+ updateProfile: { mutate: vi.fn() },},workspaceUsage: { getCurrentUsage: { query: vi.fn() } },},@@ -254,6 +259,177 @@ describe('workspace command', () => {});});+ describe('member update', () => {+ const roster = () => [+ {+ responsibilities: null,+ role: 'owner',+ title: null,+ user: { email: '[email protected]', fullName: 'Ada', username: 'ada' },+ userId: 'user_1',+ },+ {+ responsibilities: 'IM, SDK',+ role: 'admin',+ title: 'Engineer',+ user: { email: '[email protected]', fullName: 'Bob', username: null },+ userId: 'user_2',+ },+ ];++ const writeFile = (rows: unknown) => {+ const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'ws-member-')), 'rows.json');+ fs.writeFileSync(file, JSON.stringify(rows));+ return file;+ };++ beforeEach(() => {+ scopedTo('ws_1');+ mockClient.workspaceMember.list.query.mockResolvedValue(roster());+ mockClient.workspaceMember.updateProfile.mutate.mockImplementation(+ async ({ userId, ...fields }: { userId: string }) => ({+ ...roster().find((m) => m.userId === userId),+ ...fields,+ }),+ );+ });++ it('resolves members by username or email and writes the fields', async () => {+ await run(+ 'workspace',+ 'member',+ 'update',+ 'ada',+ '[email protected]',+ '--title',+ ' Lead ',+ '--responsibilities',+ 'Ship it',+ );++ expect(mockClient.workspaceMember.updateProfile.mutate).toHaveBeenCalledWith({+ responsibilities: 'Ship it',+ title: 'Lead',+ userId: 'user_1',+ });+ expect(mockClient.workspaceMember.updateProfile.mutate).toHaveBeenCalledWith({+ responsibilities: 'Ship it',+ title: 'Lead',+ userId: 'user_2',+ });+ });++ it('applies a --file batch and skips rows that already match', async () => {+ const file = writeFile([+ { member: 'user_1', responsibilities: 'Ops', title: 'CEO' },+ { member: 'user_2', responsibilities: 'IM, SDK', title: 'Engineer' },+ ]);++ await run('workspace', 'member', 'update', '--file', file, '--json');++ expect(mockClient.workspaceMember.updateProfile.mutate).toHaveBeenCalledTimes(1);+ const results = JSON.parse(String(consoleSpy.mock.calls.at(-1)![0]));+ expect(results.map((r: { status: string }) => r.status)).toEqual(['updated', 'unchanged']);+ expect(results[0]).toMatchObject({ responsibilities: 'Ops', title: 'CEO' });+ });++ it('sends only the fields that changed', async () => {+ await run('workspace', 'member', 'update', 'user_2', '-t', 'Engineer', '-r', 'IM');++ expect(mockClient.workspaceMember.updateProfile.mutate).toHaveBeenCalledWith({+ responsibilities: 'IM',+ userId: 'user_2',+ });+ });++ it('treats an empty value as clearing the field', async () => {+ await run('workspace', 'member', 'update', 'user_2', '--title', '');++ expect(mockClient.workspaceMember.updateProfile.mutate).toHaveBeenCalledWith({+ title: null,+ userId: 'user_2',+ });+ });++ it('writes nothing when any reference is unknown', async () => {+ const file = writeFile([+ { member: 'ada', title: 'CEO' },+ { member: 'ghost', title: 'Nobody' },+ ]);++ await expect(run('workspace', 'member', 'update', '-f', file)).rejects.toThrow(+ 'process.exit',+ );++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('ghost'));+ expect(mockClient.workspaceMember.updateProfile.mutate).not.toHaveBeenCalled();+ });++ // Cloud answers a workspace the caller is not in with an empty list rather+ // than an error, so that has to be named instead of "no member matches".+ it('names an inaccessible workspace instead of blaming each member', async () => {+ mockClient.workspaceMember.list.query.mockResolvedValue([]);++ await expect(run('workspace', 'member', 'update', 'ada', '-t', 'CEO')).rejects.toThrow(+ 'process.exit',+ );++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not a member'));+ expect(mockClient.workspaceMember.updateProfile.mutate).not.toHaveBeenCalled();+ });++ it('rejects a malformed file entry before hitting the server', async () => {+ const file = writeFile([{ member: 'ada' }]);++ await expect(run('workspace', 'member', 'update', '-f', file)).rejects.toThrow(+ 'process.exit',+ );++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('entry #1'));+ expect(mockClient.workspaceMember.list.query).not.toHaveBeenCalled();+ });++ it('requires a field to update', async () => {+ await expect(run('workspace', 'member', 'update', 'ada')).rejects.toThrow('process.exit');++ expect(mockClient.workspaceMember.list.query).not.toHaveBeenCalled();+ });++ it('previews with --dry-run without writing', async () => {+ await run('workspace', 'member', 'update', 'ada', '-t', 'CEO', '--dry-run', '--json');++ expect(mockClient.workspaceMember.updateProfile.mutate).not.toHaveBeenCalled();+ const results = JSON.parse(String(consoleSpy.mock.calls.at(-1)![0]));+ expect(results[0]).toMatchObject({ status: 'would-update', title: 'CEO' });+ });++ // Permission depends on the target: a non-admin is refused for someone+ // else but may still edit themselves, so a refusal must not skip later rows.+ it('keeps going after a permission error and exits non-zero', async () => {+ mockClient.workspaceMember.updateProfile.mutate.mockImplementation(+ async ({ userId, ...fields }: { userId: string }) => {+ if (userId === 'user_1')+ throw Object.assign(+ new Error("Requires admin role or higher to edit another member's profile"),+ { data: { code: 'FORBIDDEN' } },+ );+ return { ...roster().find((m) => m.userId === userId), ...fields };+ },+ );++ await expect(+ run('workspace', 'member', 'update', 'ada', 'user_2', '-t', 'X', '--json'),+ ).rejects.toThrow('process.exit');++ expect(mockClient.workspaceMember.updateProfile.mutate).toHaveBeenCalledTimes(2);+ const results = JSON.parse(String(consoleSpy.mock.calls.at(-1)![0]));+ // The refused row reports what is stored, not the value it never wrote.+ expect(results[0]).toMatchObject({ status: 'failed', title: null, userId: 'user_1' });+ expect(results[1]).toMatchObject({ status: 'updated', title: 'X', userId: 'user_2' });+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Permission denied'));+ });+ });+describe('view', () => {it('reads the workspace passed as an argument', async () => {mockClient.workspace.getById.query.mockResolvedValue({diff --git a/apps/cli/src/commands/workspace.ts b/apps/cli/src/commands/workspace.tsindex de6f757cc67..26706d982b0 100644--- a/apps/cli/src/commands/workspace.ts+++ b/apps/cli/src/commands/workspace.ts@@ -1,7 +1,9 @@+import fs from 'node:fs';+import type { Command } from 'commander';import pc from 'picocolors';-import { getTrpcClient } from '../api/client';+import { getTrpcClient, type TrpcClient } from '../api/client';import {PERSONAL_SCOPE_ENV_VALUE,resolveWorkspaceScope,@@ -90,6 +92,87 @@ const isForbidden = (error: unknown): boolean =>error !== null &&(error as { data?: { code?: string } }).data?.code === 'FORBIDDEN';+type MemberRow = Awaited<ReturnType<TrpcClient['workspaceMember']['list']['query']>>[number];++const PROFILE_FIELDS = ['title', 'responsibilities'] as const;+type ProfileField = (typeof PROFILE_FIELDS)[number];++/** One row of a profile write: `null` clears a field, a missing key keeps it. */+interface MemberProfilePatch {+ member: string;+ responsibilities?: string | null;+ title?: string | null;+}++interface MemberProfileResult {+ error?: string;+ name: string | null;+ responsibilities: string | null;+ status: 'failed' | 'unchanged' | 'updated' | 'would-update';+ title: string | null;+ userId: string;+}++/** Mirror the server: trimmed, and blank means "clear". */+const normalizeProfileValue = (value: string | null | undefined) => {+ if (value === undefined || value === null) return value;+ const trimmed = value.trim();+ return trimmed === '' ? null : trimmed;+};++/**+ * Read `[{ member, title?, responsibilities? }, β¦]`. Every entry is checked+ * before anything is sent, so a typo on row 15 cannot leave rows 1β14 written.+ */+const readProfilePatchFile = (file: string): MemberProfilePatch[] => {+ let parsed: unknown;+ try {+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch (error) {+ log.error(`Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`);+ process.exit(1);+ }++ if (!Array.isArray(parsed)) {+ log.error(`${file} must hold a JSON array of { member, title?, responsibilities? } objects.`);+ process.exit(1);+ }++ return parsed.map((entry: unknown, index): MemberProfilePatch => {+ const row = (entry ?? {}) as Record<string, unknown>;+ const fail = (reason: string): never => {+ log.error(`${file} entry #${index + 1}: ${reason}`);+ process.exit(1);+ };++ if (typeof row.member !== 'string' || !row.member.trim())+ fail('"member" must be a user id, username or email.');+ for (const field of PROFILE_FIELDS)+ if (row[field] !== undefined && row[field] !== null && typeof row[field] !== 'string')+ fail(`"${field}" must be a string or null.`);+ if (PROFILE_FIELDS.every((field) => row[field] === undefined))+ fail('provide "title" and/or "responsibilities".');++ return {+ member: row.member as string,+ responsibilities: row.responsibilities as string | null | undefined,+ title: row.title as string | null | undefined,+ };+ });+};++/** Match a member by user id, then by username or email (case-insensitive). */+const findMembers = (members: MemberRow[], ref: string): MemberRow[] => {+ const raw = ref.trim();+ const byId = members.filter((m) => m.userId === raw);+ if (byId.length > 0) return byId;++ const needle = raw.toLowerCase();+ return members.filter(+ (m) => m.user?.username?.toLowerCase() === needle || m.user?.email?.toLowerCase() === needle,+ );+};+const planLabel = (workspace: WorkspaceRow): string => {if (!workspace.plan) return '-';return workspace.lockedOut ? `${workspace.plan} (inactive)` : workspace.plan;@@ -397,12 +480,182 @@ export function registerWorkspaceCommand(program: Command) {truncate(m.user?.fullName || m.user?.username || '-', 24),m.user?.email ?? '-',m.role,+ truncate(m.title || '-', 24),timeAgo(m.joinedAt),]),- ['USER ID', 'NAME', 'EMAIL', 'ROLE', 'JOINED'],+ ['USER ID', 'NAME', 'EMAIL', 'ROLE', 'TITLE', 'JOINED'],);});+ const member = workspace.command('member').description('Manage individual workspace members');++ member+ .command('update [members...]')+ .description(+ "Set members' title and responsibilities (your own, or anyone's as admin or higher)",+ )+ .option('-w, --workspace <id|slug>', 'Workspace to write (defaults to the active scope)')+ .option('-t, --title <title>', 'Job title; pass "" to clear')+ .option('-r, --responsibilities <text>', 'Responsibilities; pass "" to clear')+ .option(+ '-f, --file <path>',+ 'JSON array of { member, title?, responsibilities? } to apply in one run',+ )+ .option('--dry-run', 'Show what would change without writing')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (+ refs: string[],+ options: {+ dryRun?: boolean;+ file?: string;+ json?: boolean | string;+ responsibilities?: string;+ title?: string;+ workspace?: string;+ },+ ) => {+ let patches: MemberProfilePatch[];+ if (options.file) {+ if (+ refs.length > 0 ||+ options.title !== undefined ||+ options.responsibilities !== undefined+ ) {+ log.error('--file carries its own members and fields; drop the other arguments.');+ process.exit(1);+ }+ patches = readProfilePatchFile(options.file);+ } else {+ if (refs.length === 0) {+ log.error('Name at least one member (user id, username or email), or pass --file.');+ process.exit(1);+ }+ if (options.title === undefined && options.responsibilities === undefined) {+ log.error('Nothing to update. Pass --title and/or --responsibilities.');+ process.exit(1);+ }+ patches = refs.map((ref) => ({+ member: ref,+ responsibilities: options.responsibilities,+ title: options.title,+ }));+ }++ const scopeId = await requireScope(options.workspace);+ const client = await getTrpcClient(scopeId);+ const members = await client.workspaceMember.list.query({}).catch((error: unknown) => {+ if (isForbidden(error)) {+ log.error(`Permission denied: you cannot read the members of workspace ${scopeId}.`);+ process.exit(1);+ }+ throw error;+ });+ // A workspace always lists at least the caller; an empty list means the+ // server did not accept this scope, which would otherwise read as+ // "no member matches" for every row.+ if (members.length === 0) {+ log.error(+ `Workspace ${scopeId} is not accessible β it does not exist or you are not a member. Nothing was written.`,+ );+ process.exit(1);+ }++ // Resolve every reference up front: an unknown or ambiguous one aborts+ // the whole run before the first write.+ const targets: { member: MemberRow; patch: MemberProfilePatch }[] = [];+ const problems: string[] = [];+ for (const patch of patches) {+ const matches = findMembers(members, patch.member);+ if (matches.length === 0) problems.push(`no member matches "${patch.member}"`);+ else if (matches.length > 1)+ problems.push(`"${patch.member}" matches ${matches.length} members β use the user id`);+ else if (targets.some((t) => t.member.userId === matches[0].userId))+ problems.push(`"${patch.member}" names ${matches[0].userId} a second time`);+ else targets.push({ member: matches[0], patch });+ }+ if (problems.length > 0) {+ for (const problem of problems) log.error(problem);+ log.error(`Nothing was written to workspace ${scopeId}.`);+ process.exit(1);+ }++ const results: MemberProfileResult[] = [];+ let forbidden = false;+ for (const { member: target, patch } of targets) {+ const name = target.user?.fullName || target.user?.username || null;+ const current = { responsibilities: target.responsibilities, title: target.title };++ // Only send fields that differ, so a re-run is a no-op rather than+ // another round of writes and audit-log entries.+ const changes: Partial<Record<ProfileField, string | null>> = {};+ for (const field of PROFILE_FIELDS) {+ const next = normalizeProfileValue(patch[field]);+ if (next !== undefined && next !== (current[field] ?? null)) changes[field] = next;+ }++ const result: MemberProfileResult = {+ name,+ ...current,+ status: 'unchanged',+ userId: target.userId,+ };+ results.push(result);++ if (Object.keys(changes).length === 0) continue;+ if (options.dryRun) {+ Object.assign(result, changes, { status: 'would-update' });+ continue;+ }++ try {+ const updated = await client.workspaceMember.updateProfile.mutate({+ userId: target.userId,+ ...changes,+ });+ Object.assign(result, {+ responsibilities: updated.responsibilities,+ status: 'updated',+ title: updated.title,+ });+ } catch (error) {+ result.status = 'failed';+ result.error = error instanceof Error ? error.message : String(error);+ // Permission depends on the target β anyone may edit their own+ // profile β so one rejection must not skip the remaining rows.+ if (isForbidden(error)) forbidden = true;+ }+ }++ if (options.json !== undefined) outputJson(results, options.json);+ else {+ printTable(+ results.map((r) => [+ r.userId,+ truncate(r.name ?? '-', 20),+ r.status === 'failed' ? pc.red(r.status) : r.status,+ truncate(r.title ?? '-', 24),+ truncate(r.error ?? r.responsibilities ?? '-', 40),+ ]),+ ['USER ID', 'NAME', 'STATUS', 'TITLE', 'RESPONSIBILITIES'],+ );+ const count = (status: MemberProfileResult['status']) =>+ results.filter((r) => r.status === status).length;+ console.log(+ options.dryRun+ ? `\n${count('would-update')} would change, ${count('unchanged')} already up to date.`+ : `\n${count('updated')} updated, ${count('unchanged')} unchanged, ${count('failed')} failed.`,+ );+ }++ if (forbidden)+ log.error(+ `Permission denied in workspace ${scopeId}: editing another member's profile needs admin or higher.`,+ );+ if (results.some((r) => r.status === 'failed')) process.exit(1);+ },+ );+workspace.command('invite <email>').description('Invite a member by email (admin or higher)')diff --git a/packages/business-server/src/lambda-routers/workspaceMember.ts b/packages/business-server/src/lambda-routers/workspaceMember.tsindex 2a878aea5be..402dd0d8941 100644--- a/packages/business-server/src/lambda-routers/workspaceMember.ts+++ b/packages/business-server/src/lambda-routers/workspaceMember.ts@@ -46,4 +46,21 @@ export const workspaceMemberRouter = router({.query(async (): Promise<WorkspaceMemberSummary[]> => []),listInvitations: wsCompatAdminProcedure.query(async (): Promise<WorkspaceInvitationItem[]> => []),++ // A member's workspace title and responsibilities. Cloud lets any member edit+ // their own and Admin or higher edit anyone's; blank clears, omitted keeps.+ updateProfile: wsCompatProcedure+ .input(+ z.object({+ responsibilities: z.string().nullable().optional(),+ title: z.string().nullable().optional(),+ userId: z.string(),+ }),+ )+ .mutation(async (): Promise<WorkspaceMemberItem> => {+ throw new TRPCError({+ code: 'NOT_IMPLEMENTED',+ message: 'Workspace member profiles are a cloud-only feature.',+ });+ }),});diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.tsindex 8ea3d31165d..32db669228b 100644--- a/packages/const/src/apiKeyScope.test.ts+++ b/packages/const/src/apiKeyScope.test.ts@@ -9,6 +9,7 @@ import {requiredApiKeyScopeForTrpc,TRPC_NAMESPACE_API_KEY_RULES,TRPC_PROCEDURE_EXTRA_SCOPES,+ TRPC_PROCEDURE_SCOPE_GRANTS,} from './apiKeyScope';describe('isValidApiKeyScope', () => {@@ -168,6 +169,18 @@ describe('requiredApiKeyScopeForTrpc', () => {expect(requiredApiKeyScopeForTrpc('usage.reset', 'mutation')).toEqual({ blocked: true });});+ it('opens a granted procedure without opening the rest of its namespace half', () => {+ expect(requiredApiKeyScopeForTrpc('workspaceMember.updateProfile', 'mutation')).toEqual({+ scopes: ['workspace:write'],+ });+ expect(requiredApiKeyScopeForTrpc('workspaceMember.updateRole', 'mutation')).toEqual({+ blocked: true,+ });+ expect(requiredApiKeyScopeForTrpc('workspaceMember.invite', 'mutation')).toEqual({+ blocked: true,+ });+ });+it('blocks sensitive nested sub-surfaces regardless of the parent namespace', () => {expect(requiredApiKeyScopeForTrpc('market.creds.list', 'query')).toEqual({ blocked: true });expect(requiredApiKeyScopeForTrpc('market.creds.createKV', 'mutation')).toEqual({@@ -228,6 +241,15 @@ describe('requiredApiKeyScopeForTrpc', () => {}});+ it('every scope grant targets a registered, non-blocked namespace and a catalog scope', () => {+ for (const [path, scope] of Object.entries(TRPC_PROCEDURE_SCOPE_GRANTS)) {+ const rule = TRPC_NAMESPACE_API_KEY_RULES[path.split('.')[0]];+ expect(rule).toBeDefined();+ expect(rule).not.toBe('blocked');+ expect(isValidApiKeyScope(scope)).toBe(true);+ }+ });+it('every extra-scope path targets a registered namespace and catalog scopes', () => {for (const [path, scopes] of Object.entries(TRPC_PROCEDURE_EXTRA_SCOPES)) {const namespace = path.split('.')[0];diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 9f90245694e..be6b9efbf32 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -444,6 +444,18 @@ export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {'webBrowsing.upsertCrawledDocument': ['knowledge:write'],};+/**+ * Single procedures opened to restricted keys inside a namespace half that is+ * otherwise closed to them (a `null` side of `rw`). The grant is the base scope+ * for that one path; the rest of the namespace half stays blocked. Keep entries+ * narrow and only for procedures that enforce their own authorization.+ */+export const TRPC_PROCEDURE_SCOPE_GRANTS: Record<string, ApiKeyScope> = {+ // a member's workspace title and responsibilities β the procedure still+ // requires self or Admin, while invite / remove / role changes stay closed+ 'workspaceMember.updateProfile': 'workspace:write',+};+/*** Nested sub-surfaces denied to restricted keys regardless of the parent* namespace rule. The namespace table only sees the first path segment, so@@ -495,7 +507,8 @@ export const requiredApiKeyScopeForTrpc = (if (!rule || rule === 'blocked') return { blocked: true };const base =- rule === 'open' ? null : 'any' in rule ? rule.any : type === 'query' ? rule.read : rule.write;+ TRPC_PROCEDURE_SCOPE_GRANTS[path] ??+ (rule === 'open' ? null : 'any' in rule ? rule.any : type === 'query' ? rule.read : rule.write);// a namespace half with no scope grants nothing to restricted keysif (rule !== 'open' && !base) return { blocked: true };