🤯 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
🐛 fix(hetero-agent): resolve Claude Code cloud token status in the run scope (#20969)
Lobehub Coder6ff166345b9f
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex dfe7a1569d0..ba0e84ca95a 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -822,8 +822,14 @@"heterogeneousStatus.cloud.tokenChange": "Change","heterogeneousStatus.cloud.tokenDesc": "Your Claude Code OAuth token. Saved securely to Credentials once submitted. Run `claude setup-token` in your terminal to generate one.","heterogeneousStatus.cloud.tokenLabel": "Claude Code Token",+ "heterogeneousStatus.cloud.tokenLookupError": "Couldn't check whether this token is available here. Retry to load it again.",+ "heterogeneousStatus.cloud.tokenNotShared": "Your personal Claude Code token is not shared to this workspace, so cloud runs here cannot use it. Save a token to share it to this workspace.","heterogeneousStatus.cloud.tokenPlaceholder": "Paste your OAuth token here",+ "heterogeneousStatus.cloud.tokenRetry": "Retry","heterogeneousStatus.cloud.tokenSave": "Save",+ "heterogeneousStatus.cloud.tokenSaveError": "Failed to save the Claude Code token. Please try again.",+ "heterogeneousStatus.cloud.tokenSharedElsewhere": "Your personal Claude Code token is shared to another workspace. Saving a token here moves it to this workspace, and cloud runs in the other workspace will no longer be able to use it.",+ "heterogeneousStatus.cloud.tokenTypeMismatch": "A credential with the key CLAUDE_CODE_OAUTH_TOKEN already exists with a different type. Remove or rename it in Credentials, then save again.","heterogeneousStatus.command.edit": "Edit command","heterogeneousStatus.command.label": "Launch Command","heterogeneousStatus.command.placeholder": "Command name or absolute path",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex f12f140e18b..fad72da3f48 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -822,8 +822,14 @@"heterogeneousStatus.cloud.tokenChange": "修改","heterogeneousStatus.cloud.tokenDesc": "你的 Claude Code OAuth Token,提交后将安全保存到凭证管理。在终端运行 `claude setup-token` 即可获取。","heterogeneousStatus.cloud.tokenLabel": "Claude Code Token",+ "heterogeneousStatus.cloud.tokenLookupError": "无法确认当前是否可以使用这个 Token,请重试。",+ "heterogeneousStatus.cloud.tokenNotShared": "你的个人 Claude Code Token 尚未共享到当前工作区,这里的云端运行无法使用它。保存 Token 后会自动共享到当前工作区。","heterogeneousStatus.cloud.tokenPlaceholder": "粘贴你的 OAuth Token",+ "heterogeneousStatus.cloud.tokenRetry": "重试","heterogeneousStatus.cloud.tokenSave": "保存",+ "heterogeneousStatus.cloud.tokenSaveError": "Claude Code Token 保存失败,请重试。",+ "heterogeneousStatus.cloud.tokenSharedElsewhere": "你的个人 Claude Code Token 已共享到另一个工作区。在这里保存 Token 会把它移到当前工作区,另一个工作区的云端运行将无法再使用它。",+ "heterogeneousStatus.cloud.tokenTypeMismatch": "已存在一个键名为 CLAUDE_CODE_OAUTH_TOKEN 但类型不同的凭证。请先在凭证管理中删除或重命名它,然后再保存。","heterogeneousStatus.command.edit": "编辑指令","heterogeneousStatus.command.label": "启动指令","heterogeneousStatus.command.placeholder": "指令名称或绝对路径",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 882d0af85cf..96b473f285e 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -518,6 +518,17 @@ export default {'heterogeneousStatus.cloud.tokenLabel': 'Claude Code Token','heterogeneousStatus.cloud.tokenDesc':'Your Claude Code OAuth token. Saved securely to Credentials once submitted. Run `claude setup-token` in your terminal to generate one.',+ 'heterogeneousStatus.cloud.tokenLookupError':+ "Couldn't check whether this token is available here. Retry to load it again.",+ 'heterogeneousStatus.cloud.tokenRetry': 'Retry',+ 'heterogeneousStatus.cloud.tokenSharedElsewhere':+ 'Your personal Claude Code token is shared to another workspace. Saving a token here moves it to this workspace, and cloud runs in the other workspace will no longer be able to use it.',+ 'heterogeneousStatus.cloud.tokenTypeMismatch':+ 'A credential with the key CLAUDE_CODE_OAUTH_TOKEN already exists with a different type. Remove or rename it in Credentials, then save again.',+ 'heterogeneousStatus.cloud.tokenNotShared':+ 'Your personal Claude Code token is not shared to this workspace, so cloud runs here cannot use it. Save a token to share it to this workspace.',+ 'heterogeneousStatus.cloud.tokenSaveError':+ 'Failed to save the Claude Code token. Please try again.','heterogeneousStatus.cloud.tokenPlaceholder': 'Paste your OAuth token here','heterogeneousStatus.cloud.tokenChange': 'Change','heterogeneousStatus.cloud.tokenSave': 'Save',diff --git a/src/business/client/hooks/useHeteroAgentCloudConfig.test.ts b/src/business/client/hooks/useHeteroAgentCloudConfig.test.tsnew file mode 100644index 00000000000..fa2784de2dc--- /dev/null+++ b/src/business/client/hooks/useHeteroAgentCloudConfig.test.ts@@ -0,0 +1,80 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useHeteroAgentCloudConfig } from './useHeteroAgentCloudConfig';++const { mockListForContext, mockProvider } = vi.hoisted(() => ({+ mockListForContext: vi.fn(),+ mockProvider: { current: undefined as Record<string, unknown> | undefined },+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ isDesktop: false,+}));++vi.mock('@/hooks/useQueryRoute', () => ({ useQueryRoute: () => ({ push: vi.fn() }) }));++vi.mock('@/hooks/useScopedCreds', () => ({ useCredsForContext: mockListForContext }));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: unknown) => unknown) => selector({}),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => () => ({ heterogeneousProvider: mockProvider.current }),+ },+}));++describe('useHeteroAgentCloudConfig', () => {+ beforeEach(() => {+ mockProvider.current = { type: 'claude-code' };+ mockListForContext.mockReset();+ });++ it('is not configured when only the agent env references the token', () => {+ mockProvider.current = {+ env: { CLAUDE_CODE_CRED_KEY: 'CLAUDE_CODE_OAUTH_TOKEN' },+ type: 'claude-code',+ };+ mockListForContext.mockReturnValue({ data: [], isLoading: false });++ const { result } = renderHook(() => useHeteroAgentCloudConfig('agt_1'));++ expect(result.current.isConfigured).toBe(false);+ });++ it('is configured when the token exists in the run scope', () => {+ mockListForContext.mockReturnValue({+ data: [{ key: 'CLAUDE_CODE_OAUTH_TOKEN', name: 'Claude Code OAuth Token' }],+ isLoading: false,+ });++ const { result } = renderHook(() => useHeteroAgentCloudConfig('agt_1'));++ expect(result.current.isConfigured).toBe(true);+ });++ it('does not block sending when the credential lookup fails', () => {+ mockListForContext.mockReturnValue({+ data: undefined,+ error: new Error('market unavailable'),+ isLoading: false,+ });++ const { result } = renderHook(() => useHeteroAgentCloudConfig('agt_1'));++ expect(result.current.isConfigured).toBe(true);+ });++ it('does not query credentials for non claude-code providers', () => {+ mockProvider.current = { type: 'codex' };+ mockListForContext.mockReturnValue({ data: undefined, isLoading: false });++ const { result } = renderHook(() => useHeteroAgentCloudConfig('agt_1'));++ expect(result.current.isConfigured).toBe(true);+ expect(mockListForContext).toHaveBeenCalledWith(false);+ });+});diff --git a/src/business/client/hooks/useHeteroAgentCloudConfig.ts b/src/business/client/hooks/useHeteroAgentCloudConfig.tsindex 73d1bf0643f..4949c2510ef 100644--- a/src/business/client/hooks/useHeteroAgentCloudConfig.ts+++ b/src/business/client/hooks/useHeteroAgentCloudConfig.ts@@ -1,14 +1,12 @@import { isDesktop } from '@lobechat/const';import urlJoin from 'url-join';+import { CLAUDE_CODE_TOKEN_CRED_KEY } from '@/helpers/claudeCodeTokenCred';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { lambdaQuery } from '@/libs/trpc/client';+import { useCredsForContext } from '@/hooks/useScopedCreds';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';-// Fixed cred key — must stay in sync with CloudHeterogeneousConfig-const CLAUDE_TOKEN_CRED_KEY = 'CLAUDE_CODE_OAUTH_TOKEN';-interface HeteroAgentCloudConfig {goToConfig: () => void;isConfigured: boolean;@@ -25,27 +23,30 @@ export const useHeteroAgentCloudConfig = (agentId: string): HeteroAgentCloudConfconst isClaudeCode = heterogeneousProvider?.type === 'claude-code';const needsCredCheck = !isDesktop && isClaudeCode;- // Only fetch credentials when actually needed- const { data: credsData, isLoading: isCredsLoading } = lambdaQuery.market.creds.list.useQuery(- undefined,- { enabled: needsCredCheck },- );+ // Only fetch credentials when actually needed. `listForContext` resolves the+ // same scope the cloud run reads (the workspace's organization view inside a+ // workspace, the personal vault otherwise) — the personal list would report+ // a token the run can't see.+ const {+ data: contextCreds,+ error: credsError,+ isLoading: isCredsLoading,+ } = useCredsForContext(needsCredCheck);// isConfigured is true when:// 1. Running on desktop (local execution, no cloud creds needed), or// 2. No heterogeneous provider on this agent, or// 3. Provider is not claude-code (e.g. codex — no cloud credential required), or- // 4. The agent env has a CLAUDE_CODE_CRED_KEY reference set, or- // 5. The CLAUDE_CODE_OAUTH_TOKEN credential actually exists in the vault- // (handles the case where the credential was saved but the env ref wasn't written)+ // 4. The CLAUDE_CODE_OAUTH_TOKEN credential exists in the run's scope. The+ // agent's CLAUDE_CODE_CRED_KEY env reference alone doesn't count: the+ // runtime only reads the credential itself.+ // 5. The credential lookup failed — the state is unknown, not missing, and+ // editing credentials can't fix a failed request; the run reports a+ // genuinely missing token itself, or// 6. Credentials are still loading — treat as configured to avoid a flash of the// "not configured" alert that immediately disappears once the query resolves- const hasCredInVault = (credsData?.data ?? []).some((c) => c.key === CLAUDE_TOKEN_CRED_KEY);- const isConfigured =- !needsCredCheck ||- !!heterogeneousProvider?.env?.CLAUDE_CODE_CRED_KEY ||- hasCredInVault ||- isCredsLoading;+ const hasCredInScope = (contextCreds ?? []).some((c) => c.key === CLAUDE_CODE_TOKEN_CRED_KEY);+ const isConfigured = !needsCredCheck || hasCredInScope || !!credsError || isCredsLoading;const goToConfig = () => {if (agentId) {diff --git a/src/helpers/claudeCodeTokenCred.test.ts b/src/helpers/claudeCodeTokenCred.test.tsnew file mode 100644index 00000000000..aa505c64af7--- /dev/null+++ b/src/helpers/claudeCodeTokenCred.test.ts@@ -0,0 +1,83 @@+import { type UserCredSummary } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { CLAUDE_CODE_TOKEN_CRED_KEY, resolveClaudeCodeTokenStatus } from './claudeCodeTokenCred';++const personalToken = (overrides: Partial<UserCredSummary> = {}): UserCredSummary =>+ ({+ createdAt: '2026-10-14T00:00:00.000Z',+ id: 7,+ key: CLAUDE_CODE_TOKEN_CRED_KEY,+ maskedPreview: 'sk-a****DgAA',+ name: 'Claude Code OAuth Token',+ type: 'kv-env',+ ...overrides,+ }) as UserCredSummary;++const contextToken = { key: CLAUDE_CODE_TOKEN_CRED_KEY, name: 'Claude Code OAuth Token' };++describe('resolveClaudeCodeTokenStatus', () => {+ it('shows the personal preview outside a workspace', () => {+ const cred = personalToken();++ expect(+ resolveClaudeCodeTokenStatus({+ contextCreds: [contextToken],+ inWorkspace: false,+ personalCreds: [cred],+ }),+ ).toEqual({ display: 'sk-a****DgAA', editable: true, status: 'configured' });+ });++ it('reports a personal token that is not shared to the active workspace', () => {+ const cred = personalToken();++ expect(+ resolveClaudeCodeTokenStatus({ contextCreds: [], inWorkspace: true, personalCreds: [cred] }),+ ).toEqual({ personalCred: cred, sharedElsewhere: false, status: 'personalNotShared' });+ });++ it('flags a personal token that is shared to a different workspace', () => {+ const cred = personalToken({ organizationAccountId: 42, sharedToActiveWorkspace: false });++ expect(+ resolveClaudeCodeTokenStatus({ contextCreds: [], inWorkspace: true, personalCreds: [cred] }),+ ).toEqual({ personalCred: cred, sharedElsewhere: true, status: 'personalNotShared' });+ });++ it('shows the personal preview once the token is shared to the active workspace', () => {+ expect(+ resolveClaudeCodeTokenStatus({+ contextCreds: [{ ...contextToken, ownerType: 'user' }],+ inWorkspace: true,+ personalCreds: [personalToken({ sharedToActiveWorkspace: true })],+ }),+ ).toEqual({ display: 'sk-a****DgAA', editable: true, status: 'configured' });+ });++ it('does not show an unshared personal preview for a workspace-owned token', () => {+ expect(+ resolveClaudeCodeTokenStatus({+ contextCreds: [{ ...contextToken, name: 'Team token', ownerType: 'organization' }],+ inWorkspace: true,+ personalCreds: [personalToken()],+ }),+ ).toEqual({ display: 'Team token', editable: false, status: 'configured' });+ });++ it('cannot edit a workspace-owned token the caller has no personal copy of', () => {+ expect(+ resolveClaudeCodeTokenStatus({+ contextCreds: [{ ...contextToken, ownerType: 'organization' }],+ inWorkspace: true,+ personalCreds: [],+ }),+ ).toEqual({ display: 'Claude Code OAuth Token', editable: false, status: 'configured' });+ });++ it('is missing when no scope holds the token', () => {+ expect(+ resolveClaudeCodeTokenStatus({ contextCreds: [], inWorkspace: false, personalCreds: [] }),+ ).toEqual({ status: 'missing' });+ });+});diff --git a/src/helpers/claudeCodeTokenCred.ts b/src/helpers/claudeCodeTokenCred.tsnew file mode 100644index 00000000000..5c192f94fa2--- /dev/null+++ b/src/helpers/claudeCodeTokenCred.ts@@ -0,0 +1,78 @@+import { type UserCredSummary } from '@lobechat/types';++/**+ * Fixed vault key of the Claude Code OAuth token. The cloud sandbox injects the+ * credential stored under this key; it never reads an agent-level reference.+ */+export const CLAUDE_CODE_TOKEN_CRED_KEY = 'CLAUDE_CODE_OAUTH_TOKEN';++/** A credential as `market.creds.listForContext` returns it. */+export interface ContextCredSummary {+ key: string;+ name: string;+ ownerDisplayName?: string;+ ownerType?: 'organization' | 'user';+}++export type ClaudeCodeTokenStatus =+ /**+ * `editable`: the token the run reads is the caller's own personal credential.+ * Saving only writes that credential, so a workspace- or other-member-owned+ * token can't be changed from here.+ */+ | { display: string; editable: boolean; status: 'configured' }+ /** The caller owns a token, but runs in the active workspace can't read it. */+ /**+ * `sharedElsewhere`: the token is linked to another workspace. A personal+ * credential links to one workspace at a time, so sharing it here moves it.+ */+ | { personalCred: UserCredSummary; sharedElsewhere: boolean; status: 'personalNotShared' }+ | { status: 'missing' }+ /** The credential lookup failed; whether the run can read a token is unknown. */+ | { status: 'unknown' };++interface ResolveClaudeCodeTokenStatusParams {+ /** `market.creds.listForContext`: the credentials a run in this scope reads. */+ contextCreds: ContextCredSummary[];+ inWorkspace: boolean;+ /** `market.creds.list`: the caller's personal vault. */+ personalCreds: UserCredSummary[];+}++/**+ * Whether a cloud run of a Claude Code agent will find its OAuth token. The+ * runtime resolves credentials in the run's scope (the workspace's+ * organization view inside a workspace, the personal vault otherwise), so the+ * caller's personal vault alone can't answer this.+ */+export const resolveClaudeCodeTokenStatus = ({+ contextCreds,+ inWorkspace,+ personalCreds,+}: ResolveClaudeCodeTokenStatusParams): ClaudeCodeTokenStatus => {+ const contextCred = contextCreds.find((c) => c.key === CLAUDE_CODE_TOKEN_CRED_KEY);+ const personalCred = personalCreds.find((c) => c.key === CLAUDE_CODE_TOKEN_CRED_KEY);++ if (contextCred) {+ // Only show the personal masked preview when that personal credential is+ // the one the run reads; otherwise it belongs to another owner.+ const isOwnCred = !inWorkspace || !!personalCred?.sharedToActiveWorkspace;+ const preview = isOwnCred ? personalCred?.maskedPreview : undefined;++ return {+ display: preview ?? contextCred.name,+ editable: isOwnCred && !!personalCred,+ status: 'configured',+ };+ }++ if (personalCred) {+ return {+ personalCred,+ sharedElsewhere: personalCred.organizationAccountId != null,+ status: 'personalNotShared',+ };+ }++ return { status: 'missing' };+};diff --git a/src/hooks/useScopedCreds.test.ts b/src/hooks/useScopedCreds.test.tsnew file mode 100644index 00000000000..2407c3fa49c--- /dev/null+++ b/src/hooks/useScopedCreds.test.ts@@ -0,0 +1,48 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ CREDS_FOR_CONTEXT_SWR_KEY,+ PERSONAL_CREDS_SWR_KEY,+ useCredsForContext,+ usePersonalCreds,+} from './useScopedCreds';++const { mockUseClientDataSWR } = vi.hoisted(() => ({ mockUseClientDataSWR: vi.fn() }));++vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: mockUseClientDataSWR }));+vi.mock('@/libs/trpc/client', () => ({ lambdaClient: {} }));++describe('useScopedCreds', () => {+ beforeEach(() => {+ mockUseClientDataSWR.mockReset();+ mockUseClientDataSWR.mockReturnValue({ data: undefined, isLoading: false });+ });++ // `useClientDataSWR` adds the active workspace id to array keys; the raw TRPC+ // query key it replaces had no workspace dimension, so a list fetched in one+ // workspace kept being served after switching to another.+ it('fetches the run-scope list through the workspace-aware SWR hook', () => {+ renderHook(() => useCredsForContext());++ expect(mockUseClientDataSWR).toHaveBeenCalledWith(+ [CREDS_FOR_CONTEXT_SWR_KEY],+ expect.any(Function),+ );+ });++ it('skips the run-scope fetch when disabled', () => {+ renderHook(() => useCredsForContext(false));++ expect(mockUseClientDataSWR).toHaveBeenCalledWith(null, expect.any(Function));+ });++ it('fetches the personal list through the workspace-aware SWR hook', () => {+ renderHook(() => usePersonalCreds());++ expect(mockUseClientDataSWR).toHaveBeenCalledWith(+ [PERSONAL_CREDS_SWR_KEY],+ expect.any(Function),+ );+ });+});diff --git a/src/hooks/useScopedCreds.ts b/src/hooks/useScopedCreds.tsnew file mode 100644index 00000000000..a23ca4a091a--- /dev/null+++ b/src/hooks/useScopedCreds.ts@@ -0,0 +1,35 @@+import { type UserCredSummary } from '@lobechat/types';++import { type ContextCredSummary } from '@/helpers/claudeCodeTokenCred';+import { mutate, useClientDataSWR } from '@/libs/swr';+import { lambdaClient } from '@/libs/trpc/client';++/**+ * SWR keys for credential lists whose content depends on the active workspace.+ * `useClientDataSWR` augments them with the workspace id, so switching+ * workspaces fetches a fresh entry. The raw TRPC React Query key has no+ * workspace dimension and keeps serving the previous workspace's list.+ */+export const CREDS_FOR_CONTEXT_SWR_KEY = 'market/creds/listForContext';+export const PERSONAL_CREDS_SWR_KEY = 'market/creds/list';++/** The credentials a run in the active scope reads (`market.creds.listForContext`). */+export const useCredsForContext = (enabled = true) =>+ useClientDataSWR<ContextCredSummary[]>(enabled ? [CREDS_FOR_CONTEXT_SWR_KEY] : null, async () => {+ const result = await lambdaClient.market.creds.listForContext.query();+ return result.data as ContextCredSummary[];+ });++/** The caller's personal vault, with `sharedToActiveWorkspace` for the active workspace. */+export const usePersonalCreds = () =>+ useClientDataSWR<UserCredSummary[]>([PERSONAL_CREDS_SWR_KEY], async () => {+ const result = await lambdaClient.market.creds.list.query();+ return (result.data ?? []) as UserCredSummary[];+ });++/** Revalidate both credential lists in every workspace context. */+export const refreshScopedCreds = () =>+ mutate(+ (key: unknown) =>+ Array.isArray(key) && [CREDS_FOR_CONTEXT_SWR_KEY, PERSONAL_CREDS_SWR_KEY].includes(key[0]),+ );diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsxindex 44ac6cf36db..38c28e9a39b 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx@@ -3,18 +3,32 @@import { type HeterogeneousProviderConfig, type UserCredSummary } from '@lobechat/types';import { Github } from '@lobehub/icons';import { Flexbox } from '@lobehub/ui';-import { Avatar, Button, Input, InputPassword, Select, Spin, Tag, Text } from '@lobehub/ui/base-ui';+import {+ Avatar,+ Button,+ Input,+ InputPassword,+ Select,+ Spin,+ Tag,+ Text,+ toast,+} from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { CheckCircle2, KeyRound, X } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import {+ CLAUDE_CODE_TOKEN_CRED_KEY,+ type ClaudeCodeTokenStatus,+ resolveClaudeCodeTokenStatus,+} from '@/helpers/claudeCodeTokenCred';import { usePermission } from '@/hooks/usePermission';-import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';--// Fixed cred key for Claude Code OAuth token — never changes-const CLAUDE_TOKEN_CRED_KEY = 'CLAUDE_CODE_OAUTH_TOKEN';+import { refreshScopedCreds, useCredsForContext, usePersonalCreds } from '@/hooks/useScopedCreds';+import { saveClaudeCodeToken } from '@/services/claudeCodeToken';const styles = createStaticStyles(({ css }) => ({card: css`@@ -113,103 +127,148 @@ interface CloudHeterogeneousConfigProps {// ── Claude Code Token section ──────────────────────────────────────────────interface TokenSectionProps {- existingCred: UserCredSummary | undefined;+ inWorkspace: boolean;onEnvChange: (patch: Record<string, string>) => void;onSaved: () => void;+ /** The caller's own token, if any — saving updates it instead of adding a duplicate key. */+ personalCred?: { id: number; type?: string };+ tokenStatus: ClaudeCodeTokenStatus;}-const TokenSection = memo<TokenSectionProps>(({ existingCred, onSaved, onEnvChange }) => {- const { t } = useTranslation('setting');- const { allowed: canEdit } = usePermission('edit_own_content');- const [editing, setEditing] = useState(!existingCred);- const [tokenInput, setTokenInput] = useState('');- const [saving, setSaving] = useState(false);+const TokenSection = memo<TokenSectionProps>(+ ({ inWorkspace, onEnvChange, onSaved, personalCred, tokenStatus }) => {+ const { t } = useTranslation('setting');+ const { allowed: canEdit } = usePermission('edit_own_content');+ const configured = tokenStatus.status === 'configured';+ const [editing, setEditing] = useState(!configured);+ const [tokenInput, setTokenInput] = useState('');+ const [saving, setSaving] = useState(false);- const handleSave = async () => {- if (!canEdit) return;+ if (tokenStatus.status === 'unknown') {+ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align="center" gap={6}>+ <KeyRound size={12} />+ <span className={styles.sectionLabel}>{t('heterogeneousStatus.cloud.tokenLabel')}</span>+ </Flexbox>+ <Flexbox horizontal align="center" gap={8}>+ <Text fontSize={12} type={'warning'}>+ {t('heterogeneousStatus.cloud.tokenLookupError')}+ </Text>+ <Button size={'small'} onClick={onSaved}>+ {t('heterogeneousStatus.cloud.tokenRetry')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ }- const token = tokenInput.trim();- if (!token) return;- setSaving(true);- try {- await lambdaClient.market.creds.createKV.mutate({- key: CLAUDE_TOKEN_CRED_KEY,- name: 'Claude Code OAuth Token',- type: 'kv-env',- values: { [CLAUDE_TOKEN_CRED_KEY]: token },- });- onEnvChange({ CLAUDE_CODE_CRED_KEY: CLAUDE_TOKEN_CRED_KEY });- setTokenInput('');- setEditing(false);- onSaved();- } finally {+ const handleSave = async () => {+ if (!canEdit) return;++ const token = tokenInput.trim();+ if (!token) return;+ setSaving(true);+ const result = await saveClaudeCodeToken({ inWorkspace, personalCred, token });setSaving(false);- }- };+ // Refetch either way: a failed share leaves the token saved but unusable+ // here, which the refreshed status shows as the "not shared" warning.+ onSaved();- return (- <Flexbox gap={8}>- <Flexbox horizontal align="center" justify="space-between">- <Flexbox horizontal align="center" gap={6}>- <KeyRound size={12} />- <span className={styles.sectionLabel}>{t('heterogeneousStatus.cloud.tokenLabel')}</span>- </Flexbox>- {existingCred && !editing && (- <span- className={styles.manageLink}- onClick={() => {- if (!canEdit) return;-- setEditing(true);- }}- >- {t('heterogeneousStatus.cloud.tokenChange')}- </span>- )}- </Flexbox>+ if (!result.ok) {+ toast.error(+ t(+ (+ {+ save: 'heterogeneousStatus.cloud.tokenSaveError',+ share: 'creds.share.error',+ type: 'heterogeneousStatus.cloud.tokenTypeMismatch',+ } as const+ )[result.failedStep],+ ),+ );+ return;+ }- {existingCred && !editing ? (- <Flexbox horizontal align="center" gap={8}>- <Tag- color="success"- icon={<CheckCircle2 size={11} />}- style={{ display: 'flex', alignItems: 'center', gap: 4 }}- >- {existingCred.maskedPreview ?? existingCred.name}- </Tag>- </Flexbox>- ) : (- <Flexbox horizontal gap={8}>- <InputPassword- autoComplete="new-password"- autoFocus={!!existingCred}- disabled={!canEdit}- placeholder={t('heterogeneousStatus.cloud.tokenPlaceholder')}- style={{ flex: 1 }}- value={tokenInput}- onChange={(e) => setTokenInput(e.target.value)}- onPressEnter={handleSave}- />- <Button disabled={!canEdit} loading={saving} type="primary" onClick={handleSave}>- {t('heterogeneousStatus.cloud.tokenSave')}- </Button>- {existingCred && (- <Button+ onEnvChange({ CLAUDE_CODE_CRED_KEY: CLAUDE_CODE_TOKEN_CRED_KEY });+ setTokenInput('');+ setEditing(false);+ };++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align="center" justify="space-between">+ <Flexbox horizontal align="center" gap={6}>+ <KeyRound size={12} />+ <span className={styles.sectionLabel}>{t('heterogeneousStatus.cloud.tokenLabel')}</span>+ </Flexbox>+ {configured && tokenStatus.editable && !editing && (+ <span+ className={styles.manageLink}onClick={() => {- setEditing(false);- setTokenInput('');+ if (!canEdit) return;++ setEditing(true);}}>- {t('heterogeneousStatus.cloud.tokenCancel')}- </Button>+ {t('heterogeneousStatus.cloud.tokenChange')}+ </span>)}</Flexbox>- )}- <span className={styles.sectionDesc}>{t('heterogeneousStatus.cloud.tokenDesc')}</span>- </Flexbox>- );-});+ {configured && !editing ? (+ <Flexbox horizontal align="center" gap={8}>+ <Tag+ color="success"+ icon={<CheckCircle2 size={11} />}+ style={{ display: 'flex', alignItems: 'center', gap: 4 }}+ >+ {tokenStatus.display}+ </Tag>+ </Flexbox>+ ) : (+ <Flexbox horizontal gap={8}>+ <InputPassword+ autoComplete="new-password"+ autoFocus={configured}+ disabled={!canEdit}+ placeholder={t('heterogeneousStatus.cloud.tokenPlaceholder')}+ style={{ flex: 1 }}+ value={tokenInput}+ onChange={(e) => setTokenInput(e.target.value)}+ onPressEnter={handleSave}+ />+ <Button disabled={!canEdit} loading={saving} type="primary" onClick={handleSave}>+ {t('heterogeneousStatus.cloud.tokenSave')}+ </Button>+ {configured && (+ <Button+ onClick={() => {+ setEditing(false);+ setTokenInput('');+ }}+ >+ {t('heterogeneousStatus.cloud.tokenCancel')}+ </Button>+ )}+ </Flexbox>+ )}++ {tokenStatus.status === 'personalNotShared' && (+ <Text fontSize={12} type={'warning'}>+ {t(+ tokenStatus.sharedElsewhere+ ? 'heterogeneousStatus.cloud.tokenSharedElsewhere'+ : 'heterogeneousStatus.cloud.tokenNotShared',+ )}+ </Text>+ )}++ <span className={styles.sectionDesc}>{t('heterogeneousStatus.cloud.tokenDesc')}</span>+ </Flexbox>+ );+ },+);// ── Repo list section ──────────────────────────────────────────────────────// Profile page: manage the list of repos (add / delete only).@@ -289,6 +348,7 @@ const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(const { t } = useTranslation('setting');const navigate = useWorkspaceAwareNavigate();const { allowed: canEdit } = usePermission('edit_own_content');+ const inWorkspace = !!useActiveWorkspaceId();const currentEnv = provider.env ?? {};const storedGithubCredKey = currentEnv.GITHUB_CRED_KEY ?? '';@@ -300,14 +360,24 @@ const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(}})();+ const { data: personalCreds, error: personalError, isLoading } = usePersonalCreds();const {- data: credsData,- isLoading,- refetch,- } = lambdaQuery.market.creds.list.useQuery(undefined);- const allCreds: UserCredSummary[] = credsData?.data ?? [];-- const claudeTokenCred = allCreds.find((c) => c.key === CLAUDE_TOKEN_CRED_KEY);+ data: contextCreds,+ error: contextError,+ isLoading: isContextLoading,+ } = useCredsForContext();+ const allCreds: UserCredSummary[] = personalCreds ?? [];++ // A failed lookup is unknown, not missing: offering save/share can't fix it.+ const tokenStatus: ClaudeCodeTokenStatus =+ contextError || personalError+ ? { status: 'unknown' }+ : resolveClaudeCodeTokenStatus({+ contextCreds: contextCreds ?? [],+ inWorkspace,+ personalCreds: allCreds,+ });+ const personalTokenCred = allCreds.find((c) => c.key === CLAUDE_CODE_TOKEN_CRED_KEY);const githubCreds = allCreds.filter((c) => c.type === 'oauth' && c.oauthProvider?.toLowerCase().includes('github'),);@@ -337,7 +407,7 @@ const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(saveEnv({ GITHUB_REPOS: JSON.stringify(nextRepos) });};- if (isLoading) {+ if (isLoading || isContextLoading) {return (<Flexbox align="center" justify="center" style={{ paddingBlock: 32 }}><Spin size="small" />@@ -350,9 +420,11 @@ const CloudHeterogeneousConfig = memo<CloudHeterogeneousConfigProps>(<Flexbox gap={16}>{/* ── Claude Code OAuth Token ── */}<TokenSection- existingCred={claudeTokenCred}+ inWorkspace={inWorkspace}+ personalCred={personalTokenCred}+ tokenStatus={tokenStatus}onEnvChange={saveEnv}- onSaved={() => refetch()}+ onSaved={() => void refreshScopedCreds()}/><div className={styles.sectionDivider} />diff --git a/src/services/claudeCodeToken.test.ts b/src/services/claudeCodeToken.test.tsnew file mode 100644index 00000000000..efb69f0e797--- /dev/null+++ b/src/services/claudeCodeToken.test.ts@@ -0,0 +1,95 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { saveClaudeCodeToken } from './claudeCodeToken';++const { mockCreds } = vi.hoisted(() => ({+ mockCreds: { createKV: vi.fn(), share: vi.fn(), update: vi.fn() },+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ market: {+ creds: {+ createKV: { mutate: mockCreds.createKV },+ share: { mutate: mockCreds.share },+ update: { mutate: mockCreds.update },+ },+ },+ },+}));++const values = { CLAUDE_CODE_OAUTH_TOKEN: 'sk-ant-test' };++describe('saveClaudeCodeToken', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockCreds.createKV.mockResolvedValue({ id: 9 });+ mockCreds.update.mockResolvedValue({ id: 7 });+ mockCreds.share.mockResolvedValue({ id: 7 });+ });++ it('creates a personal token outside a workspace without sharing it', async () => {+ const result = await saveClaudeCodeToken({ inWorkspace: false, token: 'sk-ant-test' });++ expect(result).toEqual({ ok: true });+ expect(mockCreds.createKV).toHaveBeenCalledWith(expect.objectContaining({ values }));+ expect(mockCreds.share).not.toHaveBeenCalled();+ });++ it('updates the existing token and shares it to the active workspace', async () => {+ const result = await saveClaudeCodeToken({+ inWorkspace: true,+ personalCred: { id: 7, type: 'kv-env' },+ token: 'sk-ant-test',+ });++ expect(result).toEqual({ ok: true });+ expect(mockCreds.update).toHaveBeenCalledWith({ id: 7, values });+ expect(mockCreds.createKV).not.toHaveBeenCalled();+ expect(mockCreds.share).toHaveBeenCalledWith({ id: 7 });+ });++ it('shares a newly created token by its new id', async () => {+ await saveClaudeCodeToken({ inWorkspace: true, token: 'sk-ant-test' });++ expect(mockCreds.share).toHaveBeenCalledWith({ id: 9 });+ });++ it('reports a failed share separately from a failed save', async () => {+ mockCreds.share.mockRejectedValue(new Error('market unavailable'));++ const result = await saveClaudeCodeToken({+ inWorkspace: true,+ personalCred: { id: 7, type: 'kv-env' },+ token: 'sk-ant-test',+ });++ expect(result).toEqual({ failedStep: 'share', ok: false });+ expect(mockCreds.update).toHaveBeenCalled();+ });++ it('leaves a same-key credential of another type untouched', async () => {+ const result = await saveClaudeCodeToken({+ inWorkspace: true,+ personalCred: { id: 7, type: 'kv-header' },+ token: 'sk-ant-test',+ });++ expect(result).toEqual({ failedStep: 'type', ok: false });+ expect(mockCreds.update).not.toHaveBeenCalled();+ expect(mockCreds.share).not.toHaveBeenCalled();+ });++ it('reports a failed save without sharing', async () => {+ mockCreds.update.mockRejectedValue(new Error('market unavailable'));++ const result = await saveClaudeCodeToken({+ inWorkspace: true,+ personalCred: { id: 7, type: 'kv-env' },+ token: 'sk-ant-test',+ });++ expect(result).toEqual({ failedStep: 'save', ok: false });+ expect(mockCreds.share).not.toHaveBeenCalled();+ });+});diff --git a/src/services/claudeCodeToken.ts b/src/services/claudeCodeToken.tsnew file mode 100644index 00000000000..7174724aa32--- /dev/null+++ b/src/services/claudeCodeToken.ts@@ -0,0 +1,63 @@+import { CLAUDE_CODE_TOKEN_CRED_KEY } from '@/helpers/claudeCodeTokenCred';+import { lambdaClient } from '@/libs/trpc/client';++interface SaveClaudeCodeTokenParams {+ inWorkspace: boolean;+ /** The caller's existing token — updated in place instead of adding a duplicate key. */+ personalCred?: { id: number; type?: string };+ token: string;+}++/**+ * `save` failed: nothing changed. `share` failed: the token is stored in the+ * personal vault, but runs in the active workspace still cannot read it.+ * `type`: a credential with this key exists with another type; the update API+ * changes values but not type, so it is left untouched.+ */+export type SaveClaudeCodeTokenResult =+ { ok: true } | { failedStep: 'save' | 'share' | 'type'; ok: false };++/**+ * Store the Claude Code OAuth token where the run will read it. Inside a+ * workspace a run reads the workspace's credentials, so the personal token is+ * shared to the active workspace after it is saved.+ */+export const saveClaudeCodeToken = async ({+ inWorkspace,+ personalCred,+ token,+}: SaveClaudeCodeTokenParams): Promise<SaveClaudeCodeTokenResult> => {+ const values = { [CLAUDE_CODE_TOKEN_CRED_KEY]: token };++ if (personalCred?.type !== undefined && personalCred.type !== 'kv-env') {+ return { failedStep: 'type', ok: false };+ }++ let credId: number;+ try {+ if (personalCred === undefined) {+ const created = await lambdaClient.market.creds.createKV.mutate({+ key: CLAUDE_CODE_TOKEN_CRED_KEY,+ name: 'Claude Code OAuth Token',+ type: 'kv-env',+ values,+ });+ credId = created.id;+ } else {+ await lambdaClient.market.creds.update.mutate({ id: personalCred.id, values });+ credId = personalCred.id;+ }+ } catch {+ return { failedStep: 'save', ok: false };+ }++ if (!inWorkspace) return { ok: true };++ try {+ await lambdaClient.market.creds.share.mutate({ id: credId });+ } catch {+ return { failedStep: 'share', ok: false };+ }++ return { ok: true };+};