-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsettings-hub.ts
More file actions
3049 lines (2906 loc) · 87 KB
/
settings-hub.ts
File metadata and controls
3049 lines (2906 loc) · 87 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
import { promises as fs } from "node:fs";
import { stdin as input, stdout as output } from "node:process";
import { createInterface } from "node:readline/promises";
import {
getDefaultPluginConfig,
loadPluginConfig,
savePluginConfig,
} from "../config.js";
import {
type DashboardAccentColor,
type DashboardAccountSortMode,
type DashboardDisplaySettings,
type DashboardStatuslineField,
type DashboardThemePreset,
DEFAULT_DASHBOARD_DISPLAY_SETTINGS,
getDashboardSettingsPath,
loadDashboardDisplaySettings,
saveDashboardDisplaySettings,
} from "../dashboard-settings.js";
import {
applyOcChatgptSync,
planOcChatgptSync,
runNamedBackupExport,
} from "../oc-chatgpt-orchestrator.js";
import { detectOcChatgptMultiAuthTarget } from "../oc-chatgpt-target-detection.js";
import { loadAccounts, normalizeAccountStorage } from "../storage.js";
import type { PluginConfig } from "../types.js";
import { ANSI } from "../ui/ansi.js";
import { UI_COPY } from "../ui/copy.js";
import { getUiRuntimeOptions, setUiRuntimeOptions } from "../ui/runtime.js";
import { type MenuItem, select, type SelectOptions } from "../ui/select.js";
import { getUnifiedSettingsPath } from "../unified-settings.js";
import { sleep } from "../utils.js";
type DashboardDisplaySettingKey =
| "menuShowStatusBadge"
| "menuShowCurrentBadge"
| "menuShowLastUsed"
| "menuShowQuotaSummary"
| "menuShowQuotaCooldown"
| "menuShowDetailsForUnselectedRows"
| "menuShowFetchStatus"
| "menuHighlightCurrentRow"
| "menuSortEnabled"
| "menuSortPinCurrent"
| "menuSortQuickSwitchVisibleRow";
interface DashboardDisplaySettingOption {
key: DashboardDisplaySettingKey;
label: string;
description: string;
}
const DASHBOARD_DISPLAY_OPTIONS: DashboardDisplaySettingOption[] = [
{
key: "menuShowStatusBadge",
label: "Show Status Badges",
description: "Show [ok], [active], and similar badges.",
},
{
key: "menuShowCurrentBadge",
label: "Show [current]",
description: "Mark the account active in Codex.",
},
{
key: "menuShowLastUsed",
label: "Show Last Used",
description: "Show relative usage like 'today'.",
},
{
key: "menuShowQuotaSummary",
label: "Show Limits (5h / 7d)",
description: "Show limit bars in each row.",
},
{
key: "menuShowQuotaCooldown",
label: "Show Limit Cooldowns",
description: "Show reset timers next to 5h/7d bars.",
},
{
key: "menuShowFetchStatus",
label: "Show Fetch Status",
description: "Show background limit refresh status in the menu subtitle.",
},
{
key: "menuHighlightCurrentRow",
label: "Highlight Current Row",
description: "Use stronger color on the current row.",
},
{
key: "menuSortEnabled",
label: "Enable Smart Sort",
description: "Sort accounts by readiness (view only).",
},
{
key: "menuSortPinCurrent",
label: "Pin [current] when tied",
description: "Keep current at top only when it is equally ready.",
},
{
key: "menuSortQuickSwitchVisibleRow",
label: "Quick Switch Uses Visible Rows",
description: "Number keys (1-9) follow what you see in the list.",
},
];
const DEFAULT_STATUSLINE_FIELDS: DashboardStatuslineField[] = [
"last-used",
"limits",
"status",
];
const STATUSLINE_FIELD_OPTIONS: Array<{
key: DashboardStatuslineField;
label: string;
description: string;
}> = [
{
key: "last-used",
label: "Show Last Used",
description: "Example: 'today' or '2d ago'.",
},
{
key: "limits",
label: "Show Limits (5h / 7d)",
description: "Uses cached limit data from checks.",
},
{
key: "status",
label: "Show Status Text",
description: "Visible when badges are hidden.",
},
];
const AUTO_RETURN_OPTIONS_MS = [1_000, 2_000, 4_000] as const;
const MENU_QUOTA_TTL_OPTIONS_MS = [60_000, 5 * 60_000, 10 * 60_000] as const;
const THEME_PRESET_OPTIONS: DashboardThemePreset[] = ["green", "blue"];
const ACCENT_COLOR_OPTIONS: DashboardAccentColor[] = [
"green",
"cyan",
"blue",
"yellow",
];
const PREVIEW_ACCOUNT_EMAIL = "demo@example.com";
const PREVIEW_LAST_USED = "today";
const PREVIEW_STATUS = "active";
const PREVIEW_LIMITS = "5h ██████▒▒▒▒ 62% | 7d █████▒▒▒▒▒ 49%";
const PREVIEW_LIMIT_COOLDOWNS = "5h reset 1h 20m | 7d reset 2d 04h";
type PreviewFocusKey =
| DashboardDisplaySettingKey
| DashboardStatuslineField
| "menuSortMode"
| "menuLayoutMode"
| null;
type DashboardConfigAction =
| { type: "toggle"; key: DashboardDisplaySettingKey }
| { type: "cycle-sort-mode" }
| { type: "cycle-layout-mode" }
| { type: "reset" }
| { type: "save" }
| { type: "cancel" };
type StatuslineConfigAction =
| { type: "toggle"; key: DashboardStatuslineField }
| { type: "move-up"; key: DashboardStatuslineField }
| { type: "move-down"; key: DashboardStatuslineField }
| { type: "reset" }
| { type: "save" }
| { type: "cancel" };
type BehaviorConfigAction =
| { type: "set-delay"; delayMs: number }
| { type: "toggle-pause" }
| { type: "toggle-menu-limit-fetch" }
| { type: "toggle-menu-fetch-status" }
| { type: "set-menu-quota-ttl"; ttlMs: number }
| { type: "reset" }
| { type: "save" }
| { type: "cancel" };
type ThemeConfigAction =
| { type: "set-palette"; palette: DashboardThemePreset }
| { type: "set-accent"; accent: DashboardAccentColor }
| { type: "reset" }
| { type: "save" }
| { type: "cancel" };
type BackendToggleSettingKey =
| "liveAccountSync"
| "codexCliSessionSupervisor"
| "sessionAffinity"
| "proactiveRefreshGuardian"
| "retryAllAccountsRateLimited"
| "parallelProbing"
| "storageBackupEnabled"
| "preemptiveQuotaEnabled"
| "fastSession"
| "sessionRecovery"
| "autoResume"
| "perProjectAccounts";
type BackendNumberSettingKey =
| "liveAccountSyncDebounceMs"
| "liveAccountSyncPollMs"
| "sessionAffinityTtlMs"
| "sessionAffinityMaxEntries"
| "proactiveRefreshIntervalMs"
| "proactiveRefreshBufferMs"
| "parallelProbingMaxConcurrency"
| "fastSessionMaxInputItems"
| "networkErrorCooldownMs"
| "serverErrorCooldownMs"
| "fetchTimeoutMs"
| "streamStallTimeoutMs"
| "tokenRefreshSkewMs"
| "preemptiveQuotaRemainingPercent5h"
| "preemptiveQuotaRemainingPercent7d"
| "preemptiveQuotaMaxDeferralMs";
type BackendSettingFocusKey =
| BackendToggleSettingKey
| BackendNumberSettingKey
| null;
interface BackendToggleSettingOption {
key: BackendToggleSettingKey;
label: string;
description: string;
}
interface BackendNumberSettingOption {
key: BackendNumberSettingKey;
label: string;
description: string;
min: number;
max: number;
step: number;
unit: "ms" | "percent" | "count";
}
type BackendCategoryKey =
| "session-sync"
| "rotation-quota"
| "refresh-recovery"
| "performance-timeouts";
interface BackendCategoryOption {
key: BackendCategoryKey;
label: string;
description: string;
toggleKeys: BackendToggleSettingKey[];
numberKeys: BackendNumberSettingKey[];
}
type BackendCategoryConfigAction =
| { type: "toggle"; key: BackendToggleSettingKey }
| { type: "bump"; key: BackendNumberSettingKey; direction: -1 | 1 }
| { type: "reset-category" }
| { type: "back" };
type BackendSettingsHubAction =
| { type: "open-category"; key: BackendCategoryKey }
| { type: "reset" }
| { type: "save" }
| { type: "cancel" };
type SettingsHubAction =
| { type: "account-list" }
| { type: "summary-fields" }
| { type: "behavior" }
| { type: "theme" }
| { type: "experimental" }
| { type: "backend" }
| { type: "back" };
type ExperimentalSettingsAction =
| { type: "toggle-session-supervisor" }
| { type: "sync" }
| { type: "backup" }
| { type: "toggle-refresh-guardian" }
| { type: "decrease-refresh-interval" }
| { type: "increase-refresh-interval" }
| { type: "apply" }
| { type: "save" }
| { type: "back" };
function getExperimentalSelectOptions(
ui: ReturnType<typeof getUiRuntimeOptions>,
help: string,
onInput?: SelectOptions<ExperimentalSettingsAction>["onInput"],
): SelectOptions<ExperimentalSettingsAction> {
return {
message: UI_COPY.settings.experimentalTitle,
subtitle: UI_COPY.settings.experimentalSubtitle,
help,
clearScreen: true,
theme: ui.theme,
selectedEmphasis: "minimal",
onInput,
};
}
function mapExperimentalMenuHotkey(
raw: string,
): ExperimentalSettingsAction | undefined {
if (raw === "1") return { type: "toggle-session-supervisor" };
if (raw === "2") return { type: "sync" };
if (raw === "3") return { type: "backup" };
if (raw === "4") return { type: "toggle-refresh-guardian" };
if (raw === "[" || raw === "-") return { type: "decrease-refresh-interval" };
if (raw === "]" || raw === "+") return { type: "increase-refresh-interval" };
const lower = raw.toLowerCase();
if (lower === "q") return { type: "back" };
if (lower === "s") return { type: "save" };
return undefined;
}
function mapExperimentalStatusHotkey(
raw: string,
): ExperimentalSettingsAction | undefined {
return raw.toLowerCase() === "q" ? { type: "back" } : undefined;
}
const BACKEND_TOGGLE_OPTIONS: BackendToggleSettingOption[] = [
{
key: "liveAccountSync",
label: "Enable Live Sync",
description: "Keep accounts synced when files change in another window.",
},
{
key: "codexCliSessionSupervisor",
label: "Enable Session Resume Supervisor",
description: "Wrap interactive Codex sessions so they can relaunch with resume after rotation.",
},
{
key: "sessionAffinity",
label: "Enable Session Affinity",
description: "Try to keep each conversation on the same account.",
},
{
key: "proactiveRefreshGuardian",
label: "Enable Token Refresh Guard",
description: "Refresh tokens early in the background.",
},
{
key: "retryAllAccountsRateLimited",
label: "Retry When All Rate-Limited",
description: "If all accounts are limited, wait and try again.",
},
{
key: "parallelProbing",
label: "Enable Parallel Probing",
description: "Check multiple accounts at the same time.",
},
{
key: "storageBackupEnabled",
label: "Enable Storage Backups",
description: "Create a backup before account data changes.",
},
{
key: "preemptiveQuotaEnabled",
label: "Enable Quota Deferral",
description: "Delay requests before limits are fully exhausted.",
},
{
key: "fastSession",
label: "Enable Fast Session Mode",
description: "Use lighter request handling for faster responses.",
},
{
key: "sessionRecovery",
label: "Enable Session Recovery",
description: "Restore recoverable sessions after restart.",
},
{
key: "autoResume",
label: "Enable Auto Resume",
description: "Automatically continue sessions when possible.",
},
{
key: "perProjectAccounts",
label: "Enable Per-Project Accounts",
description: "Keep separate account lists for each project.",
},
];
const BACKEND_NUMBER_OPTIONS: BackendNumberSettingOption[] = [
{
key: "liveAccountSyncDebounceMs",
label: "Live Sync Debounce",
description: "Wait this long before applying sync file changes.",
min: 50,
max: 10_000,
step: 50,
unit: "ms",
},
{
key: "liveAccountSyncPollMs",
label: "Live Sync Poll",
description: "How often to check files for account updates.",
min: 500,
max: 60_000,
step: 500,
unit: "ms",
},
{
key: "sessionAffinityTtlMs",
label: "Session Affinity TTL",
description: "How long conversation-to-account mapping is kept.",
min: 1_000,
max: 24 * 60 * 60_000,
step: 60_000,
unit: "ms",
},
{
key: "sessionAffinityMaxEntries",
label: "Session Affinity Max Entries",
description: "Maximum stored conversation mappings.",
min: 8,
max: 4_096,
step: 32,
unit: "count",
},
{
key: "proactiveRefreshIntervalMs",
label: "Refresh Guard Interval",
description: "How often to scan for tokens near expiry.",
min: 5_000,
max: 10 * 60_000,
step: 5_000,
unit: "ms",
},
{
key: "proactiveRefreshBufferMs",
label: "Refresh Guard Buffer",
description: "How early to refresh before expiry.",
min: 30_000,
max: 10 * 60_000,
step: 30_000,
unit: "ms",
},
{
key: "parallelProbingMaxConcurrency",
label: "Parallel Probe Concurrency",
description: "Maximum checks running at once.",
min: 1,
max: 5,
step: 1,
unit: "count",
},
{
key: "fastSessionMaxInputItems",
label: "Fast Session Max Inputs",
description: "Max number of input items kept in fast mode.",
min: 8,
max: 200,
step: 2,
unit: "count",
},
{
key: "networkErrorCooldownMs",
label: "Network Error Cooldown",
description: "Wait time after network errors before retry.",
min: 0,
max: 120_000,
step: 500,
unit: "ms",
},
{
key: "serverErrorCooldownMs",
label: "Server Error Cooldown",
description: "Wait time after server errors before retry.",
min: 0,
max: 120_000,
step: 500,
unit: "ms",
},
{
key: "fetchTimeoutMs",
label: "Request Timeout",
description: "Max time to wait for a request.",
min: 1_000,
max: 10 * 60_000,
step: 5_000,
unit: "ms",
},
{
key: "streamStallTimeoutMs",
label: "Stream Stall Timeout",
description: "Max wait before a stuck stream is retried.",
min: 1_000,
max: 10 * 60_000,
step: 5_000,
unit: "ms",
},
{
key: "tokenRefreshSkewMs",
label: "Token Refresh Buffer",
description: "Refresh this long before token expiry.",
min: 0,
max: 10 * 60_000,
step: 10_000,
unit: "ms",
},
{
key: "preemptiveQuotaRemainingPercent5h",
label: "5h Remaining Threshold",
description: "Start delaying when 5h remaining reaches this percent.",
min: 0,
max: 100,
step: 1,
unit: "percent",
},
{
key: "preemptiveQuotaRemainingPercent7d",
label: "7d Remaining Threshold",
description: "Start delaying when weekly remaining reaches this percent.",
min: 0,
max: 100,
step: 1,
unit: "percent",
},
{
key: "preemptiveQuotaMaxDeferralMs",
label: "Max Preemptive Deferral",
description: "Maximum time allowed for quota-based delay.",
min: 1_000,
max: 24 * 60 * 60_000,
step: 60_000,
unit: "ms",
},
];
const BACKEND_DEFAULTS = getDefaultPluginConfig();
const BACKEND_TOGGLE_OPTION_BY_KEY = new Map<
BackendToggleSettingKey,
BackendToggleSettingOption
>(BACKEND_TOGGLE_OPTIONS.map((option) => [option.key, option]));
const BACKEND_NUMBER_OPTION_BY_KEY = new Map<
BackendNumberSettingKey,
BackendNumberSettingOption
>(BACKEND_NUMBER_OPTIONS.map((option) => [option.key, option]));
const BACKEND_CATEGORY_OPTIONS: BackendCategoryOption[] = [
{
key: "session-sync",
label: "Session & Sync",
description: "Sync and session behavior.",
toggleKeys: [
"liveAccountSync",
"sessionAffinity",
"perProjectAccounts",
"sessionRecovery",
"autoResume",
],
numberKeys: [
"liveAccountSyncDebounceMs",
"liveAccountSyncPollMs",
"sessionAffinityTtlMs",
"sessionAffinityMaxEntries",
],
},
{
key: "rotation-quota",
label: "Rotation & Quota",
description: "Quota and retry behavior.",
toggleKeys: ["preemptiveQuotaEnabled", "retryAllAccountsRateLimited"],
numberKeys: [
"preemptiveQuotaRemainingPercent5h",
"preemptiveQuotaRemainingPercent7d",
"preemptiveQuotaMaxDeferralMs",
],
},
{
key: "refresh-recovery",
label: "Refresh & Recovery",
description: "Token refresh and recovery safety.",
toggleKeys: ["storageBackupEnabled"],
numberKeys: ["proactiveRefreshBufferMs", "tokenRefreshSkewMs"],
},
{
key: "performance-timeouts",
label: "Performance & Timeouts",
description: "Speed, probing, and timeout controls.",
toggleKeys: ["fastSession", "parallelProbing"],
numberKeys: [
"fastSessionMaxInputItems",
"parallelProbingMaxConcurrency",
"fetchTimeoutMs",
"streamStallTimeoutMs",
"networkErrorCooldownMs",
"serverErrorCooldownMs",
],
},
];
type DashboardSettingKey = keyof DashboardDisplaySettings;
const RETRYABLE_SETTINGS_WRITE_CODES = new Set([
"EBUSY",
"EPERM",
"EAGAIN",
"ENOTEMPTY",
"EACCES",
]);
const SETTINGS_WRITE_MAX_ATTEMPTS = 4;
const SETTINGS_WRITE_BASE_DELAY_MS = 20;
const SETTINGS_WRITE_MAX_DELAY_MS = 30_000;
const settingsWriteQueues = new Map<string, Promise<void>>();
const ACCOUNT_LIST_PANEL_KEYS = [
"menuShowStatusBadge",
"menuShowCurrentBadge",
"menuShowLastUsed",
"menuShowQuotaSummary",
"menuShowQuotaCooldown",
"menuShowFetchStatus",
"menuShowDetailsForUnselectedRows",
"menuHighlightCurrentRow",
"menuSortEnabled",
"menuSortMode",
"menuSortPinCurrent",
"menuSortQuickSwitchVisibleRow",
"menuLayoutMode",
] as const satisfies readonly DashboardSettingKey[];
const STATUSLINE_PANEL_KEYS = [
"menuStatuslineFields",
] as const satisfies readonly DashboardSettingKey[];
const BEHAVIOR_PANEL_KEYS = [
"actionAutoReturnMs",
"actionPauseOnKey",
"menuAutoFetchLimits",
"menuShowFetchStatus",
"menuQuotaTtlMs",
] as const satisfies readonly DashboardSettingKey[];
const THEME_PANEL_KEYS = [
"uiThemePreset",
"uiAccentColor",
] as const satisfies readonly DashboardSettingKey[];
function readErrorNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim().length > 0) {
const parsed = Number.parseInt(value, 10);
if (Number.isFinite(parsed)) return parsed;
}
return undefined;
}
function getErrorStatusCode(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const record = error as Record<string, unknown>;
return readErrorNumber(record.status) ?? readErrorNumber(record.statusCode);
}
function getRetryAfterMs(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const record = error as Record<string, unknown>;
return (
readErrorNumber(record.retryAfterMs) ??
readErrorNumber(record.retry_after_ms) ??
readErrorNumber(record.retryAfter) ??
readErrorNumber(record.retry_after)
);
}
function isRetryableSettingsWriteError(error: unknown): boolean {
const statusCode = getErrorStatusCode(error);
if (statusCode === 429) return true;
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return typeof code === "string" && RETRYABLE_SETTINGS_WRITE_CODES.has(code);
}
function resolveRetryDelayMs(error: unknown, attempt: number): number {
const retryAfterMs = getRetryAfterMs(error);
if (
typeof retryAfterMs === "number" &&
Number.isFinite(retryAfterMs) &&
retryAfterMs > 0
) {
return Math.max(
10,
Math.min(SETTINGS_WRITE_MAX_DELAY_MS, Math.round(retryAfterMs)),
);
}
return Math.min(
SETTINGS_WRITE_MAX_DELAY_MS,
SETTINGS_WRITE_BASE_DELAY_MS * 2 ** attempt,
);
}
async function enqueueSettingsWrite<T>(
pathKey: string,
task: () => Promise<T>,
): Promise<T> {
const previous = settingsWriteQueues.get(pathKey) ?? Promise.resolve();
const queued = previous.catch(() => {}).then(task);
const queueTail = queued.then(
() => undefined,
() => undefined,
);
settingsWriteQueues.set(pathKey, queueTail);
try {
return await queued;
} finally {
if (settingsWriteQueues.get(pathKey) === queueTail) {
settingsWriteQueues.delete(pathKey);
}
}
}
async function withQueuedRetry<T>(
pathKey: string,
task: () => Promise<T>,
): Promise<T> {
return enqueueSettingsWrite(pathKey, async () => {
let lastError: unknown;
for (let attempt = 0; attempt < SETTINGS_WRITE_MAX_ATTEMPTS; attempt += 1) {
try {
return await task();
} catch (error) {
lastError = error;
if (
!isRetryableSettingsWriteError(error) ||
attempt + 1 >= SETTINGS_WRITE_MAX_ATTEMPTS
) {
throw error;
}
await sleep(resolveRetryDelayMs(error, attempt));
}
}
throw lastError instanceof Error
? lastError
: new Error("settings save retry exhausted");
});
}
function copyDashboardSettingValue(
target: DashboardDisplaySettings,
source: DashboardDisplaySettings,
key: DashboardSettingKey,
): void {
const value = source[key];
(target as unknown as Record<string, unknown>)[key] = Array.isArray(value)
? [...value]
: value;
}
function applyDashboardDefaultsForKeys(
draft: DashboardDisplaySettings,
keys: readonly DashboardSettingKey[],
): DashboardDisplaySettings {
const next = cloneDashboardSettings(draft);
const defaults = cloneDashboardSettings(DEFAULT_DASHBOARD_DISPLAY_SETTINGS);
for (const key of keys) {
copyDashboardSettingValue(next, defaults, key);
}
return next;
}
function mergeDashboardSettingsForKeys(
base: DashboardDisplaySettings,
selected: DashboardDisplaySettings,
keys: readonly DashboardSettingKey[],
): DashboardDisplaySettings {
const next = cloneDashboardSettings(base);
for (const key of keys) {
copyDashboardSettingValue(next, selected, key);
}
return cloneDashboardSettings(next);
}
function resolvePluginConfigSavePathKey(): string {
const envPath = (process.env.CODEX_MULTI_AUTH_CONFIG_PATH ?? "").trim();
return envPath.length > 0 ? envPath : getUnifiedSettingsPath();
}
function formatPersistError(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
function warnPersistFailure(scope: string, error: unknown): void {
console.warn(
`Settings save failed (${scope}) after retries: ${formatPersistError(error)}`,
);
}
async function persistDashboardSettingsSelection(
selected: DashboardDisplaySettings,
keys: readonly DashboardSettingKey[],
scope: string,
): Promise<DashboardDisplaySettings> {
const fallback = cloneDashboardSettings(selected);
try {
return await withQueuedRetry(getDashboardSettingsPath(), async () => {
const latest = cloneDashboardSettings(
await loadDashboardDisplaySettings(),
);
const merged = mergeDashboardSettingsForKeys(latest, selected, keys);
await saveDashboardDisplaySettings(merged);
return merged;
});
} catch (error) {
warnPersistFailure(scope, error);
return fallback;
}
}
async function readFileWithRetry(path: string): Promise<string> {
for (let attempt = 0; ; attempt += 1) {
try {
return await fs.readFile(path, "utf-8");
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
throw error;
}
if (
!code ||
!RETRYABLE_SETTINGS_WRITE_CODES.has(code) ||
attempt >= SETTINGS_WRITE_MAX_ATTEMPTS - 1
) {
throw error;
}
await sleep(25 * 2 ** attempt);
}
}
}
async function persistBackendConfigSelection(
selected: PluginConfig,
scope: string,
): Promise<PluginConfig> {
const fallback = cloneBackendPluginConfig(selected);
try {
await withQueuedRetry(resolvePluginConfigSavePathKey(), async () => {
await savePluginConfig(buildBackendConfigPatch(selected));
});
return fallback;
} catch (error) {
warnPersistFailure(scope, error);
return fallback;
}
}
function normalizeStatuslineFields(
fields: DashboardStatuslineField[] | undefined,
): DashboardStatuslineField[] {
const source = fields ?? DEFAULT_STATUSLINE_FIELDS;
const seen = new Set<DashboardStatuslineField>();
const normalized: DashboardStatuslineField[] = [];
for (const field of source) {
if (seen.has(field)) continue;
seen.add(field);
normalized.push(field);
}
if (normalized.length === 0) {
return [...DEFAULT_STATUSLINE_FIELDS];
}
return normalized;
}
function highlightPreviewToken(
text: string,
ui: ReturnType<typeof getUiRuntimeOptions>,
): string {
if (!output.isTTY) return text;
if (ui.v2Enabled) {
return `${ui.theme.colors.accent}${ANSI.bold}${text}${ui.theme.colors.reset}`;
}
return `${ANSI.cyan}${ANSI.bold}${text}${ANSI.reset}`;
}
function isLastUsedPreviewFocus(focus: PreviewFocusKey): boolean {
return focus === "menuShowLastUsed" || focus === "last-used";
}
function isLimitsPreviewFocus(focus: PreviewFocusKey): boolean {
return focus === "menuShowQuotaSummary" || focus === "limits";
}
function isLimitsCooldownPreviewFocus(focus: PreviewFocusKey): boolean {
return focus === "menuShowQuotaCooldown";
}
function isStatusPreviewFocus(focus: PreviewFocusKey): boolean {
return focus === "menuShowStatusBadge" || focus === "status";
}
function isCurrentBadgePreviewFocus(focus: PreviewFocusKey): boolean {
return focus === "menuShowCurrentBadge";
}
function isCurrentRowPreviewFocus(focus: PreviewFocusKey): boolean {
return focus === "menuHighlightCurrentRow";
}
function isExpandedRowsPreviewFocus(focus: PreviewFocusKey): boolean {
return (
focus === "menuShowDetailsForUnselectedRows" || focus === "menuLayoutMode"
);
}
function buildSummaryPreviewText(
settings: DashboardDisplaySettings,
ui: ReturnType<typeof getUiRuntimeOptions>,
focus: PreviewFocusKey = null,
): string {
const partsByField = new Map<DashboardStatuslineField, string>();
if (settings.menuShowLastUsed !== false) {
const part = `last used: ${PREVIEW_LAST_USED}`;
partsByField.set(
"last-used",
isLastUsedPreviewFocus(focus) ? highlightPreviewToken(part, ui) : part,
);
}
if (settings.menuShowQuotaSummary !== false) {
const limitsText =
settings.menuShowQuotaCooldown === false
? PREVIEW_LIMITS
: `${PREVIEW_LIMITS} | ${PREVIEW_LIMIT_COOLDOWNS}`;
const part = `limits: ${limitsText}`;
partsByField.set(
"limits",
isLimitsPreviewFocus(focus) || isLimitsCooldownPreviewFocus(focus)
? highlightPreviewToken(part, ui)
: part,
);
}
if (settings.menuShowStatusBadge === false) {
const part = `status: ${PREVIEW_STATUS}`;
partsByField.set(
"status",
isStatusPreviewFocus(focus) ? highlightPreviewToken(part, ui) : part,
);
}
const orderedParts = normalizeStatuslineFields(settings.menuStatuslineFields)
.map((field) => partsByField.get(field))
.filter(
(part): part is string => typeof part === "string" && part.length > 0,
);
if (orderedParts.length > 0) {
return orderedParts.join(" | ");
}
const showsStatusField = normalizeStatuslineFields(
settings.menuStatuslineFields,
).includes("status");
if (showsStatusField && settings.menuShowStatusBadge !== false) {
const note = "status text appears only when status badges are hidden";
return isStatusPreviewFocus(focus) ? highlightPreviewToken(note, ui) : note;
}
return "no summary text is visible with current account-list settings";
}
function buildAccountListPreview(
settings: DashboardDisplaySettings,
ui: ReturnType<typeof getUiRuntimeOptions>,
focus: PreviewFocusKey = null,
): { label: string; hint: string } {
const badges: string[] = [];
if (settings.menuShowCurrentBadge !== false) {
const currentBadge = "[current]";
badges.push(
isCurrentBadgePreviewFocus(focus)
? highlightPreviewToken(currentBadge, ui)
: currentBadge,
);
}
if (settings.menuShowStatusBadge !== false) {
const statusBadge = "[active]";
badges.push(
isStatusPreviewFocus(focus)
? highlightPreviewToken(statusBadge, ui)
: statusBadge,
);
}
const badgeSuffix = badges.length > 0 ? ` ${badges.join(" ")}` : "";
const accountEmail = isCurrentRowPreviewFocus(focus)
? highlightPreviewToken(PREVIEW_ACCOUNT_EMAIL, ui)
: PREVIEW_ACCOUNT_EMAIL;
const rowDetailMode =
resolveMenuLayoutMode(settings) === "expanded-rows"
? "details shown on all rows"
: "details shown on selected row only";
const detailModeText = isExpandedRowsPreviewFocus(focus)
? highlightPreviewToken(rowDetailMode, ui)
: rowDetailMode;
return {
label: `1. ${accountEmail}${badgeSuffix}`,
hint: `${buildSummaryPreviewText(settings, ui, focus)}\n${detailModeText}`,
};
}
function cloneDashboardSettings(
settings: DashboardDisplaySettings,
): DashboardDisplaySettings {
const layoutMode = resolveMenuLayoutMode(settings);
return {