π€― 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 `lh workspace` commands and a persisted workspace scope (#19015)
Arvin Xu6430e476bddd
diff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.mdindex c3b0d1652e6..dc8a6d65670 100644--- a/.agents/skills/cli/SKILL.md+++ b/.agents/skills/cli/SKILL.md@@ -26,6 +26,7 @@ apps/cli/src/β βββ http.ts # Raw HTTP utilitiesβββ auth/β βββ credentials.ts # Encrypted credential storage (AES-256-GCM)+β βββ identity.ts # Account fingerprint for machine-local stateβ βββ refresh.ts # Token auto-refreshβ βββ resolveToken.ts # Token resolution (flag > stored)βββ commands/ # All CLI commands (one file per command group)@@ -46,7 +47,8 @@ apps/cli/src/β βββ search.ts # Global searchβ βββ skill.ts # Agent skill managementβ βββ status.ts # Gateway connectivity check-β βββ topic.ts # Conversation topic management+β βββ topic.ts # Conversation topic management+β βββ workspace.ts # Workspace list/scope/members/usage/auditβββ daemon/β βββ manager.ts # Background daemon process managementβββ tools/@@ -56,7 +58,7 @@ apps/cli/src/β βββ index.ts # Persistent settings (~/.lobehub/)βββ utils/β βββ logger.ts # Logging (verbose mode)-β βββ format.ts # Table output, JSON, timeAgo, truncate+β βββ format.ts # Table output, JSON, timeAgo/timeUntil, truncateβ βββ agentStream.ts # SSE streaming for agent runsβββ constants/βββ urls.ts # Official server & gateway URLs@@ -64,27 +66,46 @@ apps/cli/src/## Command Groups-| Command | Alias | Description |-| ------------- | ----- | ----------------------------------------------------------- |-| `lh login` | - | Authenticate via OIDC Device Code Flow |-| `lh logout` | - | Clear stored credentials |-| `lh connect` | - | Device gateway connection & daemon management |-| `lh status` | - | Quick gateway connectivity check |-| `lh agent` | - | Agent CRUD, run, status |-| `lh generate` | `gen` | Content generation (text, image, video, tts, asr, download) |-| `lh doc` | - | Document CRUD, batch-create, parse, topic linking |-| `lh file` | - | File list, view, delete, recent |-| `lh kb` | - | Knowledge base CRUD, folders, docs, upload, tree view |-| `lh memory` | - | User memory CRUD + extraction |-| `lh message` | - | Message list, search, delete, count, heatmap |-| `lh topic` | - | Topic CRUD + search + recent |-| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |-| `lh model` | - | Model CRUD, toggle, batch-toggle, clear |-| `lh provider` | - | Provider CRUD, config, test, toggle |-| `lh plugin` | - | Plugin install, uninstall, update |-| `lh search` | - | Global search across all types |-| `lh whoami` | - | Current user info |-| `lh usage` | - | Monthly/daily usage statistics |+| Command | Alias | Description |+| -------------- | ----- | ----------------------------------------------------------- |+| `lh login` | - | Authenticate via OIDC Device Code Flow |+| `lh logout` | - | Clear stored credentials |+| `lh connect` | - | Device gateway connection & daemon management |+| `lh status` | - | Quick gateway connectivity check |+| `lh agent` | - | Agent CRUD, run, status |+| `lh generate` | `gen` | Content generation (text, image, video, tts, asr, download) |+| `lh doc` | - | Document CRUD, batch-create, parse, topic linking |+| `lh file` | - | File list, view, delete, recent |+| `lh kb` | - | Knowledge base CRUD, folders, docs, upload, tree view |+| `lh memory` | - | User memory CRUD + extraction |+| `lh message` | - | Message list, search, delete, count, heatmap |+| `lh topic` | - | Topic CRUD + search + recent |+| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |+| `lh model` | - | Model CRUD, toggle, batch-toggle, clear |+| `lh provider` | - | Provider CRUD, config, test, toggle |+| `lh plugin` | - | Plugin install, uninstall, update |+| `lh search` | - | Global search across all types |+| `lh workspace` | `ws` | Workspace list, scope switch, members, invites, usage |+| `lh whoami` | - | Current user info (including the resolved workspace scope) |+| `lh usage` | - | Monthly/daily usage statistics |++### Workspace Scope++Every command runs against one scope, resolved in this order:++1. an explicit `--workspace <id>` on the commands that take it+2. the `LOBEHUB_WORKSPACE_ID` env var+3. the scope persisted by `lh workspace use <id|slug>`+4. personal content (no workspace)++The persisted scope is bound to the account and server it was chosen under. If+either changes β a different `lh login`, a `--server` switch β it is ignored and+reported as stale rather than attaching a workspace header the new identity has+no membership in. `lh logout` clears it. `lh whoami` and `lh workspace current`+both print which of the four sources is in effect.++API-key auth carries no local account identity, so there is nothing to bind a+saved scope to β those callers pass `LOBEHUB_WORKSPACE_ID` instead.## Adding a New Command@@ -177,13 +198,14 @@ if (!options.yes) {## Storage Locations-| File | Path | Purpose |-| ------------- | ----------------------------- | ------------------------------ |-| Credentials | `~/.lobehub/credentials.json` | Encrypted tokens (AES-256-GCM) |-| Settings | `~/.lobehub/settings.json` | Custom server/gateway URLs |-| Daemon PID | `~/.lobehub/daemon.pid` | Background process PID |-| Daemon Status | `~/.lobehub/daemon.status` | Connection status JSON |-| Daemon Log | `~/.lobehub/daemon.log` | Daemon output log |+| File | Path | Purpose |+| ------------- | ----------------------------- | ------------------------------------------------ |+| Credentials | `~/.lobehub/credentials.json` | Encrypted tokens (AES-256-GCM) |+| Settings | `~/.lobehub/settings.json` | Custom server/gateway URLs |+| Workspace | `~/.lobehub/active-workspace` | Active scope + the account/server it is bound to |+| Daemon PID | `~/.lobehub/daemon.pid` | Background process PID |+| Daemon Status | `~/.lobehub/daemon.status` | Connection status JSON |+| Daemon Log | `~/.lobehub/daemon.log` | Daemon output log |The base directory (`~/.lobehub/`) can be overridden with the `LOBEHUB_CLI_HOME` env var (e.g. `LOBEHUB_CLI_HOME=.lobehub-dev` for dev mode isolation).@@ -293,4 +315,4 @@ See `references/` for each command group:- **Memory**: `references/memory.md` (memory management, extraction)- **Skills & Plugins**: `references/skills-plugins.md` (skill, plugin)- **Models & Providers**: `references/models-providers.md` (model, provider)-- **Search & Config**: `references/search-config.md` (search, whoami, usage)+- **Search & Config**: `references/search-config.md` (search, whoami, usage, workspace)diff --git a/.agents/skills/cli/references/search-config.md b/.agents/skills/cli/references/search-config.mdindex 773d0ce0ab7..103b83021b0 100644--- a/.agents/skills/cli/references/search-config.md+++ b/.agents/skills/cli/references/search-config.md@@ -68,6 +68,54 @@ lh usage [--month [--daily] [--json [fields]] < YYYY-MM > ]---+## Workspace (`lh workspace`)++Aliased `lh ws`. Workspace membership is a cloud feature; on an open-source+deployment these procedures answer empty or `NOT_IMPLEMENTED`.++### Scope++| Command | Description |+| ----------------------------- | ------------------------------------------------------ |+| `lh workspace current` | Which scope commands run under, and where it came from |+| `lh workspace use <id\|slug>` | Persist the scope for subsequent commands |+| `lh workspace use --personal` | Drop back to personal content |++Resolution order is `--workspace` β `LOBEHUB_WORKSPACE_ID` β the persisted scope+β personal. Setting the persisted scope while `LOBEHUB_WORKSPACE_ID` is exported+prints a warning, because the env var still wins.++The persisted scope lives in `~/.lobehub/active-workspace` together with the+account (`sub` claim) and server URL it was chosen under. Switching account or+server invalidates it; `lh logout` deletes it. API-key auth has no local account+identity, so `workspace use` refuses to save under it β use the env var.++### Reads++| Command | Description |+| -------------------------- | ----------------------------------------------------- |+| `lh workspace list` | Workspaces you belong to; `*` marks the effective one |+| `lh workspace view [id]` | Workspace detail |+| `lh workspace settings` | The workspace settings blob |+| `lh workspace stats` | Content totals β admin only; `--mine` for your own |+| `lh workspace usage` | Credit spend by type for the billing window |+| `lh workspace members` | Members with role and email |+| `lh workspace invitations` | Pending invitations (admin) |+| `lh workspace audit-log` | Audit entries (admin, Business plan) |++### Writes++| Command | Description |+| ----------------------------------- | ----------------------------------------------- |+| `lh workspace create <name> --slug` | Create a workspace; `--use` switches into it |+| `lh workspace update` | Name / slug / description / avatar (admin) |+| `lh workspace invite <email>` | Invite a member, `--role admin\|member\|viewer` |++Slugs are 3β32 chars, lowercase alphanumerics with inner hyphens. Deleting a+workspace and removing members are deliberately not exposed here.++---+## Global OptionsThese options are available across most commands:diff --git a/apps/cli/src/api/client.test.ts b/apps/cli/src/api/client.test.tsindex ebe41fbb6c2..dd828c89f94 100644--- a/apps/cli/src/api/client.test.ts+++ b/apps/cli/src/api/client.test.ts@@ -13,6 +13,7 @@ vi.mock('../auth/refresh', () => ({}));vi.mock('../settings', () => ({+ loadActiveWorkspace: () => undefined,resolveServerUrl: () => 'https://app.lobehub.com',}));diff --git a/apps/cli/src/api/http.test.ts b/apps/cli/src/api/http.test.tsindex 900c2e333b3..51603fea3f0 100644--- a/apps/cli/src/api/http.test.ts+++ b/apps/cli/src/api/http.test.ts@@ -8,6 +8,7 @@ vi.mock('../auth/refresh', () => ({}));vi.mock('../settings', () => ({+ loadActiveWorkspace: () => undefined,resolveServerUrl: mockResolveServerUrl,}));diff --git a/apps/cli/src/api/workspace.test.ts b/apps/cli/src/api/workspace.test.tsnew file mode 100644index 00000000000..774fdefe1ae--- /dev/null+++ b/apps/cli/src/api/workspace.test.ts@@ -0,0 +1,151 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../utils/logger';+import {+ __resetStaleScopeWarning,+ resolveWorkspaceId,+ resolveWorkspaceScope,+ withWorkspaceHeader,+} from './workspace';++const { mockLoadActiveWorkspace, mockResolveIdentityFingerprint, mockResolveServerUrl } =+ vi.hoisted(() => ({+ mockLoadActiveWorkspace: vi.fn<() => Record<string, string> | undefined>(),+ mockResolveIdentityFingerprint: vi.fn<() => string | undefined>(),+ mockResolveServerUrl: vi.fn<() => string>(),+ }));++vi.mock('../settings', () => ({+ loadActiveWorkspace: mockLoadActiveWorkspace,+ resolveServerUrl: mockResolveServerUrl,+}));+vi.mock('../auth/identity', () => ({+ resolveIdentityFingerprint: mockResolveIdentityFingerprint,+}));++const SERVER = 'https://app.lobehub.com';+const stored = (overrides: Record<string, string> = {}) => ({+ identity: 'user:u1',+ serverUrl: SERVER,+ workspaceId: 'ws_stored',+ ...overrides,+});++describe('api/workspace scope resolution', () => {+ const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;++ beforeEach(() => {+ vi.clearAllMocks();+ __resetStaleScopeWarning();+ mockLoadActiveWorkspace.mockReturnValue(undefined);+ mockResolveIdentityFingerprint.mockReturnValue('user:u1');+ mockResolveServerUrl.mockReturnValue(SERVER);+ delete process.env.LOBEHUB_WORKSPACE_ID;+ });++ afterEach(() => {+ if (originalWorkspaceId === undefined) delete process.env.LOBEHUB_WORKSPACE_ID;+ else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;+ });++ it('reports personal scope when nothing is configured', () => {+ expect(resolveWorkspaceScope()).toEqual({ source: 'personal' });+ expect(resolveWorkspaceId()).toBeUndefined();+ });++ it('uses the workspace persisted by `workspace use`', () => {+ mockLoadActiveWorkspace.mockReturnValue(stored());++ expect(resolveWorkspaceScope()).toEqual({ source: 'settings', workspaceId: 'ws_stored' });+ });++ // A one-off invocation has to be able to override the machine-wide default+ // without rewriting it, so the env var wins over the persisted scope.+ it('prefers the env var over the persisted workspace', () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_env';+ mockLoadActiveWorkspace.mockReturnValue(stored());++ expect(resolveWorkspaceScope()).toEqual({ source: 'env', workspaceId: 'ws_env' });+ });++ it('prefers an explicit argument over everything else', () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_env';+ mockLoadActiveWorkspace.mockReturnValue(stored());++ expect(resolveWorkspaceScope('ws_explicit')).toEqual({+ source: 'explicit',+ workspaceId: 'ws_explicit',+ });+ });++ // Cloud answers a workspace header the caller has no membership in by falling+ // back to personal scope, so a scope carried across an account or server+ // switch would silently write personal data while claiming to be scoped.+ describe('stale bindings', () => {+ it.each([+ ['the account changed', () => mockResolveIdentityFingerprint.mockReturnValue('user:u2')],+ ['the account is gone', () => mockResolveIdentityFingerprint.mockReturnValue(undefined)],+ [+ 'the server changed',+ () => mockResolveServerUrl.mockReturnValue('https://self-hosted.example.com'),+ ],+ ])('drops the persisted scope when %s', (_label, arrange) => {+ mockLoadActiveWorkspace.mockReturnValue(stored());+ arrange();++ expect(resolveWorkspaceScope()).toEqual({ source: 'stale' });+ expect(withWorkspaceHeader({ 'Oidc-Auth': 'token' })).toEqual({ 'Oidc-Auth': 'token' });+ });++ // The reason is the whole value of the warning: "different account" and+ // "no account at all" need different fixes.+ it.each([+ [+ 'names the other account',+ () => mockResolveIdentityFingerprint.mockReturnValue('user:u2'),+ 'a different account',+ ],+ [+ 'points API-key callers at the env var',+ () => mockResolveIdentityFingerprint.mockReturnValue(undefined),+ 'LOBEHUB_WORKSPACE_ID',+ ],+ [+ 'names the other server',+ () => mockResolveServerUrl.mockReturnValue('https://self-hosted.example.com'),+ 'https://app.lobehub.com',+ ],+ ])('%s', (_label, arrange, expected) => {+ mockLoadActiveWorkspace.mockReturnValue(stored());+ arrange();++ resolveWorkspaceScope();++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining(expected));+ });++ it('warns at most once per process', () => {+ mockLoadActiveWorkspace.mockReturnValue(stored());+ mockResolveIdentityFingerprint.mockReturnValue('user:u2');++ resolveWorkspaceScope();+ resolveWorkspaceScope();++ expect(log.warn).toHaveBeenCalledTimes(1);+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('ws_stored'));+ });+ });++ it('sends the persisted workspace as a header', () => {+ mockLoadActiveWorkspace.mockReturnValue(stored());++ expect(withWorkspaceHeader({ 'Oidc-Auth': 'token' })).toEqual({+ 'Oidc-Auth': 'token',+ 'X-Workspace-Id': 'ws_stored',+ });+ });++ it('omits the header in personal scope', () => {+ expect(withWorkspaceHeader({ 'Oidc-Auth': 'token' })).toEqual({ 'Oidc-Auth': 'token' });+ });+});diff --git a/apps/cli/src/api/workspace.ts b/apps/cli/src/api/workspace.tsindex 492f2502aff..1f8d290b5f5 100644--- a/apps/cli/src/api/workspace.ts+++ b/apps/cli/src/api/workspace.ts@@ -1,14 +1,68 @@+import { resolveIdentityFingerprint } from '../auth/identity';+import { loadActiveWorkspace, resolveServerUrl } from '../settings';+import { log } from '../utils/logger';+export const WORKSPACE_ID_HEADER = 'X-Workspace-Id';+export type WorkspaceScopeSource = 'explicit' | 'env' | 'settings' | 'stale' | 'personal';++export interface WorkspaceScope {+ source: WorkspaceScopeSource;+ workspaceId?: string;+}++let warnedAboutStaleScope = false;+/**- * Resolve the workspace scope for outbound API calls.+ * A persisted scope only counts when the server and account it was chosen under+ * still match. Cloud answers an `X-Workspace-Id` the caller has no membership in+ * by quietly falling back to personal scope, so a scope left over from another+ * account would route reads *and writes* to personal data while every status+ * line still said "workspace".+ */+function resolvePersistedScope(): WorkspaceScope | undefined {+ const stored = loadActiveWorkspace();+ if (!stored) return undefined;++ const identity = resolveIdentityFingerprint();+ const reason = !identity+ ? "the current credentials don't identify an account β set LOBEHUB_WORKSPACE_ID instead"+ : identity !== stored.identity+ ? `it was set under a different account. Run 'workspace use' again to re-select it`+ : stored.serverUrl !== resolveServerUrl()+ ? `it was set for ${stored.serverUrl}`+ : undefined;++ if (!reason) return { source: 'settings', workspaceId: stored.workspaceId };++ if (!warnedAboutStaleScope) {+ warnedAboutStaleScope = true;+ log.warn(`Ignoring the saved workspace scope (${stored.workspaceId}): ${reason}.`);+ }++ return { source: 'stale' };+}++/**+ * Resolve the workspace scope for outbound API calls, along with where it came+ * from β `lh workspace current` and `lh whoami` report the source so a caller+ * can tell "wrong workspace" from "not found".*- * Precedence: explicit caller arg -> `LOBEHUB_WORKSPACE_ID` env -> personal mode.+ * Precedence: explicit caller arg -> `LOBEHUB_WORKSPACE_ID` env ->+ * `lh workspace use` (persisted, and still bound to this account/server) ->+ * personal mode.*/-export function resolveWorkspaceId(explicit?: string): string | undefined {- if (explicit) return explicit;+export function resolveWorkspaceScope(explicit?: string): WorkspaceScope {+ if (explicit) return { source: 'explicit', workspaceId: explicit };+const fromEnv = process.env.LOBEHUB_WORKSPACE_ID;- return fromEnv && fromEnv.length > 0 ? fromEnv : undefined;+ if (fromEnv && fromEnv.length > 0) return { source: 'env', workspaceId: fromEnv };++ return resolvePersistedScope() ?? { source: 'personal' };+}++export function resolveWorkspaceId(explicit?: string): string | undefined {+ return resolveWorkspaceScope(explicit).workspaceId;}export function withWorkspaceHeader(@@ -18,3 +72,8 @@ export function withWorkspaceHeader(const resolvedWorkspaceId = resolveWorkspaceId(workspaceId);return resolvedWorkspaceId ? { ...headers, [WORKSPACE_ID_HEADER]: resolvedWorkspaceId } : headers;}++/** Test seam: the stale-scope warning is emitted at most once per process. */+export function __resetStaleScopeWarning(): void {+ warnedAboutStaleScope = false;+}diff --git a/apps/cli/src/auth/identity.test.ts b/apps/cli/src/auth/identity.test.tsnew file mode 100644index 00000000000..14b40f2cf9a--- /dev/null+++ b/apps/cli/src/auth/identity.test.ts@@ -0,0 +1,80 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveIdentityFingerprint } from './identity';++const { mockLoadCredentials } = vi.hoisted(() => ({+ mockLoadCredentials: vi.fn<() => { accessToken: string } | null>(),+}));++vi.mock('./credentials', () => ({ loadCredentials: mockLoadCredentials }));++const jwtWithSub = (sub: string) =>+ `header.${Buffer.from(JSON.stringify({ sub })).toString('base64url')}.signature`;++describe('resolveIdentityFingerprint', () => {+ const originalJwt = process.env.LOBEHUB_JWT;+ const originalApiKey = process.env.LOBEHUB_CLI_API_KEY;++ beforeEach(() => {+ vi.clearAllMocks();+ delete process.env.LOBEHUB_JWT;+ mockLoadCredentials.mockReturnValue(null);+ delete process.env.LOBEHUB_CLI_API_KEY;+ });++ afterEach(() => {+ if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;+ else process.env.LOBEHUB_JWT = originalJwt;+ if (originalApiKey === undefined) delete process.env.LOBEHUB_CLI_API_KEY;+ else process.env.LOBEHUB_CLI_API_KEY = originalApiKey;+ });++ it('returns undefined when there is nothing to authenticate with', () => {+ expect(resolveIdentityFingerprint()).toBeUndefined();+ });++ it('reads the subject out of stored credentials', () => {+ mockLoadCredentials.mockReturnValue({ accessToken: jwtWithSub('user_1') });++ expect(resolveIdentityFingerprint()).toBe('user:user_1');+ });++ it('distinguishes two accounts on the same machine', () => {+ mockLoadCredentials.mockReturnValue({ accessToken: jwtWithSub('user_1') });+ const first = resolveIdentityFingerprint();++ mockLoadCredentials.mockReturnValue({ accessToken: jwtWithSub('user_2') });++ expect(resolveIdentityFingerprint()).not.toBe(first);+ });++ it('prefers the env JWT over stored credentials', () => {+ process.env.LOBEHUB_JWT = jwtWithSub('user_env');+ mockLoadCredentials.mockReturnValue({ accessToken: jwtWithSub('user_stored') });++ expect(resolveIdentityFingerprint()).toBe('user:user_env');+ });++ // An API key has no readable subject. Digesting the key to make one would put+ // a secret-derived artifact on disk, so this mode has no identity at all.+ it('has no identity for API-key credentials', () => {+ process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-secret';++ expect(resolveIdentityFingerprint()).toBeUndefined();+ });++ // The request authenticates as the API key's owner, so reading past it to the+ // stored login would bind the scope to a different account than the caller.+ it('does not fall back to the stored login when an API key is set', () => {+ process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-secret';+ mockLoadCredentials.mockReturnValue({ accessToken: jwtWithSub('user_1') });++ expect(resolveIdentityFingerprint()).toBeUndefined();+ });++ it('returns undefined for a token with no parseable subject', () => {+ mockLoadCredentials.mockReturnValue({ accessToken: 'not-a-jwt' });++ expect(resolveIdentityFingerprint()).toBeUndefined();+ });+});diff --git a/apps/cli/src/auth/identity.ts b/apps/cli/src/auth/identity.tsnew file mode 100644index 00000000000..19bd7c71c38--- /dev/null+++ b/apps/cli/src/auth/identity.ts@@ -0,0 +1,44 @@+import { readCliApiKeyEnv } from '../constants/auth';+import { loadCredentials } from './credentials';++/**+ * The account this process would authenticate as, taken from the `sub` claim of+ * whichever token is in play. Used to bind machine-local state (currently the+ * persisted workspace scope) to the account that produced it, so switching+ * accounts β or logging out and back in as someone else β cannot leave that+ * state pointing at a tenant the new identity has nothing to do with.+ *+ * Only public claims are read. An API key carries no readable subject and the+ * only local way to derive one would be to digest the key itself, which would+ * put a secret-derived artifact on disk for no benefit β so API-key mode+ * returns `undefined` and scope has to come from `LOBEHUB_WORKSPACE_ID`.+ *+ * Callers must treat `undefined` as "no identity to bind to", never as a match.+ */+export function resolveIdentityFingerprint(): string | undefined {+ // Must follow the same precedence `getAuthAndServer` uses to pick credentials.+ // Reading past an API key to the stored login would bind the scope to one+ // account while the request authenticates as another.+ const envJwt = process.env.LOBEHUB_JWT;+ if (envJwt) return userIdentity(envJwt);++ if (readCliApiKeyEnv()) return undefined;++ const stored = loadCredentials();+ return stored?.accessToken ? userIdentity(stored.accessToken) : undefined;+}++function userIdentity(token: string): string | undefined {+ const sub = parseJwtSub(token);+ return sub ? `user:${sub}` : undefined;+}++/** Parse the `sub` claim from a JWT without verifying the signature. */+function parseJwtSub(token: string): string | undefined {+ try {+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());+ return typeof payload.sub === 'string' ? payload.sub : undefined;+ } catch {+ return undefined;+ }+}diff --git a/apps/cli/src/commands/config.test.ts b/apps/cli/src/commands/config.test.tsindex db1e8897cd0..53062f7df82 100644--- a/apps/cli/src/commands/config.test.ts+++ b/apps/cli/src/commands/config.test.ts@@ -21,6 +21,12 @@ const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({}));vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+// Scope resolution falls through to the persisted `workspace use` value, which+// must not leak the developer's own machine state into these assertions.+vi.mock('../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));describe('config command', () => {let consoleSpy: ReturnType<typeof vi.spyOn>;const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;@@ -73,7 +79,11 @@ describe('config command', () => {await program.parseAsync(['node', 'test', 'whoami', '--json']);expect(consoleSpy).toHaveBeenCalledWith(- JSON.stringify({ ...state, scope: 'personal', workspaceId: null }, null, 2),+ JSON.stringify(+ { ...state, scope: 'personal', scopeSource: 'personal', workspaceId: null },+ null,+ 2,+ ),);});@@ -107,7 +117,11 @@ describe('config command', () => {await program.parseAsync(['node', 'test', 'whoami', '--json']);expect(consoleSpy).toHaveBeenCalledWith(- JSON.stringify({ userId: 'u1', scope: 'workspace', workspaceId: 'ws-42' }, null, 2),+ JSON.stringify(+ { userId: 'u1', scope: 'workspace', scopeSource: 'env', workspaceId: 'ws-42' },+ null,+ 2,+ ),);});});diff --git a/apps/cli/src/commands/config.ts b/apps/cli/src/commands/config.tsindex 8dd35c2e338..4eb09f84ae4 100644--- a/apps/cli/src/commands/config.ts+++ b/apps/cli/src/commands/config.ts@@ -2,7 +2,7 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';-import { resolveWorkspaceId } from '../api/workspace';+import { resolveWorkspaceScope } from '../api/workspace';import { CLI_PRODUCT_NAME } from '../constants/identity';import {type BoxTableRow,@@ -27,7 +27,8 @@ export function registerConfigCommand(program: Command) {// 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 workspaceId = resolveWorkspaceId();+ const scope = resolveWorkspaceScope();+ const workspaceId = scope.workspaceId;if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;@@ -35,6 +36,7 @@ export function registerConfigCommand(program: Command) {{...(state as any),scope: workspaceId ? 'workspace' : 'personal',+ scopeSource: scope.source,workspaceId: workspaceId ?? null,},fields,@@ -50,7 +52,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('personal (no workspace scope)')}`,+ ` Scope: ${workspaceId ? `workspace ${workspaceId} ${pc.dim(`(from ${scope.source})`)}` : pc.dim('personal (no workspace scope)')}`,);});diff --git a/apps/cli/src/commands/logout.test.ts b/apps/cli/src/commands/logout.test.tsindex 923bddcfd47..0a7c64c0f7a 100644--- a/apps/cli/src/commands/logout.test.ts+++ b/apps/cli/src/commands/logout.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { clearCredentials } from '../auth/credentials';import { stopDaemon } from '../daemon/manager';+import { saveActiveWorkspace } from '../settings';import { log } from '../utils/logger';import { registerLogoutCommand } from './logout';@@ -14,6 +15,10 @@ vi.mock('../daemon/manager', () => ({stopDaemon: vi.fn(),}));+vi.mock('../settings', () => ({+ saveActiveWorkspace: vi.fn(),+}));+describe('logout command', () => {beforeEach(() => {vi.clearAllMocks();@@ -37,6 +42,16 @@ describe('logout command', () => {expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Logged out'));});+ // The scope belongs to the account that set it; the next login may be someone+ // else, and a leftover scope would claim a workspace they aren't a member of.+ it('should clear the persisted workspace scope', async () => {+ vi.mocked(clearCredentials).mockReturnValue(true);++ await createProgram().parseAsync(['node', 'test', 'logout']);++ expect(saveActiveWorkspace).toHaveBeenCalledWith(null);+ });+it('should log already logged out when no credentials', async () => {vi.mocked(clearCredentials).mockReturnValue(false);diff --git a/apps/cli/src/commands/logout.ts b/apps/cli/src/commands/logout.tsindex 82a7c67c62f..b40f4482b09 100644--- a/apps/cli/src/commands/logout.ts+++ b/apps/cli/src/commands/logout.ts@@ -2,6 +2,7 @@ import type { Command } from 'commander';import { clearCredentials } from '../auth/credentials';import { stopDaemon } from '../daemon/manager';+import { saveActiveWorkspace } from '../settings';import { log } from '../utils/logger';export function registerLogoutCommand(program: Command) {@@ -17,6 +18,11 @@ export function registerLogoutCommand(program: Command) {log.info('Disconnected device daemon.');}+ // The workspace scope belongs to the account that set it. Leaving it behind+ // means the next login β possibly a different account β starts out claiming+ // a workspace it may have no membership in.+ saveActiveWorkspace(null);+const removed = clearCredentials();if (removed) {log.info('Logged out. Credentials removed.');diff --git a/apps/cli/src/commands/workspace.test.ts b/apps/cli/src/commands/workspace.test.tsnew file mode 100644index 00000000000..20cb3662630--- /dev/null+++ b/apps/cli/src/commands/workspace.test.ts@@ -0,0 +1,500 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../utils/logger';+import { registerWorkspaceCommand } from './workspace';++const {+ mockClient,+ mockGetTrpcClient,+ mockResolveIdentityFingerprint,+ mockResolveWorkspaceScope,+ mockSaveActiveWorkspace,+} = vi.hoisted(() => ({+ mockClient: {+ workspace: {+ create: { mutate: vi.fn() },+ getById: { query: vi.fn() },+ getMyStatistics: { query: vi.fn() },+ getSettings: { query: vi.fn() },+ getStatistics: { query: vi.fn() },+ list: { query: vi.fn() },+ update: { mutate: vi.fn() },+ },+ workspaceAuditLog: { list: { query: vi.fn() } },+ workspaceMember: {+ invite: { mutate: vi.fn() },+ list: { query: vi.fn() },+ listInvitations: { query: vi.fn() },+ },+ workspaceUsage: { getCurrentUsage: { query: vi.fn() } },+ },+ mockGetTrpcClient: vi.fn(),+ mockResolveIdentityFingerprint: vi.fn<() => string | undefined>(),+ mockResolveWorkspaceScope: vi.fn(),+ mockSaveActiveWorkspace: vi.fn(),+}));++vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../api/workspace', () => ({ resolveWorkspaceScope: mockResolveWorkspaceScope }));+vi.mock('../auth/identity', () => ({+ resolveIdentityFingerprint: mockResolveIdentityFingerprint,+}));+vi.mock('../settings', () => ({+ resolveServerUrl: () => 'https://app.lobehub.com',+ saveActiveWorkspace: mockSaveActiveWorkspace,+}));++/** Stand in for the resolved scope every command reads. */+const scopedTo = (workspaceId?: string) =>+ mockResolveWorkspaceScope.mockImplementation((explicit?: string) => {+ if (explicit) return { source: 'explicit', workspaceId: explicit };+ if (process.env.LOBEHUB_WORKSPACE_ID)+ return { source: 'env', workspaceId: process.env.LOBEHUB_WORKSPACE_ID };+ return workspaceId ? { source: 'settings', workspaceId } : { source: 'personal' };+ });++const createProgram = () => {+ const program = new Command();+ program.exitOverride();+ registerWorkspaceCommand(program);+ return program;+};++const run = (...argv: string[]) => createProgram().parseAsync(['node', 'test', ...argv]);++describe('workspace command', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;++ beforeEach(() => {+ vi.clearAllMocks();+ delete process.env.LOBEHUB_WORKSPACE_ID;+ scopedTo(undefined);+ mockResolveIdentityFingerprint.mockReturnValue('user:u1');+ mockGetTrpcClient.mockResolvedValue(mockClient);+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(process, 'exit').mockImplementation((() => {+ throw new Error('process.exit');+ }) as never);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ if (originalWorkspaceId === undefined) delete process.env.LOBEHUB_WORKSPACE_ID;+ else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;+ });++ describe('list', () => {+ it('lists workspaces and marks the active one', async () => {+ mockClient.workspace.list.query.mockResolvedValue([+ { id: 'ws_1', name: 'Acme', plan: 'pro', role: 'owner', slug: 'acme' },+ { id: 'ws_2', name: 'Beta', role: 'member', slug: 'beta' },+ ]);+ scopedTo('ws_2');++ await run('workspace', 'list');++ const output = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(output).toContain('Acme');+ expect(output).toContain('* ws_2');+ expect(output).not.toContain('* ws_1');+ });++ // The marker has to follow the same precedence every other command uses.+ it('marks the env-selected workspace over the persisted one', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_1';+ scopedTo('ws_2');+ mockClient.workspace.list.query.mockResolvedValue([+ { id: 'ws_1', name: 'Acme', role: 'owner', slug: 'acme' },+ { id: 'ws_2', name: 'Beta', role: 'member', slug: 'beta' },+ ]);++ await run('workspace', 'list');++ const output = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(output).toContain('* ws_1');+ expect(output).not.toContain('* ws_2');+ });++ it('reports an empty account instead of printing an empty table', async () => {+ mockClient.workspace.list.query.mockResolvedValue([]);++ await run('workspace', 'list');++ expect(consoleSpy).toHaveBeenCalledWith('No workspaces found.');+ });+ });++ describe('use', () => {+ it('accepts a slug and persists the resolved id', async () => {+ mockClient.workspace.list.query.mockResolvedValue([+ { id: 'ws_1', name: 'Acme', role: 'owner', slug: 'acme' },+ ]);++ await run('workspace', 'use', 'acme');++ expect(mockSaveActiveWorkspace).toHaveBeenCalledWith({+ identity: 'user:u1',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_1',+ });+ });++ it('refuses a workspace the account does not belong to', async () => {+ mockClient.workspace.list.query.mockResolvedValue([+ { id: 'ws_1', name: 'Acme', role: 'owner', slug: 'acme' },+ ]);++ await expect(run('workspace', 'use', 'ws_missing')).rejects.toThrow('process.exit');+ expect(mockSaveActiveWorkspace).not.toHaveBeenCalled();+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('ws_missing'));+ });++ // The env var wins in `resolveWorkspaceScope`, so persisting silently would+ // leave the user staring at the old scope.+ it('warns when LOBEHUB_WORKSPACE_ID would override the new scope', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_env';+ mockClient.workspace.list.query.mockResolvedValue([+ { id: 'ws_1', name: 'Acme', role: 'owner', slug: 'acme' },+ ]);++ await run('workspace', 'use', 'ws_1');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('LOBEHUB_WORKSPACE_ID'));+ });++ // Without an identity the record cannot be bound, and an unbound scope is+ // exactly what survives an account switch.+ it('refuses to persist a scope when not logged in', async () => {+ mockResolveIdentityFingerprint.mockReturnValue(undefined);+ mockClient.workspace.list.query.mockResolvedValue([+ { id: 'ws_1', name: 'Acme', role: 'owner', slug: 'acme' },+ ]);++ await expect(run('workspace', 'use', 'acme')).rejects.toThrow('process.exit');+ expect(mockSaveActiveWorkspace).not.toHaveBeenCalled();+ });++ it('clears the scope with --personal', async () => {+ await run('workspace', 'use', '--personal');++ expect(mockSaveActiveWorkspace).toHaveBeenCalledWith(null);+ expect(mockClient.workspace.list.query).not.toHaveBeenCalled();+ expect(log.warn).not.toHaveBeenCalled();+ });++ // Clearing the file does not clear the env var, so "Scope set to personal"+ // on its own would leave the next mutation pointed at a workspace.+ it('warns that --personal does not beat LOBEHUB_WORKSPACE_ID', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_env';++ await run('workspace', 'use', '--personal');++ expect(mockSaveActiveWorkspace).toHaveBeenCalledWith(null);+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('ws_env'));+ });+ });++ describe('scoped reads', () => {+ it('fails with an actionable message when no workspace scope is set', async () => {+ await expect(run('workspace', 'members')).rejects.toThrow('process.exit');++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('workspace use'));+ expect(mockClient.workspaceMember.list.query).not.toHaveBeenCalled();+ });++ it('sends the --workspace override into the client scope', async () => {+ mockClient.workspaceMember.list.query.mockResolvedValue([]);++ await run('workspace', 'members', '--workspace', 'ws_9');++ expect(mockGetTrpcClient).toHaveBeenCalledWith('ws_9');+ expect(consoleSpy).toHaveBeenCalledWith('No members found.');+ });++ it('lists members of the active workspace', async () => {+ scopedTo('ws_1');+ mockClient.workspaceMember.list.query.mockResolvedValue([+ {+ joinedAt: new Date().toISOString(),+ role: 'admin',+ user: { email: '[email protected]', fullName: 'Ada' },+ userId: 'user_1',+ },+ ]);++ await run('workspace', 'members');++ expect(mockGetTrpcClient).toHaveBeenCalledWith('ws_1');+ const output = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(output).toContain('Ada');+ expect(output).toContain('[email protected]');+ });+ });++ describe('view', () => {+ it('reads the workspace passed as an argument', async () => {+ mockClient.workspace.getById.query.mockResolvedValue({+ id: 'ws_1',+ name: 'Acme',+ slug: 'acme',+ });++ await run('workspace', 'view', 'ws_1', '--json');++ expect(mockGetTrpcClient).toHaveBeenCalledWith('ws_1');+ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify({ id: 'ws_1', name: 'Acme', slug: 'acme' }, null, 2),+ );+ });++ it('exits when the workspace is gone', async () => {+ scopedTo('ws_1');+ mockClient.workspace.getById.query.mockResolvedValue(null);++ await expect(run('workspace', 'view')).rejects.toThrow('process.exit');+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('ws_1'));+ });+ });++ describe('create', () => {+ it('creates a workspace and can switch to it', async () => {+ mockClient.workspace.create.mutate.mockResolvedValue({ id: 'ws_new', name: 'Acme' });++ await run('workspace', 'create', 'Acme', '--slug', 'acme', '--use');++ expect(mockClient.workspace.create.mutate).toHaveBeenCalledWith({+ avatar: undefined,+ description: undefined,+ name: 'Acme',+ slug: 'acme',+ });+ expect(mockSaveActiveWorkspace).toHaveBeenCalledWith(+ expect.objectContaining({ identity: 'user:u1', workspaceId: 'ws_new' }),+ );+ });++ it('warns that --use does not beat LOBEHUB_WORKSPACE_ID', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_env';+ mockClient.workspace.create.mutate.mockResolvedValue({ id: 'ws_new', name: 'Acme' });++ await run('workspace', 'create', 'Acme', '--slug', 'acme', '--use');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('ws_env'));+ });+ });++ describe('update', () => {+ it('rejects an update with no fields instead of sending an empty patch', async () => {+ scopedTo('ws_1');++ await expect(run('workspace', 'update')).rejects.toThrow('process.exit');+ expect(mockClient.workspace.update.mutate).not.toHaveBeenCalled();+ });++ it('sends only the provided fields', async () => {+ scopedTo('ws_1');++ await run('workspace', 'update', '--name', 'Acme Inc');++ expect(mockClient.workspace.update.mutate).toHaveBeenCalledWith({+ avatar: undefined,+ description: undefined,+ name: 'Acme Inc',+ slug: undefined,+ });+ });+ });++ describe('stats', () => {+ it('reads workspace-wide totals by default and own totals with --mine', async () => {+ scopedTo('ws_1');+ mockClient.workspace.getStatistics.query.mockResolvedValue({+ agents: 3,+ messages: 10,+ messagesToday: 2,+ topics: 5,+ });+ mockClient.workspace.getMyStatistics.query.mockResolvedValue({+ agents: 1,+ messages: 4,+ messagesToday: 1,+ topics: 2,+ });++ await run('workspace', 'stats');+ expect(mockClient.workspace.getStatistics.query).toHaveBeenCalled();++ await run('workspace', 'stats', '--mine');+ expect(mockClient.workspace.getMyStatistics.query).toHaveBeenCalled();+ });++ // Workspace-wide totals are admin-only, so a plain member otherwise gets a+ // bare FORBIDDEN for a question they are allowed to ask a different way.+ it('points a non-admin at --mine instead of surfacing FORBIDDEN', async () => {+ scopedTo('ws_1');+ mockClient.workspace.getStatistics.query.mockRejectedValue({ data: { code: 'FORBIDDEN' } });++ await expect(run('workspace', 'stats')).rejects.toThrow('process.exit');+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--mine'));+ });++ it('lets an unrelated failure through instead of blaming permissions', async () => {+ scopedTo('ws_1');+ mockClient.workspace.getStatistics.query.mockRejectedValue(new Error('fetch failed'));++ await expect(run('workspace', 'stats')).rejects.toThrow('fetch failed');+ });+ });++ describe('invite', () => {+ it('rejects an unknown role before hitting the server', async () => {+ scopedTo('ws_1');++ await expect(+ run('workspace', 'invite', '[email protected]', '--role', 'superuser'),+ ).rejects.toThrow('process.exit');+ expect(mockClient.workspaceMember.invite.mutate).not.toHaveBeenCalled();+ });++ it('invites with the default member role', async () => {+ scopedTo('ws_1');+ mockClient.workspaceMember.invite.mutate.mockResolvedValue({ id: 'inv_1' });++ await run('workspace', 'invite', '[email protected]');++ expect(mockClient.workspaceMember.invite.mutate).toHaveBeenCalledWith({+ email: '[email protected]',+ role: 'member',+ });+ });+ });++ describe('invitations', () => {+ // `timeAgo` on a future timestamp renders "-604800s ago".+ it('counts down to the expiry instead of rendering a negative age', async () => {+ scopedTo('ws_1');+ mockClient.workspaceMember.listInvitations.query.mockResolvedValue([+ {+ email: '[email protected]',+ expiresAt: new Date(Date.now() + 6 * 86_400_000 + 60_000).toISOString(),+ id: 'inv_1',+ role: 'member',+ status: 'pending',+ },+ ]);++ await run('workspace', 'invitations');++ const output = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(output).toContain('in 6d');+ expect(output).not.toContain('ago');+ });+ });++ describe('audit-log', () => {+ it('passes filters through and renders entries', async () => {+ scopedTo('ws_1');+ mockClient.workspaceAuditLog.list.query.mockResolvedValue({+ items: [+ {+ action: 'workspace.updated',+ createdAt: new Date().toISOString(),+ id: 'log_1',+ resourceType: null,+ userId: 'user_1',+ },+ ],+ nextCursor: null,+ });++ await run('workspace', 'audit-log', '--action', 'workspace.updated', '-L', '5');++ expect(mockClient.workspaceAuditLog.list.query).toHaveBeenCalledWith({+ action: 'workspace.updated',+ endDate: undefined,+ limit: 5,+ q: undefined,+ resourceType: undefined,+ startDate: undefined,+ });+ expect(consoleSpy.mock.calls.map((c) => String(c[0])).join('\n')).toContain(+ 'workspace.updated',+ );+ });++ it('rejects a non-numeric limit', async () => {+ scopedTo('ws_1');++ await expect(run('workspace', 'audit-log', '-L', 'many')).rejects.toThrow('process.exit');+ expect(mockClient.workspaceAuditLog.list.query).not.toHaveBeenCalled();+ });+ });++ describe('usage', () => {+ it('renders spend per type', async () => {+ scopedTo('ws_1');+ mockClient.workspaceUsage.getCurrentUsage.query.mockResolvedValue({+ remainingBalance: 12.5,+ since: '2026-08-01T00:00:00.000Z',+ subscription: null,+ until: '2026-08-31T00:00:00.000Z',+ usageByType: [{ spend: 3.25, type: 'chat' }],+ });++ await run('workspace', 'usage');++ const output = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(output).toContain('2026-08-01 β 2026-08-31');+ expect(output).toContain('$12.50');+ expect(output).toContain('$3.25');+ });+ });++ describe('current', () => {+ it('reports personal scope without calling the server', async () => {+ await run('workspace', 'current');++ expect(consoleSpy.mock.calls.map((c) => String(c[0])).join('\n')).toContain('personal');+ expect(mockGetTrpcClient).not.toHaveBeenCalled();+ });++ it('names the active workspace and where the scope came from', async () => {+ scopedTo('ws_1');+ mockClient.workspace.getById.query.mockResolvedValue({+ id: 'ws_1',+ name: 'Acme',+ slug: 'acme',+ });++ await run('workspace', 'current');++ const output = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(output).toContain('ws_1');+ expect(output).toContain('workspace use');+ expect(output).toContain('Acme');+ });++ it('flags a scope id the server cannot resolve', async () => {+ scopedTo('ws_typo');+ mockClient.workspace.getById.query.mockResolvedValue(null);++ await run('workspace', 'current');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('did not resolve'));+ });++ // A revoked membership must not turn `workspace current` into a stack trace,+ // but the reason has to survive β a network or auth failure is actionable+ // and must not be reported as a membership problem.+ it('reports the real reason when the workspace is unreachable', async () => {+ scopedTo('ws_1');+ mockClient.workspace.getById.query.mockRejectedValue(new Error('fetch failed'));++ await run('workspace', 'current');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('fetch failed'));+ });+ });+});diff --git a/apps/cli/src/commands/workspace.ts b/apps/cli/src/commands/workspace.tsnew file mode 100644index 00000000000..7ca5438f14b--- /dev/null+++ b/apps/cli/src/commands/workspace.ts@@ -0,0 +1,526 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../api/client';+import { resolveWorkspaceScope, type WorkspaceScope } from '../api/workspace';+import { resolveIdentityFingerprint } from '../auth/identity';+import { CLI_PRIMARY_BIN } from '../constants/identity';+import { type ActiveWorkspaceRecord, resolveServerUrl, saveActiveWorkspace } from '../settings';+import { formatCost, outputJson, printTable, timeAgo, timeUntil, truncate } from '../utils/format';+import { log } from '../utils/logger';++interface WorkspaceRow {+ id: string;+ lockedOut?: boolean;+ name: string;+ plan?: string;+ role?: string | null;+ slug: string;+ updatedAt?: Date | string;+}++const SCOPE_HINTS: Record<WorkspaceScope['source'], string> = {+ env: 'LOBEHUB_WORKSPACE_ID',+ explicit: '--workspace',+ personal: 'personal (no workspace scope)',+ settings: `${CLI_PRIMARY_BIN} workspace use`,+ stale: 'personal (saved scope ignored β see the warning above)',+};++const describeScope = (scope: WorkspaceScope): string =>+ scope.workspaceId+ ? `workspace ${scope.workspaceId} ${pc.dim(`(from ${SCOPE_HINTS[scope.source]})`)}`+ : pc.dim(SCOPE_HINTS[scope.source === 'stale' ? 'stale' : 'personal']);++/**+ * Every workspace-scoped read goes through the workspace header, so a command+ * that forgets `--workspace` while the CLI sits in personal scope silently+ * queries the wrong tenant. Fail loudly instead, and say how to fix it.+ */+const requireScope = (explicit?: string): string => {+ const scope = resolveWorkspaceScope(explicit);+ if (scope.workspaceId) return scope.workspaceId;++ log.error(+ `No workspace scope. Pass --workspace <id>, or run '${CLI_PRIMARY_BIN} workspace use <id|slug>' first.`,+ );+ process.exit(1);+};++/**+ * `LOBEHUB_WORKSPACE_ID` outranks the persisted scope, so writing the file+ * changes nothing until it is unset. Saying so is the difference between the+ * user believing they switched and their next mutation hitting another tenant.+ */+const warnIfEnvOverridesPersistedScope = (): void => {+ const fromEnv = process.env.LOBEHUB_WORKSPACE_ID;+ if (!fromEnv) return;++ log.warn(+ `LOBEHUB_WORKSPACE_ID=${fromEnv} is set and takes precedence β commands keep running against that workspace until you unset it.`,+ );+};++/**+ * Bind the scope to the account and server it was chosen under, so it stops+ * applying the moment either changes rather than silently targeting a tenant+ * the current identity has no membership in.+ */+const persistScope = (workspaceId: string): void => {+ const identity = resolveIdentityFingerprint();+ if (!identity) {+ // API-key mode has no local account identity to bind to, so there is no way+ // to tell later whether the saved scope still belongs to the caller.+ log.error(+ `Cannot save a scope for these credentials. Run '${CLI_PRIMARY_BIN} login', or set LOBEHUB_WORKSPACE_ID for this session.`,+ );+ process.exit(1);+ }++ const record: ActiveWorkspaceRecord = { identity, serverUrl: resolveServerUrl(), workspaceId };+ saveActiveWorkspace(record);+};++const isForbidden = (error: unknown): boolean =>+ typeof error === 'object' &&+ error !== null &&+ (error as { data?: { code?: string } }).data?.code === 'FORBIDDEN';++const listWorkspaces = async (): Promise<WorkspaceRow[]> => {+ const client = await getTrpcClient();+ return (await client.workspace.list.query()) as WorkspaceRow[];+};++/** Accept either a workspace id or its slug, so `lh workspace use acme` works. */+const findWorkspace = (workspaces: WorkspaceRow[], idOrSlug: string): WorkspaceRow | undefined =>+ workspaces.find((w) => w.id === idOrSlug) ?? workspaces.find((w) => w.slug === idOrSlug);++const planLabel = (workspace: WorkspaceRow): string => {+ if (!workspace.plan) return '-';+ return workspace.lockedOut ? `${workspace.plan} (inactive)` : workspace.plan;+};++export function registerWorkspaceCommand(program: Command) {+ const workspace = program+ .command('workspace')+ .alias('ws')+ .description('Manage workspaces and the workspace scope commands run under');++ // ββ scope βββββββββββββββββββββββββββββββββββββββββββββ++ workspace+ .command('current')+ .description('Show the workspace scope commands currently run under')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string }) => {+ const scope = resolveWorkspaceScope();++ if (options.json !== undefined) {+ return outputJson(+ {+ source: scope.source,+ workspaceId: scope.workspaceId ?? null,+ },+ options.json,+ );+ }++ console.log(`${pc.dim('Scope:')} ${describeScope(scope)}`);+ if (!scope.workspaceId) return;++ // Resolving the name needs a round trip, and a stale/revoked id should+ // read as a warning rather than crash the command.+ try {+ const detail = (await (+ await getTrpcClient(scope.workspaceId)+ ).workspace.getById.query()) as WorkspaceRow | null;+ // The server answers an unknown id with `null` rather than an error, so+ // without this a typo'd scope reports as healthy and every later+ // command fails somewhere else.+ if (detail) console.log(`${pc.dim('Name: ')} ${detail.name} ${pc.dim(detail.slug)}`);+ else log.warn('This workspace id did not resolve β check it with `workspace list`.');+ } catch (error) {+ // A diagnostic command should still print the scope it resolved, but+ // asserting "lost access" would bury auth, network and OSS-endpoint+ // failures behind a wrong explanation β report what actually failed.+ log.warn(+ `Could not load this workspace: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ });++ workspace+ .command('use [workspaceIdOrSlug]')+ .description('Set the workspace scope for subsequent commands')+ .option('--personal', 'Clear the workspace scope and go back to personal content')+ .action(async (idOrSlug: string | undefined, options: { personal?: boolean }) => {+ if (options.personal) {+ saveActiveWorkspace(null);+ console.log(`Scope set to ${pc.bold('personal')}.`);+ warnIfEnvOverridesPersistedScope();+ return;+ }++ if (!idOrSlug) {+ log.error('Provide a workspace id or slug, or pass --personal.');+ process.exit(1);+ }++ const workspaces = await listWorkspaces();+ const match = findWorkspace(workspaces, idOrSlug);++ if (!match) {+ log.error(`Workspace not found: ${idOrSlug}`);+ if (workspaces.length > 0) {+ console.log(pc.dim('Available:'));+ for (const w of workspaces) console.log(pc.dim(` ${w.id} ${w.slug} ${w.name}`));+ }+ process.exit(1);+ }++ persistScope(match.id);+ console.log(`Scope set to ${pc.bold(match.name)} ${pc.dim(match.id)}.`);++ warnIfEnvOverridesPersistedScope();+ });++ // ββ workspaces ββββββββββββββββββββββββββββββββββββββββ++ workspace+ .command('list')+ .alias('ls')+ .description('List workspaces you belong to')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string }) => {+ const workspaces = await listWorkspaces();+ if (options.json !== undefined) return outputJson(workspaces, options.json);+ if (workspaces.length === 0) return console.log('No workspaces found.');++ // The marker has to follow the same precedence every other command uses,+ // or an env-set scope silently stars the wrong row.+ const activeId = resolveWorkspaceScope().workspaceId;+ printTable(+ workspaces.map((w) => [+ w.id === activeId ? `${pc.green('*')} ${w.id}` : ` ${w.id}`,+ truncate(w.name, 30),+ w.slug,+ w.role ?? '-',+ planLabel(w),+ w.updatedAt ? timeAgo(w.updatedAt) : '-',+ ]),+ ['ID', 'NAME', 'SLUG', 'ROLE', 'PLAN', 'UPDATED'],+ );+ });++ workspace+ .command('view [workspaceId]')+ .description('View workspace detail (defaults to the active scope)')+ .option('--json [fields]', 'Output JSON')+ .action(async (workspaceId: string | undefined, options: { json?: boolean | string }) => {+ const scopeId = requireScope(workspaceId);+ const client = await getTrpcClient(scopeId);+ const detail = (await client.workspace.getById.query()) as WorkspaceRow | null;++ if (!detail) {+ log.error(`Workspace not found: ${scopeId}`);+ process.exit(1);+ }++ if (options.json !== undefined) return outputJson(detail, options.json);++ const row = detail as WorkspaceRow & { description?: string | null; frozen?: boolean };+ console.log(`\n${pc.bold(row.name)} ${pc.dim(row.id)}`);+ console.log(`${pc.dim('Slug:')} ${row.slug}`);+ if (row.description) console.log(`${pc.dim('About:')} ${row.description}`);+ if (row.frozen) console.log(pc.yellow('This workspace is frozen (read-only).'));+ });++ workspace+ .command('create <name>')+ .description('Create a workspace')+ .requiredOption('-s, --slug <slug>', 'URL slug, unique across LobeHub')+ .option('-d, --description <description>', 'Description')+ .option('--avatar <avatar>', 'Avatar URL or emoji')+ .option('--use', 'Switch the CLI scope to the new workspace')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (+ name: string,+ options: {+ avatar?: string;+ description?: string;+ json?: boolean | string;+ slug: string;+ use?: boolean;+ },+ ) => {+ const client = await getTrpcClient();+ const created = (await client.workspace.create.mutate({+ avatar: options.avatar,+ description: options.description,+ name,+ slug: options.slug,+ })) as WorkspaceRow;++ if (options.use) persistScope(created.id);++ if (options.json !== undefined) return outputJson(created, options.json);+ console.log(`Created ${pc.bold(created.name)} ${pc.dim(created.id)}`);+ if (options.use) {+ console.log(`Scope set to ${pc.bold(created.name)}.`);+ warnIfEnvOverridesPersistedScope();+ }+ },+ );++ workspace+ .command('update')+ .description('Update workspace profile (admin or higher)')+ .option('-w, --workspace <id>', 'Workspace to update (defaults to the active scope)')+ .option('-n, --name <name>', 'Display name')+ .option('-s, --slug <slug>', 'URL slug')+ .option('-d, --description <description>', 'Description')+ .option('--avatar <avatar>', 'Avatar URL or emoji')+ .action(+ async (options: {+ avatar?: string;+ description?: string;+ name?: string;+ slug?: string;+ workspace?: string;+ }) => {+ const patch = {+ avatar: options.avatar,+ description: options.description,+ name: options.name,+ slug: options.slug,+ };++ if (Object.values(patch).every((value) => value === undefined)) {+ log.error('Nothing to update. Pass at least one of --name / --slug / --description.');+ process.exit(1);+ }++ const scopeId = requireScope(options.workspace);+ await (await getTrpcClient(scopeId)).workspace.update.mutate(patch);+ console.log('Workspace updated.');+ },+ );++ workspace+ .command('settings')+ .description('Show the workspace settings blob')+ .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string; workspace?: string }) => {+ const scopeId = requireScope(options.workspace);+ const settings = await (await getTrpcClient(scopeId)).workspace.getSettings.query();+ if (options.json !== undefined) return outputJson(settings, options.json);+ console.log(JSON.stringify(settings ?? {}, null, 2));+ });++ workspace+ .command('stats')+ .description('Show workspace-wide content statistics (admin or higher)')+ .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')+ .option('--mine', 'Count only content you created β available to every member')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string; mine?: boolean; workspace?: string }) => {+ const scopeId = requireScope(options.workspace);+ const client = await getTrpcClient(scopeId);+ const input = { todayStartAt: new Date(new Date().setHours(0, 0, 0, 0)).toISOString() };+ // Workspace-wide totals are Admin-or-higher; members and viewers hit a bare+ // FORBIDDEN, so point them at the query that was built for them.+ const stats = options.mine+ ? await client.workspace.getMyStatistics.query(input)+ : await client.workspace.getStatistics.query(input).catch((error: unknown) => {+ if (isForbidden(error)) {+ log.error('Workspace-wide statistics need admin access β rerun with --mine.');+ process.exit(1);+ }+ throw error;+ });++ if (options.json !== undefined) return outputJson(stats, options.json);+ if (!stats) return console.log('No statistics available.');++ console.log(`${pc.dim('Agents: ')} ${stats.agents}`);+ console.log(`${pc.dim('Topics: ')} ${stats.topics}`);+ console.log(+ `${pc.dim('Messages:')} ${stats.messages} ${pc.dim(`(+${stats.messagesToday} today)`)}`,+ );+ });++ workspace+ .command('usage')+ .description('Show workspace credit usage for the current billing window')+ .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')+ .option('--since <date>', 'Window start (ISO date)')+ .option('--until <date>', 'Window end (ISO date)')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (options: {+ json?: boolean | string;+ since?: string;+ until?: string;+ workspace?: string;+ }) => {+ const scopeId = requireScope(options.workspace);+ const usage = await (+ await getTrpcClient(scopeId)+ ).workspaceUsage.getCurrentUsage.query({ since: options.since, until: options.until });++ if (options.json !== undefined) return outputJson(usage, options.json);++ const window =+ usage.since && usage.until+ ? `${usage.since.slice(0, 10)} β ${usage.until.slice(0, 10)}`+ : 'current cycle';+ console.log(`${pc.dim('Window: ')} ${window}`);+ console.log(`${pc.dim('Balance: ')} ${formatCost(usage.remainingBalance)}`);++ if (usage.usageByType.length === 0) return console.log('No spend recorded in this window.');+ printTable(+ usage.usageByType.map((row) => [row.type, formatCost(row.spend)]),+ ['TYPE', 'SPEND'],+ );+ },+ );++ // ββ members βββββββββββββββββββββββββββββββββββββββββββ++ workspace+ .command('members')+ .description('List workspace members')+ .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string; workspace?: string }) => {+ const scopeId = requireScope(options.workspace);+ const members = await (await getTrpcClient(scopeId)).workspaceMember.list.query({});++ if (options.json !== undefined) return outputJson(members, options.json);+ if (members.length === 0) return console.log('No members found.');++ printTable(+ members.map((m) => [+ m.userId,+ truncate(m.user?.fullName || m.user?.username || '-', 24),+ m.user?.email ?? '-',+ m.role,+ timeAgo(m.joinedAt),+ ]),+ ['USER ID', 'NAME', 'EMAIL', 'ROLE', 'JOINED'],+ );+ });++ workspace+ .command('invite <email>')+ .description('Invite a member by email (admin or higher)')+ .option('-w, --workspace <id>', 'Workspace to invite into (defaults to the active scope)')+ .option('-r, --role <role>', 'Role to grant: admin | member | viewer', 'member')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (+ email: string,+ options: { json?: boolean | string; role: string; workspace?: string },+ ) => {+ const roles = ['admin', 'member', 'viewer'] as const;+ const role = roles.find((r) => r === options.role);+ if (!role) {+ log.error(`Invalid role: ${options.role}. Expected one of ${roles.join(', ')}.`);+ process.exit(1);+ }++ const scopeId = requireScope(options.workspace);+ const invitation = await (+ await getTrpcClient(scopeId)+ ).workspaceMember.invite.mutate({ email, role });++ if (options.json !== undefined) return outputJson(invitation, options.json);+ console.log(`Invited ${pc.bold(email)} as ${role}.`);+ },+ );++ workspace+ .command('invitations')+ .description('List pending invitations (admin or higher)')+ .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string; workspace?: string }) => {+ const scopeId = requireScope(options.workspace);+ const invitations = await (+ await getTrpcClient(scopeId)+ ).workspaceMember.listInvitations.query();++ if (options.json !== undefined) return outputJson(invitations, options.json);+ if (invitations.length === 0) return console.log('No pending invitations.');++ printTable(+ invitations.map((i) => [+ i.id,+ i.email ?? pc.dim('(link only)'),+ i.role,+ i.status,+ timeUntil(i.expiresAt),+ ]),+ ['ID', 'EMAIL', 'ROLE', 'STATUS', 'EXPIRES'],+ );+ });++ // ββ audit log βββββββββββββββββββββββββββββββββββββββββ++ workspace+ .command('audit-log')+ .description('List workspace audit-log entries (admin or higher, Business plan)')+ .option('-w, --workspace <id>', 'Workspace to read (defaults to the active scope)')+ .option('--action <action>', 'Filter by action, for example workspace.updated')+ .option('--resource-type <type>', 'Filter by resource type')+ .option('-q, --query <text>', 'Free-text search')+ .option('--start <date>', 'Only entries at or after this ISO date')+ .option('--end <date>', 'Only entries at or before this ISO date')+ .option('-L, --limit <n>', 'Maximum rows', '30')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (options: {+ action?: string;+ end?: string;+ json?: boolean | string;+ limit: string;+ query?: string;+ resourceType?: string;+ start?: string;+ workspace?: string;+ }) => {+ const limit = Number.parseInt(options.limit, 10);+ if (!Number.isFinite(limit) || limit < 1) {+ log.error(`Invalid --limit: ${options.limit}`);+ process.exit(1);+ }++ const scopeId = requireScope(options.workspace);+ const result = await (+ await getTrpcClient(scopeId)+ ).workspaceAuditLog.list.query({+ action: options.action,+ endDate: options.end,+ limit,+ q: options.query,+ resourceType: options.resourceType,+ startDate: options.start,+ });++ if (options.json !== undefined) return outputJson(result, options.json);+ if (result.items.length === 0) return console.log('No audit-log entries found.');++ printTable(+ result.items.map((item) => [+ timeAgo(item.createdAt),+ item.action,+ item.resourceType ?? '-',+ item.userId ?? '-',+ ]),+ ['WHEN', 'ACTION', 'RESOURCE', 'USER'],+ );+ },+ );+}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 059971eb9bc..b372209241c 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -38,6 +38,7 @@ import { registerUpdateCommand } from './commands/update';import { registerUserCommand } from './commands/user';import { registerVerifyCommand } from './commands/verify';import { registerAcceptanceCommands } from './commands/verifyAcceptance';+import { registerWorkspaceCommand } from './commands/workspace';import { CLI_DISPLAY_NAME, CLI_PRIMARY_BIN, CLI_PRODUCT_NAME } from './constants/identity';import { cliVersion } from './pkg';import { executeToolCall } from './tools';@@ -102,6 +103,7 @@ export function createProgram() {registerProviderCommand(program);registerProjectCommand(program);registerPluginCommand(program);+ registerWorkspaceCommand(program);registerUserCommand(program);registerVerifyCommand(program);// First-class review-loop entry: `lh acceptance list|view|feedback|accept|reject`.diff --git a/apps/cli/src/settings/index.test.ts b/apps/cli/src/settings/index.test.tsindex 6666c76d0c0..260b728e71a 100644--- a/apps/cli/src/settings/index.test.ts+++ b/apps/cli/src/settings/index.test.ts@@ -4,17 +4,22 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { resolveCliDirName } from '../constants/identity';import { log } from '../utils/logger';import {+ loadActiveWorkspace,loadOrCreateConnectionId,loadSettings,normalizeUrl,resolveServerUrl,+ saveActiveWorkspace,saveSettings,} from './index';const tmpDir = path.join(os.tmpdir(), 'lobehub-cli-test-settings');-const settingsDir = path.join(tmpDir, '.lobehub');+// The shared test setup redirects the CLI home via `LOBEHUB_CLI_HOME`, so the+// directory under the stubbed homedir is not the default `.lobehub`.+const settingsDir = path.join(tmpDir, resolveCliDirName());const settingsFile = path.join(settingsDir, 'settings.json');const originalServer = process.env.LOBEHUB_SERVER;@@ -92,6 +97,44 @@ describe('settings', () => {expect(resolveServerUrl()).toBe('https://app.lobehub.com');});+ it('should persist the active workspace and clear it back to personal', () => {+ const record = {+ identity: 'user:u1',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_abc123',+ };+ saveActiveWorkspace(record);++ expect(loadActiveWorkspace()).toEqual(record);+ // Kept out of settings.json, which is unlinked whenever all URLs default.+ expect(fs.existsSync(path.join(settingsDir, 'active-workspace'))).toBe(true);++ saveActiveWorkspace(null);++ expect(loadActiveWorkspace()).toBeUndefined();+ expect(fs.existsSync(path.join(settingsDir, 'active-workspace'))).toBe(false);+ });++ it('should ignore a corrupt active-workspace file instead of scoping to garbage', () => {+ fs.mkdirSync(settingsDir, { recursive: true });+ fs.writeFileSync(path.join(settingsDir, 'active-workspace'), 'not an id\n{"a":1}');++ expect(loadActiveWorkspace()).toBeUndefined();+ });++ // A record without the account/server it was chosen under cannot be checked+ // for staleness, so it must not be trusted.+ it.each([+ ['a missing identity', { serverUrl: 'https://app.lobehub.com', workspaceId: 'ws_1' }],+ ['a missing serverUrl', { identity: 'user:u1', workspaceId: 'ws_1' }],+ ['an id-shaped nothing', { identity: 'user:u1', serverUrl: 'https://x', workspaceId: 'a b' }],+ ])('should reject an active-workspace record with %s', (_label, record) => {+ fs.mkdirSync(settingsDir, { recursive: true });+ fs.writeFileSync(path.join(settingsDir, 'active-workspace'), JSON.stringify(record));++ expect(loadActiveWorkspace()).toBeUndefined();+ });+it('should create a connectionId once and reuse it across calls', () => {const first = loadOrCreateConnectionId();expect(first).toMatch(/[\da-f-]{36}/);diff --git a/apps/cli/src/settings/index.ts b/apps/cli/src/settings/index.tsindex 5b150d61340..acba192fcb1 100644--- a/apps/cli/src/settings/index.ts+++ b/apps/cli/src/settings/index.ts@@ -23,6 +23,11 @@ const CONNECTION_ID_FILE = path.join(SETTINGS_DIR, 'connection-id');// `enrollWorkspace` RPC. Persisted so a daemon/process restart can re-open the// workspace share connections without the user re-sharing from the web UI.const WORKSPACE_ENROLLMENTS_FILE = path.join(SETTINGS_DIR, 'workspace-enrollments.json');+// The workspace scope every command runs under, set by `lh workspace use`. Kept+// out of settings.json for the same reason as connection-id: that file is+// unlinked whenever all URLs are default, which would silently drop the scope.+const ACTIVE_WORKSPACE_FILE = path.join(SETTINGS_DIR, 'active-workspace');+const WORKSPACE_ID_PATTERN = /^[\w-]{1,64}$/;export function normalizeUrl(url: string | undefined): string | undefined {return url ? url.replace(/\/$/, '') : undefined;@@ -133,6 +138,59 @@ export function removeWorkspaceEnrollment(workspaceId: string): void {saveWorkspaceEnrollments(current.filter((id) => id !== workspaceId));}+/**+ * The workspace scope persisted by `lh workspace use`, together with the server+ * and account it was chosen under.+ *+ * The binding is the point: a bare workspace id survives `logout`, a login as a+ * different account, and a `--server` switch, and would then attach an+ * `X-Workspace-Id` the new identity has no membership in β which cloud's compat+ * middleware silently downgrades to personal scope, so writes land on personal+ * data while the CLI still claims to be in a workspace.+ */+export interface ActiveWorkspaceRecord {+ /** Opaque fingerprint of the credentials the scope was chosen under. */+ identity: string;+ serverUrl: string;+ workspaceId: string;+}++export function loadActiveWorkspace(): ActiveWorkspaceRecord | undefined {+ try {+ const parsed: unknown = JSON.parse(fs.readFileSync(ACTIVE_WORKSPACE_FILE, 'utf8'));+ if (!parsed || typeof parsed !== 'object') return undefined;++ const { identity, serverUrl, workspaceId } = parsed as Record<string, unknown>;+ // A garbage value would be sent as `X-Workspace-Id` on every request and+ // fail each one with an opaque server error, so anything that isn't+ // id-shaped is treated as a corrupt file and ignored.+ if (typeof workspaceId !== 'string' || !WORKSPACE_ID_PATTERN.test(workspaceId))+ return undefined;+ if (typeof identity !== 'string' || !identity) return undefined;+ if (typeof serverUrl !== 'string' || !serverUrl) return undefined;++ return { identity, serverUrl, workspaceId };+ } catch {+ // not yet created, unreadable, or not JSON β personal scope+ return undefined;+ }+}++/** Persist the active workspace scope; pass `null` to fall back to personal. */+export function saveActiveWorkspace(record: ActiveWorkspaceRecord | null): void {+ if (!record) {+ try {+ fs.unlinkSync(ACTIVE_WORKSPACE_FILE);+ } catch (error) {+ log.debug('No active workspace file to remove', error);+ }+ return;+ }++ fs.mkdirSync(SETTINGS_DIR, { mode: 0o700, recursive: true });+ fs.writeFileSync(ACTIVE_WORKSPACE_FILE, JSON.stringify(record, null, 2), { mode: 0o600 });+}+export function loadSettings(): StoredSettings | null {if (!fs.existsSync(SETTINGS_FILE)) return null;diff --git a/apps/cli/src/utils/format.test.ts b/apps/cli/src/utils/format.test.tsindex a0092e0b8d7..29e8b4b2d6e 100644--- a/apps/cli/src/utils/format.test.ts+++ b/apps/cli/src/utils/format.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';-import { formatCost, formatNumber, outputJson, printBoxTable } from './format';+import { formatCost, formatNumber, outputJson, printBoxTable, timeUntil } from './format';describe('formatNumber', () => {it('should format numbers with commas', () => {@@ -164,3 +164,20 @@ describe('printBoxTable', () => {vi.restoreAllMocks();});});++describe('timeUntil', () => {+ // `timeAgo` only formats the past; an invitation expiry is in the future and+ // rendered "-604800s ago" through it.+ it('counts down to a future deadline', () => {+ expect(timeUntil(new Date(Date.now() + 3 * 86_400_000 + 60_000))).toBe('in 3d');+ expect(timeUntil(new Date(Date.now() + 90 * 60_000 + 1000))).toBe('in 1h');+ });++ it('reads a past deadline as expired', () => {+ expect(timeUntil(new Date(Date.now() - 1000))).toBe('expired');+ });++ it('degrades an unparseable date to a placeholder', () => {+ expect(timeUntil('not a date')).toBe('-');+ });+});diff --git a/apps/cli/src/utils/format.ts b/apps/cli/src/utils/format.tsindex 1c2e52abe91..024cefcde33 100644--- a/apps/cli/src/utils/format.ts+++ b/apps/cli/src/utils/format.ts@@ -15,6 +15,27 @@ export function timeAgo(date: Date | string): string {return `${seconds}s ago`;}+/**+ * Counterpart to `timeAgo` for deadlines. `timeAgo` only formats the past, so+ * feeding it a future timestamp (an invitation expiry, a lease) renders a+ * negative "-604800s ago".+ */+export function timeUntil(date: Date | string): string {+ const diff = new Date(date).getTime() - Date.now();+ if (Number.isNaN(diff)) return '-';+ if (diff <= 0) return 'expired';++ const seconds = Math.floor(diff / 1000);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);++ if (days > 0) return `in ${days}d`;+ if (hours > 0) return `in ${hours}h`;+ if (minutes > 0) return `in ${minutes}m`;+ return `in ${seconds}s`;+}+export function truncate(str: string, maxWidth: number): string {let width = 0;let i = 0;diff --git a/packages/business-server/package.json b/packages/business-server/package.jsonindex 68752cc8fb7..20eac9594b8 100644--- a/packages/business-server/package.json+++ b/packages/business-server/package.json@@ -7,6 +7,7 @@},"dependencies": {"@lobechat/agent-gateway-client": "workspace:*",+ "@lobechat/business-const": "workspace:*","@lobechat/database": "workspace:*","@lobechat/model-runtime": "workspace:*","@lobechat/trpc": "workspace:*",diff --git a/packages/business-server/src/lambda-routers/workspace.ts b/packages/business-server/src/lambda-routers/workspace.tsindex a40e6324b18..2b1fbf5a048 100644--- a/packages/business-server/src/lambda-routers/workspace.ts+++ b/packages/business-server/src/lambda-routers/workspace.ts@@ -1,13 +1,77 @@+import {+ isWorkspaceSlugFormatValid,+ WORKSPACE_SLUG_MAX,+ WORKSPACE_SLUG_MIN,+} from '@lobechat/business-const';+import type { WorkspaceItem } from '@lobechat/database/schemas';import { TRPCError } from '@trpc/server';import { z } from 'zod';-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import {+ wsAdminProcedure,+ wsCompatProcedure,+ wsProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';import { authedProcedure, router } from '@/libs/trpc/lambda';+/**+ * A workspace row as the workspace picker sees it: the stored record plus the+ * caller's membership role and the plan tag cloud derives from subscriptions.+ */+export interface WorkspaceMembershipSummary extends WorkspaceItem {+ lockedOut?: boolean;+ plan?: string;+ role: string | null;+}++export interface WorkspaceStatistics {+ agents: number;+ messages: number;+ messagesToday: number;+ topics: number;+}++// Same shape cloud enforces, so a slug the CLI or UI gets past this stub is+// only ever rejected for the reservations cloud adds on top.+const workspaceSlugSchema = z+ .string()+ .min(WORKSPACE_SLUG_MIN)+ .max(WORKSPACE_SLUG_MAX)+ .refine(isWorkspaceSlugFormatValid, { message: 'invalid-slug' });++const workspaceStatisticsInput = z+ .object({ todayStartAt: z.string().datetime().optional() })+ .optional();++const cloudOnly = (feature: string): never => {+ throw new TRPCError({+ code: 'NOT_IMPLEMENTED',+ message: `${feature} is a cloud-only feature.`,+ });+};+// Cloud overrides this at the same path with the real workspaceRouter backed by cloudDB.-// Only the procedures consumed by submodule (open-source) UI are declared here as-// typed no-op stubs so the contract type-checks; cloud supplies the real implementations.+// Only the procedures consumed by submodule (open-source) UI and by the CLI are declared+// here as typed no-op stubs so the contract type-checks; cloud supplies the real+// implementations. Keep the procedure builders and input schemas aligned with+// `apps/server/src/routers/lambda/workspace.ts` in the cloud repo β the point of a stub+// is to represent that contract, so a looser gate here is a real runtime difference.export const workspaceRouter = router({+ checkSlugAvailable: authedProcedure+ .input(z.object({ slug: z.string().min(WORKSPACE_SLUG_MIN).max(WORKSPACE_SLUG_MAX) }))+ .query((): { available: boolean } => ({ available: false })),++ create: authedProcedure+ .input(+ z.object({+ avatar: z.string().optional(),+ description: z.string().max(1000).optional(),+ name: z.string().min(1).max(255),+ slug: workspaceSlugSchema,+ }),+ )+ .mutation(async (): Promise<WorkspaceItem> => cloudOnly('Workspace creation')),+ensureMarketOrganization: authedProcedure.input(z.object({ autoProvision: z.boolean().optional() }).optional()).mutation(async (): Promise<{ created: boolean; marketAccountId: number }> => {@@ -16,5 +80,33 @@ export const workspaceRouter = router({message: 'Workspace market organization is a cloud-only feature.',});}),- getById: wsCompatProcedure.query(() => null),++ // `wsCompatProcedure` here, unlike cloud's `wsProcedure`, because open-source+ // callers (`buildAppUrl`) reach for it before they know whether a workspace+ // is in scope.+ getById: wsCompatProcedure.query((): WorkspaceItem | null => null),++ getMyStatistics: wsProcedure+ .input(workspaceStatisticsInput)+ .query((): WorkspaceStatistics | null => null),++ getSettings: wsProcedure.query((): Record<string, unknown> => ({})),++ /** Workspace-wide totals across all members β Admin or higher, like cloud. */+ getStatistics: wsAdminProcedure+ .input(workspaceStatisticsInput)+ .query((): WorkspaceStatistics | null => null),++ list: authedProcedure.query(async (): Promise<WorkspaceMembershipSummary[]> => []),++ update: wsAdminProcedure+ .input(+ z.object({+ avatar: z.string().optional(),+ description: z.string().max(1000).optional(),+ name: z.string().min(1).max(255).optional(),+ slug: workspaceSlugSchema.optional(),+ }),+ )+ .mutation(async (): Promise<void> => cloudOnly('Workspace update')),});diff --git a/packages/business-server/src/lambda-routers/workspaceAuditLog.ts b/packages/business-server/src/lambda-routers/workspaceAuditLog.tsindex 1c97cb42067..47cc7193dec 100644--- a/packages/business-server/src/lambda-routers/workspaceAuditLog.ts+++ b/packages/business-server/src/lambda-routers/workspaceAuditLog.ts@@ -1,3 +1,31 @@+import type { WorkspaceAuditLogItem } from '@lobechat/database/schemas';+import { z } from 'zod';++import {+ requireWorkspaceRole,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';import { router } from '@/libs/trpc/lambda';-export const workspaceAuditLogRouter = router({});+// Cloud overrides this at the same path with the real workspaceAuditLogRouter.+export const workspaceAuditLogRouter = router({+ list: wsCompatProcedure+ .use(requireWorkspaceRole('admin'))+ .input(+ z+ .object({+ action: z.string().optional(),+ cursor: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().int().min(1).max(200).optional(),+ q: z.string().optional(),+ resourceType: z.string().optional(),+ startDate: z.string().optional(),+ })+ .optional(),+ )+ .query(async (): Promise<{ items: WorkspaceAuditLogItem[]; nextCursor: string | null }> => ({+ items: [],+ nextCursor: null,+ })),+});diff --git a/packages/business-server/src/lambda-routers/workspaceMember.ts b/packages/business-server/src/lambda-routers/workspaceMember.tsindex c8e03c84c4d..2a878aea5be 100644--- a/packages/business-server/src/lambda-routers/workspaceMember.ts+++ b/packages/business-server/src/lambda-routers/workspaceMember.ts@@ -1,3 +1,49 @@+import type { WorkspaceInvitationItem, WorkspaceMemberItem } from '@lobechat/database/schemas';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import {+ requireWorkspaceRole,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';import { router } from '@/libs/trpc/lambda';-export const workspaceMemberRouter = router({});+/** A membership row joined with the public profile of the member. */+export interface WorkspaceMemberSummary extends WorkspaceMemberItem {+ user: {+ avatar: string | null;+ email: string | null;+ fullName: string | null;+ username: string | null;+ } | null;+}++// Cloud gates these on the compat procedure plus a role check rather than on a+// procedure that requires the header, so an unscoped call reads as empty rather+// than as a bad request. Mirror that here.+const wsCompatAdminProcedure = wsCompatProcedure.use(requireWorkspaceRole('admin'));++// Cloud overrides this at the same path with the real workspaceMemberRouter.+// Only the procedures consumed by submodule (open-source) UI and by the CLI are+// declared here as typed no-op stubs so the contract type-checks.+export const workspaceMemberRouter = router({+ invite: wsCompatAdminProcedure+ .input(+ z.object({+ email: z.string().email().optional(),+ role: z.enum(['admin', 'member', 'viewer']).default('member'),+ }),+ )+ .mutation(async (): Promise<WorkspaceInvitationItem> => {+ throw new TRPCError({+ code: 'NOT_IMPLEMENTED',+ message: 'Workspace invitations are a cloud-only feature.',+ });+ }),++ list: wsCompatProcedure+ .input(z.object({ includeDeleted: z.boolean().optional() }).optional())+ .query(async (): Promise<WorkspaceMemberSummary[]> => []),++ listInvitations: wsCompatAdminProcedure.query(async (): Promise<WorkspaceInvitationItem[]> => []),+});diff --git a/packages/business-server/src/lambda-routers/workspaceUsage.ts b/packages/business-server/src/lambda-routers/workspaceUsage.tsindex 35c832d989d..c6b815d5914 100644--- a/packages/business-server/src/lambda-routers/workspaceUsage.ts+++ b/packages/business-server/src/lambda-routers/workspaceUsage.ts@@ -1,3 +1,25 @@+import { z } from 'zod';++import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { router } from '@/libs/trpc/lambda';-export const workspaceUsageRouter = router({});+export interface WorkspaceCurrentUsage {+ remainingBalance: number;+ since: string | null;+ subscription: { plan?: string; status?: string } | null;+ until: string | null;+ usageByType: { spend: number; type: string }[];+}++// Cloud overrides this at the same path with the real workspaceUsageRouter.+export const workspaceUsageRouter = router({+ getCurrentUsage: wsCompatProcedure+ .input(z.object({ since: z.string().optional(), until: z.string().optional() }).optional())+ .query(async (): Promise<WorkspaceCurrentUsage> => ({+ remainingBalance: 0,+ since: null,+ subscription: null,+ until: null,+ usageByType: [],+ })),+});diff --git a/packages/business/const/src/index.ts b/packages/business/const/src/index.tsindex 2282d422665..ccfecdce3a0 100644--- a/packages/business/const/src/index.ts+++ b/packages/business/const/src/index.ts@@ -3,6 +3,7 @@ import { BRANDING_PROVIDER } from './branding';export * from './branding';export * from './llm';export * from './url';+export * from './workspaceSlug';export const ENABLE_BUSINESS_FEATURES = false;diff --git a/packages/business/const/src/workspaceSlug.ts b/packages/business/const/src/workspaceSlug.tsnew file mode 100644index 00000000000..ed591dd4c7c--- /dev/null+++ b/packages/business/const/src/workspaceSlug.ts@@ -0,0 +1,17 @@+/**+ * Format rules for a workspace slug, mirroring the cloud constants of the same+ * names so the open-source router contract rejects what cloud rejects.+ *+ * Cloud additionally refuses slugs that would shadow a real top-level route+ * (`chat`, `settings`, `api`, β¦) β that reservation list is a deployment+ * concern and lives only in the cloud overlay, so a slug accepted here can+ * still come back as `invalid-slug` from the server.+ */+export const WORKSPACE_SLUG_MIN = 3;+export const WORKSPACE_SLUG_MAX = 32;++export const WORKSPACE_SLUG_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;++/** Format-only check: lowercase alphanumerics and inner hyphens. */+export const isWorkspaceSlugFormatValid = (slug: string): boolean =>+ WORKSPACE_SLUG_PATTERN.test(slug);