🤯 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): share personal credentials into workspace + AI ownership disclosure (#16895)
LiJian0a86de36e4b0
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.tsindex be934e98b02..f67d6b8a402 100644--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts@@ -616,6 +616,11 @@ export const callLlm =description: cred.description,key: cred.key,name: cred.name,+ // Only present on the workspace-merged list (organizations.creds().list())+ // above — tells the AI whether this credential is the workspace's own or a+ // member's shared one, so it never misrepresents whose secret it's using.+ ownerDisplayName: cred.ownerDisplayName,+ ownerType: cred.ownerType,type: cred.type,})),);diff --git a/apps/server/src/routers/lambda/market/creds.test.ts b/apps/server/src/routers/lambda/market/creds.test.tsindex 35ca0f50685..9b2681be330 100644--- a/apps/server/src/routers/lambda/market/creds.test.ts+++ b/apps/server/src/routers/lambda/market/creds.test.ts@@ -1,9 +1,27 @@// @vitest-environment node+import { MarketAPIError } from '@lobehub/market-sdk';import { beforeEach, describe, expect, it, vi } from 'vitest';-const { mockOrgCredsList, mockPersonalCredsList } = vi.hoisted(() => ({- mockOrgCredsList: vi.fn(async () => ({ data: [{ id: 1, key: 'ORG_SECRET' }] })),+interface MockOrgCredRow {+ id: number;+ key: string;+ ownerType?: string;+}++const {+ mockOrgCredsList,+ mockPersonalCredsList,+ mockPersonalCredsShare,+ mockPersonalCredsPublish,+ mockPersonalCredsUnshare,+} = vi.hoisted(() => ({+ mockOrgCredsList: vi.fn(async (): Promise<{ data: MockOrgCredRow[] }> => ({+ data: [{ id: 1, key: 'ORG_SECRET' }],+ })),mockPersonalCredsList: vi.fn(async () => ({ 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' })),}));vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({@@ -11,10 +29,7 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({}));// Simulates the real `cloudWorkspaceAuth`: strips `workspaceId` off the-// context unless the caller is flagged as a workspace member. This is the-// gate `credsAccessor` must never be reachable around — regression test for-// the P1 finding where `ctx.workspaceId` (raw off `X-Workspace-Id`) was read-// before any membership check existed.+// context unless the caller is flagged as a workspace member.vi.mock('@/business/server/trpc-middlewares/workspaceAuth', () => ({cloudWorkspaceAuth: vi.fn((opts: any) =>opts.next({@@ -42,7 +57,12 @@ vi.mock('@/libs/trpc/lambda/middleware', () => ({vi.mock('@/server/services/market', () => ({MarketService: vi.fn(() => ({market: {- creds: { list: mockPersonalCredsList },+ creds: {+ list: mockPersonalCredsList,+ publish: mockPersonalCredsPublish,+ share: mockPersonalCredsShare,+ unshare: mockPersonalCredsUnshare,+ },organizations: {creds: vi.fn(() => ({ list: mockOrgCredsList })),},@@ -50,12 +70,24 @@ vi.mock('@/server/services/market', () => ({})),}));-describe('credsRouter workspace routing', () => {+describe('credsRouter is always personal-scoped', () => {beforeEach(() => {vi.clearAllMocks();});- it('routes to organization creds only when the caller is a verified workspace member', async () => {+ // `market.creds` is the personal-creds router used directly by the browser+ // (standalone /settings/creds page, and the workspace creds page's "your+ // personal credentials" section). `ctx.workspaceId` is ambient — set on+ // every request whenever the caller has *any* workspace selected elsewhere+ // in the app, regardless of which page/section made the call. Routing+ // `list` (or any other procedure here) off that ambient value previously+ // made this router silently return the active workspace's org creds+ // 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.+ it('returns personal creds data, never the org list, when the caller is a verified workspace member', async () => {const { credsRouter } = await import('./creds');const caller = credsRouter.createCaller({@@ -66,21 +98,17 @@ describe('credsRouter workspace routing', () => {const result = await caller.list();- expect(mockOrgCredsList).toHaveBeenCalledTimes(1);- expect(mockPersonalCredsList).not.toHaveBeenCalled();- expect(result.data).toEqual([{ id: 1, key: 'ORG_SECRET' }]);+ expect(mockPersonalCredsList).toHaveBeenCalledTimes(1);+ expect(result.data?.map((c) => c.id)).toEqual([2]);+ expect(result.data?.every((c) => c.key !== 'ORG_SECRET')).toBe(true);});- it('falls back to personal creds when the caller sends a workspaceId it is not a member of', async () => {+ it('resolves personal creds outside any workspace context, without consulting the org list at all', async () => {const { credsRouter } = await import('./creds');- // Simulates a request forging `X-Workspace-Id` for a workspace the caller- // does not belong to — cloudWorkspaceAuth (mocked above) must strip it- // before `credsAccessor` ever sees it.const caller = credsRouter.createCaller({isWorkspaceMember: false,userId: 'user-1',- workspaceId: 'someone-elses-workspace',} as any);const result = await caller.list();@@ -90,3 +118,151 @@ describe('credsRouter workspace routing', () => {expect(result.data).toEqual([{ id: 2, key: 'PERSONAL_SECRET' }]);});});++describe('credsRouter list scopes sharing to the active workspace', () => {+ beforeEach(() => {+ 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 { 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: false },+ ]);+ });++ 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);++ const result = await caller.list();++ expect(result.data).toEqual([{ id: 2, key: 'PERSONAL_SECRET' }]);+ });+});++describe('credsRouter share/publish/unshare', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('shares a personal credential into the caller-verified workspace, never a client-supplied org', async () => {+ const { credsRouter } = await import('./creds');++ const caller = credsRouter.createCaller({+ isWorkspaceMember: true,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ } as any);++ await caller.share({ id: 42, visibility: 'private' });++ expect(mockPersonalCredsShare).toHaveBeenCalledWith(42, {+ orgId: 'workspace:workspace-1',+ visibility: 'private',+ });+ });++ it('rejects share when there is no active (verified) workspace context', async () => {+ const { credsRouter } = await import('./creds');++ // Simulates both the personal-mode case (no header) and the forged-header+ // case (cloudWorkspaceAuth already stripped workspaceId for a non-member).+ const caller = credsRouter.createCaller({+ isWorkspaceMember: false,+ userId: 'user-1',+ } as any);++ await expect(caller.share({ id: 42 })).rejects.toThrow(+ 'Sharing a credential requires an active workspace context',+ );+ expect(mockPersonalCredsShare).not.toHaveBeenCalled();+ });++ it('publishes a draft-linked credential without requiring an org id', async () => {+ const { credsRouter } = await import('./creds');++ const caller = credsRouter.createCaller({+ isWorkspaceMember: true,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ } as any);++ const result = await caller.publish({ id: 42 });++ expect(mockPersonalCredsPublish).toHaveBeenCalledWith(42);+ expect(result).toEqual({ id: 42, visibility: 'public' });+ });++ it('unshares a credential, clearing its workspace link', async () => {+ const { credsRouter } = await import('./creds');++ const caller = credsRouter.createCaller({+ isWorkspaceMember: true,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ } as any);++ const result = await caller.unshare({ id: 42 });++ expect(mockPersonalCredsUnshare).toHaveBeenCalledWith(42);+ expect(result).toEqual({ id: 42, visibility: 'private' });+ });++ it('maps a Market 403 (not a member) to a tRPC FORBIDDEN error', async () => {+ mockPersonalCredsShare.mockRejectedValueOnce(+ new MarketAPIError(403, 'Forbidden', { error: 'Not a member of this organization' }),+ );+ const { credsRouter } = await import('./creds');++ const caller = credsRouter.createCaller({+ isWorkspaceMember: true,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ } as any);++ await expect(caller.share({ id: 42 })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: 'Not a member of this organization',+ });+ });+});diff --git a/apps/server/src/routers/lambda/market/creds.ts b/apps/server/src/routers/lambda/market/creds.tsindex 351aad34e3b..5ce5c472034 100644--- a/apps/server/src/routers/lambda/market/creds.ts+++ b/apps/server/src/routers/lambda/market/creds.ts@@ -1,3 +1,4 @@+import { MarketAPIError, orgRefToPathSegment } from '@lobehub/market-sdk';import { TRPCError } from '@trpc/server';import debug from 'debug';import { z } from 'zod';@@ -10,15 +11,38 @@ import { MarketService } from '@/server/services/market';const log = debug('lambda-router:market:creds');+const MARKET_STATUS_TO_TRPC_CODE: Record<number, TRPCError['code']> = {+ 400: 'BAD_REQUEST',+ 403: 'FORBIDDEN',+ 404: 'NOT_FOUND',+};++/**+ * Maps a Market API error (share/publish/unshare return structured 400/403/404+ * responses — invalid org, not a member, credential/org not found) to the+ * matching tRPC error code so the frontend can distinguish them instead of+ * seeing a blanket 500.+ */+function mapMarketShareError(error: unknown, fallbackMessage: string): TRPCError {+ if (error instanceof MarketAPIError) {+ return new TRPCError({+ cause: error,+ code: MARKET_STATUS_TO_TRPC_CODE[error.status] ?? 'INTERNAL_SERVER_ERROR',+ message: error.message || fallbackMessage,+ });+ }+ return new TRPCError({ cause: error, code: 'INTERNAL_SERVER_ERROR', message: fallbackMessage });+}+// Creds procedure with market authenticationconst credsProcedure = publicProcedure.use(serverDatabase)// `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 — so the- // `credsAccessor` routing below can never be pointed at a workspace the- // caller doesn't belong to. Must run before any procedure reads `ctx.workspaceId`.+ // `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..use(cloudWorkspaceAuth).use(marketUserInfo).use(requireMarketAuth)@@ -34,23 +58,6 @@ const credsProcedure = publicProcedure});const credsManageProcedure = credsProcedure.use(withRbacPermission('workspace:update:all'));-/**- * Inside a workspace, reads/writes must hit the workspace's shared organization- * credentials, never the operator's personal creds (LOBE-10978). `ctx.workspaceId`- * is only ever set here once `cloudWorkspaceAuth` (above) has confirmed the- * caller is a member of that workspace — never trust it directly off the raw- * `X-Workspace-Id` header. Falls back to the personal `market.creds` namespace- * outside a workspace.- *- * NOTE: unlike `workspaceCreds.ts`, writes routed through here do not (yet) emit- * a `CloudWorkspaceAuditLogModel` entry — audit logging for this path is a- * follow-up, tracked alongside LOBE-10978.- */-const credsAccessor = (ctx: { marketService: MarketService; workspaceId?: string | null }) =>- ctx.workspaceId- ? ctx.marketService.market.organizations.creds({ workspaceId: ctx.workspaceId })- : ctx.marketService.market.creds;-export const credsRouter = router({// Create file credentialcreateFile: credsManageProcedure@@ -67,7 +74,7 @@ export const credsRouter = router({log('createFile input: %O', { ...input, fileHashId: '[HIDDEN]' });try {- const result = await credsAccessor(ctx).createFile(input);+ const result = await ctx.marketService.market.creds.createFile(input);log('createFile success: id=%d', result.id);return result;} catch (error) {@@ -95,7 +102,7 @@ export const credsRouter = router({log('createKV input: %O', { ...input, values: '[HIDDEN]' });try {- const result = await credsAccessor(ctx).createKV(input);+ const result = await ctx.marketService.market.creds.createKV(input);log('createKV success: id=%d', result.id);return result;} catch (error) {@@ -122,7 +129,7 @@ export const credsRouter = router({log('createOAuth input: %O', input);try {- const result = await credsAccessor(ctx).createOAuth(input);+ const result = await ctx.marketService.market.creds.createOAuth(input);log('createOAuth success: id=%d', result.id);return result;} catch (error) {@@ -142,7 +149,7 @@ export const credsRouter = router({log('delete input: %O', input);try {- const result = await credsAccessor(ctx).delete(input.id);+ const result = await ctx.marketService.market.creds.delete(input.id);log('delete success');return result;} catch (error) {@@ -162,7 +169,7 @@ export const credsRouter = router({log('deleteByKey input: %O', input);try {- const result = await credsAccessor(ctx).deleteByKey(input.key);+ const result = await ctx.marketService.market.creds.deleteByKey(input.key);log('deleteByKey success');return result;} catch (error) {@@ -187,7 +194,7 @@ export const credsRouter = router({log('get input: %O', input);try {- const result = await credsAccessor(ctx).get(input.id, {+ const result = await ctx.marketService.market.creds.get(input.id, {decrypt: input.decrypt,});log('get success: id=%d', input.id);@@ -215,7 +222,7 @@ export const credsRouter = router({try {// First find the credential by key from the list- const listResult = await credsAccessor(ctx).list();+ const listResult = await ctx.marketService.market.creds.list();const cred = listResult.data?.find((c) => c.key === input.key);if (!cred) {@@ -226,7 +233,7 @@ export const credsRouter = router({}// Then get the full credential with optional decryption- const result = await credsAccessor(ctx).get(cred.id, {+ const result = await ctx.marketService.market.creds.get(cred.id, {decrypt: input.decrypt,});log('getByKey success: key=%s, id=%d', input.key, cred.id);@@ -249,7 +256,9 @@ export const credsRouter = router({log('getSkillCredStatus input: %O', input);try {- const result = await credsAccessor(ctx).getSkillCredStatus(input.skillIdentifier);+ const result = await ctx.marketService.market.creds.getSkillCredStatus(+ input.skillIdentifier,+ );log('getSkillCredStatus success: %d items', result.length);return result;} catch (error) {@@ -262,11 +271,70 @@ 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: 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);+ log('publish success: id=%d', result.id);+ return result;+ } catch (error) {+ log('publish error: %O', error);+ throw mapMarketShareError(error, 'Failed to publish credential');+ }+ }),++ // Share one of the caller's own personal credentials into the current+ // 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).+ share: credsProcedure+ .input(+ z.object({+ id: z.number(),+ visibility: z.enum(['private', 'public']).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ if (!ctx.workspaceId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Sharing a credential requires an active workspace context',+ });+ }+ log('share input: id=%d, visibility=%s', input.id, input.visibility);+ try {+ const result = await ctx.marketService.market.creds.share(input.id, {+ orgId: orgRefToPathSegment({ workspaceId: ctx.workspaceId }),+ visibility: input.visibility,+ });+ log('share success: id=%d', result.id);+ return result;+ } catch (error) {+ log('share error: %O', error);+ throw mapMarketShareError(error, 'Failed to share credential');+ }+ }),++ // Unshare a credential from its organization (flips back to private,+ // clears the link). Does not delete the credential.+ 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);+ log('unshare success: id=%d', result.id);+ return result;+ } catch (error) {+ log('unshare error: %O', error);+ throw mapMarketShareError(error, 'Failed to unshare credential');+ }+ }),+// Inject credentials by keys (explicit injection).- // NOTE: intentionally NOT routed through `credsAccessor` — the Market SDK's- // org-scoped creds service has no `inject` equivalent yet (LOBE-10978), so- // this always resolves against the operator's personal credentials, even- // inside a workspace.inject: credsProcedure.input(z.object({@@ -344,9 +412,43 @@ export const credsRouter = router({log('list called');try {- const result = await credsAccessor(ctx).list();+ const result = await ctx.marketService.market.creds.list();log('list success: %d credentials', result.data?.length ?? 0);- return result;++ 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;+ }} catch (error) {log('list error: %O', error);throw new TRPCError({@@ -388,10 +490,7 @@ export const credsRouter = router({log('uploadFile input: fileName=%s, fileType=%s', input.fileName, input.fileType);try {- const result = await ctx.marketService.uploadCredFile({- ...input,- orgId: ctx.workspaceId ? { workspaceId: ctx.workspaceId } : undefined,- });+ const result = await ctx.marketService.uploadCredFile(input);log('uploadFile success: fileHashId=%s', result.fileHashId);return result;} catch (error) {@@ -422,7 +521,7 @@ export const credsRouter = router({});try {- const result = await credsAccessor(ctx).update(id, data);+ const result = await ctx.marketService.market.creds.update(id, data);log('update success');return result;} catch (error) {diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex b6d1433c073..dc9f1898253 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -241,6 +241,13 @@"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.sharedBy": "Shared by {{name}}",+ "creds.personalSection.desc": "These are your own credentials. Turn on sharing to make one available to this workspace.",+ "creds.personalSection.title": "Your Personal Credentials",+ "creds.share.error": "Failed to update sharing for this credential. Please try again.",+ "creds.share.toggle": "Share to this workspace",+ "creds.share.visibility.private": "Private",+ "creds.share.visibility.public": "Public","creds.signIn": "Sign In to Market","creds.signInRequired": "Please sign in to the Market to manage your credentials","creds.table.actions": "Actions",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex c2b0ce7e77e..bd69c6ef8c3 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -241,6 +241,13 @@"creds.form.values": "键值对","creds.oauth.noConnections": "暂无可用的 OAuth 连接,请先连接账户。","creds.orgSetupRequired": "社区资料尚未设置,请先完成工作区的社区资料设置,再管理凭证。",+ "creds.owner.sharedBy": "由 {{name}} 共享",+ "creds.personalSection.desc": "这些是您自己的凭证。开启共享后可让此工作区使用该凭证。",+ "creds.personalSection.title": "您的个人凭证",+ "creds.share.error": "更新该凭证的共享状态失败,请重试。",+ "creds.share.toggle": "共享到此工作区",+ "creds.share.visibility.private": "私密",+ "creds.share.visibility.public": "公开","creds.signIn": "登录 Market","creds.signInRequired": "请登录 Market 以管理您的凭证","creds.table.actions": "操作",diff --git a/package.json b/package.jsonindex 7fcfb2332cf..92e870c850a 100644--- a/package.json+++ b/package.json@@ -294,7 +294,7 @@"@lobehub/desktop-ipc-typings": "workspace:*","@lobehub/editor": "^4.19.1","@lobehub/icons": "^5.10.0",- "@lobehub/market-sdk": "0.39.1",+ "@lobehub/market-sdk": "0.39.2","@lobehub/tts": "^5.1.2","@lobehub/ui": "^5.19.0","@modelcontextprotocol/sdk": "^1.29.0",diff --git a/packages/builtin-tool-creds/src/helpers.test.ts b/packages/builtin-tool-creds/src/helpers.test.tsnew file mode 100644index 00000000000..9c70c818fad--- /dev/null+++ b/packages/builtin-tool-creds/src/helpers.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { generateCredsList } from './helpers';++describe('generateCredsList', () => {+ it("tags a member-shared credential with who shared it, never as the workspace's own", () => {+ const result = generateCredsList([+ {+ key: 'github',+ name: 'GitHub Token',+ ownerDisplayName: 'Alice',+ ownerType: 'user',+ type: 'kv-env',+ },+ ]);++ expect(result).toContain('[shared by Alice]');+ expect(result).not.toContain('[workspace credential]');+ });++ it('tags a workspace-owned credential distinctly from a shared one', () => {+ const result = generateCredsList([+ { key: 'openai', name: 'OpenAI Key', ownerType: 'organization', type: 'kv-env' },+ ]);++ expect(result).toContain('[workspace credential]');+ expect(result).not.toContain('[shared by');+ });++ it('falls back to a generic label when a shared credential has no owner display name', () => {+ const result = generateCredsList([+ { key: 'github', name: 'GitHub Token', ownerType: 'user', type: 'kv-env' },+ ]);++ expect(result).toContain('[shared by a workspace member]');+ });++ it('adds no ownership tag for a personal-only list (ownerType absent)', () => {+ const result = generateCredsList([{ key: 'openai', name: 'OpenAI Key', type: 'kv-env' }]);++ expect(result).not.toContain('[shared by');+ expect(result).not.toContain('[workspace credential]');+ });+});diff --git a/packages/builtin-tool-creds/src/helpers.ts b/packages/builtin-tool-creds/src/helpers.tsindex d2003e40051..4fe8130e904 100644--- a/packages/builtin-tool-creds/src/helpers.ts+++ b/packages/builtin-tool-creds/src/helpers.ts@@ -7,6 +7,16 @@ export interface CredSummary {description?: string;key: string;name: string;+ /**+ * Only populated when the list comes from a workspace's merged+ * organization-scoped view (org-owned creds + members' shared creds):+ * 'organization' for a credential the workspace created directly, 'user'+ * for one a member shared in. The AI needs this to tell the user whose+ * credential it's actually using — never silently treat a member's shared+ * key as if the workspace owns it. Absent entirely for a personal-only list.+ */+ ownerDisplayName?: string;+ ownerType?: 'organization' | 'user';type: CredType;}@@ -41,7 +51,13 @@ export const groupCredsByType = (creds: CredSummary[]): Record<CredType, CredSum*/const formatCred = (cred: CredSummary): string => {const desc = cred.description ? ` - ${cred.description}` : '';- return ` - ${cred.name} (key: ${cred.key})${desc}`;+ const ownership =+ cred.ownerType === 'user'+ ? ` [shared by ${cred.ownerDisplayName ?? 'a workspace member'}]`+ : cred.ownerType === 'organization'+ ? ' [workspace credential]'+ : '';+ return ` - ${cred.name} (key: ${cred.key})${desc}${ownership}`;};/**diff --git a/packages/builtin-tool-creds/src/systemRole.ts b/packages/builtin-tool-creds/src/systemRole.tsindex b5d36adc4b1..0178a988a59 100644--- a/packages/builtin-tool-creds/src/systemRole.ts+++ b/packages/builtin-tool-creds/src/systemRole.ts@@ -21,6 +21,7 @@ Sandbox mode: {{sandbox_enabled}}1. **Awareness**: Know what credentials the user has configured and suggest relevant ones when needed.2. **Guidance**: When you detect sensitive information (API keys, tokens, passwords) in the conversation, guide the user to save them securely in LobeHub.3. **Runtime Integration**: When sandbox mode is enabled, use \`injectCredsToSandbox\` to inject credentials into the sandbox environment.+4. **Ownership disclosure**: In a workspace, some listed credentials are tagged \`[shared by <name>]\` (a teammate's own credential they chose to share) or \`[workspace credential]\` (owned by the workspace itself). Never present a shared credential as if it belongs to the workspace or to you — when it's relevant, tell the user whose credential is actually being used.</core_responsibilities><tooling>diff --git a/packages/builtin-tool-creds/vitest.config.mts b/packages/builtin-tool-creds/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-creds/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex eb45a8f9091..7623561a182 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -290,7 +290,16 @@ export default {'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.orgSetupRequired':+ 'Community Profile not set up yet. Please complete the workspace Community Profile setup to manage credentials.',+ '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.personalSection.title': 'Your Personal Credentials',+ 'creds.share.error': 'Failed to update sharing for this credential. Please try again.',+ 'creds.share.toggle': 'Share to this workspace',+ 'creds.share.visibility.private': 'Private',+ 'creds.share.visibility.public': 'Public','creds.signIn': 'Sign In to Market','creds.signInRequired': 'Please sign in to the Market to manage your credentials','creds.form.addPair': 'Add Key-Value Pair',diff --git a/packages/types/package.json b/packages/types/package.jsonindex cc2deebe286..ff4993714ee 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -10,7 +10,7 @@"test:update": "vitest -u"},"dependencies": {- "@lobehub/market-sdk": "0.39.1",+ "@lobehub/market-sdk": "0.39.2","@lobehub/market-types": "^1.17.1","model-bank": "workspace:*","type-fest": "^4.41.0",diff --git a/packages/types/src/creds/index.ts b/packages/types/src/creds/index.tsindex 3e90efbbeca..408b912d40e 100644--- a/packages/types/src/creds/index.ts+++ b/packages/types/src/creds/index.ts@@ -23,8 +23,51 @@ export interface UserCredSummary {oauthAvatar?: string;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`).+ */+ organizationAccountId?: number;+ /**+ * Owner account id of this credential, only populated in organization-scoped+ * list/get responses (`workspaceCreds.list` / `workspaceCreds.get`).+ */+ ownerAccountId?: number;+ /** See `ownerAccountId`. */+ ownerDisplayName?: string;+ /** See `ownerAccountId`. */+ ownerNamespace?: string;+ /**+ * 'organization' when the organization created this credential directly;+ * 'user' when a member shared their own personal credential in. Only+ * populated in organization-scoped list/get responses.+ */+ ownerType?: 'organization' | 'user';+ /**+ * Timestamp when `visibility` last became 'public'. Unset while only+ * draft-linked (`organizationAccountId` set, `visibility` still 'private').+ */+ 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.+ */+ sharedToActiveWorkspace?: boolean;type: CredType;updatedAt: string;+ /**+ * 'private' (default, only the owning account can see/use it) or 'public'+ * (shared with organizationAccountId's members).+ */+ visibility?: 'private' | 'public';}// ===== Credential with Plaintext (for editing) =====@@ -66,6 +109,17 @@ export interface UpdateCredRequest {values?: Record<string, string>; // Only for KV types}+// ===== Share Request =====++/**+ * Shares one of the caller's own personal credentials into a workspace's+ * Market organization. Defaults to `visibility: 'public'` (immediately+ * visible to the org); pass `'private'` to only link it as a draft.+ */+export interface ShareCredRequest {+ visibility?: 'private' | 'public';+}+// ===== Get Options =====export interface GetCredOptions {diff --git a/src/routes/(main)/[workspaceSlug]/settings/creds/features/PersonalCredsSection/ShareToggle.tsx b/src/routes/(main)/[workspaceSlug]/settings/creds/features/PersonalCredsSection/ShareToggle.tsxnew file mode 100644index 00000000000..07b59f152d6--- /dev/null+++ b/src/routes/(main)/[workspaceSlug]/settings/creds/features/PersonalCredsSection/ShareToggle.tsx@@ -0,0 +1,134 @@+'use client';++import { type UserCredSummary } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Segmented, Switch } from '@lobehub/ui/base-ui';+import { useMutation } from '@tanstack/react-query';+import { App } from 'antd';+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');+ const { message } = App.useApp();+ // 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: () => {+ message.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: () => {+ message.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}>+ {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}+ title={t('creds.share.toggle')}+ onChange={handleSwitchChange}+ />+ </Flexbox>+ );+};++export default ShareToggle;diff --git a/src/routes/(main)/[workspaceSlug]/settings/creds/features/PersonalCredsSection/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/creds/features/PersonalCredsSection/index.tsxnew file mode 100644index 00000000000..7f004e6fe27--- /dev/null+++ b/src/routes/(main)/[workspaceSlug]/settings/creds/features/PersonalCredsSection/index.tsx@@ -0,0 +1,133 @@+'use client';++import { type UserCredSummary } from '@lobechat/types';+import { Flexbox, Text } from '@lobehub/ui';+import { useMutation } from '@tanstack/react-query';+import { Empty, Spin } from 'antd';+import { createStaticStyles } from 'antd-style';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';+import CredItem from '@/routes/(main)/settings/creds/features/CredItem';+import { createEditCredModal } from '@/routes/(main)/settings/creds/features/EditCredModal';+import { createViewCredModal } from '@/routes/(main)/settings/creds/features/ViewCredModal';++import ShareToggle from './ShareToggle';++// Always the personal namespace — this section is deliberately personal-scoped+// regardless of page context, so it bypasses `useCredsApi()` entirely.+const personalCredsApi = { client: lambdaClient.market.creds, query: lambdaQuery.market.creds };++const styles = createStaticStyles(({ css }) => ({+ desc: css`+ margin-block-end: 12px;+ font-size: 13px;+ color: var(--lobe-color-text-secondary);+ `,+ empty: css`+ padding-block: 32px;+ padding-inline: 0;+ `,+ title: css`+ margin-block-end: 4px;+ font-size: 16px;+ font-weight: 600;+ `,+}));++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>;+}++/**+ * Bottom section of the workspace creds page: the caller's own *personal*+ * credentials, each with a {@link ShareToggle} to share/unshare it into the+ * current workspace's Market organization.+ *+ * 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 section above.+ // Deleting or editing a credential that's currently shared/public changes+ // what the workspace's merged list should show (a removed credential, or+ // updated name/description) just as much as share/unshare/visibility does+ // — the workspace section has no way to know on its own, since it reads a+ // disjoint (org-scoped) query.+ const refetchLists = async () => {+ await Promise.all([refetch(), onWorkspaceCredsChange()]);+ };++ const deleteMutation = useMutation({+ mutationFn: async (id: number) => {+ await lambdaClient.market.creds.delete.mutate({ id });+ },+ onSuccess: refetchLists,+ });++ const credentials = data?.data ?? [];++ const handleEdit = (cred: UserCredSummary) => {+ createEditCredModal({+ credsApi: personalCredsApi,+ cred,+ onSuccess: refetchLists,+ });+ };++ const handleView = (cred: UserCredSummary) => {+ createViewCredModal({ credsApi: personalCredsApi, cred });+ };++ return (+ <Flexbox gap={0} style={{ marginBlockStart: 32 }}>+ <Text className={styles.title}>{t('creds.personalSection.title')}</Text>+ <Text className={styles.desc}>{t('creds.personalSection.desc')}</Text>+ <AsyncBoundary+ data={data}+ empty={<Empty className={styles.empty} description={t('creds.empty')} />}+ error={error}+ errorVariant={'block'}+ isEmpty={credentials.length === 0}+ isLoading={isLoading}+ loading={+ <Flexbox align={'center'} justify={'center'} style={{ padding: 32 }}>+ <Spin />+ </Flexbox>+ }+ onRetry={() => refetch()}+ >+ <Flexbox gap={0}>+ {credentials.map((cred) => (+ <CredItem+ cred={cred}+ extra={<ShareToggle cred={cred} onChange={refetchLists} />}+ key={cred.id}+ onDelete={(id) => deleteMutation.mutate(id)}+ onEdit={handleEdit}+ onView={handleView}+ />+ ))}+ </Flexbox>+ </AsyncBoundary>+ </Flexbox>+ );+};++export default PersonalCredsSection;diff --git a/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsxindex 214f04d5c66..b176288b79a 100644--- a/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsx+++ b/src/routes/(main)/[workspaceSlug]/settings/creds/index.tsx@@ -13,19 +13,31 @@ import {CredsApiProvider,} from '@/routes/(main)/settings/creds/features/useCredsApi';+import PersonalCredsSection from './features/PersonalCredsSection';+/*** Workspace credential management.*- * Reuses the personal `<Page />` shell but rebinds every CredsApi consumer- * to the cloud `workspaceCreds.*` tRPC namespace via {@link CredsApiProvider}.- * `workspaceCreds` resolves the active workspace to its Market organization- * mirror and acts on the org's credential set so every workspace member sees- * the same shared creds.+ * Two sections:+ * - Top ("workspace"): reuses the personal `<Page />` shell but rebinds every+ * CredsApi consumer 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 {@link PersonalCredsSection}'s share toggle.+ * - Bottom ("your personal credentials"): {@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.** When the workspace has no Market organization yet (Community Profile not- * completed), the backend returns NOT_FOUND. This component intercepts that- * error and renders a setup prompt instead of letting it bubble up as a- * generic error boundary.+ * completed), the backend returns NOT_FOUND for the *workspace* section. This+ * component intercepts that error and renders a setup prompt in its place —+ * the personal section still renders below it, 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).*/const WorkspaceCredsSetting = () => {const { t } = useTranslation('setting');@@ -46,8 +58,18 @@ const WorkspaceCredsSetting = () => {// Pre-flight check: detect "org not set up" before rendering the full page.// React Query deduplicates this against the identical call inside CredsList,- // so only one network request is made.- const { error, isLoading } = workspaceCredsApi.query.list.useQuery(undefined, {+ // so only one network request is made — which is also why `refetch` here+ // refreshes the top section's list too: sharing/unsharing/re-visibility-ing+ // a credential from `PersonalCredsSection` below changes what this org-scoped+ // list should return, but that mutation lives in a different component 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, {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.@@ -60,16 +82,22 @@ const WorkspaceCredsSetting = () => {if (isAuthenticated && !isLoading && error?.data?.code === 'NOT_FOUND') {return (- <Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>- <Empty description={t('creds.orgSetupRequired')} />- </Flexbox>+ <>+ <Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>+ <Empty description={t('creds.orgSetupRequired')} />+ </Flexbox>+ <PersonalCredsSection onWorkspaceCredsChange={refetchWorkspaceCreds} />+ </>);}return (- <CredsApiProvider value={workspaceCredsApi}>- <Page />- </CredsApiProvider>+ <>+ <CredsApiProvider value={workspaceCredsApi}>+ <Page />+ </CredsApiProvider>+ <PersonalCredsSection onWorkspaceCredsChange={refetchWorkspaceCreds} />+ </>);};diff --git a/src/routes/(main)/settings/creds/features/CredItem.tsx b/src/routes/(main)/settings/creds/features/CredItem.tsxindex b95e805d1bf..203920891d3 100644--- a/src/routes/(main)/settings/creds/features/CredItem.tsx+++ b/src/routes/(main)/settings/creds/features/CredItem.tsx@@ -23,6 +23,12 @@ import { styles } from './style';interface CredItemProps {cred: UserCredSummary;+ /**+ * Extra content rendered before the "..." menu — used by the workspace+ * creds page to slot in the personal-credential share toggle without+ * duplicating this row's layout.+ */+ extra?: React.ReactNode;onDelete: (id: number) => void;onEdit: (cred: UserCredSummary) => void;onView: (cred: UserCredSummary) => void;@@ -42,7 +48,7 @@ const typeColors: Record<string, string> = {'oauth': 'green',};-const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) => {+const CredItem: FC<CredItemProps> = memo(({ cred, extra, onEdit, onDelete, onView }) => {const { t } = useTranslation('setting');const { allowed: canManageCredentials } = usePermission('manage_provider_key');@@ -111,6 +117,11 @@ const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) =><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>@@ -124,6 +135,7 @@ const CredItem: FC<CredItemProps> = memo(({ cred, onEdit, onDelete, onView }) =></Flexbox></Flexbox><Flexbox horizontal align="center" gap={8} onClick={stopPropagation}>+ {extra}<DropdownMenu items={menuItems} placement="bottomRight"><Button disabled={!canManageCredentials} icon={MoreHorizontalIcon} /></DropdownMenu>