paseo-plugin-account-switcher 0.2.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.
- package/LICENSE +21 -0
- package/README.md +130 -0
- package/THIRD_PARTY_NOTICES.md +46 -0
- package/client/accounts.tsx +198 -0
- package/client/components.tsx +173 -0
- package/client/data.ts +47 -0
- package/client/format.ts +155 -0
- package/client/login.ts +48 -0
- package/client/runtime.ts +143 -0
- package/client/sign-in-state.ts +48 -0
- package/client/sign-in.tsx +108 -0
- package/client/switcher.tsx +115 -0
- package/client/web.ts +19 -0
- package/index.client.tsx +36 -0
- package/index.server.ts +30 -0
- package/licenses/iarna-toml-2.2.5.txt +14 -0
- package/licenses/paseo-0.8.0.txt +211 -0
- package/licenses/zod-4.6.5.txt +21 -0
- package/package.json +66 -0
- package/paseo-plugin.json +1 -0
- package/server/auth.ts +141 -0
- package/server/controller.ts +319 -0
- package/server/files.ts +17 -0
- package/server/integration.ts +152 -0
- package/server/launcher-artifact.ts +2 -0
- package/server/launcher-main.ts +80 -0
- package/server/login-process.ts +119 -0
- package/server/login.ts +167 -0
- package/server/paseo-api.ts +5 -0
- package/server/profiles.ts +138 -0
- package/server/store.ts +80 -0
- package/server/switching.ts +79 -0
- package/server/usage/README.md +89 -0
- package/server/usage/claude.ts +95 -0
- package/server/usage/codex.ts +79 -0
- package/server/usage/credential-hash.ts +4 -0
- package/server/usage/credentials.ts +18 -0
- package/server/usage/index.ts +225 -0
- package/server/usage/parsers.ts +63 -0
- package/shared/contracts.ts +63 -0
package/client/format.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { Account, AccountState, Provider, UsageSnapshot, UsageWindow } from "../shared/contracts";
|
|
2
|
+
|
|
3
|
+
export const providerName: Record<Provider, string> = { claude: "Claude", codex: "Codex · ChatGPT" };
|
|
4
|
+
|
|
5
|
+
export function supportedProvider(value: string): Provider | null {
|
|
6
|
+
const name = value.split("/")[0];
|
|
7
|
+
return name === "claude" || name === "codex" ? name : null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function percent(value: number | null): string {
|
|
11
|
+
return value === null || !Number.isFinite(value) ? "—" : `${Math.round(value * 10) / 10}%`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function remainingPercent(used: number | null): number | null {
|
|
15
|
+
return used === null || !Number.isFinite(used) ? null : Math.max(0, 100 - used);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function quotaLevel(used: number | null): "unknown" | "normal" | "warning" | "critical" | "exhausted" {
|
|
19
|
+
if (used === null || !Number.isFinite(used)) return "unknown";
|
|
20
|
+
if (used >= 100) return "exhausted";
|
|
21
|
+
if (used >= 95) return "critical";
|
|
22
|
+
if (used >= 80) return "warning";
|
|
23
|
+
return "normal";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function localDate(value: string | null): string {
|
|
27
|
+
if (!value || !Number.isFinite(Date.parse(value))) return "unknown";
|
|
28
|
+
return new Date(value).toLocaleString("en-US", {
|
|
29
|
+
day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit",
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function resetCountdown(value: string | null, now = Date.now()): string {
|
|
34
|
+
if (!value || !Number.isFinite(Date.parse(value))) return "Reset time unknown";
|
|
35
|
+
const difference = Date.parse(value) - now;
|
|
36
|
+
if (difference <= 0) return "Reset time passed · waiting for new data";
|
|
37
|
+
const minutes = Math.ceil(difference / 60_000);
|
|
38
|
+
const days = Math.floor(minutes / 1_440);
|
|
39
|
+
const hours = Math.floor((minutes % 1_440) / 60);
|
|
40
|
+
const rest = minutes % 60;
|
|
41
|
+
return `Resets in ${[days ? `${days} d` : "", hours ? `${hours} hr` : "", rest ? `${rest} min` : ""].filter(Boolean).join(" ")}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function windowIsExpired(quota: UsageWindow, now = Date.now()): boolean {
|
|
45
|
+
return quota.resetsAt !== null && Number.isFinite(Date.parse(quota.resetsAt)) && Date.parse(quota.resetsAt) <= now;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function usageSummary(snapshot: UsageSnapshot | undefined, now = Date.now()): string {
|
|
49
|
+
if (!snapshot) return "limits —";
|
|
50
|
+
if (snapshot.status === "needs_auth") return "sign-in required";
|
|
51
|
+
if (snapshot.status === "unavailable") return "limits unavailable";
|
|
52
|
+
const known = snapshot.windows.filter((quota) => quota.usedPercent !== null && Number.isFinite(quota.usedPercent));
|
|
53
|
+
if (!known.length) return snapshot.status === "stale" ? "limits stale" : "limits —";
|
|
54
|
+
const limiting = known.reduce((left, right) => left.usedPercent! >= right.usedPercent! ? left : right);
|
|
55
|
+
const stale = snapshot.status === "stale" || windowIsExpired(limiting, now);
|
|
56
|
+
return `${percent(remainingPercent(limiting.usedPercent))} left${stale ? " · stale" : ""}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function currentAccount(state: AccountState, agentId: string, provider: Provider): Account | undefined {
|
|
60
|
+
const binding = state.bindings.find((item) => item.agentId === agentId);
|
|
61
|
+
if (binding && binding.currentAccountId === null) return undefined;
|
|
62
|
+
const id = binding ? binding.currentAccountId : `system-${provider}`;
|
|
63
|
+
return state.accounts.find((account) => account.id === id);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function currentAccountName(state: AccountState, agentId: string, provider: Provider): string {
|
|
67
|
+
const binding = state.bindings.find((item) => item.agentId === agentId);
|
|
68
|
+
if (binding && binding.currentAccountId === null) return "Account not confirmed";
|
|
69
|
+
return currentAccount(state, agentId, provider)?.label ?? "Account unknown";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function idleForSwitch(agent: {
|
|
73
|
+
status: string;
|
|
74
|
+
activeTurn?: unknown;
|
|
75
|
+
pendingPermissions: readonly unknown[];
|
|
76
|
+
} | null | undefined): boolean {
|
|
77
|
+
return Boolean(agent && agent.status === "idle" && !agent.activeTurn && agent.pendingPermissions.length === 0);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function errorMessage(error: unknown): string {
|
|
81
|
+
return error instanceof Error ? error.message : typeof error === "string" ? error : "Could not complete the action. Try again.";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export type Tone = "muted" | "success" | "warning" | "danger";
|
|
85
|
+
|
|
86
|
+
export function quotaTone(used: number | null): Tone {
|
|
87
|
+
const level = quotaLevel(used);
|
|
88
|
+
return level === "exhausted" || level === "critical" ? "danger" : level === "warning" ? "warning" : level === "normal" ? "success" : "muted";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Windows with a measured percentage first (provider order kept); windows without data are listed separately. */
|
|
92
|
+
export function splitWindows(windows: readonly UsageWindow[]): { known: UsageWindow[]; unknown: UsageWindow[] } {
|
|
93
|
+
const known: UsageWindow[] = [];
|
|
94
|
+
const unknown: UsageWindow[] = [];
|
|
95
|
+
for (const quota of windows) (quota.usedPercent !== null && Number.isFinite(quota.usedPercent) ? known : unknown).push(quota);
|
|
96
|
+
return { known, unknown };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function shortDuration(ms: number): string {
|
|
100
|
+
const minutes = Math.max(1, Math.ceil(ms / 60_000));
|
|
101
|
+
const days = Math.floor(minutes / 1_440);
|
|
102
|
+
const hours = Math.floor((minutes % 1_440) / 60);
|
|
103
|
+
const rest = minutes % 60;
|
|
104
|
+
if (days) return hours ? `${days} d ${hours} hr` : `${days} d`;
|
|
105
|
+
if (hours) return rest ? `${hours} hr ${rest} min` : `${hours} hr`;
|
|
106
|
+
return `${rest} min`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Compact reset countdown for one line; the full sentence stays in resetCountdown. */
|
|
110
|
+
export function shortCountdown(value: string | null, now = Date.now()): string {
|
|
111
|
+
if (!value || !Number.isFinite(Date.parse(value))) return "reset time unknown";
|
|
112
|
+
const difference = Date.parse(value) - now;
|
|
113
|
+
return difference <= 0 ? "reset time passed" : `in ${shortDuration(difference)}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function relativeTime(value: string | null, now = Date.now()): string {
|
|
117
|
+
if (!value || !Number.isFinite(Date.parse(value))) return "unknown";
|
|
118
|
+
const difference = now - Date.parse(value);
|
|
119
|
+
if (difference < 60_000) return "just now";
|
|
120
|
+
return `${shortDuration(difference)} ago`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function windowLength(minutes: number | null): string | null {
|
|
124
|
+
if (minutes === null || !Number.isFinite(minutes) || minutes <= 0) return null;
|
|
125
|
+
return shortDuration(minutes * 60_000);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** One short freshness line per snapshot; errors are shown separately and never hidden. */
|
|
129
|
+
export function freshness(snapshot: UsageSnapshot | undefined, now = Date.now()): { text: string; tone: Tone } {
|
|
130
|
+
if (!snapshot) return { text: "limits not fetched yet", tone: "muted" };
|
|
131
|
+
if (snapshot.status === "needs_auth") return { text: "limits: sign-in required", tone: "warning" };
|
|
132
|
+
if (snapshot.status === "unavailable") return { text: `limits unavailable · checked ${relativeTime(snapshot.checkedAt, now)}`, tone: "danger" };
|
|
133
|
+
const age = relativeTime(snapshot.fetchedAt, now);
|
|
134
|
+
if (snapshot.status === "stale") return { text: `stale data · ${age}`, tone: "warning" };
|
|
135
|
+
const expired = snapshot.windows.some((quota) => windowIsExpired(quota, now));
|
|
136
|
+
return expired ? { text: `reset time passed · data from ${age}`, tone: "warning" } : { text: `updated ${age}`, tone: "muted" };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function accountStatus(account: Account, snapshot: UsageSnapshot | undefined): { text: string; tone: Tone } {
|
|
140
|
+
if (account.login) return { text: "sign-in in progress", tone: "warning" };
|
|
141
|
+
if (account.authStatus === "ready" && snapshot?.status === "needs_auth") return { text: "limits require sign-in", tone: "warning" };
|
|
142
|
+
return {
|
|
143
|
+
ready: { text: "sign-in confirmed", tone: "success" as Tone },
|
|
144
|
+
needs_auth: { text: "sign-in required", tone: "warning" as Tone },
|
|
145
|
+
unknown: { text: "sign-in not checked", tone: "muted" as Tone },
|
|
146
|
+
error: { text: "sign-in error", tone: "danger" as Tone },
|
|
147
|
+
}[account.authStatus];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Every pressable keeps a 44px touch target: the drawn box plus symmetric hit slop that fills the difference.
|
|
151
|
+
export const TOUCH_TARGET = 44;
|
|
152
|
+
export function targetSlop(boxHeight: number, horizontal = 4): { top: number; bottom: number; left: number; right: number } {
|
|
153
|
+
const vertical = Math.max(0, Math.ceil((TOUCH_TARGET - boxHeight) / 2));
|
|
154
|
+
return { top: vertical, bottom: vertical, left: horizontal, right: horizontal };
|
|
155
|
+
}
|
package/client/login.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Account, LoginSession, Provider } from "../shared/contracts";
|
|
2
|
+
import { errorMessage } from "./format";
|
|
3
|
+
|
|
4
|
+
export type LoginMode = "device" | "browser";
|
|
5
|
+
export type { LoginSession } from "../shared/contracts";
|
|
6
|
+
|
|
7
|
+
/** Keep creation as a completed step if starting authorization fails. */
|
|
8
|
+
export async function addAndStartLogin(input: { provider: Provider; label: string; mode: LoginMode }, dependencies: {
|
|
9
|
+
add(input: { provider: Provider; label: string }): Promise<Account>;
|
|
10
|
+
start(input: { accountId: string; mode?: LoginMode }): Promise<LoginSession>;
|
|
11
|
+
onCreated(account: Account): void;
|
|
12
|
+
}): Promise<LoginSession> {
|
|
13
|
+
const account = await dependencies.add({ provider: input.provider, label: input.label });
|
|
14
|
+
dependencies.onCreated(account);
|
|
15
|
+
try {
|
|
16
|
+
return await dependencies.start({ accountId: account.id, ...(account.provider === "codex" ? { mode: input.mode } : {}) });
|
|
17
|
+
} catch (error) {
|
|
18
|
+
throw new Error(`Account “${account.label}” was added. Could not start sign-in: ${errorMessage(error)} Try signing in again from its card.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Second and later submits of the add form reuse the account created by the first one,
|
|
24
|
+
* so failed authorization can be retried without creating a duplicate account.
|
|
25
|
+
*/
|
|
26
|
+
export async function addOrResumeLogin(input: { provider: Provider; label: string; mode: LoginMode; created: Account | null }, dependencies: {
|
|
27
|
+
add(input: { provider: Provider; label: string }): Promise<Account>;
|
|
28
|
+
start(input: { accountId: string; mode?: LoginMode }): Promise<LoginSession>;
|
|
29
|
+
onCreated(account: Account): void;
|
|
30
|
+
}): Promise<LoginSession> {
|
|
31
|
+
const { created, ...fresh } = input;
|
|
32
|
+
if (!created) return addAndStartLogin(fresh, dependencies);
|
|
33
|
+
return dependencies.start({ accountId: created.id, ...(created.provider === "codex" ? { mode: input.mode } : {}) });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function accountAvailable(account: Account): boolean {
|
|
37
|
+
return account.authStatus === "ready" && !account.login;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Only act on a live HTTPS link; transport errors must remain visible to the user. */
|
|
41
|
+
export async function performLoginLinkAction(session: LoginSession, action: (url: string) => Promise<void>): Promise<void> {
|
|
42
|
+
if ((session.status !== "waiting" && session.status !== "verifying") || !session.authorizationUrl) {
|
|
43
|
+
throw new Error("This sign-in link is no longer available. Start sign-in again.");
|
|
44
|
+
}
|
|
45
|
+
const url = new URL(session.authorizationUrl);
|
|
46
|
+
if (url.protocol !== "https:" || url.username || url.password) throw new Error("The sign-in link is invalid. Start sign-in again.");
|
|
47
|
+
await action(session.authorizationUrl);
|
|
48
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { PluginButtonIcon, PluginButtonRegistration, PluginClientContext } from "@getpaseo/plugin/client";
|
|
2
|
+
import { listAccounts, listUsage, type AccountState, type UsageSnapshot } from "../shared/contracts";
|
|
3
|
+
import { currentAccount, currentAccountName, errorMessage, supportedProvider, usageSummary } from "./format";
|
|
4
|
+
|
|
5
|
+
// npm installs omit devDependencies, so `@getpaseo/client` types are named through the host SDK entry.
|
|
6
|
+
type PaseoAgent = Awaited<ReturnType<PluginClientContext["paseo"]["agents"]["list"]>>["entries"][number]["agent"];
|
|
7
|
+
|
|
8
|
+
export type PillTarget = Readonly<{ workspaceId: string; agentId: string }>;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One runtime per installation; teardown also guards late bootstrap/RPC results.
|
|
12
|
+
* The action pill selects a modal target. Its stable custom icon hosts the SDK modal,
|
|
13
|
+
* so the picker stays in the composer context without a separate workspace panel.
|
|
14
|
+
*/
|
|
15
|
+
export function createClientRuntime(client: PluginClientContext, icon: PluginButtonIcon) {
|
|
16
|
+
const agents = new Map<string, PaseoAgent>();
|
|
17
|
+
const pills = new Map<string, { workspaceId: string; registration: PluginButtonRegistration }>();
|
|
18
|
+
const listeners = new Set<() => void>();
|
|
19
|
+
const directoryChanges = new Set<string>();
|
|
20
|
+
let state: AccountState | undefined;
|
|
21
|
+
let usage: UsageSnapshot[] = [];
|
|
22
|
+
let directoryError: string | null = null;
|
|
23
|
+
let dataError: string | null = null;
|
|
24
|
+
let stopped = false;
|
|
25
|
+
let loadingDirectory = false;
|
|
26
|
+
let loadingData = false;
|
|
27
|
+
let queuedRefresh = false;
|
|
28
|
+
let modalTarget: PillTarget | null = null;
|
|
29
|
+
const subscriptionId = `account-switcher-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
30
|
+
|
|
31
|
+
function notify() { for (const listener of listeners) listener(); }
|
|
32
|
+
function closeModal(expected: PillTarget) {
|
|
33
|
+
// A late dismissal from an older dialog must not close a newer target,
|
|
34
|
+
// including a later opening for the same agent.
|
|
35
|
+
if (modalTarget !== expected) return;
|
|
36
|
+
modalTarget = null; notify();
|
|
37
|
+
}
|
|
38
|
+
function openModal(target: PillTarget) {
|
|
39
|
+
const agent = agents.get(target.agentId);
|
|
40
|
+
if (stopped || !agent || agent.archivedAt || agent.workspaceId !== target.workspaceId || !supportedProvider(agent.provider)) return;
|
|
41
|
+
if (modalTarget?.agentId === target.agentId && modalTarget.workspaceId === target.workspaceId) return;
|
|
42
|
+
modalTarget = { ...target }; notify();
|
|
43
|
+
}
|
|
44
|
+
function removePill(agentId: string) {
|
|
45
|
+
if (modalTarget?.agentId === agentId) closeModal(modalTarget);
|
|
46
|
+
pills.get(agentId)?.registration.remove(); pills.delete(agentId);
|
|
47
|
+
}
|
|
48
|
+
function updatePill(agent: PaseoAgent) {
|
|
49
|
+
const provider = supportedProvider(agent.provider);
|
|
50
|
+
const existing = pills.get(agent.id);
|
|
51
|
+
if (!provider || !agent.workspaceId || agent.archivedAt) {
|
|
52
|
+
removePill(agent.id); return;
|
|
53
|
+
}
|
|
54
|
+
const current = state ? currentAccount(state, agent.id, provider) : undefined;
|
|
55
|
+
const binding = state?.bindings.find((item) => item.agentId === agent.id);
|
|
56
|
+
const summary = usageSummary(usage.find((item) => item.accountId === current?.id));
|
|
57
|
+
const label = !state ? "Account · loading…" : `${currentAccountName(state, agent.id, provider)} · ${summary}${binding?.pendingAccountId ? " →" : ""}${dataError ? " · error" : ""}`;
|
|
58
|
+
const title = `${label}. Choose an account and view limits`;
|
|
59
|
+
if (existing?.workspaceId === agent.workspaceId) { existing.registration.update({ title, label }); return; }
|
|
60
|
+
removePill(agent.id);
|
|
61
|
+
const target: PillTarget = { workspaceId: agent.workspaceId, agentId: agent.id };
|
|
62
|
+
pills.set(agent.id, { workspaceId: agent.workspaceId, registration: client.addComposerPill({
|
|
63
|
+
id: `account-${agent.id}`, workspaceId: agent.workspaceId, agentId: agent.id,
|
|
64
|
+
button: { title, label, icon, behavior: { kind: "action", onPress: () => openModal(target) } },
|
|
65
|
+
}) });
|
|
66
|
+
}
|
|
67
|
+
function updateAllPills() { for (const agent of agents.values()) updatePill(agent); }
|
|
68
|
+
|
|
69
|
+
const unsubscribe = client.paseo.agents.subscribe((update) => {
|
|
70
|
+
if (stopped) return;
|
|
71
|
+
const id = update.kind === "upsert" ? update.agent.id : update.agentId;
|
|
72
|
+
if (loadingDirectory) directoryChanges.add(id);
|
|
73
|
+
if (update.kind === "upsert") { agents.set(id, update.agent); updatePill(update.agent); }
|
|
74
|
+
else { agents.delete(id); removePill(id); }
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
async function refreshDirectory() {
|
|
78
|
+
if (stopped || loadingDirectory) return;
|
|
79
|
+
loadingDirectory = true;
|
|
80
|
+
directoryChanges.clear();
|
|
81
|
+
try {
|
|
82
|
+
const listed = new Map<string, PaseoAgent>();
|
|
83
|
+
let cursor: string | undefined;
|
|
84
|
+
do {
|
|
85
|
+
const result = await client.paseo.agents.list({ scope: "active", page: { limit: 100, ...(cursor ? { cursor } : {}) }, subscribe: { subscriptionId } });
|
|
86
|
+
if (stopped) return;
|
|
87
|
+
for (const entry of result.entries) listed.set(entry.agent.id, entry.agent);
|
|
88
|
+
const next = result.pageInfo.hasMore ? result.pageInfo.nextCursor ?? undefined : undefined;
|
|
89
|
+
if (next && next === cursor) throw new Error("Could not load the next page of agents.");
|
|
90
|
+
cursor = next;
|
|
91
|
+
} while (cursor);
|
|
92
|
+
for (const [id, agent] of listed) if (!directoryChanges.has(id)) agents.set(id, agent);
|
|
93
|
+
for (const id of agents.keys()) if (!listed.has(id) && !directoryChanges.has(id)) {
|
|
94
|
+
agents.delete(id); removePill(id);
|
|
95
|
+
}
|
|
96
|
+
directoryError = null;
|
|
97
|
+
updateAllPills();
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (!stopped) directoryError = `Could not refresh agent account switchers: ${errorMessage(error)}`;
|
|
100
|
+
} finally { loadingDirectory = false; if (!stopped) notify(); }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function refreshData() {
|
|
104
|
+
if (stopped) return;
|
|
105
|
+
if (loadingData) { queuedRefresh = true; return; }
|
|
106
|
+
loadingData = true;
|
|
107
|
+
try {
|
|
108
|
+
// Read cached usage without renewing the visible-panel lease from a closed pill.
|
|
109
|
+
const results = await Promise.allSettled([client.rpc(listAccounts, {}), client.rpc(listUsage, {})]);
|
|
110
|
+
if (stopped) return;
|
|
111
|
+
const [accountsResult, usageResult] = results;
|
|
112
|
+
if (accountsResult.status === "fulfilled") state = accountsResult.value;
|
|
113
|
+
if (usageResult.status === "fulfilled") usage = usageResult.value.accounts;
|
|
114
|
+
dataError = accountsResult.status === "rejected" ? `Could not refresh accounts: ${errorMessage(accountsResult.reason)}`
|
|
115
|
+
: usageResult.status === "rejected" ? `Could not refresh limits: ${errorMessage(usageResult.reason)}` : null;
|
|
116
|
+
updateAllPills(); notify();
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (!stopped) { dataError = `Could not refresh account switchers: ${errorMessage(error)}`; notify(); }
|
|
119
|
+
} finally {
|
|
120
|
+
loadingData = false;
|
|
121
|
+
if (queuedRefresh && !stopped) { queuedRefresh = false; void refreshData(); }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
void refreshDirectory();
|
|
126
|
+
void refreshData();
|
|
127
|
+
const timer = setInterval(() => { void refreshDirectory(); void refreshData(); }, 30_000);
|
|
128
|
+
return {
|
|
129
|
+
refresh() { void refreshDirectory(); void refreshData(); },
|
|
130
|
+
getError: () => directoryError ?? dataError,
|
|
131
|
+
getModalTarget: () => modalTarget,
|
|
132
|
+
closeModal,
|
|
133
|
+
subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
134
|
+
stop() {
|
|
135
|
+
if (stopped) return;
|
|
136
|
+
stopped = true; clearInterval(timer); unsubscribe();
|
|
137
|
+
if (modalTarget) closeModal(modalTarget);
|
|
138
|
+
listeners.clear();
|
|
139
|
+
for (const { registration } of pills.values()) registration.remove();
|
|
140
|
+
pills.clear(); agents.clear();
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { queryOptions, type QueryClient } from "@tanstack/react-query";
|
|
2
|
+
import type { Account, LoginSession } from "../shared/contracts";
|
|
3
|
+
|
|
4
|
+
export type SignInTarget = { account: Account; hostId: string; sessionId: string; initial?: LoginSession; autoOpen: boolean };
|
|
5
|
+
|
|
6
|
+
export function visibleSignInTarget(target: SignInTarget | null, hostId: string): SignInTarget | null {
|
|
7
|
+
return target?.hostId === hostId ? target : null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** A late cancellation or dismissal belongs to this opening, not a later one. */
|
|
11
|
+
export function closeSignInTarget(current: SignInTarget | null, expected: SignInTarget, hostId: string): SignInTarget | null {
|
|
12
|
+
return current === expected && expected.hostId === hostId ? null : current;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function signInQueryKey(target: SignInTarget) {
|
|
16
|
+
return ["account-switcher", target.hostId, "login", target.account.id, target.sessionId] as const;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function signInPollInterval(status: LoginSession["status"] | undefined, error: unknown, actionPending: boolean): number | false {
|
|
20
|
+
if (actionPending || status === "complete" || status === "error") return false;
|
|
21
|
+
return error ? 5_000 : status === "starting" ? 1_000 : 2_000;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A failed process may still hold its account reservation until cancellation succeeds. */
|
|
25
|
+
export function canCancelSignIn(status: LoginSession["status"] | undefined, account: Account | undefined, sessionId: string): boolean {
|
|
26
|
+
if (status === "complete") return false;
|
|
27
|
+
if (status !== "error") return true;
|
|
28
|
+
return Boolean(account?.login && "sessionId" in account.login && account.login.sessionId === sessionId);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function signInQueryOptions(target: SignInTarget, read: (input: { accountId: string; sessionId: string }) => Promise<LoginSession>, actionPending: boolean) {
|
|
32
|
+
return queryOptions({
|
|
33
|
+
queryKey: signInQueryKey(target),
|
|
34
|
+
queryFn: () => read({ accountId: target.account.id, sessionId: target.sessionId }),
|
|
35
|
+
initialData: target.initial, retry: 1, refetchOnWindowFocus: false, refetchOnReconnect: false,
|
|
36
|
+
refetchInterval: query => signInPollInterval(query.state.data?.status, query.state.error, actionPending),
|
|
37
|
+
gcTime: 0,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Cancel the old poll before submitting, so its delayed reply cannot regress the result. */
|
|
42
|
+
export async function submitSignInCode(cache: QueryClient, target: SignInTarget, submit: () => Promise<LoginSession>): Promise<LoginSession> {
|
|
43
|
+
const queryKey = signInQueryKey(target);
|
|
44
|
+
await cache.cancelQueries({ queryKey, exact: true });
|
|
45
|
+
const result = await submit();
|
|
46
|
+
cache.setQueryData(queryKey, result);
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { useRpc, type PluginSurfaceProps } from "@getpaseo/plugin/client";
|
|
2
|
+
import { copyText, Modal, TextInput } from "@getpaseo/plugin/client/react-native";
|
|
3
|
+
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
4
|
+
import { useEffect, useRef, useState } from "react";
|
|
5
|
+
import { Text, View } from "react-native";
|
|
6
|
+
import { cancelLogin, getLoginStatus, submitLoginCode } from "../shared/contracts";
|
|
7
|
+
import { body, Button, Disclosure, muted, Notice, row, tabular } from "./components";
|
|
8
|
+
import { accountsKey, usageKey, useAccountsData, useAction } from "./data";
|
|
9
|
+
import { errorMessage, providerName } from "./format";
|
|
10
|
+
import { performLoginLinkAction } from "./login";
|
|
11
|
+
import { openExternal, prefersCopiedLink } from "./web";
|
|
12
|
+
import { canCancelSignIn, signInQueryOptions, submitSignInCode, type SignInTarget } from "./sign-in-state";
|
|
13
|
+
|
|
14
|
+
export type { SignInTarget } from "./sign-in-state";
|
|
15
|
+
|
|
16
|
+
export function SignInDialog({ target, theme, host, onChanged, onClose }: PluginSurfaceProps & {
|
|
17
|
+
target: SignInTarget; onChanged(): void; onClose(): void;
|
|
18
|
+
}) {
|
|
19
|
+
const read = useRpc(getLoginStatus);
|
|
20
|
+
const submit = useRpc(submitLoginCode);
|
|
21
|
+
const cancel = useRpc(cancelLogin);
|
|
22
|
+
const cache = useQueryClient();
|
|
23
|
+
const { accounts } = useAccountsData(host.id);
|
|
24
|
+
const action = useAction(host.id, onChanged);
|
|
25
|
+
const session = useQuery(signInQueryOptions(target, read, action.isPending));
|
|
26
|
+
const [code, setCode] = useState("");
|
|
27
|
+
const [notice, setNotice] = useState<string | null>(null);
|
|
28
|
+
const [linkError, setLinkError] = useState<string | null>(null);
|
|
29
|
+
const [showLink, setShowLink] = useState(false);
|
|
30
|
+
const autoOpened = useRef(false);
|
|
31
|
+
const copyFirst = prefersCopiedLink();
|
|
32
|
+
const current = session.data;
|
|
33
|
+
const finished = current?.status === "complete" || current?.status === "error";
|
|
34
|
+
const canCancel = canCancelSignIn(current?.status, accounts.data?.accounts.find(account => account.id === target.account.id), target.sessionId);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (finished) {
|
|
37
|
+
setCode("");
|
|
38
|
+
void cache.invalidateQueries({ queryKey: accountsKey(host.id) });
|
|
39
|
+
void cache.invalidateQueries({ queryKey: usageKey(host.id) });
|
|
40
|
+
onChanged();
|
|
41
|
+
}
|
|
42
|
+
}, [finished, cache, host.id, onChanged]);
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
if (!target.autoOpen || autoOpened.current || session.error || !current?.authorizationUrl || current.status !== "waiting") return;
|
|
45
|
+
autoOpened.current = true;
|
|
46
|
+
void performLoginLinkAction(current, copyFirst ? copyText : openExternal)
|
|
47
|
+
.then(() => { if (copyFirst) setNotice("Sign-in link copied. Open it in your browser."); })
|
|
48
|
+
.catch(error => setLinkError(errorMessage(error)));
|
|
49
|
+
}, [current, target.autoOpen, session.error, copyFirst]);
|
|
50
|
+
const linkAction = (kind: "open" | "copy") => action.run(async () => {
|
|
51
|
+
if (!current) return;
|
|
52
|
+
setNotice(null); setLinkError(null);
|
|
53
|
+
await performLoginLinkAction(current, kind === "open" ? openExternal : copyText);
|
|
54
|
+
if (kind === "copy") setNotice("Sign-in link copied.");
|
|
55
|
+
});
|
|
56
|
+
const submitCode = () => action.run(async () => {
|
|
57
|
+
await submitSignInCode(cache, target, () => submit({ accountId: target.account.id, sessionId: target.sessionId, code: code.trim() }));
|
|
58
|
+
setCode(""); setNotice(null);
|
|
59
|
+
});
|
|
60
|
+
return <Modal title={`Sign in to ${providerName[target.account.provider]}`} open onOpenChange={open => { if (!open) onClose(); }}>
|
|
61
|
+
<Modal.Content contentContainerStyle={{ padding: 16, gap: 12 }} style={{ backgroundColor: theme.colors.surface0 }}>
|
|
62
|
+
<Text style={{ ...body(theme), fontWeight: "600" }}>{target.account.label}</Text>
|
|
63
|
+
{session.isPending || current?.status === "starting" ? <Text style={body(theme)}>Preparing sign-in…</Text> : null}
|
|
64
|
+
{current?.status === "waiting" ? <Text style={body(theme)}>{copyFirst ? "Copy the link and open it in your browser." : "Continue in your browser. If it did not open, use the link below."}</Text> : null}
|
|
65
|
+
{current?.provider === "codex" && current.mode === "browser" && !finished ? <Notice theme={theme}>Using another device? Cancel and choose Device code.</Notice> : null}
|
|
66
|
+
{current?.status === "verifying" ? <Text style={body(theme)}>Checking sign-in…</Text> : null}
|
|
67
|
+
{current?.status === "complete" ? <Notice theme={theme} tone="success">Signed in. Your limits will refresh automatically.</Notice> : null}
|
|
68
|
+
{current?.authorizationUrl && !finished ? <View style={{ gap: 8 }}>
|
|
69
|
+
<View style={row}>
|
|
70
|
+
{!copyFirst ? <Button theme={theme} variant="primary" disabled={action.isPending || Boolean(session.error)} onPress={() => linkAction("open")}>Open browser</Button> : null}
|
|
71
|
+
<Button theme={theme} variant={copyFirst ? "primary" : "secondary"} disabled={action.isPending || Boolean(session.error)} onPress={() => linkAction("copy")}>Copy link</Button>
|
|
72
|
+
</View>
|
|
73
|
+
<Disclosure theme={theme} title="Show sign-in link" open={showLink} onToggle={() => setShowLink(!showLink)}>
|
|
74
|
+
<Text selectable style={{ ...muted(theme), flexShrink: 1 }}>{current.authorizationUrl}</Text>
|
|
75
|
+
</Disclosure>
|
|
76
|
+
</View> : null}
|
|
77
|
+
{current?.userCode && !finished ? <View style={{ gap: 6 }}>
|
|
78
|
+
<Text style={body(theme)}>Enter this code on the sign-in page:</Text>
|
|
79
|
+
<View style={row}>
|
|
80
|
+
<Text selectable style={{ ...body(theme), ...tabular, fontSize: 20, fontWeight: "600" }}>{current.userCode}</Text>
|
|
81
|
+
<Button theme={theme} disabled={action.isPending || Boolean(session.error)} onPress={() => action.run(async () => { await copyText(current.userCode!); setNotice("Code copied."); })}>Copy code</Button>
|
|
82
|
+
</View>
|
|
83
|
+
</View> : null}
|
|
84
|
+
{current?.canSubmitCode && current.status === "waiting" ? <View style={{ gap: 8 }}>
|
|
85
|
+
<Text style={body(theme)}>If the browser gives you an authorization code, paste it here.</Text>
|
|
86
|
+
<TextInput accessibilityLabel="Authorization code" placeholder="Paste authorization code" placeholderTextColor={theme.colors.foregroundMuted}
|
|
87
|
+
value={code} onChangeText={setCode} autoCapitalize="none" autoCorrect={false} secureTextEntry maxLength={2048}
|
|
88
|
+
onSubmitEditing={() => { if (code.trim() && !action.isPending && !session.error) submitCode(); }}
|
|
89
|
+
style={{ ...body(theme), minHeight: 44, padding: 10, borderWidth: 1, borderColor: theme.colors.border, borderRadius: 8, backgroundColor: theme.colors.surface1 }} />
|
|
90
|
+
<Button theme={theme} variant="primary" disabled={!code.trim() || action.isPending || Boolean(session.error)} onPress={submitCode}>Finish sign-in</Button>
|
|
91
|
+
</View> : null}
|
|
92
|
+
{current?.error ? <Notice theme={theme} tone="danger">{current.error}</Notice> : null}
|
|
93
|
+
{session.error ? <View style={{ gap: 8 }}>
|
|
94
|
+
<Notice theme={theme} tone="danger">{errorMessage(session.error)} Retrying status shortly.</Notice>
|
|
95
|
+
<Button theme={theme} disabled={session.isFetching || action.isPending} onPress={() => { void session.refetch(); }}>Retry status</Button>
|
|
96
|
+
</View> : null}
|
|
97
|
+
{linkError ? <Notice theme={theme} tone="danger">{linkError}</Notice> : null}
|
|
98
|
+
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
99
|
+
{notice ? <Notice theme={theme}>{notice}</Notice> : null}
|
|
100
|
+
<View style={row}>
|
|
101
|
+
<Button theme={theme} variant="ghost" onPress={onClose}>{finished ? "Done" : "Close"}</Button>
|
|
102
|
+
{canCancel ? <Button theme={theme} disabled={action.isPending} onPress={() => action.run(async () => {
|
|
103
|
+
await cancel({ accountId: target.account.id, sessionId: target.sessionId }); onClose();
|
|
104
|
+
})}>Cancel sign-in</Button> : null}
|
|
105
|
+
</View>
|
|
106
|
+
</Modal.Content>
|
|
107
|
+
</Modal>;
|
|
108
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { useAgent, usePaseo, useRpc, type PluginHostProps } from "@getpaseo/plugin/client";
|
|
2
|
+
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { useEffect, useMemo } from "react";
|
|
4
|
+
import { Pressable, Text, View } from "react-native";
|
|
5
|
+
import { applySwitch, prepareSwitch, refreshUsage } from "../shared/contracts";
|
|
6
|
+
import { body, Button, heading, InlineAction, muted, Notice, QuotaSummary, row, StatusDot, tabular } from "./components";
|
|
7
|
+
import { useAccountsData, useAction, useNow } from "./data";
|
|
8
|
+
import { currentAccount, currentAccountName, errorMessage, idleForSwitch, providerName, supportedProvider, usageSummary } from "./format";
|
|
9
|
+
import { accountAvailable } from "./login";
|
|
10
|
+
|
|
11
|
+
type SwitcherCallbacks = { onChanged(): void; openAccounts(): void; runtimeError?: string | null };
|
|
12
|
+
/** Modal body: the host's Modal.Content owns padding, vertical scrolling and sheet gestures. */
|
|
13
|
+
export function AgentSwitcher({ theme, host, agentId, onChanged, openAccounts, close, runtimeError }: PluginHostProps & SwitcherCallbacks & {
|
|
14
|
+
agentId: string; close(): void;
|
|
15
|
+
}) {
|
|
16
|
+
const selected = useAgent(agentId, ({ status, provider, attentionReason }) => ({ status, provider, attentionReason }));
|
|
17
|
+
const paseo = usePaseo();
|
|
18
|
+
const cache = useQueryClient();
|
|
19
|
+
const agent = useMemo(() => paseo.agents.ref(agentId), [paseo, agentId]);
|
|
20
|
+
const agentKey = useMemo(() => ["account-switcher", host.id, "agent", agentId] as const, [host.id, agentId]);
|
|
21
|
+
const live = useQuery({ queryKey: agentKey, queryFn: async () => (await agent.refresh())?.agent ?? null, refetchInterval: 5_000, retry: 1 });
|
|
22
|
+
useEffect(() => agent.subscribe((update) => {
|
|
23
|
+
cache.setQueryData(agentKey, update.kind === "upsert" ? update.agent : null);
|
|
24
|
+
}), [agent, cache, agentKey]);
|
|
25
|
+
const { accounts, usage } = useAccountsData(host.id);
|
|
26
|
+
const prepare = useRpc(prepareSwitch);
|
|
27
|
+
const apply = useRpc(applySwitch);
|
|
28
|
+
const refresh = useRpc(refreshUsage);
|
|
29
|
+
const action = useAction(host.id, onChanged);
|
|
30
|
+
const now = useNow();
|
|
31
|
+
const state = accounts.data;
|
|
32
|
+
const provider = supportedProvider(selected?.provider ?? live.data?.provider ?? "");
|
|
33
|
+
const binding = state?.bindings.find((item) => item.agentId === agentId);
|
|
34
|
+
const current = state && provider ? currentAccount(state, agentId, provider) : undefined;
|
|
35
|
+
const unconfirmed = Boolean(binding && binding.currentAccountId === null);
|
|
36
|
+
const pending = state?.accounts.find((account) => account.id === binding?.pendingAccountId);
|
|
37
|
+
const snapshot = usage.data?.accounts.find((item) => item.accountId === current?.id);
|
|
38
|
+
const enabled = state?.integration.enabled ?? false;
|
|
39
|
+
const idle = !live.error && idleForSwitch(live.data) && selected?.status === "idle" && selected.attentionReason !== "permission";
|
|
40
|
+
const switching = binding?.status === "switching";
|
|
41
|
+
const disabled = action.isPending || switching || !enabled;
|
|
42
|
+
const candidates = state?.accounts.filter((account) => account.provider === provider) ?? [];
|
|
43
|
+
const agentState = live.isPending ? { text: "checking agent status", tone: "muted" as const }
|
|
44
|
+
: idle ? { text: "agent idle", tone: "success" as const } : { text: "agent busy · apply after the response", tone: "warning" as const };
|
|
45
|
+
const leave = () => { close(); openAccounts(); };
|
|
46
|
+
return <View style={{ gap: 12, minWidth: 0 }}>
|
|
47
|
+
<View style={{ flexDirection: "row", alignItems: "flex-start", gap: 8 }}>
|
|
48
|
+
<View style={{ flex: 1, minWidth: 0, gap: 1 }}>
|
|
49
|
+
<Text style={muted(theme)}>Agent account{provider ? ` · ${providerName[provider]}` : ""}</Text>
|
|
50
|
+
<Text numberOfLines={1} style={heading(theme)}>{state && provider ? currentAccountName(state, agentId, provider) : accounts.isPending ? "Loading…" : "Unknown"}</Text>
|
|
51
|
+
</View>
|
|
52
|
+
<Button theme={theme} variant="ghost" onPress={leave}>All accounts</Button>
|
|
53
|
+
</View>
|
|
54
|
+
{runtimeError ? <Notice theme={theme} tone="danger">{runtimeError}</Notice> : null}
|
|
55
|
+
{binding?.error ? <Notice theme={theme} tone="danger">{binding.error}</Notice> : null}
|
|
56
|
+
{accounts.error ? <Notice theme={theme} tone="danger">{errorMessage(accounts.error)}</Notice> : null}
|
|
57
|
+
{usage.error ? <Notice theme={theme} tone="danger">{errorMessage(usage.error)}</Notice> : null}
|
|
58
|
+
{live.error ? <Notice theme={theme} tone="danger">Agent status unconfirmed: {errorMessage(live.error)}</Notice> : null}
|
|
59
|
+
{!provider && !live.isPending ? <Notice theme={theme}>Account switching is available for Claude and Codex only.</Notice> : null}
|
|
60
|
+
{state && !enabled ? <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
|
|
61
|
+
<View style={{ flex: 1, minWidth: 0 }}><Notice theme={theme} tone="warning">Account switching is disabled in Accounts.</Notice></View>
|
|
62
|
+
<InlineAction theme={theme} onPress={leave}>Open</InlineAction>
|
|
63
|
+
</View> : null}
|
|
64
|
+
{unconfirmed
|
|
65
|
+
? <Notice theme={theme} tone="warning">Account not confirmed. Choose an account below and apply it when the agent is idle.</Notice>
|
|
66
|
+
: provider ? <QuotaSummary theme={theme} snapshot={snapshot} now={now} compact
|
|
67
|
+
onRefresh={current ? () => action.run(() => refresh({ accountId: current.id })) : undefined} refreshing={action.isPending} /> : null}
|
|
68
|
+
{candidates.length ? <View style={{ gap: 6 }}>
|
|
69
|
+
<Text style={{ ...muted(theme), fontWeight: "600" }}>Switch to</Text>
|
|
70
|
+
{candidates.map((account) => {
|
|
71
|
+
const actual = current?.id === account.id;
|
|
72
|
+
const prepared = pending?.id === account.id;
|
|
73
|
+
const available = accountAvailable(account);
|
|
74
|
+
const blocked = disabled || actual || !available;
|
|
75
|
+
const detail = account.login ? "sign-in in progress · finish in Accounts"
|
|
76
|
+
: !available ? "sign-in required · check in Accounts"
|
|
77
|
+
: usageSummary(usage.data?.accounts.find((item) => item.accountId === account.id), now);
|
|
78
|
+
return <Pressable key={account.id} accessibilityRole="button" accessibilityLabel={`Prepare account ${account.label}`}
|
|
79
|
+
accessibilityState={{ disabled: blocked, selected: prepared }} disabled={blocked}
|
|
80
|
+
onPress={() => action.run(() => prepare({ agentId, accountId: account.id }))}
|
|
81
|
+
style={({ pressed }) => ({ flexDirection: "row", alignItems: "center", gap: 10, minHeight: 44, paddingHorizontal: 10, paddingVertical: 6, borderRadius: 8, borderWidth: 1,
|
|
82
|
+
borderColor: prepared ? theme.colors.accent : theme.colors.border,
|
|
83
|
+
backgroundColor: prepared ? theme.colors.surface2 : theme.colors.surface1, opacity: pressed ? 0.7 : !available ? 0.6 : 1 })}>
|
|
84
|
+
<View style={{ width: 14, height: 14, borderRadius: 7, borderWidth: 1.5, alignItems: "center", justifyContent: "center",
|
|
85
|
+
borderColor: prepared || actual ? theme.colors.accent : theme.colors.foregroundMuted }}>
|
|
86
|
+
{prepared || actual ? <View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: theme.colors.accent, opacity: actual && !prepared ? 0.45 : 1 }} /> : null}
|
|
87
|
+
</View>
|
|
88
|
+
<View style={{ flex: 1, minWidth: 0 }}>
|
|
89
|
+
<Text numberOfLines={1} style={{ ...body(theme), fontWeight: "600" }}>{account.label}</Text>
|
|
90
|
+
<Text numberOfLines={1} style={{ ...muted(theme), ...tabular }}>{detail}</Text>
|
|
91
|
+
</View>
|
|
92
|
+
{actual ? <Text style={muted(theme)}>current</Text> : prepared ? <Text style={{ ...muted(theme), color: theme.colors.foreground, fontWeight: "600" }}>pending</Text> : null}
|
|
93
|
+
</Pressable>;
|
|
94
|
+
})}
|
|
95
|
+
</View> : null}
|
|
96
|
+
{pending ? <View style={{ gap: 8 }}>
|
|
97
|
+
<View style={row}>
|
|
98
|
+
<Button theme={theme} variant="primary" disabled={disabled || !idle || !accountAvailable(pending)} onPress={() => action.run(async () => {
|
|
99
|
+
// Recheck immediately before requesting the daemon's own idle guard.
|
|
100
|
+
const latest = (await agent.refresh())?.agent;
|
|
101
|
+
cache.setQueryData(agentKey, latest ?? null);
|
|
102
|
+
if (!idleForSwitch(latest)) throw new Error("The agent is now busy. Wait for the turn to finish, then apply your selection again.");
|
|
103
|
+
await apply({ agentId });
|
|
104
|
+
})}>{switching || action.isPending ? "Please wait…" : `Apply “${pending.label}”`}</Button>
|
|
105
|
+
<Button theme={theme} variant="ghost" disabled={action.isPending || switching} onPress={() => action.run(() => prepare({ agentId, accountId: null }))}>Cancel selection</Button>
|
|
106
|
+
</View>
|
|
107
|
+
<Text style={muted(theme)}>{pending.login ? "Finish signing in to this account first." : idle ? "The agent session will restart with this account and keep its history." : "Wait for the response and permission requests to finish, then apply."}</Text>
|
|
108
|
+
</View> : null}
|
|
109
|
+
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
|
110
|
+
<StatusDot theme={theme} tone={agentState.tone} />
|
|
111
|
+
<Text style={muted(theme)}>{agentState.text}{action.isPending && !pending ? " · saving selection…" : ""}</Text>
|
|
112
|
+
</View>
|
|
113
|
+
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
114
|
+
</View>;
|
|
115
|
+
}
|
package/client/web.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Linking, Platform } from "react-native";
|
|
2
|
+
|
|
3
|
+
// Keep browser globals inside this platform adapter, as required by the plugin SDK.
|
|
4
|
+
declare const window: { open(url: string, target: string, features: string): unknown };
|
|
5
|
+
declare const navigator: { readonly userAgent: string };
|
|
6
|
+
|
|
7
|
+
/** The desktop renderer has no public SDK API for opening the system browser. */
|
|
8
|
+
export function prefersCopiedLink(): boolean {
|
|
9
|
+
return Platform.OS === "web" && /\bElectron\/\d/i.test(navigator.userAgent);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function openExternal(url: string): Promise<void> {
|
|
13
|
+
if (prefersCopiedLink()) throw new Error("Copy the sign-in link and open it in your browser.");
|
|
14
|
+
if (Platform.OS === "web") {
|
|
15
|
+
window.open(url, "_blank", "noopener,noreferrer");
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
await Linking.openURL(url);
|
|
19
|
+
}
|