🤯 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: add read-only Codex quota menu (#16625)
AmAzing-0778bbd032b0
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 8cebbfb5751..86205183263 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -8,7 +8,10 @@ import path from 'node:path';import type { Readable, Writable } from 'node:stream';import { finished as streamFinished } from 'node:stream/promises';-import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import type {+ CodexQuotaSnapshot,+ HeterogeneousAgentSessionError,+} from '@lobechat/electron-client-ipc';import {CLAUDE_CODE_CLI_INSTALL_COMMANDS,CLAUDE_CODE_CLI_INSTALL_DOCS_URL,@@ -38,6 +41,7 @@ import { app as electronApp, BrowserWindow } from 'electron';import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';import { detectHeterogeneousCliCommand } from '@/modules/binaries';import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';+import { fetchCodexQuota } from '@/modules/heterogeneousAgent/codexQuota';import type {HeterogeneousAgentBuildPlan,HeterogeneousAgentImageAttachment,@@ -162,6 +166,11 @@ interface GetSessionInfoParams {sessionId: string;}+interface GetCodexQuotaParams {+ command?: string;+ env?: Record<string, string>;+}+interface SessionInfo {agentSessionId?: string;}@@ -1299,6 +1308,22 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return { agentSessionId: session?.agentSessionId };}+ @IpcMethod()+ async getCodexQuota(params: GetCodexQuotaParams = {}): Promise<CodexQuotaSnapshot> {+ const command = params.command?.trim() || 'codex';+ const status = await detectHeterogeneousCliCommand('codex', command);+ const env = {+ ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),+ ...params.env,+ };++ return fetchCodexQuota({+ command: status.available && status.path ? status.path : command,+ env: Object.keys(env).length > 0 ? env : undefined,+ });+ }+/*** Signal the whole process tree spawned by this session.*diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 95983cd8616..aa52090d824 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -44,6 +44,14 @@ vi.mock('@/utils/logger', () => ({}),}));+const { fetchCodexQuotaMock } = vi.hoisted(() => ({+ fetchCodexQuotaMock: vi.fn(),+}));++vi.mock('@/modules/heterogeneousAgent/codexQuota', () => ({+ fetchCodexQuota: fetchCodexQuotaMock,+}));+// Captures the most recent spawn() call so sendPrompt tests can assert on argv.const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];let nextFakeProc: any = null;@@ -121,6 +129,7 @@ describe('HeterogeneousAgentCtr', () => {beforeEach(async () => {appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-hetero-'));+ fetchCodexQuotaMock.mockReset();});afterEach(async () => {@@ -209,6 +218,65 @@ describe('HeterogeneousAgentCtr', () => {});});+ describe('getCodexQuota', () => {+ beforeEach(() => {+ execFileMock.mockReset();+ });++ it('forwards desktop proxy env to the Codex quota RPC', async () => {+ execFileMock.mockImplementation(+ (+ _file: string,+ _args: string[],+ optionsOrCallback: unknown,+ callback?: (+ error: Error | null,+ result: { stderr: string; stdout: string },+ ) => void,+ ) => {+ const resolvedCallback =+ typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;+ resolvedCallback?.(null, { stderr: '', stdout: 'codex-cli 0.99.0' });+ },+ );+ fetchCodexQuotaMock.mockResolvedValue({+ error: null,+ provider: 'codex',+ session: null,+ status: 'ok',+ updatedAt: 1,+ weekly: null,+ });+ const networkProxy = {+ enableProxy: true,+ proxyPort: '7890',+ proxyServer: '127.0.0.1',+ proxyType: 'http',+ };+ const storeGet = vi.fn((key: string) => (key === 'networkProxy' ? networkProxy : undefined));+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: storeGet },+ } as any);++ await ctr.getCodexQuota({+ command: '/custom/bin/codex',+ env: { CODEX_HOME: '/tmp/codex-home', PATH: '/custom/bin' },+ });++ expect(storeGet).toHaveBeenCalledWith('networkProxy');+ expect(fetchCodexQuotaMock).toHaveBeenCalledWith({+ command: '/custom/bin/codex',+ env: expect.objectContaining({+ CODEX_HOME: '/tmp/codex-home',+ HTTPS_PROXY: 'http://127.0.0.1:7890',+ HTTP_PROXY: 'http://127.0.0.1:7890',+ PATH: '/custom/bin',+ }),+ });+ });+ });+describe('sendPrompt (claude-code)', () => {beforeEach(() => {spawnCalls.length = 0;diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.tsnew file mode 100644index 00000000000..99f80c2c1b6--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.test.ts@@ -0,0 +1,259 @@+import { EventEmitter } from 'node:events';+import { readFile } from 'node:fs/promises';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { fetchCodexQuota } from './codexQuota';++vi.mock('node:fs/promises', () => ({+ readFile: vi.fn(),+}));++const spawnMock = vi.hoisted(() => vi.fn());++vi.mock('node:child_process', () => ({+ spawn: spawnMock,+}));++class RpcChild extends EventEmitter {+ stderr = new EventEmitter();+ stdin = {+ write: vi.fn(),+ };+ stdout = new EventEmitter();++ kill = vi.fn();+}++const mockRpcRateLimits = (child: RpcChild, result: unknown) => {+ child.stdin.write.mockImplementation((line: string) => {+ const message = JSON.parse(line) as { id?: number; method?: string };++ if (message.method === 'initialize') {+ setTimeout(() => {+ child.stdout.emit(+ 'data',+ Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} })}\n`),+ );+ }, 0);+ }++ if (message.method === 'account/rateLimits/read') {+ setTimeout(() => {+ child.stdout.emit(+ 'data',+ Buffer.from(+ `${JSON.stringify({+ jsonrpc: '2.0',+ id: message.id,+ result,+ })}\n`,+ ),+ );+ }, 0);+ }+ });+};++describe('fetchCodexQuota', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-06-20T12:00:00Z'));+ vi.stubGlobal('fetch', vi.fn());+ vi.mocked(readFile).mockReset();+ spawnMock.mockReset();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it('fills reset-credit metadata from the Codex backend when RPC omits it', async () => {+ const child = new RpcChild();+ spawnMock.mockReturnValue(child);+ vi.mocked(readFile).mockResolvedValue(+ JSON.stringify({+ tokens: {+ access_token: 'access-token',+ account_id: 'account-id',+ },+ }),+ );+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ json: async () => ({+ available_count: 2,+ total_earned_count: 3,+ credits: [+ {+ status: 'available',+ expires_at: '2026-06-25T12:00:00Z',+ granted_at: '2026-06-18T12:00:00Z',+ },+ {+ status: 'available',+ expires_at: '2026-06-24T12:00:00Z',+ granted_at: '2026-06-17T12:00:00Z',+ },+ {+ status: 'redeemed',+ expires_at: '2026-06-23T12:00:00Z',+ granted_at: '2026-06-16T12:00:00Z',+ },+ ],+ }),+ } as Response);++ mockRpcRateLimits(child, {+ rateLimits: {+ primary: { resetsAt: 1_718_800_000, usedPercent: 4, windowDurationMins: 15 },+ secondary: { resetsAt: 1_719_300_000, usedPercent: 52, windowDurationMins: 60 },+ },+ });++ const resultPromise = fetchCodexQuota({+ command: '/custom/bin/codex',+ env: { CODEX_HOME: '/tmp/codex-home', LOBE_TEST_ENV: '1' },+ });+ await vi.advanceTimersByTimeAsync(1);+ await vi.advanceTimersByTimeAsync(1);+ const result = await resultPromise;++ expect(result).toMatchObject({+ provider: 'codex',+ status: 'ok',+ session: {+ resetsAt: 1_718_800_000 * 1000,+ usedPercent: 4,+ windowMinutes: 15,+ },+ weekly: {+ resetsAt: 1_719_300_000 * 1000,+ usedPercent: 52,+ windowMinutes: 60,+ },+ rateLimitResetCredits: {+ availableCount: 2,+ totalEarnedCount: 3,+ nextExpiresAt: Date.parse('2026-06-24T12:00:00Z'),+ },+ });+ expect(readFile).toHaveBeenCalledWith('/tmp/codex-home/auth.json', 'utf8');+ expect(spawnMock).toHaveBeenCalledWith(+ '/custom/bin/codex',+ ['-s', 'read-only', '-a', 'untrusted', 'app-server'],+ expect.objectContaining({+ env: expect.objectContaining({+ CODEX_HOME: '/tmp/codex-home',+ LOBE_TEST_ENV: '1',+ }),+ }),+ );+ expect(fetch).toHaveBeenCalledWith(+ 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits',+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: 'Bearer access-token',+ 'ChatGPT-Account-Id': 'account-id',+ 'OpenAI-Beta': 'codex-1',+ }),+ }),+ );+ });++ it('reads RPC quota when auth.json is unavailable', async () => {+ const child = new RpcChild();+ spawnMock.mockReturnValue(child);+ vi.mocked(readFile).mockRejectedValue(new Error('ENOENT'));+ mockRpcRateLimits(child, {+ rateLimits: {+ primary: { resetsAt: 1_718_800_000, usedPercent: 7 },+ secondary: { resetsAt: 1_719_300_000, usedPercent: 41 },+ },+ rateLimitResetCredits: {+ availableCount: 1,+ },+ });++ const resultPromise = fetchCodexQuota({ command: '/custom/bin/codex' });+ await vi.advanceTimersByTimeAsync(1);+ await vi.advanceTimersByTimeAsync(1);+ const result = await resultPromise;++ expect(result).toMatchObject({+ provider: 'codex',+ status: 'ok',+ session: {+ resetsAt: 1_718_800_000 * 1000,+ usedPercent: 7,+ windowMinutes: 300,+ },+ weekly: {+ resetsAt: 1_719_300_000 * 1000,+ usedPercent: 41,+ windowMinutes: 10_080,+ },+ rateLimitResetCredits: {+ availableCount: 1,+ },+ });+ expect(fetch).not.toHaveBeenCalled();+ });++ it('returns RPC quota when reset-credit enrichment times out', async () => {+ const child = new RpcChild();+ spawnMock.mockReturnValue(child);+ vi.mocked(readFile).mockResolvedValue(+ JSON.stringify({+ tokens: {+ access_token: 'access-token',+ },+ }),+ );+ vi.mocked(fetch).mockReturnValue(new Promise(() => {}) as Promise<Response>);+ mockRpcRateLimits(child, {+ rateLimits: {+ primary: { resetsAt: 1_718_800_000, usedPercent: 11 },+ secondary: { resetsAt: 1_719_300_000, usedPercent: 63 },+ },+ rateLimitResetCredits: {+ availableCount: 4,+ },+ });++ const resultPromise = fetchCodexQuota({ command: '/custom/bin/codex' });+ await vi.advanceTimersByTimeAsync(1);+ await vi.advanceTimersByTimeAsync(1);+ await vi.advanceTimersByTimeAsync(2000);+ const result = await resultPromise;++ expect(result).toMatchObject({+ provider: 'codex',+ status: 'ok',+ session: {+ resetsAt: 1_718_800_000 * 1000,+ usedPercent: 11,+ windowMinutes: 300,+ },+ weekly: {+ resetsAt: 1_719_300_000 * 1000,+ usedPercent: 63,+ windowMinutes: 10_080,+ },+ rateLimitResetCredits: {+ availableCount: 4,+ nextExpiresAt: null,+ },+ });+ expect(fetch).toHaveBeenCalledWith(+ 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits',+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: 'Bearer access-token',+ }),+ signal: expect.any(AbortSignal),+ }),+ );+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.tsnew file mode 100644index 00000000000..7868d655401--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexQuota.ts@@ -0,0 +1,437 @@+import type { ChildProcess } from 'node:child_process';+import { spawn } from 'node:child_process';+import { readFile } from 'node:fs/promises';+import { homedir } from 'node:os';+import path from 'node:path';++import { resolveCliSpawnPlan } from '@lobechat/heterogeneous-agents/spawn';++const RPC_TIMEOUT_MS = 10_000;+const RESET_CREDITS_TIMEOUT_MS = 1_500;+const CODEX_RATE_LIMIT_RESET_CREDITS_URL =+ 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits';++export interface CodexQuotaWindow {+ resetsAt: number | null;+ usedPercent: number;+ windowMinutes: number;+}++export interface CodexRateLimitResetCredits {+ availableCount: number;+ credits?: {+ expiresAt: number | null;+ grantedAt: number | null;+ status: string;+ }[];+ nextExpiresAt?: number | null;+ totalEarnedCount?: number;+}++export interface CodexQuotaSnapshot {+ error: string | null;+ provider: 'codex';+ rateLimitResetCredits?: CodexRateLimitResetCredits | null;+ session: CodexQuotaWindow | null;+ status: 'error' | 'ok' | 'unavailable';+ updatedAt: number;+ weekly: CodexQuotaWindow | null;+}++export interface FetchCodexQuotaOptions {+ codexHomePath?: string | null;+ command?: string;+ env?: NodeJS.ProcessEnv;+}++interface RpcResponse {+ error?: { message?: string };+ id?: number;+ result?: unknown;+}++interface RpcRateWindow {+ resetsAt?: number;+ usedPercent?: number;+ windowDurationMins?: number;+}++interface RpcRateLimitsResponse {+ rateLimitResetCredits?: {+ availableCount?: number;+ credits?: {+ expiresAt?: number | string | null;+ grantedAt?: number | string | null;+ status?: string;+ }[];+ nextExpiresAt?: number | string | null;+ totalEarnedCount?: number;+ } | null;+ rateLimits?: {+ primary?: RpcRateWindow;+ secondary?: RpcRateWindow;+ };+}++interface CodexAuthFile {+ tokens?: {+ access_token?: string;+ account_id?: string;+ };+}++interface BackendRateLimitResetCreditsResponse {+ available_count?: number;+ credits?: {+ expires_at?: number | string | null;+ granted_at?: number | string | null;+ status?: string;+ }[];+ total_earned_count?: number;+}++interface CodexBackendAuth {+ headers: Record<string, string>;+}++const getCodexHomePath = ({ codexHomePath, env }: FetchCodexQuotaOptions) =>+ codexHomePath ?? env?.CODEX_HOME ?? process.env.CODEX_HOME ?? path.join(homedir(), '.codex');++const errorSnapshot = (message: string): CodexQuotaSnapshot => ({+ error: message,+ provider: 'codex',+ session: null,+ status: 'error',+ updatedAt: Date.now(),+ weekly: null,+});++const buildRpcMessage = (id: number, method: string, params: unknown = {}) =>+ `${JSON.stringify({ id, jsonrpc: '2.0', method, params })}\n`;++const parseCreditTimestamp = (value: number | string | null | undefined): number | null => {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value < 10_000_000_000 ? value * 1000 : value;+ }++ if (typeof value !== 'string' || !value.trim()) return null;++ const numeric = Number(value);+ if (Number.isFinite(numeric)) {+ return numeric < 10_000_000_000 ? numeric * 1000 : numeric;+ }++ const parsed = Date.parse(value);+ return Number.isFinite(parsed) ? parsed : null;+};++const normalizeCreditStatus = (status?: string) => status?.toLowerCase() ?? 'unknown';++const getNextAvailableCreditExpiry = (+ credits: CodexRateLimitResetCredits['credits'] | undefined,+) =>+ credits+ ?.filter((credit) => credit.status === 'available' && typeof credit.expiresAt === 'number')+ .map((credit) => credit.expiresAt as number)+ .sort((a, b) => a - b)[0] ?? null;++const mapRpcResetCredits = (+ raw: RpcRateLimitsResponse['rateLimitResetCredits'],+): CodexRateLimitResetCredits | null | undefined => {+ if (raw === null) return null;+ if (raw === undefined) return undefined;+ if (typeof raw.availableCount !== 'number' || !Number.isFinite(raw.availableCount)) return null;++ const credits = raw.credits?.map((credit) => ({+ expiresAt: parseCreditTimestamp(credit.expiresAt),+ grantedAt: parseCreditTimestamp(credit.grantedAt),+ status: normalizeCreditStatus(credit.status),+ }));++ return {+ availableCount: Math.max(0, Math.floor(raw.availableCount)),+ ...(credits ? { credits } : {}),+ nextExpiresAt: parseCreditTimestamp(raw.nextExpiresAt) ?? getNextAvailableCreditExpiry(credits),+ ...(typeof raw.totalEarnedCount === 'number' && Number.isFinite(raw.totalEarnedCount)+ ? { totalEarnedCount: Math.max(0, Math.floor(raw.totalEarnedCount)) }+ : {}),+ };+};++const mapBackendResetCredits = (+ raw: BackendRateLimitResetCreditsResponse | null | undefined,+): CodexRateLimitResetCredits | null => {+ if (!raw) return null;++ const credits = raw.credits?.map((credit) => ({+ expiresAt: parseCreditTimestamp(credit.expires_at),+ grantedAt: parseCreditTimestamp(credit.granted_at),+ status: normalizeCreditStatus(credit.status),+ }));+ const availableCount =+ typeof raw.available_count === 'number' && Number.isFinite(raw.available_count)+ ? raw.available_count+ : (credits?.filter((credit) => credit.status === 'available').length ?? null);++ if (availableCount === null) return null;++ return {+ availableCount: Math.max(0, Math.floor(availableCount)),+ ...(credits ? { credits } : {}),+ nextExpiresAt: getNextAvailableCreditExpiry(credits),+ ...(typeof raw.total_earned_count === 'number' && Number.isFinite(raw.total_earned_count)+ ? { totalEarnedCount: Math.max(0, Math.floor(raw.total_earned_count)) }+ : {}),+ };+};++const readCodexBackendAuth = async (+ options: FetchCodexQuotaOptions,+): Promise<CodexBackendAuth | null> => {+ let auth: CodexAuthFile;++ try {+ const authPath = path.join(getCodexHomePath(options), 'auth.json');+ auth = JSON.parse(await readFile(authPath, 'utf8')) as CodexAuthFile;+ } catch {+ return null;+ }++ const accessToken = auth.tokens?.access_token;+ if (!accessToken) return null;++ const headers: Record<string, string> = {+ Authorization: `Bearer ${accessToken}`,+ 'OpenAI-Beta': 'codex-1',+ 'User-Agent': 'codex-cli',+ originator: 'LobeHub Desktop',+ };++ if (auth.tokens?.account_id) {+ headers['ChatGPT-Account-Id'] = auth.tokens.account_id;+ }++ return { headers };+};++const fetchBackendResetCredits = async (+ auth: CodexBackendAuth,+): Promise<CodexRateLimitResetCredits | null> => {+ const controller = new AbortController();+ let timeout: ReturnType<typeof setTimeout> | undefined;+ const timeoutPromise = new Promise<null>((resolve) => {+ timeout = setTimeout(() => {+ controller.abort();+ resolve(null);+ }, RESET_CREDITS_TIMEOUT_MS);+ });++ const fetchPromise = (async () => {+ const response = await fetch(CODEX_RATE_LIMIT_RESET_CREDITS_URL, {+ ...auth,+ signal: controller.signal,+ });+ if (!response.ok) return null;++ const payload = (await response.json()) as BackendRateLimitResetCreditsResponse;+ return mapBackendResetCredits(payload);+ })();++ try {+ return await Promise.race([fetchPromise, timeoutPromise]);+ } finally {+ if (timeout) clearTimeout(timeout);+ }+};++const mapRpcWindow = (+ raw: RpcRateWindow | undefined,+ fallbackWindowMinutes: number,+): CodexQuotaWindow | null => {+ if (!raw || typeof raw.usedPercent !== 'number' || !Number.isFinite(raw.usedPercent)) {+ return null;+ }++ const windowMinutes =+ typeof raw.windowDurationMins === 'number' &&+ Number.isFinite(raw.windowDurationMins) &&+ raw.windowDurationMins > 0+ ? Math.floor(raw.windowDurationMins)+ : fallbackWindowMinutes;++ return {+ resetsAt:+ typeof raw.resetsAt === 'number' && Number.isFinite(raw.resetsAt)+ ? raw.resetsAt * 1000+ : null,+ usedPercent: Math.min(100, Math.max(0, raw.usedPercent)),+ windowMinutes,+ };+};++const cleanupRpcListeners = (+ child: ChildProcess,+ listeners: {+ close: () => void;+ error: (error: Error) => void;+ stderrData: (chunk: Buffer) => void;+ stdoutData: (chunk: Buffer) => void;+ },+) => {+ child.stdout?.off('data', listeners.stdoutData);+ child.stderr?.off('data', listeners.stderrData);+ child.off('error', listeners.error);+ child.off('close', listeners.close);+};++const fetchViaRpc = async (+ options: FetchCodexQuotaOptions,+ auth: CodexBackendAuth | null,+): Promise<CodexQuotaSnapshot> =>+ new Promise<CodexQuotaSnapshot>((resolve) => {+ let buffer = '';+ let child: ChildProcess | null = null;+ let initId = 0;+ let stderr = '';+ let resolved = false;+ let rpcId = 0;+ let rateLimitsId: number | null = null;+ let timeout: ReturnType<typeof setTimeout> | undefined;++ const rpcArgs = ['-s', 'read-only', '-a', 'untrusted', 'app-server'];++ const settle = (result: CodexQuotaSnapshot, kill = false) => {+ if (resolved) return;+ resolved = true;+ if (timeout) {+ clearTimeout(timeout);+ timeout = undefined;+ }+ if (child) {+ cleanupRpcListeners(child, listeners);+ if (kill) child.kill();+ }+ resolve(result);+ };++ const sendRpc = (child: ChildProcess, method: string, params?: unknown) => {+ const id = ++rpcId;+ child.stdin?.write(buildRpcMessage(id, method, params));+ return id;+ };++ const sendNotification = (child: ChildProcess, method: string) => {+ child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', method, params: {} })}\n`);+ };++ const handleRateLimitsResponse = async (message: RpcResponse) => {+ if (message.error) {+ settle(errorSnapshot(message.error.message ?? 'Codex rate-limit RPC failed'), true);+ return;+ }++ const wrapper = message.result as RpcRateLimitsResponse | undefined;+ const rateLimitResetCredits = mapRpcResetCredits(wrapper?.rateLimitResetCredits);+ let backendCredits: CodexRateLimitResetCredits | null = null;++ if (auth && rateLimitResetCredits?.nextExpiresAt == null) {+ try {+ backendCredits = await fetchBackendResetCredits(auth);+ } catch {+ backendCredits = null;+ }+ }++ settle(+ {+ error: null,+ provider: 'codex',+ rateLimitResetCredits:+ backendCredits ??+ (rateLimitResetCredits === undefined ? undefined : rateLimitResetCredits),+ session: mapRpcWindow(wrapper?.rateLimits?.primary, 300),+ status: 'ok',+ updatedAt: Date.now(),+ weekly: mapRpcWindow(wrapper?.rateLimits?.secondary, 10_080),+ },+ true,+ );+ };++ const onStdoutData = (child: ChildProcess) => (chunk: Buffer) => {+ buffer += chunk.toString();++ let newlineIndex: number;+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {+ const line = buffer.slice(0, newlineIndex).trim();+ buffer = buffer.slice(newlineIndex + 1);+ if (!line) continue;++ try {+ const message = JSON.parse(line) as RpcResponse;+ if (message.id === initId) {+ if (!child) return;+ sendNotification(child, 'initialized');+ rateLimitsId = sendRpc(child, 'account/rateLimits/read');+ continue;+ }++ if (rateLimitsId !== null && message.id === rateLimitsId) {+ void handleRateLimitsResponse(message);+ }+ } catch {+ // Ignore non-JSON output from the RPC process.+ }+ }+ };++ const onStderrData = (chunk: Buffer) => {+ stderr += chunk.toString();+ };++ const listeners = {+ close: () => settle(errorSnapshot(stderr || 'Codex rate-limit RPC exited'), false),+ error: (error: Error) => settle(errorSnapshot(error.message), false),+ stderrData: onStderrData,+ stdoutData: (chunk: Buffer) => {+ if (child) onStdoutData(child)(chunk);+ },+ };++ timeout = setTimeout(() => {+ settle(errorSnapshot('Codex rate-limit RPC timed out'), true);+ }, RPC_TIMEOUT_MS);++ void resolveCliSpawnPlan(options.command ?? 'codex', rpcArgs)+ .then((spawnPlan) => {+ if (resolved) return;++ child = spawn(spawnPlan.command, spawnPlan.args, {+ env: {+ ...process.env,+ ...options.env,+ ...(options.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}),+ },+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ });+ child.stdout?.on('data', listeners.stdoutData);+ child.stderr?.on('data', listeners.stderrData);+ child.on('error', listeners.error);+ child.on('close', listeners.close);+ initId = sendRpc(child, 'initialize', {+ clientInfo: { name: 'lobehub', version: '1.0.0' },+ });+ })+ .catch((error: unknown) => {+ const message = error instanceof Error ? error.message : 'Failed to resolve Codex command';+ settle(errorSnapshot(message), true);+ });+ });++export const fetchCodexQuota = async (+ options: FetchCodexQuotaOptions = {},+): Promise<CodexQuotaSnapshot> => {+ const auth = await readCodexBackendAuth(options);+ return fetchViaRpc(options, auth);+};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 33fc513e18d..e2a709fb1f0 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -294,6 +294,31 @@"heteroAgent.executionTarget.title": "Execution Device","heteroAgent.executionTarget.unknownDevice": "Unknown device","heteroAgent.executionTarget.workspaceGroup": "Workspace",+ "heteroAgent.codexQuota.compactLeft": "{{percent}}%",+ "heteroAgent.codexQuota.duration.day_one": "{{count}}d",+ "heteroAgent.codexQuota.duration.day_other": "{{count}}d",+ "heteroAgent.codexQuota.duration.hour_one": "{{count}}h",+ "heteroAgent.codexQuota.duration.hour_other": "{{count}}h",+ "heteroAgent.codexQuota.duration.minute_one": "{{count}}m",+ "heteroAgent.codexQuota.duration.minute_other": "{{count}}m",+ "heteroAgent.codexQuota.expiresIn": "Expires in {{duration}}",+ "heteroAgent.codexQuota.left": "{{percent}}% left",+ "heteroAgent.codexQuota.nextExpiresIn": "Next expires in {{duration}}",+ "heteroAgent.codexQuota.noData": "Codex quota is not available yet.",+ "heteroAgent.codexQuota.refresh": "Refresh Codex quota",+ "heteroAgent.codexQuota.resetCredits_one": "1 rate-limit reset available",+ "heteroAgent.codexQuota.resetCredits_other": "{{count}} rate-limit resets available",+ "heteroAgent.codexQuota.resetCredits_zero": "No rate-limit resets available",+ "heteroAgent.codexQuota.resetCreditsUnavailable": "Reset credits unavailable",+ "heteroAgent.codexQuota.resetsIn": "Resets in {{duration}}",+ "heteroAgent.codexQuota.resetsSoon": "Resets soon",+ "heteroAgent.codexQuota.session": "Session",+ "heteroAgent.codexQuota.title": "Codex quota",+ "heteroAgent.codexQuota.tooltip": "View Codex quota",+ "heteroAgent.codexQuota.unavailable": "Codex quota is unavailable.",+ "heteroAgent.codexQuota.updatedAgo": "Updated {{duration}} ago",+ "heteroAgent.codexQuota.updatedJustNow": "Updated just now",+ "heteroAgent.codexQuota.weekly": "Weekly","heteroAgent.fullAccess.label": "Full access","heteroAgent.fullAccess.tooltip": "The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.","heteroAgent.modelSelector.ariaLabel": "Model: {{model}}. Reasoning: {{reasoning}}",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex d651b182fb5..57da0642275 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -294,6 +294,31 @@"heteroAgent.executionTarget.title": "执行设备","heteroAgent.executionTarget.unknownDevice": "未知设备","heteroAgent.executionTarget.workspaceGroup": "工作区设备",+ "heteroAgent.codexQuota.compactLeft": "{{percent}}%",+ "heteroAgent.codexQuota.duration.day_one": "{{count}}天",+ "heteroAgent.codexQuota.duration.day_other": "{{count}}天",+ "heteroAgent.codexQuota.duration.hour_one": "{{count}}小时",+ "heteroAgent.codexQuota.duration.hour_other": "{{count}}小时",+ "heteroAgent.codexQuota.duration.minute_one": "{{count}}分钟",+ "heteroAgent.codexQuota.duration.minute_other": "{{count}}分钟",+ "heteroAgent.codexQuota.expiresIn": "{{duration}}后过期",+ "heteroAgent.codexQuota.left": "剩余 {{percent}}%",+ "heteroAgent.codexQuota.nextExpiresIn": "下一次将在 {{duration}}后过期",+ "heteroAgent.codexQuota.noData": "暂未获取到 Codex 额度。",+ "heteroAgent.codexQuota.refresh": "刷新 Codex 额度",+ "heteroAgent.codexQuota.resetCredits_one": "1 次可用额度重置",+ "heteroAgent.codexQuota.resetCredits_other": "{{count}} 次可用额度重置",+ "heteroAgent.codexQuota.resetCredits_zero": "暂无可用额度重置",+ "heteroAgent.codexQuota.resetCreditsUnavailable": "额度重置次数不可用",+ "heteroAgent.codexQuota.resetsIn": "{{duration}}后重置",+ "heteroAgent.codexQuota.resetsSoon": "即将重置",+ "heteroAgent.codexQuota.session": "会话",+ "heteroAgent.codexQuota.title": "Codex 额度",+ "heteroAgent.codexQuota.tooltip": "查看 Codex 额度",+ "heteroAgent.codexQuota.unavailable": "Codex 额度不可用。",+ "heteroAgent.codexQuota.updatedAgo": "{{duration}}前更新",+ "heteroAgent.codexQuota.updatedJustNow": "刚刚更新",+ "heteroAgent.codexQuota.weekly": "每周","heteroAgent.fullAccess.label": "完全访问权限","heteroAgent.fullAccess.tooltip": "本地编码 Agent 运行时对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。","heteroAgent.modelSelector.ariaLabel": "模型:{{model}}。思考强度:{{reasoning}}",diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.tsindex bb0ee920d21..c97bd700850 100644--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts@@ -35,6 +35,33 @@ export interface HeterogeneousAgentRateLimitInfo {status?: string;}+export interface CodexQuotaWindow {+ resetsAt: number | null;+ usedPercent: number;+ windowMinutes: number;+}++export interface CodexRateLimitResetCredits {+ availableCount: number;+ credits?: {+ expiresAt: number | null;+ grantedAt: number | null;+ status: string;+ }[];+ nextExpiresAt?: number | null;+ totalEarnedCount?: number;+}++export interface CodexQuotaSnapshot {+ error: string | null;+ provider: 'codex';+ rateLimitResetCredits?: CodexRateLimitResetCredits | null;+ session: CodexQuotaWindow | null;+ status: 'error' | 'ok' | 'unavailable';+ updatedAt: number;+ weekly: CodexQuotaWindow | null;+}+export interface HeterogeneousAgentSessionError {agentType?: string;code?: HeterogeneousAgentSessionErrorCode | string;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 3e0d4c610fc..2e930fed517 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -179,6 +179,31 @@ export default {'heteroAgent.fullAccess.label': 'Full access','heteroAgent.fullAccess.tooltip':'The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.',+ 'heteroAgent.codexQuota.compactLeft': '{{percent}}%',+ 'heteroAgent.codexQuota.duration.day_one': '{{count}}d',+ 'heteroAgent.codexQuota.duration.day_other': '{{count}}d',+ 'heteroAgent.codexQuota.duration.hour_one': '{{count}}h',+ 'heteroAgent.codexQuota.duration.hour_other': '{{count}}h',+ 'heteroAgent.codexQuota.duration.minute_one': '{{count}}m',+ 'heteroAgent.codexQuota.duration.minute_other': '{{count}}m',+ 'heteroAgent.codexQuota.expiresIn': 'Expires in {{duration}}',+ 'heteroAgent.codexQuota.left': '{{percent}}% left',+ 'heteroAgent.codexQuota.nextExpiresIn': 'Next expires in {{duration}}',+ 'heteroAgent.codexQuota.noData': 'Codex quota is not available yet.',+ 'heteroAgent.codexQuota.refresh': 'Refresh Codex quota',+ 'heteroAgent.codexQuota.resetCredits_one': '1 rate-limit reset available',+ 'heteroAgent.codexQuota.resetCredits_other': '{{count}} rate-limit resets available',+ 'heteroAgent.codexQuota.resetCredits_zero': 'No rate-limit resets available',+ 'heteroAgent.codexQuota.resetCreditsUnavailable': 'Reset credits unavailable',+ 'heteroAgent.codexQuota.resetsIn': 'Resets in {{duration}}',+ 'heteroAgent.codexQuota.resetsSoon': 'Resets soon',+ 'heteroAgent.codexQuota.session': 'Session',+ 'heteroAgent.codexQuota.title': 'Codex quota',+ 'heteroAgent.codexQuota.tooltip': 'View Codex quota',+ 'heteroAgent.codexQuota.unavailable': 'Codex quota is unavailable.',+ 'heteroAgent.codexQuota.updatedAgo': 'Updated {{duration}} ago',+ 'heteroAgent.codexQuota.updatedJustNow': 'Updated just now',+ 'heteroAgent.codexQuota.weekly': 'Weekly','heteroAgent.modelSelector.ariaLabel': 'Model: {{model}}. Reasoning: {{reasoning}}','heteroAgent.modelSelector.default': 'Default','heteroAgent.modelSelector.defaultConfig': 'Default config',diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsxnew file mode 100644index 00000000000..26ae69eb08f--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx@@ -0,0 +1,362 @@+'use client';++import type { CodexQuotaSnapshot, CodexQuotaWindow } from '@lobechat/electron-client-ipc';+import { ActionIcon, Flexbox, Icon, Skeleton, Text, Tooltip } from '@lobehub/ui';+import { Popover } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronDownIcon, GaugeIcon, RefreshCwIcon, RotateCcwIcon } from 'lucide-react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';++const QUOTA_STALE_MS = 60_000;++const styles = createStaticStyles(({ css }) => ({+ emptyState: css`+ padding-block: 10px;+ font-size: 12px;+ color: ${cssVar.colorTextDescription};+ `,+ error: css`+ padding: 8px;+ border: 1px solid ${cssVar.colorErrorBorder};+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;+ color: ${cssVar.colorError};++ background: ${cssVar.colorErrorBg};+ `,+ header: css`+ padding-block-end: 8px;+ border-bottom: 1px solid ${cssVar.colorBorderSecondary};+ `,+ popover: css`+ width: 292px;+ `,+ progressFill: css`+ height: 100%;+ border-radius: inherit;+ background: ${cssVar.colorSuccess};+ `,+ progressTrack: css`+ overflow: hidden;++ width: 100%;+ height: 6px;+ border-radius: 999px;++ background: ${cssVar.colorFillQuaternary};+ `,+ resetCredits: css`+ padding-block-start: 8px;+ border-top: 1px solid ${cssVar.colorBorderSecondary};+ `,+ trigger: css`+ cursor: pointer;++ display: flex;+ flex: none;+ gap: 6px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 4px;+ border: 0;+ border-radius: 4px;++ font: inherit;+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ white-space: nowrap;++ appearance: none;+ background: transparent;+ transition: all 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ triggerOpen: css`+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ `,+ value: css`+ color: ${cssVar.colorText};+ `,+ window: css`+ min-width: 0;+ `,+}));++const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));++const createErrorSnapshot = (error: unknown): CodexQuotaSnapshot => ({+ error: error instanceof Error ? error.message : String(error),+ provider: 'codex',+ rateLimitResetCredits: null,+ session: null,+ status: 'error',+ updatedAt: Date.now(),+ weekly: null,+});++interface CodexQuotaMenuProps {+ command?: string;+ env?: Record<string, string>;+}++const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const [loading, setLoading] = useState(false);+ const [quota, setQuota] = useState<CodexQuotaSnapshot | null>(null);+ const [now, setNow] = useState(() => Date.now());++ const loadQuota = useCallback(async () => {+ setLoading(true);++ try {+ const nextQuota = await heterogeneousAgentService.getCodexQuota({ command, env });+ setQuota(nextQuota);+ } catch (error) {+ console.error('Failed to fetch Codex quota:', error);+ setQuota(createErrorSnapshot(error));+ } finally {+ setLoading(false);+ }+ }, [command, env]);++ useEffect(() => {+ void loadQuota();+ }, [loadQuota]);++ useEffect(() => {+ const interval = window.setInterval(() => setNow(Date.now()), QUOTA_STALE_MS);++ return () => {+ window.clearInterval(interval);+ };+ }, []);++ const formatDuration = useCallback(+ (ms: number) => {+ if (ms <= 0) return;++ const totalMinutes = Math.floor(ms / 60_000);+ const days = Math.floor(totalMinutes / (24 * 60));+ const hours = Math.floor((totalMinutes % (24 * 60)) / 60);+ const minutes = totalMinutes % 60;+ const parts: string[] = [];++ if (days > 0) parts.push(t('heteroAgent.codexQuota.duration.day', { count: days }));+ if (hours > 0) parts.push(t('heteroAgent.codexQuota.duration.hour', { count: hours }));+ if (minutes > 0 && parts.length < 2) {+ parts.push(t('heteroAgent.codexQuota.duration.minute', { count: minutes }));+ }++ return parts.slice(0, 2).join(' ') || undefined;+ },+ [t],+ );++ const formatResetCountdown = useCallback(+ (resetsAt: number | null | undefined) => {+ if (!resetsAt) return;++ const duration = formatDuration(resetsAt - now);+ return duration+ ? t('heteroAgent.codexQuota.resetsIn', { duration })+ : t('heteroAgent.codexQuota.resetsSoon');+ },+ [formatDuration, now, t],+ );++ const formatUpdatedAt = useCallback(+ (updatedAt: number) => {+ const duration = formatDuration(now - updatedAt);++ return duration+ ? t('heteroAgent.codexQuota.updatedAgo', { duration })+ : t('heteroAgent.codexQuota.updatedJustNow');+ },+ [formatDuration, now, t],+ );++ const sessionLeftPercent = quota?.session+ ? clampPercent(100 - quota.session.usedPercent)+ : undefined;+ const resetCreditCount = quota?.rateLimitResetCredits?.availableCount;+ const resetCreditExpiry = quota?.rateLimitResetCredits?.nextExpiresAt;+ const hasQuotaData = !!(quota?.session || quota?.weekly || quota?.rateLimitResetCredits);++ const handleOpenChange = useCallback(+ (nextOpen: boolean) => {+ setOpen(nextOpen);++ if (!nextOpen || loading) return;+ if (!quota || Date.now() - quota.updatedAt > QUOTA_STALE_MS) void loadQuota();+ },+ [loadQuota, loading, quota],+ );++ const renderQuotaWindow = useCallback(+ (window: CodexQuotaWindow | null, label: string) => {+ if (!window) return null;++ const leftPercent = clampPercent(100 - window.usedPercent);+ const resetLabel = formatResetCountdown(window.resetsAt);++ return (+ <Flexbox className={styles.window} gap={4} key={label}>+ <Text strong style={{ fontSize: 12 }}>+ {label}+ </Text>+ <div className={styles.progressTrack}>+ <div className={styles.progressFill} style={{ width: `${leftPercent}%` }} />+ </div>+ <Flexbox horizontal style={{ justifyContent: 'space-between' }}>+ <Text className={styles.value} style={{ fontSize: 12 }}>+ {t('heteroAgent.codexQuota.left', { percent: leftPercent })}+ </Text>+ {resetLabel && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {resetLabel}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+ );+ },+ [formatResetCountdown, t],+ );++ const resetCreditExpiryLabel = useMemo(() => {+ if (!resetCreditExpiry || resetCreditCount === undefined) return;++ const duration = formatDuration(resetCreditExpiry - now);+ if (!duration) return;++ return resetCreditCount > 1+ ? t('heteroAgent.codexQuota.nextExpiresIn', { duration })+ : t('heteroAgent.codexQuota.expiresIn', { duration });+ }, [formatDuration, now, resetCreditCount, resetCreditExpiry, t]);++ const content = (+ <Flexbox className={styles.popover} gap={10}>+ <Flexbox horizontal align={'center'} className={styles.header} justify={'space-between'}>+ <Flexbox gap={2}>+ <Text strong>{t('heteroAgent.codexQuota.title')}</Text>+ {quota?.updatedAt && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {formatUpdatedAt(quota.updatedAt)}+ </Text>+ )}+ </Flexbox>+ <Tooltip title={t('heteroAgent.codexQuota.refresh')}>+ <ActionIcon+ disabled={loading}+ icon={RefreshCwIcon}+ size={'small'}+ onClick={() => void loadQuota()}+ />+ </Tooltip>+ </Flexbox>++ {loading && !hasQuotaData ? (+ <Flexbox gap={8}>+ <Skeleton.Button active block size="small" style={{ height: 18 }} />+ <Skeleton.Button active block size="small" style={{ height: 18 }} />+ <Skeleton.Button active block size="small" style={{ height: 18 }} />+ </Flexbox>+ ) : quota?.status === 'error' || quota?.status === 'unavailable' ? (+ <div className={styles.error}>+ {quota.error || t('heteroAgent.codexQuota.unavailable')}+ </div>+ ) : hasQuotaData ? (+ <>+ <Flexbox gap={10}>+ {renderQuotaWindow(quota?.session ?? null, t('heteroAgent.codexQuota.session'))}+ {renderQuotaWindow(quota?.weekly ?? null, t('heteroAgent.codexQuota.weekly'))}+ </Flexbox>+ {resetCreditCount !== undefined ? (+ <Flexbox className={styles.resetCredits} gap={4}>+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={RotateCcwIcon} size={13} />+ <Text strong style={{ fontSize: 12 }}>+ {t('heteroAgent.codexQuota.resetCredits', { count: resetCreditCount })}+ </Text>+ </Flexbox>+ {resetCreditExpiryLabel && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {resetCreditExpiryLabel}+ </Text>+ )}+ </Flexbox>+ ) : (+ <Flexbox className={styles.resetCredits} gap={4}>+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={RotateCcwIcon} size={13} />+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('heteroAgent.codexQuota.resetCreditsUnavailable')}+ </Text>+ </Flexbox>+ </Flexbox>+ )}+ </>+ ) : (+ <div className={styles.emptyState}>{t('heteroAgent.codexQuota.noData')}</div>+ )}+ </Flexbox>+ );++ const trigger = (+ <button+ aria-expanded={open}+ aria-haspopup="dialog"+ aria-label={t('heteroAgent.codexQuota.tooltip')}+ className={cx(styles.trigger, open && styles.triggerOpen)}+ type="button"+ >+ <Icon icon={GaugeIcon} size={14} />+ {sessionLeftPercent !== undefined && (+ <span className={styles.value}>+ {t('heteroAgent.codexQuota.compactLeft', { percent: sessionLeftPercent })}+ </span>+ )}+ <Icon icon={ChevronDownIcon} size={12} />+ </button>+ );++ return (+ <Popover+ content={content}+ open={open}+ placement="topRight"+ trigger="click"+ styles={{+ content: {+ border: `1px solid ${cssVar.colorBorderSecondary}`,+ borderRadius: cssVar.borderRadiusLG,+ padding: 10,+ },+ }}+ onOpenChange={handleOpenChange}+ >+ <div>+ {open ? (+ trigger+ ) : (+ <Tooltip title={t('heteroAgent.codexQuota.tooltip')}>{trigger}</Tooltip>+ )}+ </div>+ </Popover>+ );+});++CodexQuotaMenu.displayName = 'CodexQuotaMenu';++export default CodexQuotaMenu;diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsxindex 785084fc3c4..97ca688212d 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx@@ -9,9 +9,12 @@ import { useTranslation } from 'react-i18next';import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControls';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';+import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';+import CodexQuotaMenu from './CodexQuotaMenu';+const styles = createStaticStyles(({ css }) => ({bar: css`container: runtimebar / inline-size;@@ -65,6 +68,7 @@ const HeteroControlBar = memo(() => {// All hooks must be called unconditionally (Rules of Hooks)const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));// On web there's no full-access badge / skeleton — just the workspace controls// (the cloud repo switcher is rendered inside WorkspaceControls). The CLI@@ -96,6 +100,12 @@ const HeteroControlBar = memo(() => {<span className={styles.fullAccessLabel}>{tChat('heteroAgent.fullAccess.label')}</span></div>);+ const shouldShowCodexQuota =+ agencyConfig?.heterogeneousProvider?.type === 'codex' &&+ resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ isHetero: true,+ }) === 'local';return (<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>@@ -103,6 +113,12 @@ const HeteroControlBar = memo(() => {<WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox><Flexbox horizontal align={'center'} className={styles.rightGroup} gap={4}>+ {shouldShowCodexQuota && (+ <CodexQuotaMenu+ command={agencyConfig.heterogeneousProvider?.command}+ env={agencyConfig.heterogeneousProvider?.env}+ />+ )}<Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip></Flexbox></Flexbox>diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex 560ce4708e5..f06eca7a427 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -1,3 +1,5 @@+import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';+import { ensureElectronIpc } from '@/utils/electron/ipc';/**@@ -40,6 +42,13 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.getSessionInfo({ sessionId });}+ async getCodexQuota(params?: {+ command?: string;+ env?: Record<string, string>;+ }): Promise<CodexQuotaSnapshot> {+ return this.ipc.heterogeneousAgent.getCodexQuota(params);+ }+/*** Submit the user's answer (or cancellation) for a pending CC* AskUserQuestion intervention. The main process routes it to the