Skip to content

๐Ÿคฏ 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.

โœจ feat(agent-quota): keep reported subscription accounts private and let their creator share them (#22756)

Arvin Xua4f67106abc5
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.accountVisibility.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.accountVisibility.test.ts
new file mode 100644
index 00000000000..8a7abff180c
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.accountVisibility.test.ts
@@ -0,0 +1,98 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: {} }));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn(function () {
+ return {
+ findByDeviceId: vi.fn(async (id: string) => (id === 'gateway-a' ? { id: 'row-a' } : null)),
+ findWorkspaceDeviceById: vi.fn(),
+ };
+ }),
+}));
+
+/** The caller sees `acc-visible`; `acc-hidden` is another member's private account. */
+const findById = vi.fn(async (id: string) => (id === 'acc-visible' ? { id } : null));
+const upsertBinding = vi.fn();
+const pinBinding = vi.fn();
+const listByAccount = vi.fn(async () => []);
+vi.mock('@/database/models/agentQuota', () => ({
+ AgentAccountBindingModel: vi.fn(function () {
+ return { pin: pinBinding, upsert: upsertBinding };
+ }),
+ AgentProviderAccountModel: vi.fn(function () {
+ return { findById };
+ }),
+ AgentQuotaWindowModel: vi.fn(function () {
+ return { listByAccount };
+ }),
+}));
+
+const service = {
+ listActiveRuns: vi.fn(async () => []),
+ listLatestReadings: vi.fn(async () => []),
+ listSnapshotSeries: vi.fn(async () => []),
+ listUsageTurns: vi.fn(async () => []),
+ setDeviceAccount: vi.fn(),
+};
+vi.mock('@/server/services/agentQuota', () => ({
+ AccountNotSignedInOnDeviceError: class extends Error {},
+ AgentQuotaService: vi.fn(function () {
+ return service;
+ }),
+}));
+
+const { agentQuotaRouter } = await import('../agentQuota');
+
+const caller = () =>
+ agentQuotaRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' } as any);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('agentQuota account visibility on id-addressed procedures', () => {
+ const calls = (accountId: string) => ({
+ bindAccount: () => caller().bindAccount({ accountId, agentId: 'agt-1' }),
+ getLatestReadings: () => caller().getLatestReadings({ accountId }),
+ getWindows: () => caller().getWindows({ accountId }),
+ listActiveRuns: () => caller().listActiveRuns({ accountId }),
+ listSnapshots: () => caller().listSnapshots({ accountId }),
+ listUsageTurns: () => caller().listUsageTurns({ accountId }),
+ setDeviceAccount: () =>
+ caller().setDeviceAccount({ accountId, agentId: 'agt-1', deviceId: 'gateway-a' }),
+ switchAccount: () => caller().switchAccount({ accountId, agentId: 'agt-1' }),
+ });
+
+ it.each(Object.keys(calls('')))('%s refuses an account the caller cannot see', async (name) => {
+ const call = calls('acc-hidden')[name as keyof ReturnType<typeof calls>];
+ await expect(call()).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(findById).toHaveBeenCalledWith('acc-hidden');
+ for (const fn of [...Object.values(service), upsertBinding, pinBinding, listByAccount])
+ expect(fn).not.toHaveBeenCalled();
+ });
+
+ it.each(Object.keys(calls('')))('%s serves an account the caller can see', async (name) => {
+ const call = calls('acc-visible')[name as keyof ReturnType<typeof calls>];
+ await call();
+ });
+
+ it('lets a device go back to Auto without naming an account', async () => {
+ await caller().setDeviceAccount({ accountId: null, agentId: 'agt-1', deviceId: 'gateway-a' });
+ expect(findById).not.toHaveBeenCalled();
+ expect(service.setDeviceAccount).toHaveBeenCalledWith('agt-1', 'row-a', null);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts
index 4d92c805418..8b856c81c53 100644
--- a/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts
@@ -29,7 +29,7 @@ vi.mock('@/database/models/agentQuota', () => ({
return {};
}),
AgentProviderAccountModel: vi.fn(function () {
- return {};
+ return { findById: vi.fn(async (id: string) => ({ id })) };
}),
AgentQuotaWindowModel: vi.fn(function () {
return {};
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.ts
index ac3ca439425..d57155523b0 100644
--- a/apps/server/src/routers/lambda/agentQuota.ts
+++ b/apps/server/src/routers/lambda/agentQuota.ts
@@ -48,6 +48,20 @@ const requireDeviceRowId = async (
return id;
};
+/**
+ * Refuse an account id the caller cannot see. Readings, windows, spend and
+ * runs carry no visibility of their own โ€” they inherit the account's โ€” so
+ * every procedure taking an id checks it here, or a private account would
+ * stay readable (and bindable) by anyone who learned its id while it was public.
+ */
+const requireVisibleAccount = async (
+ ctx: { accountModel: AgentProviderAccountModel },
+ accountId: string,
+): Promise<void> => {
+ if (!(await ctx.accountModel.findById(accountId)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Account not found' });
+};
+
const readingSchema = z.object({
capturedAt: z.number(),
windowMinutes: z.number().int().positive().optional(),
@@ -261,10 +275,20 @@ export const agentQuotaRouter = router({
value: z.object({
enabled: z.boolean().optional(),
label: z.string().optional(),
+ visibility: z.enum(['private', 'public']).optional(),
}),
}),
)
- .mutation(async ({ ctx, input }) => ctx.accountModel.update(input.id, input.value)),
+ .mutation(async ({ ctx, input }) => {
+ const { visibility, ...patch } = input.value;
+ if (visibility && !(await ctx.accountModel.setVisibility(input.id, visibility)))
+ // Personal accounts carry no visibility, and only the creator may change it.
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the member who added this account can change its visibility',
+ });
+ if (Object.keys(patch).length > 0) await ctx.accountModel.update(input.id, patch);
+ }),
// โ”€โ”€ bindings (agent โ†” account, incl. UI switch) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
bindAccount: quotaProcedure
@@ -277,7 +301,10 @@ export const agentQuotaRouter = router({
weight: z.number().optional(),
}),
)
- .mutation(async ({ ctx, input }) => ctx.bindingModel.upsert(input)),
+ .mutation(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.bindingModel.upsert(input);
+ }),
listBindings: quotaProcedure
.input(z.object({ agentId: z.string() }))
@@ -286,7 +313,10 @@ export const agentQuotaRouter = router({
/** UI "switch account": pin one account for an agent, demoting any prior pin. */
switchAccount: quotaProcedure
.input(z.object({ accountId: z.string(), agentId: z.string() }))
- .mutation(async ({ ctx, input }) => ctx.bindingModel.pin(input.agentId, input.accountId)),
+ .mutation(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.bindingModel.pin(input.agentId, input.accountId);
+ }),
unbindAccount: quotaProcedure
.input(z.object({ id: z.string() }))
@@ -312,6 +342,7 @@ export const agentQuotaRouter = router({
)
.mutation(async ({ ctx, input }) => {
const deviceRowId = await requireDeviceRowId(ctx, input.deviceId);
+ if (input.accountId) await requireVisibleAccount(ctx, input.accountId);
try {
await ctx.quotaService.setDeviceAccount(input.agentId, deviceRowId, input.accountId);
} catch (error) {
@@ -346,7 +377,10 @@ export const agentQuotaRouter = router({
// โ”€โ”€ quota read (QuotaMenu read model) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
getWindows: quotaProcedure
.input(z.object({ accountId: z.string(), limit: z.number().optional() }))
- .query(async ({ ctx, input }) => ctx.windowModel.listByAccount(input.accountId, input.limit)),
+ .query(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.windowModel.listByAccount(input.accountId, input.limit);
+ }),
/**
* Display read model: the newest reading per limit bucket. Prefer this over
@@ -355,7 +389,10 @@ export const agentQuotaRouter = router({
*/
getLatestReadings: quotaProcedure
.input(z.object({ accountId: z.string() }))
- .query(async ({ ctx, input }) => ctx.quotaService.listLatestReadings(input.accountId)),
+ .query(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.quotaService.listLatestReadings(input.accountId);
+ }),
/**
* Full reading time series (oldest first) for the usage calendar's daily
@@ -363,12 +400,13 @@ export const agentQuotaRouter = router({
*/
listSnapshots: quotaProcedure
.input(z.object({ accountId: z.string(), sinceDays: z.number().min(1).max(90).optional() }))
- .query(async ({ ctx, input }) =>
- ctx.quotaService.listSnapshotSeries(
+ .query(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.quotaService.listSnapshotSeries(
input.accountId,
new Date(Date.now() - (input.sinceDays ?? 42) * 24 * 60 * 60 * 1000),
- ),
- ),
+ );
+ }),
/**
* Per-turn token + cost spend (oldest first) for the usage calendar. Kept
@@ -377,17 +415,21 @@ export const agentQuotaRouter = router({
*/
listUsageTurns: quotaProcedure
.input(z.object({ accountId: z.string(), sinceDays: z.number().min(1).max(90).optional() }))
- .query(async ({ ctx, input }) =>
- ctx.quotaService.listUsageTurns(
+ .query(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.quotaService.listUsageTurns(
input.accountId,
new Date(Date.now() - (input.sinceDays ?? 42) * 24 * 60 * 60 * 1000),
- ),
- ),
+ );
+ }),
/** Agent runs in flight on an account โ€” who is spending it right now. */
listActiveRuns: quotaProcedure
.input(z.object({ accountId: z.string() }))
- .query(async ({ ctx, input }) => ctx.quotaService.listActiveRuns(input.accountId)),
+ .query(async ({ ctx, input }) => {
+ await requireVisibleAccount(ctx, input.accountId);
+ return ctx.quotaService.listActiveRuns(input.accountId);
+ }),
// โ”€โ”€ load balancing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
resolveAccountLoads: quotaProcedure
diff --git a/apps/server/src/services/agentQuota/__tests__/workspaceVisibility.test.ts b/apps/server/src/services/agentQuota/__tests__/workspaceVisibility.test.ts
new file mode 100644
index 00000000000..1f6bc828e7b
--- /dev/null
+++ b/apps/server/src/services/agentQuota/__tests__/workspaceVisibility.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { users, workspaces } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { AgentQuotaService } from '../index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const ownerId = 'agent-quota-visibility-owner';
+const teammateId = 'agent-quota-visibility-teammate';
+const workspaceId = 'agent-quota-visibility-ws';
+const identity = { email: '[email protected]', externalAccountId: 'acc-private-1' };
+const reading = (utilization: number) => ({
+ capturedAt: Date.now(),
+ limitType: 'session',
+ resetsAt: Date.now() + 3_600_000,
+ scopeKey: '',
+ utilization,
+});
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: ownerId }, { id: teammateId }]);
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Quota visibility',
+ primaryOwnerId: ownerId,
+ slug: workspaceId,
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('AgentQuotaService private workspace accounts', () => {
+ it("keeps another member's private account and its readings out of a teammate's reach", async () => {
+ const owner = new AgentQuotaService(serverDB, ownerId, workspaceId);
+ const teammate = new AgentQuotaService(serverDB, teammateId, workspaceId);
+
+ const account = (await owner.ingestSnapshot({
+ identity,
+ provider: 'claude-code',
+ readings: [reading(40)],
+ }))!;
+ expect(account.visibility).toBe('private');
+
+ // A report of the same identity neither returns the row nor lands readings in it.
+ await expect(
+ teammate.ingestSnapshot({ identity, provider: 'claude-code', readings: [reading(99)] }),
+ ).resolves.toBeUndefined();
+ expect((await owner.listLatestReadings(account.id)).map((r) => r.utilization)).toEqual([40]);
+
+ // Loads are derived from readings, so they follow the account's visibility.
+ await expect(teammate.resolveAccountLoads([account.id])).resolves.toEqual([]);
+ await expect(owner.resolveAccountLoads([account.id])).resolves.toHaveLength(1);
+ });
+});
diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.ts
index 896fc0ff00c..68da982043c 100644
--- a/apps/server/src/services/agentQuota/index.ts
+++ b/apps/server/src/services/agentQuota/index.ts
@@ -160,12 +160,17 @@ export class AgentQuotaService {
identity: QuotaAccountIdentity;
provider: string;
readings: QuotaLimitReading[];
- }): Promise<SafeAccount> => {
+ }): Promise<SafeAccount | undefined> => {
const account = await this.accounts.upsertByIdentity(
params.provider,
params.identity as AccountIdentityInput,
params.credentialRef ? { credentialRef: params.credentialRef } : {},
);
+ // Another member's private account: the reading is dropped rather than
+ // written into an account this member cannot see.
+ if (!account) return undefined;
+ // A sample read on a device proves the account is signed in there.
+ if (params.deviceId) await this.logins.record(account.id, params.deviceId);
// The wallet is not a limit reading, so it can't ride the snapshots table โ€”
// keep the latest sample on the account row or the persisted view loses the
// Extra Usage section between live samples.
@@ -174,8 +179,6 @@ export class AgentQuotaService {
metadata: { ...account.metadata, extraUsage: params.extraUsage },
});
}
- // A sample read on a device proves the account is signed in there.
- if (params.deviceId) await this.logins.record(account.id, params.deviceId);
await this.ingestReadings(account.id, params.readings, params.deviceId);
// Ingestion is the only moment new evidence arrives, so it is also the only
// sensible calibration trigger. Cheap and self-guarding: without enough clean
@@ -445,47 +448,51 @@ export class AgentQuotaService {
const accounts = await this.accounts.list();
const byId = new Map(accounts.map((a) => [a.id, a]));
+ // An id the caller cannot see (another member's private account) gets no
+ // load view: its readings inherit the account's visibility.
return Promise.all(
- accountIds.map(async (accountId) => {
- const account = byId.get(accountId);
- const buckets = await this.listLatestReadings(accountId);
- const scopedWeeklyUtil: Record<string, number> = {};
- let sessionUtil = 0;
- let weeklyUtil = 0;
- let rateLimitedUntil: number | null = null;
-
- for (const b of buckets) {
- // A reading whose window has rolled over describes spend that has
- // since refilled; counting it would keep an account benched long
- // after its quota came back.
- const utilization = currentUtilization(b, now);
-
- if (isSessionLimit(b)) {
- sessionUtil = utilization;
- // `utilization` is already 0 once the window rolled over, so a
- // stale 100% cannot bench the account past its own reset.
- if (utilization >= 100 && b.resetsAt) rateLimitedUntil = b.resetsAt;
- } else if (isScopedWeeklyLimit(b)) {
- scopedWeeklyUtil[b.scopeKey] = utilization;
- } else if (isWeeklyAllLimit(b)) {
- weeklyUtil = Math.max(weeklyUtil, utilization);
+ accountIds
+ .filter((accountId) => byId.has(accountId))
+ .map(async (accountId) => {
+ const account = byId.get(accountId);
+ const buckets = await this.listLatestReadings(accountId);
+ const scopedWeeklyUtil: Record<string, number> = {};
+ let sessionUtil = 0;
+ let weeklyUtil = 0;
+ let rateLimitedUntil: number | null = null;
+
+ for (const b of buckets) {
+ // A reading whose window has rolled over describes spend that has
+ // since refilled; counting it would keep an account benched long
+ // after its quota came back.
+ const utilization = currentUtilization(b, now);
+
+ if (isSessionLimit(b)) {
+ sessionUtil = utilization;
+ // `utilization` is already 0 once the window rolled over, so a
+ // stale 100% cannot bench the account past its own reset.
+ if (utilization >= 100 && b.resetsAt) rateLimitedUntil = b.resetsAt;
+ } else if (isScopedWeeklyLimit(b)) {
+ scopedWeeklyUtil[b.scopeKey] = utilization;
+ } else if (isWeeklyAllLimit(b)) {
+ weeklyUtil = Math.max(weeklyUtil, utilization);
+ }
}
- }
-
- const calibration = await this.calibrations.latest(accountId, 'weekly_all');
-
- return {
- accountId,
- capacityUsd: calibration ? Number(calibration.capacityUsd) : undefined,
- enabled: account?.enabled ?? true,
- label: account?.label ?? null,
- priority: 0,
- rateLimitedUntil,
- scopedWeeklyUtil,
- sessionUtil,
- weeklyUtil,
- } satisfies AccountLoadView;
- }),
+
+ const calibration = await this.calibrations.latest(accountId, 'weekly_all');
+
+ return {
+ accountId,
+ capacityUsd: calibration ? Number(calibration.capacityUsd) : undefined,
+ enabled: account?.enabled ?? true,
+ label: account?.label ?? null,
+ priority: 0,
+ rateLimitedUntil,
+ scopedWeeklyUtil,
+ sessionUtil,
+ weeklyUtil,
+ } satisfies AccountLoadView;
+ }),
);
};
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 58d23429e33..80f63873da8 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1990,6 +1990,13 @@
"subscriptionAccounts.summary": "{{inRotation}} of {{count}} in rotation",
"subscriptionAccounts.updateFailed": "Couldn't update the account. Try again.",
"subscriptionAccounts.usageTitle": "Usage history",
+ "subscriptionAccounts.visibility.private": "Private",
+ "subscriptionAccounts.visibility.privateAction": "Make private",
+ "subscriptionAccounts.visibility.privateConfirm.desc": "Only you will see it. Other members' agents stop drawing on its quota.",
+ "subscriptionAccounts.visibility.privateConfirm.title": "Make this account private?",
+ "subscriptionAccounts.visibility.publicAction": "Share with workspace",
+ "subscriptionAccounts.visibility.publicConfirm.desc": "Every member will see it, and their agents can draw on its quota. You can make it private again from the same menu.",
+ "subscriptionAccounts.visibility.publicConfirm.title": "Share this account with the workspace?",
"sync.device.deviceName.hint": "Add a name for easy identification",
"sync.device.deviceName.placeholder": "Enter device name",
"sync.device.deviceName.title": "Device Name",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 7bc6a2d1a66..23bc659f5ec 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1990,6 +1990,13 @@
"subscriptionAccounts.summary": "ๅ…ฑ {{count}} ไธช่ดฆๅท ยท {{inRotation}} ไธชๅ‚ไธŽๅˆ†้…",
"subscriptionAccounts.updateFailed": "่ดฆๅทๆ›ดๆ–ฐๅคฑ่ดฅ๏ผŒ่ฏท้‡่ฏ•",
"subscriptionAccounts.usageTitle": "็”จ้‡่ฎฐๅฝ•",
+ "subscriptionAccounts.visibility.private": "็งๆœ‰",
+ "subscriptionAccounts.visibility.privateAction": "่ฎพไธบ็งๆœ‰",
+ "subscriptionAccounts.visibility.privateConfirm.desc": "ไน‹ๅŽๅชๆœ‰ไฝ ่ƒฝ็œ‹ๅˆฐๅฎƒ๏ผŒๅ…ถไป–ๆˆๅ‘˜็š„ Agent ไธๅ†ไฝฟ็”จๅฎƒ็š„้ขๅบฆใ€‚",
+ "subscriptionAccounts.visibility.privateConfirm.title": "ๅฐ†่ฟ™ไธช่ดฆๅท่ฎพไธบ็งๆœ‰๏ผŸ",
+ "subscriptionAccounts.visibility.publicAction": "ๅ…ฑไบซ็ป™ๅ›ข้˜Ÿ",
+ "subscriptionAccounts.visibility.publicConfirm.desc": "ๆ‰€ๆœ‰ๆˆๅ‘˜้ƒฝ่ƒฝ็œ‹ๅˆฐๅฎƒ๏ผŒไป–ไปฌ็š„ Agent ไนŸๅฏไปฅไฝฟ็”จๅฎƒ็š„้ขๅบฆใ€‚ไน‹ๅŽๅฏไปฅๅœจๅŒไธ€่œๅ•้‡Œๆ”นๅ›ž็งๆœ‰ใ€‚",
+ "subscriptionAccounts.visibility.publicConfirm.title": "ๅฐ†่ฟ™ไธช่ดฆๅทๅ…ฑไบซ็ป™ๅ›ข้˜Ÿ๏ผŸ",
"sync.device.deviceName.hint": "ๆทปๅŠ ๅ็งฐไปฅไพฟไบŽ่ฏ†ๅˆซ",
"sync.device.deviceName.placeholder": "่ฏท่พ“ๅ…ฅ่ฎพๅค‡ๅ็งฐ",
"sync.device.deviceName.title": "่ฎพๅค‡ๅ็งฐ",
diff --git a/packages/database/src/models/__tests__/agentQuota.workspace.test.ts b/packages/database/src/models/__tests__/agentQuota.workspace.test.ts
index e2d0652e6eb..0983ec3bb00 100644
--- a/packages/database/src/models/__tests__/agentQuota.workspace.test.ts
+++ b/packages/database/src/models/__tests__/agentQuota.workspace.test.ts
@@ -3,10 +3,11 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agentProviderAccounts, agents, users, workspaces } from '../../schemas';
+import { agentProviderAccounts, agents, devices, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import {
AgentAccountBindingModel,
+ AgentProviderAccountLoginModel,
AgentProviderAccountModel,
AgentQuotaCalibrationModel,
AgentQuotaSnapshotModel,
@@ -175,12 +176,79 @@ describe('Agent quota workspace scope', () => {
expect(await teammate.findById(hidden.id)).toBeNull();
// a teammate cannot change it either; the owner can publish it
- await teammate.update(hidden.id, { visibility: 'public' });
+ expect(await teammate.setVisibility(hidden.id, 'public')).toBe(false);
expect(await teammate.findById(hidden.id)).toBeNull();
- await mine.update(hidden.id, { visibility: 'public' });
+ expect(await mine.setVisibility(hidden.id, 'public')).toBe(true);
expect(await teammate.findById(hidden.id)).not.toBeNull();
});
+ it('creates a reported workspace login as private, and personal ones without a say', async () => {
+ const identity = { externalAccountId: 'ext-private', email: '[email protected]' };
+ const workspaceAccounts = new AgentProviderAccountModel(serverDB, userId, workspaceId);
+ const teammate = new AgentProviderAccountModel(serverDB, teammateId, workspaceId);
+
+ const reported = await workspaceAccounts.upsertByIdentity('claude-code', identity);
+ expect(reported?.visibility).toBe('private');
+ expect(await teammate.list()).toEqual([]);
+
+ // Re-reporting does not undo a publish.
+ await workspaceAccounts.setVisibility(reported!.id, 'public');
+ const again = await workspaceAccounts.upsertByIdentity('claude-code', identity);
+ expect(again?.visibility).toBe('public');
+
+ // Personal rows have no team to hide from.
+ const personal = new AgentProviderAccountModel(serverDB, userId);
+ const own = await personal.upsertByIdentity('claude-code', identity);
+ expect(await personal.setVisibility(own!.id, 'public')).toBe(false);
+ });
+
+ it('keeps a private account from a teammate who reports its identity, even with a login', async () => {
+ const identity = { externalAccountId: 'ext-shared-login', email: '[email protected]' };
+ await serverDB.insert(devices).values({
+ deviceId: 'teammate-mac',
+ identitySource: 'machine-id',
+ userId: teammateId,
+ visibility: 'private',
+ workspaceId,
+ });
+ const [device] = await serverDB
+ .select({ id: devices.id })
+ .from(devices)
+ .where(eq(devices.deviceId, 'teammate-mac'));
+
+ const mine = new AgentProviderAccountModel(serverDB, userId, workspaceId);
+ const teammate = new AgentProviderAccountModel(serverDB, teammateId, workspaceId);
+ const account = (await mine.upsertByIdentity('claude-code', identity))!;
+
+ // Knowing the external id is not holding the login: the report neither
+ // inserts a colliding row nor reads or overwrites the private one.
+ const blind = await teammate.upsertByIdentity('claude-code', {
+ ...identity,
+ email: '[email protected]',
+ });
+ expect(blind).toBeUndefined();
+ expect((await mine.findById(account.id))?.email).toBe('[email protected]');
+ expect(
+ await serverDB
+ .select({ id: agentProviderAccounts.id })
+ .from(agentProviderAccounts)
+ .where(eq(agentProviderAccounts.externalAccountId, identity.externalAccountId)),
+ ).toHaveLength(1);
+
+ // A login reported from the teammate's own device is unverifiable, so it
+ // grants nothing either: only the creator publishing it shares it.
+ await new AgentProviderAccountLoginModel(serverDB, teammateId, workspaceId).record(
+ account.id,
+ device.id,
+ );
+ expect(await teammate.upsertByIdentity('claude-code', identity)).toBeUndefined();
+ expect(await teammate.list()).toEqual([]);
+ expect(await teammate.setVisibility(account.id, 'public')).toBe(false);
+
+ await mine.setVisibility(account.id, 'public');
+ expect((await teammate.list()).map((a) => a.id)).toEqual([account.id]);
+ });
+
it('lets the same external identity exist once per scope', async () => {
const identity = { externalAccountId: 'ext-acc-1', email: '[email protected]' };
const personalAccounts = new AgentProviderAccountModel(serverDB, userId);
@@ -188,20 +256,20 @@ describe('Agent quota workspace scope', () => {
const personal = await personalAccounts.upsertByIdentity('claude-code', identity);
const shared = await workspaceAccounts.upsertByIdentity('claude-code', identity);
- expect(shared.id).not.toBe(personal.id);
+ expect(shared?.id).not.toBe(personal?.id);
// re-observing the same identity in the same scope dedupes instead of inserting
const again = await workspaceAccounts.upsertByIdentity('claude-code', identity);
- expect(again.id).toBe(shared.id);
+ expect(again?.id).toBe(shared?.id);
expect(await workspaceAccounts.list()).toHaveLength(1);
expect(await personalAccounts.list()).toHaveLength(1);
- // โ€ฆand so does a teammate observing it from their own device: one real
- // account must stay ONE row per workspace, or the load balancer would count
- // its capacity twice.
+ // โ€ฆand so does a teammate observing it: one real account must stay ONE row
+ // per workspace, or the load balancer would count its capacity twice. The
+ // row is private, so without a login the teammate gets nothing back.
const teammateAccounts = new AgentProviderAccountModel(serverDB, teammateId, workspaceId);
const fromTeammate = await teammateAccounts.upsertByIdentity('claude-code', identity);
- expect(fromTeammate.id).toBe(shared.id);
+ expect(fromTeammate).toBeUndefined();
expect(await workspaceAccounts.list()).toHaveLength(1);
});
});
diff --git a/packages/database/src/models/agentQuota.ts b/packages/database/src/models/agentQuota.ts
index ccf46e7cdf4..2fa7f40e497 100644
--- a/packages/database/src/models/agentQuota.ts
+++ b/packages/database/src/models/agentQuota.ts
@@ -68,12 +68,29 @@ export class AgentProviderAccountModel {
return this.gateKeeperPromise;
}
+ /**
+ * The rows this member may see and use: public workspace accounts and their
+ * own private ones. A login does not widen this โ€” the server cannot verify
+ * that a reporting device really holds the provider login, so a reported
+ * login is no proof of access. Sharing a private account is its creator's
+ * call (`setVisibility`). Personal scope ignores visibility.
+ */
private mine = () =>
buildWorkspaceWhere(
{ userId: this.userId, workspaceId: this.workspaceId },
agentProviderAccounts,
);
+ /** Every row of the scope regardless of visibility: one real account is one row per workspace. */
+ private scope = () =>
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ userId: agentProviderAccounts.userId,
+ workspaceId: agentProviderAccounts.workspaceId,
+ },
+ );
+
create = async (
params: Omit<NewAgentProviderAccount, 'userId' | 'credentials'> & {
credentials?: QuotaAccountCredentials;
@@ -104,16 +121,25 @@ export class AgentProviderAccountModel {
* Insert-or-update by real identity. The provider account UUID is the natural
* dedupe key, so the same login observed on multiple devices collapses to one
* row (that is exactly what lets multi-device usage merge).
+ *
+ * Dedupe looks past visibility: a teammate's private row for the same
+ * identity is still that account, and inserting a second one would collide
+ * with the workspace identity index. Finding such a row grants nothing โ€”
+ * knowing an external id is not holding the login โ€” so it is neither updated
+ * nor returned, and `undefined` comes back. A new workspace row starts
+ * `private`: a login reported from a member's machine is theirs until they
+ * publish it.
*/
upsertByIdentity = async (
provider: string,
identity: AccountIdentityInput,
defaults: Partial<NewAgentProviderAccount> = {},
- ): Promise<SafeAccount> => {
+ ): Promise<SafeAccount | undefined> => {
if (identity.externalAccountId) {
const existing = await this.db.query.agentProviderAccounts.findFirst({
+ columns: { id: true },
where: and(
- this.mine(),
+ this.scope(),
eq(agentProviderAccounts.provider, provider),
eq(agentProviderAccounts.externalAccountId, identity.externalAccountId),
),
@@ -122,13 +148,14 @@ export class AgentProviderAccountModel {
const [row] = await this.db
.update(agentProviderAccounts)
.set({ ...identity, lastValidatedAt: new Date(), updatedAt: new Date() })
- .where(eq(agentProviderAccounts.id, existing.id))
+ .where(and(eq(agentProviderAccounts.id, existing.id), this.mine()))
.returning();
- return stripCredentials(row);
+ return row ? stripCredentials(row) : undefined;
}
}
return this.create({
+ ...(this.workspaceId && { visibility: 'private' as const }),
...defaults,
...identity,
credentialMode: defaults.credentialMode ?? QuotaCredentialMode.referenced,
@@ -198,12 +225,37 @@ export class AgentProviderAccountModel {
.where(and(eq(agentProviderAccounts.id, id), this.mine()));
};
- update = async (id: string, patch: Partial<Omit<NewAgentProviderAccount, 'credentials'>>) =>
+ update = async (
+ id: string,
+ patch: Partial<Omit<NewAgentProviderAccount, 'credentials' | 'visibility'>>,
+ ) =>
this.db
.update(agentProviderAccounts)
.set({ ...patch, updatedAt: new Date() })
.where(and(eq(agentProviderAccounts.id, id), this.mine()));
+ /**
+ * Publish or hide a workspace account. Only its creator decides: another
+ * login holder hiding it would take it away from the rest of the team, and
+ * publishing it would expose someone else's subscription. Returns whether a
+ * row changed.
+ */
+ setVisibility = async (id: string, visibility: 'private' | 'public'): Promise<boolean> => {
+ if (!this.workspaceId) return false;
+ const rows = await this.db
+ .update(agentProviderAccounts)
+ .set({ updatedAt: new Date(), visibility })
+ .where(
+ and(
+ eq(agentProviderAccounts.id, id),
+ this.scope(),
+ eq(agentProviderAccounts.userId, this.userId),
+ ),
+ )
+ .returning({ id: agentProviderAccounts.id });
+ return rows.length > 0;
+ };
+
delete = async (id: string) =>
this.db.delete(agentProviderAccounts).where(and(eq(agentProviderAccounts.id, id), this.mine()));
}
diff --git a/packages/database/src/schemas/agentQuota.ts b/packages/database/src/schemas/agentQuota.ts
index 9af59d16abb..8ddc73a9a29 100644
--- a/packages/database/src/schemas/agentQuota.ts
+++ b/packages/database/src/schemas/agentQuota.ts
@@ -52,13 +52,13 @@ export const agentProviderAccounts = pgTable(
// Visibility WITHIN a workspace (same contract as devices / agents):
// - 'public' โ†’ every member sees the subscription (without its identity
// fields) and agents can draw on it: a team account on a shared machine.
- // - 'private' โ†’ only members holding a login for it
- // (`agent_provider_account_logins`) see and use it.
+ // - 'private' โ†’ only its creator sees and uses it. Logins do not grant
+ // access: the server cannot verify a reported login, so sharing is the
+ // creator's call (publish).
// Ignored for personal rows (`workspace_id IS NULL`).
- // The default stays 'public' (today's behaviour) until ingestion dedupes by
- // identity regardless of visibility and reads go through logins; flipping
- // it earlier would make a second member's login of a private account
- // collide with the workspace identity unique index.
+ // Ingestion creates workspace rows as 'private' (`upsertByIdentity`, which
+ // dedupes by identity across visibility); the column default only covers
+ // rows added by hand and the ones that pre-date that change.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
@@ -181,9 +181,9 @@ export type AgentAccountBindingItem = typeof agentAccountBindings.$inferSelect;
* every login points at the same account row. Written by the desktop sampler
* whenever it reports a reading from a device it can resolve.
*
- * Logins decide where an account can run (a login only exists on its machine)
- * and, for a `private` account, who may see and use it: the members whose
- * devices hold a login.
+ * Logins decide where an account can run (a login only exists on its machine).
+ * They do not decide who may see a `private` account โ€” a login is reported by
+ * the device and cannot be verified, so only the account's creator sees it.
*/
export const agentProviderAccountLogins = pgTable(
'agent_provider_account_logins',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index bbbbde76ed5..597b9fa4241 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4983,6 +4983,15 @@ When I am ___, I need ___
'subscriptionAccounts.calendar.tomorrowDay': 'Tomorrow',
'subscriptionAccounts.summary': '{{inRotation}} of {{count}} in rotation',
'subscriptionAccounts.updateFailed': "Couldn't update the account. Try again.",
+ 'subscriptionAccounts.visibility.private': 'Private',
+ 'subscriptionAccounts.visibility.privateAction': 'Make private',
+ 'subscriptionAccounts.visibility.privateConfirm.desc':
+ "Only you will see it. Other members' agents stop drawing on its quota.",
+ 'subscriptionAccounts.visibility.privateConfirm.title': 'Make this account private?',
+ 'subscriptionAccounts.visibility.publicAction': 'Share with workspace',
+ 'subscriptionAccounts.visibility.publicConfirm.desc':
+ 'Every member will see it, and their agents can draw on its quota. You can make it private again from the same menu.',
+ 'subscriptionAccounts.visibility.publicConfirm.title': 'Share this account with the workspace?',
'tab.subscriptionAccounts': 'Subscription Accounts',
'taskLabels.actions.addToGroup': 'Add label to group',
'taskLabels.actions.create': 'New label',
diff --git a/src/features/SubscriptionAccounts/AccountRow.tsx b/src/features/SubscriptionAccounts/AccountRow.tsx
index 2d58dc0fd13..14039a5ec93 100644
--- a/src/features/SubscriptionAccounts/AccountRow.tsx
+++ b/src/features/SubscriptionAccounts/AccountRow.tsx
@@ -4,6 +4,7 @@ import { displayPlanTier } from '@lobechat/heterogeneous-agents/quota';
import { ClaudeCode, Codex, Kimi } from '@lobehub/icons';
import {
ActionIcon,
+ confirmModal,
DropdownMenu,
Flexbox,
Icon,
@@ -16,7 +17,15 @@ import {
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
-import { CheckIcon, MoreHorizontalIcon, PanelRightOpenIcon, PencilIcon, XIcon } from 'lucide-react';
+import {
+ CheckIcon,
+ EyeOffIcon,
+ GlobeIcon,
+ MoreHorizontalIcon,
+ PanelRightOpenIcon,
+ PencilIcon,
+ XIcon,
+} from 'lucide-react';
import { type CSSProperties, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,6 +33,8 @@ import { formatPercent, usageLevel } from '@/features/DeviceManager/DeviceHealth
import { usageTextColor } from '@/features/DeviceManager/DeviceHealth/shared';
import { UsageBar } from '@/features/DeviceManager/DeviceHealth/UsageMeter';
import { type QuotaAccount, useAgentQuotaStore } from '@/store/agentQuota';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import {
type AccountStatus,
@@ -180,9 +191,18 @@ interface AccountRowProps {
const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {
const { t } = useTranslation('setting');
const { t: tCommon } = useTranslation('common');
- const [useFetchQuotaReadings, renameQuotaAccount, setQuotaAccountEnabled] = useAgentQuotaStore(
- (s) => [s.useFetchQuotaReadings, s.renameQuotaAccount, s.setQuotaAccountEnabled],
- );
+ const [
+ useFetchQuotaReadings,
+ renameQuotaAccount,
+ setQuotaAccountEnabled,
+ setQuotaAccountVisibility,
+ ] = useAgentQuotaStore((s) => [
+ s.useFetchQuotaReadings,
+ s.renameQuotaAccount,
+ s.setQuotaAccountEnabled,
+ s.setQuotaAccountVisibility,
+ ]);
+ const currentUserId = useUserStore(userProfileSelectors.userId);
useFetchQuotaReadings(account.id);
const readings = useAgentQuotaStore((s) => s.quotaReadingsMap[account.id]);
const [busy, setBusy] = useState(false);
@@ -193,8 +213,14 @@ const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {
const meta = PROVIDER_META[account.provider];
const name = accountDisplayName(account);
const plan = displayPlanTier(account);
+ // Only workspace accounts carry a visibility; personal ones have no team to hide from.
+ const isPrivate = !!account.workspaceId && account.visibility === 'private';
// With a label set, the email moves to the subtitle so the account stays identifiable.
- const subtitle = [meta.name, account.label ? account.email : undefined]
+ const subtitle = [
+ meta.name,
+ account.label ? account.email : undefined,
+ isPrivate ? t('subscriptionAccounts.visibility.private') : undefined,
+ ]
.filter(Boolean)
.join(' ยท ');
@@ -220,6 +246,38 @@ const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {
setEditing(false);
};
+ // Only the member who added the account decides who else sees it: another
+ // login holder hiding it would take it from the team, publishing it would
+ // expose someone else's subscription. The server enforces the same rule.
+ const canChangeVisibility = !!account.workspaceId && account.userId === currentUserId;
+ const confirmVisibility = (visibility: 'private' | 'public') =>
+ confirmModal({
+ content: t(`subscriptionAccounts.visibility.${visibility}Confirm.desc`),
+ okButtonProps: visibility === 'private' ? { danger: true } : undefined,
+ okText: t(`subscriptionAccounts.visibility.${visibility}Action`),
+ onOk: async () => {
+ await run(() => setQuotaAccountVisibility(account.id, visibility));
+ },
+ title: t(`subscriptionAccounts.visibility.${visibility}Confirm.title`),
+ });
+ const visibilityItems = canChangeVisibility
+ ? [
+ isPrivate
+ ? {
+ icon: <Icon icon={GlobeIcon} />,
+ key: 'publish',
+ label: t('subscriptionAccounts.visibility.publicAction'),
+ onClick: () => confirmVisibility('public'),
+ }
+ : {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'makePrivate',
+ label: t('subscriptionAccounts.visibility.privateAction'),
+ onClick: () => confirmVisibility('private'),
+ },
+ ]
+ : [];
+
const statusText = (() => {
switch (view.status) {
case 'disabled': {
@@ -382,6 +440,7 @@ const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {
label: t('subscriptionAccounts.actions.rename'),
onClick: startEdit,
},
+ ...visibilityItems,
]}
>
<ActionIcon icon={MoreHorizontalIcon} size={'small'} title={tCommon('more')} />
diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.ts
index eb89c14fc2e..1810253026f 100644
--- a/src/services/agentQuota.ts
+++ b/src/services/agentQuota.ts
@@ -101,8 +101,10 @@ class AgentQuotaService {
lambdaClient.agentQuota.unbindAccount.mutate({ id: bindingId });
/** Edit account info (display label, enabled flag). */
- updateAccount = async (id: string, value: { enabled?: boolean; label?: string }) =>
- lambdaClient.agentQuota.updateAccount.mutate({ id, value });
+ updateAccount = async (
+ id: string,
+ value: { enabled?: boolean; label?: string; visibility?: 'private' | 'public' },
+ ) => lambdaClient.agentQuota.updateAccount.mutate({ id, value });
/** The account an agent uses on one device (gateway id); `null` = Auto there. */
getDeviceAccount = async (agentId: string, deviceId: string): Promise<QuotaDeviceAccount> =>
diff --git a/src/store/agentQuota/action.ts b/src/store/agentQuota/action.ts
index 8803a0da676..e140c57e293 100644
--- a/src/store/agentQuota/action.ts
+++ b/src/store/agentQuota/action.ts
@@ -405,6 +405,25 @@ export class ActionImpl {
await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);
};
+ /**
+ * Publish a workspace account to the team or keep it to the members signed in
+ * to it. Only its creator may; the server rejects anyone else.
+ */
+ setQuotaAccountVisibility = async (
+ accountId: string,
+ visibility: 'private' | 'public',
+ ): Promise<void> => {
+ await this.#accounts.optimistic(
+ QUOTA_ACCOUNTS_KEY,
+ (accounts) =>
+ accounts.map((account) =>
+ account.id === accountId ? { ...account, visibility } : account,
+ ),
+ () => agentQuotaService.updateAccount(accountId, { visibility }),
+ );
+ await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);
+ };
+
// ---- local Claude Code logins (desktop) ----
/**
diff --git a/src/store/agentQuota/agentQuota.replica.test.ts b/src/store/agentQuota/agentQuota.replica.test.ts
index e71ae0d2aea..595e3a9d747 100644
--- a/src/store/agentQuota/agentQuota.replica.test.ts
+++ b/src/store/agentQuota/agentQuota.replica.test.ts
@@ -386,6 +386,26 @@ describe('agent quota replicas', () => {
expect(updateAccount).toHaveBeenCalledWith('a1', { enabled: false });
expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.enabled).toBe(false);
});
+
+ it('shares a private account with the workspace in the replica and on the server', async () => {
+ vi.spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('a1', { visibility: 'private' })])
+ .mockRejectedValue(new Error('offline'));
+ const updateAccount = vi
+ .spyOn(agentQuotaService, 'updateAccount')
+ .mockResolvedValue(undefined as never);
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), { wrapper });
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeDefined(),
+ );
+
+ await act(() => useAgentQuotaStore.getState().setQuotaAccountVisibility('a1', 'public'));
+
+ expect(updateAccount).toHaveBeenCalledWith('a1', { visibility: 'public' });
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.visibility).toBe(
+ 'public',
+ );
+ });
});
describe('user-data reset', () => {