@kapybara/zerosub 1.0.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 +152 -0
- package/client/accounts-surface.tsx +592 -0
- package/client/add-account.tsx +351 -0
- package/client/commands.ts +112 -0
- package/client/fork-confirm.tsx +57 -0
- package/client/pills.ts +251 -0
- package/client/reset-confirm.tsx +138 -0
- package/client/settings-screen.tsx +120 -0
- package/client/store.ts +139 -0
- package/client/switch-row.tsx +103 -0
- package/client/ui.tsx +231 -0
- package/index.client.tsx +39 -0
- package/index.server.ts +91 -0
- package/package.json +58 -0
- package/paseo-plugin.json +7 -0
- package/server/adapter.ts +126 -0
- package/server/binaries.ts +63 -0
- package/server/claude-resets.ts +192 -0
- package/server/claude.ts +478 -0
- package/server/codex.ts +459 -0
- package/server/families.ts +78 -0
- package/server/handoff.ts +175 -0
- package/server/homes.ts +352 -0
- package/server/json-file.ts +39 -0
- package/server/limits.ts +213 -0
- package/server/machine.ts +17 -0
- package/server/modes.ts +34 -0
- package/server/paths.ts +37 -0
- package/server/process.ts +66 -0
- package/server/reopen.ts +95 -0
- package/server/routing.ts +131 -0
- package/server/service.ts +1692 -0
- package/server/state.ts +177 -0
- package/server/switch-guard.ts +28 -0
- package/server/usage.ts +68 -0
- package/shared/format.ts +99 -0
- package/shared/model.ts +150 -0
- package/shared/preferences.ts +32 -0
- package/shared/rpc.ts +120 -0
- package/shared/timeline.ts +42 -0
package/client/pills.ts
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
PluginButton,
|
|
3
|
+
PluginButtonMenuEntry,
|
|
4
|
+
PluginButtonRegistration,
|
|
5
|
+
PluginClientContext,
|
|
6
|
+
} from "@getpaseo/plugin/client";
|
|
7
|
+
import { formatPercent, peakUsage, shortLabel } from "../shared/format";
|
|
8
|
+
import { FAMILY_LABEL, type AccountView, type Family, type StateView } from "../shared/model";
|
|
9
|
+
import { setAgentAccount } from "../shared/rpc";
|
|
10
|
+
import { forkPopover } from "./fork-confirm";
|
|
11
|
+
import { resetPopover } from "./reset-confirm";
|
|
12
|
+
import type { ZeroSubStore } from "./store";
|
|
13
|
+
|
|
14
|
+
/** The most agents Paseo returns per page. */
|
|
15
|
+
const PAGE_SIZE = 200;
|
|
16
|
+
const MAX_PAGES = 10;
|
|
17
|
+
|
|
18
|
+
interface TrackedAgent {
|
|
19
|
+
id: string;
|
|
20
|
+
workspaceId: string;
|
|
21
|
+
provider: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* One composer pill per Claude/Codex agent showing the account it runs on. Tapping it opens a menu
|
|
26
|
+
* of that provider's accounts. Pills only appear once a provider has more than one account, so a
|
|
27
|
+
* single-account setup looks exactly like stock Paseo.
|
|
28
|
+
*/
|
|
29
|
+
export function contributePills(client: PluginClientContext, store: ZeroSubStore): () => void {
|
|
30
|
+
const agents = new Map<string, TrackedAgent>();
|
|
31
|
+
const pills = new Map<string, { registration: PluginButtonRegistration; key: string }>();
|
|
32
|
+
const lifetime = new AbortController();
|
|
33
|
+
let stopped = false;
|
|
34
|
+
|
|
35
|
+
function sync(): void {
|
|
36
|
+
if (stopped) return;
|
|
37
|
+
const state = store.current.state;
|
|
38
|
+
for (const [agentId, pill] of pills) {
|
|
39
|
+
if (!agents.has(agentId)) {
|
|
40
|
+
pill.registration.remove();
|
|
41
|
+
pills.delete(agentId);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
for (const agent of agents.values()) {
|
|
45
|
+
const button = state ? buttonFor(client, store, state, agent) : null;
|
|
46
|
+
const existing = pills.get(agent.id);
|
|
47
|
+
if (!button) {
|
|
48
|
+
existing?.registration.remove();
|
|
49
|
+
pills.delete(agent.id);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const key = JSON.stringify([button.label, button.title, button.icon, menuKey(button)]);
|
|
53
|
+
if (existing) {
|
|
54
|
+
if (existing.key !== key) {
|
|
55
|
+
existing.registration.update(button);
|
|
56
|
+
existing.key = key;
|
|
57
|
+
}
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const registration = client.addComposerPill({
|
|
62
|
+
id: "account",
|
|
63
|
+
workspaceId: agent.workspaceId,
|
|
64
|
+
agentId: agent.id,
|
|
65
|
+
button,
|
|
66
|
+
});
|
|
67
|
+
pills.set(agent.id, { registration, key });
|
|
68
|
+
} catch (error) {
|
|
69
|
+
console.warn("[ZeroSub] could not add account pill", error);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const unsubscribeStore = store.subscribe(sync);
|
|
75
|
+
|
|
76
|
+
const track = (agent: { id: string; workspaceId?: string | null; provider: string }) => {
|
|
77
|
+
if (!agent.workspaceId) return;
|
|
78
|
+
agents.set(agent.id, { id: agent.id, workspaceId: agent.workspaceId, provider: agent.provider });
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// The subscription covers the newest page and every later change. Older agents come from the
|
|
82
|
+
// remaining pages, so an agent that has been idle for a while still gets its pill.
|
|
83
|
+
const newestFirst = () => [{ key: "updated_at" as const, direction: "desc" as const }];
|
|
84
|
+
let snapshots = 0;
|
|
85
|
+
async function loadOlder(cursor: string | null, generation: number): Promise<void> {
|
|
86
|
+
for (let page = 1; cursor && page < MAX_PAGES; page += 1) {
|
|
87
|
+
const result = await client.paseo.agents.list({
|
|
88
|
+
signal: lifetime.signal,
|
|
89
|
+
sort: newestFirst(),
|
|
90
|
+
page: { limit: PAGE_SIZE, cursor },
|
|
91
|
+
});
|
|
92
|
+
if (stopped || generation !== snapshots) return;
|
|
93
|
+
for (const { agent } of result.entries) track(agent);
|
|
94
|
+
sync();
|
|
95
|
+
cursor = result.pageInfo.hasMore ? (result.pageInfo.nextCursor ?? null) : null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
void client.paseo.agents
|
|
100
|
+
.list({ subscribe: {}, signal: lifetime.signal, sort: newestFirst(), page: { limit: PAGE_SIZE } })
|
|
101
|
+
.then(({ subscription }) => {
|
|
102
|
+
subscription.subscribe({
|
|
103
|
+
snapshot: ({ entries, pageInfo }) => {
|
|
104
|
+
const generation = ++snapshots;
|
|
105
|
+
agents.clear();
|
|
106
|
+
for (const { agent } of entries) track(agent);
|
|
107
|
+
sync();
|
|
108
|
+
const next = pageInfo.hasMore ? (pageInfo.nextCursor ?? null) : null;
|
|
109
|
+
void loadOlder(next, generation).catch((error: unknown) => {
|
|
110
|
+
if (!stopped) console.warn("[ZeroSub] could not list older agents", error);
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
update: (message) => {
|
|
114
|
+
if (message.type !== "agent_update") return;
|
|
115
|
+
const update = message.payload;
|
|
116
|
+
if (update.kind === "remove") agents.delete(update.agentId);
|
|
117
|
+
else {
|
|
118
|
+
const known = agents.has(update.agent.id);
|
|
119
|
+
track(update.agent);
|
|
120
|
+
// A new agent may have been routed by the daemon a moment ago; fetch its account.
|
|
121
|
+
if (!known) void store.refresh();
|
|
122
|
+
}
|
|
123
|
+
sync();
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
return undefined;
|
|
127
|
+
})
|
|
128
|
+
.catch((error: unknown) => {
|
|
129
|
+
if (!stopped) console.error("[ZeroSub] agent observation failed", error);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
return () => {
|
|
133
|
+
stopped = true;
|
|
134
|
+
lifetime.abort();
|
|
135
|
+
unsubscribeStore();
|
|
136
|
+
for (const pill of pills.values()) pill.registration.remove();
|
|
137
|
+
pills.clear();
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function buttonFor(
|
|
142
|
+
client: PluginClientContext,
|
|
143
|
+
store: ZeroSubStore,
|
|
144
|
+
state: StateView,
|
|
145
|
+
agent: TrackedAgent,
|
|
146
|
+
): PluginButton | null {
|
|
147
|
+
if (!state.showComposerPill) return null;
|
|
148
|
+
const family = state.providers[agent.provider];
|
|
149
|
+
if (!family) return null;
|
|
150
|
+
const accounts = state.accounts.filter((account) => account.family === family);
|
|
151
|
+
const route = state.agents.find((entry) => entry.agentId === agent.id);
|
|
152
|
+
const current =
|
|
153
|
+
accounts.find((account) => account.id === route?.accountId) ??
|
|
154
|
+
accounts.find((account) => account.isDefault) ??
|
|
155
|
+
accounts[0];
|
|
156
|
+
if (!current) return null;
|
|
157
|
+
// A banked reset is worth offering right where the agent stopped, even with a single account.
|
|
158
|
+
const resets = current.usage?.resets ?? null;
|
|
159
|
+
const offerReset = resets !== null && (current.status === "limited" || resets.usableNow);
|
|
160
|
+
// With every account of this provider out, the work can carry on with the other provider.
|
|
161
|
+
const other: Family = family === "claude" ? "codex" : "claude";
|
|
162
|
+
const offerFork =
|
|
163
|
+
current.status === "limited" &&
|
|
164
|
+
accounts.every((account) => account.status === "limited" || account.status === "signed_out") &&
|
|
165
|
+
state.accounts.some((account) => account.family === other && account.status === "ready");
|
|
166
|
+
if (accounts.length < 2 && !(current.status === "limited" && (offerReset || offerFork))) return null;
|
|
167
|
+
|
|
168
|
+
const choose = (accountId: string | null) => async () => {
|
|
169
|
+
await store.rpc(setAgentAccount, { agentId: agent.id, accountId });
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// Codex threads can't change ChatGPT accounts in place; picking one continues in a new agent.
|
|
173
|
+
const movable = route?.movable ?? true;
|
|
174
|
+
const items: PluginButtonMenuEntry[] = accounts.map((account, index) => ({
|
|
175
|
+
kind: "item",
|
|
176
|
+
id: `account-${index}`,
|
|
177
|
+
title: account.id === current.id || movable ? menuTitle(account) : `Continue on ${account.label} (new agent)`,
|
|
178
|
+
icon: account.id === current.id ? "CircleCheck" : movable ? "Circle" : "CopyPlus",
|
|
179
|
+
disabled: account.status === "signed_out" || account.id === current.id,
|
|
180
|
+
behavior: { kind: "action", onPress: choose(account.id) },
|
|
181
|
+
}));
|
|
182
|
+
// When the agent is stuck on a limit, a way out is the most useful thing in the menu.
|
|
183
|
+
const wayOut: PluginButtonMenuEntry[] = [];
|
|
184
|
+
if (offerReset && resets) {
|
|
185
|
+
const entry: PluginButtonMenuEntry = {
|
|
186
|
+
kind: "item",
|
|
187
|
+
id: "use-reset",
|
|
188
|
+
title: `Use a banked reset on ${current.label} (${resets.available} left)…`,
|
|
189
|
+
icon: "TimerReset",
|
|
190
|
+
behavior: { kind: "popover", Content: resetPopover(store, current, agent.id) },
|
|
191
|
+
};
|
|
192
|
+
if (current.status === "limited") wayOut.push(entry);
|
|
193
|
+
else items.push(entry);
|
|
194
|
+
}
|
|
195
|
+
if (offerFork) {
|
|
196
|
+
wayOut.push({
|
|
197
|
+
kind: "item",
|
|
198
|
+
id: "fork-other",
|
|
199
|
+
title: `Continue on ${FAMILY_LABEL[other]} (new agent)…`,
|
|
200
|
+
icon: "GitFork",
|
|
201
|
+
behavior: { kind: "popover", Content: forkPopover(store, agent.id, family, other) },
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
if (wayOut.length > 0) items.unshift(...wayOut, { kind: "separator", id: "way-out-divider" });
|
|
205
|
+
items.push({ kind: "separator", id: "manage-divider" });
|
|
206
|
+
if (route?.pinned && movable) {
|
|
207
|
+
const fallback = accounts.find((account) => account.isDefault);
|
|
208
|
+
items.push({
|
|
209
|
+
kind: "item",
|
|
210
|
+
id: "follow-default",
|
|
211
|
+
title: fallback ? `Follow default (${fallback.label})` : "Follow default",
|
|
212
|
+
icon: "Undo2",
|
|
213
|
+
behavior: { kind: "action", onPress: choose(null) },
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
items.push({
|
|
217
|
+
kind: "item",
|
|
218
|
+
id: "manage",
|
|
219
|
+
title: "Manage accounts…",
|
|
220
|
+
icon: "Users",
|
|
221
|
+
behavior: {
|
|
222
|
+
kind: "action",
|
|
223
|
+
onPress() {
|
|
224
|
+
client.openSurface("accounts");
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const pending = route?.pendingAccountId ? " (after this turn)" : "";
|
|
230
|
+
return {
|
|
231
|
+
title: `Account: ${current.label}${current.email && current.email !== current.label ? ` (${current.email})` : ""}`,
|
|
232
|
+
icon: current.status === "limited" ? "CircleAlert" : "CircleUserRound",
|
|
233
|
+
label: `${shortLabel(current)}${pending}`,
|
|
234
|
+
behavior: { kind: "menu", items },
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function menuTitle(account: AccountView): string {
|
|
239
|
+
if (account.status === "signed_out") return `${account.label} — signed out`;
|
|
240
|
+
if (account.status === "limited") return `${account.label} — limit reached`;
|
|
241
|
+
const peak = account.usage ? peakUsage(account.usage.windows) : null;
|
|
242
|
+
return peak ? `${account.label} — ${formatPercent(peak.usedPercent)} used` : account.label;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function menuKey(button: PluginButton): string {
|
|
246
|
+
return button.behavior.kind === "menu"
|
|
247
|
+
? button.behavior.items
|
|
248
|
+
.map((item) => (item.kind === "item" ? `${item.id}:${item.title}:${String(item.icon)}:${item.disabled}` : item.id))
|
|
249
|
+
.join("|")
|
|
250
|
+
: "";
|
|
251
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { PluginButtonContentProps, PluginHostProps } from "@getpaseo/plugin/client";
|
|
2
|
+
import { useToast } from "@getpaseo/plugin/client/react-native";
|
|
3
|
+
import { useCallback, useState, type ComponentType } from "react";
|
|
4
|
+
import { Text, View } from "react-native";
|
|
5
|
+
import type { AccountView, ResetOffer } from "../shared/model";
|
|
6
|
+
import { redeemReset, type RedeemResult } from "../shared/rpc";
|
|
7
|
+
import { describe, type ZeroSubStore } from "./store";
|
|
8
|
+
import { Button, useText } from "./ui";
|
|
9
|
+
|
|
10
|
+
type Theme = PluginHostProps["theme"];
|
|
11
|
+
|
|
12
|
+
function formatDay(iso: string | null): string | null {
|
|
13
|
+
if (!iso) return null;
|
|
14
|
+
const at = new Date(iso);
|
|
15
|
+
return Number.isNaN(at.getTime()) ? null : at.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function list(items: readonly string[]): string {
|
|
19
|
+
if (items.length <= 1) return items[0] ?? "";
|
|
20
|
+
return `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** "2 left · use by Sep 30". */
|
|
24
|
+
export function resetDetail(resets: ResetOffer): string {
|
|
25
|
+
const until = formatDay(resets.expiresAt);
|
|
26
|
+
return `${resets.available} left${until ? ` · use by ${until}` : ""}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** "1 reset · use by Oct 23". */
|
|
30
|
+
export function resetBadge(resets: ResetOffer): string {
|
|
31
|
+
const until = formatDay(resets.expiresAt);
|
|
32
|
+
return `${resets.available} reset${resets.available === 1 ? "" : "s"}${until ? ` · use by ${until}` : " banked"}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Confirmation for spending a banked reset. A reset is scarce and can't be undone, so the user
|
|
37
|
+
* always confirms it here, whether they came from the account card or an agent's account button.
|
|
38
|
+
*/
|
|
39
|
+
export function ResetConfirm({
|
|
40
|
+
theme,
|
|
41
|
+
store,
|
|
42
|
+
account,
|
|
43
|
+
agentId,
|
|
44
|
+
onFinished,
|
|
45
|
+
onCancel,
|
|
46
|
+
}: {
|
|
47
|
+
theme: Theme;
|
|
48
|
+
store: ZeroSubStore;
|
|
49
|
+
account: AccountView;
|
|
50
|
+
/** The agent stopped by this account's limit; it carries on after the reset. */
|
|
51
|
+
agentId?: string;
|
|
52
|
+
onFinished(result: RedeemResult): void;
|
|
53
|
+
onCancel(): void;
|
|
54
|
+
}) {
|
|
55
|
+
const text = useText(theme);
|
|
56
|
+
const [busy, setBusy] = useState(false);
|
|
57
|
+
const [error, setError] = useState<string | null>(null);
|
|
58
|
+
const resets = account.usage?.resets ?? null;
|
|
59
|
+
|
|
60
|
+
const confirm = useCallback(async () => {
|
|
61
|
+
setBusy(true);
|
|
62
|
+
setError(null);
|
|
63
|
+
try {
|
|
64
|
+
onFinished(await store.rpc(redeemReset, { accountId: account.id, agentId }));
|
|
65
|
+
} catch (failure) {
|
|
66
|
+
setError(describe(failure));
|
|
67
|
+
} finally {
|
|
68
|
+
setBusy(false);
|
|
69
|
+
}
|
|
70
|
+
}, [store, account.id, agentId, onFinished]);
|
|
71
|
+
|
|
72
|
+
if (!resets) {
|
|
73
|
+
return (
|
|
74
|
+
<View style={{ gap: 12 }}>
|
|
75
|
+
<Text style={text.body}>{account.label} has no banked resets right now.</Text>
|
|
76
|
+
<Button theme={theme} label="Close" onPress={onCancel} />
|
|
77
|
+
</View>
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const refills = resets.refills.length > 0 ? `your ${list(resets.refills)} limits` : "your usage limits";
|
|
81
|
+
return (
|
|
82
|
+
<View style={{ gap: 12 }}>
|
|
83
|
+
<Text style={text.body}>
|
|
84
|
+
Refills {refills} on {account.label} now{agentId ? ", then this agent carries on" : ""}. A reset can't be undone.
|
|
85
|
+
</Text>
|
|
86
|
+
<Text style={text.muted}>{resetDetail(resets)}</Text>
|
|
87
|
+
{resets.blockedReason ? <Text style={text.warning}>{resets.blockedReason}</Text> : null}
|
|
88
|
+
{error ? <Text style={text.danger}>{error}</Text> : null}
|
|
89
|
+
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, justifyContent: "flex-end" }}>
|
|
90
|
+
<Button theme={theme} label="No, keep it" onPress={onCancel} disabled={busy} />
|
|
91
|
+
<Button
|
|
92
|
+
theme={theme}
|
|
93
|
+
tone="primary"
|
|
94
|
+
icon="TimerReset"
|
|
95
|
+
label="Yes, use my reset"
|
|
96
|
+
busy={busy}
|
|
97
|
+
disabled={!resets.usableNow}
|
|
98
|
+
onPress={() => void confirm()}
|
|
99
|
+
/>
|
|
100
|
+
</View>
|
|
101
|
+
</View>
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The confirmation as popover content for an agent's account button. */
|
|
106
|
+
export function resetPopover(store: ZeroSubStore, account: AccountView, agentId: string): ComponentType<PluginButtonContentProps> {
|
|
107
|
+
return function ResetPopover({ theme, close }: PluginButtonContentProps) {
|
|
108
|
+
const toast = useToast();
|
|
109
|
+
const text = useText(theme);
|
|
110
|
+
return (
|
|
111
|
+
<View style={{ gap: 12, maxWidth: 360 }}>
|
|
112
|
+
<Text style={text.heading}>Use a banked reset?</Text>
|
|
113
|
+
<ResetConfirm
|
|
114
|
+
theme={theme}
|
|
115
|
+
store={store}
|
|
116
|
+
account={account}
|
|
117
|
+
agentId={agentId}
|
|
118
|
+
onCancel={close}
|
|
119
|
+
onFinished={(result) => {
|
|
120
|
+
close();
|
|
121
|
+
const { message, variant } = redeemToast(account.label, result);
|
|
122
|
+
if (variant === "error") toast.error(message);
|
|
123
|
+
else toast.show(message, { variant, durationMs: 5_000 });
|
|
124
|
+
}}
|
|
125
|
+
/>
|
|
126
|
+
</View>
|
|
127
|
+
);
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Toast wording and tone for a redeem result. */
|
|
132
|
+
export function redeemToast(label: string, result: RedeemResult): { message: string; variant: "success" | "warning" | "error" } {
|
|
133
|
+
if (result.outcome === "reset") {
|
|
134
|
+
return { message: `${label}: ${result.message}${result.continued ? " The agent is carrying on." : ""}`, variant: "success" };
|
|
135
|
+
}
|
|
136
|
+
if (result.outcome === "error") return { message: result.message, variant: "error" };
|
|
137
|
+
return { message: result.message, variant: "warning" };
|
|
138
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { useHosts, useSettings, type PluginSurfaceProps } from "@getpaseo/plugin/client";
|
|
2
|
+
import {
|
|
3
|
+
SettingsAction,
|
|
4
|
+
SettingsCard,
|
|
5
|
+
SettingsInput,
|
|
6
|
+
SettingsSection,
|
|
7
|
+
SettingsSwitch,
|
|
8
|
+
} from "@getpaseo/plugin/client/ui";
|
|
9
|
+
import { useState } from "react";
|
|
10
|
+
import { Text } from "react-native";
|
|
11
|
+
import { DEFAULT_CONTINUE_PROMPT, preferences, type Preferences } from "../shared/preferences";
|
|
12
|
+
|
|
13
|
+
/** Settings → Plugins → zerosub. Accounts themselves live in the sidebar surface. */
|
|
14
|
+
export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurfaceProps & { onOpenAccounts(): void }) {
|
|
15
|
+
const settings = useSettings(preferences);
|
|
16
|
+
const multiHost = useHosts().length > 1;
|
|
17
|
+
const [prompt, setPrompt] = useState<string | null>(null);
|
|
18
|
+
const muted = { color: theme.colors.foregroundMuted };
|
|
19
|
+
if (settings.status === "loading") return <Text style={muted}>Loading…</Text>;
|
|
20
|
+
if (settings.status !== "ready") {
|
|
21
|
+
return (
|
|
22
|
+
<SettingsSection title="Preferences">
|
|
23
|
+
<Text style={{ color: theme.colors.statusDanger }}>{settings.error}</Text>
|
|
24
|
+
<SettingsAction label="Try again" actionLabel="Reload" onPress={() => void settings.reload()} />
|
|
25
|
+
{settings.status === "invalid" ? (
|
|
26
|
+
<SettingsAction label="Restore defaults" actionLabel="Reset" onPress={() => void settings.reset()} />
|
|
27
|
+
) : null}
|
|
28
|
+
</SettingsSection>
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
const save = (patch: Partial<Preferences>) =>
|
|
32
|
+
void settings.save({ ...settings.values, ...patch }, settings.revision);
|
|
33
|
+
return (
|
|
34
|
+
<>
|
|
35
|
+
{multiHost ? (
|
|
36
|
+
<Text style={muted}>These apply to agents on {host.label}. Each host keeps its own accounts and preferences.</Text>
|
|
37
|
+
) : null}
|
|
38
|
+
<SettingsSection title="Accounts">
|
|
39
|
+
<SettingsCard>
|
|
40
|
+
<SettingsAction
|
|
41
|
+
label="Add, remove, and choose default accounts"
|
|
42
|
+
actionLabel="Open accounts"
|
|
43
|
+
onPress={onOpenAccounts}
|
|
44
|
+
/>
|
|
45
|
+
</SettingsCard>
|
|
46
|
+
</SettingsSection>
|
|
47
|
+
<SettingsSection title="Automatic switching">
|
|
48
|
+
<SettingsCard>
|
|
49
|
+
<SettingsSwitch
|
|
50
|
+
label="Switch accounts when one hits its limit"
|
|
51
|
+
hint="The agent moves to the account with the most room left."
|
|
52
|
+
value={settings.values.autoSwitch}
|
|
53
|
+
disabled={settings.saving}
|
|
54
|
+
onValueChange={(autoSwitch) => save({ autoSwitch })}
|
|
55
|
+
/>
|
|
56
|
+
<SettingsSwitch
|
|
57
|
+
label="Keep going after a switch"
|
|
58
|
+
hint="Sends the follow-up below so the interrupted task continues."
|
|
59
|
+
value={settings.values.autoContinue}
|
|
60
|
+
disabled={settings.saving || !settings.values.autoSwitch}
|
|
61
|
+
onValueChange={(autoContinue) => save({ autoContinue })}
|
|
62
|
+
/>
|
|
63
|
+
<SettingsInput
|
|
64
|
+
label="Follow-up message"
|
|
65
|
+
initialValue={settings.values.continuePrompt}
|
|
66
|
+
onChangeText={setPrompt}
|
|
67
|
+
disabled={settings.saving || !settings.values.autoContinue}
|
|
68
|
+
error={settings.saveError}
|
|
69
|
+
/>
|
|
70
|
+
<SettingsAction
|
|
71
|
+
label="Save the follow-up message"
|
|
72
|
+
actionLabel="Save"
|
|
73
|
+
disabled={settings.saving || prompt === null || !prompt.trim()}
|
|
74
|
+
onPress={() => {
|
|
75
|
+
if (prompt?.trim()) save({ continuePrompt: prompt.trim() });
|
|
76
|
+
}}
|
|
77
|
+
/>
|
|
78
|
+
<SettingsAction
|
|
79
|
+
label="Restore the default follow-up"
|
|
80
|
+
actionLabel="Restore"
|
|
81
|
+
disabled={settings.saving || settings.values.continuePrompt === DEFAULT_CONTINUE_PROMPT}
|
|
82
|
+
onPress={() => save({ continuePrompt: DEFAULT_CONTINUE_PROMPT })}
|
|
83
|
+
/>
|
|
84
|
+
</SettingsCard>
|
|
85
|
+
</SettingsSection>
|
|
86
|
+
<SettingsSection title="New agents and composer">
|
|
87
|
+
<SettingsCard>
|
|
88
|
+
<SettingsSwitch
|
|
89
|
+
label="Spread new agents across accounts"
|
|
90
|
+
hint="New agents start on the account with the most room instead of the default."
|
|
91
|
+
value={settings.values.balanceNewAgents}
|
|
92
|
+
disabled={settings.saving}
|
|
93
|
+
onValueChange={(balanceNewAgents) => save({ balanceNewAgents })}
|
|
94
|
+
/>
|
|
95
|
+
<SettingsSwitch
|
|
96
|
+
label="Use banked resets when every account is out"
|
|
97
|
+
hint="Spends one of the account's banked resets instead of stopping. Off unless you turn it on: resets are scarce."
|
|
98
|
+
value={settings.values.autoRedeem}
|
|
99
|
+
disabled={settings.saving || !settings.values.autoSwitch}
|
|
100
|
+
onValueChange={(autoRedeem) => save({ autoRedeem })}
|
|
101
|
+
/>
|
|
102
|
+
<SettingsSwitch
|
|
103
|
+
label="When every account is out, fork the chat to the other provider"
|
|
104
|
+
hint="A stopped Claude chat carries on in a new ChatGPT agent, or the other way round, with the conversation so far and no more permissions than the original. The original stays as it was."
|
|
105
|
+
value={settings.values.forkOtherProvider}
|
|
106
|
+
disabled={settings.saving || !settings.values.autoSwitch}
|
|
107
|
+
onValueChange={(forkOtherProvider) => save({ forkOtherProvider })}
|
|
108
|
+
/>
|
|
109
|
+
<SettingsSwitch
|
|
110
|
+
label="Show the account pill in the composer"
|
|
111
|
+
hint="Appears on Claude and Codex agents once a provider has two or more accounts."
|
|
112
|
+
value={settings.values.showComposerPill}
|
|
113
|
+
disabled={settings.saving}
|
|
114
|
+
onValueChange={(showComposerPill) => save({ showComposerPill })}
|
|
115
|
+
/>
|
|
116
|
+
</SettingsCard>
|
|
117
|
+
</SettingsSection>
|
|
118
|
+
</>
|
|
119
|
+
);
|
|
120
|
+
}
|
package/client/store.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { PluginRpcContract } from "@getpaseo/plugin";
|
|
2
|
+
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
|
3
|
+
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
|
|
4
|
+
import { useSyncExternalStore } from "react";
|
|
5
|
+
import type { StateView } from "../shared/model";
|
|
6
|
+
import { getState } from "../shared/rpc";
|
|
7
|
+
|
|
8
|
+
const IDLE_POLL_MS = 20_000;
|
|
9
|
+
/** While the Accounts screen is open, so usage moves as agents use it. */
|
|
10
|
+
export const VISIBLE_POLL_MS = 4_000;
|
|
11
|
+
const ACTIVE_POLL_MS = 1_500;
|
|
12
|
+
|
|
13
|
+
export interface StoreSnapshot {
|
|
14
|
+
state: StateView | null;
|
|
15
|
+
error: string | null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One poller per installation feeds the surface, composer pills and commands.
|
|
20
|
+
* Polling is cheap: the daemon answers from memory and refreshes usage on its own schedule.
|
|
21
|
+
*/
|
|
22
|
+
export class ZeroSubStore {
|
|
23
|
+
private snapshot: StoreSnapshot = { state: null, error: null };
|
|
24
|
+
private readonly listeners = new Set<() => void>();
|
|
25
|
+
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
26
|
+
private inFlight: Promise<void> | null = null;
|
|
27
|
+
private issued = 0;
|
|
28
|
+
private published = 0;
|
|
29
|
+
private stopped = false;
|
|
30
|
+
/** Poll intervals wanted by open views; the shortest wins. */
|
|
31
|
+
private readonly watchers: number[] = [];
|
|
32
|
+
|
|
33
|
+
constructor(private readonly client: PluginClientContext) {}
|
|
34
|
+
|
|
35
|
+
start(): void {
|
|
36
|
+
void this.refresh();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
stop(): void {
|
|
40
|
+
this.stopped = true;
|
|
41
|
+
if (this.timer) clearTimeout(this.timer);
|
|
42
|
+
this.listeners.clear();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Calls a daemon handler, then refreshes state so every view sees the result. */
|
|
46
|
+
async rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
|
|
47
|
+
contract: PluginRpcContract<InputSchema, OutputSchema>,
|
|
48
|
+
input: ZodInput<InputSchema>,
|
|
49
|
+
): Promise<ZodOutput<OutputSchema>> {
|
|
50
|
+
try {
|
|
51
|
+
return await this.client.rpc(contract, input);
|
|
52
|
+
} finally {
|
|
53
|
+
// A poll already in flight started before this action, so ask again once it lands.
|
|
54
|
+
void this.refresh({ fresh: true });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
get current(): StoreSnapshot {
|
|
59
|
+
return this.snapshot;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
63
|
+
this.listeners.add(listener);
|
|
64
|
+
return () => this.listeners.delete(listener);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
getSnapshot = (): StoreSnapshot => this.snapshot;
|
|
68
|
+
|
|
69
|
+
/** Poll at least this often until the returned function is called. */
|
|
70
|
+
watch(intervalMs: number): () => void {
|
|
71
|
+
this.watchers.push(intervalMs);
|
|
72
|
+
this.schedule();
|
|
73
|
+
let watching = true;
|
|
74
|
+
return () => {
|
|
75
|
+
if (!watching) return;
|
|
76
|
+
watching = false;
|
|
77
|
+
const index = this.watchers.indexOf(intervalMs);
|
|
78
|
+
if (index >= 0) this.watchers.splice(index, 1);
|
|
79
|
+
this.schedule();
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Poll quickly while something (a sign-in flow) is waiting on the daemon. */
|
|
84
|
+
watchClosely(): () => void {
|
|
85
|
+
return this.watch(ACTIVE_POLL_MS);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
refresh(options: { refreshUsage?: boolean; fresh?: boolean } = {}): Promise<void> {
|
|
89
|
+
if (this.inFlight && !options.refreshUsage) {
|
|
90
|
+
if (!options.fresh) return this.inFlight;
|
|
91
|
+
return this.inFlight.then(() => this.refresh({ refreshUsage: options.refreshUsage }));
|
|
92
|
+
}
|
|
93
|
+
const sequence = ++this.issued;
|
|
94
|
+
const run = this.client
|
|
95
|
+
.rpc(getState, { refreshUsage: options.refreshUsage })
|
|
96
|
+
.then((state) => {
|
|
97
|
+
// An older, slower answer must not overwrite a newer one.
|
|
98
|
+
if (sequence >= this.published) {
|
|
99
|
+
this.published = sequence;
|
|
100
|
+
this.publish({ state, error: null });
|
|
101
|
+
}
|
|
102
|
+
})
|
|
103
|
+
.catch((error: unknown) => {
|
|
104
|
+
if (sequence >= this.published) this.publish({ state: this.snapshot.state, error: describe(error) });
|
|
105
|
+
})
|
|
106
|
+
.finally(() => {
|
|
107
|
+
if (this.inFlight === run) this.inFlight = null;
|
|
108
|
+
this.schedule();
|
|
109
|
+
});
|
|
110
|
+
this.inFlight = run;
|
|
111
|
+
return run;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private publish(next: StoreSnapshot): void {
|
|
115
|
+
if (this.stopped) return;
|
|
116
|
+
this.snapshot = next;
|
|
117
|
+
for (const listener of [...this.listeners]) listener();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private schedule(): void {
|
|
121
|
+
if (this.stopped) return;
|
|
122
|
+
if (this.timer) clearTimeout(this.timer);
|
|
123
|
+
const loginActive = this.snapshot.state?.logins.some((login) => isOpen(login.step)) ?? false;
|
|
124
|
+
const delay = Math.min(IDLE_POLL_MS, loginActive ? ACTIVE_POLL_MS : IDLE_POLL_MS, ...this.watchers);
|
|
125
|
+
this.timer = setTimeout(() => void this.refresh(), delay);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function isOpen(step: string): boolean {
|
|
130
|
+
return step === "starting" || step === "waiting" || step === "verifying";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function describe(error: unknown): string {
|
|
134
|
+
return error instanceof Error ? error.message : String(error);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function useStore(store: ZeroSubStore): StoreSnapshot {
|
|
138
|
+
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
|
139
|
+
}
|