refactor(cli): auth/workspace cleanup — record-backed token store (#37219)

Co-authored-by: Yunlu Wen <yunlu.wen@dify.ai>
This commit is contained in:
Xiyuan ChenandYunlu Wen authored and GitHub committed 2026-06-12 03:10:54 +00:00
1 parent 62ee1fff62
commit a650ffc00a
45 files changed
+795 -620

No files matched your search

+5 -5
View File
@@ -2,7 +2,7 @@ import type { ActiveContext } from '@/auth/hosts'
import type { AppInfoCache } from '@/cache/app-info'
import type { Command } from '@/framework/command'
import type { HttpClient } from '@/http/types'
import type { Store } from '@/store/store'
import type { TokenStore } from '@/store/token-store'
import type { IOStreams } from '@/sys/io/streams'
import { META_PROBE_TIMEOUT_MS, MetaClient } from '@/api/meta'
import { notLoggedInError, Registry } from '@/auth/hosts'
@@ -11,7 +11,7 @@ import { loadNudgeStore } from '@/cache/nudge-store'
import { getEnv } from '@/env/registry'
import { formatErrorForCli } from '@/errors/format'
import { createHttpClient } from '@/http/client'
import { getTokenStore, tokenKey } from '@/store/manager'
import { getTokenStore } from '@/store/manager'
import { realStreams } from '@/sys/io/streams'
import { hostWithScheme, openAPIBase } from '@/util/host'
import { versionInfo } from '@/version/info'
@@ -21,7 +21,7 @@ import { resolveRetryAttempts } from './global-flags.js'
export type AuthedContext = {
readonly reg: Registry
readonly active: ActiveContext
readonly store: Store
readonly store: TokenStore
readonly http: HttpClient
readonly host: string
readonly io: IOStreams
@@ -44,8 +44,8 @@ export async function buildAuthedContext(
if (active === undefined)
fail(cmd, opts, io)
const { store } = getTokenStore()
const bearer = store.get(tokenKey(active.host, active.email))
const store = getTokenStore(reg.token_storage)
const bearer = store.read(active.host, active.email)
if (bearer === '')
fail(cmd, opts, io)
@@ -2,43 +2,20 @@ import type { SessionListResponse, SessionRow } from '@dify/contracts/api/openap
import type { DifyMock } from '@test/fixtures/dify-mock/server'
import type { AccountSessionsClient } from '@/api/account-sessions'
import type { ActiveContext } from '@/auth/hosts'
import type { Key, Store } from '@/store/store'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { startMock } from '@test/fixtures/dify-mock/server'
import { testHttpClient } from '@test/fixtures/http-client'
import { MemStore } from '@test/fixtures/mem-store'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Registry } from '@/auth/hosts'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { tokenKey } from '@/store/manager'
import { bufferStreams } from '@/sys/io/streams'
import { listAllSessions, runDevicesList, runDevicesRevoke } from './devices.js'
class MemStore implements Store {
readonly entries = new Map<string, unknown>()
get<T>(key: Key<T>): T {
return (this.entries.get(key.key) as T | undefined) ?? key.default
}
set<T>(key: Key<T>, value: T): void {
this.entries.set(key.key, value)
}
unset<T>(key: Key<T>): void {
this.entries.delete(key.key)
}
}
function buildRegistry(host: string, email: string, tokenId: string): { reg: Registry, active: ActiveContext } {
const reg = Registry.empty('file')
reg.upsert(host, email, {
account: { id: 'acct-1', email, name: 'Test Tester' },
workspace: { id: 'ws-1', name: 'Default', role: 'owner' },
available_workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner' },
{ id: 'ws-2', name: 'Other', role: 'normal' },
],
token_id: tokenId,
})
reg.setHost(host)
@@ -82,28 +59,19 @@ describe('runDevicesList', () => {
describe('runDevicesRevoke', () => {
let mock: DifyMock
let configDir: string
let prevConfigDir: string | undefined
useTempConfigDir('difyctl-devrevoke-')
beforeEach(async () => {
mock = await startMock({ scenario: 'happy' })
configDir = await mkdtemp(join(tmpdir(), 'difyctl-devrevoke-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = configDir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await mock.stop()
await rm(configDir, { recursive: true, force: true })
})
it('exact device_label: revokes one + leaves local creds', async () => {
const io = bufferStreams()
const store = new MemStore()
const { reg, active } = buildRegistry(mock.url, 'tester@dify.ai', 'tok-1')
store.set(tokenKey(mock.url, 'tester@dify.ai'), 'dfoa_test')
store.write(mock.url, 'tester@dify.ai', 'dfoa_test')
reg.save()
const http = testHttpClient(mock.url, 'dfoa_test')
@@ -168,7 +136,7 @@ describe('runDevicesRevoke', () => {
const io = bufferStreams()
const store = new MemStore()
const { reg, active } = buildRegistry(mock.url, 'tester@dify.ai', 'tok-1')
store.set(tokenKey(mock.url, 'tester@dify.ai'), 'dfoa_test')
store.write(mock.url, 'tester@dify.ai', 'dfoa_test')
reg.save()
const http = testHttpClient(mock.url, 'dfoa_test')
@@ -1,7 +1,7 @@
import type { SessionRow } from '@dify/contracts/api/openapi/types.gen'
import type { ActiveContext, Registry } from '@/auth/hosts'
import type { HttpClient } from '@/http/types'
import type { Store } from '@/store/store'
import type { TokenStore } from '@/store/token-store'
import type { IOStreams } from '@/sys/io/streams'
import { AccountSessionsClient } from '@/api/account-sessions'
import { BaseError } from '@/errors/base'
@@ -71,7 +71,7 @@ export type DevicesRevokeOptions = {
readonly io: IOStreams
readonly reg: Registry
readonly active: ActiveContext
readonly store: Store
readonly store: TokenStore
readonly http: HttpClient
readonly target?: string
readonly all: boolean
+8 -35
View File
@@ -1,16 +1,14 @@
import type { DifyMock } from '@test/fixtures/dify-mock/server'
import type { Clock } from './device-flow.js'
import type { Key, Store } from '@/store/store'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { startMock } from '@test/fixtures/dify-mock/server'
import { testHttpClient } from '@test/fixtures/http-client'
import { MemStore } from '@test/fixtures/mem-store'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { DeviceFlowApi } from '@/api/oauth-device'
import { createHttpClient } from '@/http/client'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { tokenKey } from '@/store/manager'
import { bufferStreams } from '@/sys/io/streams'
import { openAPIBase } from '@/util/host'
import { runLogin } from './login.js'
@@ -22,40 +20,16 @@ const noopClock: Clock = {
const noopBrowser = async (): Promise<void> => { /* skip OS open */ }
class MemStore implements Store {
readonly entries = new Map<string, unknown>()
get<T>(key: Key<T>): T {
return (this.entries.get(key.key) as T | undefined) ?? key.default
}
set<T>(key: Key<T>, value: T): void {
this.entries.set(key.key, value)
}
unset<T>(key: Key<T>): void {
this.entries.delete(key.key)
}
}
describe('runLogin', () => {
let mock: DifyMock
let configDir: string
let prevConfigDir: string | undefined
const configDir = useTempConfigDir('difyctl-login-')
beforeEach(async () => {
mock = await startMock({ scenario: 'happy' })
configDir = await mkdtemp(join(tmpdir(), 'difyctl-login-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = configDir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await mock.stop()
await rm(configDir, { recursive: true, force: true })
})
it('happy: stores bearer + writes hosts.yml + greets account user', async () => {
@@ -75,10 +49,9 @@ describe('runLogin', () => {
const active = reg.resolveActive()
expect(active?.ctx.account.email).toBe('tester@dify.ai')
expect(active?.ctx.workspace?.id).toBe('550e8400-e29b-41d4-a716-446655440000')
expect(active?.ctx.available_workspaces).toHaveLength(2)
expect(store.get(tokenKey(active!.host, 'tester@dify.ai'))).toBe('dfoa_test')
expect(store.read(active!.host, 'tester@dify.ai')).toBe('dfoa_test')
const hostsRaw = await readFile(join(configDir, 'hosts.yml'), 'utf8')
const hostsRaw = await readFile(join(configDir(), 'hosts.yml'), 'utf8')
expect(hostsRaw).toContain('current_host:')
expect(hostsRaw).toContain('tester@dify.ai')
expect(hostsRaw).not.toContain('dfoa_test')
@@ -109,7 +82,7 @@ describe('runLogin', () => {
expect(active?.ctx.external_subject?.email).toBe('sso@dify.ai')
expect(active?.ctx.external_subject?.issuer).toBe('https://issuer.example')
expect(active?.ctx.account.email).toBe('')
expect(store.get(tokenKey(active!.host, 'sso@dify.ai'))).toBe('dfoe_test')
expect(store.read(active!.host, 'sso@dify.ai')).toBe('dfoe_test')
expect(io.outBuf()).toContain('external SSO')
expect(io.outBuf()).toContain('sso@dify.ai')
})
@@ -130,7 +103,7 @@ describe('runLogin', () => {
browserOpener: noopBrowser,
})).rejects.toThrow(/denied/)
expect(store.entries.size).toBe(0)
await expect(readFile(join(configDir, 'hosts.yml'), 'utf8')).rejects.toThrow(/ENOENT/)
await expect(readFile(join(configDir(), 'hosts.yml'), 'utf8')).rejects.toThrow(/ENOENT/)
})
it('expired: throws DeviceFlowError', async () => {
+7 -9
View File
@@ -1,7 +1,8 @@
import type { Clock } from './device-flow.js'
import type { CodeResponse, PollSuccess } from '@/api/oauth-device'
import type { AccountContext, Workspace } from '@/auth/hosts'
import type { StorageMode, Store } from '@/store/store'
import type { AccountContext } from '@/auth/hosts'
import type { StorageMode } from '@/store/store'
import type { TokenStore } from '@/store/token-store'
import type { ParseResult } from '@/sys/io/prompt'
import type { IOStreams } from '@/sys/io/streams'
import type { BrowserEnv, BrowserOpener } from '@/util/browser'
@@ -11,7 +12,7 @@ import { Registry } from '@/auth/hosts'
import { BaseError, isBaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { createHttpClient } from '@/http/client'
import { getTokenStore, tokenKey } from '@/store/manager'
import { detectTokenStore } from '@/store/manager'
import { colorEnabled, colorScheme } from '@/sys/io/color'
import { promptText } from '@/sys/io/prompt'
import { startSpinner } from '@/sys/io/spinner'
@@ -25,7 +26,7 @@ export type LoginOptions = {
readonly noBrowser?: boolean
readonly insecure?: boolean
readonly deviceLabel?: string
readonly store?: { readonly store: Store, readonly mode: StorageMode }
readonly store?: { readonly store: TokenStore, readonly mode: StorageMode }
readonly api?: DeviceFlowApi
readonly browserEnv?: BrowserEnv
readonly browserOpener?: BrowserOpener
@@ -69,12 +70,12 @@ export async function runLogin(opts: LoginOptions): Promise<Registry> {
spinner.stop()
}
const storeBundle = opts.store ?? getTokenStore()
const storeBundle = opts.store ?? detectTokenStore()
const display = bareHost(host)
const email = accountEmail(success)
const ctx = contextFromSuccess(success)
storeBundle.store.set(tokenKey(display, email), success.token)
storeBundle.store.write(display, email, success.token)
const reg = Registry.load()
reg.token_storage = storeBundle.mode
@@ -187,9 +188,6 @@ function contextFromSuccess(s: PollSuccess): AccountContext {
const def = findDefaultWorkspace(s)
if (def !== undefined)
ctx.workspace = def
if (s.workspaces !== undefined && s.workspaces.length > 0) {
ctx.available_workspaces = s.workspaces.map<Workspace>(w => ({ id: w.id, name: w.name, role: w.role }))
}
return ctx
}
+6 -2
View File
@@ -3,7 +3,7 @@ import type { HttpClient } from '@/http/types'
import { Registry } from '@/auth/hosts'
import { DifyCommand } from '@/commands/_shared/dify-command'
import { createHttpClient } from '@/http/client'
import { getTokenStore, tokenKey } from '@/store/manager'
import { getTokenStore } from '@/store/manager'
import { runWithSpinner } from '@/sys/io/spinner'
import { realStreams } from '@/sys/io/streams'
import { hostWithScheme, openAPIBase } from '@/util/host'
@@ -26,7 +26,11 @@ export default class Logout extends DifyCommand {
let http: HttpClient | undefined
if (active !== undefined) {
const bearer = getTokenStore().store.get(tokenKey(active.host, active.email))
let bearer = ''
try {
bearer = getTokenStore(reg.token_storage).read(active.host, active.email)
}
catch { /* keyring locked — skip remote revocation, local cleanup still runs */ }
if (bearer !== '') {
http = createHttpClient({ baseURL: openAPIBase(hostWithScheme(active.host, active.scheme)), bearer, retryAttempts: 0 })
}
+21 -30
View File
@@ -1,34 +1,14 @@
import type { Key, Store } from '@/store/store'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { MemStore } from '@test/fixtures/mem-store'
import { describe, expect, it } from 'vitest'
import { Registry } from '@/auth/hosts'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { bufferStreams } from '@/sys/io/streams'
import { runLogout } from './logout.js'
class MemStore implements Store {
readonly entries = new Map<string, unknown>()
get<T>(key: Key<T>): T { return (this.entries.get(key.key) as T | undefined) ?? key.default }
set<T>(key: Key<T>, value: T): void { this.entries.set(key.key, value) }
unset<T>(key: Key<T>): void { this.entries.delete(key.key) }
}
describe('runLogout', () => {
let dir: string
let prev: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-logout-'))
prev = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prev === undefined)
delete process.env[ENV_CONFIG_DIR]
else process.env[ENV_CONFIG_DIR] = prev
await rm(dir, { recursive: true, force: true })
})
const dir = useTempConfigDir('difyctl-logout-')
function seed(store: MemStore) {
const reg = Registry.empty('file')
@@ -37,8 +17,8 @@ describe('runLogout', () => {
reg.setHost('h1')
reg.setAccount('a@x')
reg.save()
store.set({ key: 'tokens.h1.a@x', default: '' }, 'dfoa_a')
store.set({ key: 'tokens.h1.b@x', default: '' }, 'dfoa_b')
store.write('h1', 'a@x', 'dfoa_a')
store.write('h1', 'b@x', 'dfoa_b')
}
it('removes only the active context, keeps others, unsets pointers, file survives', async () => {
@@ -49,12 +29,23 @@ describe('runLogout', () => {
expect(after?.hosts.h1?.accounts['a@x']).toBeUndefined()
expect(after?.hosts.h1?.accounts['b@x']).toBeDefined()
expect(after?.current_host).toBeUndefined()
expect(store.get({ key: 'tokens.h1.a@x', default: '' })).toBe('')
expect(store.get({ key: 'tokens.h1.b@x', default: '' })).toBe('dfoa_b')
const raw = await readFile(join(dir, 'hosts.yml'), 'utf8')
expect(store.read('h1', 'a@x')).toBe('')
expect(store.read('h1', 'b@x')).toBe('dfoa_b')
const raw = await readFile(join(dir(), 'hosts.yml'), 'utf8')
expect(raw).toContain('b@x')
})
it('clears local credentials even when the store.read throws (e.g. keyring locked)', async () => {
const store = new MemStore()
seed(store)
store.read = () => {
throw new Error('keyring locked')
}
await runLogout({ io: bufferStreams(), reg: Registry.load(), store })
const after = Registry.load()
expect(after?.hosts.h1?.accounts['a@x']).toBeUndefined()
})
it('throws NotLoggedIn when no active context', async () => {
Registry.empty('file').save()
await expect(runLogout({ io: bufferStreams(), reg: Registry.load(), store: new MemStore() }))
+9 -5
View File
@@ -1,9 +1,9 @@
import type { Registry } from '@/auth/hosts'
import type { HttpClient } from '@/http/types'
import type { Store } from '@/store/store'
import type { TokenStore } from '@/store/token-store'
import type { IOStreams } from '@/sys/io/streams'
import { AccountSessionsClient } from '@/api/account-sessions'
import { getTokenStore, tokenKey } from '@/store/manager'
import { getTokenStore } from '@/store/manager'
import { colorEnabled, colorScheme } from '@/sys/io/color'
export type LogoutOptions = {
@@ -11,7 +11,7 @@ export type LogoutOptions = {
readonly reg: Registry
readonly http?: HttpClient
/** Optional override for tests; production resolves via `getTokenStore`. */
readonly store?: Store
readonly store?: TokenStore
}
const REVOCABLE_PREFIXES = ['dfoa_', 'dfoe_'] as const
@@ -21,8 +21,12 @@ export async function runLogout(opts: LogoutOptions): Promise<void> {
const reg = opts.reg
const active = reg.requireActive()
const store = opts.store ?? getTokenStore().store
const bearer = store.get(tokenKey(active.host, active.email))
const store = opts.store ?? getTokenStore(reg.token_storage)
let bearer = ''
try {
bearer = store.read(active.host, active.email)
}
catch { /* keyring locked — skip remote revocation, local cleanup still runs */ }
let revokeWarning = ''
if (bearer !== '' && revokeAllowed(bearer) && opts.http !== undefined) {
+3 -21
View File
@@ -1,30 +1,12 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { describe, expect, it } from 'vitest'
import { isBaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { getConfigurationStore } from '@/store/manager'
import { runConfigGet } from './run'
describe('runConfigGet', () => {
let dir: string
let prevConfigDir: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-get-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await rm(dir, { recursive: true, force: true })
})
useTempConfigDir('difyctl-get-')
it('returns set value with trailing newline', () => {
getConfigurationStore().setTyped({
+3 -21
View File
@@ -1,31 +1,13 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { describe, expect, it } from 'vitest'
import { loadConfig } from '@/config/config-loader'
import { isBaseError } from '@/errors/base'
import { ErrorCode, ExitCode } from '@/errors/codes'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { getConfigurationStore } from '@/store/manager'
import { runConfigSet } from './run'
describe('runConfigSet', () => {
let dir: string
let prevConfigDir: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-set-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await rm(dir, { recursive: true, force: true })
})
useTempConfigDir('difyctl-set-')
it('persists the value and returns "set k = v\\n"', () => {
const out = runConfigSet({ store: getConfigurationStore(), key: 'defaults.format', value: 'json' })
+3 -21
View File
@@ -1,31 +1,13 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { describe, expect, it } from 'vitest'
import { loadConfig } from '@/config/config-loader'
import { isBaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { getConfigurationStore } from '@/store/manager'
import { runConfigUnset } from './run'
describe('runConfigUnset', () => {
let dir: string
let prevConfigDir: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-unset-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await rm(dir, { recursive: true, force: true })
})
useTempConfigDir('difyctl-unset-')
it('clears the requested key, leaves others intact', () => {
getConfigurationStore().setTyped({
+3 -21
View File
@@ -1,28 +1,10 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { describe, expect, it } from 'vitest'
import { getConfigurationStore } from '@/store/manager'
import { runConfigView } from './run'
describe('runConfigView', () => {
let dir: string
let prevConfigDir: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-view-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await rm(dir, { recursive: true, force: true })
})
useTempConfigDir('difyctl-view-')
it('text format: empty config returns empty string', () => {
const out = runConfigView({ store: getConfigurationStore() })
@@ -11,7 +11,6 @@ function active(): ActiveContext {
ctx: {
account: { id: 'acct-1', email: 'inviter@example.com', name: 'Inviter' },
workspace: { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
available_workspaces: [{ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' }],
},
}
}
@@ -11,7 +11,6 @@ function active(): ActiveContext {
ctx: {
account: { id: 'acct-1', email: 'me@example.com', name: 'Me' },
workspace: { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
available_workspaces: [{ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' }],
},
}
}
+1 -5
View File
@@ -19,10 +19,6 @@ function active(): ActiveContext {
ctx: {
account: { id: 'acct-1', email: 't@d.ai', name: 'T' },
workspace: { id: 'ws-1', name: 'Default', role: 'owner' },
available_workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner' },
{ id: 'ws-2', name: 'Other', role: 'normal' },
],
},
}
}
@@ -71,7 +67,7 @@ describe('runDescribeApp', () => {
})
it('text: agent app shows Agent: true', async () => {
const out = await render({ appId: 'app-4', workspace: 'ws-2' })
const out = await render({ appId: 'app-4', workspace: '00000000-0000-0000-0000-000000000002' })
expect(out).toContain('Agent:')
expect(out).toContain('true')
})
+3 -2
View File
@@ -9,13 +9,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { bufferStreams } from '@/sys/io/streams'
import { runExportApp } from './run.js'
const WS_ID = 'aaaaaaaa-0000-0000-0000-000000000001'
const baseActive: ActiveContext = {
host: '127.0.0.1',
email: 'tester@dify.ai',
ctx: {
account: { id: 'acct-1', email: 'tester@dify.ai', name: 'Test Tester' },
workspace: { id: 'ws-1', name: 'Default', role: 'owner' },
available_workspaces: [{ id: 'ws-1', name: 'Default', role: 'owner' }],
workspace: { id: WS_ID, name: 'Default', role: 'owner' },
},
scheme: 'http',
}
-4
View File
@@ -13,10 +13,6 @@ const baseActive: ActiveContext = {
ctx: {
account: { id: 'acct-1', email: 'tester@dify.ai', name: 'Test Tester' },
workspace: { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
available_workspaces: [
{ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
{ id: '550e8400-e29b-41d4-a716-446655440001', name: 'Other', role: 'normal' },
],
},
scheme: 'http',
}
+1 -8
View File
@@ -114,14 +114,7 @@ function describeToEnvelope(desc: AppDescribeResponse, wsId: string, wsName: str
function workspaceNameForId(active: ActiveContext, id: string): string {
if (id === '')
return ''
const ctx = active.ctx
if (ctx.workspace?.id === id)
return ctx.workspace.name
for (const w of ctx.available_workspaces ?? []) {
if (w.id === id)
return w.name
}
return ''
return active.ctx.workspace?.id === id ? active.ctx.workspace.name : ''
}
async function runAllWorkspaces(
-1
View File
@@ -12,7 +12,6 @@ function active(): ActiveContext {
ctx: {
account: { id: 'acct-1', email: 'me@example.com', name: 'Me' },
workspace: { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
available_workspaces: [{ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' }],
},
}
}
@@ -6,7 +6,7 @@ function env(): WorkspaceListResponse {
return {
workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner', status: 'normal', current: true },
{ id: 'ws-2', name: 'Other', role: 'normal', status: 'normal', current: false },
{ id: '00000000-0000-0000-0000-000000000002', name: 'Other', role: 'normal', status: 'normal', current: false },
],
}
}
@@ -13,10 +13,6 @@ const baseActive: ActiveContext = {
ctx: {
account: { id: 'acct-1', email: 'tester@dify.ai', name: 'Test Tester' },
workspace: { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
available_workspaces: [
{ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
{ id: '550e8400-e29b-41d4-a716-446655440001', name: 'Other', role: 'normal' },
],
},
scheme: 'http',
}
+3 -2
View File
@@ -13,13 +13,14 @@ import { bufferStreams } from '@/sys/io/streams'
import { ZERO } from '@/util/uuid.js'
import { pluginDependencyLabel, runImportApp } from './run.js'
const WS_ID = 'aaaaaaaa-0000-0000-0000-000000000001'
const baseActive: ActiveContext = {
host: '127.0.0.1',
email: 'tester@dify.ai',
ctx: {
account: { id: 'acct-1', email: 'tester@dify.ai', name: 'Test Tester' },
workspace: { id: 'ws-1', name: 'Default', role: 'owner' },
available_workspaces: [{ id: 'ws-1', name: 'Default', role: 'owner' }],
workspace: { id: WS_ID, name: 'Default', role: 'owner' },
},
scheme: 'http',
}
+2 -6
View File
@@ -20,10 +20,6 @@ function active(): ActiveContext {
ctx: {
account: { id: 'acct-1', email: 't@d.ai', name: 'T' },
workspace: { id: 'ws-1', name: 'Default', role: 'owner' },
available_workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner' },
{ id: 'ws-2', name: 'Other', role: 'normal' },
],
},
}
}
@@ -139,7 +135,7 @@ describe('runApp', () => {
const io = bufferStreams()
const cache = await loadAppInfoCache({ store: getCache(CACHE_APP_INFO) })
await runApp(
{ appId: 'app-4', workspace: 'ws-2', message: 'do research' },
{ appId: 'app-4', workspace: '00000000-0000-0000-0000-000000000002', message: 'do research' },
{ active: active(), http: testHttpClient(mock.url, 'dfoa_test'), host: mock.url, io, cache },
)
expect(io.outBuf()).toContain('do research')
@@ -150,7 +146,7 @@ describe('runApp', () => {
const io = bufferStreams()
const cache = await loadAppInfoCache({ store: getCache(CACHE_APP_INFO) })
await runApp(
{ appId: 'app-4', workspace: 'ws-2', message: 'go', stream: true },
{ appId: 'app-4', workspace: '00000000-0000-0000-0000-000000000002', message: 'go', stream: true },
{ active: active(), http: testHttpClient(mock.url, 'dfoa_test'), host: mock.url, io, cache },
)
expect(io.outBuf()).toContain('go')
-1
View File
@@ -11,7 +11,6 @@ function active(): ActiveContext {
ctx: {
account: { id: 'acct-1', email: 'me@example.com', name: 'Me' },
workspace: { id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' },
available_workspaces: [{ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Default', role: 'owner' }],
},
}
}
@@ -1,29 +1,13 @@
import type { Key, Store } from '@/store/store'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { MemStore } from '@test/fixtures/mem-store'
import { beforeEach, describe, expect, it } from 'vitest'
import { Registry } from '@/auth/hosts'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { bufferStreams } from '@/sys/io/streams'
import { runUseAccount } from './use-account'
function memStore(seed: Record<string, string>): Store {
const m = new Map<string, unknown>(Object.entries(seed))
return {
get<T>(k: Key<T>): T { return (m.get(k.key) as T | undefined) ?? k.default },
set<T>(k: Key<T>, v: T): void { m.set(k.key, v) },
unset<T>(k: Key<T>): void { m.delete(k.key) },
}
}
describe('runUseAccount', () => {
let dir: string
let prev: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-useacct-'))
prev = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
useTempConfigDir('difyctl-useacct-')
beforeEach(() => {
const reg = Registry.empty('file')
reg.upsert('h1', 'a@x', { account: { id: '1', email: 'a@x', name: 'A' } })
reg.upsert('h1', 'b@x', { account: { id: '2', email: 'b@x', name: 'B' } })
@@ -31,26 +15,20 @@ describe('runUseAccount', () => {
reg.setAccount('a@x')
reg.save()
})
afterEach(async () => {
if (prev === undefined)
delete process.env[ENV_CONFIG_DIR]
else process.env[ENV_CONFIG_DIR] = prev
await rm(dir, { recursive: true, force: true })
})
it('switches current_account when email valid + token present', async () => {
await runUseAccount({ io: bufferStreams(), email: 'b@x', store: memStore({ 'tokens.h1.b@x': 'dfoa_b' }) })
await runUseAccount({ io: bufferStreams(), email: 'b@x', store: new MemStore({ 'h1 b@x': 'dfoa_b' }) })
expect(Registry.load().hosts.h1?.current_account).toBe('b@x')
})
it('errors when the account has no stored token', async () => {
await expect(runUseAccount({ io: bufferStreams(), email: 'b@x', store: memStore({}) }))
await expect(runUseAccount({ io: bufferStreams(), email: 'b@x', store: new MemStore({}) }))
.rejects
.toThrow(/log in|no credential/i)
})
it('errors when the email is unknown on the current host', async () => {
await expect(runUseAccount({ io: bufferStreams(), email: 'z@x', store: memStore({ 'tokens.h1.z@x': 'x' }) }))
await expect(runUseAccount({ io: bufferStreams(), email: 'z@x', store: new MemStore({ 'h1 z@x': 'x' }) }))
.rejects
.toThrow(/unknown account|no account/i)
})
@@ -58,6 +36,6 @@ describe('runUseAccount', () => {
it('errors in non-TTY when email omitted', async () => {
const io = bufferStreams()
;(io as { isErrTTY: boolean }).isErrTTY = false
await expect(runUseAccount({ io, email: undefined, store: memStore({}) })).rejects.toThrow(/--email/i)
await expect(runUseAccount({ io, email: undefined, store: new MemStore({}) })).rejects.toThrow(/--email/i)
})
})
+5 -5
View File
@@ -1,10 +1,10 @@
import type { HostEntry } from '@/auth/hosts'
import type { Store } from '@/store/store'
import type { TokenStore } from '@/store/token-store'
import type { IOStreams } from '@/sys/io/streams'
import { notLoggedInError, Registry } from '@/auth/hosts'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { getTokenStore, tokenKey } from '@/store/manager'
import { getTokenStore } from '@/store/manager'
import { colorEnabled, colorScheme } from '@/sys/io/color'
import { selectFromList } from '@/sys/io/select'
@@ -12,7 +12,7 @@ export type UseAccountOptions = {
readonly io: IOStreams
readonly email: string | undefined
/** Optional override for tests; production resolves via `getTokenStore`. */
readonly store?: Store
readonly store?: TokenStore
}
type AccountChoice = { email: string, name: string, sso: boolean, active: boolean }
@@ -38,8 +38,8 @@ export async function runUseAccount(opts: UseAccountOptions): Promise<void> {
})
}
const store = opts.store ?? getTokenStore().store
if (store.get(tokenKey(host, target)) === '') {
const store = opts.store ?? getTokenStore(reg.token_storage)
if (store.read(host, target) === '') {
throw new BaseError({
code: ErrorCode.NotLoggedIn,
message: `no credential stored for ${target} on ${host}`,
+4 -17
View File
@@ -1,19 +1,12 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { beforeEach, describe, expect, it } from 'vitest'
import { Registry } from '@/auth/hosts'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { bufferStreams } from '@/sys/io/streams'
import { runUseHost } from './use-host'
describe('runUseHost', () => {
let dir: string
let prev: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-usehost-'))
prev = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
useTempConfigDir('difyctl-usehost-')
beforeEach(() => {
const reg = Registry.empty('file')
reg.upsert('h1', 'a@x', { account: { id: '1', email: 'a@x', name: 'A' } })
reg.upsert('h2', 'b@x', { account: { id: '2', email: 'b@x', name: 'B' } })
@@ -21,12 +14,6 @@ describe('runUseHost', () => {
reg.setAccount('a@x')
reg.save()
})
afterEach(async () => {
if (prev === undefined)
delete process.env[ENV_CONFIG_DIR]
else process.env[ENV_CONFIG_DIR] = prev
await rm(dir, { recursive: true, force: true })
})
it('switches current_host when host is valid', async () => {
await runUseHost({ io: bufferStreams(), host: 'h2' })
+3 -2
View File
@@ -5,16 +5,17 @@ import { Args } from '@/framework/flags'
import { runUseWorkspace } from './use'
export default class UseWorkspace extends DifyCommand {
static override description = 'Switch the active workspace on the server and refresh hosts.yml'
static override description = 'Switch the active workspace on the server (omit the id to pick interactively)'
static override effect: CommandEffect = 'write'
static override examples = [
'<%= config.bin %> use workspace ws-abc123',
'<%= config.bin %> use workspace',
]
static override args = {
workspaceId: Args.string({ description: 'workspace id to switch to', required: true }),
workspaceId: Args.string({ description: 'workspace id to switch to (omit to pick interactively)', required: false }),
}
static override flags = {
+69 -138
View File
@@ -4,24 +4,24 @@ import type {
} from '@dify/contracts/api/openapi/types.gen'
import type { ActiveContext } from '@/auth/hosts'
import type { HttpClient } from '@/http/types'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Registry } from '@/auth/hosts'
import { ENV_CONFIG_DIR } from '@/store/dir'
import { selectFromList } from '@/sys/io/select'
import { bufferStreams } from '@/sys/io/streams'
import { runUseWorkspace } from './use.js'
vi.mock('@/sys/io/select', () => ({
selectFromList: vi.fn(),
}))
const selectFromListMock = vi.mocked(selectFromList)
function makeRegistry(): Registry {
const reg = Registry.empty('file')
reg.upsert('cloud.dify.ai', 'tester@dify.ai', {
account: { id: 'acct-1', email: 'tester@dify.ai', name: 'Tester' },
workspace: { id: 'ws-1', name: 'Default', role: 'owner' },
available_workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner' },
{ id: 'ws-2', name: 'Stale Name', role: 'normal' },
],
})
reg.setHost('cloud.dify.ai')
reg.setAccount('tester@dify.ai')
@@ -35,46 +35,41 @@ function makeActive(reg: Registry): ActiveContext {
return active
}
function makeDetail(over: Partial<WorkspaceDetailResponse> = {}): WorkspaceDetailResponse {
return {
id: '00000000-0000-0000-0000-000000000002',
name: 'Two',
role: 'owner',
status: 'normal',
current: true,
created_at: '2026-05-18T00:00:00Z',
...over,
}
}
function fakeClient(opts: {
switch?: () => Promise<WorkspaceDetailResponse>
list?: () => Promise<WorkspaceListResponse>
}) {
return {
switch: vi.fn(opts.switch ?? (() => Promise.resolve({
id: 'ws-2',
name: 'Switched',
role: 'normal',
status: 'normal',
current: true,
created_at: '2026-05-18T00:00:00Z',
}))),
switch: vi.fn(opts.switch ?? (() => Promise.resolve(makeDetail()))),
list: vi.fn(opts.list ?? (() => Promise.resolve({
workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner', status: 'normal', current: false },
{ id: 'ws-2', name: 'Switched', role: 'normal', status: 'normal', current: true },
{ id: 'ws-1', name: 'Default', role: 'owner', status: 'normal', current: true },
{ id: '00000000-0000-0000-0000-000000000002', name: 'Two', role: 'owner', status: 'normal', current: false },
],
}))),
}
}
describe('runUseWorkspace', () => {
let configDir: string
useTempConfigDir('difyctl-use-workspace-')
let prevConfigDir: string | undefined
beforeEach(async () => {
configDir = await mkdtemp(join(tmpdir(), 'difyctl-use-workspace-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = configDir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await rm(configDir, { recursive: true, force: true })
beforeEach(() => {
selectFromListMock.mockReset()
})
it('happy path: POST /switch → GET /workspaces → write hosts.yml', async () => {
it('arg path: switches directly without listing and persists only the active workspace', async () => {
const io = bufferStreams()
const reg = makeRegistry()
reg.save()
@@ -82,7 +77,7 @@ describe('runUseWorkspace', () => {
const client = fakeClient({})
const next = await runUseWorkspace(
{ workspaceId: 'ws-2' },
{ workspaceId: '00000000-0000-0000-0000-000000000002' },
{
reg,
active,
@@ -92,62 +87,42 @@ describe('runUseWorkspace', () => {
},
)
expect(client.switch).toHaveBeenCalledExactlyOnceWith('ws-2')
expect(client.list).toHaveBeenCalledOnce()
expect(client.switch).toHaveBeenCalledExactlyOnceWith('00000000-0000-0000-0000-000000000002')
expect(client.list).not.toHaveBeenCalled()
const activeCtx = next.resolveActive()
expect(activeCtx?.ctx.workspace).toEqual({ id: 'ws-2', name: 'Switched', role: 'normal' })
expect(activeCtx?.ctx.available_workspaces).toEqual([
{ id: 'ws-1', name: 'Default', role: 'owner' },
{ id: 'ws-2', name: 'Switched', role: 'normal' },
])
expect(activeCtx?.ctx.workspace).toEqual({ id: '00000000-0000-0000-0000-000000000002', name: 'Two', role: 'owner' })
expect((activeCtx?.ctx as Record<string, unknown> | undefined)?.available_workspaces).toBeUndefined()
const reloaded = Registry.load()
const reloadedActive = reloaded?.resolveActive()
expect(reloadedActive?.ctx.workspace?.id).toBe('ws-2')
expect(reloadedActive?.ctx.workspace?.name).toBe('Switched')
expect(reloadedActive?.ctx.workspace?.id).toBe('00000000-0000-0000-0000-000000000002')
expect(reloadedActive?.ctx.workspace?.name).toBe('Two')
expect((reloadedActive?.ctx as Record<string, unknown> | undefined)?.available_workspaces).toBeUndefined()
expect(io.outBuf()).toMatch(/Switched to Switched \(ws-2\)/)
expect(io.outBuf()).toMatch(/Switched to Two \(00000000-0000-0000-0000-000000000002\)/)
})
it('hosts.yml contains no bearer after switch', async () => {
it('no-arg + no-TTY: rejects with usage_missing_arg and never switches', async () => {
const io = bufferStreams()
io.isErrTTY = false
const reg = makeRegistry()
reg.save()
const active = makeActive(reg)
const client = fakeClient({})
await runUseWorkspace(
{ workspaceId: 'ws-2' },
{ reg, active, http: {} as HttpClient, io, workspacesFactory: () => client as never },
)
await expect(
runUseWorkspace(
{ workspaceId: undefined },
{ reg, active, http: {} as HttpClient, io, workspacesFactory: () => client as never },
),
).rejects.toMatchObject({ code: 'usage_missing_arg' })
const reloaded = Registry.load()
const raw = JSON.stringify(reloaded)
expect(raw).not.toMatch(/bearer/)
expect(client.switch).not.toHaveBeenCalled()
expect(client.list).not.toHaveBeenCalled()
})
it('refreshes stale workspace name from server', async () => {
// registry has ws-2 named "Stale Name"; server returns "Switched".
// We expect saveRegistry to record the fresh name from the server.
const io = bufferStreams()
const reg = makeRegistry()
reg.save()
const active = makeActive(reg)
const client = fakeClient({})
await runUseWorkspace(
{ workspaceId: 'ws-2' },
{ reg, active, http: {} as HttpClient, io, workspacesFactory: () => client as never },
)
const reloaded = Registry.load()
const reloadedActive = reloaded?.resolveActive()
expect(reloadedActive?.ctx.workspace?.name).toBe('Switched')
expect(reloadedActive?.ctx.available_workspaces?.find(w => w.id === 'ws-2')?.name).toBe('Switched')
})
it('does NOT mutate hosts.yml when POST /switch fails', async () => {
it('switch failure: rejects and leaves the active workspace untouched', async () => {
const io = bufferStreams()
const reg = makeRegistry()
reg.save()
@@ -160,85 +135,41 @@ describe('runUseWorkspace', () => {
await expect(
runUseWorkspace(
{ workspaceId: 'ws-2' },
{
reg,
active,
http: {} as HttpClient,
io,
workspacesFactory: () => client as never,
},
{ workspaceId: '00000000-0000-0000-0000-000000000002' },
{ reg, active, http: {} as HttpClient, io, workspacesFactory: () => client as never },
),
).rejects.toThrow(/forbidden/)
expect(client.list).not.toHaveBeenCalled()
const after = Registry.load()
expect(after).toEqual(before)
const afterActive = after?.resolveActive()
expect(afterActive?.ctx.workspace?.id).toBe('ws-1')
expect(after?.resolveActive()?.ctx.workspace?.id).toBe('ws-1')
})
it('does NOT mutate hosts.yml when GET /workspaces fails after switch', async () => {
it('picker path (TTY): lists live workspaces and switches to the selected one', async () => {
const io = bufferStreams()
io.isErrTTY = true
const reg = makeRegistry()
reg.save()
const active = makeActive(reg)
const before = Registry.load()
const client = fakeClient({})
const client = fakeClient({
list: () => Promise.reject(new Error('transient list failure')),
})
selectFromListMock.mockResolvedValue({ id: '00000000-0000-0000-0000-000000000002', name: 'Two', role: 'owner' })
await expect(
runUseWorkspace(
{ workspaceId: 'ws-2' },
{
reg,
active,
http: {} as HttpClient,
io,
workspacesFactory: () => client as never,
},
),
).rejects.toThrow(/transient list failure/)
await runUseWorkspace(
{ workspaceId: undefined },
{ reg, active, http: {} as HttpClient, io, workspacesFactory: () => client as never },
)
const after = Registry.load()
expect(after).toEqual(before)
})
expect(client.list).toHaveBeenCalledOnce()
expect(selectFromListMock).toHaveBeenCalledOnce()
const passed = selectFromListMock.mock.calls[0]![0]
expect(passed.items).toEqual([
{ id: 'ws-1', name: 'Default', role: 'owner' },
{ id: '00000000-0000-0000-0000-000000000002', name: 'Two', role: 'owner' },
])
expect(client.switch).toHaveBeenCalledExactlyOnceWith('00000000-0000-0000-0000-000000000002')
it('throws when server returns switch=<id> but id is missing from /workspaces list', async () => {
const io = bufferStreams()
const reg = makeRegistry()
reg.save()
const active = makeActive(reg)
const client = fakeClient({
switch: () => Promise.resolve({
id: 'ws-7',
name: 'Ghost',
role: 'normal',
status: 'normal',
current: true,
created_at: null as unknown as string,
}),
list: () => Promise.resolve({
workspaces: [
{ id: 'ws-1', name: 'Default', role: 'owner', status: 'normal', current: false },
],
}),
})
await expect(
runUseWorkspace(
{ workspaceId: 'ws-7' },
{
reg,
active,
http: {} as HttpClient,
io,
workspacesFactory: () => client as never,
},
),
).rejects.toThrow(/not visible in \/workspaces/)
const reloadedActive = Registry.load()?.resolveActive()
expect(reloadedActive?.ctx.workspace?.id).toBe('00000000-0000-0000-0000-000000000002')
})
})
+46 -30
View File
@@ -5,10 +5,11 @@ import { WorkspacesClient } from '@/api/workspaces'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { colorEnabled, colorScheme } from '@/sys/io/color'
import { selectFromList } from '@/sys/io/select'
import { runWithSpinner } from '@/sys/io/spinner'
export type UseWorkspaceOptions = {
readonly workspaceId: string
readonly workspaceId?: string
}
export type UseWorkspaceDeps = {
@@ -22,16 +23,12 @@ export type UseWorkspaceDeps = {
/**
* Switch the caller's active workspace.
*
* Strict ordering:
* 1. POST /workspaces/<id>/switch — if this fails (403/404/etc.) we abort
* with no `hosts.yml` mutation, so local state never diverges from the
* server. Any fallback to a pure-local update is explicitly disallowed
* (see workspace-plan.md decision D4).
* 2. GET /workspaces — refresh the membership list so `available_workspaces`
* stays in sync. Failure here also aborts; the server-side current has
* already moved, but the local file is left untouched. A follow-up
* `difyctl get workspace` will reconcile.
* 3. Persist `workspace` + `available_workspaces` atomically via `saveRegistry`.
* With an explicit id we switch directly; with no id we fetch the live
* workspace list and let the caller pick one interactively (TTY only).
*
* The server-side switch is the source of truth: if POST
* `/workspaces/<id>/switch` fails we abort before touching `hosts.yml`, so
* local state never diverges from the server.
*/
export async function runUseWorkspace(
opts: UseWorkspaceOptions,
@@ -41,32 +38,51 @@ export async function runUseWorkspace(
const factory = deps.workspacesFactory ?? ((h: HttpClient) => new WorkspacesClient(h))
const client = factory(deps.http)
const argId = opts.workspaceId?.trim() ?? ''
const id = argId !== '' ? argId : await pickWorkspaceId(client, deps)
const detail = await runWithSpinner(
{ io: deps.io, label: `Switching to ${opts.workspaceId}` },
() => client.switch(opts.workspaceId),
{ io: deps.io, label: `Switching to ${id}` },
() => client.switch(id),
)
const list = await runWithSpinner(
{ io: deps.io, label: 'Refreshing workspaces' },
() => client.list(),
)
const matched = list.workspaces.find(w => w.id === detail.id)
if (matched === undefined) {
throw new BaseError({
code: ErrorCode.Unknown,
message: `server returned switch=${detail.id} but it is not visible in /workspaces`,
hint: 'try again or contact your workspace admin',
})
}
const nextCtx = {
...deps.active.ctx,
workspace: { id: matched.id, name: matched.name, role: matched.role },
available_workspaces: list.workspaces.map<Workspace>(w => ({ id: w.id, name: w.name, role: w.role })),
workspace: { id: detail.id, name: detail.name, role: detail.role },
}
deps.reg.upsert(deps.active.host, deps.active.email, nextCtx)
deps.reg.save()
deps.io.out.write(`${cs.successIcon()} Switched to ${matched.name} (${matched.id})\n`)
deps.io.out.write(`${cs.successIcon()} Switched to ${detail.name} (${detail.id})\n`)
return deps.reg
}
async function pickWorkspaceId(client: WorkspacesClient, deps: UseWorkspaceDeps): Promise<string> {
if (!deps.io.isErrTTY) {
throw new BaseError({
code: ErrorCode.UsageMissingArg,
message: 'a workspace id is required (no TTY)',
hint: 'pass the id: \'difyctl use workspace <id>\'',
})
}
const list = await runWithSpinner(
{ io: deps.io, label: 'Loading workspaces' },
() => client.list(),
)
const items = list.workspaces.map<Workspace>(w => ({ id: w.id, name: w.name, role: w.role }))
if (items.length === 0) {
throw new BaseError({
code: ErrorCode.AccessDenied,
message: 'no workspaces available to switch to',
})
}
const activeId = deps.active.ctx.workspace?.id
const picked = await selectFromList<Workspace>({
io: deps.io,
items,
header: 'Select a workspace',
render: w => `${w.id === activeId ? '* ' : ' '}${w.name} (${w.role})`,
})
return picked.id
}