π€― 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(quota): resolve device id server-side and drop expired windows (#17819)
Arvin Xuddf76f409e04
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.tsnew file mode 100644index 00000000000..2f755e4bf32--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.ingestSnapshot.test.ts@@ -0,0 +1,129 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++// serverDatabase middleware calls getServerDB(); stub it (the model mocks+// ignore the db handle anyway).+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),+}));++const mockFindByDeviceId = vi.fn();+const mockFindWorkspaceDeviceById = vi.fn();+const mockIngestSnapshot = vi.fn(async () => ({ ok: true }));++vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn(() => ({+ findByDeviceId: mockFindByDeviceId,+ findWorkspaceDeviceById: mockFindWorkspaceDeviceById,+ })),+}));++vi.mock('@/database/models/agentQuota', () => ({+ AgentAccountBindingModel: vi.fn(() => ({})),+ AgentProviderAccountModel: vi.fn(() => ({})),+ AgentQuotaWindowModel: vi.fn(() => ({})),+}));++vi.mock('@/server/services/agentQuota', () => ({+ AgentQuotaService: vi.fn(() => ({ ingestSnapshot: mockIngestSnapshot })),+}));++const { agentQuotaRouter } = await import('../agentQuota');++const createCaller = (workspaceId?: string) =>+ agentQuotaRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId } as any);++const READINGS = [+ {+ capturedAt: 1_700_000_000_000,+ limitType: 'session',+ resetsAt: null,+ scopeKey: '',+ utilization: 5,+ },+];++const ingest = (deviceId?: string, workspaceId?: string) =>+ createCaller(workspaceId).ingestSnapshot({+ deviceId,+ identity: { externalAccountId: 'ext-1' },+ provider: 'claude-code',+ readings: READINGS,+ });++describe('agentQuota.ingestSnapshot device resolution', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('resolves the gateway device id to the devices row uuid', async () => {+ // Clients only know the gateway id stored in `agencyConfig.boundDeviceId`;+ // snapshots reference `devices.id`. Passing the gateway id straight through+ // fails the uuid/foreign-key check and takes the whole ingest down.+ mockFindByDeviceId.mockResolvedValue({ id: '7b9a6767-9d4c-4924-86ff-135be4b2101a' });++ await ingest('agent-testing-quota-device');++ expect(mockFindByDeviceId).toHaveBeenCalledWith('agent-testing-quota-device');+ expect(mockIngestSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: '7b9a6767-9d4c-4924-86ff-135be4b2101a' }),+ );+ });++ it('still persists the reading when the device cannot be resolved', async () => {+ mockFindByDeviceId.mockResolvedValue(undefined);++ await ingest('unknown-device');++ expect(mockIngestSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: undefined, readings: READINGS }),+ );+ });++ it('skips the device lookup entirely for a local (deviceless) sample', async () => {+ await ingest(undefined);++ expect(mockFindByDeviceId).not.toHaveBeenCalled();+ expect(mockIngestSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: undefined }),+ );+ });++ it('resolves a workspace device enrolled by another member', async () => {+ // A workspace device's identity is (workspaceId, deviceId); `userId` only+ // records the first enroller, so the personal lookup misses a machine any+ // other member enrolled and the snapshot would lose its attribution.+ mockFindWorkspaceDeviceById.mockResolvedValue({ id: 'ws-device-uuid' });+ mockFindByDeviceId.mockResolvedValue(undefined);++ await ingest('shared-build-server', 'ws-1');++ expect(mockFindWorkspaceDeviceById).toHaveBeenCalledWith('shared-build-server');+ expect(mockIngestSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'ws-device-uuid' }),+ );+ });++ it('falls back to the personal device when a workspace request names one', async () => {+ mockFindWorkspaceDeviceById.mockResolvedValue(undefined);+ mockFindByDeviceId.mockResolvedValue({ id: 'personal-device-uuid' });++ await ingest('my-laptop', 'ws-1');++ expect(mockIngestSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'personal-device-uuid' }),+ );+ });++ it('skips the workspace lookup outside a workspace context', async () => {+ mockFindByDeviceId.mockResolvedValue({ id: 'personal-device-uuid' });++ await ingest('my-laptop');++ expect(mockFindWorkspaceDeviceById).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex 42422c6410d..6f653f59b59 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -5,6 +5,7 @@ import {AgentProviderAccountModel,AgentQuotaWindowModel,} from '@/database/models/agentQuota';+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';@@ -53,15 +54,35 @@ export const agentQuotaRouter = router({readings: z.array(readingSchema),}),)- .mutation(async ({ ctx, input }) =>- ctx.quotaService.ingestSnapshot({+ .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;++ return ctx.quotaService.ingestSnapshot({credentialRef: { origin: 'keychain' },- deviceId: input.deviceId,+ deviceId: deviceRow?.id,identity: input.identity,provider: input.provider,readings: input.readings,- }),- ),+ });+ }),/*** One assistant turn's consumption (desktop client-mode runs report from thediff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsxindex a2570d2ea23..f056f70ee82 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx@@ -11,7 +11,12 @@ import { fetchClaudeCodeQuotaSnapshot } from '@/services/heteroAgentQuota';import QuotaAccountSwitcher from './QuotaAccountSwitcher';import type { FetchQuotaOptions, QuotaWindowItem } from './QuotaMenu';import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';-import { buildClaudeSnapshotFromWindows, isQuotaStale, newestSeenAt } from './quotaViewModel';+import {+ buildClaudeSnapshotFromWindows,+ hasRenderableWindow,+ isQuotaStale,+ newestSeenAt,+} from './quotaViewModel';/*** Hit the live Anthropic usage API when the newest persisted reading is this@@ -103,7 +108,8 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =isQuotaStale(account?.updatedAt, Date.now(), QUOTA_REFRESH_MS)) {if (account && windows.length > 0) {- options?.onInterim?.(buildClaudeSnapshotFromWindows(account, windows));+ const interim = buildClaudeSnapshotFromWindows(account, windows);+ if (hasRenderableWindow(interim)) options?.onInterim?.(interim);}live = await fetchClaudeCodeQuotaSnapshot({ deviceId, env, force }).catch(() => null);@@ -148,10 +154,15 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =// 3) Persisted view wins β it survives a failed live fetch. Otherwise fall// back to the live snapshot: identity may be unresolvable (no// oauthAccount.accountUuid in ~/.claude.json, while the quota itself comes- // from the keychain), or every reading may lack a usable reset and project- // to zero windows. Either way real readings beat an empty panel.- if (account && windows.length > 0) return buildClaudeSnapshotFromWindows(account, windows);- return live ?? unavailableSnapshot();+ // from the keychain), every reading may lack a usable reset and project to+ // zero windows, or every persisted window may have already reset (a device+ // offline since yesterday). Note the last case is invisible in the row+ // count β ask the built snapshot, not `windows.length`, or a live sample+ // that failed to persist loses to an empty panel.+ const persisted =+ account && windows.length > 0 ? buildClaudeSnapshotFromWindows(account, windows) : null;+ if (persisted && hasRenderableWindow(persisted)) return persisted;+ return live ?? persisted ?? unavailableSnapshot();},[deviceId, env, agentId],);diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsxindex 4499672798f..7bf49872f95 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx@@ -588,6 +588,31 @@ describe('ClaudeCodeQuotaMenu', () => {expect(await screen.findByText('heteroAgent.quota.noData')).toBeTruthy();});+ it('shows the live sample when every persisted window has already reset', async () => {+ // A device offline since yesterday leaves rows behind whose windows have+ // reset. The row count still looks like "we have data", so a live sample+ // that could not be persisted (identity without an external account id here)+ // must not lose to that empty persisted view.+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);+ mockQuotaService.getWindows.mockResolvedValue([+ {+ ...persistedSessionWindow(Date.now() - 24 * 60 * 60_000),+ lastUtilization: 100,+ peakUtilization: 100,+ resetsAt: new Date(Date.now() - 60 * 60_000),+ },+ ]);+ mockService.getClaudeCodeQuota.mockResolvedValue(+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 } }),+ );++ render(<ClaudeCodeQuotaMenu />);++ // 96% left from the live sample β not the expired row's 0%, and not empty.+ expect(await screen.findByText('96%')).toBeTruthy();+ expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();+ });+it('renders persisted windows without a live call while the newest reading is fresh', async () => {mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 60_000)]);diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.tsindex f9b6ece2d85..0be8aaf8e66 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts@@ -5,6 +5,9 @@ import { buildClaudeSnapshotFromWindows, isQuotaStale } from './quotaViewModel';const reset = new Date('2026-07-21T14:00:00Z');const sessionReset = new Date('2026-07-18T20:50:00Z');+// Fixed "now" inside both windows, so the fixtures stay live regardless of the+// wall clock the suite runs on (an expired window is intentionally dropped).+const now = new Date('2026-07-18T08:05:00Z').getTime();const account = {displayName: 'Arvin',@@ -47,7 +50,7 @@ const windows: QuotaWindowRow[] = [describe('buildClaudeSnapshotFromWindows', () => {it('maps DB windows to the panel snapshot (session / weekly / Fable scoped)', () => {- const snap = buildClaudeSnapshotFromWindows(account, windows);+ const snap = buildClaudeSnapshotFromWindows(account, windows, now);expect(snap.status).toBe('ok');expect(snap.session).toEqual({resetsAt: sessionReset.getTime(),@@ -65,8 +68,39 @@ describe('buildClaudeSnapshotFromWindows', () => {});});+ it('drops windows whose reset already passed instead of showing them as spent', () => {+ // A device that has been offline since yesterday leaves windows recorded at+ // 100% utilization whose reset has since elapsed. Rendering those paints an+ // exhausted "0% left" badge over a quota that actually refilled.+ const afterReset = reset.getTime() + 60_000;+ const snap = buildClaudeSnapshotFromWindows(account, windows, afterReset);++ expect(snap.session).toBeNull();+ expect(snap.weekly).toBeNull();+ expect(snap.scopedWeekly).toBeNull();+ });++ it('keeps a window with no recorded reset time', () => {+ const snap = buildClaudeSnapshotFromWindows(+ account,+ [+ {+ lastUtilization: 30,+ limitType: 'session',+ peakUtilization: 30,+ resetsAt: null,+ scopeKey: '',+ windowSeconds: 18_000,+ },+ ],+ Date.parse('2030-01-01T00:00:00Z'),+ );++ expect(snap.session?.usedPercent).toBe(30);+ });+it('carries the account identity for the switcher', () => {- const snap = buildClaudeSnapshotFromWindows(account, windows);+ const snap = buildClaudeSnapshotFromWindows(account, windows, now);expect(snap.identity).toMatchObject({email: '[email protected]',externalAccountId: '48bfd5c6',@@ -75,31 +109,39 @@ describe('buildClaudeSnapshotFromWindows', () => {});it('prefers lastUtilization over peak and clamps to 0..100', () => {- const snap = buildClaudeSnapshotFromWindows(account, [- {- lastUtilization: null,- limitType: 'session',- peakUtilization: 150,- resetsAt: reset,- scopeKey: '',- windowSeconds: 18_000,- },- ]);+ const snap = buildClaudeSnapshotFromWindows(+ account,+ [+ {+ lastUtilization: null,+ limitType: 'session',+ peakUtilization: 150,+ resetsAt: reset,+ scopeKey: '',+ windowSeconds: 18_000,+ },+ ],+ now,+ );expect(snap.session?.usedPercent).toBe(100); // clamped; falls back to peak});it('tolerates string dates and missing windows', () => {- const snap = buildClaudeSnapshotFromWindows(account, [- {- lastSeenAt: '2026-07-18T08:00:00Z',- lastUtilization: 20,- limitType: 'session',- peakUtilization: 20,- resetsAt: '2026-07-18T20:50:00Z',- scopeKey: '',- windowSeconds: 18_000,- },- ]);+ const snap = buildClaudeSnapshotFromWindows(+ account,+ [+ {+ lastSeenAt: '2026-07-18T08:00:00Z',+ lastUtilization: 20,+ limitType: 'session',+ peakUtilization: 20,+ resetsAt: '2026-07-18T20:50:00Z',+ scopeKey: '',+ windowSeconds: 18_000,+ },+ ],+ now,+ );expect(snap.session?.usedPercent).toBe(20);expect(snap.session?.resetsAt).toBe(Date.parse('2026-07-18T20:50:00Z'));expect(snap.weekly).toBeNull();@@ -127,6 +169,7 @@ describe('isQuotaStale', () => {const snap = buildClaudeSnapshotFromWindows({ ...account, updatedAt: new Date('2026-07-18T08:50:00Z') },deviceClockAhead,+ now,);expect(snap.updatedAt).toBe(Date.parse('2026-07-18T08:50:00Z'));diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.tsindex 7fa96c2696d..b3b6cde1ba3 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts@@ -35,12 +35,19 @@ const toMs = (v: Date | string | null | undefined): number | null => {return Number.isNaN(ms) ? null : ms;};-const toWindow = (row: QuotaWindowRow | undefined): HeteroQuotaWindow | null => {+const toWindow = (row: QuotaWindowRow | undefined, now: number): HeteroQuotaWindow | null => {if (!row) return null;+ // A window whose reset has already passed says nothing about current usage β+ // the quota refilled at `resetsAt`. Showing its last utilization paints a+ // spent window as if it were live (an exhausted 0%-left badge on a fresh+ // quota), so drop it and let the caller fall back to a live sample.+ const resetsAt = toMs(row.resetsAt);+ if (resetsAt !== null && resetsAt <= now) return null;+// Displayed "used" is the latest reading; peak is the monotonic ceiling fallback.const usedPercent = Math.max(0, Math.min(100, row.lastUtilization ?? row.peakUtilization ?? 0));return {- resetsAt: toMs(row.resetsAt),+ resetsAt,usedPercent,windowMinutes: Math.round((row.windowSeconds ?? 0) / 60),};@@ -66,10 +73,12 @@ const identityOf = (account: QuotaAccountRow): ClaudeCodeAccountIdentity => ({export const buildClaudeSnapshotFromWindows = (account: QuotaAccountRow,windows: QuotaWindowRow[],+ now: number = Date.now(),): ClaudeCodeQuotaSnapshot => {const session = windows.find((w) => w.limitType === 'session');const weekly = windows.find(isWeeklyAll);const scoped = windows.find((w) => w.limitType === 'weekly_scoped' && !!w.scopeKey);+ const scopedWindow = toWindow(scoped, now);// Freshness is based on when our server received the snapshot, not on the// sampling device's wall clock. Device timestamps remain on the windows for@@ -81,11 +90,12 @@ export const buildClaudeSnapshotFromWindows = (error: null,identity: identityOf(account),provider: 'claude-code',- scopedWeekly: scoped ? { modelName: scoped.scopeKey, window: toWindow(scoped)! } : null,- session: toWindow(session),+ scopedWeekly:+ scoped && scopedWindow ? { modelName: scoped.scopeKey, window: scopedWindow } : null,+ session: toWindow(session, now),status: 'ok',- updatedAt: updatedAt || Date.now(),- weekly: toWindow(weekly),+ updatedAt: updatedAt || now,+ weekly: toWindow(weekly, now),};};@@ -98,6 +108,16 @@ export const buildClaudeSnapshotFromWindows = (export const newestSeenAt = (windows: QuotaWindowRow[]): number =>windows.reduce((max, w) => Math.max(max, toMs(w.lastSeenAt) ?? 0), 0);+/**+ * Whether a built snapshot carries at least one window worth rendering. Callers+ * cannot infer this from the persisted row count: every row may describe a+ * window that has already reset, which {@link buildClaudeSnapshotFromWindows}+ * drops. Treating a non-empty row array as "we have data" would discard a live+ * sample in favour of an empty panel.+ */+export const hasRenderableWindow = (snapshot: ClaudeCodeQuotaSnapshot): boolean =>+ !!snapshot.session || !!snapshot.weekly || !!snapshot.scopedWeekly;+/** Whether the server receipt time is older than `maxAgeMs`. */export const isQuotaStale = (receivedAt: Date | string | null | undefined,