🤯 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(creds): workspace/private credential tabs and multi-workspace sharing (#21670)
Rdmclin2a0571a29d43f
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex f10cfc6615e..dab186eb192 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -677,8 +677,8 @@ importers:../../packages/types:dependencies:'@lobehub/market-sdk':- specifier: 0.43.0- version: 0.43.0([email protected])([email protected])+ specifier: 0.46.0+ version: 0.46.0([email protected])([email protected])'@lobehub/market-types':specifier: ^1.19.0version: 1.19.0@@ -2197,14 +2197,17 @@ packages:react: 19.2.7react-dom: 19.2.7- '@lobehub/[email protected]':- resolution: {integrity: sha512-pe0+otQzPBoq9X/C1fEYkM6yjVToO7esnW4b1CrfAe8jj9OPm7QZxgM5sHh4uZ6SU95+oEjOBKCutQyvruY8ZA==}+ '@lobehub/[email protected]':+ resolution: {integrity: sha512-N2TFEUJLQ8GZwFaRimoTU6rPZEgMz3Qk9765e+2YrODv+H5qAGEXavTz1EnQww9FrrdpgzzhUhGmwxksh6wOxQ==}peerDependencies:zod: ^3.24.4'@lobehub/[email protected]':resolution: {integrity: sha512-t6384KeWcSii42kuOqZClhoMs4tus+bW/izoNq96p0M5CvTVxUjrqpmXcKQUK+bnOXMzqqcJZcCU/3hTmFz0lQ==}+ '@lobehub/[email protected]':+ resolution: {integrity: sha512-QAgcPaXgaelqPtiplYuV2aJO0JJ0N6NFICXrM0oUI+IPfFpYlTi4UUARzKCprLGnDg4rQvGHVrdiKEzOTaYYpw==}+'@lobehub/[email protected]':resolution: {integrity: sha512-kkqq2nqwcqz+rV/eUPQ7vY1TQWHWZE3kQt1MsSLtNFLNXMoKYPiF+cdahP97uunWKtf2dB48q/nkSWaZzEKRSw==}engines: {node: '>=22.0.0'}@@ -9509,9 +9512,9 @@ snapshots:react: 19.2.7react-dom: 19.2.7([email protected])dependencies:- '@lobehub/market-types': 1.19.0+ '@lobehub/market-types': 1.22.0'@opentelemetry/api': 1.9.1debug: 4.4.3([email protected])jose: 6.2.12@@ -9524,6 +9527,10 @@ snapshots:dependencies:zod: 3.25.76+ '@lobehub/[email protected]':+ dependencies:+ zod: 3.25.76+'@lobehub/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])([email protected])':dependencies:'@types/hast': 3.0.5diff --git a/apps/server/src/routers/lambda/market/creds.test.ts b/apps/server/src/routers/lambda/market/creds.test.tsindex d9d446e221e..13facf51e7a 100644--- a/apps/server/src/routers/lambda/market/creds.test.ts+++ b/apps/server/src/routers/lambda/market/creds.test.ts@@ -18,7 +18,11 @@ const {mockOrgCredsList: vi.fn(async (): Promise<{ data: MockOrgCredRow[] }> => ({data: [{ id: 1, key: 'ORG_SECRET' }],})),- mockPersonalCredsList: vi.fn(async () => ({ data: [{ id: 2, key: 'PERSONAL_SECRET' }] })),+ mockPersonalCredsList: vi.fn(+ async (): Promise<{+ data: Array<{ id: number; key: string; shares?: Array<{ workspaceId?: string }> }>;+ }> => ({ data: [{ id: 2, key: 'PERSONAL_SECRET' }] }),+ ),mockPersonalCredsPublish: vi.fn(async (id: number) => ({ id, visibility: 'public' })),mockPersonalCredsShare: vi.fn(async (id: number) => ({ id, visibility: 'private' })),mockPersonalCredsUnshare: vi.fn(async (id: number) => ({ id, visibility: 'private' })),@@ -95,8 +99,7 @@ describe('credsRouter is always personal-scoped', () => {// instead of the caller's own personal creds — indistinguishable from// `workspaceCreds.list`. This must never happen again: `list` always// returns personal creds data, with or without an active (even verified)- // workspace — the org list is only ever consulted (below) to scope the- // `sharedToActiveWorkspace` enrichment, never to source the result.+ // workspace.it('returns personal creds data, never the org list, when the caller is a verified workspace member', async () => {const { credsRouter } = await import('./creds');@@ -166,59 +169,40 @@ describe('credsRouter list scopes sharing to the active workspace', () => {vi.clearAllMocks();});- // A personal credential can only be linked to one organization at a time —- // `organizationAccountId != null` alone can't tell "shared to *this*- // workspace" apart from "shared to some other workspace previously". `list`- // cross-references the active workspace's own merged view (by id, among- // entries it marks `ownerType: 'user'`) to compute this per credential.- it('flags sharedToActiveWorkspace: true only when the credential appears as a user-owned entry in the active workspace org list', async () => {- mockOrgCredsList.mockResolvedValueOnce({- data: [{ id: 2, key: 'PERSONAL_SECRET', ownerType: 'user' }],- });- const { credsRouter } = await import('./creds');-- const caller = credsRouter.createCaller({- isWorkspaceMember: true,- userId: 'user-1',- workspaceId: 'workspace-1',- } as any);-- const result = await caller.list();-- expect(result.data).toEqual([{ id: 2, key: 'PERSONAL_SECRET', sharedToActiveWorkspace: true }]);- });-- it('flags sharedToActiveWorkspace: false when the credential is not in the active workspace org list (e.g. shared to a different workspace)', async () => {- // Org list has no entry for id 2 at all — simulates the credential being- // linked to some *other* workspace instead.+ const listIn = async (workspaceId: string | undefined) => {const { credsRouter } = await import('./creds');+ return credsRouter+ .createCaller({ isWorkspaceMember: !!workspaceId, userId: 'user-1', workspaceId } as any)+ .list();+ };++ it("flags sharedToActiveWorkspace from the credential's own shares", async () => {+ mockPersonalCredsList.mockResolvedValueOnce({+ data: [+ { id: 2, key: 'HERE', shares: [{ workspaceId: 'other' }, { workspaceId: 'workspace-1' }] },+ { id: 3, key: 'ELSEWHERE', shares: [{ workspaceId: 'other' }] },+ { id: 4, key: 'UNSHARED', shares: [] },+ ],+ });- const caller = credsRouter.createCaller({- isWorkspaceMember: true,- userId: 'user-1',- workspaceId: 'workspace-1',- } as any);-- const result = await caller.list();+ const result = await listIn('workspace-1');- expect(result.data).toEqual([- { id: 2, key: 'PERSONAL_SECRET', sharedToActiveWorkspace: false },+ expect(result.data?.map((c) => [c.key, c.sharedToActiveWorkspace])).toEqual([+ ['HERE', true],+ ['ELSEWHERE', false],+ ['UNSHARED', false],]);+ expect(mockOrgCredsList).not.toHaveBeenCalled();});- it('still returns the personal list if the active-workspace org lookup fails (e.g. org not set up yet)', async () => {- mockOrgCredsList.mockRejectedValueOnce(new Error('org not found'));- const { credsRouter } = await import('./creds');-- const caller = credsRouter.createCaller({- isWorkspaceMember: true,- userId: 'user-1',- workspaceId: 'workspace-1',- } as any);+ it('leaves the flag off outside a workspace', async () => {+ mockPersonalCredsList.mockResolvedValueOnce({+ data: [{ id: 2, key: 'HERE', shares: [{ workspaceId: 'workspace-1' }] }],+ });- const result = await caller.list();+ const result = await listIn(undefined);- expect(result.data).toEqual([{ id: 2, key: 'PERSONAL_SECRET' }]);+ expect(result.data?.[0]).not.toHaveProperty('sharedToActiveWorkspace');});});@@ -260,7 +244,7 @@ describe('credsRouter share/publish/unshare', () => {expect(mockPersonalCredsShare).not.toHaveBeenCalled();});- it('publishes a draft-linked credential without requiring an org id', async () => {+ it("publishes the credential's share into the caller-verified workspace", async () => {const { credsRouter } = await import('./creds');const caller = credsRouter.createCaller({@@ -271,11 +255,13 @@ describe('credsRouter share/publish/unshare', () => {const result = await caller.publish({ id: 42 });- expect(mockPersonalCredsPublish).toHaveBeenCalledWith(42);+ expect(mockPersonalCredsPublish).toHaveBeenCalledWith(42, undefined, {+ orgId: 'workspace:workspace-1',+ });expect(result).toEqual({ id: 42, visibility: 'public' });});- it('unshares a credential, clearing its workspace link', async () => {+ it('unshares a credential from the caller-verified workspace only', async () => {const { credsRouter } = await import('./creds');const caller = credsRouter.createCaller({@@ -286,7 +272,9 @@ describe('credsRouter share/publish/unshare', () => {const result = await caller.unshare({ id: 42 });- expect(mockPersonalCredsUnshare).toHaveBeenCalledWith(42);+ expect(mockPersonalCredsUnshare).toHaveBeenCalledWith(42, undefined, {+ orgId: 'workspace:workspace-1',+ });expect(result).toEqual({ id: 42, visibility: 'private' });});diff --git a/apps/server/src/routers/lambda/market/creds.ts b/apps/server/src/routers/lambda/market/creds.tsindex 6c1c939d765..6ae8d110040 100644--- a/apps/server/src/routers/lambda/market/creds.ts+++ b/apps/server/src/routers/lambda/market/creds.ts@@ -1,3 +1,4 @@+import type { UserCredSummary } from '@lobechat/types';import { MarketAPIError, orgRefToPathSegment } from '@lobehub/market-sdk';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -15,6 +16,7 @@ const MARKET_STATUS_TO_TRPC_CODE: Record<number, TRPCError['code']> = {400: 'BAD_REQUEST',403: 'FORBIDDEN',404: 'NOT_FOUND',+ 409: 'CONFLICT',};/**@@ -40,9 +42,9 @@ const credsProcedure = publicProcedure// `ctx.workspaceId` from the raw `X-Workspace-Id` header is NOT trustworthy on// its own (createLambdaContext copies it verbatim, with no membership check).// `cloudWorkspaceAuth` verifies the caller is actually a member before letting- // `workspaceId` through — demoting it to `undefined` otherwise. `share` below- // is the only procedure here that reads `ctx.workspaceId`; this guarantees it- // can never target a workspace the caller doesn't belong to.+ // `workspaceId` through — demoting it to `undefined` otherwise. `share`,+ // `publish` and `unshare` below target `ctx.workspaceId`; this guarantees+ // they can never reach a workspace the caller doesn't belong to..use(cloudWorkspaceAuth).use(marketUserInfo).use(requireMarketAuth)@@ -58,6 +60,14 @@ const credsProcedure = publicProcedure});const credsManageProcedure = credsProcedure.use(withRbacPermission('workspace:update:all'));+/**+ * The active workspace's organization, for share operations that act on one+ * of a credential's shares. Outside a workspace no org is sent, which Market+ * accepts while the credential has a single share.+ */+const shareTarget = (ctx: { workspaceId?: string | null }) =>+ ctx.workspaceId ? { orgId: orgRefToPathSegment({ workspaceId: ctx.workspaceId }) } : {};+export const credsRouter = router({// Create file credentialcreateFile: credsManageProcedure@@ -271,13 +281,16 @@ export const credsRouter = router({}}),- // Publish a draft-linked credential (visibility 'private') so the rest of- // the workspace's organization can see it. Owner-only — no orgId needed,- // the credential is already linked from a prior `share` call.+ // Publish a privately shared credential so every member of the active+ // workspace can use it. Owner-only.publish: credsProcedure.input(z.object({ id: z.number() })).mutation(async ({ ctx, input }) => {log('publish input: id=%d', input.id);try {- const result = await ctx.marketService.market.creds.publish(input.id);+ const result = await ctx.marketService.market.creds.publish(+ input.id,+ undefined,+ shareTarget(ctx),+ );log('publish success: id=%d', result.id);return result;} catch (error) {@@ -290,8 +303,8 @@ export const credsRouter = router({// workspace's Market organization. Always targets `ctx.workspaceId` — never// accepts an org id from client input — so `cloudWorkspaceAuth`'s membership// check (above) guarantees a caller can never share into a workspace they- // don't belong to. Re-callable to change `visibility` on an already-shared- // credential (Market's `shareCred` unconditionally overwrites).+ // don't belong to. A credential can be shared into several workspaces;+ // calling again for the same one changes that share's `visibility`.share: credsProcedure.input(z.object({@@ -320,12 +333,16 @@ export const credsRouter = router({}}),- // Unshare a credential from its organization (flips back to private,- // clears the link). Does not delete the credential.+ // Remove a credential's share into the active workspace. Does not delete+ // the credential. Its owner, or an admin of that workspace, may call it.unshare: credsProcedure.input(z.object({ id: z.number() })).mutation(async ({ ctx, input }) => {log('unshare input: id=%d', input.id);try {- const result = await ctx.marketService.market.creds.unshare(input.id);+ const result = await ctx.marketService.market.creds.unshare(+ input.id,+ undefined,+ shareTarget(ctx),+ );log('unshare success: id=%d', result.id);return result;} catch (error) {@@ -408,7 +425,7 @@ export const credsRouter = router({}),// List all credentials- list: credsProcedure.query(async ({ ctx }) => {+ list: credsProcedure.query(async ({ ctx }): Promise<{ data?: UserCredSummary[] }> => {log('list called');try {@@ -417,38 +434,15 @@ export const credsRouter = router({if (!ctx.workspaceId) return result;- // A personal credential carries at most one `organizationAccountId` link- // at a time (sharing again just overwrites it) — so `organizationAccountId- // != null` alone can't tell the frontend "shared to *this* workspace" from- // "shared to some other workspace I visited previously". Cross-reference- // against the active workspace's own merged view (which already lists the- // caller's shared/draft-linked credentials by id) to scope it correctly.- // Best-effort: if the workspace has no Market org yet (Community Profile- // not set up), don't fail the whole personal list over it — just skip- // the enrichment.- try {- const orgList = await ctx.marketService.market.organizations- .creds({ workspaceId: ctx.workspaceId })- .list();- // `ownerType` is a real field on the Market API response, but the- // installed @lobehub/market-sdk's UserCredSummary type hasn't caught- // up to it yet — same gap as `injectForSkill` below.- const activeWorkspaceCredIds = new Set(- (orgList.data as Array<{ id: number; ownerType?: string }> | undefined)- ?.filter((c) => c.ownerType === 'user')- .map((c) => c.id) ?? [],- );-- return {- data: result.data?.map((cred) => ({- ...cred,- sharedToActiveWorkspace: activeWorkspaceCredIds.has(cred.id),- })),- };- } catch (orgListError) {- log('list: failed to resolve active-workspace share scope: %O', orgListError);- return result;- }+ const workspaceId = ctx.workspaceId;+ return {+ data: result.data?.map((cred) => ({+ ...cred,+ sharedToActiveWorkspace: !!cred.shares?.some(+ (share) => share.workspaceId === workspaceId,+ ),+ })),+ };} catch (error) {log('list error: %O', error);throw new TRPCError({diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex 6b27bcbec68..ff4532e4c29 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "لا توجد اتصالات OAuth متاحة. يرجى توصيل حساب أولاً.","creds.orgSetupRequired": "لم يتم إعداد ملف تعريف المجتمع بعد. يرجى إكمال إعداد ملف تعريف مجتمع مساحة العمل لإدارة بيانات الاعتماد.","creds.owner.sharedBy": "تمت المشاركة بواسطة {{name}}",- "creds.personalSection.desc": "هذه هي بيانات الاعتماد الخاصة بك. قم بتفعيل المشاركة لجعلها متاحة لهذه مساحة العمل.","creds.share.error": "فشل في تحديث المشاركة لهذه البيانات. يرجى المحاولة مرة أخرى.",- "creds.share.toggle": "شارك مع مساحة العمل هذه",- "creds.share.visibility.private": "خاص",- "creds.share.visibility.public": "عام","creds.signIn": "تسجيل الدخول إلى السوق","creds.signInRequired": "يرجى تسجيل الدخول إلى السوق لإدارة بيانات الاعتماد الخاصة بك","creds.table.actions": "الإجراءات",@@ -354,7 +350,6 @@"creds.table.neverUsed": "لم يتم الاستخدام","creds.table.preview": "معاينة","creds.table.type": "النوع",- "creds.tabs.personal": "شخصي","creds.tabs.workspace": "مكان العمل","creds.typeDesc.file": "تحميل ملفات بيانات الاعتماد مثل حسابات الخدمة أو الشهادات","creds.typeDesc.kv-env": "تخزين مفاتيح API والرموز كمتغيرات بيئية",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "إعادة المحاولة","heterogeneousStatus.cloud.tokenSave": "حفظ","heterogeneousStatus.cloud.tokenSaveError": "فشل في حفظ رمز Claude Code. يرجى المحاولة مرة أخرى.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "تمت مشاركة رمز Claude Code الشخصي الخاص بك مع مساحة عمل أخرى. حفظ رمز هنا ينقله إلى مساحة العمل هذه، ولن تتمكن عمليات السحابة في مساحة العمل الأخرى من استخدامه بعد الآن.","heterogeneousStatus.cloud.tokenTypeMismatch": "يوجد بالفعل اعتماد بمفتاح CLAUDE_CODE_OAUTH_TOKEN من نوع مختلف. قم بإزالته أو إعادة تسميته في الاعتمادات، ثم حاول الحفظ مرة أخرى.","heterogeneousStatus.command.edit": "تحرير الأمر","heterogeneousStatus.command.label": "أمر التشغيل",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex 7dbc1f515c0..94990c4bc36 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Няма налични OAuth връзки. Моля, свържете акаунт първо.","creds.orgSetupRequired": "Профилът на общността не е настроен. Моля, завършете настройката на профила на общността на работното пространство, за да управлявате идентификационните данни.","creds.owner.sharedBy": "Споделено от {{name}}",- "creds.personalSection.desc": "Това са вашите собствени идентификационни данни. Включете споделянето, за да направите една от тях достъпна за това работно пространство.","creds.share.error": "Неуспешно актуализиране на споделянето за тези идентификационни данни. Моля, опитайте отново.",- "creds.share.toggle": "Сподели с това работно пространство",- "creds.share.visibility.private": "Лично",- "creds.share.visibility.public": "Публично","creds.signIn": "Влезте в Market","creds.signInRequired": "Моля, влезте в Market, за да управлявате вашите идентификатори","creds.table.actions": "Действия",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Никога","creds.table.preview": "Преглед","creds.table.type": "Тип",- "creds.tabs.personal": "Лични","creds.tabs.workspace": "Работно пространство","creds.typeDesc.file": "Качете файлове с идентификатори като акаунти за услуги или сертификати","creds.typeDesc.kv-env": "Съхранявайте API ключове и токени като променливи на средата",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Опитайте отново","heterogeneousStatus.cloud.tokenSave": "Запазване","heterogeneousStatus.cloud.tokenSaveError": "Неуспешно запазване на Claude Code токена. Моля, опитайте отново.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Вашият личен Claude Code токен е споделен с друго работно пространство. Запазването на токен тук ще го премести в това работно пространство, и облачните изпълнения в другото работно пространство вече няма да могат да го използват.","heterogeneousStatus.cloud.tokenTypeMismatch": "Удостоверение с ключ CLAUDE_CODE_OAUTH_TOKEN вече съществува с различен тип. Премахнете или преименувайте го в Удостоверения, след това запазете отново.","heterogeneousStatus.command.edit": "Редактиране на команда","heterogeneousStatus.command.label": "Команда за стартиране",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex 375dc425146..176f809eb19 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Keine OAuth-Verbindungen verfügbar. Bitte verbinden Sie zuerst ein Konto.","creds.orgSetupRequired": "Community-Profil noch nicht eingerichtet. Bitte richten Sie das Community-Profil des Arbeitsbereichs ein, um Anmeldedaten zu verwalten.","creds.owner.sharedBy": "Geteilt von {{name}}",- "creds.personalSection.desc": "Dies sind Ihre eigenen Anmeldedaten. Aktivieren Sie die Freigabe, um sie in diesem Arbeitsbereich verfügbar zu machen.","creds.share.error": "Freigabe für diese Anmeldedaten konnte nicht aktualisiert werden. Bitte versuchen Sie es erneut.",- "creds.share.toggle": "Für diesen Arbeitsbereich freigeben",- "creds.share.visibility.private": "Privat",- "creds.share.visibility.public": "Öffentlich","creds.signIn": "Im Market anmelden","creds.signInRequired": "Bitte melden Sie sich im Market an, um Ihre Berechtigungen zu verwalten","creds.table.actions": "Aktionen",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Nie","creds.table.preview": "Vorschau","creds.table.type": "Typ",- "creds.tabs.personal": "Persönlich","creds.tabs.workspace": "Arbeitsbereich","creds.typeDesc.file": "Berechtigungsdateien wie Servicekonten oder Zertifikate hochladen","creds.typeDesc.kv-env": "API-Schlüssel und Tokens als Umgebungsvariablen speichern",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Erneut versuchen","heterogeneousStatus.cloud.tokenSave": "Speichern","heterogeneousStatus.cloud.tokenSaveError": "Das Claude Code-Token konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Ihr persönliches Claude Code-Token ist mit einem anderen Arbeitsbereich geteilt. Wenn Sie ein Token hier speichern, wird es in diesen Arbeitsbereich verschoben, und Cloud-Ausführungen im anderen Arbeitsbereich können es nicht mehr verwenden.","heterogeneousStatus.cloud.tokenTypeMismatch": "Ein Berechtigungsnachweis mit dem Schlüssel CLAUDE_CODE_OAUTH_TOKEN existiert bereits mit einem anderen Typ. Entfernen oder benennen Sie ihn in Berechtigungen um und speichern Sie erneut.","heterogeneousStatus.command.edit": "Befehl bearbeiten","heterogeneousStatus.command.label": "Startbefehl",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 575668de73b..c75a22d7c1f 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -311,6 +311,11 @@"creds.createModal.title": "Create Credential","creds.edit.title": "Edit Credential","creds.empty": "No credentials configured yet",+ "creds.errors.createFailed": "Failed to create the credential. Please try again.",+ "creds.errors.multiOrgShareDisabled": "Sharing one credential into several workspaces is not available yet. Remove its other share first.",+ "creds.errors.privateCredExists": "You already have a private credential with this key in this workspace. Remove it before making this one private.",+ "creds.errors.privateCredsDisabled": "Private workspace credentials are not available yet. Please try again later.",+ "creds.errors.publicCredExists": "This workspace already shares a credential with this key. Remove it before publishing this one.","creds.file.authRequired": "Please sign in to the Market first","creds.file.uploadFailed": "File upload failed","creds.file.uploadSuccess": "File uploaded successfully",@@ -339,12 +344,28 @@"creds.form.values": "Key-Value Pairs","creds.oauth.noConnections": "No OAuth connections available. Please connect an account first.","creds.orgSetupRequired": "Community Profile not set up yet. Please complete the workspace Community Profile setup to manage credentials.",+ "creds.owner.fromPersonal": "From your personal account","creds.owner.sharedBy": "Shared by {{name}}",- "creds.personalSection.desc": "These are your own credentials. Turn on sharing to make one available to this workspace.",+ "creds.privateSection.desc": "Only you can see and use these credentials in this workspace. Publish one to let every member use it.",+ "creds.privateSection.empty": "No private credentials yet",+ "creds.share.alreadyShared": "Shared",+ "creds.share.badge": "Shared to {{count}} workspaces",+ "creds.share.confirm": "Share",+ "creds.share.empty": "You haven't joined any workspace yet.","creds.share.error": "Failed to update sharing for this credential. Please try again.",- "creds.share.toggle": "Share to workspace",- "creds.share.visibility.private": "Private",- "creds.share.visibility.public": "Public",+ "creds.share.menu": "Share to Workspace…",+ "creds.share.modalDesc": "Share this credential into a workspace. It stays in your account, and you can stop sharing at any time.",+ "creds.share.modalTitle": "Share Credential to Workspace",+ "creds.share.revoke": "Stop Sharing",+ "creds.share.revokeConfirmDesc": "Agent runs in that workspace will no longer be able to use it. The credential stays in your account.",+ "creds.share.revokeConfirmTitle": "Stop sharing to \"{{name}}\"?",+ "creds.share.selectPlaceholder": "Select a workspace",+ "creds.share.sharedLabel": "Shared to",+ "creds.share.success": "Shared to {{name}}",+ "creds.share.targetLabel": "Share to",+ "creds.share.unshareConfirmDesc": "Agent runs in this workspace will no longer be able to use it. The credential stays in its owner's personal account.",+ "creds.share.unshareConfirmTitle": "Stop sharing this credential to the workspace?",+ "creds.share.viewerHint": "Viewers can't share credentials","creds.signIn": "Sign In to Market","creds.signInRequired": "Please sign in to the Market to manage your credentials","creds.table.actions": "Actions",@@ -354,7 +375,7 @@"creds.table.neverUsed": "Never","creds.table.preview": "Preview","creds.table.type": "Type",- "creds.tabs.personal": "Personal",+ "creds.tabs.private": "Private","creds.tabs.workspace": "Workspace","creds.typeDesc.file": "Upload credential files like service accounts or certificates","creds.typeDesc.kv-env": "Store API keys and tokens as environment variables",@@ -371,6 +392,9 @@"creds.view.title": "View Credential: {{name}}","creds.view.values": "Credential Values","creds.view.warning": "These values are sensitive. Do not share them with others.",+ "creds.viewerHint": "Viewers can't create credentials",+ "creds.visibility.publish": "Publish to Workspace",+ "creds.visibility.publishConfirmTitle": "Publish this credential to the workspace?","creds.workspaceSection.desc": "Credentials available to everyone in this workspace, including credentials shared by members.","danger.reset.action": "Reset Now","danger.reset.confirm": "Reset all settings?",@@ -925,7 +949,6 @@"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",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex 7f2a92a98f9..0724c4e60da 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "No hay conexiones OAuth disponibles. Por favor, conecte una cuenta primero.","creds.orgSetupRequired": "El perfil de la comunidad no está configurado aún. Por favor, complete la configuración del perfil de la comunidad del espacio de trabajo para gestionar las credenciales.","creds.owner.sharedBy": "Compartido por {{name}}",- "creds.personalSection.desc": "Estas son tus propias credenciales. Activa el uso compartido para que estén disponibles en este espacio de trabajo.","creds.share.error": "No se pudo actualizar el uso compartido de esta credencial. Por favor, inténtalo de nuevo.",- "creds.share.toggle": "Compartir con este espacio de trabajo",- "creds.share.visibility.private": "Privado",- "creds.share.visibility.public": "Público","creds.signIn": "Iniciar Sesión en el Mercado","creds.signInRequired": "Por favor, inicie sesión en el Mercado para gestionar sus credenciales","creds.table.actions": "Acciones",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Nunca","creds.table.preview": "Vista Previa","creds.table.type": "Tipo",- "creds.tabs.personal": "Personal","creds.tabs.workspace": "Espacio de trabajo","creds.typeDesc.file": "Cargue archivos de credenciales como cuentas de servicio o certificados","creds.typeDesc.kv-env": "Almacene claves API y tokens como variables de entorno",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Reintentar","heterogeneousStatus.cloud.tokenSave": "Guardar","heterogeneousStatus.cloud.tokenSaveError": "No se pudo guardar el token de Claude Code. Por favor, inténtalo nuevamente.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Tu token personal de Claude Code está compartido con otro espacio de trabajo. Guardar un token aquí lo moverá a este espacio de trabajo, y las ejecuciones en la nube en el otro espacio de trabajo ya no podrán usarlo.","heterogeneousStatus.cloud.tokenTypeMismatch": "Ya existe una credencial con la clave CLAUDE_CODE_OAUTH_TOKEN de un tipo diferente. Elimínala o cámbiale el nombre en Credenciales, luego guarda nuevamente.","heterogeneousStatus.command.edit": "Editar comando","heterogeneousStatus.command.label": "Comando de inicio",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex 269b95c2aa3..04d406d5847 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "هیچ اتصال OAuth موجود نیست. لطفاً ابتدا یک حساب متصل کنید.","creds.orgSetupRequired": "پروفایل انجمن هنوز تنظیم نشده است. لطفاً تنظیمات پروفایل انجمن فضای کاری را برای مدیریت اعتبارنامهها تکمیل کنید.","creds.owner.sharedBy": "به اشتراک گذاشته شده توسط {{name}}",- "creds.personalSection.desc": "اینها اعتبارنامههای شخصی شما هستند. با روشن کردن اشتراکگذاری، یکی از آنها را برای این فضای کاری در دسترس قرار دهید.","creds.share.error": "بهروزرسانی اشتراکگذاری برای این اعتبارنامه ناموفق بود. لطفاً دوباره تلاش کنید.",- "creds.share.toggle": "اشتراکگذاری با این فضای کاری",- "creds.share.visibility.private": "خصوصی",- "creds.share.visibility.public": "عمومی","creds.signIn": "ورود به بازار","creds.signInRequired": "لطفاً برای مدیریت اعتبارنامههای خود وارد بازار شوید","creds.table.actions": "اقدامات",@@ -354,7 +350,6 @@"creds.table.neverUsed": "هرگز","creds.table.preview": "پیشنمایش","creds.table.type": "نوع",- "creds.tabs.personal": "شخصی","creds.tabs.workspace": "محیط کاری","creds.typeDesc.file": "فایلهای اعتبارنامه مانند حسابهای سرویس یا گواهیها را بارگذاری کنید","creds.typeDesc.kv-env": "کلیدهای API و توکنها را به عنوان متغیرهای محیطی ذخیره کنید",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "دوباره تلاش کنید","heterogeneousStatus.cloud.tokenSave": "ذخیره","heterogeneousStatus.cloud.tokenSaveError": "ذخیره توکن Claude Code ناموفق بود. لطفاً دوباره تلاش کنید.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "توکن شخصی Claude Code شما به یک فضای کاری دیگر به اشتراک گذاشته شده است. ذخیره یک توکن در اینجا آن را به این فضای کاری منتقل میکند و اجراهای ابری در فضای کاری دیگر دیگر نمیتوانند از آن استفاده کنند.","heterogeneousStatus.cloud.tokenTypeMismatch": "یک اعتبارنامه با کلید CLAUDE_CODE_OAUTH_TOKEN قبلاً با نوعی متفاوت وجود دارد. آن را در بخش Credentials حذف یا تغییر نام دهید، سپس دوباره ذخیره کنید.","heterogeneousStatus.command.edit": "ویرایش فرمان","heterogeneousStatus.command.label": "فرمان اجرا",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex a3febac6feb..5ab647ea0cc 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Aucune connexion OAuth disponible. Veuillez d'abord connecter un compte.","creds.orgSetupRequired": "Profil Communautaire non encore configuré. Veuillez compléter la configuration du Profil Communautaire de l'espace de travail pour gérer les identifiants.","creds.owner.sharedBy": "Partagé par {{name}}",- "creds.personalSection.desc": "Ce sont vos propres identifiants. Activez le partage pour en rendre un disponible à cet espace de travail.","creds.share.error": "Échec de la mise à jour du partage pour cet identifiant. Veuillez réessayer.",- "creds.share.toggle": "Partager avec cet espace de travail",- "creds.share.visibility.private": "Privé",- "creds.share.visibility.public": "Public","creds.signIn": "Se connecter au Marché","creds.signInRequired": "Veuillez vous connecter au Marché pour gérer vos informations d'identification","creds.table.actions": "Actions",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Jamais","creds.table.preview": "Aperçu","creds.table.type": "Type",- "creds.tabs.personal": "Personnel","creds.tabs.workspace": "Espace de travail","creds.typeDesc.file": "Téléchargez des fichiers d'identification comme des comptes de service ou des certificats","creds.typeDesc.kv-env": "Stockez des clés API et des jetons en tant que variables d'environnement",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Réessayer","heterogeneousStatus.cloud.tokenSave": "Sauvegarder","heterogeneousStatus.cloud.tokenSaveError": "Échec de l'enregistrement du jeton Claude Code. Veuillez réessayer.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Votre jeton personnel Claude Code est partagé avec un autre espace de travail. Enregistrer un jeton ici le déplace vers cet espace de travail, et les exécutions cloud dans l'autre espace de travail ne pourront plus l'utiliser.","heterogeneousStatus.cloud.tokenTypeMismatch": "Un identifiant avec la clé CLAUDE_CODE_OAUTH_TOKEN existe déjà avec un type différent. Supprimez-le ou renommez-le dans Identifiants, puis enregistrez à nouveau.","heterogeneousStatus.command.edit": "Modifier la commande","heterogeneousStatus.command.label": "Commande de lancement",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex f8122ad1e52..24659bf3516 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Nessuna connessione OAuth disponibile. Connetti prima un account.","creds.orgSetupRequired": "Profilo della comunità non ancora configurato. Completa la configurazione del profilo della comunità del workspace per gestire le credenziali.","creds.owner.sharedBy": "Condiviso da {{name}}",- "creds.personalSection.desc": "Queste sono le tue credenziali personali. Attiva la condivisione per renderle disponibili a questo workspace.","creds.share.error": "Impossibile aggiornare la condivisione per questa credenziale. Riprova.",- "creds.share.toggle": "Condividi con questo workspace",- "creds.share.visibility.private": "Privato",- "creds.share.visibility.public": "Pubblico","creds.signIn": "Accedi al Market","creds.signInRequired": "Effettua l'accesso al Market per gestire le tue credenziali","creds.table.actions": "Azioni",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Mai","creds.table.preview": "Anteprima","creds.table.type": "Tipo",- "creds.tabs.personal": "Personale","creds.tabs.workspace": "Spazio di lavoro","creds.typeDesc.file": "Carica file di credenziali come account di servizio o certificati","creds.typeDesc.kv-env": "Memorizza chiavi API e token come variabili d'ambiente",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Riprova","heterogeneousStatus.cloud.tokenSave": "Salva","heterogeneousStatus.cloud.tokenSaveError": "Impossibile salvare il token di Claude Code. Per favore riprova.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Il tuo token personale di Claude Code è condiviso con un altro spazio di lavoro. Salvare un token qui lo sposterà in questo spazio di lavoro, e le esecuzioni cloud nell'altro spazio di lavoro non potranno più utilizzarlo.","heterogeneousStatus.cloud.tokenTypeMismatch": "Una credenziale con la chiave CLAUDE_CODE_OAUTH_TOKEN esiste già con un tipo diverso. Rimuovila o rinominala in Credenziali, quindi salva di nuovo.","heterogeneousStatus.command.edit": "Modifica comando","heterogeneousStatus.command.label": "Comando di avvio",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex 03e30aa8668..072585c73ff 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "利用可能なOAuth接続がありません。まずアカウントを接続してください。","creds.orgSetupRequired": "コミュニティプロファイルがまだ設定されていません。資格情報を管理するには、ワークスペースのコミュニティプロファイル設定を完了してください。","creds.owner.sharedBy": "{{name}} によって共有されました",- "creds.personalSection.desc": "これらはあなた自身の資格情報です。共有をオンにして、このワークスペースで利用可能にしてください。","creds.share.error": "この資格情報の共有を更新できませんでした。もう一度お試しください。",- "creds.share.toggle": "このワークスペースで共有",- "creds.share.visibility.private": "非公開",- "creds.share.visibility.public": "公開","creds.signIn": "マーケットにサインイン","creds.signInRequired": "資格情報を管理するにはマーケットにサインインしてください","creds.table.actions": "操作",@@ -354,7 +350,6 @@"creds.table.neverUsed": "未使用","creds.table.preview": "プレビュー","creds.table.type": "タイプ",- "creds.tabs.personal": "個人","creds.tabs.workspace": "作業スペース","creds.typeDesc.file": "サービスアカウントや証明書などの資格情報ファイルをアップロード","creds.typeDesc.kv-env": "APIキーやトークンを環境変数として保存",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "再試行","heterogeneousStatus.cloud.tokenSave": "保存","heterogeneousStatus.cloud.tokenSaveError": "Claude Codeトークンの保存に失敗しました。もう一度お試しください。",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "個人用Claude Codeトークンは別のワークスペースに共有されています。ここでトークンを保存すると、このワークスペースに移動され、他のワークスペースでのクラウド実行では使用できなくなります。","heterogeneousStatus.cloud.tokenTypeMismatch": "キーCLAUDE_CODE_OAUTH_TOKENを持つ資格情報が既に異なるタイプで存在します。資格情報で削除または名前を変更してから、再度保存してください。","heterogeneousStatus.command.edit": "コマンドを編集","heterogeneousStatus.command.label": "起動コマンド",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex 40dcbe4f0df..3d4502a8159 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "사용 가능한 OAuth 연결이 없습니다. 먼저 계정을 연결하세요.","creds.orgSetupRequired": "커뮤니티 프로필이 아직 설정되지 않았습니다. 자격 증명을 관리하려면 워크스페이스 커뮤니티 프로필 설정을 완료하세요.","creds.owner.sharedBy": "{{name}}님이 공유함",- "creds.personalSection.desc": "이것은 귀하의 개인 자격 증명입니다. 공유를 활성화하여 이 워크스페이스에서 사용할 수 있도록 설정하세요.","creds.share.error": "이 자격 증명의 공유를 업데이트하지 못했습니다. 다시 시도하세요.",- "creds.share.toggle": "이 워크스페이스에 공유",- "creds.share.visibility.private": "비공개",- "creds.share.visibility.public": "공개","creds.signIn": "마켓에 로그인","creds.signInRequired": "자격 증명을 관리하려면 마켓에 로그인하세요","creds.table.actions": "작업",@@ -354,7 +350,6 @@"creds.table.neverUsed": "사용 안 함","creds.table.preview": "미리보기","creds.table.type": "유형",- "creds.tabs.personal": "개인","creds.tabs.workspace": "작업 공간","creds.typeDesc.file": "서비스 계정 또는 인증서와 같은 자격 증명 파일 업로드","creds.typeDesc.kv-env": "API 키와 토큰을 환경 변수로 저장",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "다시 시도","heterogeneousStatus.cloud.tokenSave": "저장","heterogeneousStatus.cloud.tokenSaveError": "Claude Code 토큰을 저장하지 못했습니다. 다시 시도해 주세요.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "개인 Claude Code 토큰이 다른 작업 공간에 공유되어 있습니다. 여기에서 토큰을 저장하면 이 작업 공간으로 이동되며, 다른 작업 공간에서는 더 이상 사용할 수 없습니다.","heterogeneousStatus.cloud.tokenTypeMismatch": "CLAUDE_CODE_OAUTH_TOKEN 키를 가진 자격 증명이 이미 다른 유형으로 존재합니다. 자격 증명에서 제거하거나 이름을 변경한 후 다시 저장하세요.","heterogeneousStatus.command.edit": "명령어 편집","heterogeneousStatus.command.label": "실행 명령어",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex 9fa75c8bcce..a9ea79d38d0 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Geen OAuth-verbindingen beschikbaar. Koppel eerst een account.","creds.orgSetupRequired": "Communityprofiel nog niet ingesteld. Voltooi de Communityprofielinstelling van de werkruimte om referenties te beheren.","creds.owner.sharedBy": "Gedeeld door {{name}}",- "creds.personalSection.desc": "Dit zijn jouw eigen referenties. Zet delen aan om er één beschikbaar te maken voor deze werkruimte.","creds.share.error": "Het bijwerken van delen voor deze referentie is mislukt. Probeer het opnieuw.",- "creds.share.toggle": "Delen met deze werkruimte",- "creds.share.visibility.private": "Privé",- "creds.share.visibility.public": "Openbaar","creds.signIn": "Inloggen op Market","creds.signInRequired": "Log in op de Market om uw referenties te beheren","creds.table.actions": "Acties",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Nooit","creds.table.preview": "Voorbeeld","creds.table.type": "Type",- "creds.tabs.personal": "Persoonlijk","creds.tabs.workspace": "Werkruimte","creds.typeDesc.file": "Upload referentiebestanden zoals serviceaccounts of certificaten","creds.typeDesc.kv-env": "Sla API-sleutels en tokens op als omgevingsvariabelen",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Opnieuw proberen","heterogeneousStatus.cloud.tokenSave": "Opslaan","heterogeneousStatus.cloud.tokenSaveError": "Het opslaan van het Claude Code-token is mislukt. Probeer het opnieuw.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Je persoonlijke Claude Code-token is gedeeld met een andere werkruimte. Het opslaan van een token hier verplaatst het naar deze werkruimte, en cloud-runs in de andere werkruimte kunnen het niet langer gebruiken.","heterogeneousStatus.cloud.tokenTypeMismatch": "Er bestaat al een referentie met de sleutel CLAUDE_CODE_OAUTH_TOKEN van een ander type. Verwijder of hernoem deze in Referenties en sla opnieuw op.","heterogeneousStatus.command.edit": "Opdracht bewerken","heterogeneousStatus.command.label": "Opstartopdracht",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex 05f01f5c022..e78bea868e1 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Brak dostępnych połączeń OAuth. Najpierw połącz konto.","creds.orgSetupRequired": "Profil społeczności nie został jeszcze skonfigurowany. Proszę ukończyć konfigurację profilu społeczności w przestrzeni roboczej, aby zarządzać poświadczeniami.","creds.owner.sharedBy": "Udostępnione przez {{name}}",- "creds.personalSection.desc": "To są Twoje własne poświadczenia. Włącz udostępnianie, aby udostępnić je w tej przestrzeni roboczej.","creds.share.error": "Nie udało się zaktualizować udostępniania dla tego poświadczenia. Spróbuj ponownie.",- "creds.share.toggle": "Udostępnij w tej przestrzeni roboczej",- "creds.share.visibility.private": "Prywatne",- "creds.share.visibility.public": "Publiczne","creds.signIn": "Zaloguj się do Marketu","creds.signInRequired": "Proszę zalogować się do Marketu, aby zarządzać poświadczeniami","creds.table.actions": "Akcje",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Nigdy","creds.table.preview": "Podgląd","creds.table.type": "Typ",- "creds.tabs.personal": "Osobiste","creds.tabs.workspace": "Przestrzeń robocza","creds.typeDesc.file": "Prześlij pliki poświadczeń, takie jak konta usługowe lub certyfikaty","creds.typeDesc.kv-env": "Przechowuj klucze API i tokeny jako zmienne środowiskowe",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Ponów próbę","heterogeneousStatus.cloud.tokenSave": "Zapisz","heterogeneousStatus.cloud.tokenSaveError": "Nie udało się zapisać tokenu Claude Code. Spróbuj ponownie.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Twój osobisty token Claude Code jest udostępniony w innym obszarze roboczym. Zapisanie tokenu tutaj przenosi go do tego obszaru roboczego, a uruchomienia w chmurze w innym obszarze roboczym nie będą mogły go już używać.","heterogeneousStatus.cloud.tokenTypeMismatch": "Poświadczenie z kluczem CLAUDE_CODE_OAUTH_TOKEN już istnieje z innym typem. Usuń je lub zmień jego nazwę w Poświadczeniach, a następnie zapisz ponownie.","heterogeneousStatus.command.edit": "Edytuj polecenie","heterogeneousStatus.command.label": "Polecenie startowe",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex f0daea6553e..7fce71bf884 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Nenhuma conexão OAuth disponível. Por favor, conecte uma conta primeiro.","creds.orgSetupRequired": "Perfil da Comunidade ainda não configurado. Conclua a configuração do Perfil da Comunidade do workspace para gerenciar credenciais.","creds.owner.sharedBy": "Compartilhado por {{name}}",- "creds.personalSection.desc": "Estas são suas próprias credenciais. Ative o compartilhamento para disponibilizar uma para este workspace.","creds.share.error": "Falha ao atualizar o compartilhamento desta credencial. Por favor, tente novamente.",- "creds.share.toggle": "Compartilhar com este workspace",- "creds.share.visibility.private": "Privado",- "creds.share.visibility.public": "Público","creds.signIn": "Entrar no Market","creds.signInRequired": "Por favor, faça login no Market para gerenciar suas credenciais","creds.table.actions": "Ações",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Nunca","creds.table.preview": "Pré-visualizar","creds.table.type": "Tipo",- "creds.tabs.personal": "Pessoal","creds.tabs.workspace": "Ambiente de trabalho","creds.typeDesc.file": "Envie arquivos de credenciais como contas de serviço ou certificados","creds.typeDesc.kv-env": "Armazene chaves de API e tokens como variáveis de ambiente",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Tentar novamente","heterogeneousStatus.cloud.tokenSave": "Salvar","heterogeneousStatus.cloud.tokenSaveError": "Falha ao salvar o token do Claude Code. Por favor, tente novamente.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Seu token pessoal do Claude Code está compartilhado com outro espaço de trabalho. Salvar um token aqui o move para este espaço de trabalho, e execuções na nuvem no outro espaço de trabalho não poderão mais usá-lo.","heterogeneousStatus.cloud.tokenTypeMismatch": "Uma credencial com a chave CLAUDE_CODE_OAUTH_TOKEN já existe com um tipo diferente. Remova ou renomeie-a em Credenciais e tente salvar novamente.","heterogeneousStatus.command.edit": "Editar comando","heterogeneousStatus.command.label": "Comando de Execução",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 1e44185b302..4e242a5e275 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Нет доступных подключений OAuth. Пожалуйста, сначала подключите учетную запись.","creds.orgSetupRequired": "Профиль сообщества еще не настроен. Пожалуйста, завершите настройку профиля сообщества рабочего пространства, чтобы управлять учетными данными.","creds.owner.sharedBy": "Поделился {{name}}",- "creds.personalSection.desc": "Это ваши личные учетные данные. Включите общий доступ, чтобы сделать их доступными для этого рабочего пространства.","creds.share.error": "Не удалось обновить общий доступ для этих учетных данных. Пожалуйста, попробуйте еще раз.",- "creds.share.toggle": "Поделиться с этим рабочим пространством",- "creds.share.visibility.private": "Приватно",- "creds.share.visibility.public": "Публично","creds.signIn": "Войти в Market","creds.signInRequired": "Пожалуйста, войдите в Market, чтобы управлять вашими учетными данными","creds.table.actions": "Действия",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Никогда","creds.table.preview": "Предпросмотр","creds.table.type": "Тип",- "creds.tabs.personal": "Личное","creds.tabs.workspace": "Рабочее пространство","creds.typeDesc.file": "Загрузите файлы учетных данных, такие как учетные записи сервисов или сертификаты","creds.typeDesc.kv-env": "Сохраните API-ключи и токены в виде переменных окружения",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Повторить попытку","heterogeneousStatus.cloud.tokenSave": "Сохранить","heterogeneousStatus.cloud.tokenSaveError": "Не удалось сохранить токен Claude Code. Пожалуйста, попробуйте снова.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Ваш личный токен Claude Code привязан к другому рабочему пространству. Сохранение токена здесь перенесет его в это рабочее пространство, и облачные запуски в другом рабочем пространстве больше не смогут его использовать.","heterogeneousStatus.cloud.tokenTypeMismatch": "Учетные данные с ключом CLAUDE_CODE_OAUTH_TOKEN уже существуют с другим типом. Удалите или переименуйте их в разделе Учетные данные, затем сохраните снова.","heterogeneousStatus.command.edit": "Редактировать команду","heterogeneousStatus.command.label": "Команда запуска",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex 9cfb9d04cfb..7f17f932808 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Mevcut OAuth bağlantısı yok. Lütfen önce bir hesap bağlayın.","creds.orgSetupRequired": "Topluluk Profili henüz ayarlanmadı. Kimlik bilgilerini yönetmek için lütfen çalışma alanı Topluluk Profili ayarlarını tamamlayın.","creds.owner.sharedBy": "{{name}} tarafından paylaşıldı",- "creds.personalSection.desc": "Bunlar sizin kendi kimlik bilgilerinizdir. Bu çalışma alanında kullanılabilir hale getirmek için paylaşımı açın.","creds.share.error": "Bu kimlik bilgisi için paylaşım güncellenemedi. Lütfen tekrar deneyin.",- "creds.share.toggle": "Bu çalışma alanıyla paylaş",- "creds.share.visibility.private": "Özel",- "creds.share.visibility.public": "Genel","creds.signIn": "Market'e Giriş Yap","creds.signInRequired": "Kimlik bilgilerinizi yönetmek için lütfen Market'e giriş yapın","creds.table.actions": "Eylemler",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Hiçbir Zaman","creds.table.preview": "Önizleme","creds.table.type": "Tür",- "creds.tabs.personal": "Kişisel","creds.tabs.workspace": "Çalışma Alanı","creds.typeDesc.file": "Hizmet hesapları veya sertifikalar gibi kimlik bilgisi dosyalarını yükleyin","creds.typeDesc.kv-env": "API anahtarlarını ve belirteçlerini ortam değişkenleri olarak saklayın",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Tekrar Dene","heterogeneousStatus.cloud.tokenSave": "Kaydet","heterogeneousStatus.cloud.tokenSaveError": "Claude Code tokeni kaydedilemedi. Lütfen tekrar deneyin.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Kişisel Claude Code tokeniniz başka bir çalışma alanına paylaşılmış. Burada bir token kaydetmek, onu bu çalışma alanına taşır ve diğer çalışma alanındaki bulut çalışmaları artık bunu kullanamaz.","heterogeneousStatus.cloud.tokenTypeMismatch": "CLAUDE_CODE_OAUTH_TOKEN anahtarına sahip bir kimlik bilgisi zaten farklı bir türle mevcut. Kimlik Bilgileri'nde bunu kaldırın veya yeniden adlandırın, ardından tekrar kaydedin.","heterogeneousStatus.command.edit": "Komutu düzenle","heterogeneousStatus.command.label": "Komut Başlat",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex cb1858ae760..d2de7936974 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "Không có kết nối OAuth nào. Vui lòng kết nối một tài khoản trước.","creds.orgSetupRequired": "Hồ sơ Cộng đồng chưa được thiết lập. Vui lòng hoàn thành thiết lập Hồ sơ Cộng đồng của không gian làm việc để quản lý thông tin đăng nhập.","creds.owner.sharedBy": "Được chia sẻ bởi {{name}}",- "creds.personalSection.desc": "Đây là thông tin đăng nhập cá nhân của bạn. Bật chia sẻ để làm cho một thông tin đăng nhập có sẵn cho không gian làm việc này.","creds.share.error": "Không thể cập nhật chia sẻ cho thông tin đăng nhập này. Vui lòng thử lại.",- "creds.share.toggle": "Chia sẻ với không gian làm việc này",- "creds.share.visibility.private": "Riêng tư",- "creds.share.visibility.public": "Công khai","creds.signIn": "Đăng Nhập vào Market","creds.signInRequired": "Vui lòng đăng nhập vào Market để quản lý thông tin xác thực của bạn","creds.table.actions": "Hành động",@@ -354,7 +350,6 @@"creds.table.neverUsed": "Chưa bao giờ","creds.table.preview": "Xem trước","creds.table.type": "Loại",- "creds.tabs.personal": "Cá nhân","creds.tabs.workspace": "Không gian làm việc","creds.typeDesc.file": "Tải lên các tệp thông tin xác thực như tài khoản dịch vụ hoặc chứng chỉ","creds.typeDesc.kv-env": "Lưu trữ khóa API và token dưới dạng biến môi trường",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "Thử lại","heterogeneousStatus.cloud.tokenSave": "Lưu","heterogeneousStatus.cloud.tokenSaveError": "Không thể lưu token Claude Code. Vui lòng thử lại.",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "Token Claude Code cá nhân của bạn đã được chia sẻ với một không gian làm việc khác. Lưu một token ở đây sẽ chuyển nó sang không gian làm việc này, và các lần chạy trên đám mây ở không gian làm việc khác sẽ không thể sử dụng nó nữa.","heterogeneousStatus.cloud.tokenTypeMismatch": "Một thông tin xác thực với khóa CLAUDE_CODE_OAUTH_TOKEN đã tồn tại với một loại khác. Xóa hoặc đổi tên nó trong phần Thông tin xác thực, sau đó lưu lại.","heterogeneousStatus.command.edit": "Chỉnh sửa lệnh","heterogeneousStatus.command.label": "Lệnh khởi chạy",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex b976ca9af33..3ee91c9c63c 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -311,6 +311,11 @@"creds.createModal.title": "创建凭证","creds.edit.title": "编辑凭证","creds.empty": "暂无凭证配置",+ "creds.errors.createFailed": "创建凭证失败,请重试。",+ "creds.errors.multiOrgShareDisabled": "暂不支持把同一个凭证共享到多个工作区,请先取消它在其他工作区的共享。",+ "creds.errors.privateCredExists": "你在此工作区已有同一键名的私人凭证,请先移除它再将此凭证设为私人。",+ "creds.errors.privateCredsDisabled": "工作区私人凭证暂未开放,请稍后再试。",+ "creds.errors.publicCredExists": "此工作区已有同一键名的共享凭证,请先移除它再发布此凭证。","creds.file.authRequired": "请先登录 Market","creds.file.uploadFailed": "文件上传失败","creds.file.uploadSuccess": "文件上传成功",@@ -339,12 +344,28 @@"creds.form.values": "键值对","creds.oauth.noConnections": "暂无可用的 OAuth 连接,请先连接账户。","creds.orgSetupRequired": "社区资料尚未设置,请先完成工作区的社区资料设置,再管理凭证。",+ "creds.owner.fromPersonal": "来自个人账号","creds.owner.sharedBy": "由 {{name}} 共享",- "creds.personalSection.desc": "这些是您自己的凭证。开启共享后可让此工作区使用该凭证。",+ "creds.privateSection.desc": "只有你能在此工作区查看和使用这些凭证。发布到工作区后,所有成员都可以使用。",+ "creds.privateSection.empty": "还没有私人凭证",+ "creds.share.alreadyShared": "已共享",+ "creds.share.badge": "已共享到 {{count}} 个工作区",+ "creds.share.confirm": "共享",+ "creds.share.empty": "你还没有加入任何工作区。","creds.share.error": "更新该凭证的共享状态失败,请重试。",- "creds.share.toggle": "共享到工作区",- "creds.share.visibility.private": "私密",- "creds.share.visibility.public": "公开",+ "creds.share.menu": "共享到工作区…",+ "creds.share.modalDesc": "将此凭证共享到工作区。凭证仍保存在你的个人账号中,随时可以取消共享。",+ "creds.share.modalTitle": "共享凭证到工作区",+ "creds.share.revoke": "取消共享",+ "creds.share.revokeConfirmDesc": "该工作区的智能体运行将无法再使用它,凭证仍保留在你的个人账号中。",+ "creds.share.revokeConfirmTitle": "取消共享到「{{name}}」?",+ "creds.share.selectPlaceholder": "选择一个工作区",+ "creds.share.sharedLabel": "已共享到的工作区",+ "creds.share.success": "已共享到 {{name}}",+ "creds.share.targetLabel": "共享至",+ "creds.share.unshareConfirmDesc": "此工作区的智能体运行将无法再使用它,凭证仍保留在所有者的个人账号中。",+ "creds.share.unshareConfirmTitle": "取消将此凭证共享到工作区?",+ "creds.share.viewerHint": "查看者无法共享凭证","creds.signIn": "登录 Market","creds.signInRequired": "请登录 Market 以管理您的凭证","creds.table.actions": "操作",@@ -354,7 +375,7 @@"creds.table.neverUsed": "从未使用","creds.table.preview": "预览","creds.table.type": "类型",- "creds.tabs.personal": "个人",+ "creds.tabs.private": "私人","creds.tabs.workspace": "工作区","creds.typeDesc.file": "上传服务账户或证书等凭证文件","creds.typeDesc.kv-env": "将 API 密钥和令牌存储为环境变量",@@ -371,6 +392,9 @@"creds.view.title": "查看凭证:{{name}}","creds.view.values": "凭证值","creds.view.warning": "这些值是敏感信息,请勿与他人分享。",+ "creds.viewerHint": "查看者无法创建凭证",+ "creds.visibility.publish": "发布到工作区",+ "creds.visibility.publishConfirmTitle": "将此凭证发布到工作区?","creds.workspaceSection.desc": "此工作区所有成员可用的凭证,包含成员共享的凭证。","danger.reset.action": "立即重置","danger.reset.confirm": "确认重置所有设置吗?",@@ -925,7 +949,6 @@"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": "启动指令",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 8d8a656ef0c..b35705f1dd0 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -340,11 +340,7 @@"creds.oauth.noConnections": "沒有可用的 OAuth 連線,請先連接帳戶。","creds.orgSetupRequired": "尚未設定社群檔案。請完成工作區的社群檔案設定以管理憑證。","creds.owner.sharedBy": "由 {{name}} 分享",- "creds.personalSection.desc": "這是您自己的憑證。開啟分享功能以使其可供此工作區使用。","creds.share.error": "更新此憑證的分享狀態失敗。請再試一次。",- "creds.share.toggle": "分享至此工作區",- "creds.share.visibility.private": "私人",- "creds.share.visibility.public": "公開","creds.signIn": "登入市場","creds.signInRequired": "請登入市場以管理您的憑證","creds.table.actions": "操作",@@ -354,7 +350,6 @@"creds.table.neverUsed": "從未使用","creds.table.preview": "預覽","creds.table.type": "類型",- "creds.tabs.personal": "個人","creds.tabs.workspace": "工作空間","creds.typeDesc.file": "上傳憑證檔案,例如服務帳戶或憑證","creds.typeDesc.kv-env": "將 API 金鑰和令牌存儲為環境變數",@@ -922,7 +917,6 @@"heterogeneousStatus.cloud.tokenRetry": "重試","heterogeneousStatus.cloud.tokenSave": "保存","heterogeneousStatus.cloud.tokenSaveError": "無法保存 Claude Code 權杖。請再試一次。",- "heterogeneousStatus.cloud.tokenSharedElsewhere": "您的個人 Claude Code 權杖已分享至另一個工作區。在此處保存權杖將移動至此工作區,且其他工作區的雲端運行將無法再使用它。","heterogeneousStatus.cloud.tokenTypeMismatch": "一個名為 CLAUDE_CODE_OAUTH_TOKEN 的憑證已存在,但類型不同。請在憑證中移除或重新命名,然後再次保存。","heterogeneousStatus.command.edit": "編輯指令","heterogeneousStatus.command.label": "啟動指令",diff --git a/package.json b/package.jsonindex 260c4e5abb7..1fb7201c291 100644--- a/package.json+++ b/package.json@@ -328,7 +328,7 @@"@lobehub/desktop-ipc-typings": "workspace:*","@lobehub/editor": "7.1.0","@lobehub/icons": "^6.13.0",- "@lobehub/market-sdk": "0.43.0",+ "@lobehub/market-sdk": "0.46.0","@lobehub/ui": "^6.9.0","@modelcontextprotocol/client": "~2.4.0","@neondatabase/serverless": "^1.1.0",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 633f8b7a180..734a8f72510 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -527,8 +527,6 @@ export default {'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':@@ -615,23 +613,54 @@ export default {'creds.createModal.title': 'Create Credential','creds.edit.title': 'Edit Credential','creds.empty': 'No credentials configured yet',+ 'creds.errors.createFailed': 'Failed to create the credential. Please try again.',+ 'creds.errors.multiOrgShareDisabled':+ 'Sharing one credential into several workspaces is not available yet. Remove its other share first.',+ 'creds.errors.privateCredExists':+ 'You already have a private credential with this key in this workspace. Remove it before making this one private.',+ 'creds.errors.privateCredsDisabled':+ 'Private workspace credentials are not available yet. Please try again later.',+ 'creds.errors.publicCredExists':+ 'This workspace already shares a credential with this key. Remove it before publishing this one.','creds.file.authRequired': 'Please sign in to the Market first','creds.file.uploadFailed': 'File upload failed','creds.file.uploadSuccess': 'File uploaded successfully','creds.file.uploading': 'Uploading...','creds.orgSetupRequired':'Community Profile not set up yet. Please complete the workspace Community Profile setup to manage credentials.',+ 'creds.owner.fromPersonal': 'From your personal account','creds.owner.sharedBy': 'Shared by {{name}}',- 'creds.personalSection.desc':- 'These are your own credentials. Turn on sharing to make one available to this workspace.',+ 'creds.privateSection.desc':+ 'Only you can see and use these credentials in this workspace. Publish one to let every member use it.',+ 'creds.privateSection.empty': 'No private credentials yet',+ 'creds.share.alreadyShared': 'Shared',+ 'creds.share.badge': 'Shared to {{count}} workspaces',+ 'creds.share.confirm': 'Share',+ 'creds.share.empty': "You haven't joined any workspace yet.",'creds.share.error': 'Failed to update sharing for this credential. Please try again.',- 'creds.share.toggle': 'Share to workspace',- 'creds.share.visibility.private': 'Private',- 'creds.share.visibility.public': 'Public',+ 'creds.share.menu': 'Share to Workspace…',+ 'creds.share.modalDesc':+ 'Share this credential into a workspace. It stays in your account, and you can stop sharing at any time.',+ 'creds.share.modalTitle': 'Share Credential to Workspace',+ 'creds.share.revoke': 'Stop Sharing',+ 'creds.share.revokeConfirmDesc':+ 'Agent runs in that workspace will no longer be able to use it. The credential stays in your account.',+ 'creds.share.revokeConfirmTitle': 'Stop sharing to "{{name}}"?',+ 'creds.share.selectPlaceholder': 'Select a workspace',+ 'creds.share.sharedLabel': 'Shared to',+ 'creds.share.success': 'Shared to {{name}}',+ 'creds.share.targetLabel': 'Share to',+ 'creds.share.unshareConfirmDesc':+ "Agent runs in this workspace will no longer be able to use it. The credential stays in its owner's personal account.",+ 'creds.share.unshareConfirmTitle': 'Stop sharing this credential to the workspace?',+ 'creds.share.viewerHint': "Viewers can't share credentials",'creds.signIn': 'Sign In to Market','creds.signInRequired': 'Please sign in to the Market to manage your credentials',- 'creds.tabs.personal': 'Personal',+ 'creds.tabs.private': 'Private','creds.tabs.workspace': 'Workspace',+ 'creds.viewerHint': "Viewers can't create credentials",+ 'creds.visibility.publish': 'Publish to Workspace',+ 'creds.visibility.publishConfirmTitle': 'Publish this credential to the workspace?','creds.workspaceSection.desc':'Credentials available to everyone in this workspace, including credentials shared by members.','creds.form.addPair': 'Add Key-Value Pair',diff --git a/packages/types/package.json b/packages/types/package.jsonindex e1fa124b6cc..9fcd884af4e 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -15,7 +15,7 @@"test:update": "vitest -u"},"dependencies": {- "@lobehub/market-sdk": "0.43.0",+ "@lobehub/market-sdk": "0.46.0","@lobehub/market-types": "^1.19.0","ajv": "^8.20.0","model-bank": "workspace:*",diff --git a/packages/types/src/creds/index.ts b/packages/types/src/creds/index.tsindex 408b912d40e..9383079d138 100644--- a/packages/types/src/creds/index.ts+++ b/packages/types/src/creds/index.ts@@ -8,8 +8,28 @@ export type CredType = 'kv-env' | 'kv-header' | 'oauth' | 'file';// ===== Credential Summary (for list display) =====+/** One workspace organization a personal credential is shared into. */+export interface CredShareSummary {+ organizationAccountId: number;+ /** Set while `visibility` is 'public': when it was last published. */+ sharedAt?: string;+ /**+ * 'private': linked for the owner's own use in that workspace only.+ * 'public': usable by every member of that workspace.+ */+ visibility: 'private' | 'public';+ /** Cloud workspace the organization mirrors, when it mirrors one. */+ workspaceId?: string;+}+export interface UserCredSummary {createdAt: string;+ /**+ * Market account of the member who created a workspace-owned credential.+ * Unset on personal credentials and on workspace credentials created+ * before creators were recorded (those are admin-managed).+ */+ createdByAccountId?: number;description?: string;// File type specificfileName?: string;@@ -24,9 +44,8 @@ export interface UserCredSummary {oauthProvider?: string;oauthUsername?: string;/**- * Account id of the organization this credential is linked to. Present- * once linked via `share`, regardless of whether `visibility` has been- * flipped to 'public' yet (see `sharedAt`).+ * Organization-scoped responses only: the organization the credential is+ * being viewed in.*/organizationAccountId?: number;/**@@ -45,27 +64,24 @@ export interface UserCredSummary {*/ownerType?: 'organization' | 'user';/**- * Timestamp when `visibility` last became 'public'. Unset while only- * draft-linked (`organizationAccountId` set, `visibility` still 'private').+ * Organization-scoped responses, member-shared credentials only: when the+ * share was last published.*/sharedAt?: string;/**- * Cloud-computed enrichment on personal-scoped list responses only- * (`market.creds.list`, when called with an active workspace context):- * whether `organizationAccountId` actually points at the *current* active- * workspace's organization, as opposed to some other workspace the- * credential was previously shared to. A personal credential can only be- * linked to one organization at a time, so `organizationAccountId != null`- * alone can't distinguish "shared here" from "shared elsewhere" — always- * prefer this field over `organizationAccountId` for workspace-scoped UI.- * Absent entirely outside a workspace context.+ * Personal responses only: whether the credential is shared into the+ * active workspace (derived from `shares`). Absent outside a workspace+ * context.*/sharedToActiveWorkspace?: boolean;+ /** Personal responses only: the workspaces this credential is shared into. */+ shares?: CredShareSummary[];type: CredType;updatedAt: string;/**- * 'private' (default, only the owning account can see/use it) or 'public'- * (shared with organizationAccountId's members).+ * Organization-scoped responses only. 'private': only its creator (a+ * workspace credential) or its owner (a shared personal credential) can+ * use it in this workspace. 'public': every member can.*/visibility?: 'private' | 'public';}diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex 85c1a0b8341..9cde21223af 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -1159,7 +1159,6 @@"src/routes/(main)/(create)/video/features/GenerationFeed/VideoReferenceFrames.tsx","src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx","src/routes/(main)/(create)/video/features/PromptInput/EditingVideoHeader.tsx",- "src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx","src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx","src/routes/(main)/_layout/style.ts","src/routes/(main)/agent/_layout/style.ts",diff --git a/src/features/Settings/creds/features/CreateCredModal/Content.tsx b/src/features/Settings/creds/features/CreateCredModal/Content.tsxindex 07a89128e86..2e93e95ae20 100644--- a/src/features/Settings/creds/features/CreateCredModal/Content.tsx+++ b/src/features/Settings/creds/features/CreateCredModal/Content.tsx@@ -15,13 +15,6 @@ import OAuthCredForm from './OAuthCredForm';const styles = stylex.create({ steps: { marginBlockEnd: '24px' } });export interface CreateCredModalContentProps {- /**- * Bound explicitly by the caller (rendered inline, inside CredsApiProvider)- * instead of read via useCredsApi() here — this content tree is portaled by- * createModal() to a global ModalHost that sits outside CredsApiProvider,- * so a local useCredsApi() call would silently fall back to the personal- * (market.creds) API even on the workspace creds page.- */credsApi: CredsApi;onSuccess?: () => void;}diff --git a/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsxindex 8ee28981573..f1f724cf216 100644--- a/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx+++ b/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx@@ -7,7 +7,8 @@ import { useMutation } from '@tanstack/react-query';import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';-import { type CredsApi } from '../useCredsApi';+import { credErrorKey } from '../credError';+import { createExtras, type CredsApi } from '../useCredsApi';const styles = stylex.create({footer: { display: 'flex', gap: '8px', justifyContent: 'flex-end', marginBlockStart: '24px' },@@ -47,8 +48,12 @@ const FileCredForm: FC<FileCredFormProps> = ({ credsApi, disabled, onBack, onSucfileName,key: values.key,name: values.name,+ ...createExtras(credsApi),});},+ onError: (error) => {+ toast.error(t(credErrorKey(error, 'creds.errors.createFailed')));+ },onSuccess: () => {onSuccess();},diff --git a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsxindex 51aa3b4cfff..8a09c240130 100644--- a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx+++ b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx@@ -1,6 +1,6 @@'use client';-import { Button, Flexbox, Input, InputPassword, TextArea } from '@lobehub/ui';+import { Button, Flexbox, Input, InputPassword, TextArea, toast } from '@lobehub/ui';import { Form, useForm } from '@lobehub/ui/form';import * as stylex from '@stylexjs/stylex';import { useMutation } from '@tanstack/react-query';@@ -8,7 +8,8 @@ import { Minus, Plus } from 'lucide-react';import { type FC } from 'react';import { useTranslation } from 'react-i18next';-import { type CredsApi } from '../useCredsApi';+import { credErrorKey } from '../credError';+import { createExtras, type CredsApi } from '../useCredsApi';const styles = stylex.create({footer: { display: 'flex', gap: '8px', justifyContent: 'flex-end', marginBlockStart: '24px' },@@ -58,8 +59,12 @@ const KVCredForm: FC<KVCredFormProps> = ({ credsApi, type, disabled, onBack, onSname: values.name,type,values: valuesObj,+ ...createExtras(credsApi),});},+ onError: (error) => {+ toast.error(t(credErrorKey(error, 'creds.errors.createFailed')));+ },onSuccess: () => {onSuccess();},diff --git a/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsxindex fb8918297b1..3811d57c488 100644--- a/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx+++ b/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx@@ -1,6 +1,6 @@'use client';-import { Avatar, Button, Empty, Flexbox, Input, Select, Spin, TextArea } from '@lobehub/ui';+import { Avatar, Button, Empty, Flexbox, Input, Select, Spin, TextArea, toast } from '@lobehub/ui';import { Form, useForm } from '@lobehub/ui/form';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';@@ -8,7 +8,8 @@ import { useMutation } from '@tanstack/react-query';import { type FC } from 'react';import { useTranslation } from 'react-i18next';-import { type CredsApi } from '../useCredsApi';+import { credErrorKey } from '../credError';+import { createExtras, type CredsApi } from '../useCredsApi';const styles = stylex.create({connectionOption: { display: 'flex', gap: '8px', alignItems: 'center' },@@ -66,8 +67,12 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ credsApi, disabled, onBack, onSkey: values.key,name: values.name,oauthConnectionId: values.oauthConnectionId,+ ...createExtras(credsApi),});},+ onError: (error) => {+ toast.error(t(credErrorKey(error, 'creds.errors.createFailed')));+ },onSuccess: () => {onSuccess();},diff --git a/src/features/Settings/creds/features/CredItem.tsx b/src/features/Settings/creds/features/CredItem.tsxindex 674f538232e..9f95b79d9c4 100644--- a/src/features/Settings/creds/features/CredItem.tsx+++ b/src/features/Settings/creds/features/CredItem.tsx@@ -5,6 +5,7 @@ import {Avatar,Button,confirmModal,+ type DropdownItem,DropdownMenu,Flexbox,Icon,@@ -24,28 +25,23 @@ import {import { type FC, memo } from 'react';import { useTranslation } from 'react-i18next';-import { usePermission } from '@/hooks/usePermission';-import { styles } from './style';interface CredItemProps {+ /** Whether the view / edit / delete handlers may run; they render disabled otherwise. */+ canManage: boolean;cred: UserCredSummary;+ /** Row-specific actions (publish, share…) listed before view / edit / delete. */+ extraMenuItems?: DropdownItem[];/**- * Extra content rendered before the "..." menu — used by the workspace- * credential page to slot in the personal-credential share toggle without- * duplicating this row's layout.- */- extra?: React.ReactNode;- /**- * Action handlers are optional: omit them all to render a row without the- * "..." menu — e.g. the workspace page's personal tab, where management is- * gated by an owner-only workspace permission the caller's own credentials- * shouldn't answer to, so the menu would only ever render disabled. CRUD- * for those rows lives on the personal settings page instead.+ * Action handlers are optional: omit one to leave its item out. A row with+ * no items renders no "..." menu.*/onDelete?: (id: number) => void;onEdit?: (cred: UserCredSummary) => void;onView?: (cred: UserCredSummary) => void;+ /** Tags shown after the type tag (owner, sharing state). */+ tags?: React.ReactNode;}const typeIcons: Record<string, React.ReactNode> = {@@ -62,115 +58,112 @@ const typeColors: Record<string, string> = {'oauth': 'green',};-const CredItem: FC<CredItemProps> = memo(({ cred, extra, onEdit, onDelete, onView }) => {- const { t } = useTranslation('setting');- const { allowed: canManageCredentials } = usePermission('manage_provider_key');+const CredItem: FC<CredItemProps> = memo(+ ({ canManage, cred, extraMenuItems = [], onEdit, onDelete, onView, tags }) => {+ const { t } = useTranslation('setting');- const handleDelete = () => {- if (!canManageCredentials) return;+ const handleDelete = () => {+ if (!canManage) return;- confirmModal({- content: t('creds.actions.deleteConfirm.content'),- okButtonProps: { danger: true },- okText: t('creds.actions.deleteConfirm.ok'),- onOk: () => onDelete?.(cred.id),- title: t('creds.actions.deleteConfirm.title'),- });- };+ confirmModal({+ content: t('creds.actions.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('creds.actions.deleteConfirm.ok'),+ onOk: () => onDelete?.(cred.id),+ title: t('creds.actions.deleteConfirm.title'),+ });+ };- const canView = canManageCredentials && (cred.type === 'kv-env' || cred.type === 'kv-header');+ const canView = canManage && (cred.type === 'kv-env' || cred.type === 'kv-header');- const menuItems = [- ...(onView && canView- ? [- {- icon: <Icon icon={Eye} />,- key: 'view',- label: t('creds.actions.view'),- onClick: () => onView(cred),- },- ]- : []),- ...(onEdit- ? [- {- icon: <Icon icon={Pencil} />,- key: 'edit',- label: t('creds.actions.edit'),- disabled: !canManageCredentials,- onClick: () => onEdit(cred),- },- ]- : []),- ...(onDelete- ? [- {- danger: true,- disabled: !canManageCredentials,- icon: <Icon icon={Trash2} />,- key: 'delete',- label: t('creds.actions.delete'),- onClick: handleDelete,- },- ]- : []),- ];+ const menuItems: DropdownItem[] = [+ ...extraMenuItems,+ ...(onView && canView+ ? [+ {+ icon: <Icon icon={Eye} />,+ key: 'view',+ label: t('creds.actions.view'),+ onClick: () => onView(cred),+ },+ ]+ : []),+ ...(onEdit+ ? [+ {+ icon: <Icon icon={Pencil} />,+ key: 'edit',+ label: t('creds.actions.edit'),+ disabled: !canManage,+ onClick: () => onEdit(cred),+ },+ ]+ : []),+ ...(onDelete+ ? [+ {+ danger: true,+ disabled: !canManage,+ icon: <Icon icon={Trash2} />,+ key: 'delete',+ label: t('creds.actions.delete'),+ onClick: handleDelete,+ },+ ]+ : []),+ ];- const renderAvatar = () => {- if (cred.type === 'oauth' && cred.oauthAvatar) {- return <Avatar avatar={cred.oauthAvatar} size={32} />;- }- return (- // `display: flex` collapses the inline span's line box so the svg sits- // dead-center in the 48px container instead of on the text baseline.- <span style={{ color: 'var(--lobe-color-text-secondary)', display: 'flex' }}>- {typeIcons[cred.type]}- </span>- );- };+ const renderAvatar = () => {+ if (cred.type === 'oauth' && cred.oauthAvatar) {+ return <Avatar avatar={cred.oauthAvatar} size={32} />;+ }+ return (+ // `display: flex` collapses the inline span's line box so the svg sits+ // dead-center in the 48px container instead of on the text baseline.+ <span style={{ color: 'var(--lobe-color-text-secondary)', display: 'flex' }}>+ {typeIcons[cred.type]}+ </span>+ );+ };- return (- <Flexbox- horizontal- align="center"- className={styles.container}- gap={16}- justify="space-between"- >- <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>- <div className={styles.icon}>{renderAvatar()}</div>- <Flexbox gap={4} style={{ overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span className={styles.title}>{cred.name}</span>- <Tag color={typeColors[cred.type]}>{t(`creds.types.${cred.type}`)}</Tag>- {/* Only populated by organization-scoped list responses (workspaceCreds.list) —- distinguishes a member's shared personal credential from one the org owns directly. */}- {cred.ownerType === 'user' && (- <Tag>{t('creds.owner.sharedBy', { name: cred.ownerDisplayName })}</Tag>- )}- </Flexbox>- <Flexbox horizontal align="center" gap={8}>- <code className={styles.key}>{cred.key}</code>- {cred.description && (- <>- <span style={{ color: 'var(--lobe-color-text-quaternary)' }}>·</span>- <span className={styles.description}>{cred.description}</span>- </>- )}+ return (+ <Flexbox+ horizontal+ align="center"+ className={styles.container}+ gap={16}+ justify="space-between"+ >+ <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>+ <div className={styles.icon}>{renderAvatar()}</div>+ <Flexbox gap={4} style={{ overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8}>+ <span className={styles.title}>{cred.name}</span>+ <Tag color={typeColors[cred.type]}>{t(`creds.types.${cred.type}`)}</Tag>+ {tags}+ </Flexbox>+ <Flexbox horizontal align="center" gap={8}>+ <code className={styles.key}>{cred.key}</code>+ {cred.description && (+ <>+ <span style={{ color: 'var(--lobe-color-text-quaternary)' }}>·</span>+ <span className={styles.description}>{cred.description}</span>+ </>+ )}+ </Flexbox></Flexbox></Flexbox>+ <Flexbox horizontal align="center" gap={8} onClick={stopPropagation}>+ {menuItems.length > 0 && (+ <DropdownMenu items={menuItems} placement="bottomRight">+ <Button icon={MoreHorizontalIcon} />+ </DropdownMenu>+ )}+ </Flexbox></Flexbox>- <Flexbox horizontal align="center" gap={8} onClick={stopPropagation}>- {extra}- {menuItems.length > 0 && (- <DropdownMenu items={menuItems} placement="bottomRight">- <Button disabled={!canManageCredentials} icon={MoreHorizontalIcon} />- </DropdownMenu>- )}- </Flexbox>- </Flexbox>- );-});+ );+ },+);CredItem.displayName = 'CredItem';diff --git a/src/features/Settings/creds/features/CredsList.tsx b/src/features/Settings/creds/features/CredsList.tsxindex 45ba6a76f6c..64a4a4a25d4 100644--- a/src/features/Settings/creds/features/CredsList.tsx+++ b/src/features/Settings/creds/features/CredsList.tsx@@ -1,44 +1,41 @@'use client';import { type UserCredSummary } from '@lobechat/types';-import { Button, Empty, Flexbox } from '@lobehub/ui';+import { Empty, Flexbox, Icon, Tag } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import { useMutation } from '@tanstack/react-query';-import { TRPCClientError } from '@trpc/client';-import { LogIn } from 'lucide-react';+import { Share2 } from 'lucide-react';import { type FC } from 'react';import { useTranslation } from 'react-i18next';+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';import AsyncBoundary from '@/components/AsyncBoundary';import ListSkeleton from '@/components/ListSkeleton';import { usePermission } from '@/hooks/usePermission';import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';-import { credsApiForRow, isActionableCredRow } from './credAccess';import CredItem from './CredItem';import { createEditCredModal } from './EditCredModal';-import { defaultCredsApi, useCredsApi } from './useCredsApi';+import MarketSignInGate from './MarketSignInGate';+import { openShareCredModal } from './ShareCredModal';+import { personalCredsApi as credsApi } from './useCredsApi';import { createViewCredModal } from './ViewCredModal';const styles = stylex.create({container: { display: 'flex', flexDirection: 'column', gap: '8px' },empty: { paddingBlock: '48px', paddingInline: '0' },- signInPrompt: {- display: 'flex',- flexDirection: 'column',- gap: '16px',- alignItems: 'center',- justifyContent: 'center',- padding: '48px',- },});+/**+ * The caller's personal credentials, on the personal settings page. Each row+ * can be shared into the caller's workspaces (see {@link openShareCredModal});+ * the workspace page lists workspace credentials through `WorkspaceCredsList`.+ */const CredsList: FC = () => {const { t } = useTranslation('setting');- const { isAuthenticated, isLoading: isAuthLoading, session, signIn } = useMarketAuth();+ const { isAuthenticated } = useMarketAuth();const { allowed: canManageCredentials } = usePermission('manage_provider_key');- const credsApi = useCredsApi();- const myAccountId = session?.userInfo?.accountId;+ const workspaces = useWorkspaces();const { data, error, isLoading, refetch } = credsApi.query.list.useQuery(undefined, {enabled: isAuthenticated,@@ -46,17 +43,10 @@ const CredsList: FC = () => {const credentials = data?.data ?? [];- // See credAccess.ts for the ownership/routing rules this applies.- const isActionable = (cred: UserCredSummary) => isActionableCredRow(cred, myAccountId);- const apiFor = (cred: UserCredSummary) =>- credsApiForRow(cred, myAccountId, credsApi, defaultCredsApi);-const deleteMutation = useMutation({mutationFn: async (id: number) => {if (!canManageCredentials) return;- const cred = credentials.find((c) => c.id === id);- if (!cred || !isActionable(cred)) return;- await apiFor(cred).client.delete.mutate({ id });+ await credsApi.client.delete.mutate({ id });},onSuccess: () => {refetch();@@ -64,78 +54,65 @@ const CredsList: FC = () => {});const handleEdit = (cred: UserCredSummary) => {- if (!isActionable(cred)) return;- createEditCredModal({- cred,- credsApi: apiFor(cred),- onSuccess: () => refetch(),- });+ createEditCredModal({ cred, credsApi, onSuccess: () => refetch() });};const handleView = (cred: UserCredSummary) => {- if (!isActionable(cred)) return;- createViewCredModal({ cred, credsApi: apiFor(cred) });+ createViewCredModal({ cred, credsApi });};- if (isAuthLoading) {- return <ListSkeleton paddingInline={0} />;- }-- if (!isAuthenticated) {- return (- <div {...stylex.props(styles.signInPrompt)}>- <Empty description={t('creds.signInRequired')} />- <Button icon={LogIn} type={'primary'} onClick={() => signIn()}>- {t('creds.signIn')}- </Button>- </div>- );- }-- // Org not created: guide users to complete Community Profile setup first.- if (!isLoading && error instanceof TRPCClientError && error.data?.code === 'NOT_FOUND') {- return (- <div {...stylex.props(styles.signInPrompt)}>- <Empty description={t('creds.orgSetupRequired')} />- </div>- );- }+ // Self-hosted deployments have no workspaces to share into.+ const shareItems = (cred: UserCredSummary) =>+ workspaces.length > 0+ ? [+ {+ icon: <Icon icon={Share2} />,+ key: 'share',+ label: t('creds.share.menu'),+ onClick: () => openShareCredModal(cred),+ },+ ]+ : [];return (- <div {...stylex.props(styles.container)}>- <AsyncBoundary- data={data}- error={error}- errorVariant={'block'}- isEmpty={credentials.length === 0}- isLoading={isLoading}- loading={<ListSkeleton paddingInline={0} />}- empty={- <Empty className={stylex.props(styles.empty).className} description={t('creds.empty')} />- }- onRetry={() => refetch()}- >- <Flexbox gap={0}>- {credentials.map((cred) => {- // Another member's shared row: no endpoint this UI can reach for- // it (see the isActionable doc comment above) — omit the action- // handlers entirely so CredItem renders the row with no "..."- // menu / view button, instead of a menu whose actions silently- // no-op.- const actionable = isActionable(cred);- return (+ <MarketSignInGate>+ <div {...stylex.props(styles.container)}>+ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'block'}+ isEmpty={credentials.length === 0}+ isLoading={isLoading}+ loading={<ListSkeleton paddingInline={0} />}+ empty={+ <Empty+ className={stylex.props(styles.empty).className}+ description={t('creds.empty')}+ />+ }+ onRetry={() => refetch()}+ >+ <Flexbox gap={0}>+ {credentials.map((cred) => (<CredItem+ canManage={canManageCredentials}cred={cred}+ extraMenuItems={shareItems(cred)}key={cred.id}- onDelete={actionable ? (id) => deleteMutation.mutate(id) : undefined}- onEdit={actionable && canManageCredentials ? (cred) => handleEdit(cred) : undefined}- onView={actionable ? handleView : undefined}+ tags={+ !!cred.shares?.length && (+ <Tag>{t('creds.share.badge', { count: cred.shares.length })}</Tag>+ )+ }+ onDelete={(id) => deleteMutation.mutate(id)}+ onEdit={canManageCredentials ? handleEdit : undefined}+ onView={handleView}/>- );- })}- </Flexbox>- </AsyncBoundary>- </div>+ ))}+ </Flexbox>+ </AsyncBoundary>+ </div>+ </MarketSignInGate>);};diff --git a/src/features/Settings/creds/features/EditCredModal/Content.tsx b/src/features/Settings/creds/features/EditCredModal/Content.tsxindex 4ab5e45a616..8314bac139e 100644--- a/src/features/Settings/creds/features/EditCredModal/Content.tsx+++ b/src/features/Settings/creds/features/EditCredModal/Content.tsx@@ -10,13 +10,6 @@ import EditMetaForm from './EditMetaForm';export interface EditCredModalContentProps {cred: UserCredSummary;- /**- * Bound explicitly by the caller (rendered inline, inside CredsApiProvider)- * instead of read via useCredsApi() here — this content tree is portaled by- * createModal() to a global ModalHost that sits outside CredsApiProvider,- * so a local useCredsApi() call would silently fall back to the personal- * (market.creds) API even on the workspace creds page.- */credsApi: CredsApi;onSuccess?: () => void;}diff --git a/src/features/Settings/creds/features/MarketSignInGate.tsx b/src/features/Settings/creds/features/MarketSignInGate.tsxnew file mode 100644index 00000000000..85f4756b970--- /dev/null+++ b/src/features/Settings/creds/features/MarketSignInGate.tsx@@ -0,0 +1,47 @@+'use client';++import { Button, Empty } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { LogIn } from 'lucide-react';+import { type FC, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import ListSkeleton from '@/components/ListSkeleton';+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';++const styles = stylex.create({+ signInPrompt: {+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '48px',+ },+});++/**+ * Credentials live in the Market account: until the user is signed in to the+ * Market, show a sign-in prompt instead of `children`.+ */+const MarketSignInGate: FC<{ children: ReactNode }> = ({ children }) => {+ const { t } = useTranslation('setting');+ const { isAuthenticated, isLoading, signIn } = useMarketAuth();++ if (isLoading) return <ListSkeleton paddingInline={0} />;++ if (!isAuthenticated) {+ return (+ <div {...stylex.props(styles.signInPrompt)}>+ <Empty description={t('creds.signInRequired')} />+ <Button icon={LogIn} type={'primary'} onClick={() => signIn()}>+ {t('creds.signIn')}+ </Button>+ </div>+ );+ }++ return children;+};++export default MarketSignInGate;diff --git a/src/features/Settings/creds/features/ShareCredModal.tsx b/src/features/Settings/creds/features/ShareCredModal.tsxnew file mode 100644index 00000000000..8bce14ef459--- /dev/null+++ b/src/features/Settings/creds/features/ShareCredModal.tsx@@ -0,0 +1,278 @@+'use client';++import { type UserCredSummary } from '@lobechat/types';+import {+ Button,+ confirmModal,+ createModal,+ Flexbox,+ Icon,+ Select,+ Tag,+ Text,+ toast,+} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { t } from 'i18next';+import { Lock, Users } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceOptionLabel } from '@/business/client/hooks/useWorkspaceOptionLabel';+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import { createWorkspaceLambdaClient, lambdaQuery } from '@/libs/trpc/client';++import { credErrorKey } from './credError';++type Visibility = 'private' | 'public';++const styles = stylex.create({+ optionHint: {+ color: cssVar.colorTextTertiary,+ fontSize: '12px',+ marginInlineStart: 'auto',+ },+ optionRow: {+ minWidth: 0,+ paddingBlock: '2px',+ width: '100%',+ },+ sharedRow: {+ backgroundColor: cssVar.colorFillQuaternary,+ borderRadius: cssVar.borderRadius,+ paddingBlock: '8px',+ paddingInline: '12px',+ },+});++interface ShareCredContentProps {+ credId: number;+}++/**+ * Body of the "Share to workspace" modal opened from a personal credential+ * row — the credential counterpart of the device share modal. Lists the+ * workspaces the credential is already shared into (each can be revoked),+ * then shares it into one more. Calls run under the target workspace's scope+ * via `createWorkspaceLambdaClient`, since the personal settings page has no+ * active workspace to inherit.+ */+const ShareCredContent = memo<ShareCredContentProps>(({ credId }) => {+ const { t: tSetting } = useTranslation('setting');+ const workspaces = useWorkspaces();+ const renderWorkspaceLabel = useWorkspaceOptionLabel();++ // Shares the personal list's query key, so a share here refreshes the page+ // behind the modal too.+ const { data, refetch } = lambdaQuery.market.creds.list.useQuery();+ const cred = data?.data?.find((c) => c.id === credId);++ const [targetId, setTargetId] = useState<string>();+ const [visibility, setVisibility] = useState<Visibility>('private');+ const [sharing, setSharing] = useState(false);++ const sharedVisibility = useMemo(+ () =>+ new Map(+ (cred?.shares ?? []).flatMap((share) =>+ share.workspaceId ? [[share.workspaceId, share.visibility] as const] : [],+ ),+ ),+ [cred?.shares],+ );+ const sharedWorkspaces = workspaces.filter((workspace) => sharedVisibility.has(workspace.id));++ const scopeLabel = (value: Visibility) =>+ tSetting(+ value === 'public'+ ? 'workspace.general.transferScope.workspace.label'+ : 'workspace.general.transferScope.private.label',+ );++ const targetOptions = useMemo(+ () =>+ workspaces.map((workspace) => {+ const shared = sharedVisibility.has(workspace.id);+ const isViewer = workspace.role === 'viewer';+ return {+ disabled: shared || isViewer || !!workspace.lockedOut,+ label: (+ <Flexbox horizontal align={'center'} {...stylex.props(styles.optionRow)} gap={8}>+ {renderWorkspaceLabel(workspace)}+ {shared && (+ <Tag size={'small'} style={{ flex: 'none', margin: 0 }}>+ {tSetting('creds.share.alreadyShared')}+ </Tag>+ )}+ {!shared && isViewer && (+ <span {...stylex.props(styles.optionHint)}>+ {tSetting('creds.share.viewerHint')}+ </span>+ )}+ </Flexbox>+ ),+ title: workspace.name,+ value: workspace.id,+ };+ }),+ [workspaces, sharedVisibility, tSetting, renderWorkspaceLabel],+ );++ const effectiveTargetId = targetId ?? targetOptions.find((option) => !option.disabled)?.value;++ const visibilityOptions = (+ [+ { desc: 'private.desc', icon: Lock, label: 'private.label', value: 'private' },+ { desc: 'workspace.desc', icon: Users, label: 'workspace.label', value: 'public' },+ ] as const+ ).map((item) => ({+ label: (+ <Flexbox horizontal align={'center'} {...stylex.props(styles.optionRow)} gap={8}>+ <Icon icon={item.icon} size={14} />+ <Text style={{ fontSize: 13, fontWeight: 500 }}>+ {tSetting(`workspace.general.transferScope.${item.label}`)}+ </Text>+ <span {...stylex.props(styles.optionHint)}>+ {tSetting(`workspace.general.transferScope.${item.desc}`)}+ </span>+ </Flexbox>+ ),+ title: tSetting(`workspace.general.transferScope.${item.label}`),+ value: item.value,+ }));++ const handleShare = async () => {+ const target = workspaces.find((w) => w.id === effectiveTargetId);+ if (!target) return;++ setSharing(true);+ try {+ await createWorkspaceLambdaClient(target.id).market.creds.share.mutate({+ id: credId,+ visibility,+ });+ await refetch();+ setTargetId(undefined);+ toast.success(tSetting('creds.share.success', { name: target.name }));+ } catch (error) {+ toast.error(tSetting(credErrorKey(error, 'creds.share.error')));+ } finally {+ setSharing(false);+ }+ };++ const handleRevoke = (workspaceId: string, name: string) =>+ confirmModal({+ content: tSetting('creds.share.revokeConfirmDesc'),+ okButtonProps: { danger: true },+ okText: tSetting('creds.share.revoke'),+ onOk: async () => {+ try {+ await createWorkspaceLambdaClient(workspaceId).market.creds.unshare.mutate({+ id: credId,+ });+ await refetch();+ } catch (error) {+ toast.error(tSetting(credErrorKey(error, 'creds.share.error')));+ }+ },+ title: tSetting('creds.share.revokeConfirmTitle', { name }),+ });++ return (+ <Flexbox gap={16} paddingBlock={8}>+ <Text style={{ fontSize: 13 }} type={'secondary'}>+ {tSetting('creds.share.modalDesc')}+ </Text>++ {sharedWorkspaces.length > 0 && (+ <Flexbox gap={6}>+ <Text style={{ fontSize: 13, fontWeight: 500 }}>+ {tSetting('creds.share.sharedLabel')}+ </Text>+ {sharedWorkspaces.map((workspace) => (+ <Flexbox+ horizontal+ align={'center'}+ {...stylex.props(styles.sharedRow)}+ gap={8}+ justify={'space-between'}+ key={workspace.id}+ >+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ {renderWorkspaceLabel(workspace)}+ <Tag size={'small'} style={{ flex: 'none', margin: 0 }}>+ {scopeLabel(sharedVisibility.get(workspace.id)!)}+ </Tag>+ </Flexbox>+ <Button size={'small'} onClick={() => handleRevoke(workspace.id, workspace.name)}>+ {tSetting('creds.share.revoke')}+ </Button>+ </Flexbox>+ ))}+ </Flexbox>+ )}++ {workspaces.length === 0 ? (+ <Flexbox align={'center'} justify={'center'} paddingBlock={24}>+ <Text fontSize={12} type={'secondary'}>+ {tSetting('creds.share.empty')}+ </Text>+ </Flexbox>+ ) : (+ <>+ <Flexbox gap={6}>+ <Text style={{ fontSize: 13, fontWeight: 500 }}>+ {tSetting('creds.share.targetLabel')}+ </Text>+ <Select+ showSearch+ options={targetOptions}+ placeholder={tSetting('creds.share.selectPlaceholder')}+ style={{ width: '100%' }}+ value={effectiveTargetId}+ onChange={(value) => setTargetId(value as string)}+ />+ </Flexbox>++ <Flexbox gap={6}>+ <Text style={{ fontSize: 13, fontWeight: 500 }}>+ {tSetting('workspace.general.transferScope.title')}+ </Text>+ <Select+ options={visibilityOptions}+ style={{ width: '100%' }}+ value={visibility}+ onChange={(value) => setVisibility(value as Visibility)}+ />+ </Flexbox>++ <Flexbox horizontal justify={'flex-end'}>+ <Button+ disabled={!effectiveTargetId}+ loading={sharing}+ type={'primary'}+ onClick={handleShare}+ >+ {tSetting('creds.share.confirm')}+ </Button>+ </Flexbox>+ </>+ )}+ </Flexbox>+ );+});++ShareCredContent.displayName = 'ShareCredContent';++export const openShareCredModal = (cred: UserCredSummary) =>+ createModal({+ content: <ShareCredContent credId={cred.id} />,+ footer: null,+ styles: {+ content: { paddingBlock: 8, paddingInline: 24 },+ },+ title: t('creds.share.modalTitle', { ns: 'setting' }),+ width: 'min(92vw, 520px)',+ });diff --git a/src/features/Settings/creds/features/ViewCredModal/Content.tsx b/src/features/Settings/creds/features/ViewCredModal/Content.tsxindex 59f5edd532f..39eea5a6369 100644--- a/src/features/Settings/creds/features/ViewCredModal/Content.tsx+++ b/src/features/Settings/creds/features/ViewCredModal/Content.tsx@@ -113,13 +113,6 @@ const KVRow: FC<KVRowProps> = ({ keyName, value }) => {export interface ViewCredModalContentProps {cred: UserCredSummary;- /**- * Bound explicitly by the caller (rendered inline, inside CredsApiProvider)- * instead of read via useCredsApi() here — this content tree is portaled by- * createModal() to a global ModalHost that sits outside CredsApiProvider,- * so a local useCredsApi() call would silently fall back to the personal- * (market.creds) API even on the workspace creds page.- */credsApi: CredsApi;}diff --git a/src/features/Settings/creds/features/WorkspaceCredsList.tsx b/src/features/Settings/creds/features/WorkspaceCredsList.tsxnew file mode 100644index 00000000000..c0ddd22617f--- /dev/null+++ b/src/features/Settings/creds/features/WorkspaceCredsList.tsx@@ -0,0 +1,181 @@+'use client';++import { type UserCredSummary } from '@lobechat/types';+import { confirmModal, Empty, Flexbox, Icon, Tag, toast } from '@lobehub/ui';+import { EyeOffIcon, GlobeIcon, Link2Off } from 'lucide-react';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import ListSkeleton from '@/components/ListSkeleton';+import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';+import { usePermission } from '@/hooks/usePermission';+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';+import { lambdaClient } from '@/libs/trpc/client';++import { isOwnCredRow, workspaceCredRowAccess } from './credAccess';+import { credErrorKey } from './credError';+import CredItem from './CredItem';+import { createEditCredModal } from './EditCredModal';+import { type CredsApi } from './useCredsApi';+import { createViewCredModal } from './ViewCredModal';++type Visibility = 'private' | 'public';++interface WorkspaceCredsListProps {+ /** The workspace binding (`workspaceCreds`), with `setVisibility`. */+ credsApi: CredsApi;+ /** Which tab: credentials shared with every member, or the caller's private ones. */+ visibility: Visibility;+}++/**+ * One tab of the workspace credential page, mirroring the device page's+ * Workspace / Private split. `workspaceCreds.list` already returns only what+ * the caller can see — shared credentials plus their own private ones — so+ * each tab is a filter on `visibility`. A row is a workspace credential or a+ * member's personal credential shared in; see `credAccess.ts` for who may do+ * what with each.+ */+const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({ credsApi, visibility }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { session } = useMarketAuth();+ const { allowed: isAdmin } = usePermission('manage_provider_key');+ const myAccountId = session?.userInfo?.accountId;++ const { data, error, isLoading, refetch } = credsApi.query.list.useQuery();+ const credentials = (data?.data ?? []).filter((cred) => cred.visibility === visibility);++ const run = async (action: () => Promise<unknown>) => {+ try {+ await action();+ await refetch();+ } catch (error) {+ toast.error(t(credErrorKey(error, 'creds.share.error')));+ }+ };++ /**+ * A workspace credential changes visibility through `workspaceCreds`; a+ * shared personal credential through its owner's share into this+ * workspace (`market.creds`, scoped to the active workspace).+ */+ const changeVisibility = (cred: UserCredSummary, next: Visibility) =>+ cred.ownerType === 'user'+ ? next === 'public'+ ? lambdaClient.market.creds.publish.mutate({ id: cred.id })+ : lambdaClient.market.creds.share.mutate({ id: cred.id, visibility: 'private' })+ : credsApi.setVisibility!(cred.id, next);++ const handlePublish = (cred: UserCredSummary) =>+ confirmModal({+ content: <VisibilityConfirmContent variant={'publish'} />,+ okText: t('creds.visibility.publish'),+ onOk: () => run(() => changeVisibility(cred, 'public')),+ title: t('creds.visibility.publishConfirmTitle'),+ });++ const handleMakePrivate = (cred: UserCredSummary) =>+ confirmModal({+ content: <VisibilityConfirmContent variant={'makePrivate'} />,+ okButtonProps: { danger: true },+ okText: t('makePrivate.confirm.ok', { ns: 'common' }),+ onOk: () => run(() => changeVisibility(cred, 'private')),+ title: t('makePrivate.confirm.title', { ns: 'common' }),+ });++ const handleUnshare = (cred: UserCredSummary) =>+ confirmModal({+ content: t('creds.share.unshareConfirmDesc'),+ okButtonProps: { danger: true },+ okText: t('creds.share.revoke'),+ onOk: () => run(() => lambdaClient.market.creds.unshare.mutate({ id: cred.id })),+ title: t('creds.share.unshareConfirmTitle'),+ });++ const handleDelete = (id: number) => run(() => credsApi.client.delete.mutate({ id }));++ return (+ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'block'}+ isEmpty={credentials.length === 0}+ isLoading={isLoading}+ loading={<ListSkeleton paddingInline={0} />}+ empty={+ <Empty+ description={t(visibility === 'private' ? 'creds.privateSection.empty' : 'creds.empty')}+ style={{ paddingBlock: 48 }}+ />+ }+ onRetry={() => refetch()}+ >+ <Flexbox gap={0}>+ {credentials.map((cred) => {+ const access = workspaceCredRowAccess(cred, { isAdmin, myAccountId });+ const extraMenuItems = [+ ...(access.publish+ ? [+ {+ icon: <Icon icon={GlobeIcon} />,+ key: 'publish',+ label: t('creds.visibility.publish'),+ onClick: () => handlePublish(cred),+ },+ ]+ : []),+ ...(access.makePrivate+ ? [+ {+ icon: <Icon icon={EyeOffIcon} />,+ key: 'makePrivate',+ label: t('makePrivate', { ns: 'common' }),+ onClick: () => handleMakePrivate(cred),+ },+ ]+ : []),+ ...(access.unshare+ ? [+ {+ danger: true,+ icon: <Icon icon={Link2Off} />,+ key: 'unshare',+ label: t('creds.share.revoke'),+ onClick: () => handleUnshare(cred),+ },+ ]+ : []),+ ];++ return (+ <CredItem+ canManage={access.manage}+ cred={cred}+ extraMenuItems={extraMenuItems}+ key={cred.id}+ tags={+ cred.ownerType === 'user' && (+ <Tag>+ {isOwnCredRow(cred, myAccountId)+ ? t('creds.owner.fromPersonal')+ : t('creds.owner.sharedBy', { name: cred.ownerDisplayName })}+ </Tag>+ )+ }+ onDelete={access.manage ? handleDelete : undefined}+ onView={access.manage ? (cred) => createViewCredModal({ cred, credsApi }) : undefined}+ onEdit={+ access.manage+ ? (cred) => createEditCredModal({ cred, credsApi, onSuccess: () => refetch() })+ : undefined+ }+ />+ );+ })}+ </Flexbox>+ </AsyncBoundary>+ );+};++export default WorkspaceCredsList;diff --git a/src/features/Settings/creds/features/credAccess.test.ts b/src/features/Settings/creds/features/credAccess.test.tsindex f23821b81b7..a0b900ef1e0 100644--- a/src/features/Settings/creds/features/credAccess.test.ts+++ b/src/features/Settings/creds/features/credAccess.test.ts@@ -1,88 +1,133 @@import { type UserCredSummary } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { credsApiForRow, isActionableCredRow, isOwnCredRow } from './credAccess';+import { isOwnCredRow, workspaceCredRowAccess } from './credAccess';-const baseCred = {+const ME = 42;+const OTHER = 99;++const row = (overrides: Partial<UserCredSummary>): UserCredSummary => ({createdAt: '2024-01-01T00:00:00.000Z',id: 1,key: 'GITHUB_TOKEN',name: 'GitHub',- type: 'kv-env' as const,+ type: 'kv-env',updatedAt: '2024-01-01T00:00:00.000Z',-};--const orgOwnedRow: UserCredSummary = {- ...baseCred,- ownerAccountId: 100,- ownerType: 'organization',-};--const myOwnRow: UserCredSummary = {- ...baseCred,- ownerAccountId: 42,- ownerType: 'user',-};--const anotherMembersRow: UserCredSummary = {- ...baseCred,- ownerAccountId: 99,- ownerType: 'user',-};--const myAccountId = 42;--describe('isOwnCredRow', () => {- it('is true for a "user"-owned row whose ownerAccountId matches the signed-in account', () => {- expect(isOwnCredRow(myOwnRow, myAccountId)).toBe(true);- });-- it("is false for another member's row even though ownerType is also 'user'", () => {- expect(isOwnCredRow(anotherMembersRow, myAccountId)).toBe(false);- });-- it('is false for an org-owned row', () => {- expect(isOwnCredRow(orgOwnedRow, myAccountId)).toBe(false);- });-- it('is false when the signed-in account id is unknown (not yet loaded)', () => {- expect(isOwnCredRow(myOwnRow, undefined)).toBe(false);- });+ ...overrides,});-describe('isActionableCredRow', () => {- it('is true for an org-owned row', () => {- expect(isActionableCredRow(orgOwnedRow, myAccountId)).toBe(true);- });+const member = { isAdmin: false, myAccountId: ME };+const admin = { isAdmin: true, myAccountId: ME };- it("is true for the signed-in member's own row", () => {- expect(isActionableCredRow(myOwnRow, myAccountId)).toBe(true);+describe('isOwnCredRow', () => {+ it('is true only for my own personal credential', () => {+ expect(isOwnCredRow(row({ ownerAccountId: ME, ownerType: 'user' }), ME)).toBe(true);+ expect(isOwnCredRow(row({ ownerAccountId: OTHER, ownerType: 'user' }), ME)).toBe(false);+ expect(isOwnCredRow(row({ ownerAccountId: ME, ownerType: 'organization' }), ME)).toBe(false);});- it("is false for another member's row — no endpoint can reach it", () => {- expect(isActionableCredRow(anotherMembersRow, myAccountId)).toBe(false);+ it('is false while my account id is unknown', () => {+ expect(isOwnCredRow(row({ ownerType: 'user' }), undefined)).toBe(false);});});-describe('credsApiForRow', () => {- const contextApi = 'workspaceCreds' as const;- const personalApi = 'marketCreds' as const;-- it('routes an org-owned row to the context (workspace) API', () => {- expect(credsApiForRow(orgOwnedRow, myAccountId, contextApi, personalApi)).toBe(contextApi);- });-- it("routes the signed-in member's own row to the personal API", () => {- expect(credsApiForRow(myOwnRow, myAccountId, contextApi, personalApi)).toBe(personalApi);+describe('workspaceCredRowAccess', () => {+ describe('workspace credentials', () => {+ it('lets the creator manage and publish a private one', () => {+ const cred = row({+ createdByAccountId: ME,+ ownerType: 'organization',+ visibility: 'private',+ });++ expect(workspaceCredRowAccess(cred, member)).toEqual({+ makePrivate: false,+ manage: true,+ publish: true,+ unshare: false,+ });+ });++ it('lets the creator take a published one back', () => {+ const cred = row({ createdByAccountId: ME, ownerType: 'organization', visibility: 'public' });++ expect(workspaceCredRowAccess(cred, member)).toMatchObject({+ makePrivate: true,+ manage: true,+ publish: false,+ });+ });++ it("lets an admin manage another member's shared one but not change its visibility", () => {+ const cred = row({+ createdByAccountId: OTHER,+ ownerType: 'organization',+ visibility: 'public',+ });++ expect(workspaceCredRowAccess(cred, admin)).toEqual({+ makePrivate: false,+ manage: true,+ publish: false,+ unshare: false,+ });+ });++ it("gives a member nothing on another member's shared one", () => {+ const cred = row({+ createdByAccountId: OTHER,+ ownerType: 'organization',+ visibility: 'public',+ });++ expect(workspaceCredRowAccess(cred, member)).toEqual({+ makePrivate: false,+ manage: false,+ publish: false,+ unshare: false,+ });+ });++ it('leaves a credential with no recorded creator to admins', () => {+ const cred = row({ ownerType: 'organization', visibility: 'public' });++ expect(workspaceCredRowAccess(cred, admin).manage).toBe(true);+ expect(workspaceCredRowAccess(cred, admin).makePrivate).toBe(false);+ expect(workspaceCredRowAccess(cred, member).manage).toBe(false);+ });});- it("routes another member's row to the context API, not the personal one — the caller must gate on isActionableCredRow first and never call this for such a row in practice", () => {- // credsApiForRow has no "no valid endpoint" return value, so this- // documents the fallback rather than endorsing it: CredsList only calls- // apiFor() after confirming isActionable(cred), so this branch is never- // reached for another member's row in the real component.- expect(credsApiForRow(anotherMembersRow, myAccountId, contextApi, personalApi)).toBe(- contextApi,- );+ describe('shared personal credentials', () => {+ it('lets the owner publish a private share or unshare it, but edit it only on the personal page', () => {+ const cred = row({ ownerAccountId: ME, ownerType: 'user', visibility: 'private' });++ expect(workspaceCredRowAccess(cred, member)).toEqual({+ makePrivate: false,+ manage: false,+ publish: true,+ unshare: true,+ });+ });++ it('lets the owner take a published share back', () => {+ const cred = row({ ownerAccountId: ME, ownerType: 'user', visibility: 'public' });++ expect(workspaceCredRowAccess(cred, member)).toMatchObject({+ makePrivate: true,+ publish: false,+ });+ });++ it("lets only an admin remove another member's published share", () => {+ const cred = row({ ownerAccountId: OTHER, ownerType: 'user', visibility: 'public' });++ expect(workspaceCredRowAccess(cred, admin)).toEqual({+ makePrivate: false,+ manage: false,+ publish: false,+ unshare: true,+ });+ expect(workspaceCredRowAccess(cred, member).unshare).toBe(false);+ });});});diff --git a/src/features/Settings/creds/features/credAccess.ts b/src/features/Settings/creds/features/credAccess.tsindex 2eddaa2b2df..38f0840a87d 100644--- a/src/features/Settings/creds/features/credAccess.ts+++ b/src/features/Settings/creds/features/credAccess.ts@@ -1,50 +1,66 @@import { type UserCredSummary } from '@lobechat/types';/**- * Ownership routing for a row from an org-scoped credential list- * (`workspaceCreds.list`). Extracted from {@link CredsList} as plain,- * dependency-free functions so the routing decision has direct unit- * coverage independent of React/tRPC test scaffolding — see- * `credAccess.test.ts`.+ * What the signed-in member may do with a row of a workspace credential list+ * (`workspaceCreds.list`). Plain functions so the rules have direct unit+ * coverage — see `credAccess.test.ts`.*- * A row can be:- * - the org's own credential (`ownerType: 'organization'`);- * - the SIGNED-IN member's own credential, published/draft-linked into the- * org (`ownerType: 'user'` AND `ownerAccountId === myAccountId`);- * - ANOTHER member's published credential (`ownerType: 'user'` AND- * `ownerAccountId !== myAccountId`) — `ownerType` alone conflates this- * with the previous case.+ * A row is one of:+ * - a workspace credential (`ownerType: 'organization'`), shared with every+ * member (`visibility: 'public'`) or private to the member who created it;+ * - the member's own personal credential shared into the workspace+ * (`ownerType: 'user'`, `ownerAccountId` is theirs);+ * - another member's published personal credential.*- * Market's org-scoped write endpoints (`/organizations/:orgId/creds/:id`- * PATCH/DELETE/GET?decrypt) resolve ownership by the *org's* account id- * only — they 404 (or refuse to decrypt) on ANY member-owned row, mine or- * someone else's. So:- * - org-owned → the workspace API (context-bound) is correct;- * - my own row → must go through my personal `market.creds` endpoint- * instead, which is scoped to my own account;- * - another member's row → no endpoint this UI can reach at all; actions- * for it must be hidden rather than misrouted (routing to my personal API- * would 404 too, since that row isn't mine).+ * Market enforces the same rules; these only decide which actions to offer.*/-type CredRowOwnership = Pick<UserCredSummary, 'ownerAccountId' | 'ownerType'>;+type CredRow = Pick<+ UserCredSummary,+ 'createdByAccountId' | 'ownerAccountId' | 'ownerType' | 'visibility'+>;-export const isOwnCredRow = (cred: CredRowOwnership, myAccountId: number | undefined): boolean =>- cred.ownerType === 'user' && cred.ownerAccountId === myAccountId;+export interface CredRowViewer {+ /** Holds the workspace's credential-management permission. */+ isAdmin: boolean;+ /** The member's Market account id. */+ myAccountId: number | undefined;+}-export const isActionableCredRow = (- cred: CredRowOwnership,- myAccountId: number | undefined,-): boolean => cred.ownerType !== 'user' || isOwnCredRow(cred, myAccountId);+export interface CredRowAccess {+ /** Make it private to its creator / owner again. */+ makePrivate: boolean;+ /** Edit, view and delete the credential itself. */+ manage: boolean;+ /** Publish it to every member. */+ publish: boolean;+ /** Remove a shared personal credential from the workspace. */+ unshare: boolean;+}-/**- * Which API binding (`personalApi` vs `contextApi`) a row's mutations should- * go through. Only meaningful for an {@link isActionableCredRow} row — the- * caller must gate on that first, since another member's row has no correct- * binding to return here.- */-export const credsApiForRow = <T>(- cred: CredRowOwnership,- myAccountId: number | undefined,- contextApi: T,- personalApi: T,-): T => (isOwnCredRow(cred, myAccountId) ? personalApi : contextApi);+const NONE: CredRowAccess = { makePrivate: false, manage: false, publish: false, unshare: false };++export const isOwnCredRow = (cred: CredRow, myAccountId: number | undefined): boolean =>+ cred.ownerType === 'user' && myAccountId !== undefined && cred.ownerAccountId === myAccountId;++export const workspaceCredRowAccess = (cred: CredRow, viewer: CredRowViewer): CredRowAccess => {+ const isPublic = cred.visibility === 'public';++ if (cred.ownerType === 'user') {+ // A personal credential is edited where it lives, on the owner's personal+ // page; here its owner only decides how it is shared, and an admin may+ // take it out of the workspace.+ if (!isOwnCredRow(cred, viewer.myAccountId)) return { ...NONE, unshare: viewer.isAdmin };+ return { makePrivate: isPublic, manage: false, publish: !isPublic, unshare: true };+ }++ // Visibility is the creator's call alone, as with a device: an admin making+ // someone's credential private would move it into that member's private list.+ const isCreator =+ viewer.myAccountId !== undefined && cred.createdByAccountId === viewer.myAccountId;+ return {+ makePrivate: isCreator && isPublic,+ manage: isCreator || viewer.isAdmin,+ publish: isCreator && !isPublic,+ unshare: false,+ };+};diff --git a/src/features/Settings/creds/features/credError.test.ts b/src/features/Settings/creds/features/credError.test.tsnew file mode 100644index 00000000000..a7ee30ff13b--- /dev/null+++ b/src/features/Settings/creds/features/credError.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import { credErrorKey } from './credError';++const trpcError = (code: string, message: string) =>+ Object.assign(new Error(message), { data: { code } });++describe('credErrorKey', () => {+ it("names Market's conflict reasons", () => {+ expect(credErrorKey(trpcError('CONFLICT', 'public_cred_exists'), 'fallback')).toBe(+ 'creds.errors.publicCredExists',+ );+ expect(credErrorKey(trpcError('CONFLICT', 'multi_org_share_disabled'), 'fallback')).toBe(+ 'creds.errors.multiOrgShareDisabled',+ );+ expect(credErrorKey(trpcError('CONFLICT', 'private_cred_exists'), 'fallback')).toBe(+ 'creds.errors.privateCredExists',+ );+ expect(credErrorKey(trpcError('CONFLICT', 'private_creds_disabled'), 'fallback')).toBe(+ 'creds.errors.privateCredsDisabled',+ );+ });++ it('falls back for any other failure', () => {+ expect(credErrorKey(trpcError('CONFLICT', 'something else'), 'fallback')).toBe('fallback');+ expect(credErrorKey(trpcError('FORBIDDEN', 'public_cred_exists'), 'fallback')).toBe('fallback');+ expect(credErrorKey('boom', 'fallback')).toBe('fallback');+ });+});diff --git a/src/features/Settings/creds/features/credError.ts b/src/features/Settings/creds/features/credError.tsnew file mode 100644index 00000000000..42952f240fe--- /dev/null+++ b/src/features/Settings/creds/features/credError.ts@@ -0,0 +1,21 @@+/**+ * Market's 409 reasons, passed through as the tRPC message by+ * `workspaceCreds`: the target slot for this key (the workspace's shared one,+ * or the caller's private one) is taken, or Market does not yet allow private+ * workspace credentials or sharing one credential into several workspaces.+ */+const CONFLICT_KEYS = {+ multi_org_share_disabled: 'creds.errors.multiOrgShareDisabled',+ private_cred_exists: 'creds.errors.privateCredExists',+ private_creds_disabled: 'creds.errors.privateCredsDisabled',+ public_cred_exists: 'creds.errors.publicCredExists',+} as const;++type ConflictKey = (typeof CONFLICT_KEYS)[keyof typeof CONFLICT_KEYS];++/** The `setting` locale key describing a credential write failure, or `fallbackKey`. */+export const credErrorKey = <K extends string>(error: unknown, fallbackKey: K): ConflictKey | K => {+ if (!(error instanceof Error)) return fallbackKey;+ if ((error as { data?: { code?: string } }).data?.code !== 'CONFLICT') return fallbackKey;+ return CONFLICT_KEYS[error.message as keyof typeof CONFLICT_KEYS] ?? fallbackKey;+};diff --git a/src/features/Settings/creds/features/useCredsApi.ts b/src/features/Settings/creds/features/useCredsApi.tsindex 37464b9cfd0..c72c8258014 100644--- a/src/features/Settings/creds/features/useCredsApi.ts+++ b/src/features/Settings/creds/features/useCredsApi.ts@@ -1,7 +1,5 @@'use client';-import { createContext, useContext } from 'react';-import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';/**@@ -11,30 +9,31 @@ import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';* (`/[workspaceSlug]/settings/credential`) share UI components but talk to* different tRPC routers — `market.creds` (Market user account) versus* `workspaceCreds` (Market organization mirroring the cloud workspace).- *- * The workspace shell wraps the page in {@link CredsApiProvider} with the- * workspace bindings. Forms/modals read whichever client/query namespace is- * active via {@link useCredsApi} and otherwise behave identically.+ * Lists, forms and modals take the binding explicitly; modals are portaled+ * to a global host, outside any page context.*/export interface CredsApi {client: typeof lambdaClient.market.creds;+ /**+ * Workspace bindings only: who a newly created credential is for —+ * `'public'` shares it with every member, `'private'` keeps it to its+ * creator. Unset for personal credentials.+ */+ createVisibility?: 'private' | 'public';query: typeof lambdaQuery.market.creds;+ /** Workspace bindings only: publish a workspace credential or take it back. */+ setVisibility?: (id: number, visibility: 'private' | 'public') => Promise<unknown>;}/**- * The personal `market.creds` binding, exported so callers that need it- * regardless of ambient context can use it explicitly — e.g. {@link CredsList}- * routing a merged workspace-view row back to the personal API when its- * `ownerType` is `'user'` (the row is a member's own credential, not the- * org's), since only the owner's personal endpoint can write to it.+ * Extra create-request fields for the binding — `workspaceCreds` accepts a+ * `visibility`; the personal `market.creds` takes none.*/-export const defaultCredsApi: CredsApi = {+export const createExtras = (credsApi: CredsApi) =>+ credsApi.createVisibility ? { visibility: credsApi.createVisibility } : {};++/** The personal `market.creds` binding. */+export const personalCredsApi: CredsApi = {client: lambdaClient.market.creds,query: lambdaQuery.market.creds,};--const CredsApiContext = createContext<CredsApi | null>(null);--export const CredsApiProvider = CredsApiContext.Provider;--export const useCredsApi = (): CredsApi => useContext(CredsApiContext) ?? defaultCredsApi;diff --git a/src/features/Settings/creds/index.tsx b/src/features/Settings/creds/index.tsxindex 619a6b3f1c1..d7819406a27 100644--- a/src/features/Settings/creds/index.tsx+++ b/src/features/Settings/creds/index.tsx@@ -11,7 +11,7 @@ import { usePermission } from '@/hooks/usePermission';import { createCreateCredModal } from './features/CreateCredModal';import CredsList from './features/CredsList';-import { useCredsApi } from './features/useCredsApi';+import { personalCredsApi } from './features/useCredsApi';interface PageProps {mobile?: boolean;@@ -21,12 +21,11 @@ const Page = ({ mobile }: PageProps) => {const { t } = useTranslation('setting');const { allowed: canManageCredentials, reason } = usePermission('manage_provider_key');const [refreshKey, setRefreshKey] = useState(0);- const credsApi = useCredsApi();const handleCreate = () => {if (!canManageCredentials) return;createCreateCredModal({- credsApi,+ credsApi: personalCredsApi,onSuccess: () => setRefreshKey((k) => k + 1),});};diff --git a/src/helpers/claudeCodeTokenCred.test.ts b/src/helpers/claudeCodeTokenCred.test.tsindex 186aa93f17a..121d99c1f9d 100644--- a/src/helpers/claudeCodeTokenCred.test.ts+++ b/src/helpers/claudeCodeTokenCred.test.ts@@ -38,15 +38,7 @@ describe('resolveClaudeCodeTokenStatus', () => {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' });+ ).toEqual({ personalCred: cred, status: 'personalNotShared' });});it('shows the personal preview once the token is shared to the active workspace', () => {diff --git a/src/helpers/claudeCodeTokenCred.ts b/src/helpers/claudeCodeTokenCred.tsindex 121ab113ee1..9da67f1ba63 100644--- a/src/helpers/claudeCodeTokenCred.ts+++ b/src/helpers/claudeCodeTokenCred.ts@@ -22,11 +22,7 @@ export type ClaudeCodeTokenStatus =*/| { 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' }+ | { personalCred: UserCredSummary; status: 'personalNotShared' }| { status: 'missing' }/** The credential lookup failed; whether the run can read a token is unknown. */| { status: 'unknown' };@@ -67,11 +63,7 @@ export const resolveClaudeCodeTokenStatus = ({}if (personalCred) {- return {- personalCred,- sharedElsewhere: personalCred.organizationAccountId != null,- status: 'personalNotShared',- };+ return { personalCred, status: 'personalNotShared' };}return { status: 'missing' };diff --git a/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/ShareToggle.tsx b/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/ShareToggle.tsxdeleted file mode 100644index ecab1d1eead..00000000000--- a/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/ShareToggle.tsx+++ /dev/null@@ -1,130 +0,0 @@-'use client';--import { type UserCredSummary } from '@lobechat/types';-import { Flexbox, Segmented, Switch, Text, toast } from '@lobehub/ui';-import { useMutation } from '@tanstack/react-query';-import { type FC, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { lambdaClient } from '@/libs/trpc/client';--interface ShareToggleProps {- cred: UserCredSummary;- /**- * Called after a share/unshare/visibility change lands — may be async.- * The mutation waits for it to settle before releasing its optimistic- * override (see below), so the switch never reverts-then-jumps once fresh- * data arrives.- */- onChange: () => Promise<unknown> | void;-}--/**- * Per-row control for the workspace creds page's "your personal credentials"- * section. Lets the owner share one of their own personal credentials into- * the current workspace's Market organization (or unshare it), and — once- * shared — flip its visibility between 'private' (draft, only the owner can- * see it's linked) and 'public' (visible to the rest of the workspace).- *- * Always targets the *active* workspace: the underlying `market.creds.share`- * procedure resolves the org from `ctx.workspaceId` server-side (verified- * membership), never from client input — this component never needs to know- * the workspace's Market org id.- */-const ShareToggle: FC<ShareToggleProps> = ({ cred, onChange }) => {- const { t } = useTranslation('setting');-- // A personal credential can only be linked to one organization at a time,- // so `organizationAccountId != null` alone can't tell "shared to *this*- // workspace" apart from "shared to some other workspace previously" — the- // list procedure resolves that distinction server-side. Defaults to false- // (safe: never surfaces an unshare/visibility control for a link that- // actually belongs to a different workspace) when unset, e.g. outside a- // workspace context or when the active workspace's org isn't set up yet.- const isShared = cred.sharedToActiveWorkspace ?? false;-- // `cred` only reflects the real server state once the parent's list(s)- // refetch — which we deliberately wait on inside the mutations below, so- // there's a real gap between "user clicked" and "`cred` prop updates".- // Without a local optimistic override, the switch/segmented would sit- // frozen (looking unresponsive) for that whole round-trip, then snap on- // their own once fresh data lands. `null` means "no override, trust `cred`".- const [pendingShared, setPendingShared] = useState<boolean | null>(null);- const [pendingVisibility, setPendingVisibility] = useState<'private' | 'public' | null>(null);-- const clearPending = () => {- setPendingShared(null);- setPendingVisibility(null);- };-- const shareMutation = useMutation({- mutationFn: async (visibility: 'private' | 'public') => {- await lambdaClient.market.creds.share.mutate({ id: cred.id, visibility });- },- onError: () => {- toast.error(t('creds.share.error'));- },- // Awaited by react-query before onSettled fires, so the optimistic- // override below only lifts once the refetched `cred` prop already- // agrees with it — never a moment earlier.- onSuccess: async () => {- await onChange();- },- onSettled: clearPending,- });-- const unshareMutation = useMutation({- mutationFn: async () => {- await lambdaClient.market.creds.unshare.mutate({ id: cred.id });- },- onError: () => {- toast.error(t('creds.share.error'));- },- onSuccess: async () => {- await onChange();- },- onSettled: clearPending,- });-- const isPending = shareMutation.isPending || unshareMutation.isPending;- const shared = pendingShared ?? isShared;- const visibility = pendingVisibility ?? cred.visibility ?? 'private';-- const handleSwitchChange = (checked: boolean) => {- setPendingShared(checked);- if (checked) {- setPendingVisibility('private');- shareMutation.mutate('private');- } else {- unshareMutation.mutate();- }- };-- const handleVisibilityChange = (value: 'private' | 'public') => {- setPendingVisibility(value);- shareMutation.mutate(value);- };-- return (- <Flexbox horizontal align={'center'} gap={8}>- <Text fontSize={12} type={'secondary'}>- {t('creds.share.toggle')}- </Text>- {shared && (- <Segmented- disabled={isPending}- size={'small'}- value={visibility}- options={[- { label: t('creds.share.visibility.private'), value: 'private' },- { label: t('creds.share.visibility.public'), value: 'public' },- ]}- onChange={handleVisibilityChange}- />- )}- <Switch checked={shared} loading={isPending} onChange={handleSwitchChange} />- </Flexbox>- );-};--export default ShareToggle;diff --git a/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsxdeleted file mode 100644index bf8a7c838f8..00000000000--- a/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx+++ /dev/null@@ -1,87 +0,0 @@-'use client';--import { createStaticStyles, Empty, Flexbox } from '@lobehub/ui';-import { type FC } from 'react';-import { useTranslation } from 'react-i18next';--import AsyncBoundary from '@/components/AsyncBoundary';-import ListSkeleton from '@/components/ListSkeleton';-import CredItem from '@/features/Settings/creds/features/CredItem';-import { lambdaQuery } from '@/libs/trpc/client';--import ShareToggle from './ShareToggle';--const styles = createStaticStyles(({ css }) => ({- empty: css`- padding-block: 32px;- padding-inline: 0;- `,-}));--interface PersonalCredsSectionProps {- /**- * Called after a share/unshare/visibility change succeeds. The workspace- * section above reads a disjoint credential set (org-scoped), so it has no- * way to know this section's mutations should invalidate it — the parent- * page wires this to its own `workspaceCreds.list` query's `refetch`.- * Returns a promise: {@link ShareToggle} awaits it (alongside this- * section's own refetch) before releasing its optimistic pending state, so- * the toggle never snaps to a different value after already looking settled.- */- onWorkspaceCredsChange: () => Promise<unknown>;-}--/**- * Personal tab of the workspace credential page: the caller's own *personal*- * credentials, each with a {@link ShareToggle} to share/unshare it into the- * current workspace's Market organization. The page provides the outlined- * list container; this component renders only the list body.- *- * Rows are share-only — no "..." action menu. Editing/deleting here is gated- * by the Admin-or-higher `manage_provider_key` workspace permission, which the- * caller's own credentials shouldn't answer to, so for most members the menu- * could only ever render disabled; CRUD lives on the personal settings page.- *- * Always queries the personal `market.creds` namespace directly — never- * `useCredsApi()` — since that hook resolves to `workspaceCreds` on this page- * and this section is deliberately personal-scoped regardless of page context.- */-const PersonalCredsSection: FC<PersonalCredsSectionProps> = ({ onWorkspaceCredsChange }) => {- const { t } = useTranslation('setting');-- const { data, error, isLoading, refetch } = lambdaQuery.market.creds.list.useQuery(undefined);-- // Refreshes both this personal list and the workspace tab's list: a- // share/unshare/visibility change alters what the org-scoped merged list- // should return, and that list has no way to know on its own.- const refetchLists = async () => {- await Promise.all([refetch(), onWorkspaceCredsChange()]);- };-- const credentials = data?.data ?? [];-- return (- <AsyncBoundary- data={data}- empty={<Empty className={styles.empty} description={t('creds.empty')} />}- error={error}- errorVariant={'block'}- isEmpty={credentials.length === 0}- isLoading={isLoading}- loading={<ListSkeleton paddingInline={0} />}- onRetry={() => refetch()}- >- <Flexbox gap={0}>- {credentials.map((cred) => (- <CredItem- cred={cred}- extra={<ShareToggle cred={cred} onChange={refetchLists} />}- key={cred.id}- />- ))}- </Flexbox>- </AsyncBoundary>- );-};--export default PersonalCredsSection;diff --git a/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsxindex 2eb30839338..0ca1262b101 100644--- a/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx+++ b/src/routes/(main)/[workspaceSlug]/settings/credential/index.tsx@@ -11,26 +11,19 @@ import {Text,Tooltip,} from '@lobehub/ui';-import { Plus, UserRoundIcon, UsersIcon } from 'lucide-react';-import { useMemo, useState } from 'react';+import { Lock, Plus, UsersIcon } from 'lucide-react';+import { useState } from 'react';import { useTranslation } from 'react-i18next';+import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';import { createCreateCredModal } from '@/features/Settings/creds/features/CreateCredModal';-import CredsList from '@/features/Settings/creds/features/CredsList';-import { type CredsApi, CredsApiProvider } from '@/features/Settings/creds/features/useCredsApi';+import MarketSignInGate from '@/features/Settings/creds/features/MarketSignInGate';+import { type CredsApi } from '@/features/Settings/creds/features/useCredsApi';+import WorkspaceCredsList from '@/features/Settings/creds/features/WorkspaceCredsList';import { usePermission } from '@/hooks/usePermission';import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';-import PersonalCredsSection from './features/PersonalCredsSection';--// Always the personal namespace — the personal scope is deliberately-// personal-scoped regardless of page context (see PersonalCredsSection).-const personalCredsApi: CredsApi = {- client: lambdaClient.market.creds,- query: lambdaQuery.market.creds,-};-const styles = createStaticStyles(({ css, cssVar }) => ({container: css`overflow: hidden;@@ -44,68 +37,61 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-type CredsScope = 'personal' | 'workspace';+type Visibility = 'private' | 'public';++interface WorkspaceCredsClient {+ setVisibility: {+ mutate: (input: { id: number; visibility: Visibility }) => Promise<unknown>;+ };+}++/**+ * The cloud `workspaceCreds` router mirrors `market.creds` (plus+ * `setVisibility`), but it is registered in the cloud lambda namespace — the+ * open-source build only has an empty stub — so strict typeof equality+ * breaks. Cast at the boundary; consumers only touch overlapping members.+ */+const workspaceClient = lambdaClient.workspaceCreds as unknown as CredsApi['client'] &+ WorkspaceCredsClient;++const workspaceCredsApi = (createVisibility: Visibility): CredsApi => ({+ client: workspaceClient,+ createVisibility,+ query: lambdaQuery.workspaceCreds as unknown as CredsApi['query'],+ setVisibility: (id, visibility) => workspaceClient.setVisibility.mutate({ id, visibility }),+});++const credsApiByTab: Record<Visibility, CredsApi> = {+ private: workspaceCredsApi('private'),+ public: workspaceCredsApi('public'),+};/**- * Workspace credential management.+ * Workspace credential management, split like the device page:*- * One unified header row — scope tabs on the left, the create action on the- * right — above an outlined list container (same container treatment as the- * agent channel detail page). The create button follows the active scope.+ * - "Workspace": credentials every member can use — the workspace's own and+ * members' personal credentials published here.+ * - "Private": credentials only the caller can use in this workspace — ones+ * they created here, and their personal credentials shared here privately.*- * - "Workspace" tab: the shared {@link CredsList} rebound to the cloud- * `workspaceCreds.*` tRPC namespace via {@link CredsApiProvider}.- * `workspaceCreds` resolves the active workspace to its Market organization- * mirror; Market's `list` there already merges the org's own credentials- * with every member's *published* (public-visibility) personal credentials,- * so a shared credential surfaces here automatically once its owner turns- * on the share toggle in the personal tab.- * - "Personal" tab: {@link PersonalCredsSection} — the caller's own personal- * credentials, each with a switch to share/unshare it into this workspace's- * organization (and a private/public visibility choice once shared). Always- * personal-scoped, independent of the workspace org's setup state.+ * A credential created on a tab belongs to the workspace with that tab's+ * visibility; personal credentials are shared in from the personal settings+ * page ("Share to Workspace…"), not listed here wholesale.** When the workspace has no Market organization yet (Community Profile not- * completed), the backend returns NOT_FOUND for the *workspace* scope. This- * component intercepts that error and renders a setup prompt in its place —- * the personal tab still works, since sharing your own credential doesn't- * require the org to exist yet (it will simply fail with a normal error until- * Community Profile setup completes).+ * completed), the backend returns NOT_FOUND and the page shows a setup prompt.*/const WorkspaceCredsSetting = () => {const { t } = useTranslation('setting');const { isAuthenticated } = useMarketAuth();- const { allowed: canManageCredentials, reason } = usePermission('manage_provider_key');- const [scope, setScope] = useState<CredsScope>('workspace');-- const workspaceCredsApi = useMemo<CredsApi>(- () => ({- // The workspaceCreds router is a structural mirror of market.creds, but- // strict typeof equality breaks because workspaceCreds is registered in- // the cloud lambda namespace. Cast at the boundary; downstream consumers- // only touch overlapping members (list/get/createKV/createOAuth/- // createFile/update/delete/uploadFile/listOAuthConnections).- client: lambdaClient.workspaceCreds as unknown as CredsApi['client'],- query: lambdaQuery.workspaceCreds as unknown as CredsApi['query'],- }),- [],- );-- // Pre-flight check: detect "org not set up" before rendering the list.- // React Query deduplicates this against the identical call inside CredsList,- // so only one network request is made — which is also why `refetch` here- // refreshes the workspace list too: creating a credential from the header,- // or sharing/unsharing/re-visibility-ing a credential from the personal tab,- // changes what this org-scoped list should return, but those mutations live- // in other components with no direct handle on CredsList's own query. Since- // both hooks share the same query key (workspaceCreds.list, input- // undefined), refetching this one pushes the fresh result to every- // subscriber, including CredsList's.- const {- error,- isLoading,- refetch: refetchWorkspaceCreds,- } = workspaceCredsApi.query.list.useQuery(undefined, {+ const { allowed: isAdmin, reason } = usePermission('manage_provider_key');+ const isViewer = useIsWorkspaceViewer();+ const [tab, setTab] = useState<Visibility>('public');+ const credsApi = credsApiByTab[tab];++ // Both tabs filter this one list; it also shares its query key with the+ // list inside WorkspaceCredsList, so `refetch` here refreshes the tab.+ const { error, isLoading, refetch } = credsApi.query.list.useQuery(undefined, {enabled: isAuthenticated,// No retry for NOT_FOUND — the org won't materialise on its own.// Cap retries for other errors (500s, network) so failures surface instead of looping.@@ -116,42 +102,19 @@ const WorkspaceCredsSetting = () => {},});- // Same dedup trick for the personal scope: shares its query key with the- // list inside PersonalCredsSection, so a create from the unified header- // refreshes that tab's list (and pre-warms it while the workspace tab is- // active, since the tabs render only the active scope).- const { refetch: refetchPersonalCreds } = personalCredsApi.query.list.useQuery(undefined, {- enabled: isAuthenticated,- });-const orgMissing = isAuthenticated && !isLoading && error?.data?.code === 'NOT_FOUND';- // The Admin-or-higher `manage_provider_key` gate mirrors the server's- // `requireWorkspaceRole('admin')` on workspaceCreds writes — but it only- // applies to the workspace scope. Personal credentials are the caller's own- // (`market.creds`), so workspace RBAC never disables creation there.- const canCreate = scope === 'workspace' ? canManageCredentials : true;- const createBlockedReason = scope === 'workspace' && !canManageCredentials ? reason : '';+ // Shared credentials need the Admin-or-higher `manage_provider_key`, matching+ // the server; private ones are any non-viewer member's own.+ const canCreate = tab === 'public' ? isAdmin : !isViewer;+ const createBlockedReason =+ tab === 'public' ? (isAdmin ? '' : reason) : isViewer ? t('creds.viewerHint') : '';const handleCreate = () => {if (!canCreate) return;- if (scope === 'workspace') {- createCreateCredModal({- credsApi: workspaceCredsApi,- onSuccess: () => refetchWorkspaceCreds(),- });- } else {- createCreateCredModal({- credsApi: personalCredsApi,- onSuccess: () => refetchPersonalCreds(),- });- }+ createCreateCredModal({ credsApi, onSuccess: () => refetch() });};- // Hidden while signed out (the list shows the sign-in prompt instead) and- // while the workspace org is missing (creation would fail server-side).- const showCreateButton = isAuthenticated && !(scope === 'workspace' && orgMissing);-const createButton = (<Buttondisabled={!canCreate}@@ -167,22 +130,15 @@ const WorkspaceCredsSetting = () => {<Flexbox gap={16}><Flexbox horizontal align={'center'} gap={16} justify={'space-between'}><Tabs- activeKey={scope}+ activeKey={tab}items={[- {- icon: <Icon icon={UsersIcon} />,- key: 'workspace',- label: t('creds.tabs.workspace'),- },- {- icon: <Icon icon={UserRoundIcon} />,- key: 'personal',- label: t('creds.tabs.personal'),- },+ { icon: <Icon icon={UsersIcon} />, key: 'public', label: t('creds.tabs.workspace') },+ { icon: <Icon icon={Lock} />, key: 'private', label: t('creds.tabs.private') },]}- onChange={(key) => setScope(key as CredsScope)}+ onChange={(key) => setTab(key as Visibility)}/>- {showCreateButton &&+ {isAuthenticated &&+ !orgMissing &&// Disabled buttons swallow hover events, so the tooltip needs the// span wrapper to fire (see the usePermission docstring pattern).(createBlockedReason ? (@@ -195,24 +151,18 @@ const WorkspaceCredsSetting = () => {</Flexbox><Flexbox gap={12}><Text className={styles.desc}>- {scope === 'workspace'- ? t('creds.workspaceSection.desc')- : t('creds.personalSection.desc')}+ {t(tab === 'public' ? 'creds.workspaceSection.desc' : 'creds.privateSection.desc')}</Text><Block className={styles.container} variant={'outlined'}>- {scope === 'workspace' ? (- orgMissing ? (+ <MarketSignInGate>+ {orgMissing ? (<Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}><Empty description={t('creds.orgSetupRequired')} /></Flexbox>) : (- <CredsApiProvider value={workspaceCredsApi}>- <CredsList />- </CredsApiProvider>- )- ) : (- <PersonalCredsSection onWorkspaceCredsChange={refetchWorkspaceCreds} />- )}+ <WorkspaceCredsList credsApi={credsApi} key={tab} visibility={tab} />+ )}+ </MarketSignInGate></Block></Flexbox></Flexbox>diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsxindex 60e8906a53a..ee967612984 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/CloudHeterogeneousConfig.tsx@@ -292,11 +292,7 @@ const TokenSection = memo<TokenSectionProps>({tokenStatus.status === 'personalNotShared' && (<Text fontSize={12} type={'warning'}>- {t(- tokenStatus.sharedElsewhere- ? 'heterogeneousStatus.cloud.tokenSharedElsewhere'- : 'heterogeneousStatus.cloud.tokenNotShared',- )}+ {t('heterogeneousStatus.cloud.tokenNotShared')}</Text>)}