Add usage status bar and Codex account switching (#483)
This commit is contained in:
@@ -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<CodexRateLimitAccountsState> {
|
||||
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<CodexRateLimitAccountsState> {
|
||||
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<CodexRateLimitAccountsState> {
|
||||
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<CodexRateLimitAccountsState> {
|
||||
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<void> {
|
||||
await new Promise<void>((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<string, unknown>
|
||||
|
||||
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<string, unknown> | 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<string, unknown>
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private readRecordClaim(
|
||||
value: Record<string, unknown> | null,
|
||||
key: string
|
||||
): Record<string, unknown> | null {
|
||||
const claim = value?.[key]
|
||||
if (!claim || typeof claim !== 'object' || Array.isArray(claim)) {
|
||||
return null
|
||||
}
|
||||
return claim as Record<string, unknown>
|
||||
}
|
||||
|
||||
private readStringClaim(value: Record<string, unknown> | 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
|
||||
}
|
||||
}
|
||||
+32
-2
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
@@ -84,7 +84,8 @@ describe('registerPtyHandlers', () => {
|
||||
/** Helper: trigger pty:spawn and return the env passed to node-pty. */
|
||||
function spawnAndGetEnv(
|
||||
argsEnv?: Record<string, string>,
|
||||
processEnvOverrides?: Record<string, string | undefined>
|
||||
processEnvOverrides?: Record<string, string | undefined>,
|
||||
getSelectedCodexHomePath?: () => string | null
|
||||
): Record<string, string> {
|
||||
const savedEnv: Record<string, string | undefined> = {}
|
||||
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', () => {
|
||||
|
||||
+50
-7
@@ -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<string, string>
|
||||
|
||||
// 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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -27,7 +27,8 @@ function buildMenuOptions() {
|
||||
onOpenSettings: vi.fn(),
|
||||
onZoomIn: vi.fn(),
|
||||
onZoomOut: vi.fn(),
|
||||
onZoomReset: vi.fn()
|
||||
onZoomReset: vi.fn(),
|
||||
onToggleStatusBar: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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<string | null> {
|
||||
if (process.platform !== 'darwin') {
|
||||
return null
|
||||
}
|
||||
|
||||
return new Promise<string | null>((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<string | null> {
|
||||
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<string | null> {
|
||||
// 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<ProviderRateLimits> {
|
||||
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<ProviderRateLimits> {
|
||||
// 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'
|
||||
}
|
||||
}
|
||||
@@ -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<ProviderRateLimits> {
|
||||
const pty = await import('node-pty')
|
||||
|
||||
return new Promise<ProviderRateLimits>((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<typeof setInterval> | 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'
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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<ProviderRateLimits> {
|
||||
return new Promise<ProviderRateLimits>((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<ProviderRateLimits> {
|
||||
const pty = await import('node-pty')
|
||||
|
||||
return new Promise<ProviderRateLimits>((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<ProviderRateLimits> {
|
||||
// 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'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T> = {
|
||||
promise: Promise<T>
|
||||
resolve: (value: T) => void
|
||||
}
|
||||
|
||||
function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((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<void> } {
|
||||
return service as unknown as { fetchAll: () => Promise<void> }
|
||||
}
|
||||
|
||||
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<ProviderRateLimits>()
|
||||
const firstCodex = deferred<ProviderRateLimits>()
|
||||
|
||||
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<ProviderRateLimits>()
|
||||
const firstCodex = deferred<ProviderRateLimits>()
|
||||
const secondClaude = deferred<ProviderRateLimits>()
|
||||
const secondCodex = deferred<ProviderRateLimits>()
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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<typeof setInterval> | 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<RateLimitState> {
|
||||
// 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<RateLimitState> {
|
||||
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<void> {
|
||||
if (!this.shouldBackgroundPoll()) {
|
||||
return
|
||||
}
|
||||
if (Date.now() - this.lastFetchAt < MIN_REFETCH_MS) {
|
||||
return
|
||||
}
|
||||
await this.fetchAll()
|
||||
}
|
||||
|
||||
private async fetchAll(options?: { force?: boolean }): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
Vendored
+17
@@ -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<void>
|
||||
hasChildProcesses: (id: string) => Promise<boolean>
|
||||
getForegroundProcess: (id: string) => Promise<string | null>
|
||||
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<GlobalSettings>) => Promise<GlobalSettings>
|
||||
listFonts: () => Promise<string[]>
|
||||
}
|
||||
codexAccounts: {
|
||||
list: () => Promise<CodexRateLimitAccountsState>
|
||||
add: () => Promise<CodexRateLimitAccountsState>
|
||||
reauthenticate: (args: { accountId: string }) => Promise<CodexRateLimitAccountsState>
|
||||
remove: (args: { accountId: string }) => Promise<CodexRateLimitAccountsState>
|
||||
select: (args: { accountId: string | null }) => Promise<CodexRateLimitAccountsState>
|
||||
}
|
||||
cli: {
|
||||
getInstallStatus: () => Promise<CliInstallStatus>
|
||||
install: () => Promise<CliInstallStatus>
|
||||
@@ -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<RuntimeStatus>
|
||||
getStatus: () => Promise<RuntimeStatus>
|
||||
}
|
||||
rateLimits: {
|
||||
get: () => Promise<RateLimitState>
|
||||
refresh: () => Promise<RateLimitState>
|
||||
setPollingInterval: (ms: number) => Promise<void>
|
||||
onUpdate: (callback: (state: RateLimitState) => void) => () => void
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<boolean> =>
|
||||
ipcRenderer.invoke('pty:hasChildProcesses', { id }),
|
||||
|
||||
/** Return the PTY foreground process basename when available (e.g. "codex"). */
|
||||
getForegroundProcess: (id: string): Promise<string | null> =>
|
||||
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<string[]> => ipcRenderer.invoke('settings:listFonts')
|
||||
},
|
||||
|
||||
codexAccounts: {
|
||||
list: (): Promise<unknown> => ipcRenderer.invoke('codexAccounts:list'),
|
||||
add: (): Promise<unknown> => ipcRenderer.invoke('codexAccounts:add'),
|
||||
reauthenticate: (args: { accountId: string }): Promise<unknown> =>
|
||||
ipcRenderer.invoke('codexAccounts:reauthenticate', args),
|
||||
remove: (args: { accountId: string }): Promise<unknown> =>
|
||||
ipcRenderer.invoke('codexAccounts:remove', args),
|
||||
select: (args: { accountId: string | null }): Promise<unknown> =>
|
||||
ipcRenderer.invoke('codexAccounts:select', args)
|
||||
},
|
||||
|
||||
cli: {
|
||||
getInstallStatus: (): Promise<CliInstallStatus> => ipcRenderer.invoke('cli:getInstallStatus'),
|
||||
install: (): Promise<CliInstallStatus> => 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<RuntimeStatus> =>
|
||||
ipcRenderer.invoke('runtime:syncWindowGraph', graph),
|
||||
getStatus: (): Promise<RuntimeStatus> => ipcRenderer.invoke('runtime:getStatus')
|
||||
},
|
||||
|
||||
rateLimits: {
|
||||
get: (): Promise<RateLimitState> => ipcRenderer.invoke('rateLimits:get'),
|
||||
refresh: (): Promise<RateLimitState> => ipcRenderer.invoke('rateLimits:refresh'),
|
||||
setPollingInterval: (ms: number): Promise<void> =>
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-17
@@ -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 {
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
<div className="flex flex-row flex-1 min-h-0 overflow-hidden">
|
||||
{showSidebar ? <Sidebar /> : null}
|
||||
<div className="relative flex flex-1 min-w-0 min-h-0 overflow-hidden">
|
||||
<div className="flex flex-1 min-w-0 min-h-0 flex-col">
|
||||
<div
|
||||
className={
|
||||
activeView === 'settings' || !activeWorktreeId
|
||||
? 'hidden flex-1 min-w-0 min-h-0'
|
||||
: 'flex flex-1 min-w-0 min-h-0'
|
||||
}
|
||||
>
|
||||
<Terminal />
|
||||
<div className="flex flex-row flex-1 min-h-0 overflow-hidden">
|
||||
{showSidebar ? <Sidebar /> : null}
|
||||
<div className="relative flex flex-1 min-w-0 min-h-0 overflow-hidden">
|
||||
<div className="flex flex-1 min-w-0 min-h-0 flex-col">
|
||||
<div
|
||||
className={
|
||||
activeView === 'settings' || !activeWorktreeId
|
||||
? 'hidden flex-1 min-w-0 min-h-0'
|
||||
: 'flex flex-1 min-w-0 min-h-0'
|
||||
}
|
||||
>
|
||||
<Terminal />
|
||||
</div>
|
||||
{activeView === 'settings' ? <Settings /> : !activeWorktreeId ? <Landing /> : null}
|
||||
</div>
|
||||
{activeView === 'settings' ? <Settings /> : !activeWorktreeId ? <Landing /> : null}
|
||||
</div>
|
||||
{showSidebar && rightSidebarOpen ? <RightSidebar /> : null}
|
||||
</div>
|
||||
{showSidebar && rightSidebarOpen ? <RightSidebar /> : null}
|
||||
</div>
|
||||
<StatusBar />
|
||||
</TooltipProvider>
|
||||
<QuickOpen />
|
||||
<WorktreeJumpPalette />
|
||||
<ZoomOverlay />
|
||||
|
||||
@@ -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 (
|
||||
<div className="pointer-events-none absolute right-3 top-3 z-20">
|
||||
<div className="pointer-events-auto flex items-center gap-2 rounded-lg border border-border/80 bg-popover/95 px-2 py-1.5 shadow-lg backdrop-blur-sm">
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
Codex is using the previous account
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => queueCodexPaneRestarts(staleWorktreePtyIds)}
|
||||
className="inline-flex items-center gap-1.5 rounded-md bg-foreground px-2 py-1 text-[11px] font-medium text-background transition-colors hover:opacity-90"
|
||||
>
|
||||
<RefreshCw className="size-3" />
|
||||
Restart
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
for (const ptyId of staleWorktreePtyIds) {
|
||||
clearCodexRestartNotice(ptyId)
|
||||
}
|
||||
}}
|
||||
className="rounded-md px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground"
|
||||
>
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
{worktreeTabs.map((tab) => (
|
||||
<TerminalPane
|
||||
key={`${tab.id}-${tab.generation ?? 0}`}
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
splitting individual settings into separate files would scatter related controls without a
|
||||
meaningful abstraction boundary. */
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { GlobalSettings } from '../../../../shared/types'
|
||||
import type { CodexRateLimitAccountsState, GlobalSettings } from '../../../../shared/types'
|
||||
import { Button } from '../ui/button'
|
||||
import { Input } from '../ui/input'
|
||||
import { Label } from '../ui/label'
|
||||
import { Separator } from '../ui/separator'
|
||||
import { Download, FolderOpen, Loader2, RefreshCw, Timer } from 'lucide-react'
|
||||
import { Download, FolderOpen, Loader2, Plus, RefreshCw, Timer, Trash2 } from 'lucide-react'
|
||||
import { useAppStore } from '../../store'
|
||||
import { CliSection } from './CliSection'
|
||||
import { toast } from 'sonner'
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { clampNumber } from '@/lib/terminal-theme'
|
||||
import {
|
||||
GENERAL_BROWSER_SEARCH_ENTRIES,
|
||||
GENERAL_CODEX_ACCOUNTS_SEARCH_ENTRIES,
|
||||
GENERAL_CACHE_TIMER_SEARCH_ENTRIES,
|
||||
GENERAL_CLI_SEARCH_ENTRIES,
|
||||
GENERAL_EDITOR_SEARCH_ENTRIES,
|
||||
@@ -29,6 +30,15 @@ import {
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'
|
||||
import { SearchableSetting } from './SearchableSetting'
|
||||
import { matchesSettingsSearch } from './settings-search'
|
||||
import { markLiveCodexSessionsForRestart } from '@/lib/codex-session-restart'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '../ui/dialog'
|
||||
|
||||
export { GENERAL_PANE_SEARCH_ENTRIES }
|
||||
|
||||
@@ -37,13 +47,66 @@ type GeneralPaneProps = {
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => 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<string | null>(null)
|
||||
const [autoSaveDelayDraft, setAutoSaveDelayDraft] = useState(
|
||||
String(settings.editorAutoSaveDelayMs)
|
||||
)
|
||||
const [codexAccounts, setCodexAccounts] = useState<CodexRateLimitAccountsState>({
|
||||
accounts: [],
|
||||
activeAccountId: null
|
||||
})
|
||||
const [codexAction, setCodexAction] = useState<
|
||||
'idle' | 'adding' | `reauth:${string}` | `remove:${string}` | `select:${string | 'system'}`
|
||||
>('idle')
|
||||
const [removeAccountId, setRemoveAccountId] = useState<string | null>(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<void> => {
|
||||
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<void> => {
|
||||
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<CodexRateLimitAccountsState>
|
||||
): Promise<void> => {
|
||||
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) ? (
|
||||
<section key="workspace" className="space-y-4">
|
||||
@@ -159,7 +292,6 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea
|
||||
/>
|
||||
</button>
|
||||
</SearchableSetting>
|
||||
|
||||
</section>
|
||||
) : null,
|
||||
matchesSettingsSearch(searchQuery, GENERAL_BROWSER_SEARCH_ENTRIES) ? (
|
||||
@@ -394,6 +526,176 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea
|
||||
)}
|
||||
</section>
|
||||
) : null,
|
||||
matchesSettingsSearch(searchQuery, GENERAL_CODEX_ACCOUNTS_SEARCH_ENTRIES) ? (
|
||||
<section key="codex-accounts" id="general-codex-accounts" className="space-y-4 scroll-mt-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-semibold">Codex Accounts</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Add and switch between Codex accounts in Orca.
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Each account keeps its own local sign-in context in Orca. Account auth stays on this
|
||||
device.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<SearchableSetting
|
||||
title="Codex Accounts"
|
||||
description="Manage which Codex account Orca uses for live rate limit fetching."
|
||||
keywords={['codex', 'account', 'rate limit', 'status bar', 'quota']}
|
||||
className="space-y-3 px-1 py-2"
|
||||
>
|
||||
{/* 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. */}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Accounts</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Add a Codex account to use it in Orca.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void runCodexAccountAction('adding', () => window.api.codexAccounts.add())
|
||||
}
|
||||
disabled={codexAction !== 'idle'}
|
||||
className="gap-2"
|
||||
>
|
||||
{codexAction === 'adding' ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<Plus className="size-3.5" />
|
||||
)}
|
||||
Add Account
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{codexAccounts.accounts.length === 0 ? (
|
||||
<div className="rounded-md border border-dashed border-border/70 px-3 py-4 text-xs text-muted-foreground">
|
||||
No managed Codex accounts yet. Orca will use your system default Codex login until you
|
||||
add one here.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
void runCodexAccountAction('select:system', () =>
|
||||
window.api.codexAccounts.select({ accountId: null })
|
||||
)
|
||||
}
|
||||
disabled={codexAction !== 'idle'}
|
||||
className={`flex min-h-[58px] w-full items-center justify-between gap-3 rounded-md border px-3 py-3 text-left transition-colors ${
|
||||
codexAccounts.activeAccountId === null
|
||||
? 'border-foreground/25 bg-accent/20'
|
||||
: 'border-border/70 hover:bg-accent/10'
|
||||
} disabled:cursor-default disabled:opacity-100`}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 text-sm">
|
||||
<span className="font-medium">System default</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
Use your current system Codex login.
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{codexAccounts.activeAccountId === null ? (
|
||||
<span className="rounded-full bg-foreground px-2 py-0.5 text-[10px] font-medium text-background">
|
||||
Active
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
{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 (
|
||||
<button
|
||||
key={account.id}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
void runCodexAccountAction(`select:${account.id}`, () =>
|
||||
window.api.codexAccounts.select({ accountId: account.id })
|
||||
)
|
||||
}
|
||||
disabled={isBusy}
|
||||
className={`flex min-h-[58px] w-full items-center justify-between gap-3 rounded-md border px-3 py-3 text-left transition-colors ${
|
||||
isActive
|
||||
? 'border-foreground/25 bg-accent/20'
|
||||
: 'border-border/70 hover:bg-accent/10'
|
||||
}`}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-3 max-md:flex-col max-md:items-start">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 text-sm">
|
||||
<span className="truncate font-medium">{account.email}</span>
|
||||
{account.workspaceLabel ? (
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{account.workspaceLabel}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{formatAccountTimestamp(account.lastAuthenticatedAt)}
|
||||
</span>
|
||||
{isActive ? (
|
||||
<span className="shrink-0 rounded-full bg-foreground px-2 py-0.5 text-[10px] font-medium text-background">
|
||||
Active
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center justify-end gap-2 max-md:w-full max-md:flex-wrap">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
void runCodexAccountAction(`reauth:${account.id}`, () =>
|
||||
window.api.codexAccounts.reauthenticate({ accountId: account.id })
|
||||
)
|
||||
}}
|
||||
disabled={isBusy}
|
||||
className="h-8 gap-2 px-3"
|
||||
>
|
||||
{isReauthing ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="size-3.5" />
|
||||
)}
|
||||
Re-authenticate
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
setRemoveAccountId(account.id)
|
||||
}}
|
||||
disabled={isBusy}
|
||||
className="h-8 gap-2 px-3"
|
||||
>
|
||||
{isRemoving ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="size-3.5" />
|
||||
)}
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</SearchableSetting>
|
||||
</section>
|
||||
) : null,
|
||||
matchesSettingsSearch(searchQuery, GENERAL_UPDATE_SEARCH_ENTRIES) ? (
|
||||
<section key="updates" className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
@@ -489,6 +791,40 @@ export function GeneralPane({ settings, updateSettings }: GeneralPaneProps): Rea
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<Dialog
|
||||
open={removeAccountId !== null}
|
||||
onOpenChange={(open) => !open && setRemoveAccountId(null)}
|
||||
>
|
||||
<DialogContent showCloseButton={false}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Remove Codex Account?</DialogTitle>
|
||||
<DialogDescription>
|
||||
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.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setRemoveAccountId(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
const accountId = removeAccountId
|
||||
if (!accountId) {
|
||||
return
|
||||
}
|
||||
setRemoveAccountId(null)
|
||||
void runCodexAccountAction(`remove:${accountId}`, () =>
|
||||
window.api.codexAccounts.remove({ accountId })
|
||||
)
|
||||
}}
|
||||
>
|
||||
Remove Account
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{visibleSections.map((section, index) => (
|
||||
<div key={index} className="space-y-8">
|
||||
{index > 0 ? <Separator /> : null}
|
||||
|
||||
@@ -80,6 +80,7 @@ function Settings(): React.JSX.Element {
|
||||
const [activeSectionId, setActiveSectionId] = useState('general')
|
||||
const contentScrollRef = useRef<HTMLDivElement | null>(null)
|
||||
const terminalFontsLoadedRef = useRef(false)
|
||||
const pendingNavSectionRef = useRef<string | null>(null)
|
||||
const pendingScrollTargetRef = useRef<string | null>(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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
]
|
||||
|
||||
@@ -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 (
|
||||
<div className="w-[48px] h-[6px] rounded-full bg-muted overflow-hidden flex-shrink-0">
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-300 bg-muted-foreground/40"
|
||||
style={{ width: `${Math.min(100, Math.max(0, leftPct))}%` }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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 (
|
||||
<span className="tabular-nums">
|
||||
{left}% {label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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 (
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground">
|
||||
<ProviderIcon provider={provider} />
|
||||
<span className="animate-pulse">···</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Fetching with no prior data
|
||||
if (p.status === 'fetching' && !p.session && !p.weekly) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground">
|
||||
<ProviderIcon provider={provider} />
|
||||
<span className="animate-pulse">···</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Unavailable (CLI not installed)
|
||||
if (p.status === 'unavailable') {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground/50">
|
||||
<ProviderIcon provider={provider} /> --
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Error with no data
|
||||
if (p.status === 'error' && !p.session && !p.weekly) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground">
|
||||
<ProviderIcon provider={provider} />
|
||||
<AlertTriangle size={11} className="text-muted-foreground/80" />
|
||||
{!compact && <span className="text-[11px] font-medium">{statusLabel}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// 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 ? (
|
||||
<RefreshCw size={10} className="animate-spin text-muted-foreground" />
|
||||
) : isStale ? (
|
||||
<AlertTriangle size={11} className="text-muted-foreground/80" />
|
||||
) : null
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<ProviderIcon provider={provider} />
|
||||
{p.session && !compact && <MiniBar leftPct={Math.max(0, 100 - p.session.usedPercent)} />}
|
||||
{p.session && <WindowLabel w={p.session} label="5h" />}
|
||||
{p.session && p.weekly && <span className="text-muted-foreground">·</span>}
|
||||
{p.weekly && <WindowLabel w={p.weekly} label="wk" />}
|
||||
<span className="inline-flex w-3 justify-center">
|
||||
{/* 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}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
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<CodexRateLimitAccountsState>({
|
||||
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<void> => {
|
||||
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 (
|
||||
<ProviderDetailsMenu
|
||||
provider={codex}
|
||||
compact={compact}
|
||||
iconOnly={iconOnly}
|
||||
ariaLabel="Open Codex details and account switcher"
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<DropdownMenuLabel>Codex Account</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onSelect={(event) => {
|
||||
event.preventDefault()
|
||||
setAccountsExpanded((prev) => !prev)
|
||||
}}
|
||||
>
|
||||
<span className="max-w-[180px] truncate text-[12px] text-foreground">
|
||||
{activeAccountLabel}
|
||||
</span>
|
||||
{accountsExpanded ? (
|
||||
<ChevronDown className="ml-auto size-3.5 text-muted-foreground/85" />
|
||||
) : (
|
||||
<ChevronRight className="ml-auto size-3.5 text-muted-foreground/85" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{accountsExpanded ? (
|
||||
<div className="px-1 pb-1">
|
||||
<div className="px-2 py-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
|
||||
Switch to
|
||||
</div>
|
||||
<div className="max-h-[220px] overflow-y-auto rounded-md border border-border/60 bg-accent/5 p-1">
|
||||
{availableSwitchTargets.length === 0 ? (
|
||||
<div className="px-2 py-1.5 text-[11px] text-muted-foreground">No other accounts</div>
|
||||
) : null}
|
||||
{availableSwitchTargets.map((target) => (
|
||||
<DropdownMenuItem
|
||||
key={target.id ?? 'system'}
|
||||
onSelect={(event) => {
|
||||
// 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}
|
||||
>
|
||||
<span className="truncate">{target.label}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{staleCodexTabCount > 0 ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<div className="px-2 py-2">
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
{/* 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 ? (
|
||||
<span className="mt-0.5 block">
|
||||
Visible sessions restart now. Others restart when their worktree becomes active.
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => queueCodexPaneRestarts(staleCodexPtyIds)}
|
||||
className="mt-2 inline-flex w-full items-center justify-center rounded-md border border-border/70 px-2.5 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent/60"
|
||||
>
|
||||
{staleCodexSessionCount === 1
|
||||
? 'Restart Session'
|
||||
: `Restart ${staleCodexSessionCount} Sessions`}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onSelect={() => {
|
||||
openSettingsTarget({
|
||||
pane: 'general',
|
||||
repoId: null,
|
||||
sectionId: 'general-codex-accounts'
|
||||
})
|
||||
setActiveView('settings')
|
||||
}}
|
||||
>
|
||||
Manage Accounts…
|
||||
</DropdownMenuItem>
|
||||
</ProviderDetailsMenu>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<DropdownMenu open={open} onOpenChange={onOpenChange}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center cursor-pointer rounded px-1 py-0.5 hover:bg-accent/70"
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{iconOnly ? (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span
|
||||
className={`inline-block h-2 w-2 rounded-full ${provider.session || provider.weekly ? 'bg-muted-foreground/60' : 'bg-muted-foreground/30'}`}
|
||||
/>
|
||||
<span className="text-muted-foreground">
|
||||
{provider.provider === 'claude' ? 'C' : 'X'}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<ProviderSegment p={provider} compact={compact} />
|
||||
)}
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent side="top" align="start" sideOffset={8} className="w-[260px]">
|
||||
<div className="p-2">
|
||||
<ProviderPanel p={provider} />
|
||||
</div>
|
||||
{children ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{children}
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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<HTMLDivElement>(null)
|
||||
const [isRefreshing, setIsRefreshing] = useState(false)
|
||||
|
||||
const [containerWidth, setContainerWidth] = useState(900)
|
||||
const resizeObserverRef = useRef<ResizeObserver | null>(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 (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
<div
|
||||
ref={containerRefCallback}
|
||||
className="flex items-center h-6 min-h-[24px] px-3 gap-4 border-t border-border bg-[var(--bg-titlebar,var(--card))] text-xs select-none shrink-0"
|
||||
>
|
||||
{iconOnly ? (
|
||||
<>
|
||||
{showClaude && (
|
||||
<ProviderDetailsMenu
|
||||
provider={claude}
|
||||
compact={compact}
|
||||
iconOnly
|
||||
ariaLabel="Open Claude usage details"
|
||||
/>
|
||||
)}
|
||||
{showCodex && <CodexSwitcherMenu codex={codex} compact={compact} iconOnly />}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{showClaude && (
|
||||
<ProviderDetailsMenu
|
||||
provider={claude}
|
||||
compact={compact}
|
||||
iconOnly={false}
|
||||
ariaLabel="Open Claude usage details"
|
||||
/>
|
||||
)}
|
||||
|
||||
{showCodex && <CodexSwitcherMenu codex={codex} compact={compact} iconOnly={false} />}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
{anyVisible && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
className="p-0.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40"
|
||||
aria-label="Refresh rate limits"
|
||||
>
|
||||
<RefreshCw size={11} className={isRefreshing ? 'animate-spin' : ''} />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={6}>
|
||||
Refresh usage data
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
|
||||
<ContextMenuContent className="min-w-0 w-fit">
|
||||
<ContextMenuCheckboxItem
|
||||
checked={statusBarItems.includes('claude')}
|
||||
onCheckedChange={() => toggleStatusBarItem('claude')}
|
||||
>
|
||||
Claude Usage
|
||||
</ContextMenuCheckboxItem>
|
||||
<ContextMenuCheckboxItem
|
||||
checked={statusBarItems.includes('codex')}
|
||||
onCheckedChange={() => toggleStatusBarItem('codex')}
|
||||
>
|
||||
Codex Usage
|
||||
</ContextMenuCheckboxItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export function OpenAIIcon({ size = 14 }: { size?: number }): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
fillRule="evenodd"
|
||||
height={size}
|
||||
width={size}
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function ClaudeIcon({ size = 14 }: { size?: number }): React.JSX.Element {
|
||||
return (
|
||||
<svg height={size} width={size} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"
|
||||
fill="#D97757"
|
||||
fillRule="nonzero"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -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 <OpenAIIcon size={13} />
|
||||
}
|
||||
return <ClaudeIcon size={13} />
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="space-y-0.5">
|
||||
<div className={`text-[11px] font-medium ${labelClass}`}>Usage unavailable</div>
|
||||
<div className={detailClass}>{message}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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 (
|
||||
<div className="space-y-1">
|
||||
<div className="font-medium text-background">{label}</div>
|
||||
<div className="w-full h-[6px] rounded-full bg-background/20 overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded-full ${barColor(leftPct)} transition-all duration-300`}
|
||||
style={{ width: `${Math.min(100, Math.max(0, leftPct))}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between text-background/60">
|
||||
<span>{leftPct}% left</span>
|
||||
{resetIn && <span>Resets in {resetIn}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tooltip content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function ProviderTooltip({ p }: { p: ProviderRateLimits | null }): React.JSX.Element {
|
||||
if (!p) {
|
||||
return <span className="text-xs text-background/60">No data available</span>
|
||||
}
|
||||
|
||||
const name = p.provider === 'claude' ? 'Claude' : 'Codex'
|
||||
|
||||
if (p.status === 'unavailable') {
|
||||
return (
|
||||
<div className="text-xs w-[200px]">
|
||||
<div className="flex items-center gap-1.5 font-medium text-background">
|
||||
<ProviderIcon provider={p.provider} />
|
||||
{name}
|
||||
</div>
|
||||
<div className="text-background/60">{p.error ?? 'CLI not found'}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (p.status === 'error' && !p.session && !p.weekly) {
|
||||
return (
|
||||
<div className="text-xs w-[200px]">
|
||||
<div className="flex items-center gap-1.5 font-medium text-background">
|
||||
<ProviderIcon provider={p.provider} />
|
||||
{name}
|
||||
</div>
|
||||
<div className="text-background/60">{p.error ?? 'Unable to fetch usage'}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const updatedAgo = p.updatedAt ? `Updated ${formatTimeAgo(p.updatedAt)}` : 'Not yet updated'
|
||||
|
||||
return (
|
||||
<div className="text-xs w-[200px] space-y-3">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 font-medium text-background text-[13px]">
|
||||
<ProviderIcon provider={p.provider} />
|
||||
{name}
|
||||
</div>
|
||||
<div className="text-background/50">{updatedAgo}</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="border-t border-background/15" />
|
||||
|
||||
{/* Session window */}
|
||||
<TooltipWindowSection w={p.session} label="Session" />
|
||||
|
||||
{/* Weekly window */}
|
||||
<TooltipWindowSection w={p.weekly} label="Weekly" />
|
||||
|
||||
{/* Stale data warning */}
|
||||
{p.error ? <ErrorMessage message={p.error} inverted /> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 <span className={`text-xs ${mutedClass}`}>No data available</span>
|
||||
}
|
||||
|
||||
const name = p.provider === 'claude' ? 'Claude' : 'Codex'
|
||||
|
||||
if (p.status === 'unavailable') {
|
||||
return (
|
||||
<div className={`text-xs ${className ?? 'w-full'}`}>
|
||||
<div className={`flex items-center gap-1.5 font-medium ${textClass}`}>
|
||||
<ProviderIcon provider={p.provider} />
|
||||
{name}
|
||||
</div>
|
||||
<div className={mutedClass}>{p.error ?? 'CLI not found'}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (p.status === 'error' && !p.session && !p.weekly) {
|
||||
return (
|
||||
<div className={`text-xs ${className ?? 'w-full'}`}>
|
||||
<div className={`flex items-center gap-1.5 font-medium ${textClass}`}>
|
||||
<ProviderIcon provider={p.provider} />
|
||||
{name}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<ErrorMessage message={p.error ?? 'Unable to fetch usage'} inverted={inverted} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="space-y-1">
|
||||
<div className={`font-medium ${textClass}`}>{label}</div>
|
||||
<div className={`h-[6px] w-full overflow-hidden rounded-full ${emptyBarClass}`}>
|
||||
<div
|
||||
className={`h-full rounded-full ${barColor(leftPct)} transition-all duration-300`}
|
||||
style={{ width: `${Math.min(100, Math.max(0, leftPct))}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className={`flex justify-between ${mutedClass}`}>
|
||||
<span>{leftPct}% left</span>
|
||||
{resetIn && <span>Resets in {resetIn}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`${className ?? 'w-full'} space-y-3 text-xs`}>
|
||||
<div>
|
||||
<div className={`flex items-center gap-1.5 text-[13px] font-medium ${textClass}`}>
|
||||
<ProviderIcon provider={p.provider} />
|
||||
{name}
|
||||
</div>
|
||||
<div className={faintClass}>{updatedAgo}</div>
|
||||
</div>
|
||||
|
||||
<div className={`border-t ${dividerClass}`} />
|
||||
|
||||
<PanelWindowSection w={p.session} label="Session" />
|
||||
<PanelWindowSection w={p.weekly} label="Weekly" />
|
||||
|
||||
{p.error ? <ErrorMessage message={p.error} inverted={inverted} /> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<Map<number, PtyTransport>>(new Map())
|
||||
const panePtyBindingsRef = useRef<Map<number, IDisposable>>(new Map())
|
||||
const pendingWritesRef = useRef<Map<number, string>>(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 (
|
||||
<>
|
||||
<div
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PaneManager, ManagedPane } from '@/lib/pane-manager/pane-manager'
|
||||
import type { IDisposable } from '@xterm/xterm'
|
||||
import { isGeminiTerminalTitle, isClaudeAgent } from '@/lib/agent-status'
|
||||
import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph'
|
||||
import { useAppStore } from '@/store'
|
||||
@@ -17,6 +18,7 @@ type PtyConnectionDeps = {
|
||||
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
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,11 +42,13 @@ type UseTerminalPaneLifecycleDeps = {
|
||||
>
|
||||
paneFontSizesRef: React.RefObject<Map<number, number>>
|
||||
paneTransportsRef: React.RefObject<Map<number, PtyTransport>>
|
||||
panePtyBindingsRef: React.RefObject<Map<number, IDisposable>>
|
||||
pendingWritesRef: React.RefObject<Map<number, string>>
|
||||
isActiveRef: React.RefObject<boolean>
|
||||
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()
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<string[]> {
|
||||
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<void> {
|
||||
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
|
||||
}))
|
||||
)
|
||||
}
|
||||
@@ -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<AppState>()((...a) => ({
|
||||
...createRepoSlice(...a),
|
||||
@@ -25,7 +26,8 @@ export const useAppStore = create<AppState>()((...a) => ({
|
||||
...createStatsSlice(...a),
|
||||
...createClaudeUsageSlice(...a),
|
||||
...createCodexUsageSlice(...a),
|
||||
...createBrowserSlice(...a)
|
||||
...createBrowserSlice(...a),
|
||||
...createRateLimitSlice(...a)
|
||||
}))
|
||||
|
||||
export type { AppState } from './types'
|
||||
|
||||
@@ -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<void>
|
||||
refreshRateLimits: () => Promise<void>
|
||||
setRateLimitsFromPush: (state: RateLimitState) => void
|
||||
}
|
||||
|
||||
export const createRateLimitSlice: StateCreator<AppState, [], [], RateLimitSlice> = (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 })
|
||||
}
|
||||
})
|
||||
@@ -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<AppState>()((...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()
|
||||
|
||||
@@ -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)
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ export type TerminalSlice = {
|
||||
activeTabIdByWorktree: Record<string, string | null>
|
||||
ptyIdsByTabId: Record<string, string[]>
|
||||
suppressedPtyExitIds: Record<string, true>
|
||||
pendingCodexPaneRestartIds: Record<string, true>
|
||||
codexRestartNoticeByPtyId: Record<
|
||||
string,
|
||||
{ previousAccountLabel: string; nextAccountLabel: string }
|
||||
>
|
||||
expandedPaneByTabId: Record<string, boolean>
|
||||
canExpandPaneByTabId: Record<string, boolean>
|
||||
terminalLayoutsByTabId: Record<string, TerminalLayoutSnapshot>
|
||||
@@ -49,7 +54,14 @@ export type TerminalSlice = {
|
||||
updateTabPtyId: (tabId: string, ptyId: string) => void
|
||||
clearTabPtyId: (tabId: string, ptyId?: string) => void
|
||||
shutdownWorktreeTerminals: (worktreeId: string) => Promise<void>
|
||||
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<AppState, [], [], TerminalSlice>
|
||||
activeTabIdByWorktree: {},
|
||||
ptyIdsByTabId: {},
|
||||
suppressedPtyExitIds: {},
|
||||
pendingCodexPaneRestartIds: {},
|
||||
codexRestartNoticeByPtyId: {},
|
||||
expandedPaneByTabId: {},
|
||||
canExpandPaneByTabId: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
@@ -412,7 +426,23 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
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<AppState, [], [], TerminalSlice>
|
||||
...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<AppState, [], [], TerminalSlice>
|
||||
tabsByWorktree: nextTabsByWorktree,
|
||||
ptyIdsByTabId: nextPtyIdsByTabId,
|
||||
suppressedPtyExitIds: nextSuppressedPtyExitIds,
|
||||
pendingCodexPaneRestartIds: nextPendingCodexPaneRestartIds,
|
||||
codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId,
|
||||
pendingSetupSplitByTabId: nextPendingSetupSplitByTabId,
|
||||
pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId,
|
||||
browserTabsByWorktree: nextBrowserTabsByWorktree,
|
||||
@@ -504,6 +542,88 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
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 }
|
||||
|
||||
@@ -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<UISlice['settingsNavigationTarget']>) => 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<AppState, [], [], UISlice> = (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<AppState, [], [], UISlice> = (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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user