@kapybara/zerosub 1.5.1 → 1.18.3

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.
Files changed (56) hide show
  1. package/README.md +220 -26
  2. package/client/accounts-surface.tsx +344 -110
  3. package/client/add-account.tsx +335 -23
  4. package/client/api-account.tsx +250 -0
  5. package/client/azure-account.tsx +311 -0
  6. package/client/commands.ts +44 -8
  7. package/client/composer-item.tsx +203 -0
  8. package/client/fork-confirm.tsx +71 -0
  9. package/client/fork-settings.tsx +148 -0
  10. package/client/pace.tsx +196 -0
  11. package/client/pi-accounts.tsx +571 -0
  12. package/client/pills.ts +63 -25
  13. package/client/reset-confirm.tsx +12 -3
  14. package/client/settings-screen.tsx +48 -9
  15. package/client/store.ts +148 -19
  16. package/client/switch-row.tsx +28 -8
  17. package/client/ui.tsx +11 -0
  18. package/index.client.tsx +4 -1
  19. package/index.server.ts +53 -10
  20. package/package.json +5 -2
  21. package/server/account-identity.ts +11 -0
  22. package/server/adapter.ts +115 -8
  23. package/server/api-usage.ts +144 -0
  24. package/server/azure.ts +346 -0
  25. package/server/binaries.ts +41 -3
  26. package/server/claude.ts +276 -21
  27. package/server/codex-same-conversation.ts +71 -0
  28. package/server/codex.ts +35 -7
  29. package/server/continuations.ts +67 -17
  30. package/server/cursor.ts +222 -0
  31. package/server/families.ts +105 -8
  32. package/server/grok.ts +225 -0
  33. package/server/handoff.ts +211 -29
  34. package/server/homes.ts +1263 -35
  35. package/server/json-file.ts +39 -8
  36. package/server/launchers.ts +319 -0
  37. package/server/limits.ts +80 -3
  38. package/server/main-proxy.ts +238 -0
  39. package/server/modes.ts +20 -4
  40. package/server/paths.ts +81 -1
  41. package/server/pi.ts +528 -0
  42. package/server/placement.ts +133 -0
  43. package/server/process.ts +18 -1
  44. package/server/processes.ts +66 -0
  45. package/server/provider-env.ts +28 -0
  46. package/server/proxy.ts +282 -0
  47. package/server/reopen.ts +50 -8
  48. package/server/routing.ts +337 -30
  49. package/server/service.ts +4320 -805
  50. package/server/state.ts +303 -24
  51. package/server/usage.ts +2 -0
  52. package/shared/format.ts +170 -2
  53. package/shared/model.ts +339 -2
  54. package/shared/preferences.ts +22 -1
  55. package/shared/rpc.ts +130 -8
  56. package/shared/timeline.ts +11 -0
package/client/pills.ts CHANGED
@@ -4,12 +4,11 @@ import type {
4
4
  PluginButtonRegistration,
5
5
  PluginClientContext,
6
6
  } from "@getpaseo/plugin/client";
