diff --git a/src/main/codex-accounts/service.ts b/src/main/codex-accounts/service.ts new file mode 100644 index 000000000..6362d8c26 --- /dev/null +++ b/src/main/codex-accounts/service.ts @@ -0,0 +1,437 @@ +/* eslint-disable max-lines -- Why: this service intentionally keeps Codex +account lifecycle, path safety, login, and identity parsing in one audited +main-process module so the managed-account boundary stays explicit. */ +import { randomUUID } from 'node:crypto' +import { spawn } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { join, relative, resolve, sep } from 'node:path' +import { app } from 'electron' +import type { + CodexManagedAccount, + CodexManagedAccountSummary, + CodexRateLimitAccountsState +} from '../../shared/types' +import type { Store } from '../persistence' +import type { RateLimitService } from '../rate-limits/service' + +const LOGIN_TIMEOUT_MS = 120_000 +const MAX_LOGIN_OUTPUT_CHARS = 4_000 + +type CodexOAuthCredentials = { + idToken: string | null + accountId: string | null +} + +type ResolvedCodexIdentity = { + email: string | null + providerAccountId: string | null + workspaceLabel: string | null + workspaceAccountId: string | null +} + +export class CodexAccountService { + constructor( + private readonly store: Store, + private readonly rateLimits: RateLimitService + ) {} + + listAccounts(): CodexRateLimitAccountsState { + this.normalizeActiveSelection() + return this.getSnapshot() + } + + async addAccount(): Promise { + const accountId = randomUUID() + const managedHomePath = this.createManagedHome(accountId) + + try { + await this.runCodexLogin(managedHomePath) + const identity = this.readIdentityFromHome(managedHomePath) + if (!identity.email) { + throw new Error('Codex login completed, but Orca could not resolve the account email.') + } + + const now = Date.now() + const account: CodexManagedAccount = { + id: accountId, + email: identity.email, + managedHomePath, + providerAccountId: identity.providerAccountId, + workspaceLabel: identity.workspaceLabel, + workspaceAccountId: identity.workspaceAccountId, + createdAt: now, + updatedAt: now, + lastAuthenticatedAt: now + } + + const settings = this.store.getSettings() + this.store.updateSettings({ + codexManagedAccounts: [...settings.codexManagedAccounts, account], + activeCodexManagedAccountId: account.id + }) + + await this.rateLimits.refreshForCodexAccountChange() + return this.getSnapshot() + } catch (error) { + this.safeRemoveManagedHome(managedHomePath) + throw error + } + } + + async reauthenticateAccount(accountId: string): Promise { + const account = this.requireAccount(accountId) + const managedHomePath = this.assertManagedHomePath(account.managedHomePath) + + await this.runCodexLogin(managedHomePath) + const identity = this.readIdentityFromHome(managedHomePath) + if (!identity.email) { + throw new Error('Codex login completed, but Orca could not resolve the account email.') + } + + const settings = this.store.getSettings() + const now = Date.now() + const updatedAccounts = settings.codexManagedAccounts.map((entry) => + entry.id === accountId + ? { + ...entry, + email: identity.email!, + providerAccountId: identity.providerAccountId, + workspaceLabel: identity.workspaceLabel, + workspaceAccountId: identity.workspaceAccountId, + updatedAt: now, + lastAuthenticatedAt: now + } + : entry + ) + + this.store.updateSettings({ + codexManagedAccounts: updatedAccounts + }) + + // Why: re-auth can change which actual Codex identity the managed home + // points at. Force a fresh read immediately so the status bar cannot keep + // showing the previous account's quota under the updated label. + await this.rateLimits.refreshForCodexAccountChange() + return this.getSnapshot() + } + + async removeAccount(accountId: string): Promise { + const account = this.requireAccount(accountId) + const settings = this.store.getSettings() + const nextAccounts = settings.codexManagedAccounts.filter((entry) => entry.id !== accountId) + const nextActiveId = + settings.activeCodexManagedAccountId === accountId + ? null + : settings.activeCodexManagedAccountId + + this.store.updateSettings({ + codexManagedAccounts: nextAccounts, + activeCodexManagedAccountId: nextActiveId + }) + + this.safeRemoveManagedHome(account.managedHomePath) + await this.rateLimits.refreshForCodexAccountChange() + return this.getSnapshot() + } + + async selectAccount(accountId: string | null): Promise { + if (accountId !== null) { + this.requireAccount(accountId) + } + + this.store.updateSettings({ + activeCodexManagedAccountId: accountId + }) + + await this.rateLimits.refreshForCodexAccountChange() + return this.getSnapshot() + } + + getSelectedManagedHomePath(): string | null { + const account = this.getActiveAccount() + if (!account) { + return null + } + + try { + return this.assertManagedHomePath(account.managedHomePath) + } catch (error) { + // Why: if the selected managed home was deleted or tampered with outside + // Orca, the safest recovery is to fall back to the ambient system Codex + // login immediately rather than keeping a broken active selection around. + this.store.updateSettings({ activeCodexManagedAccountId: null }) + console.warn('[codex-accounts] Ignoring invalid managed home path:', error) + return null + } + } + + private getSnapshot(): CodexRateLimitAccountsState { + const settings = this.store.getSettings() + return { + accounts: settings.codexManagedAccounts + .map((account) => this.toSummary(account)) + .sort((a, b) => b.updatedAt - a.updatedAt), + activeAccountId: settings.activeCodexManagedAccountId + } + } + + private getActiveAccount(): CodexManagedAccount | null { + this.normalizeActiveSelection() + const settings = this.store.getSettings() + if (!settings.activeCodexManagedAccountId) { + return null + } + return ( + settings.codexManagedAccounts.find( + (entry) => entry.id === settings.activeCodexManagedAccountId + ) ?? null + ) + } + + private toSummary(account: CodexManagedAccount): CodexManagedAccountSummary { + return { + id: account.id, + email: account.email, + providerAccountId: account.providerAccountId ?? null, + workspaceLabel: account.workspaceLabel ?? null, + workspaceAccountId: account.workspaceAccountId ?? null, + createdAt: account.createdAt, + updatedAt: account.updatedAt, + lastAuthenticatedAt: account.lastAuthenticatedAt + } + } + + private requireAccount(accountId: string): CodexManagedAccount { + const settings = this.store.getSettings() + const account = settings.codexManagedAccounts.find((entry) => entry.id === accountId) + if (!account) { + throw new Error('That Codex rate limit account no longer exists.') + } + return account + } + + private normalizeActiveSelection(): void { + const settings = this.store.getSettings() + if (!settings.activeCodexManagedAccountId) { + return + } + const hasActiveAccount = settings.codexManagedAccounts.some( + (entry) => entry.id === settings.activeCodexManagedAccountId + ) + if (!hasActiveAccount) { + this.store.updateSettings({ activeCodexManagedAccountId: null }) + } + } + + private createManagedHome(accountId: string): string { + const managedHomePath = join(this.getManagedAccountsRoot(), accountId, 'home') + mkdirSync(managedHomePath, { recursive: true }) + // Why: Codex expects CODEX_HOME to be a concrete directory it can own. We + // pre-create the directory and leave a marker so future cleanup code can + // prove the path belongs to Orca before deleting anything. + writeFileSync(join(managedHomePath, '.orca-managed-home'), `${accountId}\n`, 'utf-8') + return this.assertManagedHomePath(managedHomePath) + } + + private getManagedAccountsRoot(): string { + const root = join(app.getPath('userData'), 'codex-accounts') + mkdirSync(root, { recursive: true }) + return root + } + + private assertManagedHomePath(candidatePath: string): string { + const rootPath = this.getManagedAccountsRoot() + const resolvedCandidate = resolve(candidatePath) + const resolvedRoot = resolve(rootPath) + + // realpath() requires the leaf to exist. For pre-login add flow we create + // the home directory first so the containment check still verifies the + // canonical on-disk target rather than trusting persisted text blindly. + const canonicalCandidate = realpathSync(resolvedCandidate) + const canonicalRoot = realpathSync(resolvedRoot) + const relativePath = relative(canonicalRoot, canonicalCandidate) + const escaped = + relativePath === '' || + relativePath === '.' || + relativePath.startsWith('..') || + relativePath.includes(`..${sep}`) + + if (escaped) { + throw new Error('Managed Codex home escaped Orca account storage.') + } + + if (!existsSync(join(canonicalCandidate, '.orca-managed-home'))) { + throw new Error('Managed Codex home is missing Orca ownership marker.') + } + + return canonicalCandidate + } + + private safeRemoveManagedHome(candidatePath: string): void { + let managedHomePath: string + try { + managedHomePath = this.assertManagedHomePath(candidatePath) + } catch (error) { + console.warn('[codex-accounts] Refusing to remove untrusted managed home:', error) + return + } + + rmSync(managedHomePath, { recursive: true, force: true }) + } + + private async runCodexLogin(managedHomePath: string): Promise { + await new Promise((resolvePromise, rejectPromise) => { + const child = spawn('codex', ['login'], { + stdio: ['ignore', 'pipe', 'pipe'], + env: { + ...process.env, + CODEX_HOME: managedHomePath + } + }) + + let settled = false + let output = '' + const appendOutput = (chunk: Buffer): void => { + output = `${output}${chunk.toString()}` + if (output.length > MAX_LOGIN_OUTPUT_CHARS) { + output = output.slice(-MAX_LOGIN_OUTPUT_CHARS) + } + } + + const settle = (callback: () => void): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + callback() + } + + const timeout = setTimeout(() => { + child.kill() + settle(() => { + rejectPromise(new Error('Codex sign-in took too long to finish. Please try again.')) + }) + }, LOGIN_TIMEOUT_MS) + + child.stdout.on('data', appendOutput) + child.stderr.on('data', appendOutput) + + child.on('error', (error) => { + settle(() => { + const cause = (error as NodeJS.ErrnoException).code === 'ENOENT' + rejectPromise(new Error(cause ? 'Codex CLI not found.' : error.message)) + }) + }) + + child.on('close', (code) => { + settle(() => { + if (code === 0) { + resolvePromise() + return + } + const trimmedOutput = output.trim() + rejectPromise( + new Error( + trimmedOutput + ? `Codex login failed: ${trimmedOutput}` + : `Codex login exited with code ${code ?? 'unknown'}.` + ) + ) + }) + }) + }) + } + + private readIdentityFromHome(managedHomePath: string): ResolvedCodexIdentity { + const credentials = this.loadOAuthCredentials(managedHomePath) + const payload = credentials.idToken ? this.parseJwtPayload(credentials.idToken) : null + const authClaims = this.readRecordClaim(payload, 'https://api.openai.com/auth') + const profileClaims = this.readRecordClaim(payload, 'https://api.openai.com/profile') + + return { + email: this.normalizeField( + this.readStringClaim(payload, 'email') ?? this.readStringClaim(profileClaims, 'email') + ), + providerAccountId: this.normalizeField( + credentials.accountId ?? + this.readStringClaim(authClaims, 'chatgpt_account_id') ?? + this.readStringClaim(payload, 'chatgpt_account_id') + ), + workspaceLabel: this.normalizeField( + this.readStringClaim(authClaims, 'workspace_name') ?? + this.readStringClaim(profileClaims, 'workspace_name') + ), + workspaceAccountId: this.normalizeField( + this.readStringClaim(authClaims, 'workspace_account_id') ?? + credentials.accountId ?? + this.readStringClaim(payload, 'chatgpt_account_id') + ) + } + } + + private loadOAuthCredentials(managedHomePath: string): CodexOAuthCredentials { + const authFilePath = join(this.assertManagedHomePath(managedHomePath), 'auth.json') + const raw = JSON.parse(readFileSync(authFilePath, 'utf-8')) as Record + + if (typeof raw.OPENAI_API_KEY === 'string' && raw.OPENAI_API_KEY.trim() !== '') { + return { + idToken: null, + accountId: null + } + } + + const tokens = this.readRecordClaim(raw, 'tokens') + return { + idToken: this.normalizeField( + this.readStringClaim(tokens, 'id_token') ?? this.readStringClaim(tokens, 'idToken') + ), + accountId: this.normalizeField( + this.readStringClaim(tokens, 'account_id') ?? this.readStringClaim(tokens, 'accountId') + ) + } + } + + private parseJwtPayload(token: string): Record | null { + const parts = token.split('.') + if (parts.length < 2) { + return null + } + + let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/') + while (payload.length % 4 !== 0) { + payload += '=' + } + + try { + const json = Buffer.from(payload, 'base64').toString('utf-8') + return JSON.parse(json) as Record + } catch { + return null + } + } + + private readRecordClaim( + value: Record | null, + key: string + ): Record | null { + const claim = value?.[key] + if (!claim || typeof claim !== 'object' || Array.isArray(claim)) { + return null + } + return claim as Record + } + + private readStringClaim(value: Record | null, key: string): string | null { + const claim = value?.[key] + return typeof claim === 'string' ? claim : null + } + + private normalizeField(value: string | null | undefined): string | null { + if (!value) { + return null + } + const trimmed = value.trim() + return trimmed === '' ? null : trimmed + } +} diff --git a/src/main/index.ts b/src/main/index.ts index bad3514c4..99dc44509 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -21,15 +21,19 @@ import { installUncaughtPipeErrorGuard, patchPackagedProcessPath } from './startup/configure-process' +import { RateLimitService } from './rate-limits/service' import { attachMainWindowServices } from './window/attach-main-window-services' import { createMainWindow } from './window/createMainWindow' +import { CodexAccountService } from './codex-accounts/service' let mainWindow: BrowserWindow | null = null let store: Store | null = null let stats: StatsCollector | null = null let claudeUsage: ClaudeUsageStore | null = null let codexUsage: CodexUsageStore | null = null +let codexAccounts: CodexAccountService | null = null let runtime: OrcaRuntimeService | null = null +let rateLimits: RateLimitService | null = null let runtimeRpc: OrcaRuntimeRpcServer | null = null installUncaughtPipeErrorGuard() @@ -64,10 +68,29 @@ function openMainWindow(): BrowserWindow { if (!codexUsage) { throw new Error('Codex usage store must be initialized before opening the main window') } + if (!rateLimits) { + throw new Error('Rate limit service must be initialized before opening the main window') + } + if (!codexAccounts) { + throw new Error('Codex account service must be initialized before opening the main window') + } const window = createMainWindow(store) - registerCoreHandlers(store, runtime, stats, claudeUsage, codexUsage, window.webContents.id) - attachMainWindowServices(window, store, runtime) + registerCoreHandlers( + store, + runtime, + stats, + claudeUsage, + codexUsage, + codexAccounts, + rateLimits, + window.webContents.id + ) + attachMainWindowServices(window, store, runtime, () => + codexAccounts!.getSelectedManagedHomePath() + ) + rateLimits.attach(window) + rateLimits.start() window.on('closed', () => { if (mainWindow === window) { mainWindow = null @@ -90,6 +113,9 @@ app.whenReady().then(async () => { stats = new StatsCollector() claudeUsage = new ClaudeUsageStore(store) codexUsage = new CodexUsageStore(store) + rateLimits = new RateLimitService() + codexAccounts = new CodexAccountService(store, rateLimits) + rateLimits.setCodexHomePathResolver(() => codexAccounts!.getSelectedManagedHomePath()) runtime = new OrcaRuntimeService(store, stats) nativeTheme.themeSource = store.getSettings().theme ?? 'system' @@ -106,6 +132,9 @@ app.whenReady().then(async () => { }, onZoomReset: () => { mainWindow?.webContents.send('terminal:zoom', 'reset') + }, + onToggleStatusBar: () => { + mainWindow?.webContents.send('ui:toggleStatusBar') } }) runtimeRpc = new OrcaRuntimeRpcServer({ @@ -145,6 +174,7 @@ app.on('before-quit', () => { // are still running. killAllPty() does not call runtime.onPtyExit(), // so without this ordering, running agents would produce orphaned // agent_start events with no matching stops. + rateLimits?.stop() stats?.flush() killAllPty() void closeAllWatchers() diff --git a/src/main/ipc/codex-accounts.ts b/src/main/ipc/codex-accounts.ts new file mode 100644 index 000000000..12b132eca --- /dev/null +++ b/src/main/ipc/codex-accounts.ts @@ -0,0 +1,16 @@ +import { ipcMain } from 'electron' +import type { CodexAccountService } from '../codex-accounts/service' + +export function registerCodexAccountHandlers(codexAccounts: CodexAccountService): void { + ipcMain.handle('codexAccounts:list', () => codexAccounts.listAccounts()) + ipcMain.handle('codexAccounts:add', () => codexAccounts.addAccount()) + ipcMain.handle('codexAccounts:reauthenticate', (_event, args: { accountId: string }) => + codexAccounts.reauthenticateAccount(args.accountId) + ) + ipcMain.handle('codexAccounts:remove', (_event, args: { accountId: string }) => + codexAccounts.removeAccount(args.accountId) + ) + ipcMain.handle('codexAccounts:select', (_event, args: { accountId: string | null }) => + codexAccounts.selectAccount(args.accountId) + ) +} diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 6fba21532..c5f84fa22 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -84,7 +84,8 @@ describe('registerPtyHandlers', () => { /** Helper: trigger pty:spawn and return the env passed to node-pty. */ function spawnAndGetEnv( argsEnv?: Record, - processEnvOverrides?: Record + processEnvOverrides?: Record, + getSelectedCodexHomePath?: () => string | null ): Record { const savedEnv: Record = {} if (processEnvOverrides) { @@ -102,7 +103,7 @@ describe('registerPtyHandlers', () => { // Clear previously registered handlers so re-registration doesn't // accumulate stale state across calls within one test. handlers.clear() - registerPtyHandlers(mainWindow as never) + registerPtyHandlers(mainWindow as never, undefined, getSelectedCodexHomePath) handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, @@ -143,6 +144,16 @@ describe('registerPtyHandlers', () => { expect(env.COLORTERM).toBe('truecolor') expect(env.TERM_PROGRAM).toBe('Orca') }) + + it('injects the selected Codex home into Orca terminal PTYs', () => { + const env = spawnAndGetEnv(undefined, undefined, () => '/tmp/orca-codex-home') + expect(env.CODEX_HOME).toBe('/tmp/orca-codex-home') + }) + + it('leaves ambient CODEX_HOME untouched when system default is selected', () => { + const env = spawnAndGetEnv(undefined, { CODEX_HOME: '/tmp/system-codex-home' }, () => null) + expect(env.CODEX_HOME).toBe('/tmp/system-codex-home') + }) }) it('rejects missing WSL worktree cwd instead of validating only the fallback Windows cwd', () => { diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index faf0ecb07..2943433c9 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -1,3 +1,8 @@ +/* eslint-disable max-lines -- Why: PTY IPC is intentionally centralized in one +main-process module so spawn-time environment scoping, lifecycle cleanup, +foreground-process inspection, and renderer IPC stay behind a single audited +boundary. Splitting it by line count would scatter tightly coupled terminal +process behavior across files without a cleaner ownership seam. */ import { basename } from 'path' import { existsSync, accessSync, statSync, chmodSync, constants as fsConstants } from 'fs' import { type BrowserWindow, ipcMain } from 'electron' @@ -22,7 +27,8 @@ let didEnsureSpawnHelperExecutable = false function getShellValidationError(shellPath: string): string | null { if (!existsSync(shellPath)) { return ( - `Shell "${shellPath}" does not exist. ` + `Set a valid SHELL environment variable or install zsh/bash.` + `Shell "${shellPath}" does not exist. ` + + `Set a valid SHELL environment variable or install zsh/bash.` ) } try { @@ -41,15 +47,18 @@ function ensureNodePtySpawnHelperExecutable(): void { try { const unixTerminalPath = require.resolve('node-pty/lib/unixTerminal.js') - const packageRoot = basename(unixTerminalPath) === 'unixTerminal.js' - ? unixTerminalPath.replace(/[/\\]lib[/\\]unixTerminal\.js$/, '') - : unixTerminalPath + const packageRoot = + basename(unixTerminalPath) === 'unixTerminal.js' + ? unixTerminalPath.replace(/[/\\]lib[/\\]unixTerminal\.js$/, '') + : unixTerminalPath const candidates = [ `${packageRoot}/build/Release/spawn-helper`, `${packageRoot}/build/Debug/spawn-helper`, `${packageRoot}/prebuilds/${process.platform}-${process.arch}/spawn-helper` ].map((candidate) => - candidate.replace('app.asar/', 'app.asar.unpacked/').replace('node_modules.asar/', 'node_modules.asar.unpacked/') + candidate + .replace('app.asar/', 'app.asar.unpacked/') + .replace('node_modules.asar/', 'node_modules.asar.unpacked/') ) for (const candidate of candidates) { @@ -74,13 +83,18 @@ function ensureNodePtySpawnHelperExecutable(): void { } } -export function registerPtyHandlers(mainWindow: BrowserWindow, runtime?: OrcaRuntimeService): void { +export function registerPtyHandlers( + mainWindow: BrowserWindow, + runtime?: OrcaRuntimeService, + getSelectedCodexHomePath?: () => string | null +): void { // Remove any previously registered handlers so we can re-register them // (e.g. when macOS re-activates the app and creates a new window). ipcMain.removeHandler('pty:spawn') ipcMain.removeHandler('pty:resize') ipcMain.removeHandler('pty:kill') ipcMain.removeHandler('pty:hasChildProcesses') + ipcMain.removeHandler('pty:getForegroundProcess') ipcMain.removeAllListeners('pty:write') // Kill orphaned PTY processes from previous page loads when the renderer reloads. @@ -200,6 +214,7 @@ export function registerPtyHandlers(mainWindow: BrowserWindow, runtime?: OrcaRun throw new Error(`Working directory "${validationCwd}" is not a directory.`) } + const selectedCodexHomePath = getSelectedCodexHomePath?.() ?? null const spawnEnv = { ...process.env, ...args.env, @@ -209,6 +224,15 @@ export function registerPtyHandlers(mainWindow: BrowserWindow, runtime?: OrcaRun FORCE_HYPERLINK: '1' } as Record + // Why: the selected Codex account should affect Codex launched inside + // Orca terminals too, not just Orca's background quota fetches. Inject + // the managed CODEX_HOME only into this PTY environment so the override + // stays scoped to Orca terminals instead of mutating the app process or + // the user's external shells. + if (selectedCodexHomePath) { + spawnEnv.CODEX_HOME = selectedCodexHomePath + } + // Why: When Electron is launched from Finder (not a terminal), the process // does not inherit the user's shell locale settings. Without an explicit // UTF-8 locale, multi-byte characters (e.g. em dashes U+2014) are @@ -245,7 +269,9 @@ export function registerPtyHandlers(mainWindow: BrowserWindow, runtime?: OrcaRun // should not brick Orca terminals. Fall back to system shells so the // user still gets a working terminal while the bad SHELL config remains. const configuredShellPath = shellPath - const fallbackShells = ['/bin/zsh', '/bin/bash', '/bin/sh'].filter((s) => s !== configuredShellPath) + const fallbackShells = ['/bin/zsh', '/bin/bash', '/bin/sh'].filter( + (s) => s !== configuredShellPath + ) for (const fallback of fallbackShells) { if (getShellValidationError(fallback)) { continue @@ -373,6 +399,23 @@ export function registerPtyHandlers(mainWindow: BrowserWindow, runtime?: OrcaRun return false } }) + + ipcMain.handle('pty:getForegroundProcess', (_event, args: { id: string }): string | null => { + const proc = ptyProcesses.get(args.id) + if (!proc) { + return null + } + try { + // Why: live Codex-session actions must key off the PTY foreground process, + // not the tab title. Agent CLIs do not reliably emit stable OSC titles, + // so title-based detection misses real Codex sessions that still need a + // restart after account switching. + return proc.process || null + } catch { + // .process can throw if the PTY fd is already closed. + return null + } + }) } /** diff --git a/src/main/ipc/rate-limits.ts b/src/main/ipc/rate-limits.ts new file mode 100644 index 000000000..1a4634e8f --- /dev/null +++ b/src/main/ipc/rate-limits.ts @@ -0,0 +1,10 @@ +import { ipcMain } from 'electron' +import type { RateLimitService } from '../rate-limits/service' + +export function registerRateLimitHandlers(rateLimits: RateLimitService): void { + ipcMain.handle('rateLimits:get', () => rateLimits.getState()) + ipcMain.handle('rateLimits:refresh', () => rateLimits.refresh()) + ipcMain.handle('rateLimits:setPollingInterval', (_event, ms: number) => + rateLimits.setPollingInterval(ms) + ) +} diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index b8a90c7a7..8ae4724af 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -14,8 +14,10 @@ const { registerUIHandlersMock, registerFilesystemHandlersMock, registerRuntimeHandlersMock, + registerCodexAccountHandlersMock, registerClipboardHandlersMock, registerUpdaterHandlersMock, + registerRateLimitHandlersMock, registerBrowserHandlersMock, setTrustedBrowserRendererWebContentsIdMock, registerFilesystemWatcherHandlersMock @@ -33,8 +35,10 @@ const { registerUIHandlersMock: vi.fn(), registerFilesystemHandlersMock: vi.fn(), registerRuntimeHandlersMock: vi.fn(), + registerCodexAccountHandlersMock: vi.fn(), registerClipboardHandlersMock: vi.fn(), registerUpdaterHandlersMock: vi.fn(), + registerRateLimitHandlersMock: vi.fn(), registerBrowserHandlersMock: vi.fn(), setTrustedBrowserRendererWebContentsIdMock: vi.fn(), registerFilesystemWatcherHandlersMock: vi.fn() @@ -92,10 +96,18 @@ vi.mock('./filesystem-watcher', () => ({ registerFilesystemWatcherHandlers: registerFilesystemWatcherHandlersMock })) +vi.mock('./rate-limits', () => ({ + registerRateLimitHandlers: registerRateLimitHandlersMock +})) + vi.mock('./runtime', () => ({ registerRuntimeHandlers: registerRuntimeHandlersMock })) +vi.mock('./codex-accounts', () => ({ + registerCodexAccountHandlers: registerCodexAccountHandlersMock +})) + vi.mock('../window/attach-main-window-services', () => ({ registerClipboardHandlers: registerClipboardHandlersMock, registerUpdaterHandlers: registerUpdaterHandlersMock @@ -123,8 +135,10 @@ describe('registerCoreHandlers', () => { registerUIHandlersMock.mockReset() registerFilesystemHandlersMock.mockReset() registerRuntimeHandlersMock.mockReset() + registerCodexAccountHandlersMock.mockReset() registerClipboardHandlersMock.mockReset() registerUpdaterHandlersMock.mockReset() + registerRateLimitHandlersMock.mockReset() registerBrowserHandlersMock.mockReset() setTrustedBrowserRendererWebContentsIdMock.mockReset() registerFilesystemWatcherHandlersMock.mockReset() @@ -136,17 +150,23 @@ describe('registerCoreHandlers', () => { const stats = { marker: 'stats' } const claudeUsage = { marker: 'claudeUsage' } const codexUsage = { marker: 'codexUsage' } + const codexAccounts = { marker: 'codexAccounts' } + const rateLimits = { marker: 'rateLimits' } registerCoreHandlers( store as never, runtime as never, stats as never, claudeUsage as never, - codexUsage as never + codexUsage as never, + codexAccounts as never, + rateLimits as never ) expect(registerClaudeUsageHandlersMock).toHaveBeenCalledWith(claudeUsage) expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage) + expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith(codexAccounts) + expect(registerRateLimitHandlersMock).toHaveBeenCalledWith(rateLimits) expect(registerGitHubHandlersMock).toHaveBeenCalledWith(store, stats) expect(registerStatsHandlersMock).toHaveBeenCalledWith(stats) expect(registerNotificationHandlersMock).toHaveBeenCalledWith(store) diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 14f4969b0..b8b4c522d 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -9,6 +9,7 @@ import { registerClaudeUsageHandlers } from './claude-usage' import { registerCodexUsageHandlers } from './codex-usage' import { registerGitHubHandlers } from './github' import { registerStatsHandlers } from './stats' +import { registerRateLimitHandlers } from './rate-limits' import { registerRuntimeHandlers } from './runtime' import { registerNotificationHandlers } from './notifications' import { setTrustedBrowserRendererWebContentsId } from './browser' @@ -17,6 +18,7 @@ import { registerSettingsHandlers } from './settings' import { registerBrowserHandlers } from './browser' import { registerShellHandlers } from './shell' import { registerUIHandlers } from './ui' +import { registerCodexAccountHandlers } from './codex-accounts' import { warmSystemFontFamilies } from '../system-fonts' import { registerClipboardHandlers, @@ -24,6 +26,8 @@ import { } from '../window/attach-main-window-services' import type { ClaudeUsageStore } from '../claude-usage/store' import type { CodexUsageStore } from '../codex-usage/store' +import type { RateLimitService } from '../rate-limits/service' +import type { CodexAccountService } from '../codex-accounts/service' export function registerCoreHandlers( store: Store, @@ -31,6 +35,8 @@ export function registerCoreHandlers( stats: StatsCollector, claudeUsage: ClaudeUsageStore, codexUsage: CodexUsageStore, + codexAccounts: CodexAccountService, + rateLimits: RateLimitService, mainWindowWebContentsId: number | null = null ): void { setTrustedBrowserRendererWebContentsId(mainWindowWebContentsId) @@ -38,6 +44,8 @@ export function registerCoreHandlers( registerPreflightHandlers() registerClaudeUsageHandlers(claudeUsage) registerCodexUsageHandlers(codexUsage) + registerCodexAccountHandlers(codexAccounts) + registerRateLimitHandlers(rateLimits) registerGitHubHandlers(store, stats) registerStatsHandlers(stats) registerNotificationHandlers(store) diff --git a/src/main/menu/register-app-menu.test.ts b/src/main/menu/register-app-menu.test.ts index a3d3d6a56..f53bbfa21 100644 --- a/src/main/menu/register-app-menu.test.ts +++ b/src/main/menu/register-app-menu.test.ts @@ -27,7 +27,8 @@ function buildMenuOptions() { onOpenSettings: vi.fn(), onZoomIn: vi.fn(), onZoomOut: vi.fn(), - onZoomReset: vi.fn() + onZoomReset: vi.fn(), + onToggleStatusBar: vi.fn() } } diff --git a/src/main/menu/register-app-menu.ts b/src/main/menu/register-app-menu.ts index 23ef09cd5..49fb180b1 100644 --- a/src/main/menu/register-app-menu.ts +++ b/src/main/menu/register-app-menu.ts @@ -6,6 +6,7 @@ type RegisterAppMenuOptions = { onZoomIn: () => void onZoomOut: () => void onZoomReset: () => void + onToggleStatusBar: () => void } export function registerAppMenu({ @@ -13,7 +14,8 @@ export function registerAppMenu({ onCheckForUpdates, onZoomIn, onZoomOut, - onZoomReset + onZoomReset, + onToggleStatusBar }: RegisterAppMenuOptions): void { const reloadFocusedWindow = (ignoreCache: boolean): void => { const webContents = BrowserWindow.getFocusedWindow()?.webContents @@ -116,7 +118,12 @@ export function registerAppMenu({ label: `Open Worktree Palette\t${process.platform === 'darwin' ? 'Cmd+J' : 'Ctrl+Shift+J'}` }, { type: 'separator' }, - { role: 'togglefullscreen' } + { role: 'togglefullscreen' }, + { type: 'separator' }, + { + label: 'Toggle Status Bar', + click: () => onToggleStatusBar() + } ] }, { diff --git a/src/main/rate-limits/claude-fetcher.ts b/src/main/rate-limits/claude-fetcher.ts new file mode 100644 index 000000000..f7ff64328 --- /dev/null +++ b/src/main/rate-limits/claude-fetcher.ts @@ -0,0 +1,261 @@ +import { readFile } from 'node:fs/promises' +import { execFile } from 'node:child_process' +import { homedir } from 'node:os' +import path from 'node:path' +import type { ProviderRateLimits, RateLimitWindow } from '../../shared/rate-limit-types' +import { fetchViaPty } from './claude-pty' + +const OAUTH_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage' +const OAUTH_BETA_HEADER = 'oauth-2025-04-20' +const API_TIMEOUT_MS = 10_000 + +// --------------------------------------------------------------------------- +// Credential reading — tries multiple sources for an OAuth bearer token +// --------------------------------------------------------------------------- + +type ClaudeCredentials = { + claudeAiOauth?: { + accessToken?: string + refreshToken?: string + expiresAt?: number // unix ms + } +} + +type KeychainCredentials = { + claudeAiOauth?: { + accessToken?: string + expiresAt?: number + } +} + +/** + * Read OAuth token from macOS Keychain. + * Why: Claude Code v2.x+ stores OAuth credentials in the macOS Keychain + * under service "Claude Code-credentials". This is the standard location + * for Claude Max/Pro OAuth tokens. Only returns a token if the keychain + * entry has a `claudeAiOauth.accessToken` — API key users won't have this. + */ +async function readFromKeychain(): Promise { + if (process.platform !== 'darwin') { + return null + } + + return new Promise((resolve) => { + const user = process.env.USER ?? '' + if (!user) { + resolve(null) + return + } + + execFile( + 'security', + ['find-generic-password', '-s', 'Claude Code-credentials', '-a', user, '-w'], + { timeout: 3_000 }, + (err, stdout) => { + if (err || !stdout.trim()) { + resolve(null) + return + } + try { + const parsed = JSON.parse(stdout.trim()) as KeychainCredentials + const token = parsed?.claudeAiOauth?.accessToken + if (!token || typeof token !== 'string') { + resolve(null) + return + } + + const expiresAt = parsed.claudeAiOauth?.expiresAt + if (typeof expiresAt === 'number' && expiresAt < Date.now()) { + resolve(null) + return + } + + resolve(token) + } catch { + resolve(null) + } + } + ) + }) +} + +/** + * Read OAuth token from ~/.claude/.credentials.json (legacy path). + * Why: older Claude CLI versions store credentials in this plain JSON + * file. We keep it as a fallback for compatibility. + */ +async function readFromCredentialsFile(): Promise { + const credPath = path.join(homedir(), '.claude', '.credentials.json') + try { + const raw = await readFile(credPath, 'utf-8') + const parsed = JSON.parse(raw) as ClaudeCredentials + const token = parsed?.claudeAiOauth?.accessToken + if (!token || typeof token !== 'string') { + return null + } + + const expiresAt = parsed.claudeAiOauth?.expiresAt + if (typeof expiresAt === 'number' && expiresAt < Date.now()) { + return null + } + + return token + } catch { + return null + } +} + +/** + * Try credential sources that yield a genuine OAuth bearer token. + * Why: we intentionally do NOT read ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY + * here — those are API keys which return 401 on the OAuth usage endpoint. + * API-key users are served by the PTY fallback instead. + */ +async function readOAuthCredentials(): Promise { + // 1. macOS Keychain (Claude Max/Pro OAuth) + const fromKeychain = await readFromKeychain() + if (fromKeychain) { + return fromKeychain + } + + // 2. Legacy credentials file + const fromFile = await readFromCredentialsFile() + if (fromFile) { + return fromFile + } + + return null +} + +// --------------------------------------------------------------------------- +// OAuth API fetch +// --------------------------------------------------------------------------- + +type OAuthUsageWindow = { + utilization?: number + resets_at?: string +} + +type OAuthUsageResponse = { + five_hour?: OAuthUsageWindow + seven_day?: OAuthUsageWindow +} + +function parseResetDescription(isoString: string | undefined): string | null { + if (!isoString) { + return null + } + try { + const date = new Date(isoString) + if (isNaN(date.getTime())) { + return null + } + const now = new Date() + const isToday = date.toDateString() === now.toDateString() + if (isToday) { + return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' }) + } + return date.toLocaleDateString(undefined, { + weekday: 'short', + hour: 'numeric', + minute: '2-digit' + }) + } catch { + return null + } +} + +function mapWindow( + raw: OAuthUsageWindow | undefined, + windowMinutes: number +): RateLimitWindow | null { + if (!raw || typeof raw.utilization !== 'number') { + return null + } + return { + usedPercent: Math.min(100, Math.max(0, raw.utilization)), + windowMinutes, + resetsAt: raw.resets_at ? new Date(raw.resets_at).getTime() || null : null, + resetDescription: parseResetDescription(raw.resets_at) + } +} + +async function fetchViaOAuth(token: string): Promise { + const controller = new AbortController() + const timeout = setTimeout(() => controller.abort(), API_TIMEOUT_MS) + + try { + const res = await fetch(OAUTH_USAGE_URL, { + headers: { + Authorization: `Bearer ${token}`, + 'anthropic-beta': OAUTH_BETA_HEADER + }, + signal: controller.signal + }) + + if (!res.ok) { + throw new Error(`OAuth API returned ${res.status}`) + } + + const data = (await res.json()) as OAuthUsageResponse + + return { + provider: 'claude', + session: mapWindow(data.five_hour, 300), + weekly: mapWindow(data.seven_day, 10080), + updatedAt: Date.now(), + error: null, + status: 'ok' + } + } finally { + clearTimeout(timeout) + } +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +export async function fetchClaudeRateLimits(): Promise { + // Path A: try OAuth API if we have a genuine OAuth token + const oauthToken = await readOAuthCredentials() + if (oauthToken) { + try { + return await fetchViaOAuth(oauthToken) + } catch { + // OAuth API failed — fall through to PTY scraping as a backup + // for subscription users whose token may still be valid for the CLI. + } + + // Path B: PTY fallback — only for subscription plan users (Max/Pro) + // whose OAuth token we found but the API call failed. The CLI's + // `/usage` command is subscription-only, so there's no point + // attempting PTY for API key users. + try { + return await fetchViaPty() + } catch (err) { + const message = err instanceof Error ? err.message : 'Unknown error' + return { + provider: 'claude', + session: null, + weekly: null, + updatedAt: Date.now(), + error: message, + status: 'error' + } + } + } + + // No OAuth token found — user authenticates via API key. + // Why: plan usage limits (session/weekly) only exist for Claude Max/Pro + // subscription plans. API key users are billed per-token and don't have + // rate limit windows to display. + return { + provider: 'claude', + session: null, + weekly: null, + updatedAt: Date.now(), + error: 'No subscription plan — API key billing', + status: 'unavailable' + } +} diff --git a/src/main/rate-limits/claude-pty.ts b/src/main/rate-limits/claude-pty.ts new file mode 100644 index 000000000..22a8edbbd --- /dev/null +++ b/src/main/rate-limits/claude-pty.ts @@ -0,0 +1,292 @@ +import type { ProviderRateLimits, RateLimitWindow } from '../../shared/rate-limit-types' + +const PTY_TIMEOUT_MS = 25_000 + +// --------------------------------------------------------------------------- +// PTY fallback — spawn interactive `claude`, send `/usage`, parse the TUI +// --------------------------------------------------------------------------- + +// Why: these patterns match the Claude CLI's /usage TUI panel output. +// "Current session" shows a percent like "62% used" or "62% left". +// "Current week" section is similar. +const SESSION_RE = /current\s*session/i +const WEEKLY_RE = /current\s*week/i +const PERCENT_RE = /(\d{1,3})(?:\.\d+)?\s*%\s*(used|left|remaining|available)/i +const RESET_LINE_RE = /resets?\s+(?:at\s+|in\s+)?(.+)/i + +/** + * Extract percent-left from lines following a label match. + * Scans up to 12 lines after the label to find the associated percent. + */ +function extractPercentAfterLabel(lines: string[], labelRe: RegExp): number | null { + for (let i = 0; i < lines.length; i++) { + if (!labelRe.test(lines[i])) { + continue + } + // Scan next 12 lines for a percent + for (let j = i; j < Math.min(i + 12, lines.length); j++) { + const m = PERCENT_RE.exec(lines[j]) + if (m) { + const pct = parseFloat(m[1]) + const word = m[2].toLowerCase() + const isUsed = word === 'used' + return isUsed ? pct : 100 - pct + } + } + } + return null +} + +function extractResetAfterLabel(lines: string[], labelRe: RegExp): string | null { + for (let i = 0; i < lines.length; i++) { + if (!labelRe.test(lines[i])) { + continue + } + for (let j = i; j < Math.min(i + 14, lines.length); j++) { + const m = RESET_LINE_RE.exec(lines[j]) + if (m) { + return m[1].trim().replace(/[)]+$/, '') + } + } + } + return null +} + +function parsePtyUsage(output: string): { + session: RateLimitWindow | null + weekly: RateLimitWindow | null +} { + const lines = output.split(/\r?\n/) + + const sessionPct = extractPercentAfterLabel(lines, SESSION_RE) + const weeklyPct = extractPercentAfterLabel(lines, WEEKLY_RE) + + const session: RateLimitWindow | null = + sessionPct !== null + ? { + usedPercent: Math.min(100, Math.max(0, sessionPct)), + windowMinutes: 300, + resetsAt: null, + resetDescription: extractResetAfterLabel(lines, SESSION_RE) + } + : null + + const weekly: RateLimitWindow | null = + weeklyPct !== null + ? { + usedPercent: Math.min(100, Math.max(0, weeklyPct)), + windowMinutes: 10080, + resetsAt: null, + resetDescription: extractResetAfterLabel(lines, WEEKLY_RE) + } + : null + + return { session, weekly } +} + +// Why: these substrings indicate the /usage TUI panel has finished +// rendering. We stop collecting output once one appears, then allow +// a settle period for the rest of the content to flush. +const STOP_SUBSTRINGS = [ + 'Current week (all models)', + 'Current week (Opus)', + 'Current week (Sonnet only)', + 'Current week (Sonnet)', + 'Current session', + 'Failed to load usage data', + 'failed to load usage data' +] + +// Why: prompt detection is unreliable because the Claude CLI v2.x renders +// a status bar and TUI elements that push the `❯` prompt out of any +// reasonable detection window. Instead we wait a fixed 2s after spawning +// for the CLI to initialize, then send `/usage\r` directly. Command +// palette prompts ("Show plan usage limits") are auto-confirmed with Enter. +const COMMAND_PALETTE_RE = /show plan|usage limits/i +const TRUST_PROMPT_RE = /do you trust|trust the files|safety check/i +const RATE_LIMITED_RE = /rate limited\.?\s+please try again later/i +const LOAD_FAILED_RE = /failed to load usage data/i +const STARTUP_DELAY_MS = 2_000 +const SETTLE_AFTER_STOP_MS = 2_000 + +function describeClaudeUsageFailure(output: string): string { + if (RATE_LIMITED_RE.test(output)) { + return 'Claude usage is rate limited right now.' + } + + if (LOAD_FAILED_RE.test(output)) { + return 'Claude usage is unavailable right now.' + } + + // Why: parser failures are an implementation detail of Orca's PTY fallback. + // The UI should explain the user-visible outcome, not leak internal parsing + // mechanics that the user cannot act on. + return 'Claude usage is unavailable right now.' +} + +export async function fetchViaPty(): Promise { + const pty = await import('node-pty') + + return new Promise((resolve) => { + let output = '' + let resolved = false + let sentUsage = false + let stopDetected = false + + const term = pty.spawn('claude', [], { + name: 'xterm-256color', + cols: 120, + rows: 40, + env: { ...process.env, TERM: 'xterm-256color' } + }) + + const timeout = setTimeout(() => { + if (!resolved) { + resolved = true + term.kill() + // Even on timeout, try to parse whatever we collected + // eslint-disable-next-line no-control-regex + const clean = output.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + const { session, weekly } = parsePtyUsage(clean) + if (session || weekly) { + resolve({ + provider: 'claude', + session, + weekly, + updatedAt: Date.now(), + error: null, + status: 'ok' + }) + } else { + resolve({ + provider: 'claude', + session: null, + weekly: null, + updatedAt: Date.now(), + error: 'PTY timeout — /usage panel did not render', + status: 'error' + }) + } + } + }, PTY_TIMEOUT_MS) + + // Why: the Claude TUI may have scrollable panels or prompts. + // Sending Enter every 0.8s advances through them. + let enterInterval: ReturnType | null = null + + function startEnterPresses(): void { + if (enterInterval) { + return + } + enterInterval = setInterval(() => { + if (!resolved) { + term.write('\r') + } + }, 800) + } + + function finalize(): void { + if (resolved) { + return + } + resolved = true + clearTimeout(timeout) + if (enterInterval) { + clearInterval(enterInterval) + } + term.kill() + + // eslint-disable-next-line no-control-regex + const clean = output.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + const { session, weekly } = parsePtyUsage(clean) + + if (!session && !weekly) { + resolve({ + provider: 'claude', + session: null, + weekly: null, + updatedAt: Date.now(), + error: describeClaudeUsageFailure(clean), + status: 'error' + }) + } else { + resolve({ + provider: 'claude', + session, + weekly, + updatedAt: Date.now(), + error: null, + status: 'ok' + }) + } + } + + // Why: wait 2s for the CLI to initialize, then send `/usage\r` + // directly without detecting the prompt character (see comment above). + setTimeout(() => { + if (resolved) { + return + } + sentUsage = true + term.write('/usage\r') + startEnterPresses() + }, STARTUP_DELAY_MS) + + term.onData((data) => { + output += data + + // eslint-disable-next-line no-control-regex + const cleanChunk = data.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + + // Why: the Claude CLI may prompt for first-run setup (trust files, + // workspace directory). Auto-accept so we can reach /usage. + if (TRUST_PROMPT_RE.test(cleanChunk)) { + term.write('y\r') + return + } + + // Why: Claude CLI v2.x may show a command palette when `/usage` is + // entered, listing options like "Show plan usage limits". Auto-confirm + // by sending Enter when these prompts appear. + if (sentUsage && COMMAND_PALETTE_RE.test(cleanChunk)) { + term.write('\r') + } + + // Check if we've hit a stop substring indicating the panel rendered + if (sentUsage && !stopDetected) { + // eslint-disable-next-line no-control-regex + const clean = output.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + for (const sub of STOP_SUBSTRINGS) { + if (clean.includes(sub)) { + stopDetected = true + // Why: 2.0s settle time after detecting the stop substring + // allows the full panel to finish rendering. + setTimeout(finalize, SETTLE_AFTER_STOP_MS) + break + } + } + } + }) + + term.onExit(() => { + if (enterInterval) { + clearInterval(enterInterval) + } + if (!resolved) { + resolved = true + clearTimeout(timeout) + // eslint-disable-next-line no-control-regex + const clean = output.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + const { session, weekly } = parsePtyUsage(clean) + resolve({ + provider: 'claude', + session, + weekly, + updatedAt: Date.now(), + error: session || weekly ? null : 'CLI exited before /usage rendered', + status: session || weekly ? 'ok' : 'error' + }) + } + }) + }) +} diff --git a/src/main/rate-limits/codex-fetcher.ts b/src/main/rate-limits/codex-fetcher.ts new file mode 100644 index 000000000..d1383b7fc --- /dev/null +++ b/src/main/rate-limits/codex-fetcher.ts @@ -0,0 +1,398 @@ +/* eslint-disable max-lines -- Why: keeping both Codex RPC and PTY fallback +paths together in one file makes it easier to audit the protocol/parsing +differences and ensure account-scoped env handling stays identical. */ +import type { ProviderRateLimits, RateLimitWindow } from '../../shared/rate-limit-types' +import { spawn } from 'node:child_process' + +const RPC_TIMEOUT_MS = 10_000 +const PTY_TIMEOUT_MS = 15_000 + +export type FetchCodexRateLimitsOptions = { + codexHomePath?: string | null +} + +// --------------------------------------------------------------------------- +// JSON-RPC helpers +// --------------------------------------------------------------------------- + +type RpcResponse = { + id: number + result?: unknown + error?: { code: number; message: string } +} + +type RpcRateWindow = { + usedPercent?: number + windowDurationMins?: number + resetsAt?: number // Unix seconds +} + +type RpcRateLimitsResult = { + primary?: RpcRateWindow + secondary?: RpcRateWindow +} + +// Why: the Codex app-server wraps rate limit data inside a `rateLimits` key. +// The actual response shape is `{ rateLimits: { primary, secondary, ... } }`. +type RpcRateLimitsResponse = { + rateLimits?: RpcRateLimitsResult +} + +function buildRpcMessage(id: number, method: string, params?: unknown): string { + return `${JSON.stringify({ jsonrpc: '2.0', id, method, params: params ?? {} })}\n` +} + +function mapRpcWindow(raw: RpcRateWindow | undefined): RateLimitWindow | null { + if (!raw || typeof raw.usedPercent !== 'number') { + return null + } + let resetDescription: string | null = null + let resetsAt: number | null = null + + if (raw.resetsAt) { + // Why: Codex returns resetsAt as Unix seconds, not milliseconds. + const date = new Date(raw.resetsAt * 1000) + if (!isNaN(date.getTime())) { + resetsAt = date.getTime() + const now = new Date() + const isToday = date.toDateString() === now.toDateString() + resetDescription = isToday + ? date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' }) + : date.toLocaleDateString(undefined, { + weekday: 'short', + hour: 'numeric', + minute: '2-digit' + }) + } + } + + return { + usedPercent: Math.min(100, Math.max(0, raw.usedPercent)), + windowMinutes: raw.windowDurationMins ?? 300, + resetsAt, + resetDescription + } +} + +// --------------------------------------------------------------------------- +// RPC fetch — spawn `codex -s read-only -a untrusted app-server` +// --------------------------------------------------------------------------- + +async function fetchViaRpc(options?: FetchCodexRateLimitsOptions): Promise { + return new Promise((resolve) => { + let buffer = '' + let resolved = false + let rpcId = 0 + + const child = spawn('codex', ['-s', 'read-only', '-a', 'untrusted', 'app-server'], { + stdio: ['pipe', 'pipe', 'pipe'], + // Why: the selected Codex rate-limit account must only affect this fetch + // subprocess. Never mutate process.env globally or other Codex features + // would inherit the managed account unintentionally. + env: { + ...process.env, + ...(options?.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}) + } + }) + + const timeout = setTimeout(() => { + if (!resolved) { + resolved = true + child.kill() + resolve({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: 'RPC timeout', + status: 'error' + }) + } + }, RPC_TIMEOUT_MS) + + function sendRpc(method: string, params?: unknown): number { + const id = ++rpcId + child.stdin.write(buildRpcMessage(id, method, params)) + return id + } + + // Why: the Codex RPC server follows the JSON-RPC/LSP initialization + // handshake: client sends `initialize` request, waits for the response, + // then sends an `initialized` notification. Only after that will the + // server accept other methods. Skipping the notification causes "Not + // initialized" errors on subsequent requests. + let rateLimitsId: number | null = null + + const initId = sendRpc('initialize', { + clientInfo: { name: 'orca', version: '1.0.0' } + }) + + function sendNotification(method: string): void { + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, params: {} })}\n`) + } + + child.stdout.on('data', (chunk: Buffer) => { + buffer += chunk.toString() + + // JSON-RPC messages are newline-delimited + let newlineIdx: number + while ((newlineIdx = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, newlineIdx).trim() + buffer = buffer.slice(newlineIdx + 1) + if (!line) { + continue + } + + try { + const msg = JSON.parse(line) as RpcResponse + + // Skip server-initiated notifications (no id field) + if (msg.id == null) { + continue + } + + if (msg.id === initId) { + // Initialize succeeded — send `initialized` notification, then + // request rate limits. + sendNotification('initialized') + rateLimitsId = sendRpc('account/rateLimits/read') + continue + } + + if (rateLimitsId !== null && msg.id === rateLimitsId) { + if (resolved) { + return + } + resolved = true + clearTimeout(timeout) + child.kill() + + if (msg.error) { + resolve({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: msg.error.message, + status: 'error' + }) + return + } + + const wrapper = msg.result as RpcRateLimitsResponse | undefined + const result = wrapper?.rateLimits + const session = mapRpcWindow(result?.primary) + const weekly = mapRpcWindow(result?.secondary) + + resolve({ + provider: 'codex', + session, + weekly, + updatedAt: Date.now(), + error: null, + status: 'ok' + }) + } + } catch { + // Non-JSON line from the RPC server — ignore + } + } + }) + + child.on('error', (err) => { + if (!resolved) { + resolved = true + clearTimeout(timeout) + const isNotInstalled = (err as NodeJS.ErrnoException).code === 'ENOENT' + resolve({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: isNotInstalled ? 'Codex CLI not found' : err.message, + status: isNotInstalled ? 'unavailable' : 'error' + }) + } + }) + + child.on('close', () => { + if (!resolved) { + resolved = true + clearTimeout(timeout) + resolve({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: 'RPC process exited unexpectedly', + status: 'error' + }) + } + }) + }) +} + +// --------------------------------------------------------------------------- +// PTY fallback — spawn `codex`, send `/status`, parse rendered output +// --------------------------------------------------------------------------- + +// Why: these patterns match the Codex CLI's /status output format. +// "5h limit" and "Weekly limit" lines contain a percent and optional reset text. +const FIVE_HOUR_RE = /5h\s+limit[:\s]*(\d+)%/i +const WEEKLY_RE = /weekly\s+limit[:\s]*(\d+)%/i +const RESET_TEXT_RE = /resets?\s+(?:at\s+|in\s+)?(.+)/i + +function parsePtyStatus(output: string): { + session: RateLimitWindow | null + weekly: RateLimitWindow | null +} { + const fiveMatch = FIVE_HOUR_RE.exec(output) + const weeklyMatch = WEEKLY_RE.exec(output) + + const session: RateLimitWindow | null = fiveMatch + ? { + usedPercent: Math.min(100, parseInt(fiveMatch[1], 10)), + windowMinutes: 300, + resetsAt: null, + resetDescription: null + } + : null + + const weekly: RateLimitWindow | null = weeklyMatch + ? { + usedPercent: Math.min(100, parseInt(weeklyMatch[1], 10)), + windowMinutes: 10080, + resetsAt: null, + resetDescription: null + } + : null + + // Try to extract reset time from surrounding text + const resetMatch = RESET_TEXT_RE.exec(output) + if (resetMatch && session) { + session.resetDescription = resetMatch[1].trim() + } + + return { session, weekly } +} + +async function fetchViaPty(options?: FetchCodexRateLimitsOptions): Promise { + const pty = await import('node-pty') + + return new Promise((resolve) => { + let output = '' + let resolved = false + let sentStatus = false + + const term = pty.spawn('codex', [], { + name: 'xterm-256color', + cols: 120, + rows: 40, + env: { + ...process.env, + TERM: 'xterm-256color', + ...(options?.codexHomePath ? { CODEX_HOME: options.codexHomePath } : {}) + } + }) + + const timeout = setTimeout(() => { + if (!resolved) { + resolved = true + term.kill() + resolve({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: 'PTY timeout', + status: 'error' + }) + } + }, PTY_TIMEOUT_MS) + + term.onData((data) => { + output += data + + // Wait for prompt, then send /status + if (!sentStatus && />\s*$/.test(data)) { + sentStatus = true + term.write('/status\r') + return + } + + // Check if we have parseable output + if (sentStatus && (FIVE_HOUR_RE.test(output) || WEEKLY_RE.test(output))) { + setTimeout(() => { + if (resolved) { + return + } + resolved = true + clearTimeout(timeout) + term.kill() + + // eslint-disable-next-line no-control-regex + const clean = output.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + const { session, weekly } = parsePtyStatus(clean) + + resolve({ + provider: 'codex', + session, + weekly, + updatedAt: Date.now(), + error: session || weekly ? null : 'Failed to parse CLI output', + status: session || weekly ? 'ok' : 'error' + }) + }, 500) + } + }) + + term.onExit(() => { + if (!resolved) { + resolved = true + clearTimeout(timeout) + // eslint-disable-next-line no-control-regex + const clean = output.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '') + const { session, weekly } = parsePtyStatus(clean) + resolve({ + provider: 'codex', + session, + weekly, + updatedAt: Date.now(), + error: session || weekly ? null : 'CLI exited before status was available', + status: session || weekly ? 'ok' : 'error' + }) + } + }) + }) +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +export async function fetchCodexRateLimits( + options?: FetchCodexRateLimitsOptions +): Promise { + // Path A: try RPC first + try { + return await fetchViaRpc(options) + } catch { + // RPC failed — fall through to PTY + } + + // Path B: PTY fallback + try { + return await fetchViaPty(options) + } catch (err) { + const message = err instanceof Error ? err.message : 'Unknown error' + const isNotInstalled = message.includes('ENOENT') + return { + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: isNotInstalled ? 'Codex CLI not found' : message, + status: isNotInstalled ? 'unavailable' : 'error' + } + } +} diff --git a/src/main/rate-limits/service.test.ts b/src/main/rate-limits/service.test.ts new file mode 100644 index 000000000..346539b00 --- /dev/null +++ b/src/main/rate-limits/service.test.ts @@ -0,0 +1,179 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ProviderRateLimits } from '../../shared/rate-limit-types' +import { RateLimitService } from './service' +import { fetchClaudeRateLimits } from './claude-fetcher' +import { fetchCodexRateLimits } from './codex-fetcher' + +vi.mock('./claude-fetcher', () => ({ + fetchClaudeRateLimits: vi.fn() +})) + +vi.mock('./codex-fetcher', () => ({ + fetchCodexRateLimits: vi.fn() +})) + +type Deferred = { + promise: Promise + resolve: (value: T) => void +} + +function deferred(): Deferred { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +function okProvider( + provider: 'claude' | 'codex', + usedPercent: number, + updatedAt = Date.now() +): ProviderRateLimits { + return { + provider, + session: { + usedPercent, + windowMinutes: 300, + resetsAt: null, + resetDescription: null + }, + weekly: null, + updatedAt, + error: null, + status: 'ok' + } +} + +function errorProvider(provider: 'claude' | 'codex', message: string): ProviderRateLimits { + return { + provider, + session: null, + weekly: null, + updatedAt: Date.now(), + error: message, + status: 'error' + } +} + +function serviceInternals(service: RateLimitService): { fetchAll: () => Promise } { + return service as unknown as { fetchAll: () => Promise } +} + +describe('RateLimitService', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('does not refetch Claude when a Codex account switch is queued during fetchAll', async () => { + const service = new RateLimitService() + const firstClaude = deferred() + const firstCodex = deferred() + + vi.mocked(fetchClaudeRateLimits).mockImplementationOnce(() => firstClaude.promise) + vi.mocked(fetchCodexRateLimits) + .mockImplementationOnce(() => firstCodex.promise) + .mockResolvedValueOnce(okProvider('codex', 42)) + + const fullRefresh = service.refresh() + await Promise.resolve() + + const switchRefresh = service.refreshForCodexAccountChange() + await Promise.resolve() + + firstClaude.resolve(okProvider('claude', 18)) + firstCodex.resolve(okProvider('codex', 24)) + + await fullRefresh + await switchRefresh + + expect(fetchClaudeRateLimits).toHaveBeenCalledTimes(1) + expect(fetchCodexRateLimits).toHaveBeenCalledTimes(2) + }) + + it('keeps recent stale data across repeated failures', async () => { + const service = new RateLimitService() + const internal = serviceInternals(service) + + vi.mocked(fetchClaudeRateLimits) + .mockResolvedValueOnce(okProvider('claude', 33, Date.now())) + .mockResolvedValueOnce(errorProvider('claude', 'temporary failure')) + .mockResolvedValueOnce(errorProvider('claude', 'still failing')) + + vi.mocked(fetchCodexRateLimits) + .mockResolvedValueOnce(okProvider('codex', 44, Date.now())) + .mockResolvedValueOnce(okProvider('codex', 44, Date.now())) + .mockResolvedValueOnce(okProvider('codex', 44, Date.now())) + + await internal.fetchAll() + await internal.fetchAll() + + let state = service.getState() + expect(state.claude?.status).toBe('error') + expect(state.claude?.session?.usedPercent).toBe(33) + + await internal.fetchAll() + + state = service.getState() + expect(state.claude?.status).toBe('error') + expect(state.claude?.session?.usedPercent).toBe(33) + expect(state.claude?.error).toBe('still failing') + }) + + it('bypasses the debounce for explicit manual refreshes', async () => { + const service = new RateLimitService() + + vi.mocked(fetchClaudeRateLimits) + .mockResolvedValueOnce(okProvider('claude', 10, Date.now())) + .mockResolvedValueOnce(okProvider('claude', 11, Date.now())) + + vi.mocked(fetchCodexRateLimits) + .mockResolvedValueOnce(okProvider('codex', 20, Date.now())) + .mockResolvedValueOnce(okProvider('codex', 21, Date.now())) + + await service.refresh() + await service.refresh() + + expect(fetchClaudeRateLimits).toHaveBeenCalledTimes(2) + expect(fetchCodexRateLimits).toHaveBeenCalledTimes(2) + }) + + it('waits for a queued explicit refresh when another fetch is already in flight', async () => { + const service = new RateLimitService() + const firstClaude = deferred() + const firstCodex = deferred() + const secondClaude = deferred() + const secondCodex = deferred() + + vi.mocked(fetchClaudeRateLimits) + .mockImplementationOnce(() => firstClaude.promise) + .mockImplementationOnce(() => secondClaude.promise) + vi.mocked(fetchCodexRateLimits) + .mockImplementationOnce(() => firstCodex.promise) + .mockImplementationOnce(() => secondCodex.promise) + + const backgroundFetch = serviceInternals(service).fetchAll() + await Promise.resolve() + + let refreshResolved = false + const manualRefresh = service.refresh().then(() => { + refreshResolved = true + }) + await Promise.resolve() + + firstClaude.resolve(okProvider('claude', 10, Date.now())) + firstCodex.resolve(okProvider('codex', 20, Date.now())) + await Promise.resolve() + + expect(refreshResolved).toBe(false) + + secondClaude.resolve(okProvider('claude', 11, Date.now())) + secondCodex.resolve(okProvider('codex', 21, Date.now())) + await backgroundFetch + await manualRefresh + + expect(refreshResolved).toBe(true) + expect(fetchClaudeRateLimits).toHaveBeenCalledTimes(2) + expect(fetchCodexRateLimits).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/rate-limits/service.ts b/src/main/rate-limits/service.ts new file mode 100644 index 000000000..440735961 --- /dev/null +++ b/src/main/rate-limits/service.ts @@ -0,0 +1,385 @@ +/* eslint-disable max-lines -- Why: this service centralizes polling, stale-data +handling, account-switch fetch semantics, and renderer push coordination so the +fetch ordering rules stay in one place. */ +import type { BrowserWindow } from 'electron' +import type { RateLimitState, ProviderRateLimits } from '../../shared/rate-limit-types' +import { fetchClaudeRateLimits } from './claude-fetcher' +import { fetchCodexRateLimits } from './codex-fetcher' + +// Why: quota state does not need near-real-time polling, and a less aggressive +// default reduces avoidable Claude /usage pressure. We intentionally use a +// slower cadence here rather than polling every 2 minutes. +const DEFAULT_POLL_MS = 5 * 60 * 1000 // 5 minutes +const MIN_REFETCH_MS = 30 * 1000 // 30 seconds — debounce rapid refresh requests +const STALE_THRESHOLD_MS = 10 * 60 * 1000 // 10 minutes — after this, stale data is dropped + +export class RateLimitService { + private state: RateLimitState = { claude: null, codex: null } + private pollInterval: number = DEFAULT_POLL_MS + private timer: ReturnType | null = null + private lastFetchAt = 0 + private mainWindow: BrowserWindow | null = null + private detachWindowListeners: (() => void) | null = null + private isFetching = false + private fullFetchQueued = false + private codexOnlyFetchQueued = false + private fetchIdleResolvers: (() => void)[] = [] + private codexFetchGeneration = 0 + private codexHomePathResolver: (() => string | null) | null = null + + constructor() {} + + setCodexHomePathResolver(resolver: () => string | null): void { + this.codexHomePathResolver = resolver + } + + attach(mainWindow: BrowserWindow): void { + this.detachWindowListeners?.() + this.mainWindow = mainWindow + const refreshOnResume = (): void => { + void this.refreshIfWindowActive() + } + mainWindow.on('focus', refreshOnResume) + mainWindow.on('show', refreshOnResume) + mainWindow.on('restore', refreshOnResume) + this.detachWindowListeners = () => { + mainWindow.removeListener('focus', refreshOnResume) + mainWindow.removeListener('show', refreshOnResume) + mainWindow.removeListener('restore', refreshOnResume) + } + mainWindow.on('closed', () => { + this.detachWindowListeners?.() + this.detachWindowListeners = null + if (this.mainWindow === mainWindow) { + this.mainWindow = null + } + }) + } + + start(): void { + // Fire initial fetch immediately on start + void this.fetchAll() + this.startTimer() + } + + stop(): void { + this.stopTimer() + this.detachWindowListeners?.() + this.detachWindowListeners = null + this.mainWindow = null + } + + getState(): RateLimitState { + return this.state + } + + async refresh(): Promise { + // Why: the explicit refresh button is a user-directed recovery action. + // Debouncing it behind the background poll throttle makes the UI feel + // broken after wake/focus transitions because the click can no-op even + // though the user is asking for a fresh read right now. + await this.fetchAll({ force: true }) + return this.state + } + + async refreshForCodexAccountChange(): Promise { + this.codexFetchGeneration += 1 + // Why: switching the selected Codex account must immediately clear the old + // Codex quota view. Keeping stale values visible would show the previous + // account's limits under the newly selected identity until the next poll. + this.updateState({ + ...this.state, + codex: this.withFetchingStatus(null, 'codex') + }) + await this.fetchCodexOnly({ force: true }) + return this.state + } + + setPollingInterval(ms: number): void { + this.pollInterval = Math.max(30_000, ms) + if (this.timer) { + this.stopTimer() + this.startTimer() + } + } + + // --------------------------------------------------------------------------- + // Internal + // --------------------------------------------------------------------------- + + private startTimer(): void { + this.stopTimer() + this.timer = setInterval(() => { + if (!this.shouldBackgroundPoll()) { + return + } + void this.fetchAll() + }, this.pollInterval) + } + + private stopTimer(): void { + if (this.timer) { + clearInterval(this.timer) + this.timer = null + } + } + + private shouldBackgroundPoll(): boolean { + if (!this.mainWindow || this.mainWindow.isDestroyed()) { + return false + } + // Why: these quota fetches only power in-app UI. When Orca is hidden, + // minimized, or unfocused, polling only burns CLI/API budget without any + // visible benefit. We refresh again as soon as the window becomes active. + if (!this.mainWindow.isVisible() || this.mainWindow.isMinimized()) { + return false + } + return this.mainWindow.isFocused() + } + + private async refreshIfWindowActive(): Promise { + if (!this.shouldBackgroundPoll()) { + return + } + if (Date.now() - this.lastFetchAt < MIN_REFETCH_MS) { + return + } + await this.fetchAll() + } + + private async fetchAll(options?: { force?: boolean }): Promise { + if (this.isFetching) { + if (options?.force) { + this.fullFetchQueued = true + return this.waitForFetchIdle() + } + return + } + this.isFetching = true + + try { + let shouldContinue = true + while (shouldContinue) { + await this.runFetchAllCycle() + shouldContinue = false + if (this.fullFetchQueued) { + this.fullFetchQueued = false + shouldContinue = true + continue + } + if (this.codexOnlyFetchQueued) { + this.codexOnlyFetchQueued = false + await this.runFetchCodexOnlyCycle() + } + } + } finally { + this.isFetching = false + this.resolveFetchIdleWaiters() + } + } + + private async fetchCodexOnly(options?: { force?: boolean }): Promise { + if (this.isFetching) { + if (options?.force) { + this.codexOnlyFetchQueued = true + return this.waitForFetchIdle() + } + return + } + this.isFetching = true + + try { + let shouldContinue = true + while (shouldContinue) { + await this.runFetchCodexOnlyCycle() + shouldContinue = false + if (this.fullFetchQueued) { + this.fullFetchQueued = false + await this.runFetchAllCycle() + continue + } + if (this.codexOnlyFetchQueued) { + this.codexOnlyFetchQueued = false + shouldContinue = true + } + } + } finally { + this.isFetching = false + this.resolveFetchIdleWaiters() + } + } + + private waitForFetchIdle(): Promise { + if (!this.isFetching && !this.fullFetchQueued && !this.codexOnlyFetchQueued) { + return Promise.resolve() + } + // Why: explicit refresh callers need to await the queued follow-up cycle + // when a poll is already in flight, otherwise the UI stops spinning before + // the user-requested refresh actually runs. + return new Promise((resolve) => { + this.fetchIdleResolvers.push(resolve) + }) + } + + private resolveFetchIdleWaiters(): void { + if (this.isFetching || this.fullFetchQueued || this.codexOnlyFetchQueued) { + return + } + const resolvers = this.fetchIdleResolvers + this.fetchIdleResolvers = [] + for (const resolve of resolvers) { + resolve() + } + } + + private withFetchingStatus( + current: ProviderRateLimits | null, + provider: 'claude' | 'codex' + ): ProviderRateLimits { + if (!current) { + return { + provider, + session: null, + weekly: null, + updatedAt: 0, + error: null, + status: 'fetching' + } + } + return { ...current, status: 'fetching' } + } + + private async runFetchAllCycle(): Promise { + const codexHomePath = this.codexHomePathResolver?.() ?? null + const codexProvenance = codexHomePath ? `managed:${codexHomePath}` : 'system' + const codexGeneration = this.codexFetchGeneration + const previousState = this.state + + // Mark both providers as fetching while keeping previous data visible. + // Codex account changes clear Codex separately before this method is + // called, so ordinary refreshes still preserve the current values. + this.updateState({ + claude: this.withFetchingStatus(previousState.claude, 'claude'), + codex: this.withFetchingStatus(previousState.codex, 'codex') + }) + + const [claude, codex] = await Promise.all([ + fetchClaudeRateLimits().catch( + (err): ProviderRateLimits => ({ + provider: 'claude', + session: null, + weekly: null, + updatedAt: Date.now(), + error: err instanceof Error ? err.message : 'Unknown error', + status: 'error' + }) + ), + fetchCodexRateLimits({ codexHomePath }).catch( + (err): ProviderRateLimits => ({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: err instanceof Error ? err.message : 'Unknown error', + status: 'error' + }) + ) + ]) + + const latestCodexHomePath = this.codexHomePathResolver?.() ?? null + const latestCodexProvenance = latestCodexHomePath ? `managed:${latestCodexHomePath}` : 'system' + const shouldApplyCodex = + codexGeneration === this.codexFetchGeneration && codexProvenance === latestCodexProvenance + + // Why: account switches can race in-flight Codex fetches. Only apply a + // Codex result if both the selected-account provenance and the request + // generation still match, otherwise an old account could overwrite the + // newly selected account's quota state. + this.updateState({ + claude: this.applyStalePolicy(claude, previousState.claude), + codex: shouldApplyCodex ? this.applyStalePolicy(codex, previousState.codex) : this.state.codex + }) + + this.lastFetchAt = Date.now() + } + + private async runFetchCodexOnlyCycle(): Promise { + const codexHomePath = this.codexHomePathResolver?.() ?? null + const codexProvenance = codexHomePath ? `managed:${codexHomePath}` : 'system' + const codexGeneration = this.codexFetchGeneration + const previousState = this.state + + this.updateState({ + ...previousState, + codex: this.withFetchingStatus(previousState.codex, 'codex') + }) + + const codex = await fetchCodexRateLimits({ codexHomePath }).catch( + (err): ProviderRateLimits => ({ + provider: 'codex', + session: null, + weekly: null, + updatedAt: Date.now(), + error: err instanceof Error ? err.message : 'Unknown error', + status: 'error' + }) + ) + + const latestCodexHomePath = this.codexHomePathResolver?.() ?? null + const latestCodexProvenance = latestCodexHomePath ? `managed:${latestCodexHomePath}` : 'system' + const shouldApplyCodex = + codexGeneration === this.codexFetchGeneration && codexProvenance === latestCodexProvenance + + this.updateState({ + ...this.state, + codex: shouldApplyCodex ? this.applyStalePolicy(codex, previousState.codex) : this.state.codex + }) + + this.lastFetchAt = Date.now() + } + + private applyStalePolicy( + fresh: ProviderRateLimits, + previous: ProviderRateLimits | null + ): ProviderRateLimits { + // Fresh data is fine — use it + if (fresh.status === 'ok') { + return fresh + } + + const previousHasData = Boolean(previous?.session || previous?.weekly) + + // No previous data to fall back on + if (!previous || !previousHasData) { + return fresh + } + + // Previous data is too old — don't show stale data + if (Date.now() - previous.updatedAt > STALE_THRESHOLD_MS) { + return fresh + } + + // Why: once we have a recent successful snapshot, repeated transient + // failures should keep showing that same snapshot until it ages out of the + // stale window. Otherwise the bar flaps from "stale but useful" to empty + // after the second failure even though the last known quota is still fresh + // enough to be actionable. + return { + ...previous, + error: fresh.error, + status: 'error' + } + } + + private updateState(next: RateLimitState): void { + this.state = next + this.pushToRenderer() + } + + private pushToRenderer(): void { + if (!this.mainWindow || this.mainWindow.isDestroyed()) { + return + } + this.mainWindow.webContents.send('rateLimits:update', this.state) + } +} diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index bfa22f1fb..f2203f300 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -19,11 +19,12 @@ import { export function attachMainWindowServices( mainWindow: BrowserWindow, store: Store, - runtime: OrcaRuntimeService + runtime: OrcaRuntimeService, + getSelectedCodexHomePath?: () => string | null ): void { registerRepoHandlers(mainWindow, store) registerWorktreeHandlers(mainWindow, store) - registerPtyHandlers(mainWindow, runtime) + registerPtyHandlers(mainWindow, runtime, getSelectedCodexHomePath) registerFileDropRelay(mainWindow) setupAutoUpdater(mainWindow, { getLastUpdateCheckAt: () => store.getUI().lastUpdateCheckAt, diff --git a/src/preload/api-types.d.ts b/src/preload/api-types.d.ts index b11529e05..a2b01c2d3 100644 --- a/src/preload/api-types.d.ts +++ b/src/preload/api-types.d.ts @@ -1,6 +1,7 @@ /* eslint-disable max-lines -- Why: the preload contract is intentionally centralized in one declaration file so renderer and preload stay in lockstep when IPC surfaces change. */ import type { BrowserLoadError, + CodexRateLimitAccountsState, CreateWorktreeResult, DirEntry, FsChangedPayload, @@ -51,6 +52,7 @@ import type { ClaudeUsageSessionRow, ClaudeUsageSummary } from '../../shared/claude-usage-types' +import type { RateLimitState } from '../../shared/rate-limit-types' import type { CodexUsageBreakdownKind, CodexUsageBreakdownRow, @@ -186,6 +188,7 @@ export type PreloadApi = { resize: (id: string, cols: number, rows: number) => void kill: (id: string) => Promise hasChildProcesses: (id: string) => Promise + getForegroundProcess: (id: string) => Promise onData: (callback: (data: { id: string; data: string }) => void) => () => void onExit: (callback: (data: { id: string; code: number }) => void) => () => void } @@ -224,6 +227,13 @@ export type PreloadApi = { set: (args: Partial) => Promise listFonts: () => Promise } + codexAccounts: { + list: () => Promise + add: () => Promise + reauthenticate: (args: { accountId: string }) => Promise + remove: (args: { accountId: string }) => Promise + select: (args: { accountId: string | null }) => Promise + } cli: { getInstallStatus: () => Promise install: () => Promise @@ -350,6 +360,7 @@ export type PreloadApi = { onNewTerminalTab: (callback: () => void) => () => void onCloseActiveTab: (callback: () => void) => () => void onSwitchTab: (callback: (direction: 1 | -1) => void) => () => void + onToggleStatusBar: (callback: () => void) => () => void onActivateWorktree: ( callback: (data: { repoId: string; worktreeId: string; setup?: WorktreeSetupLaunch }) => void ) => () => void @@ -370,4 +381,10 @@ export type PreloadApi = { syncWindowGraph: (graph: RuntimeSyncWindowGraph) => Promise getStatus: () => Promise } + rateLimits: { + get: () => Promise + refresh: () => Promise + setPollingInterval: (ms: number) => Promise + onUpdate: (callback: (state: RateLimitState) => void) => () => void + } } diff --git a/src/preload/index.ts b/src/preload/index.ts index 4b966c61e..828fb456e 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -6,6 +6,7 @@ import { electronAPI } from '@electron-toolkit/preload' import type { CliInstallStatus } from '../shared/cli-install-types' import type { FsChangedPayload, NotificationDispatchResult } from '../shared/types' import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../shared/runtime-types' +import type { RateLimitState } from '../shared/rate-limit-types' import { ORCA_EDITOR_SAVE_DIRTY_FILES_EVENT, type EditorSaveDirtyFilesDetail @@ -197,6 +198,10 @@ const api = { hasChildProcesses: (id: string): Promise => ipcRenderer.invoke('pty:hasChildProcesses', { id }), + /** Return the PTY foreground process basename when available (e.g. "codex"). */ + getForegroundProcess: (id: string): Promise => + ipcRenderer.invoke('pty:getForegroundProcess', { id }), + onData: (callback: (data: { id: string; data: string }) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: { id: string; data: string }) => callback(data) @@ -269,6 +274,17 @@ const api = { listFonts: (): Promise => ipcRenderer.invoke('settings:listFonts') }, + codexAccounts: { + list: (): Promise => ipcRenderer.invoke('codexAccounts:list'), + add: (): Promise => ipcRenderer.invoke('codexAccounts:add'), + reauthenticate: (args: { accountId: string }): Promise => + ipcRenderer.invoke('codexAccounts:reauthenticate', args), + remove: (args: { accountId: string }): Promise => + ipcRenderer.invoke('codexAccounts:remove', args), + select: (args: { accountId: string | null }): Promise => + ipcRenderer.invoke('codexAccounts:select', args) + }, + cli: { getInstallStatus: (): Promise => ipcRenderer.invoke('cli:getInstallStatus'), install: (): Promise => ipcRenderer.invoke('cli:install'), @@ -598,6 +614,11 @@ const api = { ipcRenderer.on('ui:switchTab', listener) return () => ipcRenderer.removeListener('ui:switchTab', listener) }, + onToggleStatusBar: (callback: () => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent) => callback() + ipcRenderer.on('ui:toggleStatusBar', listener) + return () => ipcRenderer.removeListener('ui:toggleStatusBar', listener) + }, onActivateWorktree: ( callback: (data: { repoId: string @@ -704,6 +725,18 @@ const api = { syncWindowGraph: (graph: RuntimeSyncWindowGraph): Promise => ipcRenderer.invoke('runtime:syncWindowGraph', graph), getStatus: (): Promise => ipcRenderer.invoke('runtime:getStatus') + }, + + rateLimits: { + get: (): Promise => ipcRenderer.invoke('rateLimits:get'), + refresh: (): Promise => ipcRenderer.invoke('rateLimits:refresh'), + setPollingInterval: (ms: number): Promise => + ipcRenderer.invoke('rateLimits:setPollingInterval', ms), + onUpdate: (callback: (state: RateLimitState) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, state: RateLimitState) => callback(state) + ipcRenderer.on('rateLimits:update', listener) + return () => ipcRenderer.removeListener('rateLimits:update', listener) + } } } diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 37771b7e4..8282b1b4a 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -1,6 +1,6 @@ /* eslint-disable max-lines */ import { useEffect } from 'react' -import { DEFAULT_WORKTREE_CARD_PROPERTIES } from '../../shared/constants' +import { DEFAULT_STATUS_BAR_ITEMS, DEFAULT_WORKTREE_CARD_PROPERTIES } from '../../shared/constants' import { isGitRepoKind } from '../../shared/repo-kind' import { Minimize2, PanelLeft, PanelRight } from 'lucide-react' @@ -18,6 +18,7 @@ import Settings from './components/settings/Settings' import RightSidebar from './components/right-sidebar' import QuickOpen from './components/QuickOpen' import WorktreeJumpPalette from './components/WorktreeJumpPalette' +import { StatusBar } from './components/status-bar/StatusBar' import { ZoomOverlay } from './components/ZoomOverlay' import { useGitStatusPolling } from './components/right-sidebar/useGitStatusPolling' import { @@ -148,6 +149,8 @@ function App(): React.JSX.Element { uiZoomLevel: 0, editorFontZoomLevel: 0, worktreeCardProperties: [...DEFAULT_WORKTREE_CARD_PROPERTIES], + statusBarItems: [...DEFAULT_STATUS_BAR_ITEMS], + statusBarVisible: true, dismissedUpdateVersion: null, lastUpdateCheckAt: null }) @@ -532,25 +535,26 @@ function App(): React.JSX.Element { ) : null} - -
- {showSidebar ? : null} -
-
-
- +
+ {showSidebar ? : null} +
+
+
+ +
+ {activeView === 'settings' ? : !activeWorktreeId ? : null}
- {activeView === 'settings' ? : !activeWorktreeId ? : null}
+ {showSidebar && rightSidebarOpen ? : null}
- {showSidebar && rightSidebarOpen ? : null} -
+ + diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 0437ed1a7..884b2c59d 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -13,6 +13,7 @@ import { DialogTitle } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' +import { RefreshCw } from 'lucide-react' import TabBar from './tab-bar/TabBar' import TerminalPane from './terminal-pane/TerminalPane' import { @@ -39,6 +40,10 @@ export default function Terminal(): React.JSX.Element | null { const setTabCustomTitle = useAppStore((s) => s.setTabCustomTitle) const setTabColor = useAppStore((s) => s.setTabColor) const consumeSuppressedPtyExit = useAppStore((s) => s.consumeSuppressedPtyExit) + const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) + const codexRestartNoticeByPtyId = useAppStore((s) => s.codexRestartNoticeByPtyId) + const queueCodexPaneRestarts = useAppStore((s) => s.queueCodexPaneRestarts) + const clearCodexRestartNotice = useAppStore((s) => s.clearCodexRestartNotice) const expandedPaneByTabId = useAppStore((s) => s.expandedPaneByTabId) const workspaceSessionReady = useAppStore((s) => s.workspaceSessionReady) const openFiles = useAppStore((s) => s.openFiles) @@ -758,6 +763,51 @@ export default function Terminal(): React.JSX.Element | null { className={isVisible ? 'absolute inset-0' : 'absolute inset-0 hidden'} aria-hidden={!isVisible} > + {(() => { + const staleWorktreePtyIds = worktreeTabs.flatMap((tab) => + (ptyIdsByTabId[tab.id] ?? []).filter((ptyId) => + Boolean(codexRestartNoticeByPtyId[ptyId]) + ) + ) + if (staleWorktreePtyIds.length === 0) { + return null + } + // Why: account switching is global, but repeating the same + // stale-session prompt in every affected Codex pane quickly + // turns into noise. Keep one worktree-scoped chip in the + // same visual corner so users get the same prompt style + // without having to dismiss it in every pane. + return ( +
+
+ + Codex is using the previous account + +
+ + +
+
+
+ ) + })()} {worktreeTabs.map((tab) => ( ) => void } +function getCodexAccountLabel( + state: CodexRateLimitAccountsState, + accountId: string | null | undefined +): string { + if (accountId == null) { + return 'System default' + } + return state.accounts.find((account) => account.id === accountId)?.email ?? 'Codex account' +} + +function getCodexAccountErrorDescription(error: unknown): string { + const message = String((error as Error)?.message ?? error) + .replace(/^Error occurred in handler for 'codexAccounts:[^']+':\s*/i, '') + .replace(/^Error invoking remote method 'codexAccounts:[^']+':\s*/i, '') + .replace(/^Error:\s*/i, '') + .trim() + const normalizedMessage = message.toLowerCase() + + // Why: Codex account actions cross the Electron IPC boundary, and invoke() + // failures often include transport-level wrapper text that is useful in + // devtools but noisy in product UI. Normalize the handful of expected auth + // failures here so users see actionable sign-in guidance instead of IPC + // internals or raw upstream wording. + if (normalizedMessage.includes('timed out waiting for codex login to finish')) { + return 'Codex sign-in took too long to finish. Please try again.' + } + if (normalizedMessage.includes('codex sign-in took too long to finish')) { + return 'Codex sign-in took too long to finish. Please try again.' + } + if ( + normalizedMessage.includes('auth error 502') || + normalizedMessage.includes('gateway') || + normalizedMessage.includes('bad gateway') + ) { + return 'Codex sign-in is temporarily unavailable. Please try again in a minute.' + } + if (normalizedMessage.startsWith('codex login failed:')) { + const loginMessage = message.slice('Codex login failed:'.length).trim() + return loginMessage || 'Codex sign-in failed. Please try again.' + } + + return message || 'Codex sign-in failed. Please try again.' +} + export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): React.JSX.Element { const searchQuery = useAppStore((s) => s.settingsSearchQuery) const updateStatus = useAppStore((s) => s.updateStatus) + const fetchSettings = useAppStore((s) => s.fetchSettings) const [appVersion, setAppVersion] = useState(null) const [autoSaveDelayDraft, setAutoSaveDelayDraft] = useState( String(settings.editorAutoSaveDelayMs) ) + const [codexAccounts, setCodexAccounts] = useState({ + accounts: [], + activeAccountId: null + }) + const [codexAction, setCodexAction] = useState< + 'idle' | 'adding' | `reauth:${string}` | `remove:${string}` | `select:${string | 'system'}` + >('idle') + const [removeAccountId, setRemoveAccountId] = useState(null) useEffect(() => { window.api.updater.getVersion().then(setAppVersion) @@ -53,6 +116,31 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea setAutoSaveDelayDraft(String(settings.editorAutoSaveDelayMs)) }, [settings.editorAutoSaveDelayMs]) + useEffect(() => { + let stale = false + + const loadCodexAccounts = async (): Promise => { + try { + const next = await window.api.codexAccounts.list() + if (!stale) { + setCodexAccounts(next) + } + } catch (error) { + if (!stale) { + toast.error('Could not load Codex accounts.', { + description: String((error as Error)?.message ?? error) + }) + } + } + } + + void loadCodexAccounts() + + return () => { + stale = true + } + }, []) + const handleBrowseWorkspace = async () => { const path = await window.api.repos.pickFolder() if (path) { @@ -90,6 +178,51 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea }) } + const syncCodexAccounts = async (next: CodexRateLimitAccountsState): Promise => { + setCodexAccounts(next) + await fetchSettings() + } + + const formatAccountTimestamp = (timestamp: number): string => { + return new Date(timestamp).toLocaleString(undefined, { + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit' + }) + } + + const runCodexAccountAction = async ( + action: typeof codexAction, + operation: () => Promise + ): Promise => { + const previousActiveAccountId = codexAccounts.activeAccountId + setCodexAction(action) + try { + const next = await operation() + await syncCodexAccounts(next) + const shouldPromptRestart = + action === 'adding' || + (action.startsWith('select:') && previousActiveAccountId !== next.activeAccountId) || + (action.startsWith('reauth:') && + next.activeAccountId !== null && + action === `reauth:${next.activeAccountId}`) || + (action.startsWith('remove:') && previousActiveAccountId !== next.activeAccountId) + if (shouldPromptRestart) { + void markLiveCodexSessionsForRestart({ + previousAccountLabel: getCodexAccountLabel(codexAccounts, previousActiveAccountId), + nextAccountLabel: getCodexAccountLabel(next, next.activeAccountId) + }) + } + } catch (error) { + toast.error('Codex account update failed.', { + description: getCodexAccountErrorDescription(error) + }) + } finally { + setCodexAction('idle') + } + } + const visibleSections = [ matchesSettingsSearch(searchQuery, GENERAL_WORKSPACE_SEARCH_ENTRIES) ? (
@@ -159,7 +292,6 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea /> -
) : null, matchesSettingsSearch(searchQuery, GENERAL_BROWSER_SEARCH_ENTRIES) ? ( @@ -394,6 +526,176 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea )} ) : null, + matchesSettingsSearch(searchQuery, GENERAL_CODEX_ACCOUNTS_SEARCH_ENTRIES) ? ( +
+
+

Codex Accounts

+

+ Add and switch between Codex accounts in Orca. +

+

+ Each account keeps its own local sign-in context in Orca. Account auth stays on this + device. +

+
+ + + {/* Why: Settings deep-links can target this subsection directly from + the status-bar account switcher. Keeping a stable DOM anchor here + avoids dumping the user at the top of General and making them hunt + for the actual Codex account controls. */} +
+
+ +

+ Add a Codex account to use it in Orca. +

+
+ +
+ + {codexAccounts.accounts.length === 0 ? ( +
+ No managed Codex accounts yet. Orca will use your system default Codex login until you + add one here. +
+ ) : ( +
+ + {codexAccounts.accounts.map((account) => { + const isActive = codexAccounts.activeAccountId === account.id + const isReauthing = codexAction === `reauth:${account.id}` + const isRemoving = codexAction === `remove:${account.id}` + const isBusy = codexAction !== 'idle' + + return ( + + +
+
+ + ) + })} +
+ )} + + + ) : null, matchesSettingsSearch(searchQuery, GENERAL_UPDATE_SEARCH_ENTRIES) ? (
@@ -489,6 +791,40 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea return (
+ !open && setRemoveAccountId(null)} + > + + + Remove Codex Account? + + Orca will delete the managed Codex home for this saved account. If it is currently + active, Orca falls back to the system default Codex login. + + + + + + + + {visibleSections.map((section, index) => (
{index > 0 ? : null} diff --git a/src/renderer/src/components/settings/Settings.tsx b/src/renderer/src/components/settings/Settings.tsx index b0b5cfad2..dbdc4fb35 100644 --- a/src/renderer/src/components/settings/Settings.tsx +++ b/src/renderer/src/components/settings/Settings.tsx @@ -80,6 +80,7 @@ function Settings(): React.JSX.Element { const [activeSectionId, setActiveSectionId] = useState('general') const contentScrollRef = useRef(null) const terminalFontsLoadedRef = useRef(false) + const pendingNavSectionRef = useRef(null) const pendingScrollTargetRef = useRef(null) useEffect(() => { @@ -100,10 +101,12 @@ function Settings(): React.JSX.Element { return } - pendingScrollTargetRef.current = getSettingsSectionId( + const paneSectionId = getSettingsSectionId( settingsNavigationTarget.pane as SettingsNavTarget, settingsNavigationTarget.repoId ) + pendingNavSectionRef.current = paneSectionId + pendingScrollTargetRef.current = settingsNavigationTarget.sectionId ?? paneSectionId clearSettingsTarget() }, [clearSettingsTarget, settingsNavigationTarget]) @@ -277,17 +280,19 @@ function Settings(): React.JSX.Element { useEffect(() => { const scrollTargetId = pendingScrollTargetRef.current + const pendingNavSectionId = pendingNavSectionRef.current const visibleIds = new Set(visibleNavSections.map((section) => section.id)) - if (scrollTargetId && visibleIds.has(scrollTargetId)) { + if (scrollTargetId && pendingNavSectionId && visibleIds.has(pendingNavSectionId)) { const target = document.getElementById(scrollTargetId) target?.scrollIntoView({ behavior: 'smooth', block: 'start' }) - setActiveSectionId(scrollTargetId) + setActiveSectionId(pendingNavSectionId) + pendingNavSectionRef.current = null pendingScrollTargetRef.current = null return } - if (scrollTargetId && settingsSearchQuery.trim() !== '') { + if (scrollTargetId && pendingNavSectionId && settingsSearchQuery.trim() !== '') { setSettingsSearchQuery('') return } diff --git a/src/renderer/src/components/settings/general-search.ts b/src/renderer/src/components/settings/general-search.ts index 5b2236674..0cfbf0835 100644 --- a/src/renderer/src/components/settings/general-search.ts +++ b/src/renderer/src/components/settings/general-search.ts @@ -68,11 +68,25 @@ export const GENERAL_BROWSER_SEARCH_ENTRIES: SettingsSearchEntry[] = [ } ] +export const GENERAL_CODEX_ACCOUNTS_SEARCH_ENTRIES: SettingsSearchEntry[] = [ + { + title: 'Codex Accounts', + description: 'Manage which Codex account Orca uses for live rate limit fetching.', + keywords: ['codex', 'account', 'rate limit', 'status bar', 'quota'] + }, + { + title: 'Active Codex Account', + description: 'Choose which saved Codex account powers live quota reads.', + keywords: ['codex', 'account', 'switch', 'active', 'status bar'] + } +] + export const GENERAL_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ ...GENERAL_WORKSPACE_SEARCH_ENTRIES, ...GENERAL_BROWSER_SEARCH_ENTRIES, ...GENERAL_EDITOR_SEARCH_ENTRIES, ...GENERAL_CLI_SEARCH_ENTRIES, ...GENERAL_CACHE_TIMER_SEARCH_ENTRIES, + ...GENERAL_CODEX_ACCOUNTS_SEARCH_ENTRIES, ...GENERAL_UPDATE_SEARCH_ENTRIES ] diff --git a/src/renderer/src/components/status-bar/StatusBar.tsx b/src/renderer/src/components/status-bar/StatusBar.tsx new file mode 100644 index 000000000..d8b64b4fb --- /dev/null +++ b/src/renderer/src/components/status-bar/StatusBar.tsx @@ -0,0 +1,543 @@ +/* eslint-disable max-lines -- Why: the status bar keeps provider rendering, +interaction menus, and compact-layout behavior together so the hover/click +states stay consistent across Claude and Codex. */ +import { AlertTriangle, ChevronDown, ChevronRight, RefreshCw } from 'lucide-react' +import { useCallback, useEffect, useRef, useState } from 'react' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { + ContextMenu, + ContextMenuCheckboxItem, + ContextMenuContent, + ContextMenuTrigger +} from '@/components/ui/context-menu' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { useAppStore } from '../../store' +import type { CodexRateLimitAccountsState } from '../../../../shared/types' +import type { ProviderRateLimits, RateLimitWindow } from '../../../../shared/rate-limit-types' +import { ProviderIcon, ProviderPanel } from './tooltip' +import { markLiveCodexSessionsForRestart } from '@/lib/codex-session-restart' + +function getCodexAccountLabel( + state: CodexRateLimitAccountsState, + accountId: string | null | undefined +): string { + if (accountId == null) { + return 'System default' + } + return state.accounts.find((account) => account.id === accountId)?.email ?? 'Codex account' +} + +// --------------------------------------------------------------------------- +// Mini progress bar (shows remaining capacity, grey) +// --------------------------------------------------------------------------- + +function MiniBar({ leftPct }: { leftPct: number }): React.JSX.Element { + return ( +
+
+
+ ) +} + +// --------------------------------------------------------------------------- +// Window label (shows percent remaining) +// --------------------------------------------------------------------------- + +function WindowLabel({ w, label }: { w: RateLimitWindow; label: string }): React.JSX.Element { + const left = Math.max(0, Math.round(100 - w.usedPercent)) + return ( + + {left}% {label} + + ) +} + +// --------------------------------------------------------------------------- +// Provider segment +// --------------------------------------------------------------------------- + +function ProviderSegment({ + p, + compact +}: { + p: ProviderRateLimits | null + compact: boolean +}): React.JSX.Element { + const provider = p?.provider ?? 'claude' + const statusLabel = p?.error && /rate limit/i.test(p.error) ? 'Limited' : 'Unavailable' + + // Idle / initial load + if (!p || p.status === 'idle') { + return ( + + + ··· + + ) + } + + // Fetching with no prior data + if (p.status === 'fetching' && !p.session && !p.weekly) { + return ( + + + ··· + + ) + } + + // Unavailable (CLI not installed) + if (p.status === 'unavailable') { + return ( + + -- + + ) + } + + // Error with no data + if (p.status === 'error' && !p.session && !p.weekly) { + return ( + + + + {!compact && {statusLabel}} + + ) + } + + // Has data (ok, fetching with stale data, or error with stale data) + const isStale = p.status === 'error' + const isFetching = p.status === 'fetching' + const trailingStatusIcon = isFetching ? ( + + ) : isStale ? ( + + ) : null + + return ( + + + {p.session && !compact && } + {p.session && } + {p.session && p.weekly && ·} + {p.weekly && } + + {/* Why: reserve the trailing provider-status slot even when no icon is + visible so Claude/Codex do not shift horizontally as fetching/error + adornments appear and disappear. */} + {trailingStatusIcon} + + + ) +} + +function CodexSwitcherMenu({ + codex, + compact, + iconOnly +}: { + codex: ProviderRateLimits + compact: boolean + iconOnly: boolean +}): React.JSX.Element { + const [open, setOpen] = useState(false) + const [accountsExpanded, setAccountsExpanded] = useState(false) + const [accounts, setAccounts] = useState({ + accounts: [], + activeAccountId: null + }) + const [isSwitching, setIsSwitching] = useState(false) + const setActiveView = useAppStore((s) => s.setActiveView) + const openSettingsTarget = useAppStore((s) => s.openSettingsTarget) + const fetchSettings = useAppStore((s) => s.fetchSettings) + const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) + const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) + const codexRestartNoticeByPtyId = useAppStore((s) => s.codexRestartNoticeByPtyId) + const queueCodexPaneRestarts = useAppStore((s) => s.queueCodexPaneRestarts) + const codexAccountSyncKey = useAppStore((s) => { + const settings = s.settings + if (!settings) { + return 'no-settings' + } + return `${settings.activeCodexManagedAccountId ?? 'system'}:${settings.codexManagedAccounts.map((account) => `${account.id}:${account.updatedAt}`).join('|')}` + }) + + const loadAccounts = useCallback(async () => { + const next = await window.api.codexAccounts.list() + setAccounts(next) + }, []) + + useEffect(() => { + // Why: the status bar keeps its own lightweight account snapshot for the + // dropdown. Settings account actions mutate the main-process store outside + // this component, so we refresh when the persisted account roster changes + // or when the menu opens instead of leaving a stale account list mounted. + void loadAccounts().catch((error) => { + console.error('Failed to load Codex accounts for status bar:', error) + }) + }, [loadAccounts, open, codexAccountSyncKey]) + + const handleSelectAccount = async (accountId: string | null): Promise => { + if (isSwitching) { + return + } + const previousActiveAccountId = accounts.activeAccountId + setIsSwitching(true) + try { + const next = await window.api.codexAccounts.select({ accountId }) + setAccounts(next) + await fetchSettings() + if (previousActiveAccountId !== next.activeAccountId) { + await markLiveCodexSessionsForRestart({ + previousAccountLabel: getCodexAccountLabel(accounts, previousActiveAccountId), + nextAccountLabel: getCodexAccountLabel(next, next.activeAccountId) + }) + // Why: account switching can require a second explicit recovery step + // for live Codex terminals. Keeping the switcher open and collapsing + // back to the summary row lets the follow-up "restart open tabs" + // prompt appear in the same flow instead of feeling detached. + setAccountsExpanded(false) + } + } catch (error) { + console.error('Failed to switch Codex account from status bar:', error) + } finally { + setIsSwitching(false) + } + } + + useEffect(() => { + if (!open) { + setAccountsExpanded(false) + } + }, [open]) + + const activeAccountLabel = + accounts.activeAccountId === null + ? 'System default' + : (accounts.accounts.find((account) => account.id === accounts.activeAccountId)?.email ?? + 'Managed') + const availableSwitchTargets = [ + ...(accounts.activeAccountId === null + ? [] + : [{ id: null as string | null, label: 'System default' }]), + ...accounts.accounts + .filter((account) => account.id !== accounts.activeAccountId) + .map((account) => ({ + id: account.id, + label: account.workspaceLabel + ? `${account.email} (${account.workspaceLabel})` + : account.email + })) + ] + const staleCodexPtyIds = Object.keys(codexRestartNoticeByPtyId) + const staleCodexTabIds = Object.keys(ptyIdsByTabId).filter((tabId) => + (ptyIdsByTabId[tabId] ?? []).some((ptyId) => Boolean(codexRestartNoticeByPtyId[ptyId])) + ) + const staleCodexWorktreeCount = new Set( + Object.entries(tabsByWorktree).flatMap(([worktreeId, tabs]) => + tabs.some((tab) => staleCodexTabIds.includes(tab.id)) ? [worktreeId] : [] + ) + ).size + const staleCodexSessionCount = staleCodexPtyIds.length + const staleCodexTabCount = staleCodexTabIds.length + + return ( + + Codex Account + { + event.preventDefault() + setAccountsExpanded((prev) => !prev) + }} + > + + {activeAccountLabel} + + {accountsExpanded ? ( + + ) : ( + + )} + + {accountsExpanded ? ( +
+
+ Switch to +
+
+ {availableSwitchTargets.length === 0 ? ( +
No other accounts
+ ) : null} + {availableSwitchTargets.map((target) => ( + { + // Why: account switching may need an immediate follow-up + // restart action for live Codex tabs. Prevent the menu from + // auto-closing so that prompt can stay within the same + // account-switcher interaction instead of jumping elsewhere. + event.preventDefault() + void handleSelectAccount(target.id) + }} + disabled={isSwitching} + > + {target.label} + + ))} +
+
+ ) : null} + {staleCodexTabCount > 0 ? ( + <> + +
+
+ {/* Why: stale restart notices are tracked per PTY session, but the + bulk restart action operates per PTY-backed pane restart. Show + both counts so split panes do not make the number look wrong. */} + {staleCodexSessionCount === 1 + ? '1 Codex session is still on the old account' + : `${staleCodexSessionCount} Codex sessions are still on the old account.`} + {staleCodexWorktreeCount > 1 ? ( + + Visible sessions restart now. Others restart when their worktree becomes active. + + ) : null} +
+ +
+ + ) : null} + + { + openSettingsTarget({ + pane: 'general', + repoId: null, + sectionId: 'general-codex-accounts' + }) + setActiveView('settings') + }} + > + Manage Accounts… + +
+ ) +} + +function ProviderDetailsMenu({ + provider, + compact, + iconOnly, + ariaLabel, + open, + onOpenChange, + children +}: { + provider: ProviderRateLimits + compact: boolean + iconOnly: boolean + ariaLabel: string + open?: boolean + onOpenChange?: (open: boolean) => void + children?: React.ReactNode +}): React.JSX.Element { + return ( + + + + + +
+ +
+ {children ? ( + <> + + {children} + + ) : null} +
+
+ ) +} + +// --------------------------------------------------------------------------- +// StatusBar +// --------------------------------------------------------------------------- + +export function StatusBar(): React.JSX.Element | null { + const rateLimits = useAppStore((s) => s.rateLimits) + const refreshRateLimits = useAppStore((s) => s.refreshRateLimits) + const statusBarVisible = useAppStore((s) => s.statusBarVisible) + const statusBarItems = useAppStore((s) => s.statusBarItems) + const toggleStatusBarItem = useAppStore((s) => s.toggleStatusBarItem) + const containerRef = useRef(null) + const [isRefreshing, setIsRefreshing] = useState(false) + + const [containerWidth, setContainerWidth] = useState(900) + const resizeObserverRef = useRef(null) + + const containerRefCallback = useCallback((node: HTMLDivElement | null) => { + if (resizeObserverRef.current) { + resizeObserverRef.current.disconnect() + resizeObserverRef.current = null + } + if (node) { + containerRef.current = node + const observer = new ResizeObserver((entries) => { + for (const entry of entries) { + setContainerWidth(entry.contentRect.width) + } + }) + observer.observe(node) + resizeObserverRef.current = observer + setContainerWidth(node.getBoundingClientRect().width) + } + }, []) + + const handleRefresh = useCallback(async () => { + if (isRefreshing) { + return + } + setIsRefreshing(true) + try { + await refreshRateLimits() + } finally { + setIsRefreshing(false) + } + }, [isRefreshing, refreshRateLimits]) + + if (!statusBarVisible) { + return null + } + + const { claude, codex } = rateLimits + + // Why: hiding `unavailable` providers makes the status bar appear to lose a + // provider at random after refreshes or wake/resume. Keeping the slot visible + // preserves layout stability and makes it obvious that the provider is still + // configured but currently unavailable. + const showClaude = claude && statusBarItems.includes('claude') + const showCodex = codex && statusBarItems.includes('codex') + const anyVisible = showClaude || showCodex + + const compact = containerWidth < 900 + const iconOnly = containerWidth < 500 + + return ( + + +
+ {iconOnly ? ( + <> + {showClaude && ( + + )} + {showCodex && } + + ) : ( + <> + {showClaude && ( + + )} + + {showCodex && } + + )} + +
+ + {anyVisible && ( + + + + + + Refresh usage data + + + )} +
+ + + + toggleStatusBarItem('claude')} + > + Claude Usage + + toggleStatusBarItem('codex')} + > + Codex Usage + + + + ) +} diff --git a/src/renderer/src/components/status-bar/icons.tsx b/src/renderer/src/components/status-bar/icons.tsx new file mode 100644 index 000000000..3f9bca4e8 --- /dev/null +++ b/src/renderer/src/components/status-bar/icons.tsx @@ -0,0 +1,26 @@ +export function OpenAIIcon({ size = 14 }: { size?: number }): React.JSX.Element { + return ( + + + + ) +} + +export function ClaudeIcon({ size = 14 }: { size?: number }): React.JSX.Element { + return ( + + + + ) +} diff --git a/src/renderer/src/components/status-bar/tooltip.tsx b/src/renderer/src/components/status-bar/tooltip.tsx new file mode 100644 index 000000000..d1b1305bc --- /dev/null +++ b/src/renderer/src/components/status-bar/tooltip.tsx @@ -0,0 +1,279 @@ +import type { ProviderRateLimits, RateLimitWindow } from '../../../../shared/rate-limit-types' +import { ClaudeIcon, OpenAIIcon } from './icons' + +// --------------------------------------------------------------------------- +// Formatting helpers +// --------------------------------------------------------------------------- + +export function formatTimeAgo(ts: number): string { + const diff = Date.now() - ts + if (diff < 60_000) { + return 'just now' + } + const mins = Math.floor(diff / 60_000) + if (mins < 60) { + return `${mins}m ago` + } + const hours = Math.floor(mins / 60) + return `${hours}h ago` +} + +function formatDuration(ms: number): string { + if (ms <= 0) { + return 'now' + } + const totalMins = Math.floor(ms / 60_000) + if (totalMins < 60) { + return `${totalMins}m` + } + const hours = Math.floor(totalMins / 60) + const mins = totalMins % 60 + if (hours >= 24) { + const days = Math.floor(hours / 24) + const remHours = hours % 24 + return remHours > 0 ? `${days}d ${remHours}h` : `${days}d` + } + return mins > 0 ? `${hours}h ${mins}m` : `${hours}h` +} + +// --------------------------------------------------------------------------- +// Shared icon component +// --------------------------------------------------------------------------- + +export function ProviderIcon({ provider }: { provider: string }): React.JSX.Element { + if (provider === 'codex') { + return + } + return +} + +function ErrorMessage({ + message, + inverted = false +}: { + message: string + inverted?: boolean +}): React.JSX.Element { + const labelClass = inverted ? 'text-background/80' : 'text-foreground/85' + const detailClass = inverted ? 'text-background/55' : 'text-muted-foreground' + + return ( +
+
Usage unavailable
+
{message}
+
+ ) +} + +// --------------------------------------------------------------------------- +// Tooltip — progress bar section for a single window +// --------------------------------------------------------------------------- + +// Why: the base tooltip component uses `bg-foreground text-background` which +// inverts the color scheme (light bg in dark mode). These rich tooltips use +// `text-background` for primary text and `text-background/50` for secondary +// to stay readable inside the inverted tooltip container. + +// Why: color-coded by remaining capacity so users can quickly gauge urgency. +// Green = comfortable (>40% left), yellow = caution (20-40%), red = critical (<20%). +function barColor(leftPct: number): string { + if (leftPct > 40) { + return 'bg-green-500' + } + if (leftPct > 20) { + return 'bg-yellow-500' + } + return 'bg-red-500' +} + +function TooltipWindowSection({ + w, + label +}: { + w: RateLimitWindow | null + label: string +}): React.JSX.Element | null { + if (!w) { + return null + } + const leftPct = Math.max(0, Math.round(100 - w.usedPercent)) + const resetIn = w.resetsAt ? formatDuration(w.resetsAt - Date.now()) : null + + return ( +
+
{label}
+
+
+
+
+ {leftPct}% left + {resetIn && Resets in {resetIn}} +
+
+ ) +} + +// --------------------------------------------------------------------------- +// Tooltip content +// --------------------------------------------------------------------------- + +export function ProviderTooltip({ p }: { p: ProviderRateLimits | null }): React.JSX.Element { + if (!p) { + return No data available + } + + const name = p.provider === 'claude' ? 'Claude' : 'Codex' + + if (p.status === 'unavailable') { + return ( +
+
+ + {name} +
+
{p.error ?? 'CLI not found'}
+
+ ) + } + + if (p.status === 'error' && !p.session && !p.weekly) { + return ( +
+
+ + {name} +
+
{p.error ?? 'Unable to fetch usage'}
+
+ ) + } + + const updatedAgo = p.updatedAt ? `Updated ${formatTimeAgo(p.updatedAt)}` : 'Not yet updated' + + return ( +
+ {/* Header */} +
+
+ + {name} +
+
{updatedAgo}
+
+ + {/* Divider */} +
+ + {/* Session window */} + + + {/* Weekly window */} + + + {/* Stale data warning */} + {p.error ? : null} +
+ ) +} + +export function ProviderPanel({ + p, + inverted = false, + className +}: { + p: ProviderRateLimits | null + inverted?: boolean + className?: string +}): React.JSX.Element { + const textClass = inverted ? 'text-background' : 'text-foreground' + const mutedClass = inverted ? 'text-background/60' : 'text-muted-foreground' + const faintClass = inverted ? 'text-background/50' : 'text-muted-foreground/80' + const dividerClass = inverted ? 'border-background/15' : 'border-border/70' + const emptyBarClass = inverted ? 'bg-background/20' : 'bg-muted' + + if (!p) { + return No data available + } + + const name = p.provider === 'claude' ? 'Claude' : 'Codex' + + if (p.status === 'unavailable') { + return ( +
+
+ + {name} +
+
{p.error ?? 'CLI not found'}
+
+ ) + } + + if (p.status === 'error' && !p.session && !p.weekly) { + return ( +
+
+ + {name} +
+
+ +
+
+ ) + } + + const updatedAgo = p.updatedAt ? `Updated ${formatTimeAgo(p.updatedAt)}` : 'Not yet updated' + + const PanelWindowSection = ({ + w, + label + }: { + w: RateLimitWindow | null + label: string + }): React.JSX.Element | null => { + if (!w) { + return null + } + const leftPct = Math.max(0, Math.round(100 - w.usedPercent)) + const resetIn = w.resetsAt ? formatDuration(w.resetsAt - Date.now()) : null + + return ( +
+
{label}
+
+
+
+
+ {leftPct}% left + {resetIn && Resets in {resetIn}} +
+
+ ) + } + + return ( +
+
+
+ + {name} +
+
{updatedAgo}
+
+ +
+ + + + + {p.error ? : null} +
+ ) +} diff --git a/src/renderer/src/components/terminal-pane/TerminalPane.tsx b/src/renderer/src/components/terminal-pane/TerminalPane.tsx index 040de253c..44fda5f97 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPane.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPane.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { createPortal } from 'react-dom' import type { CSSProperties } from 'react' +import type { IDisposable } from '@xterm/xterm' import { useAppStore } from '../../store' import { DEFAULT_TERMINAL_DIVIDER_DARK, @@ -24,6 +25,7 @@ import { useTerminalPaneGlobalEffects } from './use-terminal-pane-global-effects import { useTerminalPaneLifecycle } from './use-terminal-pane-lifecycle' import { useTerminalPaneContextMenu } from './use-terminal-pane-context-menu' import { useNotificationDispatch } from './use-notification-dispatch' +import { connectPanePty } from './pty-connection' /** Global set of buffer-capture callbacks, one per mounted TerminalPane. * The beforeunload handler in App.tsx invokes every callback to populate @@ -57,6 +59,7 @@ export default function TerminalPane({ new Map() ) const paneTransportsRef = useRef>(new Map()) + const panePtyBindingsRef = useRef>(new Map()) const pendingWritesRef = useRef>(new Map()) const isActiveRef = useRef(isActive) isActiveRef.current = isActive @@ -85,6 +88,12 @@ export default function TerminalPane({ const setTabPaneExpanded = useAppStore((store) => store.setTabPaneExpanded) const setTabCanExpandPane = useAppStore((store) => store.setTabCanExpandPane) + const suppressPtyExit = useAppStore((store) => store.suppressPtyExit) + const pendingCodexPaneRestartIds = useAppStore((store) => store.pendingCodexPaneRestartIds) + const consumePendingCodexPaneRestart = useAppStore( + (store) => store.consumePendingCodexPaneRestart + ) + const clearCodexRestartNotice = useAppStore((store) => store.clearCodexRestartNotice) const savedLayout = useAppStore((store) => store.terminalLayoutsByTabId[tabId] ?? EMPTY_LAYOUT) const setTabLayout = useAppStore((store) => store.setTabLayout) const initialLayoutRef = useRef(savedLayout) @@ -128,6 +137,7 @@ export default function TerminalPane({ const systemPrefersDark = useSystemPrefersDark() const dispatchNotification = useNotificationDispatch(worktreeId) + const setCacheTimerStartedAt = useAppStore((store) => store.setCacheTimerStartedAt) // Memoized with useCallback so downstream hooks (useTerminalKeyboardShortcuts, // useTerminalPaneLifecycle, createExpandCollapseActions) don't tear down and @@ -250,16 +260,18 @@ export default function TerminalPane({ expandedStyleSnapshotRef, paneFontSizesRef, paneTransportsRef, + panePtyBindingsRef, pendingWritesRef, isActiveRef, onPtyExitRef, onPtyErrorRef, clearTabPtyId, + consumeSuppressedPtyExit: useAppStore((store) => store.consumeSuppressedPtyExit), updateTabTitle, updateTabPtyId, markWorktreeUnread, dispatchNotification, - setCacheTimerStartedAt: useAppStore((store) => store.setCacheTimerStartedAt), + setCacheTimerStartedAt, setTabPaneExpanded, setTabCanExpandPane, setExpandedPane, @@ -270,6 +282,91 @@ export default function TerminalPane({ setRenamingPaneId }) + const handleRestartCodexPane = useCallback( + (paneId: number) => { + const manager = managerRef.current + const pane = manager?.getPanes().find((candidate) => candidate.id === paneId) + if (!manager || !pane) { + return + } + + const transport = paneTransportsRef.current.get(paneId) + const panePtyBinding = panePtyBindingsRef.current.get(paneId) + const existingPtyId = transport?.getPtyId() + + if (existingPtyId) { + suppressPtyExit(existingPtyId) + clearCodexRestartNotice(existingPtyId) + // Why: pane-scoped Codex restarts should preserve the split layout and + // replace only the stale session in place. Clearing the PTY binding and + // consuming the upcoming suppressed exit keeps the pane mounted while a + // fresh PTY reconnects under the newly selected Codex account. + clearTabPtyId(tabId, existingPtyId) + } + + panePtyBinding?.dispose() + panePtyBindingsRef.current.delete(paneId) + transport?.destroy?.() + paneTransportsRef.current.delete(paneId) + setCacheTimerStartedAt(`${tabId}:${paneId}`, null) + + const newPaneBinding = connectPanePty(pane, manager, { + tabId, + worktreeId, + cwd, + startup: { command: 'codex' }, + paneTransportsRef, + pendingWritesRef, + isActiveRef, + onPtyExitRef, + onPtyErrorRef, + clearTabPtyId, + consumeSuppressedPtyExit: useAppStore.getState().consumeSuppressedPtyExit, + updateTabTitle, + updateTabPtyId, + markWorktreeUnread, + dispatchNotification, + setCacheTimerStartedAt + }) + panePtyBindingsRef.current.set(paneId, newPaneBinding) + manager.setActivePane(paneId, { focus: true }) + }, + [ + clearCodexRestartNotice, + clearTabPtyId, + cwd, + dispatchNotification, + markWorktreeUnread, + onPtyExitRef, + setCacheTimerStartedAt, + suppressPtyExit, + tabId, + updateTabPtyId, + updateTabTitle, + worktreeId + ] + ) + + useEffect(() => { + const manager = managerRef.current + if (!manager) { + return + } + + for (const pane of manager.getPanes()) { + const ptyId = paneTransportsRef.current.get(pane.id)?.getPtyId() + if (!ptyId || !pendingCodexPaneRestartIds[ptyId]) { + continue + } + // Why: the status-bar switcher can request a global restart for stale + // Codex sessions, but the actual execution must stay pane scoped so a + // split tab does not lose unrelated non-Codex panes. + if (consumePendingCodexPaneRestart(ptyId)) { + handleRestartCodexPane(pane.id) + } + } + }, [consumePendingCodexPaneRestart, handleRestartCodexPane, pendingCodexPaneRestartIds]) + useTerminalFontZoom({ isActive, managerRef, paneFontSizesRef, settingsRef }) useTerminalKeyboardShortcuts({ @@ -534,7 +631,6 @@ export default function TerminalPane({ } const activePane = managerRef.current?.getActivePane() - return ( <>
void> onPtyErrorRef?: React.RefObject<(paneId: number, message: string) => void> clearTabPtyId: (tabId: string, ptyId: string) => void + consumeSuppressedPtyExit: (ptyId: string) => boolean updateTabTitle: (tabId: string, title: string) => void updateTabPtyId: (tabId: string, ptyId: string) => void markWorktreeUnread: (worktreeId: string) => void @@ -31,7 +33,7 @@ export function connectPanePty( pane: ManagedPane, manager: PaneManager, deps: PtyConnectionDeps -): void { +): IDisposable { // Why: setup commands must only run once — in the initial pane of the tab. // Capture and clear the startup reference synchronously so that panes // created later by splits or layout restoration cannot re-execute the @@ -56,6 +58,14 @@ export function connectPanePty( // we must republish when a pane loses its PTY instead of waiting for a // broader layout change that may never happen. scheduleRuntimeGraphSync() + // Why: intentional restarts suppress the PTY exit ahead of time so the + // pane stays mounted and can reconnect in place. Without consuming the + // suppression here, split-pane Codex restarts would still close the pane + // because this handler runs before the tab-level close logic sees the exit. + if (deps.consumeSuppressedPtyExit(ptyId)) { + manager.setPaneGpuRendering(pane.id, true) + return + } manager.setPaneGpuRendering(pane.id, true) const panes = manager.getPanes() if (panes.length <= 1) { @@ -145,11 +155,11 @@ export function connectPanePty( }) deps.paneTransportsRef.current.set(pane.id, transport) - pane.terminal.onData((data) => { + const onDataDisposable = pane.terminal.onData((data) => { transport.sendInput(data) }) - pane.terminal.onResize(({ cols, rows }) => { + const onResizeDisposable = pane.terminal.onResize(({ cols, rows }) => { transport.resize(cols, rows) }) @@ -238,4 +248,11 @@ export function connectPanePty( } scheduleRuntimeGraphSync() }) + + return { + dispose() { + onDataDisposable.dispose() + onResizeDisposable.dispose() + } + } } diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts index 55fc036a0..9a29e6464 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts @@ -42,11 +42,13 @@ type UseTerminalPaneLifecycleDeps = { > paneFontSizesRef: React.RefObject> paneTransportsRef: React.RefObject> + panePtyBindingsRef: React.RefObject> pendingWritesRef: React.RefObject> isActiveRef: React.RefObject onPtyExitRef: React.RefObject<(ptyId: string) => void> onPtyErrorRef?: React.RefObject<(paneId: number, message: string) => void> clearTabPtyId: (tabId: string, ptyId: string) => void + consumeSuppressedPtyExit: (ptyId: string) => boolean updateTabTitle: (tabId: string, title: string) => void updateTabPtyId: (tabId: string, ptyId: string) => void markWorktreeUnread: (worktreeId: string) => void @@ -82,11 +84,13 @@ export function useTerminalPaneLifecycle({ expandedStyleSnapshotRef, paneFontSizesRef, paneTransportsRef, + panePtyBindingsRef, pendingWritesRef, isActiveRef, onPtyExitRef, onPtyErrorRef, clearTabPtyId, + consumeSuppressedPtyExit, updateTabTitle, updateTabPtyId, markWorktreeUnread, @@ -127,6 +131,7 @@ export function useTerminalPaneLifecycle({ } const expandedStyleSnapshots = expandedStyleSnapshotRef.current const paneTransports = paneTransportsRef.current + const panePtyBindings = panePtyBindingsRef.current const pendingWrites = pendingWritesRef.current const linkDisposables = linkProviderDisposablesRef.current const worktreePath = @@ -182,6 +187,7 @@ export function useTerminalPaneLifecycle({ onPtyExitRef, onPtyErrorRef, clearTabPtyId, + consumeSuppressedPtyExit, updateTabTitle, updateTabPtyId, markWorktreeUnread, @@ -221,7 +227,8 @@ export function useTerminalPaneLifecycle({ } } applyAppearance(manager) - connectPanePty(pane, manager, ptyDeps) + const panePtyBinding = connectPanePty(pane, manager, ptyDeps) + panePtyBindings.set(pane.id, panePtyBinding) scheduleRuntimeGraphSync() queueResizeAll(true) }, @@ -232,6 +239,11 @@ export function useTerminalPaneLifecycle({ linkProviderDisposablesRef.current.delete(paneId) } const transport = paneTransportsRef.current.get(paneId) + const panePtyBinding = panePtyBindings.get(paneId) + if (panePtyBinding) { + panePtyBinding.dispose() + panePtyBindings.delete(paneId) + } if (transport) { const ptyId = transport.getPtyId() if (ptyId) { @@ -424,6 +436,10 @@ export function useTerminalPaneLifecycle({ for (const transport of paneTransports.values()) { transport.destroy?.() } + for (const panePtyBinding of panePtyBindings.values()) { + panePtyBinding.dispose() + } + panePtyBindings.clear() paneTransports.clear() pendingWrites.clear() manager.destroy() diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index f0ed3d36d..18c175058 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -8,6 +8,7 @@ import { import { getVisibleWorktreeIds } from '@/components/sidebar/visible-worktrees' import { nextEditorFontZoomLevel, computeEditorFontSize } from '@/lib/editor-font-zoom' import type { UpdateStatus } from '../../../shared/types' +import type { RateLimitState } from '../../../shared/rate-limit-types' import { createUpdateToastController } from './update-toast-controller' import { zoomLevelToPercent, ZOOM_MIN, ZOOM_MAX } from '@/components/settings/SettingsConstants' import { dispatchZoomLevelChanged } from '@/lib/zoom-events' @@ -117,6 +118,13 @@ export function useIpcEvents(): void { }) ) + unsubs.push( + window.api.ui.onToggleStatusBar(() => { + const store = useAppStore.getState() + store.setStatusBarVisible(!store.statusBarVisible) + }) + ) + unsubs.push( window.api.ui.onActivateWorktree(({ repoId, worktreeId, setup }) => { void (async () => { @@ -282,6 +290,17 @@ export function useIpcEvents(): void { }) ) + // Hydrate initial rate limit state then subscribe to push updates + window.api.rateLimits.get().then((state) => { + useAppStore.getState().setRateLimitsFromPush(state as RateLimitState) + }) + + unsubs.push( + window.api.rateLimits.onUpdate((state) => { + useAppStore.getState().setRateLimitsFromPush(state as RateLimitState) + }) + ) + // Zoom handling for menu accelerators and keyboard fallback paths. unsubs.push( window.api.ui.onTerminalZoom((direction) => { diff --git a/src/renderer/src/lib/codex-session-restart.test.ts b/src/renderer/src/lib/codex-session-restart.test.ts new file mode 100644 index 000000000..e32c733b5 --- /dev/null +++ b/src/renderer/src/lib/codex-session-restart.test.ts @@ -0,0 +1,146 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { markLiveCodexSessionsForRestart } from './codex-session-restart' + +const ACCOUNT_A = 'account-a@example.com' +const ACCOUNT_B = 'account-b@example.com' +const ACCOUNT_C = 'account-c@example.com' + +describe('markLiveCodexSessionsForRestart', () => { + const originalWindow = (globalThis as { window?: typeof window }).window + + beforeEach(() => { + useAppStore.setState({ + tabsByWorktree: { + wt1: [ + { + id: 'tab-1', + ptyId: 'pty-1', + worktreeId: 'wt1', + title: 'orca-1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + ptyIdsByTabId: { + 'tab-1': ['pty-1'] + }, + pendingCodexPaneRestartIds: {}, + codexRestartNoticeByPtyId: {}, + markCodexRestartNotices: useAppStore.getState().markCodexRestartNotices + }) + + ;(globalThis as { window: typeof window }).window = { + ...originalWindow, + api: { + ...originalWindow?.api, + pty: { + ...originalWindow?.api?.pty, + getForegroundProcess: vi.fn() + } + } + } as unknown as typeof window + }) + + afterEach(() => { + if (originalWindow) { + ;(globalThis as { window: typeof window }).window = originalWindow + } else { + delete (globalThis as { window?: typeof window }).window + } + }) + + it('marks a live Codex PTY for restart', async () => { + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('codex') + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + + expect(window.api.pty.getForegroundProcess).toHaveBeenCalledWith('pty-1') + expect(useAppStore.getState().codexRestartNoticeByPtyId['pty-1']).toEqual({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + }) + + it('does not mark non-codex foreground processes', async () => { + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('zsh') + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + + expect(useAppStore.getState().codexRestartNoticeByPtyId).toEqual({}) + }) + + it('treats codex.exe as codex for Windows PTYs', async () => { + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('codex.exe') + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + + expect(useAppStore.getState().codexRestartNoticeByPtyId['pty-1']).toEqual({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + }) + + it('treats codex-prefixed packaged binaries as codex', async () => { + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('codex-aarch64-ap') + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + + expect(useAppStore.getState().codexRestartNoticeByPtyId['pty-1']).toEqual({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + }) + + it('clears stale restart notices when the selected account switches back to the live pane account', async () => { + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('codex') + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + useAppStore.getState().queueCodexPaneRestarts(['pty-1']) + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_B, + nextAccountLabel: ACCOUNT_A + }) + + expect(useAppStore.getState().codexRestartNoticeByPtyId).toEqual({}) + expect(useAppStore.getState().pendingCodexPaneRestartIds).toEqual({}) + }) + + it('preserves the pane original account across repeated switches until restart', async () => { + vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('codex') + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_B + }) + + await markLiveCodexSessionsForRestart({ + previousAccountLabel: ACCOUNT_B, + nextAccountLabel: ACCOUNT_C + }) + + expect(useAppStore.getState().codexRestartNoticeByPtyId['pty-1']).toEqual({ + previousAccountLabel: ACCOUNT_A, + nextAccountLabel: ACCOUNT_C + }) + }) +}) diff --git a/src/renderer/src/lib/codex-session-restart.ts b/src/renderer/src/lib/codex-session-restart.ts new file mode 100644 index 000000000..a3a71f2d6 --- /dev/null +++ b/src/renderer/src/lib/codex-session-restart.ts @@ -0,0 +1,63 @@ +import type { AppState } from '@/store' +import { useAppStore } from '@/store' + +function normalizeProcessName(processName: string | null): string | null { + if (!processName) { + return null + } + return processName.toLowerCase().replace(/\.exe$/, '') +} + +function isCodexForegroundProcess(processName: string | null): boolean { + const normalized = normalizeProcessName(processName) + if (!normalized) { + return false + } + // Why: node-pty exposes the OS foreground process name, which can be the + // shipped Codex binary name (for example "codex-aarch64-ap" on macOS) + // instead of the shell command the user typed. Match on a Codex prefix so + // account-switch restart prompts still appear for real Codex sessions. + return normalized === 'codex' || normalized.startsWith('codex-') +} + +async function getLiveCodexSessionPtyIds(state: AppState): Promise { + const tabs = Object.values(state.tabsByWorktree).flat() + const checks = await Promise.all( + tabs.map(async (tab) => { + const ptyIds = state.ptyIdsByTabId[tab.id] ?? [] + if (ptyIds.length === 0) { + return [] as string[] + } + + // Why: Codex sessions are not reliably discoverable from tab labels. + // Tabs keep fallback names until a CLI emits an OSC title, and Codex + // does not always do that. The foreground PTY process is the stable + // source of truth for whether this live tab is actually running Codex. + const foregroundProcesses = await Promise.all( + ptyIds.map((ptyId) => window.api.pty.getForegroundProcess(ptyId)) + ) + return ptyIds.filter((_, index) => isCodexForegroundProcess(foregroundProcesses[index])) + }) + ) + + return checks.flat() +} + +export async function markLiveCodexSessionsForRestart(args: { + previousAccountLabel: string + nextAccountLabel: string +}): Promise { + const state = useAppStore.getState() + const liveCodexSessionPtyIds = await getLiveCodexSessionPtyIds(state) + if (liveCodexSessionPtyIds.length === 0) { + return + } + + useAppStore.getState().markCodexRestartNotices( + liveCodexSessionPtyIds.map((ptyId) => ({ + ptyId, + previousAccountLabel: args.previousAccountLabel, + nextAccountLabel: args.nextAccountLabel + })) + ) +} diff --git a/src/renderer/src/store/index.ts b/src/renderer/src/store/index.ts index 79939a46c..78d9a2fea 100644 --- a/src/renderer/src/store/index.ts +++ b/src/renderer/src/store/index.ts @@ -12,6 +12,7 @@ import { createStatsSlice } from './slices/stats' import { createClaudeUsageSlice } from './slices/claude-usage' import { createCodexUsageSlice } from './slices/codex-usage' import { createBrowserSlice } from './slices/browser' +import { createRateLimitSlice } from './slices/rate-limits' export const useAppStore = create()((...a) => ({ ...createRepoSlice(...a), @@ -25,7 +26,8 @@ export const useAppStore = create()((...a) => ({ ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), ...createCodexUsageSlice(...a), - ...createBrowserSlice(...a) + ...createBrowserSlice(...a), + ...createRateLimitSlice(...a) })) export type { AppState } from './types' diff --git a/src/renderer/src/store/slices/rate-limits.ts b/src/renderer/src/store/slices/rate-limits.ts new file mode 100644 index 000000000..f393ac92b --- /dev/null +++ b/src/renderer/src/store/slices/rate-limits.ts @@ -0,0 +1,36 @@ +import type { StateCreator } from 'zustand' +import type { RateLimitState } from '../../../../shared/rate-limit-types' +import type { AppState } from '../types' + +export type RateLimitSlice = { + rateLimits: RateLimitState + fetchRateLimits: () => Promise + refreshRateLimits: () => Promise + setRateLimitsFromPush: (state: RateLimitState) => void +} + +export const createRateLimitSlice: StateCreator = (set) => ({ + rateLimits: { claude: null, codex: null }, + + fetchRateLimits: async () => { + try { + const state = await window.api.rateLimits.get() + set({ rateLimits: state }) + } catch (error) { + console.error('Failed to fetch rate limits:', error) + } + }, + + refreshRateLimits: async () => { + try { + const state = await window.api.rateLimits.refresh() + set({ rateLimits: state }) + } catch (error) { + console.error('Failed to refresh rate limits:', error) + } + }, + + setRateLimitsFromPush: (state) => { + set({ rateLimits: state }) + } +}) diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts index c4d21c3f8..df08ed7d3 100644 --- a/src/renderer/src/store/slices/store-session-cascades.test.ts +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -96,6 +96,7 @@ import { createStatsSlice } from './stats' import { createClaudeUsageSlice } from './claude-usage' import { createCodexUsageSlice } from './codex-usage' import { createBrowserSlice } from './browser' +import { createRateLimitSlice } from './rate-limits' function createTestStore() { return create()((...a) => ({ @@ -110,7 +111,8 @@ function createTestStore() { ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), ...createCodexUsageSlice(...a), - ...createBrowserSlice(...a) + ...createBrowserSlice(...a), + ...createRateLimitSlice(...a) })) } @@ -234,6 +236,41 @@ describe('removeRepo cascade', () => { }) }) +describe('restartCodexTabs', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('queues pane-scoped codex restarts without remounting the whole tab', () => { + const store = createTestStore() + const wt1 = 'repo1::/path/wt1' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [makeWorktree({ id: wt1, repoId: 'repo1', path: '/path/wt1' })] + }, + tabsByWorktree: { + [wt1]: [makeTab({ id: 'tab1', worktreeId: wt1, title: 'codex', generation: 2 })] + }, + ptyIdsByTabId: { + tab1: ['pty-a', 'pty-b'] + }, + pendingStartupByTabId: {} + }) + + store.getState().queueCodexPaneRestarts(['pty-b']) + const state = store.getState() + + expect(state.pendingCodexPaneRestartIds).toEqual({ 'pty-b': true }) + expect(state.pendingStartupByTabId).toEqual({}) + expect(state.suppressedPtyExitIds).toEqual({}) + expect(state.tabsByWorktree[wt1][0].generation).toBe(2) + }) +}) + describe('hydrateWorkspaceSession', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/src/renderer/src/store/slices/store-test-helpers.ts b/src/renderer/src/store/slices/store-test-helpers.ts index ada4371c9..1b933bebc 100644 --- a/src/renderer/src/store/slices/store-test-helpers.ts +++ b/src/renderer/src/store/slices/store-test-helpers.ts @@ -20,6 +20,7 @@ import { createStatsSlice } from './stats' import { createClaudeUsageSlice } from './claude-usage' import { createCodexUsageSlice } from './codex-usage' import { createBrowserSlice } from './browser' +import { createRateLimitSlice } from './rate-limits' export const TEST_REPO = { id: 'repo1', @@ -42,7 +43,8 @@ export function createTestStore() { ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), ...createCodexUsageSlice(...a), - ...createBrowserSlice(...a) + ...createBrowserSlice(...a), + ...createRateLimitSlice(...a) })) } diff --git a/src/renderer/src/store/slices/tabs.test.ts b/src/renderer/src/store/slices/tabs.test.ts index b9f3a5cc6..6e6ce6f44 100644 --- a/src/renderer/src/store/slices/tabs.test.ts +++ b/src/renderer/src/store/slices/tabs.test.ts @@ -91,6 +91,7 @@ import { createStatsSlice } from './stats' import { createClaudeUsageSlice } from './claude-usage' import { createCodexUsageSlice } from './codex-usage' import { createBrowserSlice } from './browser' +import { createRateLimitSlice } from './rate-limits' const WT = 'repo1::/tmp/feature' @@ -107,7 +108,8 @@ function createTestStore() { ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), ...createCodexUsageSlice(...a), - ...createBrowserSlice(...a) + ...createBrowserSlice(...a), + ...createRateLimitSlice(...a) })) } diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index cfbc6b1bc..f01e4a204 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -22,6 +22,11 @@ export type TerminalSlice = { activeTabIdByWorktree: Record ptyIdsByTabId: Record suppressedPtyExitIds: Record + pendingCodexPaneRestartIds: Record + codexRestartNoticeByPtyId: Record< + string, + { previousAccountLabel: string; nextAccountLabel: string } + > expandedPaneByTabId: Record canExpandPaneByTabId: Record terminalLayoutsByTabId: Record @@ -49,7 +54,14 @@ export type TerminalSlice = { updateTabPtyId: (tabId: string, ptyId: string) => void clearTabPtyId: (tabId: string, ptyId?: string) => void shutdownWorktreeTerminals: (worktreeId: string) => Promise + suppressPtyExit: (ptyId: string) => void consumeSuppressedPtyExit: (ptyId: string) => boolean + queueCodexPaneRestarts: (ptyIds: string[]) => void + consumePendingCodexPaneRestart: (ptyId: string) => boolean + markCodexRestartNotices: ( + notices: { ptyId: string; previousAccountLabel: string; nextAccountLabel: string }[] + ) => void + clearCodexRestartNotice: (ptyId: string) => void setTabPaneExpanded: (tabId: string, expanded: boolean) => void setTabCanExpandPane: (tabId: string, canExpand: boolean) => void setTabLayout: (tabId: string, layout: TerminalLayoutSnapshot | null) => void @@ -90,6 +102,8 @@ export const createTerminalSlice: StateCreator activeTabIdByWorktree: {}, ptyIdsByTabId: {}, suppressedPtyExitIds: {}, + pendingCodexPaneRestartIds: {}, + codexRestartNoticeByPtyId: {}, expandedPaneByTabId: {}, canExpandPaneByTabId: {}, terminalLayoutsByTabId: {}, @@ -412,7 +426,23 @@ export const createTerminalSlice: StateCreator nextPtyIdsByTabId[tabId] = ptyId ? (nextPtyIdsByTabId[tabId] ?? []).filter((id) => id !== ptyId) : [] - return { tabsByWorktree: next, ptyIdsByTabId: nextPtyIdsByTabId } + const nextPendingCodexPaneRestartIds = { ...s.pendingCodexPaneRestartIds } + const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId } + if (ptyId) { + delete nextPendingCodexPaneRestartIds[ptyId] + delete nextCodexRestartNoticeByPtyId[ptyId] + } else { + for (const currentPtyId of s.ptyIdsByTabId[tabId] ?? []) { + delete nextPendingCodexPaneRestartIds[currentPtyId] + delete nextCodexRestartNoticeByPtyId[currentPtyId] + } + } + return { + tabsByWorktree: next, + ptyIdsByTabId: nextPtyIdsByTabId, + pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds, + codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId + } }) // Bump meaningful activity when a PTY exits, but skip if this exit @@ -441,6 +471,12 @@ export const createTerminalSlice: StateCreator ...s.suppressedPtyExitIds, ...Object.fromEntries(ptyIds.map((ptyId) => [ptyId, true] as const)) } + const nextPendingCodexPaneRestartIds = { ...s.pendingCodexPaneRestartIds } + const nextCodexRestartNoticeByPtyId = { ...s.codexRestartNoticeByPtyId } + for (const ptyId of ptyIds) { + delete nextPendingCodexPaneRestartIds[ptyId] + delete nextCodexRestartNoticeByPtyId[ptyId] + } // Why: clear any queued setup and issue-command splits for the affected // tabs so stale commands do not fire unintended splits when the worktree // is later remounted. @@ -473,6 +509,8 @@ export const createTerminalSlice: StateCreator tabsByWorktree: nextTabsByWorktree, ptyIdsByTabId: nextPtyIdsByTabId, suppressedPtyExitIds: nextSuppressedPtyExitIds, + pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds, + codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId, pendingSetupSplitByTabId: nextPendingSetupSplitByTabId, pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId, browserTabsByWorktree: nextBrowserTabsByWorktree, @@ -504,6 +542,88 @@ export const createTerminalSlice: StateCreator return wasSuppressed }, + suppressPtyExit: (ptyId) => { + set((s) => ({ + suppressedPtyExitIds: { ...s.suppressedPtyExitIds, [ptyId]: true } + })) + }, + + queueCodexPaneRestarts: (ptyIds) => { + if (ptyIds.length === 0) { + return + } + set((s) => ({ + pendingCodexPaneRestartIds: { + ...s.pendingCodexPaneRestartIds, + ...Object.fromEntries(ptyIds.map((ptyId) => [ptyId, true] as const)) + } + })) + }, + + consumePendingCodexPaneRestart: (ptyId) => { + let wasQueued = false + set((s) => { + if (!s.pendingCodexPaneRestartIds[ptyId]) { + return {} + } + wasQueued = true + const next = { ...s.pendingCodexPaneRestartIds } + delete next[ptyId] + return { pendingCodexPaneRestartIds: next } + }) + return wasQueued + }, + + markCodexRestartNotices: (notices) => { + if (notices.length === 0) { + return + } + set((s) => { + const next = { ...s.codexRestartNoticeByPtyId } + const nextPendingCodexPaneRestartIds = { ...s.pendingCodexPaneRestartIds } + for (const notice of notices) { + const existing = next[notice.ptyId] + const previousAccountLabel = existing?.previousAccountLabel ?? notice.previousAccountLabel + + // Why: a live Codex pane stays on the account it originally launched + // with until that pane actually restarts. Repeated account switches + // must preserve that original pane account; otherwise A -> B -> A + // keeps showing a stale restart notice even though the pane never left + // account A and no longer needs a restart. + if (previousAccountLabel === notice.nextAccountLabel) { + delete next[notice.ptyId] + delete nextPendingCodexPaneRestartIds[notice.ptyId] + continue + } + + next[notice.ptyId] = { + previousAccountLabel, + nextAccountLabel: notice.nextAccountLabel + } + } + return { + codexRestartNoticeByPtyId: next, + pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds + } + }) + }, + + clearCodexRestartNotice: (ptyId) => { + set((s) => { + if (!s.codexRestartNoticeByPtyId[ptyId]) { + return {} + } + const next = { ...s.codexRestartNoticeByPtyId } + const nextPendingCodexPaneRestartIds = { ...s.pendingCodexPaneRestartIds } + delete next[ptyId] + delete nextPendingCodexPaneRestartIds[ptyId] + return { + codexRestartNoticeByPtyId: next, + pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds + } + }) + }, + setTabPaneExpanded: (tabId, expanded) => { set((s) => ({ expandedPaneByTabId: { ...s.expandedPaneByTabId, [tabId]: expanded } diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 99c20dcda..f32a0dde8 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -1,7 +1,15 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' -import type { PersistedUIState, UpdateStatus, WorktreeCardProperty } from '../../../../shared/types' -import { DEFAULT_WORKTREE_CARD_PROPERTIES } from '../../../../shared/constants' +import type { + PersistedUIState, + StatusBarItem, + UpdateStatus, + WorktreeCardProperty +} from '../../../../shared/types' +import { + DEFAULT_STATUS_BAR_ITEMS, + DEFAULT_WORKTREE_CARD_PROPERTIES +} from '../../../../shared/constants' type LegacyPersistedSortBy = PersistedUIState['sortBy'] | 'smart' @@ -26,6 +34,7 @@ export type UISlice = { settingsNavigationTarget: { pane: 'general' | 'appearance' | 'terminal' | 'shortcuts' | 'repo' repoId: string | null + sectionId?: string } | null openSettingsTarget: (target: NonNullable) => void clearSettingsTarget: () => void @@ -54,6 +63,10 @@ export type UISlice = { setFilterRepoIds: (ids: string[]) => void worktreeCardProperties: WorktreeCardProperty[] toggleWorktreeCardProperty: (prop: WorktreeCardProperty) => void + statusBarItems: StatusBarItem[] + toggleStatusBarItem: (item: StatusBarItem) => void + statusBarVisible: boolean + setStatusBarVisible: (v: boolean) => void pendingRevealWorktreeId: string | null revealWorktreeInSidebar: (worktreeId: string) => void clearPendingRevealWorktreeId: () => void @@ -115,6 +128,23 @@ export const createUISlice: StateCreator = (set) => ( return { worktreeCardProperties: updated } }), + statusBarItems: [...DEFAULT_STATUS_BAR_ITEMS], + toggleStatusBarItem: (item) => + set((s) => { + const current = s.statusBarItems || DEFAULT_STATUS_BAR_ITEMS + const updated = current.includes(item) + ? current.filter((i) => i !== item) + : [...current, item] + window.api.ui.set({ statusBarItems: updated }).catch(console.error) + return { statusBarItems: updated } + }), + + statusBarVisible: true, + setStatusBarVisible: (v) => { + window.api.ui.set({ statusBarVisible: v }).catch(console.error) + set({ statusBarVisible: v }) + }, + pendingRevealWorktreeId: null, revealWorktreeInSidebar: (worktreeId) => set({ pendingRevealWorktreeId: worktreeId }), clearPendingRevealWorktreeId: () => set({ pendingRevealWorktreeId: null }), @@ -145,6 +175,8 @@ export const createUISlice: StateCreator = (set) => ( uiZoomLevel: ui.uiZoomLevel ?? 0, editorFontZoomLevel: ui.editorFontZoomLevel ?? 0, worktreeCardProperties: ui.worktreeCardProperties ?? [...DEFAULT_WORKTREE_CARD_PROPERTIES], + statusBarItems: ui.statusBarItems ?? [...DEFAULT_STATUS_BAR_ITEMS], + statusBarVisible: ui.statusBarVisible ?? true, dismissedUpdateVersion: ui.dismissedUpdateVersion ?? null, persistedUIReady: true } diff --git a/src/renderer/src/store/types.ts b/src/renderer/src/store/types.ts index 41dd57a97..b507eca0d 100644 --- a/src/renderer/src/store/types.ts +++ b/src/renderer/src/store/types.ts @@ -10,6 +10,7 @@ import type { StatsSlice } from './slices/stats' import type { ClaudeUsageSlice } from './slices/claude-usage' import type { CodexUsageSlice } from './slices/codex-usage' import type { BrowserSlice } from './slices/browser' +import type { RateLimitSlice } from './slices/rate-limits' export type AppState = RepoSlice & WorktreeSlice & @@ -22,4 +23,5 @@ export type AppState = RepoSlice & StatsSlice & ClaudeUsageSlice & CodexUsageSlice & - BrowserSlice + BrowserSlice & + RateLimitSlice diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 87ae93256..49db23cf7 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -4,6 +4,7 @@ import type { PersistedState, PersistedUIState, RepoHookSettings, + StatusBarItem, WorkspaceSessionState, WorktreeCardProperty } from './types' @@ -51,6 +52,8 @@ export const DEFAULT_WORKTREE_CARD_PROPERTIES: WorktreeCardProperty[] = [ 'comment' ] +export const DEFAULT_STATUS_BAR_ITEMS: StatusBarItem[] = ['claude', 'codex'] + export const REPO_COLORS = [ '#737373', // neutral '#ef4444', // red @@ -106,7 +109,9 @@ export function getDefaultSettings(homedir: string): GlobalSettings { notifications: getDefaultNotificationSettings(), diffDefaultView: 'inline', promptCacheTimerEnabled: false, - promptCacheTtlMs: 300_000 + promptCacheTtlMs: 300_000, + codexManagedAccounts: [], + activeCodexManagedAccountId: null } } @@ -146,6 +151,8 @@ export function getDefaultUIState(): PersistedUIState { uiZoomLevel: 0, editorFontZoomLevel: 0, worktreeCardProperties: [...DEFAULT_WORKTREE_CARD_PROPERTIES], + statusBarItems: [...DEFAULT_STATUS_BAR_ITEMS], + statusBarVisible: true, dismissedUpdateVersion: null, lastUpdateCheckAt: null } diff --git a/src/shared/rate-limit-types.ts b/src/shared/rate-limit-types.ts new file mode 100644 index 000000000..53f3b91ad --- /dev/null +++ b/src/shared/rate-limit-types.ts @@ -0,0 +1,30 @@ +export type RateLimitWindow = { + /** Percentage of the window consumed (0–100). */ + usedPercent: number + /** Window duration in minutes: 300 (5h) or 10080 (7d). */ + windowMinutes: number + /** Unix ms timestamp when the window resets, if known. */ + resetsAt: number | null + /** Human-readable reset description, e.g. "2:30 PM" or "Thu". */ + resetDescription: string | null +} + +export type ProviderRateLimitStatus = 'idle' | 'fetching' | 'ok' | 'error' | 'unavailable' + +export type ProviderRateLimits = { + provider: 'claude' | 'codex' + /** 5-hour session window, null if not available. */ + session: RateLimitWindow | null + /** 7-day weekly window, null if not available. */ + weekly: RateLimitWindow | null + /** Unix ms timestamp of the last successful data update. */ + updatedAt: number + /** Human-readable error message, null when status is 'ok'. */ + error: string | null + status: ProviderRateLimitStatus +} + +export type RateLimitState = { + claude: ProviderRateLimits | null + codex: ProviderRateLimits | null +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 9d64d8991..51383f1d2 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -320,6 +320,34 @@ export type NotificationSettings = { suppressWhenFocused: boolean } +export type CodexManagedAccount = { + id: string + email: string + managedHomePath: string + providerAccountId?: string | null + workspaceLabel?: string | null + workspaceAccountId?: string | null + createdAt: number + updatedAt: number + lastAuthenticatedAt: number +} + +export type CodexManagedAccountSummary = { + id: string + email: string + providerAccountId?: string | null + workspaceLabel?: string | null + workspaceAccountId?: string | null + createdAt: number + updatedAt: number + lastAuthenticatedAt: number +} + +export type CodexRateLimitAccountsState = { + accounts: CodexManagedAccountSummary[] + activeAccountId: string | null +} + export type GlobalSettings = { workspaceDir: string nestWorkspaces: boolean @@ -359,6 +387,13 @@ export type GlobalSettings = { * 300 000 (5 min, the standard Anthropic API / Bedrock TTL) and * 3 600 000 (1 hr, for extended-TTL plans). */ promptCacheTtlMs: number + /** Why: Codex rate-limit account routing is a durable app preference owned by + * the main process, not transient UI state. Persisting the selected managed + * homes here lets Orca resolve the correct `CODEX_HOME` before the renderer + * hydrates, while keeping this scope explicitly separate from Codex usage + * analytics and external terminal sessions. */ + codexManagedAccounts: CodexManagedAccount[] + activeCodexManagedAccountId: string | null } export type NotificationEventSource = 'agent-task-complete' | 'terminal-bell' | 'test' @@ -380,6 +415,8 @@ export type NotificationDispatchResult = { export type WorktreeCardProperty = 'status' | 'unread' | 'ci' | 'issue' | 'pr' | 'comment' +export type StatusBarItem = 'claude' | 'codex' + export type PersistedUIState = { lastActiveRepoId: string | null lastActiveWorktreeId: string | null @@ -392,6 +429,8 @@ export type PersistedUIState = { uiZoomLevel: number editorFontZoomLevel: number worktreeCardProperties: WorktreeCardProperty[] + statusBarItems: StatusBarItem[] + statusBarVisible: boolean dismissedUpdateVersion: string | null lastUpdateCheckAt: number | null /** Whether Orca has already attempted to trigger the macOS notification