@kapybara/zerosub 1.5.0 → 1.18.2

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 +222 -27
  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 +128 -18
  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 +221 -30
  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 -803
  50. package/server/state.ts +305 -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
@@ -0,0 +1,203 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import * as paseoClient from "@getpaseo/plugin/client";
3
+ import * as paseoUi from "@getpaseo/plugin/client/ui";
4
+ import type { ComponentType } from "react";
5
+ import { accountPeak, formatCredits, formatPercent, paceVerdict, pillText } from "../shared/format";
6
+ import { ACCOUNT_METADATA_KEY, AGENT_METADATA_KEY, HAND_OFF, type AccountView, type StateView } from "../shared/model";
7
+ import { moveAgent, useStore, type ZeroSubStore } from "./store";
8
+
9
+ /**
10
+ * Paseo 0.16's composer items, as far as the account control uses them. The plugin SDK this builds
11
+ * against (0.9.1) doesn't list them, and an older app doesn't have them: there the control is left out.
12
+ */
13
+ interface Composer {
14
+ /** `agent`: a running agent. `draft`: a new agent in a workspace. `new-workspace`: the New workspace screen. */
15
+ readonly context: "agent" | "draft" | "new-workspace";
16
+ readonly agent: { readonly provider: string | null; readonly metadata: Readonly<Record<string, unknown>> };
17
+ /** In a composer without an agent, what's set is sent when the agent is created. `null` removes a key. */
18
+ setMetadata(patch: Record<string, string | null>): Promise<void>;
19
+ }
20
+
21
+ interface SelectProps {
22
+ title: string;
23
+ icon: string;
24
+ value: string;
25
+ options: readonly AccountOption[];
26
+ onValueChange(event: { value: string }): void | Promise<void>;
27
+ }
28
+
29
+ interface ComposerItems {
30
+ addComposerItem?(item: { id: string; Component: ComponentType }): () => void;
31
+ }
32
+
33
+ export interface AccountOption {
34
+ value: string;
35
+ label: string;
36
+ description?: string;
37
+ }
38
+
39
+ export interface AccountChoices {
40
+ value: string;
41
+ options: AccountOption[];
42
+ icon: string;
43
+ }
44
+
45
+ /** The option that names no account: the agent starts, or goes back to, where the default sends it. */
46
+ export const FOLLOW = "follow";
47
+ /** The option that opens the Accounts screen. */
48
+ export const MANAGE = "manage";
49
+
50
+ /**
51
+ * What the account control offers in a composer whose agent doesn't exist yet, or null when there's
52
+ * nothing to choose: fewer than two accounts, the account button turned off, a provider ZeroSub
53
+ * doesn't route, or a host whose Paseo keeps no agent metadata to carry the choice in (an app from
54
+ * 0.16 can be talking to an older host, which would then fail to create the agent). Only accounts
55
+ * that can take a new agent are offered, as routing would pass over the others. The first option
56
+ * names none and says where the agent starts then.
57
+ */
58
+ export function accountChoices(state: StateView, provider: string | null, chosen: unknown): AccountChoices | null {
59
+ if (!state.showComposerPill || state.agentMetadata !== true || !provider) return null;
60
+ const family = state.providers[provider];
61
+ if (!family) return null;
62
+ const accounts = state.accounts.filter((account) => account.family === family);
63
+ if (accounts.length < 2) return null;
64
+ const offered = accounts.filter((account) => takesAgents(state, account));
65
+
66
+ // Without a choice: the one-time pick, else (when spreading) the account with the most room, else the default.
67
+ const picked = offered.find((account) => account.nextAgentUntil);
68
+ const usual = picked ?? (state.balanceNewAgents ? undefined : offered.find((account) => account.isDefault));
69
+ const pacedId = state.pacedNext?.[family];
70
+ const pacedLabel = offered.find((account) => account.id === pacedId)?.label;
71
+ // A one-time pick sends the next agent there, whatever pacing would choose.
72
+ const picks = (account: AccountView) => !picked && pacedId === account.id;
73
+ const options: AccountOption[] = [
74
+ usual
75
+ ? { value: FOLLOW, label: usual.label, description: detail(usual, picks(usual), picked ? "Picked for the next new agent" : "Default") }
76
+ : { value: FOLLOW, label: "Automatic", description: pacedLabel ? `Pacing picks ${pacedLabel}` : "The account with the most room" },
77
+ ];
78
+ for (const account of offered) {
79
+ if (account !== usual) options.push({ value: account.id, label: account.label, description: detail(account, picks(account)) });
80
+ }
81
+ // A choice that's no longer offered (the provider changed, or its account can't take agents now) reads as none.
82
+ const value = options.some((option) => option.value === chosen) ? (chosen as string) : FOLLOW;
83
+ return { value, options, icon: "CircleUserRound" };
84
+ }
85
+
86
+ /**
87
+ * What the account control offers for a running agent: the account it's on first (named with the
88
+ * one it's moving from while a move is under way, as on the account button), then the accounts it
89
+ * can move to, going back to the default, and the Accounts screen. Null when the agent isn't routed
90
+ * or its provider has one account. What needs a confirmation, a banked reset or a fork to the other
91
+ * provider, stays with the account button, which shows for it (see pills.ts).
92
+ */
93
+ export function agentChoices(state: StateView, agentId: string): AccountChoices | null {
94
+ if (!state.showComposerPill) return null;
95
+ const route = state.agents.find((entry) => entry.agentId === agentId);
96
+ if (!route || route.inComposer === false) return null;
97
+ const accounts = state.accounts.filter((account) => account.family === route.family);
98
+ const current = accounts.find((account) => account.id === route.accountId);
99
+ if (!current || accounts.length < 2) return null;
100
+ const running = route.pendingAccountId ? state.accounts.find((account) => account.id === route.pendingAccountId) : undefined;
101
+ const { label } = pillText(current, running ?? null, route.waiting ?? (state.canReopen ? "idle" : "restart"));
102
+ // As on the account button: pacing's verdict names the account it picks for the next new agent.
103
+ const next = (account: AccountView) => state.pacedNext?.[account.family] === account.id;
104
+ const options: AccountOption[] = [{ value: current.id, label, description: detail(current, next(current)) }];
105
+ // Codex threads can't change accounts in place and continue in the task's tab for the account;
106
+ // Grok conversations stay on theirs, so the others aren't offered.
107
+ const stays = !route.movable && !HAND_OFF[route.family];
108
+ for (const account of accounts) {
109
+ if (stays || account === current || !takesAgents(state, account)) continue;
110
+ options.push({ value: account.id, label: route.movable ? account.label : `Continue on ${account.label}`, description: detail(account, next(account)) });
111
+ }
112
+ if (route.pinned && route.movable) {
113
+ const fallback = accounts.find((account) => account.isDefault);
114
+ options.push({ value: FOLLOW, label: fallback ? `Follow default (${fallback.label})` : "Follow default" });
115
+ }
116
+ options.push({ value: MANAGE, label: "Manage accounts…" });
117
+ return { value: current.id, options, icon: current.status === "limited" ? "CircleAlert" : "CircleUserRound" };
118
+ }
119
+
120
+ /** As routing takes them: an account at its limit only with automatic switching off. */
121
+ function takesAgents(state: StateView, account: AccountView): boolean {
122
+ return account.status !== "signed_out" && account.status !== "disabled" && !(state.autoSwitch && account.status === "limited");
123
+ }
124
+
125
+ function detail(account: AccountView, next: boolean, lead?: string): string | undefined {
126
+ // A pace and a lead mean a one-time pick: the pick wins over pacing's verdict.
127
+ if (account.pace) return lead ?? paceVerdict(account.pace, next);
128
+ const parts = lead ? [lead] : [];
129
+ if (account.status === "limited") parts.push("Limit reached");
130
+ else {
131
+ // A full window of one model only (Claude's "Weekly · Opus") isn't the account's room.
132
+ const peak = account.usage ? accountPeak(account.usage.windows) : null;
133
+ if (peak) parts.push(`${formatPercent(peak.usedPercent)} used`);
134
+ const credits = account.usage?.credits;
135
+ if (peak && credits) parts.push(formatCredits(credits));
136
+ }
137
+ return parts.length > 0 ? parts.join(" · ") : undefined;
138
+ }
139
+
140
+ /**
141
+ * The Account control, in every composer. Where the agent doesn't exist yet (a new agent's tab, the
142
+ * New workspace screen) the choice travels in the new agent's metadata, and routing starts the
143
+ * agent on it. For a running agent it shows the agent's account and moves the agent, so the account
144
+ * stays in one place once the first message is sent. Paseo says nothing of which agent a composer
145
+ * belongs to but that agent's metadata, so the daemon keeps the agent's ID there (see
146
+ * `AGENT_METADATA_KEY`), and until it's there the control shows nothing.
147
+ *
148
+ * `added` says whether the control is there, for the account button to step back (see pills.ts).
149
+ */
150
+ export function contributeComposerItem(client: PluginClientContext, store: ZeroSubStore): { added: boolean; stop(): void } {
151
+ const none = { added: false, stop() {} };
152
+ const { useComposer } = paseoClient as unknown as { useComposer?: () => Composer };
153
+ const { Select } = paseoUi as unknown as { Select?: ComponentType<SelectProps> };
154
+ const host = client as unknown as ComposerItems;
155
+ if (typeof host.addComposerItem !== "function" || typeof useComposer !== "function" || !Select) return none;
156
+
157
+ const move = (state: StateView, agentId: string, choices: AccountChoices, value: string): void | Promise<void> => {
158
+ if (value === MANAGE) return client.openSurface("accounts");
159
+ if (value === choices.value) return;
160
+ const accountId = value === FOLLOW ? null : value;
161
+ const family = state.agents.find((entry) => entry.agentId === agentId)?.family;
162
+ const to = state.accounts.find((account) => (accountId ? account.id === accountId : account.family === family && account.isDefault));
163
+ return moveAgent(store, agentId, accountId, to?.label ?? "the default account");
164
+ };
165
+
166
+ const AccountItem = () => {
167
+ const composer = useComposer();
168
+ const { state } = useStore(store);
169
+ if (!state) return null;
170
+ if (composer.context === "agent") {
171
+ const agentId = composer.agent.metadata[AGENT_METADATA_KEY];
172
+ const choices = typeof agentId === "string" ? agentChoices(state, agentId) : null;
173
+ if (!choices || typeof agentId !== "string") return null;
174
+ return (
175
+ <Select
176
+ title="Account"
177
+ icon={choices.icon}
178
+ value={choices.value}
179
+ options={choices.options}
180
+ onValueChange={({ value }) => move(state, agentId, choices, value)}
181
+ />
182
+ );
183
+ }
184
+ const choices = accountChoices(state, composer.agent.provider, composer.agent.metadata[ACCOUNT_METADATA_KEY]);
185
+ if (!choices) return null;
186
+ return (
187
+ <Select
188
+ title="Account"
189
+ icon={choices.icon}
190
+ value={choices.value}
191
+ options={choices.options}
192
+ onValueChange={({ value }) => composer.setMetadata({ [ACCOUNT_METADATA_KEY]: value === FOLLOW ? null : value })}
193
+ />
194
+ );
195
+ };
196
+
197
+ try {
198
+ return { added: true, stop: host.addComposerItem({ id: "account", Component: AccountItem }) };
199
+ } catch (error) {
200
+ console.warn("[ZeroSub] could not add the account control to composers", error);
201
+ return none;
202
+ }
203
+ }
@@ -57,3 +57,74 @@ export function forkPopover(store: ZeroSubStore, agentId: string, from: Family,
57
57
  );
