🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-quota): choose the Claude Code account per device (#21984)
Arvin Xuf73fa077bca7
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.tsnew file mode 100644index 00000000000..4d92c805418--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts@@ -0,0 +1,109 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as AgentQuotaModule from '@/server/services/agentQuota';++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: {} }));++const mockFindByDeviceId = vi.fn();+vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn(function () {+ return { findByDeviceId: mockFindByDeviceId, findWorkspaceDeviceById: vi.fn() };+ }),+}));++vi.mock('@/database/models/agentQuota', () => ({+ AgentAccountBindingModel: vi.fn(function () {+ return {};+ }),+ AgentProviderAccountModel: vi.fn(function () {+ return {};+ }),+ AgentQuotaWindowModel: vi.fn(function () {+ return {};+ }),+}));++const mockGetDeviceAccount = vi.fn();+const mockSetDeviceAccount = vi.fn();+const mockSelectForAgent = vi.fn();+vi.mock('@/server/services/agentQuota', async (importOriginal) => {+ const { AccountNotSignedInOnDeviceError } = await importOriginal<typeof AgentQuotaModule>();+ return {+ AccountNotSignedInOnDeviceError,+ AgentQuotaService: vi.fn(function () {+ return {+ getDeviceAccount: mockGetDeviceAccount,+ selectForAgent: mockSelectForAgent,+ setDeviceAccount: mockSetDeviceAccount,+ };+ }),+ };+});++const { AccountNotSignedInOnDeviceError } = await import('@/server/services/agentQuota');+const { agentQuotaRouter } = await import('../agentQuota');++const caller = () => agentQuotaRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++beforeEach(() => {+ vi.clearAllMocks();+ mockFindByDeviceId.mockImplementation(async (id: string) =>+ id === 'gateway-a' ? { id: 'row-a' } : undefined,+ );+});++describe('agentQuota per-device account choice', () => {+ it('reads and writes the choice on the device row, not the gateway id', async () => {+ mockGetDeviceAccount.mockResolvedValue('acc-1');++ await expect(+ caller().getDeviceAccount({ agentId: 'agt-1', deviceId: 'gateway-a' }),+ ).resolves.toEqual({ accountId: 'acc-1' });+ await caller().setDeviceAccount({ accountId: null, agentId: 'agt-1', deviceId: 'gateway-a' });++ expect(mockGetDeviceAccount).toHaveBeenCalledWith('agt-1', 'row-a');+ expect(mockSetDeviceAccount).toHaveBeenCalledWith('agt-1', 'row-a', null);+ });++ it('answers Auto for a device it cannot resolve, and refuses to write there', async () => {+ await expect(+ caller().getDeviceAccount({ agentId: 'agt-1', deviceId: 'unknown' }),+ ).resolves.toEqual({ accountId: null });+ await expect(+ caller().setDeviceAccount({ accountId: 'acc-1', agentId: 'agt-1', deviceId: 'unknown' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockSetDeviceAccount).not.toHaveBeenCalled();+ });++ it('reports a pick without a login on the device as a precondition failure', async () => {+ mockSetDeviceAccount.mockRejectedValue(new AccountNotSignedInOnDeviceError());++ await expect(+ caller().setDeviceAccount({ accountId: 'acc-1', agentId: 'agt-1', deviceId: 'gateway-a' }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });++ it('selects for the run device', async () => {+ mockSelectForAgent.mockResolvedValue(null);++ await caller().selectAccountForAgent({ agentId: 'agt-1', deviceId: 'gateway-a' });++ expect(mockSelectForAgent).toHaveBeenCalledWith(+ 'agt-1',+ expect.objectContaining({ deviceId: 'row-a' }),+ );+ });+});diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex 1e3143c558e..ac3ca439425 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -1,3 +1,5 @@+import type { QuotaDeviceAccount } from '@lobechat/types';+import { TRPCError } from '@trpc/server';import { z } from 'zod';import { cloudWorkspaceAuth } from '@/business/server/trpc-middlewares/workspaceAuth';@@ -9,7 +11,8 @@ import {import { DeviceModel } from '@/database/models/device';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { AgentQuotaService } from '@/server/services/agentQuota';+import { AccountNotSignedInOnDeviceError, AgentQuotaService } from '@/server/services/agentQuota';+import { resolveDeviceRowId } from '@/server/services/agentQuota/resolveDeviceRowId';import { deviceGateway } from '@/server/services/deviceGateway';import { assertWorkspaceDeviceVisible } from './deviceWorkspaceGuard';@@ -29,6 +32,21 @@ const quotaProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {});const providerSchema = z.enum(['claude-code', 'codex', 'kimi-code']);+/** `devices.id` of a device the client names by its gateway id; see `resolveDeviceRowId`. */+const deviceRowIdOf = (+ ctx: { deviceModel: DeviceModel; workspaceId?: string | null },+ gatewayDeviceId: string | undefined,+) => resolveDeviceRowId(ctx.deviceModel, ctx.workspaceId, gatewayDeviceId);++/** Like `deviceRowIdOf`, for writes that cannot proceed without the device. */+const requireDeviceRowId = async (+ ctx: { deviceModel: DeviceModel; workspaceId?: string | null },+ gatewayDeviceId: string,+): Promise<string> => {+ const id = await deviceRowIdOf(ctx, gatewayDeviceId);+ if (!id) throw new TRPCError({ code: 'NOT_FOUND', message: 'Device not found' });+ return id;+};const readingSchema = z.object({capturedAt: z.number(),@@ -177,29 +195,14 @@ export const agentQuotaRouter = router({}),).mutation(async ({ ctx, input }) => {- // Clients know a device by its gateway id (the string `devices.device_id`- // stored in `agencyConfig.boundDeviceId`), but snapshots reference the- // `devices.id` uuid. Resolve it here rather than trusting the client: a- // raw gateway id fails the uuid/foreign-key check and would take the- // whole ingest down with it, silently stranding the reading. An- // unresolvable device only costs attribution, so keep the reading.- //- // A workspace device's identity is `(workspaceId, deviceId)` — `userId`- // only records the first enroller — so the personal `(userId, deviceId)`- // lookup misses a machine any other member enrolled. Try the- // workspace-scoped lookup first when the request carries a workspace- // (it also applies the device's visibility rules), then fall back to the- // caller's own devices.- const deviceModel = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);- const deviceRow = input.deviceId- ? ((ctx.workspaceId- ? await deviceModel.findWorkspaceDeviceById(input.deviceId)- : undefined) ?? (await deviceModel.findByDeviceId(input.deviceId)))- : undefined;+ // An unresolvable device only costs attribution, so keep the reading: a+ // raw gateway id would fail the uuid/foreign-key check and take the whole+ // ingest down with it, silently stranding the reading.+ const deviceRowId = await deviceRowIdOf(ctx, input.deviceId);return ctx.quotaService.ingestSnapshot({credentialRef: { origin: 'keychain' },- deviceId: deviceRow?.id,+ deviceId: deviceRowId,extraUsage: input.extraUsage,identity: input.identity,provider: input.provider,@@ -289,6 +292,57 @@ export const agentQuotaRouter = router({.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => ctx.bindingModel.remove(input.id)),+ // ── per-device account choice (a login only exists on its machine) ───────+ /** The account an agent uses on one device; `accountId: null` = Auto there. */+ getDeviceAccount: quotaProcedure+ .input(z.object({ agentId: z.string(), deviceId: z.string() }))+ .query(async ({ ctx, input }): Promise<QuotaDeviceAccount> => {+ const deviceRowId = await deviceRowIdOf(ctx, input.deviceId);+ return {+ accountId: deviceRowId+ ? await ctx.quotaService.getDeviceAccount(input.agentId, deviceRowId)+ : null,+ };+ }),++ /** Pin an account for an agent on one device, or return it to Auto (`accountId: null`). */+ setDeviceAccount: quotaProcedure+ .input(+ z.object({ accountId: z.string().nullable(), agentId: z.string(), deviceId: z.string() }),+ )+ .mutation(async ({ ctx, input }) => {+ const deviceRowId = await requireDeviceRowId(ctx, input.deviceId);+ try {+ await ctx.quotaService.setDeviceAccount(input.agentId, deviceRowId, input.accountId);+ } catch (error) {+ if (error instanceof AccountNotSignedInOnDeviceError)+ throw new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message: error.message,+ });+ throw error;+ }+ }),++ /** A device reports every login it holds for a provider; the rest are forgotten there. */+ syncDeviceLogins: quotaProcedure+ .input(+ z.object({+ deviceId: z.string(),+ externalAccountIds: z.array(z.string()),+ provider: providerSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const deviceRowId = await requireDeviceRowId(ctx, input.deviceId);+ await ctx.quotaService.syncDeviceLogins(+ deviceRowId,+ input.provider,+ input.externalAccountIds,+ );+ }),+// ── quota read (QuotaMenu read model) ────────────────────────────────────getWindows: quotaProcedure.input(z.object({ accountId: z.string(), limit: z.number().optional() }))@@ -344,6 +398,8 @@ export const agentQuotaRouter = router({.input(z.object({agentId: z.string(),+ /** Gateway id of the device the run spawns on. */+ deviceId: z.string().optional(),modelScope: z.string().optional(),provider: z.string().optional(),runnableExternalAccountIds: z.array(z.string()).optional(),@@ -351,6 +407,7 @@ export const agentQuotaRouter = router({).query(async ({ ctx, input }) =>ctx.quotaService.selectForAgent(input.agentId, {+ deviceId: await deviceRowIdOf(ctx, input.deviceId),modelScope: input.modelScope,provider: input.provider,runnableExternalAccountIds: input.runnableExternalAccountIds,diff --git a/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.ts b/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.tsnew file mode 100644index 00000000000..63ec63f2d3a--- /dev/null+++ b/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.ts@@ -0,0 +1,239 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ AgentAccountBindingModel,+ AgentDeviceAccountBindingModel,+} from '@/database/models/agentQuota';+import { agents, devices, users } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { QuotaBindingRole } from '@/database/types/agentQuota';++import { AccountNotSignedInOnDeviceError, AgentQuotaService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agent-quota-device-user';+const agentId = 'agent-dev';++let service: AgentQuotaService;+let bindings: AgentAccountBindingModel;+let deviceBindings: AgentDeviceAccountBindingModel;+let deviceA: string;+let deviceB: string;++const addDevice = async (gatewayId: string) => {+ const [row] = await serverDB+ .insert(devices)+ .values({ deviceId: gatewayId, identitySource: 'stable', userId })+ .returning();+ return row.id;+};++/** An account signed in on `deviceId` (a sample ingested from there). */+const signedIn = (externalAccountId: string, deviceId?: string) =>+ service.ingestSnapshot({+ deviceId,+ identity: { email: `${externalAccountId}@example.com`, externalAccountId },+ provider: 'claude-code',+ readings: [],+ });++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({ id: agentId, slug: agentId, title: 'Dev', userId });+ service = new AgentQuotaService(serverDB, userId);+ bindings = new AgentAccountBindingModel(serverDB, userId);+ deviceBindings = new AgentDeviceAccountBindingModel(serverDB, userId);+ deviceA = await addDevice('gateway-a');+ deviceB = await addDevice('gateway-b');+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentQuotaService per-device account choice', () => {+ it('resolves a gateway device id to its row', async () => {+ expect(await service.resolveDeviceRowId('gateway-a')).toBe(deviceA);+ expect(await service.resolveDeviceRowId('unknown')).toBeUndefined();+ expect(await service.resolveDeviceRowId(undefined)).toBeUndefined();+ });++ it('routes each device to its own pick, and a device without one balances', async () => {+ const onA = await signedIn('acc-a', deviceA);+ const onB = await signedIn('acc-b', deviceB);+ for (const account of [onA, onB])+ await bindings.upsert({ accountId: account.id, agentId, role: QuotaBindingRole.pool });++ await service.setDeviceAccount(agentId, deviceA, onA.id);++ expect(await service.selectForAgent(agentId, { deviceId: deviceA })).toMatchObject({+ accountId: onA.id,+ pinScope: 'device',+ reason: 'pinned',+ });+ expect(+ await service.selectForAgent(agentId, {+ deviceId: deviceB,+ runnableExternalAccountIds: ['acc-b'],+ }),+ ).toMatchObject({ accountId: onB.id, reason: 'balanced' });+ expect(await service.getDeviceAccount(agentId, deviceA)).toBe(onA.id);+ expect(await service.getDeviceAccount(agentId, deviceB)).toBeNull();+ });++ // Regression: the pin was agent-wide, so an account picked on device A made+ // the agent fail on device B, where that account was never signed in.+ it('skips an agent-wide pin the caller cannot run and balances instead', async () => {+ const onA = await signedIn('acc-a', deviceA);+ const onB = await signedIn('acc-b', deviceB);+ await bindings.upsert({ accountId: onA.id, agentId, role: QuotaBindingRole.pinned });+ await bindings.upsert({ accountId: onB.id, agentId, role: QuotaBindingRole.pool });++ expect(+ await service.selectForAgent(agentId, {+ deviceId: deviceB,+ runnableExternalAccountIds: ['acc-b'],+ }),+ ).toMatchObject({ accountId: onB.id, reason: 'balanced' });+ // Where it can run, the old pin still holds.+ expect(+ await service.selectForAgent(agentId, {+ deviceId: deviceA,+ runnableExternalAccountIds: ['acc-a'],+ }),+ ).toMatchObject({ accountId: onA.id, pinScope: 'agent', reason: 'pinned' });+ });++ it('hands a legacy pin to the devices that hold its login on the first per-device write', async () => {+ const shared = await signedIn('acc-shared', deviceA);+ const onB = await signedIn('acc-b', deviceB);+ await bindings.upsert({ accountId: shared.id, agentId, role: QuotaBindingRole.pinned });+ await bindings.upsert({ accountId: onB.id, agentId, role: QuotaBindingRole.pool });++ // Choosing Auto on device B must not move device A off its pin.+ await service.setDeviceAccount(agentId, deviceB, null);++ expect(await service.getDeviceAccount(agentId, deviceA)).toBe(shared.id);+ expect(await service.getDeviceAccount(agentId, deviceB)).toBeNull();+ const roles = (await bindings.listByAgent(agentId)).map((b) => b.role);+ expect(roles).not.toContain(QuotaBindingRole.pinned);+ });++ it('refuses a pick for an account the device holds no login for', async () => {+ const onA = await signedIn('acc-a', deviceA);+ await bindings.upsert({ accountId: onA.id, agentId, role: QuotaBindingRole.pool });++ await expect(service.setDeviceAccount(agentId, deviceB, onA.id)).rejects.toBeInstanceOf(+ AccountNotSignedInOnDeviceError,+ );+ });++ it('leaves a legacy pin and every device untouched when the pick is refused', async () => {+ const shared = await signedIn('acc-shared', deviceA);+ const onlyA = await signedIn('acc-only-a', deviceA);+ await bindings.upsert({ accountId: shared.id, agentId, role: QuotaBindingRole.pinned });+ await bindings.upsert({ accountId: onlyA.id, agentId, role: QuotaBindingRole.pool });++ // Device B holds no login for it: the choice is refused...+ await expect(service.setDeviceAccount(agentId, deviceB, onlyA.id)).rejects.toBeInstanceOf(+ AccountNotSignedInOnDeviceError,+ );++ // ...and the legacy pin was neither handed out nor demoted.+ expect(await deviceBindings.listByAgent(agentId)).toEqual([]);+ const pinned = (await bindings.listByAgent(agentId)).find(+ (b) => b.role === QuotaBindingRole.pinned,+ );+ expect(pinned?.accountId).toBe(shared.id);+ });++ it('ignores a pick whose account left the rotation', async () => {+ const onA = await signedIn('acc-a', deviceA);+ const other = await signedIn('acc-other', deviceA);+ await bindings.upsert({ accountId: onA.id, agentId, role: QuotaBindingRole.pool });+ await bindings.upsert({ accountId: other.id, agentId, role: QuotaBindingRole.pool });+ await service.setDeviceAccount(agentId, deviceA, onA.id);++ await bindings.upsert({ accountId: onA.id, agentId, role: QuotaBindingRole.disabled });++ expect(await service.selectForAgent(agentId, { deviceId: deviceA })).toMatchObject({+ accountId: other.id,+ reason: 'balanced',+ });+ });++ it('forgets logins a device no longer reports, and the picks made on them', async () => {+ const kept = await signedIn('acc-kept', deviceA);+ const gone = await signedIn('acc-gone', deviceA);+ await bindings.upsert({ accountId: gone.id, agentId, role: QuotaBindingRole.pool });+ await service.setDeviceAccount(agentId, deviceA, gone.id);++ await service.syncDeviceLogins(deviceA, 'claude-code', ['acc-kept', 'acc-unknown']);++ expect(await service.getDeviceAccount(agentId, deviceA)).toBeNull();+ expect(await deviceBindings.listByAgent(agentId)).toEqual([]);+ // The kept login is still there, so it can be picked.+ await bindings.upsert({ accountId: kept.id, agentId, role: QuotaBindingRole.pool });+ await expect(service.setDeviceAccount(agentId, deviceA, kept.id)).resolves.toBeUndefined();+ });++ it('records a login when a device syncs one ingested without a device', async () => {+ const account = await signedIn('acc-local');+ await bindings.upsert({ accountId: account.id, agentId, role: QuotaBindingRole.pool });++ await expect(service.setDeviceAccount(agentId, deviceA, account.id)).rejects.toBeInstanceOf(+ AccountNotSignedInOnDeviceError,+ );+ await service.syncDeviceLogins(deviceA, 'claude-code', ['acc-local']);+ await service.setDeviceAccount(agentId, deviceA, account.id);++ expect(await service.getDeviceAccount(agentId, deviceA)).toBe(account.id);+ });+});++describe('AgentQuotaService.planDeviceRouting per device', () => {+ it("sends the device's own pick as the pin", async () => {+ const onA = await signedIn('acc-a', deviceA);+ const onB = await signedIn('acc-b', deviceB);+ for (const account of [onA, onB])+ await bindings.upsert({ accountId: account.id, agentId, role: QuotaBindingRole.pool });+ await service.setDeviceAccount(agentId, deviceB, onB.id);++ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceB, provider: 'claude-code' }),+ ).toEqual({+ candidates: [{ externalAccountId: 'acc-b', name: '[email protected]' }],+ mode: 'pinned',+ });+ });++ // Regression: a device-bound run used the agent-wide pin made on another+ // machine, so the device refused to start it.+ it('turns an agent-wide pin into the first Auto candidate where its login is unknown', async () => {+ const onA = await signedIn('acc-a', deviceA);+ const onB = await signedIn('acc-b', deviceB);+ await bindings.upsert({ accountId: onA.id, agentId, role: QuotaBindingRole.pinned });+ await bindings.upsert({ accountId: onB.id, agentId, role: QuotaBindingRole.pool });++ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceB, provider: 'claude-code' }),+ ).toEqual({+ candidates: [+ { externalAccountId: 'acc-a', name: '[email protected]' },+ { externalAccountId: 'acc-b', name: '[email protected]' },+ ],+ mode: 'balanced',+ });+ // On the device that holds its login it stays a strict pin.+ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceA, provider: 'claude-code' }),+ ).toEqual({+ candidates: [{ externalAccountId: 'acc-a', name: '[email protected]' }],+ mode: 'pinned',+ });+ });+});diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.tsindex 15645ab1ef8..1f8051ed6c8 100644--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts@@ -185,7 +185,7 @@ describe('AgentQuotaService.selectForAgent', () => {);});- it('balances only across accounts the caller can run, but still returns a pin', async () => {+ it('balances only across accounts the caller can run, skipping a pin it cannot run', async () => {const bindings = new AgentAccountBindingModel(serverDB, userId);await serverDB.insert(agents).values([{ id: 'agent-3', slug: 'agent-3', title: 'A3', userId }]);const local = await service.ingestSnapshot({@@ -216,14 +216,20 @@ describe('AgentQuotaService.selectForAgent', () => {}),).toBeNull();- // A pinned account the caller cannot run is still the answer.+ // An agent-wide pin the caller cannot run was picked on another machine:+ // balance across what it can run instead. Where it can run, it still holds.await bindings.upsert({accountId: remote.id,agentId: 'agent-3',role: QuotaBindingRole.pinned,});expect(await service.selectForAgent('agent-3', onlyLocal)).toMatchObject({+ accountId: local.id,+ reason: 'balanced',+ });+ expect(await service.selectForAgent('agent-3', onlyRemote)).toMatchObject({accountId: remote.id,+ pinScope: 'agent',reason: 'pinned',});});diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.tsindex 8d577aa88ce..ae3cb60b069 100644--- a/apps/server/src/services/agentQuota/index.ts+++ b/apps/server/src/services/agentQuota/index.ts@@ -19,16 +19,20 @@ import {windowSecondsForKind,windowsToCalibrationIntervals,} from '@lobechat/heterogeneous-agents/quota';+import pMap from 'p-map';import type { AccountIdentityInput, SafeAccount } from '@/database/models/agentQuota';import {AgentAccountBindingModel,+ AgentDeviceAccountBindingModel,+ AgentProviderAccountLoginModel,AgentProviderAccountModel,AgentQuotaCalibrationModel,AgentQuotaSnapshotModel,AgentQuotaUsageLedgerModel,AgentQuotaWindowModel,} from '@/database/models/agentQuota';+import { DeviceModel } from '@/database/models/device';import type { LobeChatDatabase } from '@/database/type';import {type QuotaAccountCredentialRef,@@ -38,6 +42,7 @@ import {} from '@/database/types/agentQuota';import { claudeModelPrice, codexModelPrice } from './pricing';+import { resolveDeviceRowId } from './resolveDeviceRowId';const readQuotaWindowMetadata = (raw: Record<string, unknown> | null) => ({...(typeof raw?.windowMinutes === 'number' &&@@ -73,12 +78,18 @@ export interface QuotaUsageTurn {* the database models.*/interface SelectAccountOptions {+ /**+ * `devices.id` of the machine the run spawns on. Its own account choice+ * (`agent_device_account_bindings`) wins over the agent-wide pin.+ */+ deviceId?: string;modelScope?: string;now?: number;provider?: string;/*** Provider account ids the caller holds a local login for. Auto mode only- * balances across these; omitted = every pooled account is runnable.+ * balances across these, and an agent-wide pin outside them is skipped (it+ * was chosen on another machine); omitted = every account is runnable.*/runnableExternalAccountIds?: string[];}@@ -86,17 +97,50 @@ interface SelectAccountOptions {/** How recently a run must have billed an account to count as running on it. */const ACTIVE_RUN_WINDOW_MS = 6 * 60 * 60 * 1000;+/** Postgres `foreign_key_violation`. */+const FOREIGN_KEY_VIOLATION = '23503';++/** The (account, device) pair of a device account choice is not a recorded login. */+export class AccountNotSignedInOnDeviceError extends Error {+ constructor() {+ super('The account is not signed in on this device');+ this.name = 'AccountNotSignedInOnDeviceError';+ }+}++const isForeignKeyViolation = (error: unknown): boolean => {+ for (let current: unknown = error; current; current = (current as { cause?: unknown }).cause) {+ if ((current as { code?: unknown }).code === FOREIGN_KEY_VIOLATION) return true;+ }+ return false;+};++/** Where a pin came from: the run's own device, or the legacy agent-wide pin. */+export type AccountPinScope = 'agent' | 'device';+export class AgentQuotaService {private accounts: AgentProviderAccountModel;private bindings: AgentAccountBindingModel;+ private deviceBindings: AgentDeviceAccountBindingModel;+ private devices: DeviceModel;+ private logins: AgentProviderAccountLoginModel;+ private workspaceId?: string;+ private db: LobeChatDatabase;+ private userId: string;private snapshots: AgentQuotaSnapshotModel;private ledger: AgentQuotaUsageLedgerModel;private windows: AgentQuotaWindowModel;private calibrations: AgentQuotaCalibrationModel;constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;this.accounts = new AgentProviderAccountModel(db, userId, workspaceId);this.bindings = new AgentAccountBindingModel(db, userId, workspaceId);+ this.deviceBindings = new AgentDeviceAccountBindingModel(db, userId, workspaceId);+ this.devices = new DeviceModel(db, userId, workspaceId);+ this.logins = new AgentProviderAccountLoginModel(db, userId, workspaceId);+ this.workspaceId = workspaceId;this.snapshots = new AgentQuotaSnapshotModel(db, userId, workspaceId);this.ledger = new AgentQuotaUsageLedgerModel(db, userId, workspaceId);this.windows = new AgentQuotaWindowModel(db, userId, workspaceId);@@ -129,6 +173,8 @@ 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@@ -438,10 +484,18 @@ export class AgentQuotaService {);};+ /** `devices.id` of a device known by its gateway id; see `resolveDeviceRowId`. */+ resolveDeviceRowId = (gatewayDeviceId?: string): Promise<string | undefined> =>+ resolveDeviceRowId(this.devices, this.workspaceId, gatewayDeviceId);+/**- * Pick the account an agent should run on. A pinned binding short-circuits- * load balancing (that is the UI "switch account" lock); otherwise the pool- * is ranked weekly-headroom-first, scope-aware.+ * Pick the account an agent should run on, in this order:+ *+ * 1. the agent's account choice on the run's device (`deviceId`);+ * 2. the agent-wide pin, unless the caller says it cannot run it here+ * (`runnableExternalAccountIds`) — such a pin was picked on another+ * machine, so this one balances instead of failing on it;+ * 3. the pool, ranked weekly-headroom-first, scope-aware.** Returns the credential pointer alongside so the spawn side can act on the* choice (set `CLAUDE_CONFIG_DIR` for a config-dir profile, leave the default@@ -455,6 +509,7 @@ export class AgentQuotaService {credentialMode: string;credentialRef: QuotaAccountCredentialRef | null;externalAccountId: string | null;+ pinScope?: AccountPinScope;reason: 'pinned' | 'balanced';} | null> => {const chosen = await this.selectAccountId(agentId, options);@@ -468,10 +523,79 @@ export class AgentQuotaService {credentialMode: account.credentialMode,credentialRef: account.credentialRef ?? null,externalAccountId: account.externalAccountId ?? null,+ ...(chosen.pinScope && { pinScope: chosen.pinScope }),reason: chosen.reason,};};+ /** The account an agent is set to use on one device; `null` = Auto there. */+ getDeviceAccount = async (agentId: string, deviceId: string): Promise<string | null> =>+ (await this.deviceBindings.find(agentId, deviceId))?.accountId ?? null;++ /**+ * Set (or clear, with `null`) the account an agent uses on one device.+ *+ * An agent-wide pin left over from before choices were per device is first+ * handed to every device that holds a login for it, then demoted to the+ * pool: from here on each device keeps its own choice, so changing this+ * device neither moves the others nor stays overridden by the old pin.+ *+ * Throws `AccountNotSignedInOnDeviceError` when the device holds no recorded+ * login for the account. Retiring the legacy pin and the choice commit+ * together, so a rejected choice leaves every device's routing as it was.+ */+ setDeviceAccount = async (+ agentId: string,+ deviceId: string,+ accountId: string | null,+ ): Promise<void> => {+ try {+ await this.db.transaction(async (tx) => {+ const scoped = new AgentQuotaService(tx as LobeChatDatabase, this.userId, this.workspaceId);+ await scoped.retireAgentPin(agentId);++ if (accountId) await scoped.deviceBindings.set(agentId, deviceId, accountId);+ else await scoped.deviceBindings.clear(agentId, deviceId);+ });+ } catch (error) {+ if (isForeignKeyViolation(error)) throw new AccountNotSignedInOnDeviceError();+ throw error;+ }+ };++ /**+ * Replace the logins recorded for one provider on a device with the ones it+ * reports now. Accounts it no longer lists lose their login there, and with+ * it any device account choice made on them (FK cascade). Accounts without+ * a row in this scope are ignored: ingestion creates them first.+ */+ syncDeviceLogins = async (+ deviceId: string,+ provider: string,+ externalAccountIds: string[],+ ): Promise<void> => {+ const accounts = (await this.accounts.list()).filter((a) => a.provider === provider);+ const present = new Set(externalAccountIds);+ const signedInIds = new Set(+ accounts+ .filter((a) => a.externalAccountId && present.has(a.externalAccountId))+ .map((a) => a.id),+ );++ await pMap([...signedInIds], (accountId) => this.logins.record(accountId, deviceId), {+ concurrency: 8,+ });++ const providerIds = new Set(accounts.map((a) => a.id));+ const recorded = await this.logins.listByDevice(deviceId);+ await this.logins.removeOnDevice(+ deviceId,+ recorded+ .map((login) => login.accountId)+ .filter((id) => providerIds.has(id) && !signedInIds.has(id)),+ );+ };+/*** The account choice for a run on an execution device, which picks the* login itself (only it knows which accounts it is signed in to): the pin,@@ -480,10 +604,15 @@ export class AgentQuotaService {** Only `referenced` accounts map to a device login; a run pinned to any* other account keeps the default login, as on the desktop.+ *+ * With the run's `deviceId`, that device's own choice is the pin. A legacy+ * agent-wide pin stays strict only where its login is recorded; elsewhere+ * it was picked on another machine, so it becomes the first Auto candidate+ * and the device falls through to the pool (or its default login).*/planDeviceRouting = async (agentId: string,- options: Pick<SelectAccountOptions, 'modelScope' | 'now' | 'provider'> = {},+ options: Pick<SelectAccountOptions, 'deviceId' | 'modelScope' | 'now' | 'provider'> = {},): Promise<ClaudeCodeAccountRouting | null> => {const bindings = await this.enabledBindings(agentId, options.provider);const accounts = new Map((await this.accounts.list()).map((a) => [a.id, a]));@@ -495,14 +624,29 @@ export class AgentQuotaService {return { externalAccountId: account.externalAccountId, ...(name ? { name } : {}) };};+ const deviceChoice = await this.deviceChoiceOf(agentId, bindings, options.deviceId);+ if (deviceChoice) {+ const account = routed(deviceChoice);+ return account ? { candidates: [account], mode: 'pinned' } : null;+ }+const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);+ let pinnedElsewhere: ClaudeCodeRoutedAccount | undefined;if (pinned) {const account = routed(pinned.accountId);- return account ? { candidates: [account], mode: 'pinned' } : null;+ if (!account) return null;+ const strict =+ !options.deviceId ||+ (await this.logins.listByAccount(pinned.accountId)).some(+ (login) => login.deviceId === options.deviceId,+ );+ if (strict) return { candidates: [account], mode: 'pinned' };+ pinnedElsewhere = account;}const pool = bindings.filter((b) => b.role === QuotaBindingRole.pool);- if (pool.length === 0) return null;+ if (pool.length === 0)+ return pinnedElsewhere ? { candidates: [pinnedElsewhere], mode: 'balanced' } : null;const now = options.now ?? Date.now();const priorityById = new Map(pool.map((b) => [b.accountId, b.priority]));@@ -514,10 +658,63 @@ export class AgentQuotaService {loads.map((l) => ({ ...l, priority: priorityById.get(l.accountId) ?? 0 })),{ modelScope: options.modelScope, now },).flatMap((load) => routed(load.accountId) ?? []);+ if (pinnedElsewhere)+ candidates.splice(+ 0,+ 0,+ ...[pinnedElsewhere].filter(+ (account) => !candidates.some((c) => c.externalAccountId === account.externalAccountId),+ ),+ );return candidates.length > 0 ? { candidates, mode: 'balanced' } : null;};+ /**+ * The account the agent's choice on `deviceId` names, while it is still in+ * the agent's rotation (an account since dropped or disabled no longer+ * counts). `bindings` are the agent's enabled bindings for the provider.+ */+ private deviceChoiceOf = async (+ agentId: string,+ bindings: { accountId: string; role: string }[],+ deviceId?: string,+ ): Promise<string | undefined> => {+ if (!deviceId) return;+ const choice = await this.deviceBindings.find(agentId, deviceId);+ if (!choice) return;+ const usable = bindings.some(+ (b) => b.accountId === choice.accountId && b.role !== QuotaBindingRole.disabled,+ );+ return usable ? choice.accountId : undefined;+ };++ /** Move a legacy agent-wide pin onto the devices that can run it, then demote it. */+ private retireAgentPin = async (agentId: string) => {+ const pinned = (await this.bindings.listByAgent(agentId)).find(+ (b) => b.role === QuotaBindingRole.pinned,+ );+ if (!pinned) return;++ // Insert-if-absent rather than reading the choices first: another device's+ // first choice may commit concurrently, and the handed-down pin must not+ // replace it.+ const logins = await this.logins.listByAccount(pinned.accountId);+ await pMap(+ logins,+ (login) => this.deviceBindings.setIfAbsent(agentId, login.deviceId, pinned.accountId),+ { concurrency: 8 },+ );+ await this.bindings.upsert({+ accountId: pinned.accountId,+ agentId,+ enabled: pinned.enabled,+ priority: pinned.priority,+ role: QuotaBindingRole.pool,+ weight: pinned.weight,+ });+ };+/*** The agent's enabled bindings. Bindings are written provider-blind; a* caller that names its provider must never be routed onto another@@ -535,26 +732,39 @@ export class AgentQuotaService {private selectAccountId = async (agentId: string,options: SelectAccountOptions,- ): Promise<{ accountId: string; reason: 'pinned' | 'balanced' } | null> => {+ ): Promise<{+ accountId: string;+ pinScope?: AccountPinScope;+ reason: 'pinned' | 'balanced';+ } | null> => {const bindings = await this.enabledBindings(agentId, options.provider);- const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);- if (pinned) return { accountId: pinned.accountId, reason: 'pinned' };- let pool = bindings.filter((b) => b.role === QuotaBindingRole.pool);- // Auto mode may only land on an account the caller can actually run. A- // pin is still returned as-is: the caller must say it cannot run it,- // rather than quietly run another account.+ // The device's own choice is returned even when the caller cannot run it:+ // the caller must say so rather than quietly run another account.+ const deviceChoice = await this.deviceChoiceOf(agentId, bindings, options.deviceId);+ if (deviceChoice) return { accountId: deviceChoice, pinScope: 'device', reason: 'pinned' };++ let canRun = (_accountId: string) => true;if (options.runnableExternalAccountIds) {const runnable = new Set(options.runnableExternalAccountIds);// One read of the caller's accounts rather than a lookup per binding.const externalIdById = new Map((await this.accounts.list()).map((account) => [account.id, account.externalAccountId]),);- pool = pool.filter((b) => {- const externalId = externalIdById.get(b.accountId);+ canRun = (accountId) => {+ const externalId = externalIdById.get(accountId);return !!externalId && runnable.has(externalId);- });+ };}++ // A legacy agent-wide pin the caller cannot run was picked on another+ // machine: balance here instead of failing on it.+ const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);+ if (pinned && canRun(pinned.accountId))+ return { accountId: pinned.accountId, pinScope: 'agent', reason: 'pinned' };++ // Auto mode may only land on an account the caller can actually run.+ const pool = bindings.filter((b) => b.role === QuotaBindingRole.pool && canRun(b.accountId));if (pool.length === 0) return null;const now = options.now ?? Date.now();diff --git a/apps/server/src/services/agentQuota/resolveDeviceRowId.ts b/apps/server/src/services/agentQuota/resolveDeviceRowId.tsnew file mode 100644index 00000000000..21b11443f58--- /dev/null+++ b/apps/server/src/services/agentQuota/resolveDeviceRowId.ts@@ -0,0 +1,24 @@+import type { DeviceModel } from '@/database/models/device';++/**+ * Clients and dispatch know a device by its gateway id (the string+ * `devices.device_id`, e.g. `agencyConfig.boundDeviceId`), but quota rows+ * reference the `devices.id` uuid. `undefined` when it does not resolve.+ *+ * A workspace device's identity is `(workspaceId, deviceId)` — `userId` only+ * records the first enroller — so the personal `(userId, deviceId)` lookup+ * misses a machine any other member enrolled. Try the workspace-scoped lookup+ * first when there is a workspace (it also applies the device's visibility+ * rules), then fall back to the caller's own devices.+ */+export const resolveDeviceRowId = async (+ deviceModel: Pick<DeviceModel, 'findByDeviceId' | 'findWorkspaceDeviceById'>,+ workspaceId: string | null | undefined,+ gatewayDeviceId: string | undefined,+): Promise<string | undefined> => {+ if (!gatewayDeviceId) return undefined;+ const row =+ (workspaceId ? await deviceModel.findWorkspaceDeviceById(gatewayDeviceId) : undefined) ??+ (await deviceModel.findByDeviceId(gatewayDeviceId));+ return row?.id;+};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.tsindex dc63d639e28..116c7722fed 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts@@ -37,6 +37,8 @@ const resolveClaudeAccountRouting = async (deps: HeteroDispatchDeps,params: {agentId: string;+ /** Gateway id of the device the run is dispatched to. */+ deviceId: string;heteroType: HeteroDispatchInput['heteroType'];heterogeneousProvider: HeteroDispatchInput['heterogeneousProvider'];},@@ -45,11 +47,13 @@ const resolveClaudeAccountRouting = async (if (claudeCodeAgentEnvPicksLogin(params.heterogeneousProvider?.env)) return;try {- const routing = await new AgentQuotaService(- deps.db,- deps.userId,- deps.workspaceId,- ).planDeviceRouting(params.agentId, { provider: 'claude-code' });+ const quota = new AgentQuotaService(deps.db, deps.userId, deps.workspaceId);+ // The device's own account choice wins; an agent-wide pin made on another+ // machine must not block this one.+ const routing = await quota.planDeviceRouting(params.agentId, {+ deviceId: await quota.resolveDeviceRowId(params.deviceId),+ provider: 'claude-code',+ });return routing ?? undefined;} catch (err) {log('execAgent: Claude Code account routing failed: %O', err);@@ -206,6 +210,7 @@ export const dispatchToCliDevice = async (const claudeAccountRouting = await resolveClaudeAccountRouting(deps, {agentId: resolvedAgentId,+ deviceId: dispatchDeviceId,heteroType,heterogeneousProvider,});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.tsindex 2982c272fce..de27124e830 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts@@ -62,7 +62,10 @@ vi.mock('@/server/modules/AgentRuntime/factory', () => ({vi.mock('@/server/services/agentQuota', () => ({AgentQuotaService: vi.fn(function () {- return { planDeviceRouting: mocks.planDeviceRouting };+ return {+ planDeviceRouting: mocks.planDeviceRouting,+ resolveDeviceRowId: async (id?: string) => (id ? `row-${id}` : undefined),+ };}),}));@@ -549,7 +552,11 @@ describe('dispatchHeteroAgent — local CLI agents', () => {await dispatchHeteroAgent(deps, createCtx(deviceCtx), createInput('claude-code'));- expect(mocks.planDeviceRouting).toHaveBeenCalledWith('agent-1', { provider: 'claude-code' });+ // The routing is asked for this device, so its own account choice applies.+ expect(mocks.planDeviceRouting).toHaveBeenCalledWith('agent-1', {+ deviceId: 'row-dev-1',+ provider: 'claude-code',+ });expect(mocks.dispatchAgentRun.mock.calls[0][0].claudeAccountRouting).toEqual(routing);});diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 402419ff7cb..d7c2be2f1b7 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1408,8 +1408,10 @@"heteroAgent.claudeQuota.manage.modeManualHint": "Always run this agent on the account you pick.","heteroAgent.claudeQuota.manage.more": "More","heteroAgent.claudeQuota.manage.notSignedIn": "Not signed in on this device",+ "heteroAgent.claudeQuota.manage.notSignedInOnDevice": "That account isn't signed in on this device yet. Sign in there first.","heteroAgent.claudeQuota.manage.remove": "Remove account","heteroAgent.claudeQuota.manage.signIn": "Sign in",+ "heteroAgent.claudeQuota.manage.switchFailed": "Couldn't switch the account. Try again.","heteroAgent.claudeQuota.manage.title": "Claude Code accounts","heteroAgent.claudeQuota.manage.use": "Use","heteroAgent.claudeQuota.manage.weeklyLeft": "{{percent}}% weekly",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 55da3d86b8a..669f1f7bcd9 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1408,8 +1408,10 @@"heteroAgent.claudeQuota.manage.modeManualHint": "该助手始终使用你选定的账号运行。","heteroAgent.claudeQuota.manage.more": "更多","heteroAgent.claudeQuota.manage.notSignedIn": "本机未登录",+ "heteroAgent.claudeQuota.manage.notSignedInOnDevice": "该账号还没有在这台设备上登录,请先在该设备上登录。","heteroAgent.claudeQuota.manage.remove": "移除账号","heteroAgent.claudeQuota.manage.signIn": "登录",+ "heteroAgent.claudeQuota.manage.switchFailed": "切换账号失败,请重试。","heteroAgent.claudeQuota.manage.title": "Claude Code 账号","heteroAgent.claudeQuota.manage.use": "使用","heteroAgent.claudeQuota.manage.weeklyLeft": "本周剩余 {{percent}}%",diff --git a/packages/database/src/models/__tests__/agentQuota.deviceAccounts.test.ts b/packages/database/src/models/__tests__/agentQuota.deviceAccounts.test.tsnew file mode 100644index 00000000000..b3312834cce--- /dev/null+++ b/packages/database/src/models/__tests__/agentQuota.deviceAccounts.test.ts@@ -0,0 +1,142 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, devices, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import {+ AgentDeviceAccountBindingModel,+ AgentProviderAccountLoginModel,+ AgentProviderAccountModel,+} from '../agentQuota';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agent-quota-device-user';+const teammateId = 'agent-quota-device-teammate';+const workspaceId = 'agent-quota-device-workspace';+const agentId = 'agent-quota-device-agent';++let deviceA: string;+let deviceB: string;+let accountId: string;+let otherAccountId: string;++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: teammateId }]);+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Device accounts',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await serverDB.insert(agents).values({ id: agentId, userId });+ const rows = await serverDB+ .insert(devices)+ .values([+ { deviceId: 'gateway-a', identitySource: 'stable', userId },+ { deviceId: 'gateway-b', identitySource: 'stable', userId },+ ])+ .returning();+ [deviceA, deviceB] = rows.map((row) => row.id);+ const accounts = new AgentProviderAccountModel(serverDB, userId);+ accountId = (await accounts.upsertByIdentity('claude-code', { externalAccountId: 'ext-1' })).id;+ otherAccountId = (await accounts.upsertByIdentity('claude-code', { externalAccountId: 'ext-2' }))+ .id;+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentProviderAccountLoginModel', () => {+ it('records one login per account and device, refreshing it on every report', async () => {+ const logins = new AgentProviderAccountLoginModel(serverDB, userId);++ const first = await logins.record(accountId, deviceA);+ const again = await logins.record(accountId, deviceA);+ await logins.record(accountId, deviceB);++ expect(again.id).toBe(first.id);+ expect(again.lastSeenAt.getTime()).toBeGreaterThanOrEqual(first.lastSeenAt.getTime());+ expect((await logins.listByDevice(deviceA)).map((l) => l.accountId)).toEqual([accountId]);+ expect((await logins.listByAccount(accountId)).map((l) => l.deviceId).sort()).toEqual(+ [deviceA, deviceB].sort(),+ );+ });++ it('removes only the named logins on one device', async () => {+ const logins = new AgentProviderAccountLoginModel(serverDB, userId);+ await logins.record(accountId, deviceA);+ await logins.record(otherAccountId, deviceA);+ await logins.record(accountId, deviceB);++ await logins.removeOnDevice(deviceA, []);+ await logins.removeOnDevice(deviceA, [accountId]);++ expect((await logins.listByDevice(deviceA)).map((l) => l.accountId)).toEqual([otherAccountId]);+ expect(await logins.listByDevice(deviceB)).toHaveLength(1);+ });++ it('keeps personal and workspace logins apart', async () => {+ await new AgentProviderAccountLoginModel(serverDB, userId).record(accountId, deviceA);++ expect(+ await new AgentProviderAccountLoginModel(serverDB, userId, workspaceId).listByDevice(deviceA),+ ).toEqual([]);+ expect(+ await new AgentProviderAccountLoginModel(serverDB, teammateId).listByDevice(deviceA),+ ).toEqual([]);+ });+});++describe('AgentDeviceAccountBindingModel', () => {+ it('keeps one choice per agent and device, replaced by the next one', async () => {+ const logins = new AgentProviderAccountLoginModel(serverDB, userId);+ const choices = new AgentDeviceAccountBindingModel(serverDB, userId);+ await logins.record(accountId, deviceA);+ await logins.record(otherAccountId, deviceA);+ await logins.record(accountId, deviceB);++ await choices.set(agentId, deviceA, accountId);+ await choices.set(agentId, deviceA, otherAccountId);+ await choices.set(agentId, deviceB, accountId);++ expect((await choices.find(agentId, deviceA))?.accountId).toBe(otherAccountId);+ expect(await choices.listByAgent(agentId)).toHaveLength(2);++ await choices.clear(agentId, deviceA);+ expect(await choices.find(agentId, deviceA)).toBeNull();+ });++ // Regression: handing a legacy pin down to a device replaced a choice made+ // there by a concurrent first per-device write.+ it('hands down a choice only where the device has none yet', async () => {+ const logins = new AgentProviderAccountLoginModel(serverDB, userId);+ const choices = new AgentDeviceAccountBindingModel(serverDB, userId);+ await logins.record(accountId, deviceA);+ await logins.record(otherAccountId, deviceA);+ await logins.record(accountId, deviceB);+ await choices.set(agentId, deviceA, otherAccountId);++ await choices.setIfAbsent(agentId, deviceA, accountId);+ await choices.setIfAbsent(agentId, deviceB, accountId);++ expect((await choices.find(agentId, deviceA))?.accountId).toBe(otherAccountId);+ expect((await choices.find(agentId, deviceB))?.accountId).toBe(accountId);+ });++ it('rejects a choice the device holds no login for, and drops it with the login', async () => {+ const logins = new AgentProviderAccountLoginModel(serverDB, userId);+ const choices = new AgentDeviceAccountBindingModel(serverDB, userId);++ await expect(choices.set(agentId, deviceA, accountId)).rejects.toThrow();++ await logins.record(accountId, deviceA);+ await choices.set(agentId, deviceA, accountId);+ await logins.removeOnDevice(deviceA, [accountId]);++ expect(await choices.find(agentId, deviceA)).toBeNull();+ });+});diff --git a/packages/database/src/models/agentQuota.ts b/packages/database/src/models/agentQuota.tsindex 64dcc0e842c..ccf46e7cdf4 100644--- a/packages/database/src/models/agentQuota.ts+++ b/packages/database/src/models/agentQuota.ts@@ -12,7 +12,9 @@ import type {} from '../schemas';import {agentAccountBindings,+ agentDeviceAccountBindings,agentOperations,+ agentProviderAccountLogins,agentProviderAccounts,agentQuotaCalibrations,agentQuotaSnapshots,@@ -286,6 +288,162 @@ export class AgentAccountBindingModel {this.db.delete(agentAccountBindings).where(and(eq(agentAccountBindings.id, id), this.mine()));}+// ─────────────────────────────────────────────────────────────────────────────+// Logins — which devices an account is signed in on+// ─────────────────────────────────────────────────────────────────────────────++export class AgentProviderAccountLoginModel {+ private userId: string;+ private db: LobeChatDatabase;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private mine = () =>+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ agentProviderAccountLogins,+ );++ /** Record that `deviceId` holds a login for `accountId` (refreshes `lastSeenAt`). */+ record = async (accountId: string, deviceId: string) => {+ const now = new Date();+ const [row] = await this.db+ .insert(agentProviderAccountLogins)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ { accountId, deviceId, lastSeenAt: now },+ ),+ )+ .onConflictDoUpdate({+ set: { lastSeenAt: now, updatedAt: now, userId: this.userId },+ target: [agentProviderAccountLogins.accountId, agentProviderAccountLogins.deviceId],+ })+ .returning();+ return row;+ };++ listByDevice = async (deviceId: string) =>+ this.db+ .select()+ .from(agentProviderAccountLogins)+ .where(and(this.mine(), eq(agentProviderAccountLogins.deviceId, deviceId)));++ listByAccount = async (accountId: string) =>+ this.db+ .select()+ .from(agentProviderAccountLogins)+ .where(and(this.mine(), eq(agentProviderAccountLogins.accountId, accountId)));++ /** Forget logins on a device; device account bindings on them go with them (FK cascade). */+ removeOnDevice = async (deviceId: string, accountIds: string[]) => {+ if (accountIds.length === 0) return;+ await this.db+ .delete(agentProviderAccountLogins)+ .where(+ and(+ this.mine(),+ eq(agentProviderAccountLogins.deviceId, deviceId),+ inArray(agentProviderAccountLogins.accountId, accountIds),+ ),+ );+ };+}++// ─────────────────────────────────────────────────────────────────────────────+// Device account bindings — an agent's account choice on one device+// ─────────────────────────────────────────────────────────────────────────────++export class AgentDeviceAccountBindingModel {+ private userId: string;+ private db: LobeChatDatabase;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private mine = () =>+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ agentDeviceAccountBindings,+ );++ find = async (agentId: string, deviceId: string) =>+ (await this.db.query.agentDeviceAccountBindings.findFirst({+ where: and(+ this.mine(),+ eq(agentDeviceAccountBindings.agentId, agentId),+ eq(agentDeviceAccountBindings.deviceId, deviceId),+ ),+ })) ?? null;++ listByAgent = async (agentId: string) =>+ this.db+ .select()+ .from(agentDeviceAccountBindings)+ .where(and(this.mine(), eq(agentDeviceAccountBindings.agentId, agentId)));++ /**+ * Choose the account an agent uses on a device. The (account, device) pair+ * must be a recorded login there: the composite foreign key rejects the+ * write otherwise.+ */+ set = async (agentId: string, deviceId: string, accountId: string) => {+ const now = new Date();+ const [row] = await this.db+ .insert(agentDeviceAccountBindings)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ { accountId, agentId, deviceId },+ ),+ )+ .onConflictDoUpdate({+ set: { accountId, updatedAt: now, userId: this.userId },+ target: [agentDeviceAccountBindings.agentId, agentDeviceAccountBindings.deviceId],+ })+ .returning();+ return row;+ };++ /**+ * Like `set`, but never replaces a choice the device already has: a pin+ * handed down to a device must not overwrite a choice made there meanwhile.+ */+ setIfAbsent = async (agentId: string, deviceId: string, accountId: string) => {+ await this.db+ .insert(agentDeviceAccountBindings)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ { accountId, agentId, deviceId },+ ),+ )+ .onConflictDoNothing({+ target: [agentDeviceAccountBindings.agentId, agentDeviceAccountBindings.deviceId],+ });+ };++ clear = async (agentId: string, deviceId: string) =>+ this.db+ .delete(agentDeviceAccountBindings)+ .where(+ and(+ this.mine(),+ eq(agentDeviceAccountBindings.agentId, agentId),+ eq(agentDeviceAccountBindings.deviceId, deviceId),+ ),+ );+}+// ─────────────────────────────────────────────────────────────────────────────// Snapshots — append-only observation// ─────────────────────────────────────────────────────────────────────────────diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 60bdb88ac01..8acd9eb2f5f 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -33,6 +33,9 @@ export default {'heteroAgent.claudeQuota.manage.loginSuccess': 'Signed in as {{account}}','heteroAgent.claudeQuota.manage.loginWaiting': 'Finish signing in in your browser…','heteroAgent.claudeQuota.manage.notSignedIn': 'Not signed in on this device',+ 'heteroAgent.claudeQuota.manage.notSignedInOnDevice':+ "That account isn't signed in on this device yet. Sign in there first.",+ 'heteroAgent.claudeQuota.manage.switchFailed': "Couldn't switch the account. Try again.",'heteroAgent.claudeQuota.manage.signIn': 'Sign in','heteroAgent.claudeQuota.noRunnableAccount':"None of the Claude Code accounts in this agent's rotation are signed in on this device. Sign one in from Manage accounts, or add a signed-in account to the rotation.",diff --git a/packages/types/src/agentQuota.ts b/packages/types/src/agentQuota.tsnew file mode 100644index 00000000000..cfefd14f393--- /dev/null+++ b/packages/types/src/agentQuota.ts@@ -0,0 +1,8 @@+/**+ * The Claude Code account an agent uses on one device. A login only exists on+ * the machine it was signed in on, so the Manual pick is made per device;+ * `accountId: null` means that device runs in Auto mode.+ */+export interface QuotaDeviceAccount {+ accountId: string | null;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex a83205b4838..6e3d7d886bd 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -6,6 +6,7 @@ export * from './agentHook';export * from './agentHookResponse';export * from './agentMail';export * from './agentOperation';+export * from './agentQuota';export * from './aiChat';export * from './aiProvider';export * from './apiKey';diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsxindex 9d100bb943e..6c540b7029f 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx@@ -11,6 +11,7 @@ import { agentQuotaService } from '@/services/agentQuota';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import { fetchClaudeCodeQuotaSnapshot } from '@/services/heteroAgentQuota';import { getAgentQuotaStoreState } from '@/store/agentQuota';+import { getElectronStoreState } from '@/store/electron';import QuotaAccountSwitcher from './QuotaAccountSwitcher';import type { FetchQuotaOptions, QuotaWindowItem } from './QuotaMenu';@@ -115,14 +116,29 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =const force = !!options?.force;const quotaStore = getAgentQuotaStoreState();- // 1) Resolve the account to display — pinned for this agent, else the first.- const [initialAccounts, bindings] = await Promise.all([+ // 1) Resolve the account to display — pinned for this agent on this+ // desktop (its own pick, else the agent-wide pin), else the first.+ const localDeviceId =+ isDesktop && !deviceId && agentId+ ? await getElectronStoreState().resolveGatewayDeviceId()+ : undefined;+ const [initialAccounts, bindings, deviceAccount] = await Promise.all([quotaStore.readQuotaAccounts().catch(() => []),agentId ? quotaStore.readQuotaBindings(agentId).catch(() => []) : [],+ agentId && localDeviceId+ ? quotaStore.readQuotaDeviceAccount(agentId, localDeviceId).catch(() => null)+ : null,]);let accounts = initialAccounts;let claude = accounts.filter((a) => a.provider === 'claude-code');- const pinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;+ // A pick whose account has since left the agent's rotation no longer+ // routes runs (as at spawn), so it is not what this panel shows either.+ const devicePickId = bindings.some(+ (b) => b.accountId === deviceAccount?.accountId && b.enabled && b.role !== 'disabled',+ )+ ? deviceAccount?.accountId+ : undefined;+ const pinnedId = devicePickId ?? bindings.find((b) => b.role === 'pinned')?.accountId;const trustedExternalAccountId = deviceId ? trustedDeviceAccounts.get(deviceId) : undefined;let account = deviceId? claude.find((a) => a.externalAccountId === trustedExternalAccountId)diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsxindex d55d67e58e9..966acc48ec9 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx@@ -6,7 +6,9 @@ import { type ReactElement } from 'react';import { SWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createReplicaState } from '@/libs/replica';import { agentQuotaService } from '@/services/agentQuota';+import { gatewayConnectionService } from '@/services/electron/gatewayConnection';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import { useAgentQuotaStore } from '@/store/agentQuota';import {@@ -192,6 +194,8 @@ describe('QuotaAccountManager on the desktop', () => {beforeEach(() => {desktop.value = true;isolateQuotaReplica();+ // A signed-in desktop: the IPC below resolves this as its stable id.+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } } as never);vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([account('here'),account('away'),@@ -207,11 +211,22 @@ describe('QuotaAccountManager on the desktop', () => {vi.spyOn(heterogeneousAgentService, 'getClaudeCodeQuota').mockResolvedValue({status: 'unavailable',} as never);+ vi.spyOn(agentQuotaService, 'getDeviceAccount').mockResolvedValue({ accountId: null });+ vi.spyOn(agentQuotaService, 'syncDeviceLogins').mockResolvedValue(undefined as never);+ // The desktop IPC behind this machine's stable device id answers with the+ // id each case sets on `gatewayDeviceInfo`.+ vi.spyOn(gatewayConnectionService, 'getStableDeviceId').mockImplementation(+ async () => useElectronStore.getState().gatewayDeviceInfo?.deviceId ?? null,+ );});afterEach(() => {desktop.value = false;- useElectronStore.setState({ gatewayDeviceInfo: undefined });+ useElectronStore.setState({+ gatewayDeviceInfo: undefined,+ gatewayStableDeviceIdMap: {},+ gatewayStableDeviceIdReplica: createReplicaState(),+ });vi.restoreAllMocks();});@@ -256,6 +271,90 @@ describe('QuotaAccountManager on the desktop', () => {expect(heterogeneousAgentService.listClaudeCodeAccounts).toHaveBeenCalled();});+ it('shows this device’s own pick over the agent-wide pin', async () => {+ act(() =>+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } } as never),+ );+ vi.mocked(agentQuotaService.listBindings).mockResolvedValue([+ binding('b1', 'here', 'pinned'),+ binding('b2', 'away', 'pool'),+ ]);+ vi.mocked(agentQuotaService.getDeviceAccount).mockResolvedValue({ accountId: 'away' });++ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} deviceId={'device-1'} />);++ await waitFor(() => expect(checkedOption()).toContain('[email protected]'));+ expect(agentQuotaService.getDeviceAccount).toHaveBeenCalledWith('agent-1', 'device-1');+ });++ // Regression: a pin made on another machine read as this device's choice,+ // with its account marked "not signed in on this device".+ it('reads an agent-wide pin this device cannot run as Auto', async () => {+ act(() =>+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } } as never),+ );+ vi.mocked(agentQuotaService.listBindings).mockResolvedValue([+ binding('b1', 'here', 'pool'),+ binding('b2', 'away', 'pinned'),+ ]);++ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);++ await screen.findByText('heteroAgent.claudeQuota.manage.notSignedIn');+ await waitFor(() =>+ expect(checkedOption()).toContain('heteroAgent.claudeQuota.manage.modeAuto'),+ );+ expect(screen.getByText(/heteroAgent\.claudeQuota\.manage\.autoRoutingTo/)).toBeTruthy();+ });++ it('saves a switch for this device only, not for every device', async () => {+ act(() =>+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } } as never),+ );+ const setDeviceAccount = vi+ .spyOn(agentQuotaService, 'setDeviceAccount')+ .mockResolvedValue(undefined as never);+ const switchAccount = vi.spyOn(agentQuotaService, 'switchAccount');++ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);+ await waitFor(() =>+ expect(radioFor('[email protected]').getAttribute('aria-disabled')).not.toBe('true'),+ );+ fireEvent.click(radioFor('[email protected]'));+ fireEvent.click(+ await screen.findByRole('button', { name: 'heteroAgent.claudeQuota.manage.confirmSwitch' }),+ );++ await waitFor(() =>+ expect(setDeviceAccount).toHaveBeenCalledWith('agent-1', 'this-desktop', 'here'),+ );+ expect(switchAccount).not.toHaveBeenCalled();+ });++ // Regression: a failed stable-id lookup read as "no device", so a switch+ // here became an agent-wide pin that moved every other device too.+ it('takes no writes while this desktop’s device id cannot be resolved', async () => {+ act(() =>+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } } as never),+ );+ vi.mocked(gatewayConnectionService.getStableDeviceId).mockRejectedValue(new Error('ipc down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const switchAccount = vi.spyOn(agentQuotaService, 'switchAccount');+ const setDeviceAccount = vi.spyOn(agentQuotaService, 'setDeviceAccount');++ renderWithFreshCache(<QuotaAccountManager agentId={'agent-1'} />);++ await waitFor(() =>+ expect(checkedOption()).toContain('heteroAgent.claudeQuota.manage.modeAuto'),+ );+ for (const radio of screen.getAllByRole('radio'))+ expect(radio.getAttribute('aria-disabled')).toBe('true');+ for (const toggle of screen.getAllByRole('switch'))+ expect(toggle.hasAttribute('disabled')).toBe(true);+ expect(switchAccount).not.toHaveBeenCalled();+ expect(setDeviceAccount).not.toHaveBeenCalled();+ });+it('lists only Claude Code accounts, never another coding agent’s', async () => {vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([account('here'),diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsxindex 1af9b5b91e4..1cb412c6e97 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx@@ -36,6 +36,7 @@ import {useAgentQuotaStore,} from '@/store/agentQuota';import { useElectronStore } from '@/store/electron';+import { electronGatewaySelectors } from '@/store/electron/selectors';const styles = createStaticStyles(({ css }) => ({footer: css`@@ -124,7 +125,8 @@ interface QuotaAccountManagerProps {/*** Bound execution device the agent runs on. A remote device's logins live* on that machine, not on the desktop showing this modal, so local sign-in- * state says nothing about which accounts it can run there.+ * state says nothing about which accounts it can run there. The Manual pick+ * is made for this device (this desktop when unset).*/deviceId?: string;}@@ -134,8 +136,10 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceIdconst [useFetchQuotaAccounts,useFetchQuotaBindings,+ useFetchQuotaDeviceAccount,bindQuotaAccount,renameQuotaAccount,+ setQuotaDeviceAccount,switchQuotaAccount,unbindQuotaAccount,useFetchClaudeLocalAccounts,@@ -144,8 +148,10 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId] = useAgentQuotaStore((s) => [s.useFetchQuotaAccounts,s.useFetchQuotaBindings,+ s.useFetchQuotaDeviceAccount,s.bindQuotaAccount,s.renameQuotaAccount,+ s.setQuotaDeviceAccount,s.switchQuotaAccount,s.unbindQuotaAccount,s.useFetchClaudeLocalAccounts,@@ -158,8 +164,35 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId// Only the desktop runs Claude Code locally, so only it has logins to show —// and only when this agent runs here: in-process, or through the gateway on// this desktop's own device row, which spawns on the same logins.- const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);+ const [currentDeviceId, useFetchGatewayStableDeviceId] = useElectronStore((s) => [+ s.gatewayDeviceInfo?.deviceId,+ s.useFetchGatewayStableDeviceId,+ ]);+ // The cached id may still be the install's fallback before the gateway+ // connects; resolving corrects it, so the pick lands on this machine's row.+ // Until it settles a write could not tell this device from "no device" and+ // would fall back to the agent-wide pin, so the controls wait for it.+ const needsLocalDevice = isDesktop && !deviceId;+ useFetchGatewayStableDeviceId(needsLocalDevice);+ const stableDeviceId = useElectronStore(electronGatewaySelectors.gatewayStableDeviceId);+ // The replica entry is `undefined` until this device is resolved (or hydrated).+ const localDeviceSettled = !needsLocalDevice || stableDeviceId !== undefined;+ // Resolved to no id (the IPC lookup failed): this is still a desktop picking+ // for itself, not the web's agent-wide case, so it shows but cannot write.+ const localDeviceMissing = needsLocalDevice && stableDeviceId === null;const managesLocalLogins = isDesktop && (!deviceId || deviceId === currentDeviceId);+ // A login lives on one machine, so the Manual pick belongs to one device.+ // The web without a bound device has none and keeps the agent-wide pin.+ // Never the cached `gatewayDeviceInfo` id: before the gateway connects that+ // is the install's fallback UUID, not the row the server knows this machine by.+ const targetDeviceId = deviceId ?? (isDesktop ? (stableDeviceId ?? undefined) : undefined);+ useFetchQuotaDeviceAccount(agentId, targetDeviceId);+ const deviceAccount = useAgentQuotaStore(+ agentQuotaSelectors.deviceAccount(agentId, targetDeviceId),+ );+ const deviceAccountConfirmed = useAgentQuotaStore(+ agentQuotaSelectors.isDeviceAccountConfirmed(scope, agentId, targetDeviceId),+ );useFetchClaudeLocalAccounts(managesLocalLogins);const localAccounts = useAgentQuotaStore((s) => s.claudeLocalAccounts);const loginPending = useAgentQuotaStore((s) => s.claudeLoginPending);@@ -185,14 +218,21 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId// Until this agent's bindings are on screen, every row would read as "off"// and Auto as routing to nobody: keep the mode and per-account controls// disabled and show no routing hint instead of acting on that guess.- const bindingsLoaded = loadedBindings !== undefined;+ const bindingsLoaded =+ localDeviceSettled &&+ loadedBindings !== undefined &&+ (!targetDeviceId || deviceAccount !== undefined);// A hydrated row may be outdated (changed in another tab or on another// device): show it, but take writes only once the server confirmed it, so a// change is computed against the bindings the server actually holds.const bindingsConfirmed = useAgentQuotaStore(agentQuotaSelectors.isBindingsConfirmed(scope, agentId),);- const canEditBindings = bindingsLoaded && bindingsConfirmed;+ const canEditBindings =+ !localDeviceMissing &&+ bindingsLoaded &&+ bindingsConfirmed &&+ (!targetDeviceId || deviceAccountConfirmed);const readingsMap = useAgentQuotaStore((s) => s.quotaReadingsMap);const weeklyById = useMemo(() =>@@ -240,7 +280,18 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceId[localAccounts, managesLocalLogins],);- const pinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;+ // A legacy agent-wide pin only counts here while this device can run it: a+ // pin picked on another machine leaves this one balancing (as runs do).+ const agentPinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;+ const agentPinned = accounts.find((a) => a.id === agentPinnedId);+ const devicePinnedId = deviceAccount?.accountId ?? undefined;+ const pinnedId = targetDeviceId+ ? devicePinnedId && inRotation(devicePinnedId)+ ? devicePinnedId+ : agentPinned && signedInHere(agentPinned)+ ? agentPinned.id+ : undefined+ : agentPinnedId;const current = pinnedId ?? AUTO;const selected = pending ?? current;const dirty = pending !== null && pending !== current;@@ -270,16 +321,40 @@ const QuotaAccountManager = memo<QuotaAccountManagerProps>(({ agentId, deviceIdrun(async () => {const value = pending;if (value === null) return;- if (value === AUTO) {+ // Never turn this desktop's pick into an agent-wide one.+ if (needsLocalDevice && !targetDeviceId) return;+ if (value !== AUTO && !bindings.some((b) => b.accountId === value)) {+ await bindQuotaAccount(agentId, value, 'pool');+ }+ if (targetDeviceId) {+ await setQuotaDeviceAccount(agentId, targetDeviceId, value === AUTO ? null : value);+ } else if (value === AUTO) {if (pinnedId) await bindQuotaAccount(agentId, pinnedId, 'pool');} else {- if (!bindings.some((b) => b.accountId === value)) {- await bindQuotaAccount(agentId, value, 'pool');- }await switchQuotaAccount(agentId, value);}- }).then(() => setPending(null)),- [agentId, bindQuotaAccount, bindings, pending, pinnedId, run, switchQuotaAccount],+ })+ .then(() => setPending(null))+ .catch((error: { data?: { code?: string } }) => {+ toast.error(+ error?.data?.code === 'PRECONDITION_FAILED'+ ? t('heteroAgent.claudeQuota.manage.notSignedInOnDevice')+ : t('heteroAgent.claudeQuota.manage.switchFailed'),+ );+ }),+ [+ agentId,+ bindQuotaAccount,+ bindings,+ needsLocalDevice,+ pending,+ pinnedId,+ run,+ setQuotaDeviceAccount,+ switchQuotaAccount,+ t,+ targetDeviceId,+ ],);const setRotation = useCallback(diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsxindex 54e9497a2c8..1a202a846af 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx@@ -10,6 +10,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';import { cacheScope } from '@/libs/replica';import { hashQuotaSourceKey, quotaPanelResource } from '@/store/agentQuota/projection';+import { useElectronStore } from '@/store/electron';import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';import { createQuotaSourceKey } from './QuotaMenu';@@ -82,7 +83,8 @@ vi.mock('@/libs/trpc/client', () => ({// path without each one stalling on a real HTTP request; individual tests can// hand it persisted accounts/windows.const mockQuotaService = vi.hoisted(() => ({- getLatestReadings: vi.fn(async (): Promise<unknown[]> => []),+ getDeviceAccount: vi.fn(async (): Promise<{ accountId: string | null }> => ({ accountId: null })),+ getLatestReadings: vi.fn(async (_accountId?: string): Promise<unknown[]> => []),ingestClaudeSnapshot: vi.fn(async () => undefined),ingestCodexSnapshot: vi.fn(async () => undefined),ingestKimiCodeSnapshot: vi.fn(async () => undefined),@@ -90,6 +92,7 @@ const mockQuotaService = vi.hoisted(() => ({refreshKimiCodeQuota: vi.fn(),listAccounts: vi.fn(async (): Promise<unknown[]> => []),listBindings: vi.fn(async (): Promise<unknown[]> => []),+ syncDeviceLogins: vi.fn(async () => undefined),}));vi.mock('@/services/agentQuota', () => ({ agentQuotaService: mockQuotaService }));@@ -213,6 +216,7 @@ beforeEach(() => {mockQuotaService.ingestKimiCodeSnapshot.mockClear();mockQuotaService.listAccounts.mockClear().mockResolvedValue([]);mockQuotaService.listBindings.mockClear().mockResolvedValue([]);+ mockQuotaService.getDeviceAccount.mockClear().mockResolvedValue({ accountId: null });vi.mocked(openQuotaCalendarModal).mockClear();});@@ -688,6 +692,31 @@ describe('ClaudeCodeQuotaMenu', () => {expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();});+ // Regression: a pick whose account was then disabled for the agent kept the+ // panel on that account, though runs no longer use it.+ it('does not show a device pick whose account left the agent rotation', async () => {+ const now = Date.now() - 60_000;+ mockQuotaService.listAccounts.mockResolvedValue([+ persistedAccount(now),+ { ...persistedAccount(now), externalAccountId: 'ext-2', id: 'acc-2' },+ ]);+ mockQuotaService.listBindings.mockResolvedValue([+ { accountId: 'acc-1', agentId: 'agent-1', enabled: true, id: 'b1', role: 'pool' },+ { accountId: 'acc-2', agentId: 'agent-1', enabled: true, id: 'b2', role: 'disabled' },+ ]);+ mockQuotaService.getDeviceAccount.mockResolvedValue({ accountId: 'acc-2' });+ mockQuotaService.getLatestReadings.mockImplementation(async (accountId?: string) => [+ { ...persistedSessionReading(now), utilization: accountId === 'acc-2' ? 50 : 8 },+ ]);+ vi.spyOn(useElectronStore.getState(), 'resolveGatewayDeviceId').mockResolvedValue('device-a');++ render(<ClaudeCodeQuotaMenu />);++ expect(await screen.findByText('92%')).toBeTruthy();+ expect(mockQuotaService.getDeviceAccount).toHaveBeenCalledWith('agent-1', 'device-a');+ expect(screen.queryByText('50%')).toBeNull();+ });+it('refreshes from the live API when the newest persisted reading is stale', async () => {// Under the previous 30 min policy this 31-minute-old reading is a// conservative stale case; the gate now trips at 2 minutes.diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.tsindex ab47591c7f2..eb89c14fc2e 100644--- a/src/services/agentQuota.ts+++ b/src/services/agentQuota.ts@@ -9,6 +9,7 @@ import type {QuotaAccountIdentity,QuotaLimitReading,} from '@lobechat/heterogeneous-agents/quota';+import type { QuotaDeviceAccount } from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -103,10 +104,31 @@ class AgentQuotaService {updateAccount = async (id: string, value: { enabled?: boolean; label?: string }) =>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> =>+ lambdaClient.agentQuota.getDeviceAccount.query({ agentId, deviceId });++ /** Pin an account for an agent on one device, or return it to Auto (`null`). */+ setDeviceAccount = async (agentId: string, deviceId: string, accountId: string | null) =>+ lambdaClient.agentQuota.setDeviceAccount.mutate({ accountId, agentId, deviceId });++ /** Report every login a device holds for a provider; the rest are forgotten there. */+ syncDeviceLogins = async (+ deviceId: string,+ provider: 'claude-code' | 'codex' | 'kimi-code',+ externalAccountIds: string[],+ ) => lambdaClient.agentQuota.syncDeviceLogins.mutate({ deviceId, externalAccountIds, provider });+/** Who the load balancer would pick right now (Auto mode preview + reason). */selectAccountForAgent = async (agentId: string,- options?: { modelScope?: string; provider?: string; runnableExternalAccountIds?: string[] },+ options?: {+ /** Gateway id of the device the run spawns on. */+ deviceId?: string;+ modelScope?: string;+ provider?: string;+ runnableExternalAccountIds?: string[];+ },) => lambdaClient.agentQuota.selectAccountForAgent.query({ agentId, ...options });/** One assistant turn's consumption → usage ledger (idempotent by message id). */diff --git a/src/store/agentQuota/action.ts b/src/store/agentQuota/action.tsindex 04b5196b5a2..6b66667f562 100644--- a/src/store/agentQuota/action.ts+++ b/src/store/agentQuota/action.ts@@ -9,12 +9,14 @@ import { mutate, useClientDataSWR } from '@/libs/swr';import { electronKeys } from '@/libs/swr/keys';import { agentQuotaService } from '@/services/agentQuota';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { getElectronStoreState } from '@/store/electron';import { type StoreSetter } from '@/store/types';import { flattenActions } from '@/store/utils/flattenActions';import { initialState, type State } from './initialState';import {hashQuotaSourceKey,+ parseQuotaDeviceAccountKey,QUOTA_ACCOUNTS_KEY,QUOTA_HISTORY_DAYS,QUOTA_HISTORY_WINDOW_LIMIT,@@ -22,6 +24,9 @@ import {quotaAccountsResource,type QuotaBinding,quotaBindingsResource,+ type QuotaDeviceAccount,+ quotaDeviceAccountKey,+ quotaDeviceAccountResource,type QuotaHistory,type QuotaHistoryFetched,quotaHistoryResource,@@ -45,7 +50,7 @@ type Setter = StoreSetter<Store>;*/export const QUOTA_READ_DEDUPE_MS = 10_000;-type QuotaResourceName = 'accounts' | 'bindings' | 'history' | 'readings';+type QuotaResourceName = 'accounts' | 'bindings' | 'deviceAccount' | 'history' | 'readings';interface ReadOptions {/** Skip the dedupe window and retire older requests (after a write / ingest). */@@ -82,6 +87,7 @@ export class ActionImpl {readonly #set: Setter;readonly #accounts;readonly #bindings;+ readonly #deviceAccount;readonly #readings;readonly #history;readonly #panel;@@ -121,6 +127,19 @@ export class ActionImpl {stateKey: 'quotaBindingsReplica',view: recordLens<Store, QuotaBinding[]>('quotaBindingsMap'),});+ this.#deviceAccount = createReplicaSlice(quotaDeviceAccountResource, {+ actionPrefix: 'quotaDeviceAccount',+ effects: confirmOn('deviceAccount'),+ fetcher: (key) => {+ const { agentId, deviceId } = parseQuotaDeviceAccountKey(key);+ return agentQuotaService.getDeviceAccount(agentId, deviceId);+ },+ get,+ merge: sameValue,+ set,+ stateKey: 'quotaDeviceAccountReplica',+ view: recordLens<Store, QuotaDeviceAccount>('quotaDeviceAccountMap'),+ });this.#readings = createReplicaSlice(quotaReadingsResource, {actionPrefix: 'quotaReadings',effects: confirmOn('readings'),@@ -187,6 +206,15 @@ export class ActionImpl {useFetchQuotaBindings = (agentId?: string | null): ReplicaSyncResult =>this.#bindings.useSync(agentId || null, this.#syncOptions('bindings', agentId));+ /** Sync one agent's account choice on one device (gateway id). */+ useFetchQuotaDeviceAccount = (+ agentId?: string | null,+ deviceId?: string | null,+ ): ReplicaSyncResult => {+ const key = agentId && deviceId ? quotaDeviceAccountKey(agentId, deviceId) : null;+ return this.#deviceAccount.useSync(key, this.#syncOptions('deviceAccount', key));+ };+useFetchQuotaReadings = (accountId?: string | null): ReplicaSyncResult =>this.#readings.useSync(accountId || null, this.#syncOptions('readings', accountId));@@ -227,6 +255,19 @@ export class ActionImpl {readQuotaBindings = (agentId: string, options?: ReadOptions): Promise<QuotaBinding[]> =>this.#read('bindings', this.#bindings, agentId, 'quotaBindingsMap', options);+ readQuotaDeviceAccount = (+ agentId: string,+ deviceId: string,+ options?: ReadOptions,+ ): Promise<QuotaDeviceAccount> =>+ this.#read(+ 'deviceAccount',+ this.#deviceAccount,+ quotaDeviceAccountKey(agentId, deviceId),+ 'quotaDeviceAccountMap',+ options,+ );+/*** A `fresh` readings read follows an ingest (local, device-side or a reset),* which also appended to the account's snapshot series and windows: refresh a@@ -259,6 +300,31 @@ export class ActionImpl {await this.#refresh(this.#bindings, agentId);};+ /**+ * Pin an account for an agent on one device (Manual mode there), or return+ * that device to Auto with `null`. The server first hands a legacy+ * agent-wide pin to the devices that hold its login, so the bindings change+ * too and are re-read.+ */+ setQuotaDeviceAccount = async (+ agentId: string,+ deviceId: string,+ accountId: string | null,+ ): Promise<void> => {+ const key = quotaDeviceAccountKey(agentId, deviceId);+ if (this.#get().quotaDeviceAccountMap[key] === undefined)+ await this.readQuotaDeviceAccount(agentId, deviceId);+ await this.#deviceAccount.optimistic(+ key,+ () => ({ accountId }),+ () => agentQuotaService.setDeviceAccount(agentId, deviceId, accountId),+ );+ await Promise.all([+ this.#refresh(this.#deviceAccount, key),+ this.#refresh(this.#bindings, agentId),+ ]);+ };+/** Add an account to an agent's pool, or change its role there. */bindQuotaAccount = async (agentId: string,@@ -387,7 +453,13 @@ export class ActionImpl {reset = (): void => {// A mounted manager / calendar keeps its sync key across the reset, so// nothing would refetch until a focus or remount: revalidate once cleared.- for (const slice of [this.#accounts, this.#bindings, this.#readings, this.#history])+ for (const slice of [+ this.#accounts,+ this.#bindings,+ this.#deviceAccount,+ this.#readings,+ this.#history,+ ])void slice.clear().then(() => slice.revalidate());void this.#panel.clear();this.#appliedAt.clear();@@ -407,6 +479,30 @@ export class ActionImpl {accounts.map((account) => this.#ingestLocalLogin(account).catch(() => false)),);if (ingested.some(Boolean)) await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);+ // Record which logins this machine holds, so a per-device account choice+ // can only name one it can run (and a signed-out one stops counting).+ const deviceId = await getElectronStoreState().resolveGatewayDeviceId();+ if (deviceId) {+ const synced = await agentQuotaService+ .syncDeviceLogins(+ deviceId,+ 'claude-code',+ accounts.flatMap((account) => account.identity.externalAccountId ?? []),+ )+ .then(() => true)+ .catch((error) => {+ console.error('[agentQuota:syncDeviceLogins]', error);+ return false;+ });+ // A login gone from this machine takes the picks made on it along, so+ // re-read the picks already on screen for this device.+ if (synced)+ await Promise.all(+ Object.keys(this.#get().quotaDeviceAccountMap)+ .filter((key) => parseQuotaDeviceAccountKey(key).deviceId === deviceId)+ .map((key) => this.#refresh(this.#deviceAccount, key)),+ );+ }return accounts;};@@ -504,7 +600,7 @@ export class ActionImpl {fetch: (params: string, options?: ReadOptions) => Promise<{ applied: boolean; data: T }>;},key: string,- field: 'quotaAccountsMap' | 'quotaBindingsMap' | 'quotaReadingsMap',+ field: 'quotaAccountsMap' | 'quotaBindingsMap' | 'quotaDeviceAccountMap' | 'quotaReadingsMap',{ fresh = false }: ReadOptions = {},retried = false,): Promise<T> => {diff --git a/src/store/agentQuota/agentQuota.deviceAccount.test.ts b/src/store/agentQuota/agentQuota.deviceAccount.test.tsnew file mode 100644index 00000000000..7958be85c70--- /dev/null+++ b/src/store/agentQuota/agentQuota.deviceAccount.test.ts@@ -0,0 +1,102 @@+/**+ * @vitest-environment happy-dom+ *+ * The per-device account choice: a login lives on one machine, so the Manual+ * pick is stored per device, and the desktop reports which logins it holds.+ */+import { randomUUID } from 'node:crypto';++import { act } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { agentQuotaService } from '@/services/agentQuota';+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { useElectronStore } from '@/store/electron';++import { agentQuotaSelectors, useAgentQuotaStore } from './index';+import { initialState } from './initialState';++beforeEach(() => {+ const scope = `quota-device-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ act(() => useAgentQuotaStore.setState(initialState, false));+ vi.spyOn(agentQuotaService, 'listBindings').mockResolvedValue([]);+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('per-device account choice', () => {+ it('saves a pick for one device and re-reads it with the bindings it moved', async () => {+ const getDeviceAccount = vi+ .spyOn(agentQuotaService, 'getDeviceAccount')+ .mockResolvedValueOnce({ accountId: null })+ .mockResolvedValue({ accountId: 'acc-1' });+ const setDeviceAccount = vi+ .spyOn(agentQuotaService, 'setDeviceAccount')+ .mockResolvedValue(undefined as never);++ await act(() =>+ useAgentQuotaStore.getState().setQuotaDeviceAccount('agent-1', 'device-a', 'acc-1'),+ );++ expect(setDeviceAccount).toHaveBeenCalledWith('agent-1', 'device-a', 'acc-1');+ expect(getDeviceAccount).toHaveBeenLastCalledWith('agent-1', 'device-a');+ expect(agentQuotaService.listBindings).toHaveBeenCalledWith('agent-1');+ expect(+ agentQuotaSelectors.deviceAccount('agent-1', 'device-a')(useAgentQuotaStore.getState()),+ ).toEqual({ accountId: 'acc-1' });+ expect(+ agentQuotaSelectors.deviceAccount('agent-1', 'device-b')(useAgentQuotaStore.getState()),+ ).toBeUndefined();+ });++ it('reports every local login for this desktop after listing them', async () => {+ vi.spyOn(heterogeneousAgentService, 'listClaudeCodeAccounts').mockResolvedValue([+ { configDir: null, identity: { externalAccountId: 'ext-default' } },+ { configDir: '/profiles/two', identity: { externalAccountId: 'ext-2' } },+ ] as never);+ vi.spyOn(heterogeneousAgentService, 'getClaudeCodeQuota').mockResolvedValue(null as never);+ vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([]);+ vi.spyOn(agentQuotaService, 'ingestClaudeSnapshot').mockResolvedValue({} as never);+ vi.spyOn(useElectronStore.getState(), 'resolveGatewayDeviceId').mockResolvedValue('device-a');+ const syncDeviceLogins = vi+ .spyOn(agentQuotaService, 'syncDeviceLogins')+ .mockResolvedValue(undefined as never);++ await useAgentQuotaStore.getState().refreshClaudeLocalAccounts();++ expect(syncDeviceLogins).toHaveBeenCalledWith('device-a', 'claude-code', [+ 'ext-default',+ 'ext-2',+ ]);+ });++ // Regression: signing out removed the pick on the server, but the manager+ // opened right after still showed it until it was reopened.+ it('re-reads the picks on screen for this desktop once its logins are reported', async () => {+ vi.spyOn(heterogeneousAgentService, 'listClaudeCodeAccounts').mockResolvedValue([]);+ vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([]);+ vi.spyOn(useElectronStore.getState(), 'resolveGatewayDeviceId').mockResolvedValue('device-a');+ vi.spyOn(agentQuotaService, 'syncDeviceLogins').mockResolvedValue(undefined as never);+ const getDeviceAccount = vi+ .spyOn(agentQuotaService, 'getDeviceAccount')+ .mockResolvedValueOnce({ accountId: 'acc-gone' })+ .mockResolvedValue({ accountId: null });++ await useAgentQuotaStore.getState().readQuotaDeviceAccount('agent-1', 'device-a');+ expect(+ agentQuotaSelectors.deviceAccount('agent-1', 'device-a')(useAgentQuotaStore.getState()),+ ).toEqual({ accountId: 'acc-gone' });++ await useAgentQuotaStore.getState().refreshClaudeLocalAccounts();++ expect(getDeviceAccount).toHaveBeenCalledTimes(2);+ expect(+ agentQuotaSelectors.deviceAccount('agent-1', 'device-a')(useAgentQuotaStore.getState()),+ ).toEqual({ accountId: null });+ });+});diff --git a/src/store/agentQuota/initialState.ts b/src/store/agentQuota/initialState.tsindex 6e0e3dca85d..cd406f9a3df 100644--- a/src/store/agentQuota/initialState.ts+++ b/src/store/agentQuota/initialState.ts@@ -5,6 +5,7 @@ import { createReplicaState, type ReplicaState } from '@/libs/replica';import type {QuotaAccount,QuotaBinding,+ QuotaDeviceAccount,QuotaHistory,QuotaLatestReading,QuotaPanelSnapshot,@@ -33,6 +34,10 @@ export interface State {* the matching flag is set.*/quotaConfirmed: Record<string, true>;+ /** Replica view of each agent's account choice per device, keyed `quotaDeviceAccountKey`. */+ quotaDeviceAccountMap: Record<string, QuotaDeviceAccount>;+ /** Replica bookkeeping of `quotaDeviceAccountMap`. */+ quotaDeviceAccountReplica: ReplicaState<QuotaDeviceAccount>;/** Replica view of each account's calendar history, keyed by account id. */quotaHistoryMap: Record<string, QuotaHistory>;/** Replica bookkeeping of `quotaHistoryMap`. */@@ -55,6 +60,8 @@ export const initialState: State = {quotaBindingsMap: {},quotaBindingsReplica: createReplicaState(),quotaConfirmed: {},+ quotaDeviceAccountMap: {},+ quotaDeviceAccountReplica: createReplicaState(),quotaHistoryMap: {},quotaHistoryReplica: createReplicaState(),quotaPanelMap: {},diff --git a/src/store/agentQuota/projection.ts b/src/store/agentQuota/projection.tsindex 42ef76f19e0..93ef2f145bc 100644--- a/src/store/agentQuota/projection.ts+++ b/src/store/agentQuota/projection.ts@@ -1,4 +1,5 @@import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';+import type { QuotaDeviceAccount } from '@lobechat/types';import { defineReplica } from '@/libs/replica';import type { agentQuotaService } from '@/services/agentQuota';@@ -62,6 +63,31 @@ export const quotaBindingsResource = defineReplica<string, QuotaBinding[]>({version: 1,});+export type { QuotaDeviceAccount } from '@lobechat/types';++/** Replica key of one agent's account choice on one device (gateway id). */+export const quotaDeviceAccountKey = (agentId: string, deviceId: string) =>+ `${agentId}|${deviceId}`;++/** Inverse of `quotaDeviceAccountKey`; agent ids never contain `|`. */+export const parseQuotaDeviceAccountKey = (key: string) => {+ const index = key.indexOf('|');+ return { agentId: key.slice(0, index), deviceId: key.slice(index + 1) };+};++/**+ * One agent's account choice on one device, keyed `quotaDeviceAccountKey`. A+ * login lives on one machine, so the Manual pick is made per device; a device+ * without one falls back to the legacy agent-wide pin, then Auto.+ */+export const quotaDeviceAccountResource = defineReplica<string, QuotaDeviceAccount>({+ key: (key) => key,+ name: 'agentQuotaDeviceAccount',+ persist: { maxEntries: 50 },+ storage: 'indexedDB',+ version: 1,+});+/** The newest reading per limit bucket of one account, keyed by account id. */export const quotaReadingsResource = defineReplica<string, QuotaLatestReading[]>({key: (accountId) => accountId,diff --git a/src/store/agentQuota/selectors.ts b/src/store/agentQuota/selectors.tsindex 68920aec640..868e94bb30d 100644--- a/src/store/agentQuota/selectors.ts+++ b/src/store/agentQuota/selectors.ts@@ -1,11 +1,16 @@import { quotaConfirmedKey, type Store } from './action';-import { hashQuotaSourceKey, QUOTA_ACCOUNTS_KEY } from './projection';+import { hashQuotaSourceKey, QUOTA_ACCOUNTS_KEY, quotaDeviceAccountKey } from './projection';const accounts = (s: Store) => s.quotaAccountsMap[QUOTA_ACCOUNTS_KEY];const bindings = (agentId?: string | null) => (s: Store) =>agentId ? s.quotaBindingsMap[agentId] : undefined;+const deviceAccount = (agentId?: string | null, deviceId?: string | null) => (s: Store) =>+ agentId && deviceId+ ? s.quotaDeviceAccountMap[quotaDeviceAccountKey(agentId, deviceId)]+ : undefined;+const readings = (accountId?: string | null) => (s: Store) =>accountId ? s.quotaReadingsMap[accountId] : undefined;@@ -22,6 +27,15 @@ const isAccountsConfirmed = (scope: string) => (s: Store) =>const isBindingsConfirmed = (scope: string, agentId?: string | null) => (s: Store) =>!!agentId && !!s.quotaConfirmed[quotaConfirmedKey(scope, 'bindings', agentId)];+/** The server answered for one agent's account choice on one device in `scope` during this session. */+const isDeviceAccountConfirmed =+ (scope: string, agentId?: string | null, deviceId?: string | null) => (s: Store) =>+ !!agentId &&+ !!deviceId &&+ !!s.quotaConfirmed[+ quotaConfirmedKey(scope, 'deviceAccount', quotaDeviceAccountKey(agentId, deviceId))+ ];+/** The server answered for one account's calendar history in `scope` during this session. */const isHistoryConfirmed = (scope: string, accountId?: string | null) => (s: Store) =>!!accountId && !!s.quotaConfirmed[quotaConfirmedKey(scope, 'history', accountId)];@@ -29,9 +43,11 @@ const isHistoryConfirmed = (scope: string, accountId?: string | null) => (s: Stoexport const agentQuotaSelectors = {accounts,bindings,+ deviceAccount,history,isAccountsConfirmed,isBindingsConfirmed,+ isDeviceAccountConfirmed,isHistoryConfirmed,panel,readings,diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.tsindex da7968b699f..aabef0ee56e 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts@@ -7,11 +7,16 @@ const listAccounts = vi.hoisted(() => vi.fn());const listClaudeCodeAccounts = vi.hoisted(() => vi.fn());const resolveClaudeCodeAccount = vi.hoisted(() => vi.fn());const getClaudeCodeInheritedRoutingEnv = vi.hoisted(() => vi.fn());+const resolveGatewayDeviceId = vi.hoisted(() => vi.fn());vi.mock('@/services/agentQuota', () => ({agentQuotaService: { listAccounts, selectAccountForAgent },}));+vi.mock('@/store/electron', () => ({+ getElectronStoreState: () => ({ resolveGatewayDeviceId }),+}));+vi.mock('@/services/electron/heterogeneousAgent', () => ({heterogeneousAgentService: {getClaudeCodeInheritedRoutingEnv,@@ -42,6 +47,7 @@ beforeEach(() => {.mockResolvedValue([localAccount('ext-default', null), localAccount('ext-1', '/profiles/one')]);resolveClaudeCodeAccount.mockReset();getClaudeCodeInheritedRoutingEnv.mockReset().mockResolvedValue({});+ resolveGatewayDeviceId.mockReset().mockResolvedValue(undefined);});describe('resolveQuotaAccountSpawnPlan', () => {@@ -79,6 +85,63 @@ describe('resolveQuotaAccountSpawnPlan', () => {await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).rejects.toThrow('[email protected]');});+ it('asks for the account chosen on this device', async () => {+ resolveGatewayDeviceId.mockResolvedValue('device-b');+ selectAccountForAgent.mockResolvedValue(selection({ pinScope: 'device' }));+ resolveClaudeCodeAccount.mockResolvedValue({ configDir: '/profiles/one', kind: 'profile' });++ await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');++ expect(selectAccountForAgent).toHaveBeenCalledWith('agt-1', {+ deviceId: 'device-b',+ provider: 'claude-code',+ });+ });++ it("fails this device's own pick when its login is gone instead of running another", async () => {+ resolveGatewayDeviceId.mockResolvedValue('device-b');+ selectAccountForAgent.mockResolvedValue(+ selection({ externalAccountId: 'ext-elsewhere', pinScope: 'device' }),+ );+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });+ listAccounts.mockResolvedValue([{ email: '[email protected]', id: 'acc-1', label: null }]);++ await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).rejects.toThrow('[email protected]');+ expect(listClaudeCodeAccounts).not.toHaveBeenCalled();+ });++ // Regression: an account pinned on device A made every run of the agent on+ // device B fail with "not signed in on this device".+ it('re-balances an agent-wide pin made on another device onto the logins here', async () => {+ resolveGatewayDeviceId.mockResolvedValue('device-b');+ selectAccountForAgent+ .mockResolvedValueOnce(selection({ externalAccountId: 'ext-a', pinScope: 'agent' }))+ .mockResolvedValueOnce(+ selection({ accountId: 'acc-2', externalAccountId: 'ext-1', reason: 'balanced' }),+ );+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });++ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');++ expect(selectAccountForAgent).toHaveBeenLastCalledWith('agt-1', {+ deviceId: 'device-b',+ provider: 'claude-code',+ runnableExternalAccountIds: ['ext-default', 'ext-1'],+ });+ expect(plan).toMatchObject({ accountId: 'acc-2', env: { CLAUDE_CONFIG_DIR: '/profiles/one' } });+ });++ it('runs on the default login when a pin from another device leaves nothing runnable here', async () => {+ selectAccountForAgent+ .mockResolvedValueOnce(selection({ externalAccountId: 'ext-a', pinScope: 'agent' }))+ .mockResolvedValueOnce(null);+ resolveClaudeCodeAccount.mockResolvedValue({ kind: 'missing' });++ await expect(resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).resolves.toEqual({+ env: {},+ });+ });+it('re-balances Auto mode onto the accounts signed in here', async () => {selectAccountForAgent.mockResolvedValueOnce(selection({ externalAccountId: 'ext-away', reason: 'balanced' }))diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.tsindex 1180e765703..cd3bab4023b 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts@@ -6,6 +6,7 @@ import { t } from 'i18next';import { agentQuotaService } from '@/services/agentQuota';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { getElectronStoreState } from '@/store/electron';export interface QuotaAccountSpawnPlan {/** Account chosen for this run, when routing applied. */@@ -56,15 +57,17 @@ const inheritedEnvRoutesExternally = async (agentEnv?: Record<string, string>) =/*** Resolve which provider account this agent should run on and turn the choice- * into spawn env. Account rows are shared across devices, but a login is not:- * the desktop maps the chosen account to the login it holds on THIS machine —+ * into spawn env. Account rows are shared across devices, but a login is not,+ * so the choice is asked for THIS device (its own Manual pick wins) and the+ * desktop maps it to the login it holds here —** - the default login → no override;* - the account's own profile → `CLAUDE_CONFIG_DIR=<profile>`;- * - no local login → the run fails with a clear reason, never falls back to an- * unselected login: a pinned account names the missing login, and Auto mode- * re-selects among the accounts this device can run, failing when the- * rotation holds none of them.+ * - no local login → never falls back to an unselected login: this device's+ * own pick names the missing login and fails the run; a legacy agent-wide+ * pin (picked on another machine) and Auto mode re-select among the+ * accounts this device can run; Auto fails when the rotation holds none,+ * the legacy pin then spawns on the default login like an unbound agent.** No bindings, or the quota service unreachable, → `{}` and the spawn behaves* as before; a desktop that fails to look up its logins fails the run. An env@@ -82,9 +85,12 @@ export const resolveQuotaAccountSpawnPlan = async (if (adapterType !== 'claude-code' || !agentId) return NO_ROUTING;if (claudeCodeAgentEnvPicksLogin(agentEnv)) return NO_ROUTING;+ // Without a device id (signed out of the gateway) only agent-wide choices apply.+ const deviceId = await getElectronStoreState().resolveGatewayDeviceId();const select = (runnableExternalAccountIds?: string[]) =>agentQuotaService.selectAccountForAgent(agentId, {+ ...(deviceId && { deviceId }),provider: adapterType,...(runnableExternalAccountIds && { runnableExternalAccountIds }),})@@ -97,10 +103,13 @@ export const resolveQuotaAccountSpawnPlan = async (let resolution = await resolveLocalLogin(selection);- // Auto picked an account this desktop has no login for: pick again among- // the ones it has. (Listing first on every run would cost unbound agents- // a Keychain read per profile for nothing.)- if (resolution?.kind === 'missing' && selection.reason === 'balanced') {+ // Auto, or a pin made on another machine, picked an account this desktop has+ // no login for: pick again among the ones it has. (Listing first on every+ // run would cost unbound agents a Keychain read per profile for nothing.)+ // Only a legacy agent-wide pin is re-picked; this device's own pin (or one+ // from a server that predates per-device picks) stays strict.+ const strictPin = selection.reason === 'pinned' && selection.pinScope !== 'agent';+ if (resolution?.kind === 'missing' && !strictPin) {// The selected login is known to be absent here, so a failed listing must// stop the run — falling back would start it on a login nobody selected.const local = await heterogeneousAgentService.listClaudeCodeAccounts().catch((error) => {@@ -112,6 +121,10 @@ export const resolveQuotaAccountSpawnPlan = async (const runnable = local.flatMap((account) => account.identity.externalAccountId ?? []);const rebalanced = await select(runnable);+ // A pin made on another machine is not a choice for this one: with nothing+ // in the rotation it can run, this device behaves as if it had no binding+ // and spawns on its default login.+ if (!rebalanced && selection.pinScope === 'agent') return NO_ROUTING;// The listing just read every login, so map the new pick from it rather// than scanning the logins again.const login = rebalanced@@ -135,7 +148,7 @@ export const resolveQuotaAccountSpawnPlan = async (if (resolution?.kind === 'profile')return { ...attribution, env: { CLAUDE_CONFIG_DIR: resolution.configDir } };- if (resolution?.kind === 'missing' && selection.reason === 'pinned') {+ if (resolution?.kind === 'missing') {const pinnedId = selection.accountId;const account = await agentQuotaService.listAccounts()diff --git a/src/store/electron/actions/__tests__/gateway.test.ts b/src/store/electron/actions/__tests__/gateway.test.tsindex 10cb48a08e4..3240c747b12 100644--- a/src/store/electron/actions/__tests__/gateway.test.ts+++ b/src/store/electron/actions/__tests__/gateway.test.ts@@ -1,8 +1,9 @@-import { act } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';import { useElectronStore } from '@/store/electron';+import { electronGatewaySelectors } from '@/store/electron/selectors';const service = vi.hoisted(() => ({getDeviceInfo: vi.fn(),@@ -125,3 +126,37 @@ describe('ElectronGatewayActionImpl', () => {expect(useElectronStore.getState().gatewayConnectionError).toBeUndefined();});});++describe('useFetchGatewayStableDeviceId', () => {+ it('holds this machine’s stable id in the replica and corrects a cached fallback id', async () => {+ useElectronStore.setState({+ gatewayDeviceInfo: { deviceId: 'fallback-uuid', hostname: 'mac', platform: 'darwin' },+ gatewayStableDeviceIdMap: {},+ });+ service.getStableDeviceId.mockResolvedValue('stable-1');++ renderHook(() => useElectronStore.getState().useFetchGatewayStableDeviceId());++ await waitFor(() =>+ expect(electronGatewaySelectors.gatewayStableDeviceId(useElectronStore.getState())).toBe(+ 'stable-1',+ ),+ );+ expect(useElectronStore.getState().gatewayDeviceInfo?.deviceId).toBe('stable-1');+ });++ it('records no device while signed out, and fetches nothing when disabled', async () => {+ useElectronStore.setState({ gatewayStableDeviceIdMap: {} });+ service.getStableDeviceId.mockResolvedValue(undefined);++ renderHook(() => useElectronStore.getState().useFetchGatewayStableDeviceId(false));+ expect(service.getStableDeviceId).not.toHaveBeenCalled();++ renderHook(() => useElectronStore.getState().useFetchGatewayStableDeviceId());+ await waitFor(() =>+ expect(electronGatewaySelectors.gatewayStableDeviceId(useElectronStore.getState())).toBe(+ null,+ ),+ );+ });+});diff --git a/src/store/electron/actions/gateway.ts b/src/store/electron/actions/gateway.tsindex a55a570f4e2..4d24162531b 100644--- a/src/store/electron/actions/gateway.ts+++ b/src/store/electron/actions/gateway.ts@@ -3,10 +3,16 @@ import type { GatewayConnectionState } from '@lobechat/electron-client-ipc';import { type SWRResponse } from 'swr';import useSWR from 'swr';+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';import { electronKeys } from '@/libs/swr/keys';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';import { type StoreSetter } from '@/store/types';+import {+ GATEWAY_STABLE_DEVICE_ID_KEY,+ type GatewayStableDeviceId,+ gatewayStableDeviceIdResource,+} from '../projection';import { type ElectronStore } from '../store';type Setter = StoreSetter<ElectronStore>;@@ -22,11 +28,22 @@ export interface GatewayDeviceInfo {export class ElectronGatewayActionImpl {readonly #get: () => ElectronStore;readonly #set: Setter;+ readonly #stableDeviceId;constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {void _api;this.#get = get;this.#set = set;+ this.#stableDeviceId = createReplicaSlice(gatewayStableDeviceIdResource, {+ actionPrefix: 'gatewayStableDeviceId',+ fetcher: async (): Promise<GatewayStableDeviceId> => ({+ deviceId: (await this.resolveGatewayDeviceId()) ?? null,+ }),+ get,+ set,+ stateKey: 'gatewayStableDeviceIdReplica',+ view: recordLens<ElectronStore, GatewayStableDeviceId>('gatewayStableDeviceIdMap'),+ });}connectGateway = async (): Promise<void> => {@@ -87,6 +104,15 @@ export class ElectronGatewayActionImpl {}};+ /**+ * Keep this machine's stable device id in sync for a mounted view that must+ * not act before it is known. Data comes from+ * `electronSelectors.gatewayStableDeviceId`; resolving also corrects a cached+ * fallback id in `gatewayDeviceInfo`.+ */+ useFetchGatewayStableDeviceId = (enabled = true): ReplicaSyncResult =>+ this.#stableDeviceId.useSync(isDesktop && enabled ? GATEWAY_STABLE_DEVICE_ID_KEY : null);+useFetchGatewayDeviceInfo = (): SWRResponse<GatewayDeviceInfo> => {return useSWR<GatewayDeviceInfo>(// Desktop-only IPC: on web there is no electronAPI, so never fetch off-desktop.diff --git a/src/store/electron/initialState.ts b/src/store/electron/initialState.tsindex dc789045afb..f1c67badf4c 100644--- a/src/store/electron/initialState.ts+++ b/src/store/electron/initialState.ts@@ -6,6 +6,8 @@ import {type NetworkProxySettings,} from '@lobechat/electron-client-ipc';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type CurrentRouteMetaState } from './actions/currentRouteMeta';import { currentRouteMetaInitialState } from './actions/currentRouteMeta';import { type GatewayDeviceInfo } from './actions/gateway';@@ -13,6 +15,7 @@ import { type RecentPagesState } from './actions/recentPages';import { recentPagesInitialState } from './actions/recentPages';import { type TabPagesState } from './actions/tabPages';import { tabPagesInitialState } from './actions/tabPages';+import { type GatewayStableDeviceId } from './projection';export type RemoteServerError = 'CONFIG_ERROR' | 'AUTH_ERROR' | 'DISCONNECT_ERROR';@@ -34,6 +37,10 @@ export interface ElectronState extends CurrentRouteMetaState, RecentPagesState,gatewayConnectionError?: GatewayConnectionError;gatewayConnectionStatus: GatewayConnectionStatus;gatewayDeviceInfo?: GatewayDeviceInfo;+ /** Replica view of this desktop's stable gateway device id (`GATEWAY_STABLE_DEVICE_ID_KEY`). */+ gatewayStableDeviceIdMap: Record<string, GatewayStableDeviceId>;+ /** Replica bookkeeping of `gatewayStableDeviceIdMap`. */+ gatewayStableDeviceIdReplica: ReplicaState<GatewayStableDeviceId>;isAppStateInit?: boolean;isConnectingServer?: boolean;isConnectionDrawerOpen?: boolean;@@ -53,6 +60,8 @@ export const initialState: ElectronState = {dataSyncConfig: { storageMode: 'cloud' },desktopHotkeys: {},gatewayConnectionStatus: 'disconnected',+ gatewayStableDeviceIdMap: {},+ gatewayStableDeviceIdReplica: createReplicaState(),isAppStateInit: false,isConnectingServer: false,isConnectionDrawerOpen: false,diff --git a/src/store/electron/projection.ts b/src/store/electron/projection.tsnew file mode 100644index 00000000000..ea2aa2c7aa7--- /dev/null+++ b/src/store/electron/projection.ts@@ -0,0 +1,22 @@+import { defineReplica } from '@/libs/replica';++/** This machine has one stable gateway device id, so the replica has one entry. */+export const GATEWAY_STABLE_DEVICE_ID_KEY = 'self';++/** `deviceId: null` = the desktop could not resolve one (signed out of the gateway). */+export interface GatewayStableDeviceId {+ deviceId: string | null;+}++/**+ * This desktop's stable gateway device id. Unlike `gatewayDeviceInfo`, which+ * holds the install's fallback UUID until the gateway connects, this is the+ * user-scoped id the server keys devices by. It paints from local storage on a+ * reload and is re-derived over IPC behind it.+ */+export const gatewayStableDeviceIdResource = defineReplica<string, GatewayStableDeviceId>({+ key: (key) => key,+ name: 'electronGatewayStableDeviceId',+ storage: 'localStorage',+ version: 1,+});diff --git a/src/store/electron/selectors/gateway.ts b/src/store/electron/selectors/gateway.tsnew file mode 100644index 00000000000..f80b06541c6--- /dev/null+++ b/src/store/electron/selectors/gateway.ts@@ -0,0 +1,11 @@+import { type ElectronState } from '@/store/electron/initialState';++import { GATEWAY_STABLE_DEVICE_ID_KEY } from '../projection';++/** This desktop's stable gateway device id; `undefined` until resolved, `null` = none. */+const gatewayStableDeviceId = (s: ElectronState) =>+ s.gatewayStableDeviceIdMap[GATEWAY_STABLE_DEVICE_ID_KEY]?.deviceId;++export const electronGatewaySelectors = {+ gatewayStableDeviceId,+};diff --git a/src/store/electron/selectors/index.ts b/src/store/electron/selectors/index.tsindex f3eeeaa10fa..638b22f808c 100644--- a/src/store/electron/selectors/index.ts+++ b/src/store/electron/selectors/index.ts@@ -1,3 +1,4 @@export * from './desktopState';+export * from './gateway';export * from './hotkey';export * from './sync';