π€― 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): show the server-reported scope in lh whoami (#22254)
Lobehub Coder1523320fc466
diff --git a/apps/cli/src/commands/config.test.ts b/apps/cli/src/commands/config.test.tsindex 5a1f33f9be0..25c9f8c715d 100644--- a/apps/cli/src/commands/config.test.ts+++ b/apps/cli/src/commands/config.test.ts@@ -5,6 +5,9 @@ import { registerConfigCommand } from './config';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {+ auth: {+ getScope: { query: vi.fn() },+ },usage: {findAndGroupByDateRange: { query: vi.fn() },findAndGroupByDay: { query: vi.fn() },@@ -43,6 +46,12 @@ describe('config command', () => {consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});mockGetTrpcClient.mockResolvedValue(mockTrpcClient);mockTrpcClient.user.getUserState.query.mockReset();+ mockTrpcClient.auth.getScope.query.mockReset();+ mockTrpcClient.auth.getScope.query.mockResolvedValue({+ scope: 'personal',+ source: 'personal',+ workspaceId: null,+ });mockTrpcClient.usage.findByMonth.query.mockReset();mockTrpcClient.usage.findAndGroupByDay.query.mockReset();mockTrpcClient.usage.findAndGroupByDateRange.query.mockReset();@@ -94,30 +103,43 @@ describe('config command', () => {);});- // Every command resolves its scope from this env var, so reporting it is- // what lets a caller β usually an agent editing its own config β tell a- // real "not found" from "I'm looking in the wrong workspace".- it('should report the active workspace scope', async () => {- process.env.LOBEHUB_WORKSPACE_ID = 'ws-42';+ // The server reports the scope the request actually ran under, so a+ // workspace API key shows its own workspace even with no local scope set.+ it('should report the workspace scope the server resolved', async () => {+ mockTrpcClient.auth.getScope.query.mockResolvedValue({+ scope: 'workspace',+ source: 'apiKey',+ workspaceId: 'ws-42',+ });mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });const program = createProgram();await program.parseAsync(['node', 'test', 'whoami']);expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('workspace ws-42'));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('(from apiKey)'));});- it('should report personal scope when no workspace is set', async () => {+ // A header naming a workspace the caller cannot use is demoted to personal+ // on the server; the locally configured id must not be shown instead.+ it('should report personal when the server ignores the local workspace', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws-missing';mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });const program = createProgram();await program.parseAsync(['node', 'test', 'whoami']);expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('personal'));+ expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining('ws-missing'));});- it('should carry the workspace scope into --json output', async () => {- process.env.LOBEHUB_WORKSPACE_ID = 'ws-42';+ it('should carry the server scope into --json output', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws-other';+ mockTrpcClient.auth.getScope.query.mockResolvedValue({+ scope: 'workspace',+ source: 'header',+ workspaceId: 'ws-42',+ });mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });const program = createProgram();@@ -125,12 +147,45 @@ describe('config command', () => {expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(- { userId: 'u1', scope: 'workspace', scopeSource: 'env', workspaceId: 'ws-42' },+ { userId: 'u1', scope: 'workspace', scopeSource: 'header', workspaceId: 'ws-42' },null,2,),);});++ // Self-hosted servers older than this CLI have no `auth.getScope`; whoami+ // must still print the identity rather than failing outright.+ it('should fall back to the local scope when the server lacks auth.getScope', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws-local';+ mockTrpcClient.auth.getScope.query.mockRejectedValue(+ Object.assign(new Error('No "query"-procedure on path "auth.getScope"'), {+ data: { code: 'NOT_FOUND' },+ }),+ );+ mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'whoami', '--json']);++ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify(+ { userId: 'u1', scope: 'workspace', scopeSource: 'env', workspaceId: 'ws-local' },+ null,+ 2,+ ),+ );+ });++ it('should surface other auth.getScope failures', async () => {+ mockTrpcClient.auth.getScope.query.mockRejectedValue(+ Object.assign(new Error('boom'), { data: { code: 'INTERNAL_SERVER_ERROR' } }),+ );+ mockTrpcClient.user.getUserState.query.mockResolvedValue({ userId: 'u1' });++ const program = createProgram();+ await expect(program.parseAsync(['node', 'test', 'whoami'])).rejects.toThrow('boom');+ });});describe('usage', () => {diff --git a/apps/cli/src/commands/config.ts b/apps/cli/src/commands/config.tsindex 55069c1eca6..f70d7114608 100644--- a/apps/cli/src/commands/config.ts+++ b/apps/cli/src/commands/config.ts@@ -6,6 +6,7 @@ import { getOpenApi } from '../api/openapi';import { resolveWorkspaceScope } from '../api/workspace';import { resolveWorkspaceRef } from '../api/workspaceRef';import { CLI_PRODUCT_NAME } from '../constants/identity';+import { isMissingProcedure } from '../utils/error';import {type BoxTableRow,formatCost,@@ -24,22 +25,35 @@ export function registerConfigCommand(program: Command) {.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)').action(async (options: { json?: string | boolean }) => {const client = await getTrpcClient();- const state = await client.user.getUserState.query();-- // Every command resolves its scope the same way, so reporting it here is- // what lets a caller (usually an agent editing its own config) tell a- // genuine "not found" from "I'm looking in the wrong workspace".- const scope = resolveWorkspaceScope();- const workspaceId = scope.workspaceId;+ // The scope comes from the server: it is the workspace the request+ // actually ran under (a workspace API key pins its own workspace; a+ // header naming a workspace the caller is not a member of falls back to+ // personal), which is what lets a caller β usually an agent editing its+ // own config β tell a genuine "not found" from "I'm looking in the wrong+ // workspace".+ const [state, { scope, source, workspaceId }] = await Promise.all([+ client.user.getUserState.query(),+ client.auth.getScope.query().catch((error: unknown) => {+ if (!isMissingProcedure(error)) throw error;+ // Self-hosted servers older than this CLI have no `auth.getScope`;+ // report the scope this CLI sends instead.+ const local = resolveWorkspaceScope();+ return {+ scope: local.workspaceId ? 'workspace' : 'personal',+ source: local.source,+ workspaceId: local.workspaceId ?? null,+ };+ }),+ ]);if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;outputJson({...(state as any),- scope: workspaceId ? 'workspace' : 'personal',- scopeSource: scope.source,- workspaceId: workspaceId ?? null,+ scope,+ scopeSource: source,+ workspaceId,},fields,);@@ -54,7 +68,7 @@ export function registerConfigCommand(program: Command) {if (s.userId) console.log(` User ID: ${s.userId}`);if (s.subscriptionPlan) console.log(` Plan: ${s.subscriptionPlan}`);console.log(- ` Scope: ${workspaceId ? `workspace ${workspaceId} ${pc.dim(`(from ${scope.source})`)}` : pc.dim('personal (no workspace scope)')}`,+ ` Scope: ${workspaceId ? `workspace ${workspaceId} ${pc.dim(`(from ${source})`)}` : pc.dim('personal (no workspace scope)')}`,);});