7
- import { formatCredits, 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";
7
+ import { accountPeak, formatCredits, formatPercent, paceVerdict, pillText } from "../shared/format";
8
+ import { FAMILY_LABEL, HAND_OFF, OTHER_FAMILY, type AccountView, type StateView } from "../shared/model";
9
+ import { forkPopover, openCodeForkPopover } from "./fork-confirm";
11
10
  import { resetPopover } from "./reset-confirm";
12
- import type { ZeroSubStore } from "./store";
11
+ import { moveAgent, type ZeroSubStore } from "./store";
13
12
 
14
13
  /** The most agents Paseo returns per page. */
15
14
  const PAGE_SIZE = 200;
@@ -24,9 +23,10 @@ interface TrackedAgent {
24
23
  /**
25
24
  * One composer pill per Claude/Codex agent showing the account it runs on. Tapping it opens a menu
26
25
  * 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.
26
+ * single-account setup looks exactly like stock Paseo. With `inComposer`, the Account control in
27
+ * the composer shows the account instead, and a pill appears only to offer a way out of a limit.
28
28
  */
29
- export function contributePills(client: PluginClientContext, store: ZeroSubStore): () => void {
29
+ export function contributePills(client: PluginClientContext, store: ZeroSubStore, inComposer = false): () => void {
30
30
  const agents = new Map<string, TrackedAgent>();
31
31
  const pills = new Map<string, { registration: PluginButtonRegistration; key: string }>();
32
32
  const lifetime = new AbortController();
@@ -42,7 +42,7 @@ export function contributePills(client: PluginClientContext, store: ZeroSubStore
42
42
  }
43
43
  }
44
44
  for (const agent of agents.values()) {
45
- const button = state ? buttonFor(client, store, state, agent) : null;
45
+ const button = state ? buttonFor(client, store, state, agent, inComposer) : null;
46
46
  const existing = pills.get(agent.id);
47
47
  if (!button) {
48
48
  existing?.registration.remove();
@@ -143,6 +143,7 @@ function buttonFor(
143
143
  store: ZeroSubStore,
144
144
  state: StateView,
145
145
  agent: TrackedAgent,
146
+ inComposer: boolean,
146
147
  ): PluginButton | null {
147
148
  if (!state.showComposerPill) return null;
148
149
  const family = state.providers[agent.provider];
@@ -157,27 +158,44 @@ function buttonFor(
157
158
  // A banked reset is worth offering right where the agent stopped, even with a single account.
158
159
  const resets = current.usage?.resets ?? null;
159
160
  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";
161
+ // With every account of this provider out, the work can carry on with the other provider (Pi has none).
162
+ const other = OTHER_FAMILY[family];
162
163
  const offerFork =
164
+ other !== null &&
163
165
  current.status === "limited" &&
164
166
  accounts.every((account) => account.status === "limited" || account.status === "signed_out" || account.status === "disabled") &&
165
167
  state.accounts.some((account) => account.family === other && account.status === "ready");
166
- if (accounts.length < 2 && !(current.status === "limited" && (offerReset || offerFork))) return null;
168
+ // OpenCode is a harness, not an account: any Claude agent can continue there by hand, however its
169
+ // accounts are doing and whether or not automatic forking is on, once this host has OpenCode. Even a
170
+ // single ready account gets the pill for that entry; Codex still only shows a pill with two accounts or a way out of a limit.
171
+ const offerOpenCode = family === "claude" && state.openCodeAvailable;
172
+ if (accounts.length < 2 && !(offerOpenCode || (current.status === "limited" && (offerReset || offerFork)))) return null;
173
+ // Where the composer has the Account control (see composer-item.tsx), the account stays there for
174
+ // a running agent too. The button is then only for what a control can't offer, each needing a
175
+ // confirmation: continuing on OpenCode, or the way out of a limit. Or it stands in for an agent
176
+ // the control can't show for.
177
+ if (inComposer && state.agentMetadata && route?.inComposer !== false && !(offerOpenCode || (current.status === "limited" && (offerReset || offerFork)))) return null;
167
178
 
168
- const choose = (accountId: string | null) => async () => {
169
- await store.rpc(setAgentAccount, { agentId: agent.id, accountId });
170
- };
179
+ // Paseo shows what an action throws: here, that the agent couldn't be reloaded.
180
+ const choose = (accountId: string | null, to: string) => () => moveAgent(store, agent.id, accountId, to);
171
181
 
172
182
  // Codex threads can't change accounts in place; continue in this task's tab for that account.
173
183
  const movable = route?.movable ?? true;
184
+ // Grok conversations stay on their account: the others are listed, not offered.
185
+ const stays = !movable && !HAND_OFF[family];
174
186
  const items: PluginButtonMenuEntry[] = accounts.map((account, index) => ({
175
187
  kind: "item",
176
188
  id: `account-${index}`,
177
- title: account.id === current.id || movable ? menuTitle(account) : `Continue on ${account.label}`,
178
- icon: account.id === current.id ? "CircleCheck" : movable ? "Circle" : "ArrowRightLeft",
179
- disabled: account.status === "signed_out" || account.status === "disabled" || account.id === current.id,
180
- behavior: { kind: "action", onPress: choose(account.id) },
189
+ title: account.id === current.id || movable || stays ? menuTitle(state, account) : `Continue on ${account.label}`,
190
+ icon: account.id === current.id ? "CircleCheck" : movable || stays ? "Circle" : "ArrowRightLeft",
191
+ // With automatic switching on, an account at its limit would only pass the agent on (the server refuses it too).
192
+ disabled:
193
+ stays ||
194
+ account.status === "signed_out" ||
195
+ account.status === "disabled" ||
196
+ (state.autoSwitch && account.status === "limited") ||
197
+ account.id === current.id,
198
+ behavior: { kind: "action", onPress: choose(account.id, account.label) },
181
199
  }));
182
200
  // When the agent is stuck on a limit, a way out is the most useful thing in the menu.
183
201
  const wayOut: PluginButtonMenuEntry[] = [];
@@ -192,7 +210,7 @@ function buttonFor(
192
210
  if (current.status === "limited") wayOut.push(entry);
193
211
  else items.push(entry);
194
212
  }
195
- if (offerFork) {
213
+ if (offerFork && other) {
196
214
  wayOut.push({
197
215
  kind: "item",
198
216
  id: "fork-other",
@@ -202,6 +220,15 @@ function buttonFor(
202
220
  });
203
221
  }
204
222
  if (wayOut.length > 0) items.unshift(...wayOut, { kind: "separator", id: "way-out-divider" });
223
+ if (offerOpenCode) {
224
+ items.push({
225
+ kind: "item",
226
+ id: "fork-opencode",
227
+ title: "Continue on OpenCode (new agent)…",
228
+ icon: "Bot",
229
+ behavior: { kind: "popover", Content: openCodeForkPopover(store, agent.id) },
230
+ });
231
+ }
205
232
  if (route?.selectionReason === "weekly_reset") {
206
233
  items.push({
207
234
  kind: "item", id: "selection-reason",
@@ -209,6 +236,13 @@ function buttonFor(
209
236
  icon: "Info", disabled: true, behavior: { kind: "action", onPress() {} },
210
237
  });
211
238
  }
239
+ if (stays) {
240
+ items.push({
241
+ kind: "item", id: "stays",
242
+ title: `${FAMILY_LABEL[family]} conversations stay on their account; new agents follow your pick`,
243
+ icon: "Info", disabled: true, behavior: { kind: "action", onPress() {} },
244
+ });
245
+ }
212
246
  items.push({ kind: "separator", id: "manage-divider" });
213
247
  if (route?.pinned && movable) {
214
248
  const fallback = accounts.find((account) => account.isDefault);
@@ -217,7 +251,7 @@ function buttonFor(
217
251
  id: "follow-default",
218
252
  title: fallback ? `Follow default (${fallback.label})` : "Follow default",
219
253
  icon: "Undo2",
220
- behavior: { kind: "action", onPress: choose(null) },
254
+ behavior: { kind: "action", onPress: choose(null, fallback?.label ?? "the default account") },
221
255
  });
222
256
  }
223
257
  items.push({
@@ -233,20 +267,24 @@ function buttonFor(
233
267
  },
234
268
  });
235
269
 
236
- const pending = route?.pendingAccountId ? " (after this turn)" : "";
270
+ const running = route?.pendingAccountId ? state.accounts.find((account) => account.id === route.pendingAccountId) : undefined;
237
271
  return {
238
- title: `Account: ${current.label}${current.email && current.email !== current.label ? ` (${current.email})` : ""}`,
272
+ ...pillText(current, running ?? null, route?.waiting ?? (state.canReopen ? "idle" : "restart")),
239
273
  icon: current.status === "limited" ? "CircleAlert" : "CircleUserRound",
240
- label: `${shortLabel(current)}${pending}`,
241
274
  behavior: { kind: "menu", items },
242
275
  };
243
276
  }
244
277
 
245
- function menuTitle(account: AccountView): string {
278
+ function menuTitle(state: StateView, account: AccountView): string {
246
279
  if (account.status === "signed_out") return `${account.label} — signed out`;
247
280
  if (account.status === "disabled") return `${account.label} — disabled`;
248
281
  if (account.status === "limited") return `${account.label} — limit reached`;
249
- const peak = account.usage ? peakUsage(account.usage.windows) : null;
282
+ if (account.pace) {
283
+ const verdict = paceVerdict(account.pace, state.pacedNext?.[account.family] === account.id);
284
+ return `${account.label} — ${verdict.charAt(0).toLowerCase()}${verdict.slice(1)}`;
285
+ }
286
+ // A full window of one model only (Claude's "Weekly · Opus") isn't the account's room.
287
+ const peak = account.usage ? accountPeak(account.usage.windows) : null;
250
288
  if (!peak) return account.label;
251
289
  const credits = account.usage?.credits;
252
290
  return `${account.label} — ${formatPercent(peak.usedPercent)} used${credits ? ` · ${formatCredits(credits)}` : ""}`;
@@ -4,7 +4,7 @@ import { useCallback, useState, type ComponentType } from "react";
4
4
  import { Text, View } from "react-native";
5
5
  import type { AccountView, ResetOffer } from "../shared/model";
6
6
  import { redeemReset, type RedeemResult } from "../shared/rpc";
7
- import { describe, type ZeroSubStore } from "./store";
7
+ import { describe, stoppedWaiting, type ZeroSubStore } from "./store";
8
8
  import { Button, useText } from "./ui";
9
9
 
10
10
  type Theme = PluginHostProps["theme"];
@@ -63,7 +63,15 @@ export function ResetConfirm({
63
63
  try {
64
64
  onFinished(await store.rpc(redeemReset, { accountId: account.id, agentId }));
65
65
  } catch (failure) {
66
- setError(describe(failure));
66
+ // The daemon carries on with the reset; using another now could spend a second one.
67
+ if (stoppedWaiting(failure)) {
68
+ onFinished({
69
+ outcome: "pending",
70
+ message: `Still using the reset on ${account.label}. Its limits show on its card once it's done; don't use another.`,
71
+ left: null,
72
+ continued: false,
73
+ });
74
+ } else setError(describe(failure));
67
75
  } finally {
68
76
  setBusy(false);
69
77
  }
@@ -131,10 +139,11 @@ export function resetPopover(store: ZeroSubStore, account: AccountView, agentId:
131
139
  }
132
140
 
133
141
  /** Toast wording and tone for a redeem result. */
134
- export function redeemToast(label: string, result: RedeemResult): { message: string; variant: "success" | "warning" | "error" } {
142
+ export function redeemToast(label: string, result: RedeemResult): { message: string; variant: "success" | "info" | "warning" | "error" } {
135
143
  if (result.outcome === "reset") {
136
144
  return { message: `${label}: ${result.message}${result.continued ? " The agent is carrying on." : ""}`, variant: "success" };
137
145
  }
138
146
  if (result.outcome === "error") return { message: result.message, variant: "error" };
147
+ if (result.outcome === "pending") return { message: result.message, variant: "info" };
139
148
  return { message: result.message, variant: "warning" };
140
149
  }
@@ -9,12 +9,19 @@ import {
9
9
  import { useState } from "react";
10
10
  import { Text } from "react-native";
11
11
  import { DEFAULT_CONTINUE_PROMPT, preferences, type Preferences } from "../shared/preferences";
12
+ import { ForkDestinationRows, OpenCodeForkRows } from "./fork-settings";
12
13
 
13
14
  /** Settings → Plugins → zerosub. Accounts themselves live in the sidebar surface. */
14
15
  export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurfaceProps & { onOpenAccounts(): void }) {
15
16
  const settings = useSettings(preferences);
16
17
  const multiHost = useHosts().length > 1;
17
- const [prompt, setPrompt] = useState<string | null>(null);
18
+ // What's typed into the follow-up box, over which saved message. The box only takes its text when
19
+ // it's made, so it's made again once the saved one changes (restored, say, or on another device).
20
+ const [draft, setDraft] = useState<{ over: string; text: string } | null>(null);
21
+ // Whether the last save was the follow-up's: its box says why that failed, the top any other.
22
+ const [savedPrompt, setSavedPrompt] = useState(false);
23
+ // The box goes while the settings can't be shown (a refresh failed, say), and what's typed with it.
24
+ if (settings.status !== "ready" && draft) setDraft(null);
18
25
  const muted = { color: theme.colors.foregroundMuted };
19
26
  if (settings.status === "loading") return <Text style={muted}>Loading…</Text>;
20
27
  if (settings.status !== "ready") {
@@ -23,15 +30,26 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
23
30
  <Text style={{ color: theme.colors.statusDanger }}>{settings.error}</Text>
24
31
  <SettingsAction label="Try again" actionLabel="Reload" onPress={() => void settings.reload()} />
25
32
  {settings.status === "invalid" ? (
26
- <SettingsAction label="Restore defaults" actionLabel="Reset" onPress={() => void settings.reset()} />
33
+ <>
34
+ <SettingsAction label="Restore defaults" actionLabel="Reset" onPress={() => void settings.reset()} />
35
+ {settings.saveError ? <Text style={{ color: theme.colors.statusDanger }}>{settings.saveError}</Text> : null}
36
+ </>
27
37
  ) : null}
28
38
  </SettingsSection>
29
39
  );
30
40
  }
31
- const save = (patch: Partial<Preferences>) =>
41
+ const save = (patch: Partial<Preferences>) => {
42
+ setSavedPrompt("continuePrompt" in patch);
32
43
  void settings.save({ ...settings.values, ...patch }, settings.revision);
44
+ };
45
+ const saved = settings.values.continuePrompt;
46
+ // Typed into a box made for an earlier saved message: it went with that box, even should the saved
47
+ // message come back to what it was (restored after a save, say).
48
+ if (draft && draft.over !== saved) setDraft(null);
49
+ const typed = draft?.over === saved ? draft.text.trim() : "";
33
50
  return (
34
51
  <>
52
+ {settings.saveError && !savedPrompt ? <Text style={{ color: theme.colors.statusDanger }}>{settings.saveError}</Text> : null}
35
53
  {multiHost ? (
36
54
  <Text style={muted}>These apply to agents on {host.label}. Each host keeps its own accounts and preferences.</Text>
37
55
  ) : null}
@@ -68,18 +86,19 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
68
86
  onValueChange={(autoContinue) => save({ autoContinue })}
69
87
  />
70
88
  <SettingsInput
89
+ key={saved}
71
90
  label="Follow-up message"
72
- initialValue={settings.values.continuePrompt}
73
- onChangeText={setPrompt}
91
+ initialValue={saved}
92
+ onChangeText={(text) => setDraft({ over: saved, text })}
74
93
  disabled={settings.saving || !settings.values.autoContinue}
75
- error={settings.saveError}
94
+ error={savedPrompt ? settings.saveError : null}
76
95
  />
77
96
  <SettingsAction
78
97
  label="Save the follow-up message"
79
98
  actionLabel="Save"
80
- disabled={settings.saving || prompt === null || !prompt.trim()}
99
+ disabled={settings.saving || !typed || typed === saved}
81
100
  onPress={() => {
82
- if (prompt?.trim()) save({ continuePrompt: prompt.trim() });
101
+ if (typed && typed !== saved) save({ continuePrompt: typed });
83
102
  }}
84
103
  />
85
104
  <SettingsAction
@@ -113,13 +132,28 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
113
132
  disabled={settings.saving}
114
133
  onValueChange={(useCredits) => save({ useCredits })}
115
134
  />
135
+ <SettingsSwitch
136
+ label="Use paid API accounts when every subscription is out"
137
+ hint="Off unless you turn it on. When every ChatGPT subscription account is at its limit, signed out or disabled, agents may move to an Azure OpenAI account, billed per token (after a banked reset, if those are used automatically). Off, it's used only as the default or when you pick it for an agent."
138
+ value={settings.values.paidApiFallback}
139
+ disabled={settings.saving}
140
+ onValueChange={(paidApiFallback) => save({ paidApiFallback })}
141
+ />
116
142
  <SettingsSwitch
117
143
  label="When every account is out, fork the chat to the other provider"
118
- 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."
144
+ hint="A stopped Claude chat carries on in a new ChatGPT or OpenCode agent (pick the destination below) with the conversation so far. ChatGPT gets a mode no looser than this agent's. OpenCode gets Plan or Build under the host's own permission policy, which can allow more than Claude does. The original stays as it was."
119
145
  value={settings.values.forkOtherProvider}
120
146
  disabled={settings.saving || !settings.values.autoSwitch}
121
147
  onValueChange={(forkOtherProvider) => save({ forkOtherProvider })}
122
148
  />
149
+ <ForkDestinationRows values={settings.values} saving={settings.saving} onSave={save} />
150
+ <SettingsSwitch
151
+ label="Keep a Codex chat in the same conversation"
152
+ hint="Off unless you turn it on. Two ChatGPT accounts in one workspace reload this agent on the other account instead of opening a new tab. A different workspace, an email-only account, or a workspace that is out of credits still opens a new tab. If the first turn cannot resume the thread, this agent goes back and the new tab opens."
153
+ value={settings.values.codexSameConversation}
154
+ disabled={settings.saving || !settings.values.autoSwitch}
155
+ onValueChange={(codexSameConversation) => save({ codexSameConversation })}
156
+ />
123
157
  <SettingsSwitch
124
158
  label="Show the account pill in the composer"
125
159
  hint="Appears on Claude and Codex agents once a provider has two or more accounts."
@@ -129,6 +163,11 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
129
163
  />
130
164
  </SettingsCard>
131
165
  </SettingsSection>
166
+ <SettingsSection title="Continue on OpenCode">
167
+ <SettingsCard>
168
+ <OpenCodeForkRows values={settings.values} saving={settings.saving} onSave={save} />
169
+ </SettingsCard>
170
+ </SettingsSection>
132
171
  </>
133
172
  );
134
173
  }
package/client/store.ts CHANGED
@@ -2,8 +2,9 @@ import type { PluginRpcContract } from "@getpaseo/plugin";
2
2
  import type { PluginClientContext } from "@getpaseo/plugin/client";
3
3
  import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
4
4
  import { useSyncExternalStore } from "react";
5
+ import { moveProblem } from "../shared/format";
5
6
  import type { StateView } from "../shared/model";
6
- import { getState } from "../shared/rpc";
7
+ import { getState, setAgentAccount } from "../shared/rpc";
7
8
 
8
9
  const IDLE_POLL_MS = 20_000;
9
10
  /** While the Accounts screen is open, so usage moves as agents use it. */
@@ -13,6 +14,8 @@ const ACTIVE_POLL_MS = 1_500;
13
14
  export interface StoreSnapshot {
14
15
  state: StateView | null;
15
16
  error: string | null;
17
+ /** When `state` arrived (ms since the epoch), so a view can say how old it is while refreshes fail. */
18
+ updatedAt: number | null;
16
19
  }
17
20
 
18
21
  /**
@@ -31,6 +34,7 @@ export interface ZeroSubStore {
31
34
  getSnapshot(): StoreSnapshot;
32
35
  watch(intervalMs: number): () => void;
33
36
  watchClosely(): () => void;
37
+ /** `refreshUsage` reads every account's usage first. */
34
38
  refresh(options?: { refreshUsage?: boolean; fresh?: boolean }): Promise<void>;
35
39
  }
36
40
 
@@ -39,10 +43,16 @@ export interface ZeroSubStore {
39
43
  * large enough to be compiled lazily, so a class silently becomes undefined and `new` throws reading `.prototype`.
40
44
  */
41
45
  export function createZeroSubStore(client: PluginClientContext): ZeroSubStore {
42
- let snapshot: StoreSnapshot = { state: null, error: null };
46
+ let snapshot: StoreSnapshot = { state: null, error: null, updatedAt: null };
43
47
  const listeners = new Set<() => void>();
44
48
  let timer: ReturnType<typeof setTimeout> | null = null;
49
+ /** The plain state query under way; polls and the refresh after an action share it. */
45
50
  let inFlight: Promise<void> | null = null;
51
+ /**
52
+ * An explicit usage refresh under way. The daemon can take a while over one (it may renew sign-ins),
53
+ * so it runs beside the plain queries instead of holding them (and every action waiting on one) up.
54
+ */
55
+ let usageInFlight: Promise<void> | null = null;
46
56
  let issued = 0;
47
57
  let published = 0;
48
58
  let stopped = false;
@@ -99,29 +109,52 @@ export function createZeroSubStore(client: PluginClientContext): ZeroSubStore {
99
109
  }
100
110
 
101
111
  function refresh(options: { refreshUsage?: boolean; fresh?: boolean } = {}): Promise<void> {
102
- if (inFlight && !options.refreshUsage) {
112
+ if (options.refreshUsage) return refreshUsage();
113
+ if (inFlight) {
103
114
  if (!options.fresh) return inFlight;
104
- return inFlight.then(() => refresh({ refreshUsage: options.refreshUsage }));
115
+ return inFlight.then(() => refresh());
105
116
  }
117
+ const run = query(false).then(() => undefined);
118
+ inFlight = run;
119
+ void run.finally(() => {
120
+ if (inFlight === run) inFlight = null;
121
+ });
122
+ return run;
123
+ }
124
+
125
+ /** Asks the daemon to read every account's usage now, then shows the result. */
126
+ function refreshUsage(): Promise<void> {
127
+ if (usageInFlight) return usageInFlight;
128
+ const run = query(true).then((shown) => {
129
+ // A poll that started while usage was being read answered first, maybe with older readings.
130
+ // The daemon has the new ones now, so ask once more rather than leave them unshown.
131
+ if (!shown) return refresh({ fresh: true });
132
+ return undefined;
133
+ });
134
+ usageInFlight = run;
135
+ void run.finally(() => {
136
+ if (usageInFlight === run) usageInFlight = null;
137
+ });
138
+ return run;
139
+ }
140
+
141
+ /** One state query. Resolves to whether its answer was shown: an older, slower answer never replaces a newer one. */
142
+ function query(withUsage: boolean): Promise<boolean> {
106
143
  const sequence = ++issued;
107
- const run = client
108
- .rpc(getState, { refreshUsage: options.refreshUsage })
144
+ return client
145
+ .rpc(getState, { refreshUsage: withUsage ? true : undefined })
109
146
  .then((state) => {
110
- // An older, slower answer must not overwrite a newer one.
111
- if (sequence >= published) {
112
- published = sequence;
113
- publish({ state, error: null });
114
- }
147
+ if (sequence < published) return false;
148
+ published = sequence;
149
+ publish({ state, error: null, updatedAt: Date.now() });
150
+ return true;
115
151
  })
116
152
  .catch((error: unknown) => {
117
- if (sequence >= published) publish({ state: snapshot.state, error: describe(error) });
153
+ if (sequence < published) return false;
154
+ publish({ ...snapshot, error: describe(error) });
155
+ return true;
118
156
  })
119
- .finally(() => {
120
- if (inFlight === run) inFlight = null;
121
- schedule();
122
- });
123
- inFlight = run;
124
- return run;
157
+ .finally(schedule);
125
158
  }
126
159
 
127
160
  function publish(next: StoreSnapshot): void {
@@ -157,8 +190,104 @@ function isOpen(step: string): boolean {
157
190
  return step === "starting" || step === "waiting" || step === "verifying";
158
191
  }
159
192
 
193
+ /** An error in words for the user. Paseo checks RPC input against its schema first, and Zod's error is a JSON list. */
160
194
  export function describe(error: unknown): string {
161
- return error instanceof Error ? error.message : String(error);
195
+ const issues = zodIssues(error);
196
+ if (issues) return issues.map(describeIssue).join(" ");
197
+ return messageOf(error);
198
+ }
199
+
200
+ /**
201
+ * An error's message without what Paseo wraps a plugin handler's error in: `Request failed: `
202
+ * before it, ` requestType=… code=…` after.
203
+ */
204
+ function messageOf(error: unknown): string {
205
+ const message = error instanceof Error ? error.message : String(error);
206
+ const unwrapped = message.replace(/\s+requestType=\S+(?:\s+code=\S+)?\s*$/, "").replace(/^Request failed: /, "");
207
+ return unwrapped.trim() ? unwrapped : message;
208
+ }
209
+
210
+ /** Field names as the forms show them. */
211
+ const FIELD_NAMES: Record<string, string> = {
212
+ label: "Name",
213
+ key: "Key",
214
+ baseUrl: "Base URL",
215
+ proxy: "Proxy",
216
+ code: "Code",
217
+ };
218
+
219
+ /** What Zod 3 and 4 put in an issue, as far as wording it goes. */
220
+ interface Issue {
221
+ code?: string;
222
+ path: unknown[];
223
+ message: string;
224
+ /** Zod 4. */
225
+ origin?: string;
226
+ /** Zod 3. */
227
+ type?: string;
228
+ maximum?: number | bigint;
229
+ minimum?: number | bigint;
230
+ }
231
+
232
+ /** Zod's issues, from the error itself or from its message, the form they keep once they've crossed an RPC. */
233
+ function zodIssues(error: unknown): Issue[] | null {
234
+ const own = typeof error === "object" && error !== null ? (error as { issues?: unknown }).issues : undefined;
235
+ if (isIssueList(own)) return own;
236
+ const message = error instanceof Error || typeof error === "string" ? messageOf(error) : null;
237
+ if (!message?.trimStart().startsWith("[")) return null;
238
+ try {
239
+ const parsed: unknown = JSON.parse(message);
240
+ return isIssueList(parsed) ? parsed : null;
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+
246
+ function isIssueList(value: unknown): value is Issue[] {
247
+ return (
248
+ Array.isArray(value) &&
249
+ value.length > 0 &&
250
+ value.every(
251
+ (issue: unknown) =>
252
+ typeof issue === "object" &&
253
+ issue !== null &&
254
+ typeof (issue as Issue).message === "string" &&
255
+ Array.isArray((issue as Issue).path),
256
+ )
257
+ );
258
+ }
259
+
260
+ function describeIssue(issue: Issue): string {
261
+ const key = issue.path.at(-1);
262
+ const field = typeof key === "string" ? (FIELD_NAMES[key] ?? key) : null;
263
+ if (field && (issue.origin ?? issue.type) === "string") {
264
+ if (issue.code === "too_big" && issue.maximum !== undefined) return `${field} can be at most ${issue.maximum} characters.`;
265
+ if (issue.code === "too_small" && Number(issue.minimum) <= 1) return `${field} can't be empty.`;
266
+ if (issue.code === "too_small" && issue.minimum !== undefined) return `${field} needs at least ${issue.minimum} characters.`;
267
+ }
268
+ return field ? `${field}: ${issue.message}` : issue.message;
269
+ }
270
+
271
+ /**
272
+ * Paseo stopped waiting for the daemon's answer. The plugin doesn't stop with it, so what was asked
273
+ * for may still be under way, or done: say that rather than that it failed.
274
+ */
275
+ export function stoppedWaiting(error: unknown): boolean {
276
+ return /Plugin RPC timed out|Timeout waiting for message/i.test(describe(error));
277
+ }
278
+
279
+ /**
280
+ * Moves an agent to an account (`null`: back to following the default), for its account button
281
+ * and its Account control. Throws what Paseo should show: that the agent couldn't be reloaded, say.
282
+ */
283
+ export async function moveAgent(store: ZeroSubStore, agentId: string, accountId: string | null, to: string): Promise<void> {
284
+ const summary = await store.rpc(setAgentAccount, { agentId, accountId }).catch((error: unknown) => {
285
+ // The move goes on without Paseo waiting for it, and the account shows it under way.
286
+ if (stoppedWaiting(error)) return null;
287
+ throw error;
288
+ });
289
+ const problem = summary && moveProblem(summary, to);
290
+ if (problem) throw new Error(problem);
162
291
  }
163
292
 
164
293
  export function useStore(store: ZeroSubStore): StoreSnapshot {
@@ -21,24 +21,39 @@ function cause(row: SwitchRow): string | null {
21
21
  return `${row.to} is enabled again.`;
22
22
  case "default":
23
23
  return "The default account changed.";
24
+ case "pacing":
25
+ return `${from} is close to its 5-hour limit.`;
24
26
  default:
25
27
  return null;
26
28
  }
27
29
  }
28
30
 
29
- /** The work went on in a new agent on the other provider (Claude ↔ ChatGPT). */
31
+ /** The work went on in a new agent on the other provider (Claude ↔ ChatGPT), or on OpenCode. */
30
32
  function isFork(row: SwitchRow): boolean {
31
- return row.toFamily !== null && row.toFamily !== row.family;
33
+ return row.toProvider !== null || (row.toFamily !== null && row.toFamily !== row.family);
32
34
  }
33
35
 
34
36
  export function describeRow(row: SwitchRow): string {
35
- if (isFork(row) && row.toFamily && row.continuedIn) {
37
+ if (isFork(row) && row.continuedIn) {
38
+ const title = row.continuedIn.title;
39
+ const detail = row.detail ? ` ${row.detail}` : "";
40
+ if (row.delivery === "up-to-date") {
41
+ return `The work is already up to date in “${title}” on ${row.to}; ZeroSub sent nothing new.${detail}`;
42
+ }
43
+ if (row.delivery === "found") {
44
+ return `ZeroSub found the existing OpenCode continuation “${title}” but couldn't tell what it has received. Nothing was sent; open that chat to check it against the latest instructions.${detail}`;
45
+ }
46
+ if (row.delivery === "uncertain") {
47
+ return `ZeroSub couldn't confirm its last handoff to “${title}”. Nothing more was sent; open that chat before retrying.${detail}`;
48
+ }
36
49
  const reset = formatResetIn(row.resetsAt);
37
50
  const lead =
38
51
  row.reason === "exhausted"
39
52
  ? `Every ${FAMILY_LABEL[row.family]} account is at its limit${reset ? ` (${row.from ?? "this one"} resets ${reset})` : ""}, so the work`
40
53
  : "The work";
41
- return `${lead} continues on ${FAMILY_LABEL[row.toFamily]} in a new agent: “${row.continuedIn.title}” (${row.to}).`;
54
+ const destination = row.toProvider ? row.to : (row.toFamily ? FAMILY_LABEL[row.toFamily] : row.to);
55
+ // A fork to the other provider moved to an account; an OpenCode fork has none to name.
56
+ return `${lead} continues on ${destination} in a new agent: “${title}”${row.toProvider ? "." : ` (${row.to}).`}${detail}`;
42
57
  }
43
58
  if (row.reason === "exhausted") {
44
59
  const reset = formatResetIn(row.resetsAt);
@@ -55,17 +70,22 @@ export function describeRow(row: SwitchRow): string {
55
70
  const lead = why ? `${why} ` : "";
56
71
  switch (row.outcome) {
57
72
  case "continued":
73
+ if (row.continuedIn && row.detail) {
74
+ return `${lead}${row.detail} This task continues in “${row.continuedIn.title}” on ${row.to}.`;
75
+ }
58
76
  return row.continuedIn
59
77
  ? `${lead}ChatGPT conversations can't change accounts, so this task continues in “${row.continuedIn.title}” on ${row.to}.`
60
78
  : `${lead}Continuing on ${row.to}.`;
61
79
  case "stayed":
62
80
  return `${lead}This conversation stays on ${row.from ?? "its account"}.${row.detail ? ` ${row.detail}` : ""}`;
63
81
  case "pending":
64
- return `${lead}Moves to ${row.to} when its session next starts.`;
82
+ return `${lead}Moves to ${row.to} when its session next starts.${row.detail ? ` ${row.detail}` : ""}`;
65
83
  default: {
66
- const from =
67
- row.from && row.reason !== "limit" && row.reason !== "signed_out" && row.reason !== "disabled" ? `from ${row.from} ` : "";
68
- return `${lead}Switched ${from}to ${row.to}${row.continued ? " and carried on" : ""}.`;
84
+ const hidesFrom =
85
+ row.reason === "limit" || row.reason === "signed_out" || row.reason === "disabled" || row.reason === "pacing";
86
+ const from = row.from && !hidesFrom ? `from ${row.from} ` : "";
87
+ const place = row.sameConversation ? " in this conversation" : "";
88
+ return `${lead}Switched ${from}to ${row.to}${place}${row.continued ? " and carried on" : ""}.`;
69
89
  }
70
90
  }
71
91
  }
package/client/ui.tsx CHANGED
@@ -78,6 +78,17 @@ function TooltipBubble({
78
78
  );
79
79
  }
80
80
 
81
+ /** A hover tip over any content (a long press shows it on touch), for what a bar can't say. */
82
+ export function Hint({ theme, text, align = "center", children }: { theme: Theme; text: string; align?: TooltipAlign; children: ReactNode }) {
83
+ const tip = useTooltip(text);
84
+ return (
85
+ <Pressable accessible={false} {...tip.handlers} style={{ position: "relative", zIndex: tip.visible ? 1000 : undefined }}>
86
+ {children}
87
+ {tip.visible ? <TooltipBubble theme={theme} text={text} placement="top" align={align} /> : null}
88
+ </Pressable>
89
+ );
90
+ }
91
+
81
92
  export function Button({
82
93
  theme,
83
94
  label,