@omercnet/paseo-omp 5.2.4 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,894 @@
1
+ import { type PluginSurfaceProps, useRpc } from "@getpaseo/plugin/client";
2
+ import {
3
+ Icon,
4
+ Modal,
5
+ SettingsCard,
6
+ SettingsSelect,
7
+ TextInput,
8
+ useToast,
9
+ } from "@getpaseo/plugin/client/ui";
10
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
11
+ import { type ReactNode, useRef, useState } from "react";
12
+ import { Pressable, Text, View } from "react-native";
13
+ import {
14
+ cancelOmpAccountLogin,
15
+ listOmpAccounts,
16
+ type OmpAccount,
17
+ type OmpAccountProvider,
18
+ type OmpAccountsSettingPath,
19
+ type OmpAccountsSettings,
20
+ type OmpAccountsView,
21
+ type OmpLogin,
22
+ redeemOmpAccountReset,
23
+ removeOmpAccount,
24
+ setOmpAccountSteering,
25
+ setOmpAccountsSetting,
26
+ startOmpAccountLogin,
27
+ submitOmpAccountLoginCode,
28
+ } from "../shared/omp-accounts";
29
+ import { type OmpStore, storeLabel } from "../shared/omp-store";
30
+ import { openOmpExternalUrl } from "./external-url";
31
+ import {
32
+ accountGroups,
33
+ accountsPollInterval,
34
+ balanceLine,
35
+ loginIsOpen,
36
+ resetsLabel,
37
+ signInProviders,
38
+ usedPercent,
39
+ } from "./omp-accounts-state";
40
+ import type { OmpConfigStyles } from "./omp-config-styles";
41
+ import { ompStoreKey } from "./omp-store-state";
42
+ import { quotaResetLabel, quotaSeverityFromFraction } from "./quota-state";
43
+
44
+ type Theme = PluginSurfaceProps["theme"];
45
+
46
+ /** Kept apart from the config editor's `paseo-omp` key so account work never locks setting edits. */
47
+ const ACCOUNTS_KEY = ["paseo-omp-accounts"] as const;
48
+
49
+ type Pending = { kind: "remove"; account: OmpAccount } | { kind: "reset"; account: OmpAccount };
50
+
51
+ type SignInState =
52
+ | { kind: "pick" }
53
+ | { kind: "starting"; provider: OmpAccountProvider }
54
+ | { kind: "failed"; message: string }
55
+ | { kind: "login"; id: string };
56
+
57
+ function describe(error: unknown): string {
58
+ return error instanceof Error ? error.message : String(error);
59
+ }
60
+
61
+ function accountKey(account: Pick<OmpAccount, "provider" | "credentialId">): string {
62
+ return `${account.provider}/${account.credentialId}`;
63
+ }
64
+
65
+ interface ActionButtonProps {
66
+ styles: OmpConfigStyles;
67
+ theme: Theme;
68
+ label: string;
69
+ onPress(): void;
70
+ tone?: "primary" | "danger";
71
+ disabled?: boolean;
72
+ }
73
+
74
+ function ActionButton({ styles, theme, label, onPress, tone, disabled }: ActionButtonProps) {
75
+ const dangerBorder = tone === "danger" ? { borderColor: theme.colors.statusDanger } : null;
76
+ const dangerText = tone === "danger" ? { color: theme.colors.statusDanger } : null;
77
+ return (
78
+ <Pressable
79
+ accessibilityRole="button"
80
+ accessibilityLabel={label}
81
+ accessibilityState={{ disabled: disabled === true }}
82
+ disabled={disabled}
83
+ onPress={onPress}
84
+ style={[
85
+ styles.editorAction,
86
+ tone === "primary" ? styles.editorActionPrimary : null,
87
+ dangerBorder,
88
+ disabled ? { opacity: 0.5 } : null,
89
+ ]}
90
+ >
91
+ <Text
92
+ style={[
93
+ styles.editorActionText,
94
+ tone === "primary" ? styles.editorActionTextPrimary : null,
95
+ dangerText,
96
+ ]}
97
+ >
98
+ {label}
99
+ </Text>
100
+ </Pressable>
101
+ );
102
+ }
103
+
104
+ function severityColor(theme: Theme, usedFraction: number): string {
105
+ const severity = quotaSeverityFromFraction(usedFraction);
106
+ if (severity === "danger") return theme.colors.statusDanger;
107
+ if (severity === "warning") return theme.colors.statusWarning;
108
+ return theme.colors.statusSuccess;
109
+ }
110
+
111
+ function UsageBar({
112
+ theme,
113
+ styles,
114
+ limit,
115
+ }: {
116
+ theme: Theme;
117
+ styles: OmpConfigStyles;
118
+ limit: OmpAccount["limits"][number];
119
+ }) {
120
+ const color = severityColor(theme, limit.usedFraction);
121
+ const percent = usedPercent(limit.usedFraction);
122
+ const resets = quotaResetLabel(limit.resetsAt);
123
+ return (
124
+ <View style={{ gap: 3 }}>
125
+ <View style={{ flexDirection: "row", justifyContent: "space-between", gap: 8 }}>
126
+ <Text numberOfLines={1} style={[styles.rowLabel, { flexShrink: 1 }]}>
127
+ {limit.label}
128
+ </Text>
129
+ <Text style={[styles.rowValue, { color }]}>{`${percent}%`}</Text>
130
+ </View>
131
+ <View
132
+ style={{
133
+ height: 6,
134
+ borderRadius: 3,
135
+ overflow: "hidden",
136
+ backgroundColor: theme.colors.surface2,
137
+ }}
138
+ >
139
+ <View style={{ height: "100%", width: `${percent}%`, backgroundColor: color }} />
140
+ </View>
141
+ {resets ? <Text style={styles.collectionSummary}>{resets}</Text> : null}
142
+ </View>
143
+ );
144
+ }
145
+
146
+ function usageAgeLabel(account: OmpAccount): string | null {
147
+ if (account.usageAt === null || account.limits.length === 0) return null;
148
+ const minutes = Math.max(0, Math.floor((Date.now() - account.usageAt) / 60_000));
149
+ const age = minutes < 1 ? "just now" : `${minutes}m ago`;
150
+ return account.usageIsRecorded ? `OMP's last recorded reading, ${age}` : `Read by OMP ${age}`;
151
+ }
152
+
153
+ /** The reserve select's options; a value outside the fixed choices (set by hand) is listed as itself. */
154
+ function reserveOptions(account: OmpAccount, defaultReservePct: number) {
155
+ const current = account.steering?.reservePct ?? null;
156
+ const value = current === null ? "default" : String(current);
157
+ const options = [
158
+ { label: `OMP default (${defaultReservePct}%)`, value: "default" },
159
+ ...RESERVE_CHOICES.map((pct) => ({ label: `${pct}%`, value: pct })),
160
+ ];
161
+ if (current !== null && !RESERVE_CHOICES.some((pct) => pct === value)) {
162
+ options.push({ label: `${value}%`, value });
163
+ }
164
+ return { value, options };
165
+ }
166
+
167
+ function AccountCard({
168
+ account,
169
+ theme,
170
+ styles,
171
+ defaultReservePct,
172
+ saving,
173
+ onRemove,
174
+ onRedeem,
175
+ onSteer,
176
+ }: {
177
+ account: OmpAccount;
178
+ theme: Theme;
179
+ styles: OmpConfigStyles;
180
+ defaultReservePct: number;
181
+ /** A steering change is saving; the controls wait for it without unmounting. */
182
+ saving: boolean;
183
+ onRemove(): void;
184
+ onRedeem(): void;
185
+ onSteer(change: { preferred?: boolean; reservePct?: number | null }): void;
186
+ }) {
187
+ const reserveShown = reserveOptions(account, defaultReservePct);
188
+ const age = usageAgeLabel(account);
189
+ return (
190
+ <View style={styles.card}>
191
+ <View style={styles.cardHeader}>
192
+ <Text numberOfLines={1} style={[styles.cardTitle, { flexShrink: 1 }]}>
193
+ {account.label}
194
+ </Text>
195
+ {account.resets ? (
196
+ <View style={styles.chip}>
197
+ <Text style={styles.chipText}>{resetsLabel(account.resets)}</Text>
198
+ </View>
199
+ ) : null}
200
+ </View>
201
+ {account.oauth ? null : <Text style={styles.muted}>API key</Text>}
202
+ {account.limits.map((limit) => (
203
+ <UsageBar key={limit.id} theme={theme} styles={styles} limit={limit} />
204
+ ))}
205
+ {account.oauth && account.limits.length === 0 ? (
206
+ <Text style={styles.muted}>OMP has no usage reading for this login yet</Text>
207
+ ) : null}
208
+ {age ? <Text style={styles.collectionSummary}>{age}</Text> : null}
209
+ {account.resets?.blockedReason ? (
210
+ <Text style={styles.collectionSummary}>{account.resets.blockedReason}</Text>
211
+ ) : null}
212
+ {account.steering?.preferred ? (
213
+ <Text style={styles.collectionSummary}>
214
+ Preferred: new agents start here while it has room. OMP can still pick another login, for
215
+ example when it can't read this one's usage.
216
+ </Text>
217
+ ) : null}
218
+ <View style={styles.row}>
219
+ {account.steering ? (
220
+ <ActionButton
221
+ styles={styles}
222
+ theme={theme}
223
+ label={account.steering.preferred ? "Stop preferring" : "Prefer"}
224
+ disabled={saving}
225
+ onPress={() => onSteer({ preferred: !account.steering?.preferred })}
226
+ />
227
+ ) : null}
228
+ {account.resets ? (
229
+ <ActionButton
230
+ styles={styles}
231
+ theme={theme}
232
+ label="Use reset"
233
+ disabled={!account.resets.usableNow}
234
+ onPress={onRedeem}
235
+ />
236
+ ) : null}
237
+ <ActionButton
238
+ styles={styles}
239
+ theme={theme}
240
+ label="Remove"
241
+ tone="danger"
242
+ onPress={onRemove}
243
+ />
244
+ </View>
245
+ {account.steering ? (
246
+ <SettingsSelect
247
+ label="Keep in reserve"
248
+ hint="OMP moves agents off this login before this much is left"
249
+ value={reserveShown.value}
250
+ options={reserveShown.options}
251
+ disabled={saving}
252
+ onValueChange={(choice) =>
253
+ onSteer({ reservePct: choice === "default" ? null : Number(choice) })
254
+ }
255
+ />
256
+ ) : null}
257
+ </View>
258
+ );
259
+ }
260
+
261
+ type SettingRow = {
262
+ path: OmpAccountsSettingPath;
263
+ label: string;
264
+ hint: string;
265
+ options: readonly { label: string; value: string }[];
266
+ };
267
+
268
+ type SteerChange =
269
+ | { kind: "account"; account: OmpAccount; preferred?: boolean; reservePct?: number | null }
270
+ | { kind: "setting"; path: OmpAccountsSettingPath; value: string | number | boolean };
271
+
272
+ const RESERVE_CHOICES = ["0", "5", "10", "20", "30", "50"] as const;
273
+ const KEEP_CHOICES = ["0", "1", "2", "3"] as const;
274
+ const REDEEM_WORDS = [
275
+ { label: "Ask before the first one", value: "unset" },
276
+ { label: "Yes", value: "yes" },
277
+ { label: "No", value: "no" },
278
+ ];
279
+
280
+ /** OMP's own settings for how it uses these logins, worded for the people who use them. */
281
+ const SETTING_ROWS: readonly SettingRow[] = [
282
+ {
283
+ path: "retry.usageReservePct",
284
+ label: "Default reserve",
285
+ hint: "Quota OMP keeps unused on each login unless the login sets its own",
286
+ options: RESERVE_CHOICES.map((pct) => ({ label: `${pct}%`, value: pct })),
287
+ },
288
+ {
289
+ path: "retry.usageReservePolicy",
290
+ label: "When every login is down to its reserve",
291
+ hint: "What OMP does once no login has room left above its reserve",
292
+ options: [
293
+ { label: "Ask first", value: "confirm" },
294
+ { label: "Use the reserve", value: "auto" },
295
+ { label: "Stop", value: "fail-closed" },
296
+ ],
297
+ },
298
+ {
299
+ path: "retry.waitForUsageReset",
300
+ label: "When an agent hits a limit",
301
+ hint: "Waiting holds the agent, and its subagents, until the limit resets",
302
+ options: [
303
+ { label: "Wait for the reset", value: "true" },
304
+ { label: "Stop with an error", value: "false" },
305
+ ],
306
+ },
307
+ {
308
+ path: "codexResets.autoRedeem",
309
+ label: "Use banked ChatGPT resets automatically",
310
+ hint: "When an agent is stuck and no other login can take over, and for resets about to expire",
311
+ options: REDEEM_WORDS,
312
+ },
313
+ {
314
+ path: "codexResets.keepCredits",
315
+ label: "ChatGPT resets to keep",
316
+ hint: "Automatic use never goes below this many, except for resets about to expire",
317
+ options: KEEP_CHOICES.map((count) => ({ label: count === "0" ? "None" : count, value: count })),
318
+ },
319
+ {
320
+ path: "claudeResets.autoRedeem",
321
+ label: "Use banked Claude resets automatically",
322
+ hint: "Only for the limits a reset covers",
323
+ options: REDEEM_WORDS,
324
+ },
325
+ {
326
+ path: "claudeResets.keepCredits",
327
+ label: "Claude resets to keep",
328
+ hint: "Automatic use never goes below this many, except for resets about to expire",
329
+ options: KEEP_CHOICES.map((count) => ({ label: count === "0" ? "None" : count, value: count })),
330
+ },
331
+ ];
332
+
333
+ /** The select's string back to the type OMP's setting takes. */
334
+ function settingValue(row: SettingRow, choice: string): string | number | boolean {
335
+ if (row.path === "retry.waitForUsageReset") return choice === "true";
336
+ if (row.path.endsWith("keepCredits") || row.path === "retry.usageReservePct")
337
+ return Number(choice);
338
+ return choice;
339
+ }
340
+
341
+ /** The current value as a select option; a value outside the fixed choices is listed as itself. */
342
+ function withCurrent(row: SettingRow, current: string | number | boolean | undefined) {
343
+ if (current === undefined) return { value: "", options: row.options };
344
+ const value = String(current);
345
+ const known = row.options.some((option) => option.value === value);
346
+ return { value, options: known ? row.options : [...row.options, { label: value, value }] };
347
+ }
348
+
349
+ function SteeringSettingsCard({
350
+ styles,
351
+ settings,
352
+ disabled,
353
+ onChange,
354
+ }: {
355
+ styles: OmpConfigStyles;
356
+ settings: OmpAccountsSettings;
357
+ disabled: boolean;
358
+ onChange(path: OmpAccountsSettingPath, value: string | number | boolean): void;
359
+ }) {
360
+ return (
361
+ <View style={{ gap: 8 }}>
362
+ <Text style={styles.cardTitle}>How OMP uses these logins</Text>
363
+ <Text style={styles.muted}>
364
+ OMP's own settings, written to its config for the selected store. Terminal omp follows them
365
+ too.
366
+ </Text>
367
+ <SettingsCard>
368
+ {SETTING_ROWS.map((row) => {
369
+ const shown = withCurrent(row, settings[row.path]);
370
+ return (
371
+ <SettingsSelect
372
+ key={row.path}
373
+ label={row.label}
374
+ hint={row.hint}
375
+ value={shown.value}
376
+ options={shown.options}
377
+ disabled={disabled || shown.value === ""}
378
+ onValueChange={(choice) => onChange(row.path, settingValue(row, choice))}
379
+ />
380
+ );
381
+ })}
382
+ </SettingsCard>
383
+ </View>
384
+ );
385
+ }
386
+
387
+ function ConfirmModal({
388
+ styles,
389
+ theme,
390
+ title,
391
+ body,
392
+ confirmLabel,
393
+ tone,
394
+ busy,
395
+ onConfirm,
396
+ onCancel,
397
+ }: {
398
+ styles: OmpConfigStyles;
399
+ theme: Theme;
400
+ title: string;
401
+ body: string;
402
+ confirmLabel: string;
403
+ tone: "primary" | "danger";
404
+ busy: boolean;
405
+ onConfirm(): void;
406
+ onCancel(): void;
407
+ }) {
408
+ return (
409
+ <Modal title={title} open onOpenChange={(open) => (open || busy ? undefined : onCancel())}>
410
+ <Modal.Content>
411
+ <Text style={styles.rowValue}>{body}</Text>
412
+ <View style={[styles.row, { justifyContent: "flex-end" }]}>
413
+ <ActionButton
414
+ styles={styles}
415
+ theme={theme}
416
+ label="Cancel"
417
+ disabled={busy}
418
+ onPress={onCancel}
419
+ />
420
+ <ActionButton
421
+ styles={styles}
422
+ theme={theme}
423
+ label={busy ? "Working..." : confirmLabel}
424
+ tone={tone}
425
+ disabled={busy}
426
+ onPress={onConfirm}
427
+ />
428
+ </View>
429
+ </Modal.Content>
430
+ </Modal>
431
+ );
432
+ }
433
+
434
+ function ProviderPicker({
435
+ styles,
436
+ theme,
437
+ providers,
438
+ onPick,
439
+ }: {
440
+ styles: OmpConfigStyles;
441
+ theme: Theme;
442
+ providers: readonly OmpAccountProvider[];
443
+ onPick(provider: OmpAccountProvider): void;
444
+ }) {
445
+ const [query, setQuery] = useState("");
446
+ const shown = signInProviders(providers, query);
447
+ return (
448
+ <>
449
+ <Text style={styles.muted}>Which provider is the login for?</Text>
450
+ <TextInput
451
+ value={query}
452
+ onChangeText={setQuery}
453
+ placeholder="Search providers"
454
+ placeholderTextColor={theme.colors.foregroundMuted}
455
+ autoCapitalize="none"
456
+ autoCorrect={false}
457
+ accessibilityLabel="Search providers"
458
+ style={styles.search}
459
+ />
460
+ {shown.length === 0 ? <Text style={styles.muted}>No provider matches</Text> : null}
461
+ {shown.map((provider) => (
462
+ <Pressable
463
+ key={provider.id}
464
+ accessibilityRole="button"
465
+ accessibilityLabel={`Sign in to ${provider.name}`}
466
+ onPress={() => onPick(provider)}
467
+ style={[
468
+ styles.editorAction,
469
+ { flexDirection: "row", justifyContent: "space-between", gap: 8 },
470
+ ]}
471
+ >
472
+ <Text style={[styles.editorActionText, { flexShrink: 1 }]}>{provider.name}</Text>
473
+ {provider.authenticated ? <Text style={styles.collectionSummary}>Signed in</Text> : null}
474
+ </Pressable>
475
+ ))}
476
+ </>
477
+ );
478
+ }
479
+
480
+ function LoginProgress({
481
+ styles,
482
+ theme,
483
+ login,
484
+ onSubmit,
485
+ onRetry,
486
+ onClose,
487
+ }: {
488
+ styles: OmpConfigStyles;
489
+ theme: Theme;
490
+ login: OmpLogin;
491
+ onSubmit(code: string): Promise<void>;
492
+ onRetry(): void;
493
+ onClose(): void;
494
+ }) {
495
+ const toast = useToast();
496
+ const [code, setCode] = useState("");
497
+ const [submitting, setSubmitting] = useState(false);
498
+ const [codeError, setCodeError] = useState<string | null>(null);
499
+ const url = login.url;
500
+
501
+ async function submit() {
502
+ setSubmitting(true);
503
+ setCodeError(null);
504
+ try {
505
+ await onSubmit(code);
506
+ setCode("");
507
+ } catch (error) {
508
+ setCodeError(describe(error));
509
+ } finally {
510
+ setSubmitting(false);
511
+ }
512
+ }
513
+
514
+ if (login.step === "done") {
515
+ return (
516
+ <>
517
+ <Text style={styles.cardTitle}>You're signed in</Text>
518
+ <Text style={styles.rowValue}>OMP agents on this host can use the login now.</Text>
519
+ <View style={[styles.row, { justifyContent: "flex-end" }]}>
520
+ <ActionButton
521
+ styles={styles}
522
+ theme={theme}
523
+ label="Done"
524
+ tone="primary"
525
+ onPress={onClose}
526
+ />
527
+ </View>
528
+ </>
529
+ );
530
+ }
531
+ if (login.step === "failed" || login.step === "canceled") {
532
+ return (
533
+ <>
534
+ <Text style={login.step === "failed" ? styles.error : styles.muted}>
535
+ {login.message ?? "Sign-in did not finish"}
536
+ </Text>
537
+ <View style={[styles.row, { justifyContent: "flex-end" }]}>
538
+ <ActionButton styles={styles} theme={theme} label="Close" onPress={onClose} />
539
+ <ActionButton
540
+ styles={styles}
541
+ theme={theme}
542
+ label="Try again"
543
+ tone="primary"
544
+ onPress={onRetry}
545
+ />
546
+ </View>
547
+ </>
548
+ );
549
+ }
550
+ if (login.step === "starting") return <Text style={styles.muted}>Preparing sign-in...</Text>;
551
+ if (login.step === "verifying") return <Text style={styles.muted}>Checking the login...</Text>;
552
+ return (
553
+ <>
554
+ <Text style={styles.cardTitle}>1. Open the sign-in page</Text>
555
+ <Text style={styles.muted}>Sign in with the account you want to add.</Text>
556
+ {login.instructions ? <Text style={styles.rowValue}>{login.instructions}</Text> : null}
557
+ <View style={styles.row}>
558
+ <ActionButton
559
+ styles={styles}
560
+ theme={theme}
561
+ label="Open sign-in page"
562
+ tone="primary"
563
+ disabled={url === null}
564
+ onPress={() => {
565
+ if (url)
566
+ openOmpExternalUrl(url).catch((error: unknown) => toast.error(describe(error)));
567
+ }}
568
+ />
569
+ </View>
570
+ {login.codePrompt ? (
571
+ <>
572
+ <Text style={styles.cardTitle}>
573
+ 2. Not on this host's computer? Paste what the page shows
574
+ </Text>
575
+ <Text style={styles.muted}>
576
+ On the host's computer sign-in finishes by itself. Anywhere else, paste the code, or the
577
+ address of the page that failed to load after signing in.
578
+ </Text>
579
+ <TextInput
580
+ value={code}
581
+ onChangeText={setCode}
582
+ placeholder={login.codePrompt}
583
+ placeholderTextColor={theme.colors.foregroundMuted}
584
+ autoCapitalize="none"
585
+ autoCorrect={false}
586
+ accessibilityLabel="Sign-in code or redirect URL"
587
+ onSubmitEditing={() => void submit()}
588
+ style={styles.scalarInput}
589
+ />
590
+ {codeError ? <Text style={styles.error}>{codeError}</Text> : null}
591
+ <View style={styles.row}>
592
+ <ActionButton
593
+ styles={styles}
594
+ theme={theme}
595
+ label={submitting ? "Continuing..." : "Continue"}
596
+ tone="primary"
597
+ disabled={submitting || code.trim() === ""}
598
+ onPress={() => void submit()}
599
+ />
600
+ </View>
601
+ </>
602
+ ) : (
603
+ <Text style={styles.muted}>Waiting for you to finish signing in...</Text>
604
+ )}
605
+ {login.message ? <Text style={styles.collectionSummary}>{login.message}</Text> : null}
606
+ </>
607
+ );
608
+ }
609
+
610
+ function SignInModal({
611
+ styles,
612
+ theme,
613
+ store,
614
+ view,
615
+ onClose,
616
+ }: {
617
+ styles: OmpConfigStyles;
618
+ theme: Theme;
619
+ store: OmpStore | undefined;
620
+ view: OmpAccountsView | undefined;
621
+ onClose(): void;
622
+ }) {
623
+ const queryClient = useQueryClient();
624
+ const start = useRpc(startOmpAccountLogin);
625
+ const submit = useRpc(submitOmpAccountLoginCode);
626
+ const cancel = useRpc(cancelOmpAccountLogin);
627
+ const [state, setState] = useState<SignInState>({ kind: "pick" });
628
+ const closed = useRef(false);
629
+ const login =
630
+ state.kind === "login" ? view?.logins.find((entry) => entry.id === state.id) : undefined;
631
+
632
+ async function begin(provider: OmpAccountProvider) {
633
+ setState({ kind: "starting", provider });
634
+ try {
635
+ const started = await start({ store, provider: provider.id });
636
+ // Closed while omp was starting: nothing else knows the id, so cancel it here or it keeps
637
+ // the OAuth callback port until the next sign-in.
638
+ if (closed.current) {
639
+ cancel({ store, loginId: started.id }).catch(() => undefined);
640
+ return;
641
+ }
642
+ setState({ kind: "login", id: started.id });
643
+ await queryClient.invalidateQueries({ queryKey: ACCOUNTS_KEY });
644
+ } catch (error) {
645
+ if (!closed.current) setState({ kind: "failed", message: describe(error) });
646
+ }
647
+ }
648
+
649
+ function close() {
650
+ closed.current = true;
651
+ if (login && loginIsOpen(login)) cancel({ store, loginId: login.id }).catch(() => undefined);
652
+ onClose();
653
+ }
654
+
655
+ let body: ReactNode;
656
+ if (state.kind === "pick") {
657
+ body = (
658
+ <ProviderPicker
659
+ styles={styles}
660
+ theme={theme}
661
+ providers={view?.providers ?? []}
662
+ onPick={(provider) => void begin(provider)}
663
+ />
664
+ );
665
+ } else if (state.kind === "starting") {
666
+ body = <Text style={styles.muted}>{`Starting ${state.provider.name} sign-in...`}</Text>;
667
+ } else if (state.kind === "failed") {
668
+ body = (
669
+ <>
670
+ <Text style={styles.error}>{state.message}</Text>
671
+ <View style={[styles.row, { justifyContent: "flex-end" }]}>
672
+ <ActionButton styles={styles} theme={theme} label="Close" onPress={close} />
673
+ </View>
674
+ </>
675
+ );
676
+ } else if (login) {
677
+ body = (
678
+ <LoginProgress
679
+ styles={styles}
680
+ theme={theme}
681
+ login={login}
682
+ onSubmit={async (code) => {
683
+ await submit({ store, loginId: login.id, code });
684
+ await queryClient.invalidateQueries({ queryKey: ACCOUNTS_KEY });
685
+ }}
686
+ onRetry={() => setState({ kind: "pick" })}
687
+ onClose={close}
688
+ />
689
+ );
690
+ } else {
691
+ body = <Text style={styles.muted}>Preparing sign-in...</Text>;
692
+ }
693
+
694
+ return (
695
+ <Modal title="Add OMP login" open onOpenChange={(open) => (open ? undefined : close())}>
696
+ <Modal.Content>
697
+ <Text style={styles.collectionSummary}>{`Adds the login to ${storeLabel(store)}`}</Text>
698
+ {body}
699
+ </Modal.Content>
700
+ </Modal>
701
+ );
702
+ }
703
+
704
+ export function OmpAccountsSection({
705
+ theme,
706
+ styles,
707
+ store,
708
+ }: {
709
+ theme: Theme;
710
+ styles: OmpConfigStyles;
711
+ store?: OmpStore;
712
+ }) {
713
+ const toast = useToast();
714
+ const queryClient = useQueryClient();
715
+ const load = useRpc(listOmpAccounts);
716
+ const remove = useRpc(removeOmpAccount);
717
+ const redeem = useRpc(redeemOmpAccountReset);
718
+ const [adding, setAdding] = useState(false);
719
+ const [pending, setPending] = useState<Pending | null>(null);
720
+ const setSteering = useRpc(setOmpAccountSteering);
721
+ const setSetting = useRpc(setOmpAccountsSetting);
722
+ const queryKey = [...ACCOUNTS_KEY, ompStoreKey(store)];
723
+ const accounts = useQuery({
724
+ queryKey,
725
+ queryFn: () => load({ store }),
726
+ refetchInterval: (query) => accountsPollInterval(query.state.data),
727
+ });
728
+ const refresh = useMutation({
729
+ mutationKey: [...ACCOUNTS_KEY, "refresh"],
730
+ mutationFn: () => load({ store, refresh: true }),
731
+ onSuccess: (view) => queryClient.setQueryData(queryKey, view),
732
+ onError: (error) => toast.error(describe(error)),
733
+ });
734
+ const removeLogin = useMutation({
735
+ mutationKey: [...ACCOUNTS_KEY, "remove"],
736
+ mutationFn: (account: OmpAccount) =>
737
+ remove({ store, provider: account.provider, credentialId: account.credentialId }),
738
+ onSuccess: async (_result, account) => {
739
+ toast.show(`Signed ${account.label} out of OMP`, { variant: "success" });
740
+ await queryClient.invalidateQueries({ queryKey: ACCOUNTS_KEY });
741
+ },
742
+ onError: (error) => toast.error(describe(error)),
743
+ onSettled: () => setPending(null),
744
+ });
745
+ const redeemReset = useMutation({
746
+ mutationKey: [...ACCOUNTS_KEY, "redeem"],
747
+ mutationFn: (account: OmpAccount) =>
748
+ redeem({ store, provider: account.provider, credentialId: account.credentialId }),
749
+ onSuccess: async (result) => {
750
+ if (result.ok) toast.show(result.message, { variant: "success" });
751
+ else toast.error(result.message);
752
+ await queryClient.invalidateQueries({ queryKey: ACCOUNTS_KEY });
753
+ },
754
+ onError: (error) => toast.error(describe(error)),
755
+ onSettled: () => setPending(null),
756
+ });
757
+ const steer = useMutation({
758
+ mutationKey: [...ACCOUNTS_KEY, "steer"],
759
+ mutationFn: (change: SteerChange) =>
760
+ change.kind === "account"
761
+ ? setSteering({
762
+ store,
763
+ provider: change.account.provider,
764
+ credentialId: change.account.credentialId,
765
+ preferred: change.preferred,
766
+ reservePct: change.reservePct,
767
+ })
768
+ : setSetting({ store, path: change.path, value: change.value }),
769
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ACCOUNTS_KEY }),
770
+ onError: (error) => toast.error(describe(error)),
771
+ });
772
+
773
+ const view = accounts.data;
774
+ const groups = view ? accountGroups(view) : [];
775
+ const busy = removeLogin.isPending || redeemReset.isPending;
776
+ const reservePct = view?.settings["retry.usageReservePct"];
777
+ const defaultReserve = typeof reservePct === "number" ? reservePct : 10;
778
+
779
+ return (
780
+ <>
781
+ <View style={styles.sectionHeader}>
782
+ <View style={styles.sectionHeaderRow}>
783
+ <Text style={styles.sectionTitle}>Accounts</Text>
784
+ <Pressable
785
+ accessibilityRole="button"
786
+ accessibilityLabel="Refresh OMP accounts"
787
+ style={styles.refresh}
788
+ disabled={refresh.isPending}
789
+ onPress={() => refresh.mutate()}
790
+ >
791
+ <Icon name="RefreshCw" size={14} color={theme.colors.foreground} />
792
+ <Text style={styles.refreshLabel}>
793
+ {refresh.isPending ? "Refreshing..." : "Refresh"}
794
+ </Text>
795
+ </Pressable>
796
+ <ActionButton
797
+ styles={styles}
798
+ theme={theme}
799
+ label="Add login"
800
+ tone="primary"
801
+ disabled={view === undefined || !view.installed}
802
+ onPress={() => setAdding(true)}
803
+ />
804
+ </View>
805
+ <Text style={styles.source}>{storeLabel(store)}</Text>
806
+ </View>
807
+ <Text style={styles.muted}>
808
+ OMP keeps its own sign-ins. It spreads agents across them and moves off a login that hits a
809
+ limit by itself. This page shows those logins and signs them in or out through omp.
810
+ </Text>
811
+ {accounts.isLoading ? <Text style={styles.muted}>Loading OMP accounts...</Text> : null}
812
+ {accounts.error ? (
813
+ <Text
814
+ style={styles.error}
815
+ >{`Could not read OMP's accounts: ${describe(accounts.error)}`}</Text>
816
+ ) : null}
817
+ {view && !view.installed ? (
818
+ <Text style={styles.muted}>The omp command was not found on this host.</Text>
819
+ ) : null}
820
+ {view?.error ? <Text style={styles.error}>{view.error}</Text> : null}
821
+ {view?.installed && view.fetchedAt !== null && groups.length === 0 ? (
822
+ <Text style={styles.muted}>No OMP logins yet. Add one to get started.</Text>
823
+ ) : null}
824
+ {groups.map(({ provider, accounts: logins }) => (
825
+ <View key={provider.id} style={{ gap: 8 }}>
826
+ <Text style={styles.cardTitle}>{provider.name}</Text>
827
+ {view?.balance
828
+ .filter((preview) => preview.provider === provider.id)
829
+ .map((preview) => (
830
+ <Text key={preview.model} style={styles.collectionSummary}>
831
+ {balanceLine(preview)}
832
+ </Text>
833
+ ))}
834
+ {logins.map((account) => (
835
+ <AccountCard
836
+ key={accountKey(account)}
837
+ account={account}
838
+ theme={theme}
839
+ styles={styles}
840
+ defaultReservePct={defaultReserve}
841
+ saving={steer.isPending}
842
+ onRemove={() => setPending({ kind: "remove", account })}
843
+ onRedeem={() => setPending({ kind: "reset", account })}
844
+ onSteer={(change) => steer.mutate({ kind: "account", account, ...change })}
845
+ />
846
+ ))}
847
+ </View>
848
+ ))}
849
+ {view?.installed && view.fetchedAt !== null ? (
850
+ <SteeringSettingsCard
851
+ styles={styles}
852
+ settings={view.settings}
853
+ disabled={steer.isPending}
854
+ onChange={(path, value) => steer.mutate({ kind: "setting", path, value })}
855
+ />
856
+ ) : null}
857
+ {pending?.kind === "remove" ? (
858
+ <ConfirmModal
859
+ styles={styles}
860
+ theme={theme}
861
+ title={`Remove ${pending.account.label}?`}
862
+ body="This signs the login out of OMP on this machine, for the terminal too. OMP agents carry on with its other logins."
863
+ confirmLabel="Remove"
864
+ tone="danger"
865
+ busy={busy}
866
+ onConfirm={() => removeLogin.mutate(pending.account)}
867
+ onCancel={() => setPending(null)}
868
+ />
869
+ ) : null}
870
+ {pending?.kind === "reset" ? (
871
+ <ConfirmModal
872
+ styles={styles}
873
+ theme={theme}
874
+ title="Use a banked reset?"
875
+ body={`Spends one banked reset on ${pending.account.label} to refill its limits now. A reset can't be undone.`}
876
+ confirmLabel="Use reset"
877
+ tone="primary"
878
+ busy={busy}
879
+ onConfirm={() => redeemReset.mutate(pending.account)}
880
+ onCancel={() => setPending(null)}
881
+ />
882
+ ) : null}
883
+ {adding ? (
884
+ <SignInModal
885
+ styles={styles}
886
+ theme={theme}
887
+ store={store}
888
+ view={view}
889
+ onClose={() => setAdding(false)}
890
+ />
891
+ ) : null}
892
+ </>
893
+ );
894
+ }