Repository navigation
Expand file tree
/
Copy pathsidebar-state.ts
More file actions
1076 lines (1008 loc) · 34 KB
/
Copy pathsidebar-state.ts
File metadata and controls
1076 lines (1008 loc) · 34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export interface QuotaWindow {
usedPercent: number
remainingPercent: number
resetsAt?: string
checkedAt?: number
}
export interface ScopedQuotaWindow extends QuotaWindow {
id: string
title: string
modelId?: string
modelName: string
}
export interface AccountQuota {
checkedAt?: number
five_hour?: QuotaWindow
seven_day?: QuotaWindow
scoped?: ScopedQuotaWindow[]
extraUsage?: {
used: { amountMinor: number; currency: string; exponent: number }
limit: { amountMinor: number; currency: string; exponent: number }
utilizationPercent?: number
severity?: string
exhausted: boolean
}
bindingWindow?: string
fallbackAdvised?: boolean
}
export interface SidebarAccountState {
id: string
label: string | undefined
quota: AccountQuota | null
enabled: boolean
stateLine?: string
quotaDated?: boolean
// True when the account's refresh token is permanently dead (400
// invalid_grant) and it needs a re-login — distinct from a transient backoff.
needsReauth: boolean
// True when the vault credential needs a new sign-in.
vaultReauth?: boolean
// A gate alone does not prove the sidecar can serve a request.
vaultServed?: boolean
custodyState?:
| 'off'
| 'on-vault-served'
| 'on-vault-reauth'
| 'on-cold'
| 'unknown-identity'
| 'on-identity-mismatch'
| 'on-corrupt-binding'
tierLabel?: string
}
export interface FableRecoverySidebarState {
sessionId: string
mode: 'opus' | 'fable' | 'server'
remaining: number
changedAt: number
/**
* The model id the user originally requested (e.g. 'claude-fable-5' or
* 'claude-opus-5'). Optional for backward compatibility with pre-Opus-5
* state files; older recoveries default to Fable 5 in the summary.
*/
requestedModelId?: string
/** Anthropic-selected target while server-side safety fallback is active. */
targetModelId?: string
}
export interface PrimeSidebarAccountState {
id: string
label: string
nextDueAt?: number | null
lastPrimedAt?: number | null
lastResult?: 'ok' | 'error' | 'skipped'
usage?: PrimeUsageCounters
estimatedCostUsd?: number
}
export interface SidebarState {
main: {
quota: AccountQuota | null
enabled?: boolean
tierLabel?: string
stateLine?: string
quotaDated?: boolean
quotaBackedOff?: boolean
quotaBackoffUntil?: number
refreshBackedOff?: boolean
refreshBackoffUntil?: number
}
fallbacks: SidebarAccountState[]
activeId: string | undefined
route: string
relay: { enabled: boolean; transport: string } | null
fastMode: boolean
cacheKeep?: {
enabled: boolean
window?: string
trackedSessions?: number
}
/**
* Prime opt-in flag plus per-account status. Absent on the wire when
* the feature is disabled — `normalizeSidebarState` validates every
* account independently and drops any entry it cannot prove.
*/
prime?: {
enabled: boolean
accounts: PrimeSidebarAccountState[]
}
fableRecoveries?: FableRecoverySidebarState[]
lastUpdated: number
}
import { randomUUID } from 'node:crypto'
import {
mkdir,
readFile,
rename,
rm,
rmdir,
stat,
unlink,
writeFile,
} from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import type { PrimeUsageCounters } from '@cortexkit/anthropic-auth-core'
import {
formatQuota,
isQuotaStale,
logger,
quotaDisplayProjection,
} from '@cortexkit/anthropic-auth-core'
const STATE_FILE_ENV = 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE'
const DEFAULT_STATE_DIR = join(tmpdir(), 'opencode-anthropic-auth')
const DEFAULT_STATE_FILE = join(DEFAULT_STATE_DIR, 'sidebar-state.json')
export function getSidebarStateFile(): string {
return process.env[STATE_FILE_ENV] || DEFAULT_STATE_FILE
}
export const DEFAULT_SIDEBAR_STATE: SidebarState = {
main: { quota: null },
fallbacks: [],
activeId: undefined,
route: 'main',
relay: null,
fastMode: false,
lastUpdated: 0,
}
function isRecord(v: unknown): v is Record<string, unknown> {
return v !== null && typeof v === 'object' && !Array.isArray(v)
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value)
}
function normalizePrimeUsage(value: unknown): PrimeUsageCounters | undefined {
if (!isRecord(value)) return undefined
const count = Number(value.count)
const inputTokens = Number(value.inputTokens)
const outputTokens = Number(value.outputTokens)
const since = Number(value.since)
if (
![count, inputTokens, outputTokens, since].every(Number.isFinite) ||
count < 0 ||
inputTokens < 0 ||
outputTokens < 0 ||
since < 0
) {
return undefined
}
return {
count: Math.floor(count),
inputTokens: Math.floor(inputTokens),
outputTokens: Math.floor(outputTokens),
since: Math.floor(since),
}
}
function normalizePrimeAccount(
value: unknown,
): PrimeSidebarAccountState | undefined {
if (!isRecord(value)) return undefined
if (typeof value.id !== 'string' || !value.id.trim()) return undefined
if (typeof value.label !== 'string' || !value.label.trim()) return undefined
const account: PrimeSidebarAccountState = {
id: value.id.trim(),
label: value.label.trim(),
}
if (value.nextDueAt === null) {
account.nextDueAt = null
} else if (isFiniteNumber(value.nextDueAt)) {
account.nextDueAt = value.nextDueAt
}
if (value.lastPrimedAt === null) {
account.lastPrimedAt = null
} else if (isFiniteNumber(value.lastPrimedAt)) {
account.lastPrimedAt = value.lastPrimedAt
}
if (
value.lastResult === 'ok' ||
value.lastResult === 'error' ||
value.lastResult === 'skipped'
) {
account.lastResult = value.lastResult
}
const usage = normalizePrimeUsage(value.usage)
if (usage) account.usage = usage
if (isFiniteNumber(value.estimatedCostUsd)) {
account.estimatedCostUsd = value.estimatedCostUsd
}
return account
}
function normalizePrimeSection(
value: unknown,
): SidebarState['prime'] | undefined {
if (!isRecord(value)) return undefined
if (typeof value.enabled !== 'boolean') return undefined
const accounts = Array.isArray(value.accounts)
? value.accounts
.map(normalizePrimeAccount)
.filter((a): a is PrimeSidebarAccountState => a != null)
: []
return { enabled: value.enabled, accounts }
}
function normalizeQuotaWindow(value: unknown): QuotaWindow | undefined {
if (!isRecord(value)) return undefined
const usedPercent = Number(value.usedPercent)
const remainingPercent = Number(value.remainingPercent)
if (!Number.isFinite(usedPercent) || !Number.isFinite(remainingPercent)) {
return undefined
}
return {
usedPercent,
remainingPercent,
resetsAt: typeof value.resetsAt === 'string' ? value.resetsAt : undefined,
...(isFiniteNumber(value.checkedAt) && { checkedAt: value.checkedAt }),
}
}
function normalizeAccountQuota(value: unknown): AccountQuota | null {
if (!isRecord(value)) return null
const quota: AccountQuota = {}
if (isFiniteNumber(value.checkedAt)) quota.checkedAt = value.checkedAt
const fiveHour = normalizeQuotaWindow(value.five_hour)
const sevenDay = normalizeQuotaWindow(value.seven_day)
if (fiveHour) quota.five_hour = fiveHour
if (sevenDay) quota.seven_day = sevenDay
if (Array.isArray(value.scoped)) {
const scoped = value.scoped
.map((entry): ScopedQuotaWindow | undefined => {
if (!isRecord(entry)) return undefined
const window = normalizeQuotaWindow(entry)
if (!window) return undefined
if (typeof entry.id !== 'string' || !entry.id.trim()) return undefined
if (typeof entry.title !== 'string' || !entry.title.trim()) {
return undefined
}
if (typeof entry.modelName !== 'string' || !entry.modelName.trim()) {
return undefined
}
const modelId =
typeof entry.modelId === 'string' && entry.modelId.trim()
? entry.modelId.trim()
: undefined
return {
...window,
id: entry.id.trim(),
title: entry.title.trim(),
...(modelId && { modelId }),
modelName: entry.modelName.trim(),
}
})
.filter((entry): entry is ScopedQuotaWindow => entry != null)
// Preserve empty `[]` so a sidebar reader can distinguish "scoped owned
// by anthropic-auth, none visible" from "no quota data at all". The OUTER
// Array.isArray guard means pre-feature inputs without a `scoped` key are
// not affected — only inputs that already carried an array reach this line.
quota.scoped = scoped
}
if (isRecord(value.extraUsage)) {
const used = normalizeQuotaMoney(value.extraUsage.used)
const limit = normalizeQuotaMoney(value.extraUsage.limit)
if (used && limit && typeof value.extraUsage.exhausted === 'boolean') {
quota.extraUsage = {
used,
limit,
...(typeof value.extraUsage.utilizationPercent === 'number' &&
Number.isFinite(value.extraUsage.utilizationPercent) && {
utilizationPercent: value.extraUsage.utilizationPercent,
}),
...(typeof value.extraUsage.severity === 'string' && {
severity: value.extraUsage.severity,
}),
exhausted: value.extraUsage.exhausted,
}
}
}
if (typeof value.bindingWindow === 'string' && value.bindingWindow.trim()) {
quota.bindingWindow = value.bindingWindow.trim()
}
if (typeof value.fallbackAdvised === 'boolean') {
quota.fallbackAdvised = value.fallbackAdvised
}
return Object.keys(quota).length ? quota : null
}
function normalizeQuotaMoney(value: unknown) {
if (!isRecord(value)) return undefined
if (
!Number.isInteger(value.amountMinor) ||
typeof value.currency !== 'string' ||
!/^[A-Za-z]{3}$/.test(value.currency.trim()) ||
!Number.isInteger(value.exponent) ||
(value.exponent as number) < 0 ||
(value.exponent as number) > 20
) {
return undefined
}
return {
amountMinor: value.amountMinor as number,
currency: value.currency.trim(),
exponent: value.exponent as number,
}
}
export function normalizeSidebarState(raw: unknown): SidebarState {
if (!isRecord(raw)) return { ...DEFAULT_SIDEBAR_STATE }
const main: SidebarState['main'] = { quota: null }
if (isRecord(raw.main)) {
const m = raw.main
main.quota = normalizeAccountQuota(m.quota)
if (typeof m.enabled === 'boolean') main.enabled = m.enabled
if (typeof m.stateLine === 'string') main.stateLine = m.stateLine
if (m.quotaDated === true) main.quotaDated = true
if (typeof m.tierLabel === 'string' && m.tierLabel.trim()) {
main.tierLabel = m.tierLabel.trim()
}
if (typeof m.quotaBackedOff === 'boolean')
main.quotaBackedOff = m.quotaBackedOff
if (typeof m.quotaBackoffUntil === 'number')
main.quotaBackoffUntil = m.quotaBackoffUntil
if (typeof m.refreshBackedOff === 'boolean')
main.refreshBackedOff = m.refreshBackedOff
if (typeof m.refreshBackoffUntil === 'number')
main.refreshBackoffUntil = m.refreshBackoffUntil
}
const fallbacks: SidebarAccountState[] = Array.isArray(raw.fallbacks)
? raw.fallbacks
.filter(isRecord)
.filter((entry) => typeof entry.id === 'string')
.map((entry) => ({
id: entry.id as string,
label: typeof entry.label === 'string' ? entry.label : undefined,
quota: normalizeAccountQuota(entry.quota),
enabled: typeof entry.enabled === 'boolean' ? entry.enabled : false,
...(typeof entry.stateLine === 'string' && {
stateLine: entry.stateLine,
}),
...(entry.quotaDated === true && { quotaDated: true }),
needsReauth:
typeof entry.needsReauth === 'boolean' ? entry.needsReauth : false,
...(entry.vaultReauth === true && { vaultReauth: true }),
...(entry.vaultServed === true && { vaultServed: true }),
...(typeof entry.custodyState === 'string' && {
custodyState:
entry.custodyState as SidebarAccountState['custodyState'],
}),
tierLabel:
typeof entry.tierLabel === 'string' && entry.tierLabel.trim()
? entry.tierLabel.trim()
: undefined,
}))
: []
let relay: SidebarState['relay'] = null
if (isRecord(raw.relay)) {
const r = raw.relay
if (typeof r.enabled === 'boolean' && typeof r.transport === 'string') {
relay = { enabled: r.enabled, transport: r.transport }
}
}
let cacheKeep: SidebarState['cacheKeep']
if (isRecord(raw.cacheKeep)) {
const ck = raw.cacheKeep
if (typeof ck.enabled === 'boolean') {
cacheKeep = {
enabled: ck.enabled,
window: typeof ck.window === 'string' ? ck.window : undefined,
trackedSessions:
typeof ck.trackedSessions === 'number'
? ck.trackedSessions
: undefined,
}
}
}
const fableRecoveries: FableRecoverySidebarState[] = Array.isArray(
raw.fableRecoveries,
)
? raw.fableRecoveries
.filter(isRecord)
.flatMap((recovery): FableRecoverySidebarState[] => {
if (
typeof recovery.sessionId !== 'string' ||
(recovery.mode !== 'opus' &&
recovery.mode !== 'fable' &&
recovery.mode !== 'server') ||
typeof recovery.remaining !== 'number' ||
!Number.isFinite(recovery.remaining) ||
typeof recovery.changedAt !== 'number' ||
!Number.isFinite(recovery.changedAt)
)
return []
return [
{
sessionId: recovery.sessionId,
mode: recovery.mode,
remaining: Math.max(0, Math.floor(recovery.remaining)),
changedAt: recovery.changedAt,
requestedModelId:
typeof recovery.requestedModelId === 'string'
? recovery.requestedModelId
: undefined,
targetModelId:
typeof recovery.targetModelId === 'string'
? recovery.targetModelId
: undefined,
},
]
})
: []
return {
main,
fallbacks,
activeId: typeof raw.activeId === 'string' ? raw.activeId : undefined,
route:
typeof raw.route === 'string' ? raw.route : DEFAULT_SIDEBAR_STATE.route,
relay,
fastMode:
typeof raw.fastMode === 'boolean'
? raw.fastMode
: DEFAULT_SIDEBAR_STATE.fastMode,
cacheKeep,
prime: normalizePrimeSection(raw.prime),
fableRecoveries: fableRecoveries.length > 0 ? fableRecoveries : undefined,
lastUpdated: typeof raw.lastUpdated === 'number' ? raw.lastUpdated : 0,
}
}
let writeChain: Promise<void> = Promise.resolve()
// Wait through ordinary contention while staying below the 2s stale-eviction window.
const SIDEBAR_LOCK_BUDGET_MS = 1_000
const SIDEBAR_LOCK_STALE_MS = 2_000
const SIDEBAR_LOCK_RETRY_MIN_MS = 5
const SIDEBAR_LOCK_RETRY_MAX_MS = 15
interface SidebarStateWriteTestHooks {
afterMergeRead?: (stateFile: string) => void | Promise<void>
beforeRename?: (stateFile: string, tempFile: string) => void | Promise<void>
afterRename?: (stateFile: string) => void | Promise<void>
afterStaleLockStat?: (lockDir: string) => void | Promise<void>
onStaleLockClaimed?: (lockDir: string) => void | Promise<void>
onLockAcquired?: (lockDir: string) => void | Promise<void>
beforeReleaseDirectoryRemoval?: (lockDir: string) => void | Promise<void>
lockBudgetMs?: number
lockRetryMinMs?: number
lockRetryMaxMs?: number
}
const sidebarStateWriteTestHooks = new Map<string, SidebarStateWriteTestHooks>()
export function __setSidebarStateWriteTestHooks(
hooks: SidebarStateWriteTestHooks | null,
stateFile = getSidebarStateFile(),
): void {
if (hooks) sidebarStateWriteTestHooks.set(stateFile, hooks)
else sidebarStateWriteTestHooks.delete(stateFile)
}
function sidebarStateWriteHooksFor(
stateFile: string,
): SidebarStateWriteTestHooks | undefined {
return sidebarStateWriteTestHooks.get(stateFile)
}
// Boot-routing test hooks live here rather than in index.ts: the plugin entry
// module must export nothing beyond the plugin factory — opencode's plugin
// loader treats extra entry-point exports as plugin candidates and fails to
// load the plugin (same incident class as the removed
// __setBootProfileHydrationForTest export).
export interface InitialSidebarRoutingTestHooks {
beforeSidebarRead?: () => void | Promise<void>
beforeStorageLoad?: () => void | Promise<void>
afterStorageLoad?: () => void | Promise<void>
}
let initialSidebarRoutingTestHooks: InitialSidebarRoutingTestHooks | null = null
export function __setInitialSidebarRoutingTestHooks(
hooks: InitialSidebarRoutingTestHooks | null,
): void {
initialSidebarRoutingTestHooks = hooks
}
export function getInitialSidebarRoutingTestHooks(): InitialSidebarRoutingTestHooks | null {
return initialSidebarRoutingTestHooks
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function acquireSidebarStateLock(stateFile: string): Promise<{
release: () => Promise<void>
ownsLock: () => Promise<boolean>
} | null> {
const lockDir = `${stateFile}.lock`
const testHooks = sidebarStateWriteHooksFor(stateFile)
const budgetMs = testHooks?.lockBudgetMs ?? SIDEBAR_LOCK_BUDGET_MS
const retryMinMs = testHooks?.lockRetryMinMs ?? SIDEBAR_LOCK_RETRY_MIN_MS
const retryMaxMs = testHooks?.lockRetryMaxMs ?? SIDEBAR_LOCK_RETRY_MAX_MS
const deadline = Date.now() + budgetMs
while (true) {
try {
await mkdir(lockDir)
const ownerId = randomUUID()
const ownerFile = join(lockDir, ownerId)
await writeFile(ownerFile, '', {
encoding: 'utf8',
mode: 0o600,
flag: 'wx',
})
await testHooks?.onLockAcquired?.(lockDir)
return {
ownsLock: async () => {
try {
await stat(ownerFile)
return true
} catch {
return false
}
},
release: async () => {
// Unlinking this acquisition's unique file makes the filesystem reject
// a stale release after eviction handed the path to a successor.
try {
await unlink(ownerFile)
} catch {
return
}
await testHooks?.beforeReleaseDirectoryRemoval?.(lockDir)
await rmdir(lockDir).catch(() => {})
},
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
logger.trace('sidebar', 'state lock unavailable; write skipped', {
stateFile,
error: error instanceof Error ? error.message : String(error),
})
return null
}
}
try {
const lockStat = await stat(lockDir)
if (Date.now() - lockStat.mtimeMs > SIDEBAR_LOCK_STALE_MS) {
await testHooks?.afterStaleLockStat?.(lockDir)
const evictedLockDir = `${lockDir}.evict-${process.pid}-${randomUUID()}`
try {
await rename(lockDir, evictedLockDir)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
throw error
}
await testHooks?.onStaleLockClaimed?.(lockDir)
await rm(evictedLockDir, { recursive: true, force: true }).catch(
() => {},
)
continue
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
logger.trace('sidebar', 'state lock inspection failed; write skipped', {
stateFile,
error: error instanceof Error ? error.message : String(error),
})
return null
}
const remainingMs = deadline - Date.now()
if (remainingMs <= 0) {
logger.warn('sidebar', 'lock budget exhausted, write skipped', {
stateFile,
budgetMs,
})
return null
}
const jitterMs =
retryMinMs + Math.floor(Math.random() * (retryMaxMs - retryMinMs + 1))
await sleep(Math.min(jitterMs, remainingMs))
}
}
export async function __acquireSidebarStateLockForTest(
stateFile: string,
): Promise<(() => Promise<void>) | null> {
return (await acquireSidebarStateLock(stateFile))?.release ?? null
}
async function writeSidebarStateAtomic(
stateFile: string,
state: SidebarState,
ownsLock: () => Promise<boolean>,
): Promise<'written' | 'lock-lost-before-rename' | 'lock-lost-after-rename'> {
const testHooks = sidebarStateWriteHooksFor(stateFile)
const tempFile = `${stateFile}.${process.pid}.${randomUUID()}.tmp`
await writeFile(tempFile, JSON.stringify(state), {
encoding: 'utf8',
mode: 0o600,
})
try {
if (!(await ownsLock())) {
logger.trace('sidebar', 'state lock lost before rename; write aborted', {
stateFile,
})
await rm(tempFile, { force: true }).catch(() => {})
return 'lock-lost-before-rename'
}
await testHooks?.beforeRename?.(stateFile, tempFile)
// No production await separates this ownership fence from rename. A process
// freeze between the adjacent syscalls remains possible, so rename is also
// fenced from the other side below.
if (!(await ownsLock())) {
logger.trace('sidebar', 'state lock lost before rename; write aborted', {
stateFile,
})
await rm(tempFile, { force: true }).catch(() => {})
return 'lock-lost-before-rename'
}
await rename(tempFile, stateFile)
// Look the hooks up again: a test may start listening while this write is
// in flight, after reading the old file, and must still hear this rename.
await sidebarStateWriteHooksFor(stateFile)?.afterRename?.(stateFile)
if (!(await ownsLock())) return 'lock-lost-after-rename'
return 'written'
} catch (error) {
await rm(tempFile, { force: true }).catch(() => {})
throw error
}
}
export async function getSidebarState(
stateFile = getSidebarStateFile(),
): Promise<SidebarState> {
try {
const raw = await readFile(stateFile, 'utf8')
return normalizeSidebarState(JSON.parse(raw))
} catch {
return DEFAULT_SIDEBAR_STATE
}
}
export interface SidebarStateWriteOptions {
routingAuthoritative?: boolean
resolvePreservedRouting?: (current: SidebarState) =>
| (Pick<SidebarState, 'activeId' | 'route'> & {
state?: SidebarState
})
| undefined
| Promise<
| (Pick<SidebarState, 'activeId' | 'route'> & {
state?: SidebarState
})
| undefined
>
onRoutingResolved?: (
routing: Pick<SidebarState, 'activeId' | 'route'>,
) => void
}
export async function setSidebarState(
state: SidebarState,
stateFile = getSidebarStateFile(),
options: SidebarStateWriteOptions = {},
): Promise<void> {
writeChain = writeChain
.then(async () => {
await mkdir(dirname(stateFile), { recursive: true })
for (let attempt = 0; attempt < 2; attempt++) {
const repairingPostRenameLoss = attempt === 1
const lock = await acquireSidebarStateLock(stateFile)
// Sidebar frames are display-only and refresh within seconds; dropping one
// is safer than clobbering routing state that may stay authoritative until
// another process handles its next request.
if (!lock) {
if (repairingPostRenameLoss) {
logger.warn(
'sidebar',
'post-rename repair lock unavailable; write skipped',
{ stateFile },
)
}
return
}
let stateToWrite = state
let result:
| 'written'
| 'lock-lost-before-rename'
| 'lock-lost-after-rename'
try {
if (options.routingAuthoritative === false) {
const current = await getSidebarState(stateFile)
const preservedRouting =
await options.resolvePreservedRouting?.(current)
if (preservedRouting) {
const preservedState = preservedRouting.state ?? state
stateToWrite = {
...preservedState,
activeId: preservedRouting.activeId,
route: preservedRouting.route,
lastUpdated: Math.max(
preservedState.lastUpdated,
current.lastUpdated,
),
}
}
await sidebarStateWriteHooksFor(stateFile)?.afterMergeRead?.(
stateFile,
)
} else if (repairingPostRenameLoss) {
const current = await getSidebarState(stateFile)
// A successor owns its fresh account/quota and recovery snapshots;
// this routing frame may only republish its decision and shared UI state.
stateToWrite = {
...current,
activeId: state.activeId,
route: state.route,
relay: state.relay,
fastMode: state.fastMode,
cacheKeep: state.cacheKeep,
lastUpdated: Math.max(current.lastUpdated, state.lastUpdated),
}
}
// The state file is a cross-process artifact; future account fields must fail closed.
stateToWrite = normalizeSidebarState(stateToWrite)
result = await writeSidebarStateAtomic(
stateFile,
stateToWrite,
lock.ownsLock,
)
} finally {
await lock.release()
}
if (result === 'lock-lost-after-rename') {
if (repairingPostRenameLoss) {
logger.warn(
'sidebar',
'post-rename repair lost lock; write skipped',
{ stateFile },
)
return
}
logger.warn(
'sidebar',
'state lock lost after rename; repairing write',
{
stateFile,
},
)
continue
}
if (result === 'lock-lost-before-rename') return
options.onRoutingResolved?.({
activeId: stateToWrite.activeId,
route: stateToWrite.route,
})
return
}
})
.catch(() => {
// Best-effort — sidebar is non-critical
})
return writeChain
}
export async function drainSidebarWrites(): Promise<void> {
return writeChain
}
// Resolve the currently-active account from activeId for the collapsed sidebar
// view. activeId === 'main' (or undefined/unmatched/disabled) → the main
// account; otherwise the enabled fallback whose id matches.
export function resolveActiveAccount(state: SidebarState): {
id: string
name: string
quota: AccountQuota | null
stateLine?: string
quotaDated?: boolean
} {
const activeId = state.activeId
if (activeId && activeId !== 'main') {
// A disabled fallback cannot remain the active route, even though vault
// accounts stay visible in the expanded inventory while turned off.
const fallback = state.fallbacks?.find(
(account) => account.enabled && account.id === activeId,
)
if (fallback) {
return {
id: fallback.id,
name: fallback.label ?? fallback.id,
quota: fallback.quota,
...(fallback.stateLine && {
stateLine: fallback.stateLine,
quotaDated: fallback.quotaDated,
}),
}
}
}
return {
id: 'main',
name: 'main',
quota: state.main?.quota ?? null,
...(state.main?.stateLine && {
stateLine: state.main.stateLine,
quotaDated: state.main.quotaDated,
}),
}
}
/**
* Pretty label for a recoverable-refusal source model (Fable 5/5.1 or Opus 5).
* Falls back to the raw id for unrecognized ids so the sidebar never goes
* blank on a future model that has not yet been cataloged here.
*/
export function formatFallbackModelLabel(modelId: string | undefined): string {
if (
modelId === 'claude-mythos-5-1' ||
modelId?.startsWith('claude-mythos-5-1-')
)
return 'Mythos 5.1'
if (
modelId === 'claude-fable-5-1' ||
modelId?.startsWith('claude-fable-5-1-')
)
return 'Fable 5.1'
if (modelId === 'claude-fable-5' || modelId?.startsWith('claude-fable-5-'))
return 'Fable 5'
if (modelId === 'claude-opus-5-5' || modelId?.startsWith('claude-opus-5-5-'))
return 'Opus 5.5'
if (modelId === 'claude-opus-5' || modelId?.startsWith('claude-opus-5-'))
return 'Opus 5'
if (modelId === 'claude-opus-4-8' || modelId?.startsWith('claude-opus-4-8-'))
return 'Opus 4.8'
return modelId ?? 'Fable 5'
}
export function formatPrimeTime(epochMs: number): string {
return new Date(epochMs).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})
}
export function formatPrimeCost(value: number): string {
if (value === 0) return '0'
if (value < 0.0001) return value.toExponential(2)
return value.toFixed(Math.min(6, Math.max(0, 4)))
}
export function formatPrimeAccountValue(account: PrimeSidebarAccountState): {
text: string
hasError: boolean
} {
if (account.lastResult === 'error') {
return { text: 'err', hasError: true }
}
if (account.lastResult === 'skipped') {
return { text: 'skip', hasError: false }
}
if (account.nextDueAt && account.nextDueAt > Date.now()) {
return { text: formatPrimeTime(account.nextDueAt), hasError: false }
}
if (account.lastPrimedAt) {
return {
text: `primed ${formatPrimeTime(account.lastPrimedAt)} \u2713`,
hasError: false,
}
}
if (account.usage?.count) {
return {
text: `\u2713 ${account.usage.count} \u2248 $${formatPrimeCost(account.estimatedCostUsd ?? 0)}`,
hasError: false,
}
}
return { text: '\u2014', hasError: false }
}
export function getFableRecoverySummary(
state: SidebarState,
sessionId: string,
): string | undefined {
const recovery = state.fableRecoveries?.find(
(candidate) => candidate.sessionId === sessionId,
)
if (!recovery) return undefined
if (recovery.mode === 'fable') {
return `${formatFallbackModelLabel(recovery.requestedModelId)} · restored`
}
if (recovery.mode === 'server') {
return `${formatFallbackModelLabel(recovery.requestedModelId)}→${formatFallbackModelLabel(recovery.targetModelId)} · safety`
}
return `Opus 4.8 · ${recovery.remaining} left`
}
/** Keep full shared names when they fit; truncate only to preserve row columns. */
export function formatQuotaRowLabel(name: string, width = 10): string {
if (width <= 0) return ''
let label = name
if (Bun.stringWidth(label) > width) {
label = ''
for (const character of name) {
if (Bun.stringWidth(label + character) > width - 1) break
label += character
}
label += '…'
}
return label + ' '.repeat(Math.max(0, width - Bun.stringWidth(label)))
}
export function getCollapsedQuotaSummary(
quota: AccountQuota | null,
now = Date.now(),
): {
fiveHourUsedPercent: number | null
sevenDayUsedPercent: number | null
scopedUsedPercents: number[]
text: string | null
stale: boolean
} {
const fiveHourUsedPercent = quota?.five_hour?.usedPercent ?? null
const sevenDayUsedPercent = quota?.seven_day?.usedPercent ?? null
const scoped = quota?.scoped ?? []
const scopedUsedPercents = scoped.map((window) => window.usedPercent)
if (
!quota ||
(fiveHourUsedPercent == null &&
sevenDayUsedPercent == null &&
scoped.length === 0 &&
!quota.extraUsage)
) {
return {
fiveHourUsedPercent,
sevenDayUsedPercent,
scopedUsedPercents,
text: null,
stale: false,
}
}
const projection = quotaDisplayProjection(quota, now)
return {
fiveHourUsedPercent,
sevenDayUsedPercent,
scopedUsedPercents,
// The narrow form leaves out the reading's age to stay on one line, so
// a stale reading is dimmed instead of labelled.
text: formatQuota(projection, { now, form: 'narrow' }),
stale: isQuotaStale(projection, { now }),
}
}
export function getCollapsedAccounts(
state: SidebarState,
showFallbacks = true,
) {
const activeId = resolveActiveAccount(state).id
return [
{
id: 'main',