π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent-quota): route spawns to the selected account + per-turn usage ledger (#17441)
Arvin Xub8a108eee018
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex bf63268af78..13da21a3a3a 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -1241,3 +1241,27 @@ active: true, remoteServerUrl: 'http://localhost:<port>', storageMode: 'selfHostrestart, and re-point the Electron app at the new server (see C17 step 3). Also check`lsof -iTCP:<port>` plus the listener's `ps` cwd before blaming your own code β a listener fromANOTHER repo checkout answering on "your" port produces confusing wrong-stack error traces.++### E41. β Electron main crashes with `electron.app undefined` β the agent harness leaks `ELECTRON_RUN_AS_NODE=1`++- **Situation**: `electron-dev.sh start` fails repeatedly; the instance log shows+ `TypeError: Cannot read properties of undefined (reading 'setName')` at `electron.app.setName(...)`+ with a plain `Node.js v24.x` banner, and the dev watcher then tears everything down. Rebuilding+ electron / reinstalling deps does not help; the same script worked in earlier sessions.+- **Cause (measured)**: the Claude Code agent session itself runs under Electron and its shell+ snapshot exports `ELECTRON_RUN_AS_NODE=1`. Every child inherits it, so the spawned Electron+ binary boots as PLAIN NODE β `require('electron')` returns a path string, `electron.app` is+ undefined. Whether a session carries the variable depends on how that session was started,+ which is why the symptom appears "randomly" across sessions.+- **Works**: strip it at the launch site: `env -u ELECTRON_RUN_AS_NODE .agents/acceptance/scripts/electron-dev.sh start <id>`.+ Check `env | grep ELECTRON` FIRST whenever an Electron dev boot dies before any window appears.+- **Also learned this run**:+ - Background holder tasks die when the agent session process cycles (context compaction spawns a+ new process and reaps the old task tree) β every "mystery SIGTERM" of Electron/dev-server today+ traced to session-lifetime, not to sibling sessions or a human. macOS has no `setsid(1)`;+ daemonize with python `os.fork()+os.setsid()` double-fork AND keep the leader alive, or accept+ the session-bound lifetime and re-start per session.+ - Running the full-stack web dev (`init-dev-env.sh dev`) and the desktop instance vite+ concurrently from ONE worktree makes both optimizers share `<root>/node_modules/.vite` β+ two cold optimizers clobber each other and dynamic imports 504 (`Outdated Optimize Dep`)+ indefinitely. Boot them sequentially (let one finish bundling before starting the other).diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 0b5086da546..9d9ce1a88b7 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -58,7 +58,10 @@ import { detectHeterogeneousCliCommand } from '@/modules/binaries';import { resolveCliScript } from '@/modules/cliEmbedding';import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';import { buildBrowserMcpTools } from '@/modules/heterogeneousAgent/browserMcpTools';-import { fetchClaudeCodeQuota } from '@/modules/heterogeneousAgent/claudeCodeQuota';+import {+ fetchClaudeCodeQuota,+ readClaudeCodeIdentity,+} from '@/modules/heterogeneousAgent/claudeCodeQuota';import {consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,fetchCodexQuota,@@ -1747,6 +1750,16 @@ export default class HeterogeneousAgentCtr extends ControllerModule {* comes from Anthropic's OAuth usage API using the local `claude` login,* and the request goes through the app's global proxy dispatcher.*/+ /**+ * Identity of the Claude login a spawn with this env would use. Pure local+ * file read (`.claude.json` of the resolved profile) β cheap enough to call+ * once per run for usageβaccount attribution; never touches the network.+ */+ @IpcMethod()+ async getClaudeCodeIdentity(params: { env?: Record<string, string> } = {}) {+ return readClaudeCodeIdentity({ env: params.env });+ }+@IpcMethod()async getClaudeCodeQuota(params: GetClaudeCodeQuotaParams = {},diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.tsindex 4fe799b7b68..1cf6e8942c2 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/claudeCodeQuota.ts@@ -289,6 +289,14 @@ const mapScopedWeekly = (payload: OAuthUsageResponse): ClaudeCodeScopedWeekly |* explicit profile dir's copy) carries `oauthAccount`; the credential blob* itself has no identity. Best-effort β quota still works without it.*/+/**+ * Identity of the login a spawn with this env would actually use β pure local+ * file read (no usage-API call), so it is safe to invoke once per run for+ * usageβaccount attribution.+ */+export const readClaudeCodeIdentity = async (options: FetchClaudeCodeQuotaOptions) =>+ readAccountIdentity(options);+const readAccountIdentity = async (options: FetchClaudeCodeQuotaOptions) => {const explicit = resolveExplicitConfigDir(options);const candidates = explicitdiff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex f747b060ec1..42422c6410d 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -63,6 +63,33 @@ export const agentQuotaRouter = router({}),),+ /**+ * One assistant turn's consumption (desktop client-mode runs report from the+ * renderer). Idempotent by message id β replays cannot double-count.+ */+ recordUsage: quotaProcedure+ .input(+ z.object({+ agentId: z.string().optional(),+ externalAccountId: z.string().optional(),+ messageId: z.string().optional(),+ model: z.string().optional(),+ occurredAt: z.number().optional(),+ operationId: z.string().optional(),+ provider: providerSchema,+ topicId: z.string().optional(),+ usage: z.object({+ cacheRead: z.number().optional(),+ cacheWrite1h: z.number().optional(),+ cacheWrite5m: z.number().optional(),+ input: z.number().optional(),+ output: z.number().optional(),+ reasoning: z.number().optional(),+ }),+ }),+ )+ .mutation(async ({ ctx, input }) => ctx.quotaService.recordUsage(input)),+// ββ accounts ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββcreateAccount: quotaProcedure.input(diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.tsindex 1f35a294664..a54ac872207 100644--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts@@ -111,3 +111,76 @@ describe('AgentQuotaService.ingestSnapshot', () => {expect(await calibrations.latest(account.id, 'session')).toBeNull();});});++describe('AgentQuotaService.recordUsage', () => {+ it('attributes the turn to the account and computes cost from model-bank rates', async () => {+ const account = await service.ingestSnapshot({+ identity,+ provider: 'claude-code',+ readings: [],+ });++ await service.recordUsage({+ externalAccountId: identity.externalAccountId,+ messageId: 'msg-1',+ model: 'claude-opus-4-8',+ occurredAt: Date.parse('2026-07-01T01:00:00Z'),+ provider: 'claude-code',+ usage: { cacheRead: 1_000_000, cacheWrite5m: 100_000, input: 10_000, output: 40_000 },+ });++ const from = new Date('2026-07-01T00:00:00Z');+ const to = new Date('2026-07-01T02:00:00Z');+ // opus 4.8: in $5, out $25, cacheRead $0.5, cacheWrite $6.25 per MTok β+ // 0.01*5 + 0.04*25 + 1*0.5 + 0.1*6.25 = 2.175+ expect(await ledger.sumCostUsd(account.id, from, to)).toBeCloseTo(2.175, 6);++ // replayed event (same message id) must not double-count+ await service.recordUsage({+ externalAccountId: identity.externalAccountId,+ messageId: 'msg-1',+ model: 'claude-opus-4-8',+ occurredAt: Date.parse('2026-07-01T01:00:00Z'),+ provider: 'claude-code',+ usage: { output: 40_000 },+ });+ expect(await ledger.sumCostUsd(account.id, from, to)).toBeCloseTo(2.175, 6);+ });++ it('stores tokens without a cost for a model the bank does not know', async () => {+ const account = await service.ingestSnapshot({+ identity,+ provider: 'claude-code',+ readings: [],+ });++ await service.recordUsage({+ externalAccountId: identity.externalAccountId,+ messageId: 'msg-unknown-model',+ model: 'claude-experimental-x',+ occurredAt: Date.parse('2026-07-01T01:00:00Z'),+ provider: 'claude-code',+ usage: { output: 40_000 },+ });++ // row exists (tokens kept) but contributes no fabricated cost+ expect(+ await ledger.sumCostUsd(+ account.id,+ new Date('2026-07-01T00:00:00Z'),+ new Date('2026-07-01T02:00:00Z'),+ ),+ ).toBe(0);+ });++ it('drops nothing when the account is unknown β row lands unattributed', async () => {+ await service.recordUsage({+ externalAccountId: 'never-seen-account',+ messageId: 'msg-orphan',+ model: 'claude-opus-4-8',+ provider: 'claude-code',+ usage: { output: 1000 },+ });+ // no throw = pass; the row is accountId-null and excluded from calibration+ });+});diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.tsindex 997bc7ccb69..bacd91ca949 100644--- a/apps/server/src/services/agentQuota/index.ts+++ b/apps/server/src/services/agentQuota/index.ts@@ -1,10 +1,12 @@import {type AccountLoad,calibrateCapacity,+ computeTurnCostUsd,MIN_CALIBRATION_SAMPLES,projectWindows,type QuotaAccountIdentity,type QuotaLimitReading,+ type QuotaTokenUsage,selectAccount,windowSecondsForKind,windowsToCalibrationIntervals,@@ -20,7 +22,13 @@ import {AgentQuotaWindowModel,} from '@/database/models/agentQuota';import type { LobeChatDatabase } from '@/database/type';-import { type QuotaAccountCredentialRef, QuotaBindingRole } from '@/database/types/agentQuota';+import {+ type QuotaAccountCredentialRef,+ QuotaBindingRole,+ QuotaCostSource,+} from '@/database/types/agentQuota';++import { claudeModelPrice } from './pricing';export interface AccountLoadView extends AccountLoad {capacityUsd?: number;@@ -173,6 +181,69 @@ export class AgentQuotaService {}};+ /**+ * Record one assistant turn's consumption in the usage ledger β the "our own+ * spend" half of the Ξutilization β Ξcost pair that calibration crosses.+ * Cost is computed here from token classes and the model bank's rates (cache+ * read/write price differently β that is why raw token counts are the wrong+ * unit); a model the bank doesn't know stores its tokens with a null cost+ * instead of a guessed one. Idempotent per `externalEventId` (message id), so+ * a replayed event cannot double-count.+ */+ recordUsage = async (params: {+ agentId?: string;+ /** Real provider account id resolved at spawn; attributes the row. */+ externalAccountId?: string;+ messageId?: string;+ model?: string;+ occurredAt?: number;+ operationId?: string;+ provider: string;+ topicId?: string;+ usage: QuotaTokenUsage;+ }): Promise<void> => {+ const externalEventId = params.messageId ?? params.operationId;+ if (!externalEventId) return;++ const account = params.externalAccountId+ ? await this.accounts.findByExternalId(params.provider, params.externalAccountId)+ : null;++ const price = params.model ? claudeModelPrice(params.model) : null;+ const costUsd = price ? computeTurnCostUsd(params.usage, price) : null;++ const row = {+ accountId: account?.id ?? null,+ cacheReadTokens: params.usage.cacheRead ?? null,+ cacheWriteTokens: params.usage.cacheWrite5m ?? params.usage.cacheWrite1h ?? null,+ costSource: costUsd == null ? null : QuotaCostSource.computed,+ costUsd,+ externalEventId,+ inputTokens: params.usage.input ?? null,+ model: params.model ?? null,+ occurredAt: new Date(params.occurredAt ?? Date.now()),+ outputTokens: params.usage.output ?? null,+ provider: params.provider,+ reasoningTokens: params.usage.reasoning ?? null,+ };++ try {+ await this.ledger.append({+ ...row,+ agentId: params.agentId ?? null,+ messageId: params.messageId ?? null,+ operationId: params.operationId ?? null,+ topicId: params.topicId ?? null,+ });+ } catch {+ // The provenance links are FK-checked and the client races the message+ // batcher (or the row may since be deleted). The spend record itself is+ // the valuable part β land it without the links (the message id survives+ // inside externalEventId) rather than silently losing the turn.+ await this.ledger.append(row);+ }+ };+/** Build the LB load view for a set of accounts from their latest readings. */resolveAccountLoads = async (accountIds: string[]): Promise<AccountLoadView[]> => {const accounts = await this.accounts.list();@@ -219,10 +290,39 @@ export class AgentQuotaService {* 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.+ *+ * 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+ * login for keychain) without a second round-trip.*/selectForAgent = async (agentId: string,options: { modelScope?: string; now?: number } = {},+ ): Promise<{+ accountId: string;+ credentialMode: string;+ credentialRef: QuotaAccountCredentialRef | null;+ externalAccountId: string | null;+ reason: 'pinned' | 'balanced';+ } | null> => {+ const chosen = await this.selectAccountId(agentId, options);+ if (!chosen) return null;++ const account = await this.accounts.findById(chosen.accountId);+ if (!account) return null;++ return {+ accountId: account.id,+ credentialMode: account.credentialMode,+ credentialRef: account.credentialRef ?? null,+ externalAccountId: account.externalAccountId ?? null,+ reason: chosen.reason,+ };+ };++ private selectAccountId = async (+ agentId: string,+ options: { modelScope?: string; now?: number },): Promise<{ accountId: string; reason: 'pinned' | 'balanced' } | null> => {const bindings = (await this.bindings.listByAgent(agentId)).filter((b) => b.enabled);const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);diff --git a/apps/server/src/services/agentQuota/pricing.ts b/apps/server/src/services/agentQuota/pricing.tsnew file mode 100644index 00000000000..2841f26edba--- /dev/null+++ b/apps/server/src/services/agentQuota/pricing.ts@@ -0,0 +1,32 @@+import type { QuotaModelPrice } from '@lobechat/heterogeneous-agents/quota';+import anthropicModels from 'model-bank/anthropic';++/**+ * $ per million tokens for a Claude model, from the model bank. The bank lists+ * the base input/output rates plus the cache-read and 5-minute cache-write+ * rates; the 1-hour write rate is derived inside `computeTurnCostUsd` (2x base+ * input) when not provided. Returns null for models the bank doesn't know β+ * the caller should then store the tokens without a computed cost rather than+ * guess a price.+ */+export const claudeModelPrice = (modelId: string): QuotaModelPrice | null => {+ const model = anthropicModels.find((m) => m.id === modelId);+ const units = model?.pricing?.units;+ if (!units) return null;++ const rate = (name: string) => {+ const unit = units.find((u) => u.name === name && u.unit === 'millionTokens');+ return unit && 'rate' in unit ? unit.rate : undefined;+ };++ const input = rate('textInput');+ const output = rate('textOutput');+ if (input === undefined || output === undefined) return null;++ return {+ cacheRead: rate('textInput_cacheRead'),+ cacheWrite5m: rate('textInput_cacheWrite'),+ input,+ output,+ };+};diff --git a/packages/database/src/models/agentQuota.ts b/packages/database/src/models/agentQuota.tsindex 3ae89334876..13f7be93671 100644--- a/packages/database/src/models/agentQuota.ts+++ b/packages/database/src/models/agentQuota.ts@@ -147,6 +147,21 @@ export class AgentProviderAccountModel {return row ? stripCredentials(row) : null;};+ /** Look up the row for a real provider account (usage β account attribution). */+ findByExternalId = async (+ provider: string,+ externalAccountId: string,+ ): Promise<SafeAccount | null> => {+ const row = await this.db.query.agentProviderAccounts.findFirst({+ where: and(+ this.mine(),+ eq(agentProviderAccounts.provider, provider),+ eq(agentProviderAccounts.externalAccountId, externalAccountId),+ ),+ });+ return row ? stripCredentials(row) : null;+ };+/** Decrypt the managed OAuth credential for spawn-time injection. */getCredentials = async (id: string): Promise<QuotaAccountCredentials | null> => {const row = await this.db.query.agentProviderAccounts.findFirst({diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 57e810fc67b..6019d737c9e 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -243,6 +243,25 @@ describe('ClaudeCodeAdapter', () => {);});+ it('classifies a profile with no login at all ("Not logged in Β· Please run /login") as auth_required', () => {+ // CC emits this phrasing when the resolved profile (e.g. an isolated+ // CLAUDE_CONFIG_DIR injected by account routing) has no credentials β+ // it must render the auth guide card, not the generic error card.+ const adapter = new ClaudeCodeAdapter();+ const rawError = 'Not logged in Β· Please run /login';++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({ is_error: true, result: rawError, type: 'result' });++ const errorEvent = events.at(-1)!;+ expect(errorEvent.type).toBe('error');+ expect(errorEvent.data).toMatchObject({+ agentType: 'claude-code',+ code: 'auth_required',+ stderr: rawError,+ });+ });+it('classifies overloaded failures from api_error_status 529 result events', () => {const adapter = new ClaudeCodeAdapter();const rawError =diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex b8bc375a17d..ec517bfdb76 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -198,6 +198,10 @@ const CLI_AUTH_REQUIRED_PATTERNS = [/invalid authentication credentials/i,/authentication[_ ]error/i,/not authenticated/i,+ // CC's phrasing when the resolved profile (e.g. an isolated CLAUDE_CONFIG_DIR)+ // simply has no login at all, as opposed to a rejected credential.+ /not logged in/i,+ /please run \/login/i,/\bunauthorized\b/i,/\b401\b/,] as const;diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsxindex a8e9aded148..bb8de1be95c 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx@@ -8,7 +8,7 @@ import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { agentQuotaService } from '@/services/agentQuota';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';-// import QuotaAccountSwitcher from './QuotaAccountSwitcher';+import QuotaAccountSwitcher from './QuotaAccountSwitcher';import type { FetchQuotaOptions, QuotaWindowItem } from './QuotaMenu';import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';import { buildClaudeSnapshotFromWindows, isQuotaStale } from './quotaViewModel';@@ -189,11 +189,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {getRefreshErrorText={getRefreshErrorText}getUnavailableText={getUnavailableText}getWindows={getWindows}- // Account switcher entry is intentionally off until `selectForAgent` is wired- // into the spawn path: switching today moves bindings without changing the- // credential the run actually uses. Re-enable together with that wiring by- // uncommenting this line and the QuotaAccountSwitcher import above.- // renderHeader={(quota) => <QuotaAccountSwitcher placement="top" snapshot={quota} />}+ renderHeader={(quota) => <QuotaAccountSwitcher placement="top" snapshot={quota} />}sourceKey={sourceKey}title={t('heteroAgent.claudeQuota.title')}tooltip={t('heteroAgent.claudeQuota.tooltip')}diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.tsindex 9301d66ee6f..760b3d0f1dc 100644--- a/src/services/agentQuota.ts+++ b/src/services/agentQuota.ts@@ -49,6 +49,25 @@ class AgentQuotaService {/** Who the load balancer would pick right now (Auto mode preview + reason). */selectAccountForAgent = async (agentId: string, modelScope?: string) =>lambdaClient.agentQuota.selectAccountForAgent.query({ agentId, modelScope });++ /** One assistant turn's consumption β usage ledger (idempotent by message id). */+ recordUsage = async (params: {+ agentId?: string;+ externalAccountId?: string;+ messageId?: string;+ model?: string;+ occurredAt?: number;+ operationId?: string;+ provider: 'claude-code' | 'codex';+ topicId?: string;+ usage: {+ cacheRead?: number;+ cacheWrite5m?: number;+ input?: number;+ output?: number;+ reasoning?: number;+ };+ }) => lambdaClient.agentQuota.recordUsage.mutate(params);}export const agentQuotaService = new AgentQuotaService();diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex a31ef793a49..03ca96838f4 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -87,6 +87,16 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.getClaudeCodeQuota(params);}+ /**+ * Identity of the Claude login a spawn with this env would use β a pure+ * local file read, safe to call once per run for usage attribution.+ */+ async getClaudeCodeIdentity(params?: {+ env?: Record<string, string>;+ }): Promise<ClaudeCodeQuotaSnapshot['identity']> {+ return this.ipc.heterogeneousAgent.getClaudeCodeIdentity(params);+ }+/*** Submit the user's answer (or cancellation) for a pending CC* AskUserQuestion intervention. The main process routes it to thediff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 8e5648273e0..36bc47d59f9 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -66,9 +66,11 @@ const mockStartSession = vi.fn();const mockSendPrompt = vi.fn();const mockStopSession = vi.fn();const mockGetSessionInfo = vi.fn();+const mockGetClaudeCodeIdentity = vi.fn(async (..._args: any[]) => null);vi.mock('@/services/electron/heterogeneousAgent', () => ({heterogeneousAgentService: {+ getClaudeCodeIdentity: (...args: any[]) => mockGetClaudeCodeIdentity(...args),getSessionInfo: (...args: any[]) => mockGetSessionInfo(...args),sendPrompt: (...args: any[]) => mockSendPrompt(...args),startSession: (...args: any[]) => mockStartSession(...args),@@ -76,6 +78,17 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({},}));+// agentQuotaService β account routing (pre-spawn) + usage ledger (per turn).+// Unmocked, both fire REAL trpc fetches from inside the executor.+const mockSelectAccountForAgent = vi.fn(async (..._args: any[]): Promise<unknown> => null);+const mockRecordQuotaUsage = vi.fn(async (..._args: any[]) => undefined);+vi.mock('@/services/agentQuota', () => ({+ agentQuotaService: {+ recordUsage: (...args: any[]) => mockRecordQuotaUsage(...args),+ selectAccountForAgent: (...args: any[]) => mockSelectAccountForAgent(...args),+ },+}));+// Gateway event handler β we spy on it but let it run (it calls getMessages)vi.mock('../transports/gateway/gatewayEventHandler', () => ({createGatewayEventHandler: vi.fn(() => vi.fn()),@@ -3913,6 +3926,57 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(threadAssistantIds.size).toBeGreaterThan(0);});+ // A CC Task/subagent burns the SAME subscription as its parent, so its+ // turns must reach the usage ledger too β only ledgering main-agent turns+ // understates the account and skews capacity calibration high.+ it('ledgers subagent turn usage via agentQuotaService.recordUsage', async () => {+ await runWithEvents([+ ccInit(),+ ccToolUse('msg_main', 'toolu_task', 'Task', { description: 'x', subagent_type: 'Plan' }),+ // subagent closing turn with real usage on message.usage (batch mode)+ {+ message: {+ content: [{ text: 'sub done', type: 'text' }],+ id: 'msg_sub_1',+ role: 'assistant',+ usage: { cache_read_input_tokens: 300, input_tokens: 40, output_tokens: 60 },+ },+ parent_tool_use_id: 'toolu_task',+ type: 'assistant',+ },+ ccResult(),+ ]);++ const subagentLedgerCall = mockRecordQuotaUsage.mock.calls.find(+ ([p]: any) => p.usage?.output === 60,+ );+ expect(subagentLedgerCall).toBeDefined();+ expect(subagentLedgerCall![0]).toMatchObject({+ provider: 'claude-code',+ usage: { cacheRead: 300, input: 40, output: 60 },+ });+ });++ it('ledgers main-agent turn usage via agentQuotaService.recordUsage', async () => {+ await runWithEvents([+ ccInit(),+ ccMessageStart('msg_01', 'claude-opus-4-6'),+ ccAssistant('msg_01', [{ text: 'Hello', type: 'text' }], { model: 'claude-opus-4-6' }),+ ccMessageDelta({ input_tokens: 100, output_tokens: 20 }),+ ccResult(),+ ]);++ const mainLedgerCall = mockRecordQuotaUsage.mock.calls.find(+ ([p]: any) => p.usage?.output === 20,+ );+ expect(mainLedgerCall).toBeDefined();+ expect(mainLedgerCall![0]).toMatchObject({+ model: 'claude-opus-4-6',+ provider: 'claude-code',+ usage: { input: 100, output: 20 },+ });+ });+it('does NOT create a Thread when topicId is missing (non-topic-scoped run)', async () => {await runWithEvents([diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex ac072374308..c3ac13fc235 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -50,6 +50,7 @@ import {removeHeteroSessionIdForWorkingDirectory,setHeteroSessionIdForWorkingDirectory,} from '@/helpers/heteroSessionByWorkingDirectory';+import { agentQuotaService } from '@/services/agentQuota';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import {type MessageBatchOperation,@@ -75,6 +76,7 @@ import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';+import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';import { buildResumeReplayMessages } from './resumeReplay';import { buildLobeHubSessionEnv } from './sessionEnv';@@ -576,6 +578,43 @@ export const executeHeterogeneousAgent = async (const adapterType = resolveAdapterType(heterogeneousProvider);+ // Which real provider account this run consumes, resolved once after spawn+ // from the FINAL env (so an agent-env override is attributed correctly, not+ // the routed choice). Read by the per-turn usageβledger hook below.+ let runExternalAccountId: string | undefined;++ // Usage ledger: one turn's spend, attributed to the account the run is on β+ // the "our own cost" half calibration crosses with the provider's utilization+ // meter. Main-agent AND subagent turns both route here: a CC Task/subagent+ // burns the same subscription as its parent, so skipping it would understate+ // the account and skew calibration high. Fire-and-forget: accounting must+ // never stall or fail the run, and the server dedupes by message id.+ const recordQuotaLedgerUsage = (intent: {+ messageId: string;+ model?: string;+ usage: unknown;+ }) => {+ if (adapterType !== 'claude-code') return;+ const u = intent.usage as ModelUsage;+ agentQuotaService+ .recordUsage({+ agentId: context.agentId,+ externalAccountId: runExternalAccountId,+ messageId: intent.messageId,+ model: intent.model,+ operationId,+ provider: 'claude-code',+ topicId: context.topicId ?? undefined,+ usage: {+ cacheRead: u.inputCachedTokens,+ cacheWrite5m: u.inputWriteCacheTokens,+ input: u.inputCacheMissTokens,+ output: u.totalOutputTokens,+ },+ })+ .catch(() => {});+ };+// Shared run lifecycle β hetero owns its terminal lifecycle here// (the desktop notification via `afterRunComplete`); queued persistence + op// completion stay in this executor's flow because the resume-session-id save@@ -1515,6 +1554,9 @@ export const executeHeterogeneousAgent = async (} catch (err) {console.error('[HeterogeneousAgent] Failed to record subagent usage:', err);}+ // Subagent turns bill the same account as the parent β ledger them too,+ // or a Task-heavy run understates the account and skews calibration.+ recordQuotaLedgerUsage(intent);return;}@@ -1799,6 +1841,8 @@ export const executeHeterogeneousAgent = async ({ id: intent.messageId, type: 'updateMessage', value: update as any },{ operationId },);++ recordQuotaLedgerUsage(intent);return;}@@ -1858,28 +1902,52 @@ export const executeHeterogeneousAgent = async (await rehydrateClientSubagentRuns();try {+ // Account routing: realize the pinned/balanced account choice as spawn env+ // (CLAUDE_CONFIG_DIR profile). Unbound agents get {} and spawn exactly as+ // before; a quota-service failure must never block the run.+ const quotaAccountPlan = await resolveQuotaAccountSpawnPlan(context.agentId, adapterType);++ const sessionEnv = {+ // Tell the CLI which LobeHub conversation it is running inside. The child+ // (and every subprocess it spawns, e.g. `lh`) inherits these, so a tool+ // running under the agent can attribute its output back to this topic+ // without the agent having to pass ids it can't see. User-configured env+ // wins β this is provenance, never an override the user can't escape.+ ...buildLobeHubSessionEnv({+ agentId: context.agentId,+ operationId,+ topicId: context.topicId,+ }),+ ...quotaAccountPlan.env,+ // The agent's own env is the most specific choice and keeps winning β+ // over both provenance and account routing.+ ...heterogeneousProvider.env,+ };+// Start session (pass resumeSessionId for multi-turn --resume)const result = await heterogeneousAgentService.startSession({agentType: adapterType,args: buildHeteroSpawnArgs(heterogeneousProvider),command: heterogeneousProvider.command || getDefaultHeterogeneousCommand(adapterType),cwd: workingDirectory,- env: {- // Tell the CLI which LobeHub conversation it is running inside. The child- // (and every subprocess it spawns, e.g. `lh`) inherits these, so a tool- // running under the agent can attribute its output back to this topic- // without the agent having to pass ids it can't see. User-configured env- // wins β this is provenance, never an override the user can't escape.- ...buildLobeHubSessionEnv({- agentId: context.agentId,- operationId,- topicId: context.topicId,- }),- ...heterogeneousProvider.env,- },+ env: sessionEnv,resumeSessionId,useClaudeCodeSdk: labPreferSelectors.enableClaudeCodeSdk(useUserStore.getState()),});++ // Attribute the run to the login the FINAL env actually resolves to (an+ // agent-env CLAUDE_CONFIG_DIR beats routing, and unbound agents use the+ // default login). Falls back to the routed choice when the file read fails.+ if (adapterType === 'claude-code') {+ heterogeneousAgentService+ .getClaudeCodeIdentity({ env: sessionEnv })+ .then((identity) => {+ runExternalAccountId = identity?.externalAccountId ?? quotaAccountPlan.externalAccountId;+ })+ .catch(() => {+ runExternalAccountId = quotaAccountPlan.externalAccountId;+ });+ }agentSessionId = result.sessionId;if (!agentSessionId) throw new Error('Agent session returned no sessionId');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.tsnew file mode 100644index 00000000000..a7791581b7a--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';++const selectAccountForAgent = vi.hoisted(() => vi.fn());++vi.mock('@/services/agentQuota', () => ({+ agentQuotaService: { selectAccountForAgent },+}));++const selection = (over: Record<string, unknown> = {}) => ({+ accountId: 'acc-1',+ credentialMode: 'referenced',+ credentialRef: { origin: 'keychain' },+ externalAccountId: 'ext-1',+ reason: 'pinned',+ ...over,+});++beforeEach(() => {+ selectAccountForAgent.mockReset();+});++describe('resolveQuotaAccountSpawnPlan', () => {+ it('routes a config-dir account via CLAUDE_CONFIG_DIR', async () => {+ selectAccountForAgent.mockResolvedValue(+ selection({ credentialRef: { configDir: '/profiles/work', origin: 'config-dir' } }),+ );++ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');++ expect(plan.env).toEqual({ CLAUDE_CONFIG_DIR: '/profiles/work' });+ expect(plan.accountId).toBe('acc-1');+ expect(plan.externalAccountId).toBe('ext-1');+ expect(plan.reason).toBe('pinned');+ });++ it('keeps the default login (no override) for a keychain account', async () => {+ selectAccountForAgent.mockResolvedValue(selection());++ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');++ expect(plan.env).toEqual({});+ expect(plan.externalAccountId).toBe('ext-1');+ });++ it('attributes but never injects env for a managed account', async () => {+ selectAccountForAgent.mockResolvedValue(+ selection({+ credentialMode: 'managed',+ credentialRef: { configDir: '/x', origin: 'config-dir' },+ }),+ );++ const plan = await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code');++ expect(plan.env).toEqual({});+ expect(plan.accountId).toBe('acc-1');+ });++ it.each([+ ['non-claude adapter', () => resolveQuotaAccountSpawnPlan('agt-1', 'codex')],+ ['missing agentId', () => resolveQuotaAccountSpawnPlan(undefined, 'claude-code')],+ ])('skips routing entirely for %s', async (_label, run) => {+ const plan = await run();+ expect(plan).toEqual({ env: {} });+ expect(selectAccountForAgent).not.toHaveBeenCalled();+ });++ it('degrades to no routing when the agent is unbound or the service fails', async () => {+ selectAccountForAgent.mockResolvedValueOnce(null);+ expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).toEqual({ env: {} });++ selectAccountForAgent.mockRejectedValueOnce(new Error('offline'));+ expect(await resolveQuotaAccountSpawnPlan('agt-1', 'claude-code')).toEqual({ env: {} });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.tsnew file mode 100644index 00000000000..5bc37fd0829--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts@@ -0,0 +1,53 @@+import { agentQuotaService } from '@/services/agentQuota';++export interface QuotaAccountSpawnPlan {+ /** Account chosen for this run, when routing applied. */+ accountId?: string;+ /** Env overrides realizing the choice (spread before the agent's own env). */+ env: Record<string, string>;+ /** Real provider account id, for runβaccount usage attribution. */+ externalAccountId?: string;+ reason?: 'pinned' | 'balanced';+}++const NO_ROUTING: QuotaAccountSpawnPlan = { env: {} };++/**+ * Resolve which provider account this agent should run on and turn the choice+ * into spawn env. The mapping mirrors how the CLI itself scopes logins:+ *+ * - `config-dir` account β `CLAUDE_CONFIG_DIR=<dir>` (an isolated CLI profile);+ * - `keychain` / `default-file` account β no override, the default login is it;+ * - `managed` accounts (cloud-held token) are not runnable locally yet;+ * - no bindings / quota service unreachable β `{}`, spawn behaves as before.+ *+ * The result is spread BEFORE `heterogeneousProvider.env`: an env the user put+ * on the agent explicitly is a stronger, more specific choice than pool+ * routing, and must keep winning.+ */+export const resolveQuotaAccountSpawnPlan = async (+ agentId: string | undefined,+ adapterType: string,+): Promise<QuotaAccountSpawnPlan> => {+ // Codex accounts exist in the DB but have no runnable credential mapping yet.+ if (adapterType !== 'claude-code' || !agentId) return NO_ROUTING;++ const selection = await agentQuotaService.selectAccountForAgent(agentId).catch(() => null);+ if (!selection) return NO_ROUTING;++ const attribution = {+ accountId: selection.accountId,+ externalAccountId: selection.externalAccountId ?? undefined,+ reason: selection.reason,+ };++ if (selection.credentialMode !== 'referenced') return { ...attribution, env: {} };++ const ref = selection.credentialRef;+ if (ref?.origin === 'config-dir' && ref.configDir) {+ return { ...attribution, env: { CLAUDE_CONFIG_DIR: ref.configDir } };+ }++ // Default login (keychain / ~/.claude): nothing to override.+ return { ...attribution, env: {} };+};