58
58
  };
59
59
  }
60
+
61
+ /**
62
+ * Confirmation for carrying a stopped Claude chat on in a new agent on this host's OpenCode, offered
63
+ * on every Claude agent's account button whether or not automatic forking is on. The model and
64
+ * thinking option come from ZeroSub's settings; refusals (say, a saved model that has left the
65
+ * host's catalog) show right here.
66
+ */
67
+ export function openCodeForkPopover(store: ZeroSubStore, agentId: string): ComponentType<PluginButtonContentProps> {
68
+ return function OpenCodeForkPopover({ theme, close }: PluginButtonContentProps) {
69
+ const toast = useToast();
70
+ const text = useText(theme);
71
+ const [busy, setBusy] = useState(false);
72
+ const [error, setError] = useState<string | null>(null);
73
+
74
+ const start = async () => {
75
+ setBusy(true);
76
+ setError(null);
77
+ try {
78
+ const fork = await store.rpc(forkAgent, { agentId, destination: "opencode" });
79
+ close();
80
+ if (fork.delivery === "up-to-date") {
81
+ toast.show("No update was sent: the OpenCode continuation already has everything from this agent.", {
82
+ variant: "default",
83
+ durationMs: 5_000,
84
+ });
85
+ } else if (fork.delivery === "found") {
86
+ toast.show(`Found the existing OpenCode continuation “${fork.title}”. Nothing was sent; open that chat to inspect it.`, {
87
+ variant: "default",
88
+ durationMs: 5_000,
89
+ });
90
+ } else if (fork.delivery === "uncertain") {
91
+ toast.show(`The last handoff to “${fork.title}” couldn't be confirmed. Nothing more was sent; open that chat before retrying. To continue in a new chat instead, archive that one.`, {
92
+ variant: "default",
93
+ durationMs: 5_000,
94
+ });
95
+ } else {
96
+ toast.show(`Continuing on OpenCode in “${fork.title}”`, { variant: "success", durationMs: 5_000 });
97
+ }
98
+ } catch (failure) {
99
+ setError(describe(failure));
100
+ setBusy(false);
101
+ }
102
+ };
103
+
104
+ return (
105
+ <View style={{ gap: 12, maxWidth: 360 }}>
106
+ <Text style={text.heading}>Continue on OpenCode?</Text>
107
+ <Text style={text.body}>
108
+ This starts a new OpenCode agent in this workspace with the conversation so far, using the OpenCode model and
109
+ thinking option picked in ZeroSub's settings. It gets Plan or Build under this host's OpenCode permission
110
+ policy. Build edits files and runs shell without asking, so it can allow more than Claude does. Claude's Auto classifier and
111
+ sandbox rules aren't copied. This agent stays as it is.
112
+ </Text>
113
+ {error ? <Text style={text.danger}>{error}</Text> : null}
114
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, justifyContent: "flex-end" }}>
115
+ <Button theme={theme} label="Not now" tooltip="Close without starting a new agent" tooltipAlign="end" onPress={close} disabled={busy} />
116
+ <Button
117
+ theme={theme}
118
+ tone="primary"
119
+ icon="GitFork"
120
+ label="Continue on OpenCode"
121
+ tooltip="Start a new OpenCode agent with this conversation so far"
122
+ tooltipAlign="end"
123
+ busy={busy}
124
+ onPress={() => void start()}
125
+ />
126
+ </View>
127
+ </View>
128
+ );
129
+ };
130
+ }
@@ -0,0 +1,148 @@
1
+ import { usePaseo } from "@getpaseo/plugin/client";
2
+ import { SettingsRow, SettingsSelect } from "@getpaseo/plugin/client/ui";
3
+ import { useEffect, useState } from "react";
4
+ import { OPENCODE_LABEL, OPENCODE_PROVIDER } from "../shared/model";
5
+ import type { Preferences } from "../shared/preferences";
6
+
7
+ interface CatalogModel {
8
+ id: string;
9
+ label: string;
10
+ isDefault?: boolean;
11
+ thinkingOptions?: Array<{ id: string; label: string; isDefault?: boolean }>;
12
+ }
13
+
14
+ // Paseo 0.16 lists its own "Default" thinking option, which sends no variant: the same as "Model default".
15
+ const pickable = (options: CatalogModel["thinkingOptions"]) => (options ?? []).filter((option) => !(option.isDefault && option.id === "default"));
16
+
17
+ type Catalog =
18
+ | { status: "loading" }
19
+ | { status: "ready"; models: CatalogModel[] }
20
+ | { status: "error"; message: string }
21
+ | { status: "empty" };
22
+
23
+ /** Where a stopped Claude chat continues when the fork option is on. Rendered under the fork toggle. */
24
+ export function ForkDestinationRows({
25
+ values,
26
+ saving,
27
+ onSave,
28
+ }: {
29
+ values: Preferences;
30
+ saving: boolean;
31
+ onSave(patch: Partial<Preferences>): void;
32
+ }) {
33
+ const destinationEnabled = !saving && values.forkOtherProvider && values.autoSwitch;
34
+ return (
35
+ <SettingsSelect
36
+ key="destination"
37
+ label="Fork a stopped Claude chat to"
38
+ hint={
39
+ values.claudeForkDestination === "opencode"
40
+ ? "Applies when every Claude account is out. OpenCode runs this host's permission policy, so Build can edit files and run shell without asking. That can allow more than Claude does."
41
+ : "Applies when every Claude account is out. ChatGPT uses the account with the most room left."
42
+ }
43
+ value={values.claudeForkDestination}
44
+ options={[
45
+ { label: "ChatGPT", value: "codex" },
46
+ { label: OPENCODE_LABEL, value: "opencode" },
47
+ ]}
48
+ disabled={!destinationEnabled}
49
+ onValueChange={(claudeForkDestination) => onSave({ claudeForkDestination })}
50
+ />
51
+ );
52
+ }
53
+
54
+ /**
55
+ * The OpenCode model and thinking option, read from this host's catalog. Always visible and editable:
56
+ * a hand "Continue on OpenCode" uses them in every state, and the automatic fork uses them when its
57
+ * destination is OpenCode.
58
+ */
59
+ export function OpenCodeForkRows({
60
+ values,
61
+ saving,
62
+ onSave,
63
+ }: {
64
+ values: Preferences;
65
+ saving: boolean;
66
+ onSave(patch: Partial<Preferences>): void;
67
+ }) {
68
+ const paseo = usePaseo();
69
+ const [catalog, setCatalog] = useState<Catalog>({ status: "loading" });
70
+ useEffect(() => {
71
+ let live = true;
72
+ paseo.providers
73
+ .listModels(OPENCODE_PROVIDER)
74
+ // A response with no models field and one with an empty list both mean: nothing to pick from.
75
+ .then((result) => {
76
+ if (!live) return;
77
+ if (result.error) setCatalog({ status: "error", message: String(result.error) });
78
+ else setCatalog((result.models ?? []).length > 0 ? { status: "ready", models: result.models ?? [] } : { status: "empty" });
79
+ })
80
+ .catch((error: unknown) => {
81
+ if (live) setCatalog({ status: "error", message: error instanceof Error ? error.message : String(error) });
82
+ });
83
+ return () => {
84
+ live = false;
85
+ };
86
+ }, [paseo]);
87
+
88
+ if (catalog.status !== "ready") {
89
+ const hint =
90
+ catalog.status === "loading"
91
+ ? "Loading this host's OpenCode catalog…"
92
+ : catalog.status === "empty"
93
+ ? "This host's OpenCode reported no models."
94
+ : `Couldn't read this host's OpenCode models: ${catalog.message}`;
95
+ return <SettingsRow label="OpenCode model" hint={hint} />;
96
+ }
97
+
98
+ const hostDefault = catalog.models.find((entry) => entry.isDefault);
99
+ const saved = values.forkOpenCodeModel ? catalog.models.find((entry) => entry.id === values.forkOpenCodeModel) : undefined;
100
+ // The model a fork would use: the saved one, else the one the host marks default. Never a guess.
101
+ const model = values.forkOpenCodeModel ? saved : hostDefault;
102
+ // A "default" saved from Paseo 0.16's own Default option means Model default.
103
+ const thinking = values.forkOpenCodeThinking === "default" ? "" : values.forkOpenCodeThinking;
104
+ const rows = [
105
+ <SettingsSelect
106
+ key="model"
107
+ label="OpenCode model"
108
+ hint={
109
+ values.forkOpenCodeModel && !saved
110
+ ? "That model is no longer in this host's catalog; pick another."
111
+ : !hostDefault && !values.forkOpenCodeModel
112
+ ? "This host marks no OpenCode default; pick a model."
113
+ : "Used by Continue on OpenCode in the account menu, and by the automatic fork when its destination is OpenCode."
114
+ }
115
+ value={values.forkOpenCodeModel}
116
+ options={[
117
+ ...(hostDefault ? [{ label: "Host default", value: "" }] : []),
118
+ ...catalog.models.map((entry) => ({ label: entry.label, value: entry.id })),
119
+ ]}
120
+ disabled={saving}
121
+ onValueChange={(forkOpenCodeModel) => {
122
+ // A thinking option the newly chosen model doesn't offer can't stand.
123
+ const next = forkOpenCodeModel ? catalog.models.find((entry) => entry.id === forkOpenCodeModel) : hostDefault;
124
+ const keep = next?.thinkingOptions?.some((option) => option.id === thinking);
125
+ onSave(keep ? { forkOpenCodeModel } : { forkOpenCodeModel, forkOpenCodeThinking: "" });
126
+ }}
127
+ />,
128
+ <SettingsSelect
129
+ key="thinking"
130
+ label="OpenCode thinking"
131
+ hint={
132
+ !model
133
+ ? "Pick a model above to choose its thinking option."
134
+ : values.forkOpenCodeModel
135
+ ? "How hard the model thinks on the fork. Empty uses the model's default."
136
+ : `How hard the host default, “${model.label}”, thinks on the fork. Empty uses the model's default.`
137
+ }
138
+ value={thinking}
139
+ options={[
140
+ { label: "Model default", value: "" },
141
+ ...pickable(model?.thinkingOptions).map((option) => ({ label: option.label, value: option.id })),
142
+ ]}
143
+ disabled={saving || !model}
144
+ onValueChange={(forkOpenCodeThinking) => onSave({ forkOpenCodeThinking })}
145
+ />,
146
+ ];
147
+ return <>{rows}</>;
148
+ }
@@ -0,0 +1,196 @@
1
+ import type { PluginHostProps } from "@getpaseo/plugin/client";
2
+ import type { ReactNode } from "react";
3
+ import { Text, View } from "react-native";
4
+ import { PACE_GATE_PERCENT, type PaceView } from "../shared/model";
5
+ import { Hint, useText } from "./ui";
6
+
7
+ type Theme = PluginHostProps["theme"];
8
+
9
+ /** A run of text; the bold ones are the numbers, as in the usage rows above. */
10
+ export type Segment = { text: string; bold?: boolean };
11
+
12
+ export interface PaceCopy {
13
+ fiveHour: Segment[];
14
+ pending: string | null;
15
+ /** What the short pending line adds up to, for screen readers. */
16
+ pendingDetail: string | null;
17
+ weekly: Segment[] | null;
18
+ standing: "ahead" | "behind" | "on" | null;
19
+ held: string | null;
20
+ }
21
+
22
+ const r = Math.round;
23
+ const PROJECTION_HINT =
24
+ "Projected up to 1 hour ahead (never past the reset) at this window's average burn rate so far, counted over at least 30 minutes, plus 10% for each agent just placed here.";
25
+ const STANDING_LABEL = { ahead: "ahead of pace", behind: "behind pace", on: "on pace" };
26
+
27
+ /** The words under an account's pacing bars. */
28
+ export function describePace(pace: PaceView): PaceCopy {
29
+ const { fiveHourUsed, fiveHourProjected, pendingFiveHour, weeklyUsed, pendingWeekly, weekElapsed, pending, gated } = pace;
30
+ let standing: PaceCopy["standing"] = null;
31
+ let weekly: Segment[] | null = weeklyUsed === null ? null : [{ text: `${r(weeklyUsed)}%`, bold: true }, { text: " used" }];
32
+ if (weeklyUsed !== null && weekElapsed !== null) {
33
+ const used = r(weeklyUsed + pendingWeekly);
34
+ const gone = r(weekElapsed);
35
+ standing = used > gone ? "ahead" : used < gone ? "behind" : "on";
36
+ weekly = [
37
+ { text: `${r(weeklyUsed)}%`, bold: true },
38
+ { text: " used · " },
39
+ { text: `${r(weekElapsed)}%`, bold: true },
40
+ { text: ` elapsed · ${STANDING_LABEL[standing]}` },
41
+ ];
42
+ }
43
+ return {
44
+ fiveHour:
45
+ fiveHourUsed === null
46
+ ? [{ text: `No 5-hour reading yet. Pacing counts it as ${r(fiveHourProjected)}%.` }]
47
+ : [{ text: `${r(fiveHourUsed)}%`, bold: true }, { text: " now · " }, { text: `${r(fiveHourProjected)}%`, bold: true }, { text: " projected" }],
48
+ pending: pending === 0 ? null : `+${pending} new agent${pending === 1 ? "" : "s"} not in the reading yet`,
49
+ pendingDetail:
50
+ pending === 0
51
+ ? null
52
+ : `Counts ${pending} new agent${pending === 1 ? "" : "s"} the reading doesn't show yet (+${r(pendingFiveHour)}% 5-hour, +${r(pendingWeekly)}% weekly)`,
53
+ weekly,
54
+ standing,
55
+ held: gated
56
+ ? `Pacing holds it back: new agents start on other accounts first while it is projected at or past ${PACE_GATE_PERCENT}% of its 5-hour limit.`
57
+ : null,
58
+ };
59
+ }
60
+
61
+ /** Segments as one Text, bold runs in the foreground color over a muted base, like `UsageBar`. */
62
+ function Segments({ theme, parts }: { theme: Theme; parts: Segment[] }) {
63
+ const colors = theme.colors;
64
+ return (
65
+ <Text style={{ color: colors.foregroundMuted, fontSize: 12 }}>
66
+ {parts.map((part, index) =>
67
+ part.bold ? (
68
+ <Text key={index} style={{ color: colors.foreground, fontWeight: "600" }}>
69
+ {part.text}
70
+ </Text>
71
+ ) : (
72
+ part.text
73
+ ),
74
+ )}
75
+ </Text>
76
+ );
77
+ }
78
+
79
+ /** A thin bar of stacked fills, widest first, with an optional tick. */
80
+ function PaceBar({
81
+ theme,
82
+ color,
83
+ fills,
84
+ tick,
85
+ label,
86
+ now,
87
+ hint,
88
+ }: {
89
+ theme: Theme;
90
+ color: string;
91
+ fills: Array<[percent: number, opacity: number]>;
92
+ tick: number | null;
93
+ label: string;
94
+ now: number;
95
+ hint?: string;
96
+ }) {
97
+ const colors = theme.colors;
98
+ const bar = (
99
+ <View style={{ height: 12, position: "relative" }}>
100
+ <View
101
+ accessibilityRole="progressbar"
102
+ accessibilityLabel={label}
103
+ accessibilityValue={{ min: 0, max: 100, now: Math.round(Math.min(100, now)) }}
104
+ style={{ height: 6, borderRadius: 3, backgroundColor: colors.surface2, overflow: "hidden", marginTop: 3 }}
105
+ >
106
+ {fills.map(([percent, opacity], index) => (
107
+ <View
108
+ key={index}
109
+ style={{ position: "absolute", left: 0, top: 0, height: 6, borderRadius: 3, width: `${Math.min(100, percent)}%`, backgroundColor: color, opacity }}
110
+ />
111
+ ))}
112
+ </View>
113
+ {tick === null ? null : (
114
+ <View style={{ position: "absolute", left: `${tick}%`, top: 0, width: 2, height: 12, marginLeft: -1, backgroundColor: colors.foreground }} />
115
+ )}
116
+ </View>
117
+ );
118
+ return hint ? (
119
+ <Hint theme={theme} text={hint}>
120
+ {bar}
121
+ </Hint>
122
+ ) : (
123
+ bar
124
+ );
125
+ }
126
+
127
+ function PaceRow({ theme, left, right }: { theme: Theme; left: ReactNode; right: ReactNode }) {
128
+ return <View style={{ flexDirection: "row", flexWrap: "wrap", justifyContent: "space-between", columnGap: 8 }}>{left}{right}</View>;
129
+ }
130
+
131
+ /** How pacing reads an account: the 5-hour projection against the gate, the weekly use, and pending agents. */
132
+ export function PaceSection({ theme, pace }: { theme: Theme; pace: PaceView }) {
133
+ const text = useText(theme);
134
+ const colors = theme.colors;
135
+ const copy = describePace(pace);
136
+ const { fiveHourUsed, fiveHourProjected, pendingFiveHour, weeklyUsed, pendingWeekly, weekElapsed } = pace;
137
+ return (
138
+ // Rows sit 10 apart and a label sits 4 over its bar, as in `UsageBar`; each bar's box has 3 spare above and
139
+ // below its 6 px track, so the row gap is 7, the label gap 1, and the closing margin -3.
140
+ <View style={{ gap: 7, marginBottom: copy.held ? 0 : -3 }}>
141
+ <Text style={[text.small, { fontWeight: "600", marginBottom: 4 }]}>Pacing</Text>
142
+ <View style={{ gap: 1 }}>
143
+ <PaceRow
144
+ theme={theme}
145
+ left={<Text style={text.small}>Hourly projection</Text>}
146
+ right={
147
+ <Hint theme={theme} text={PROJECTION_HINT} align="end">
148
+ <View accessible accessibilityLabel={copy.fiveHour.map((part) => part.text).join("")} accessibilityHint={PROJECTION_HINT}>
149
+ <Segments theme={theme} parts={copy.fiveHour} />
150
+ </View>
151
+ </Hint>
152
+ }
153
+ />
154
+ <PaceBar
155
+ theme={theme}
156
+ color={pace.gated ? colors.statusWarning : colors.statusSuccess}
157
+ fills={[
158
+ [fiveHourProjected, 0.2],
159
+ [fiveHourProjected - pendingFiveHour, 0.45],
160
+ [fiveHourUsed ?? 0, 1],
161
+ ]}
162
+ tick={PACE_GATE_PERCENT}
163
+ label={`5-hour use projected an hour ahead, gate ${PACE_GATE_PERCENT}%`}
164
+ hint={`New agents skip an account projected at ${PACE_GATE_PERCENT}% or more of its 5-hour limit`}
165
+ now={fiveHourProjected}
166
+ />
167
+ </View>
168
+ {copy.pending ? (
169
+ <Text accessibilityLabel={copy.pendingDetail ?? undefined} numberOfLines={1} style={text.small}>
170
+ {copy.pending}
171
+ </Text>
172
+ ) : null}
173
+ {copy.weekly && weeklyUsed !== null ? (
174
+ <View style={{ gap: 1 }}>
175
+ <PaceRow
176
+ theme={theme}
177
+ left={<Text style={text.small}>Weekly pace</Text>}
178
+ right={<Segments theme={theme} parts={copy.weekly} />}
179
+ />
180
+ <PaceBar
181
+ theme={theme}
182
+ color={copy.standing === "ahead" ? colors.statusWarning : colors.statusSuccess}
183
+ fills={[
184
+ [weeklyUsed + pendingWeekly, 0.2],
185
+ [weeklyUsed, 1],
186
+ ]}
187
+ tick={weekElapsed}
188
+ label="Weekly use against the week gone"
189
+ now={weeklyUsed + pendingWeekly}
190
+ />
191
+ </View>
192
+ ) : null}
193
+ {copy.held ? <Text style={text.warning}>{copy.held}</Text> : null}
194
+ </View>
195
+ );
196
+ }