ccdeck 3.80.0 → 3.81.1

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 (48) hide show
  1. package/README.md +23 -4
  2. package/bin/cli/tui.js +433 -11
  3. package/dist/web/assets/{BrowserWatchModal-Bfvo_8H6.js → BrowserWatchModal-BcvsD8Np.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-GS5jIQ_J.js → IntegrationModal-BMtv2XWR.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Bxd2ElWb.js → RadioPanel-k65VVqTb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-FgHBI2Oh.js → TrafficRadar-BNw0skS3.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-APwKtE2J.js → UsageHistoryModal-CYxrrwCl.js} +1 -1
  8. package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
  9. package/dist/web/assets/{app-BzHVsgB2.js → app-DCoamBD4.js} +93 -93
  10. package/dist/web/assets/{index-7whwMaPX.js → index-BMX8nr4f.js} +1 -1
  11. package/dist/web/index.html +3 -3
  12. package/package.json +1 -1
  13. package/release-notes.json +62 -0
  14. package/src/server/account-notify.mjs +81 -16
  15. package/src/server/account-routes.mjs +20 -2
  16. package/src/server/account-watch.mjs +21 -0
  17. package/src/server/codex-auto.mjs +157 -37
  18. package/src/server/codex-lan-identity.mjs +61 -0
  19. package/src/server/codex-live-engine.mjs +28 -2
  20. package/src/server/codex-live-rpc.mjs +4 -1
  21. package/src/server/codex-profiles.mjs +34 -4
  22. package/src/server/codex-projects.mjs +308 -0
  23. package/src/server/codex-selection.mjs +17 -2
  24. package/src/server/codex-share.mjs +74 -12
  25. package/src/server/codex-terminal.mjs +1 -1
  26. package/src/server/codex-usage.mjs +69 -0
  27. package/src/server/codex-windows-private.mjs +2 -0
  28. package/src/server/codex-windows-private.ps1 +48 -1
  29. package/src/server/index.mjs +6 -4
  30. package/src/server/lan-codex-store.mjs +173 -0
  31. package/src/server/lan-codex.mjs +103 -0
  32. package/src/server/lan-copies.mjs +1 -1
  33. package/src/server/lan-deck.mjs +5 -0
  34. package/src/server/lan-engine.mjs +34 -6
  35. package/src/server/lan-manifest.mjs +16 -2
  36. package/src/server/lan-serve.mjs +21 -6
  37. package/src/server/lifecycle.mjs +2 -2
  38. package/src/server/npm-upgrade.mjs +17 -6
  39. package/src/server/pinned-build.mjs +3 -0
  40. package/src/server/request-gates.mjs +3 -0
  41. package/src/server/self-update.mjs +2 -72
  42. package/src/server/terminal-cli.mjs +8 -2
  43. package/src/server/tui-codex.mjs +229 -0
  44. package/src/server/tui-lan.mjs +684 -0
  45. package/src/server/tui-machine.mjs +492 -0
  46. package/src/server/tui-network.mjs +730 -0
  47. package/src/server/tui-view.mjs +735 -60
  48. package/src/server/version-order.mjs +74 -0
package/README.md CHANGED
@@ -75,11 +75,11 @@ The deck opens on these eight pictures the first time it runs — they are the w
75
75
  </tr>
76
76
  <tr>
77
77
  <td><img src="assets/guide/welcome-5.svg" width="440" alt="Cores, memory and heat while the agents run, and what is hogging them."></td>
78
- <td><img src="assets/guide/welcome-6.svg" width="440" alt="Several Claude accounts: switch, add one, share one to another machine."></td>
78
+ <td><img src="assets/guide/welcome-6.svg" width="440" alt="Several Claude and Codex accounts: switch, add one, share one to another machine."></td>
79
79
  </tr>
80
80
  <tr>
81
81
  <td align="center"><sub>Cores, memory and heat while the agents run, and what is hogging them.</sub></td>
82
- <td align="center"><sub>Several Claude accounts: switch, add one, share one to another machine.</sub></td>
82
+ <td align="center"><sub>Several Claude and Codex accounts: switch, add one, share one to another machine.</sub></td>
83
83
  </tr>
84
84
  <tr>
85
85
  <td><img src="assets/guide/welcome-7.svg" width="440" alt="Your machines repair each other's expired logins over the local network."></td>
@@ -370,6 +370,9 @@ For plain `codex` commands to use this default, click **Enable terminal selectio
370
370
 
371
371
  **Share Codex accounts** exports selected ChatGPT logins stored in `auth.json` as a code you can paste into **Import Codex accounts** on another machine, including Windows. Import creates separate profiles, keeps the current default and existing logins, and skips an exact repeated import. It transfers the login only, without configuration or conversation history. The code contains live credentials: it is encoded, not encrypted, and has no automatic expiry or ccdeck revocation. Use a trusted private channel and delete clipboard/message copies afterward. Both machines share the OAuth renewal token; renewing on one can invalidate the other copy and require signing in again. Keyring-only logins and API keys cannot be shared.
372
372
 
373
+ On Windows, Share reports when the profile's permissions prevent export. **Secure permissions and share** is an explicit, optional repair: it gives only your Windows user access to the selected Codex folders and `auth.json`, changes inherited access for their contents, and keeps the login, settings and selected account in place. Close programs holding the login file if Windows refuses the change, and run ccdeck without administrator rights. Automatic network sync never changes folder permissions. After preparation, a paired deck can receive the selected shared login on its next round.
374
+
375
+
373
376
  **An already-open Codex app or IDE:** on macOS, Linux and Windows with Codex 0.166.0 or newer, **Use account** can also update the existing native shared app-server through its local control socket. Every conversation using that daemon changes together, including conversations opened before ccdeck. Their IDs, history and settings remain in place. Windows uses Codex's own `app-server proxy` to reach its AF_UNIX socket; run Codex and ccdeck as your normal Windows user. Existing unsafe permissions are rejected rather than changed.
374
377
 
375
378
  For conversations that accept direct input, ccdeck waits for observed tools and approvals, pauses responses through the native interrupt API, verifies the new login, then submits one Continue in each paused conversation. Supported subagents move with their parent: parents pause first, then the same child conversations resume before their parents. A naturally finished response stays idle.
@@ -517,10 +520,14 @@ ccdeck switch pick from a list (arrows, Enter; Esc cancels)
517
520
  ccdeck usage the active account's limits, every lane
518
521
  ccdeck sessions what each session is doing, the ones waiting on you first
519
522
  ccdeck open the deck in your browser — over SSH, the line that opens it on yours
520
- ccdeck tui all of the above on one screen that stays up
523
+ ccdeck tui all of the above, and the machine, on one screen that stays up
521
524
  ```
522
525
 
523
- **`ccdeck tui`** keeps the accounts and the sessions waiting on you on one full screen, read again every few seconds. Move with the arrows (or `j` / `k`, or a slot's number), **Enter** switches to the selected account, **b** selects the one Auto-switch would pick, **a** turns Auto-switch on or off, **r** reads the usage again, **?** lists the keys and **q** leaves with your terminal as it was. With no deck running it reads claude-swap's store and **d** starts one in the background. It fits from 40×12 up, sets the selected account's detail beside the waiting sessions from 120 columns, follows `NO_COLOR`, and draws in ASCII on a console that cannot show its lines.
526
+ **`ccdeck tui`** keeps the accounts, the sessions waiting on you and the machine on one full screen, read again every few seconds. Move with the arrows (or `j` / `k`, or a slot's number), **Enter** switches to the selected account, **b** selects the one Auto-switch would pick, **a** turns Auto-switch on or off, **r** reads the usage again, **?** lists the keys and **q** leaves with your terminal as it was. **m** opens the selected account's actions, as in the deck's account menu: set or clear home (⌂), hold out of Auto-switch's rotation (‖) or put back, rename, move to another slot, and remove, which asks first; **h**, **o**, **n**, **v** and **x** reach them straight from the list. While nobody is waiting on you, the room goes to the machine's charts: all cores and the busiest one, memory, swap, queued work, temperature and throttling, live, or the last hours by the minute with **t**. With no deck running it reads claude-swap's store and **d** starts one in the background. It fits from 40×12 up, sets the selected account's detail beside the waiting sessions from 120 columns, follows `NO_COLOR`, and draws in ASCII on a console that cannot show its lines.
527
+
528
+ **Codex accounts**: once the deck has one, the title reads **Claude | Codex** and **c** (or ← →) turns the list to the other side. There **Enter** makes the selected account Codex's default, **a** turns Codex Auto-switch on or off, and **m** offers sign in again, rename, set or clear home (⌂), hold out of rotation and remove, for accounts added in the deck. **+**, or **Enter** on a signed-out account, shows a sign-in link and a code: open the link in any browser, a phone included, type the code there, and the sign-in finishes by itself.
529
+
530
+ **Local network**: **l** opens the deck's Local network on its own tab, with what the panel in the browser has. **Space** turns sync with paired decks on or off, picks which accounts paired decks get, and sets the sharing, pairing and Tailscale switches. On a deck, **Enter** accepts one that asks to pair, checks a paired one now, or lets a declined one ask again; **n** names it and **x** declines, unpairs (it asks first) or stops dialling an address. **n** on this deck's own line renames it. **+** adds a deck by its address or with an invite: make one to paste on the other deck, or paste the one it made. **r** checks every paired deck now. A deck that asks to pair while you are on the accounts is said there too, and **l** goes back to them.
524
531
 
525
532
  **Adding an account over SSH**: **+** signs one in, and **Enter** on an account whose login has expired signs it in again, keeping its slot, alias and history. The screen shows a sign-in link to open in any browser; once you approve, the page there shows a code, which you paste back into the terminal. If that browser runs on the machine itself, the sign-in finishes without the code. The account you are using stays active throughout. Sign-in goes through the deck, so it needs one running.
526
533
 
@@ -834,6 +841,18 @@ Nothing is installed unless you click, or, with **Update when idle** on (Setting
834
841
 
835
842
  **The `ccdeck` your terminal starts** is a separate copy whenever the deck runs from the desktop app, npx or a checkout, and it does not move when they do. When the first `ccdeck` on your PATH is older than the deck, the deck runs the same install for it — `npm install -g --prefix <its prefix> ccdeck@latest`, into the prefix that copy lives in — five minutes after it starts, without waiting for an idle moment, since nothing of the deck's restarts. It does that only for a global npm install of `ccdeck` whose folders you can write, under the same switch (the desktop app shows none, and keeps it on), and never with `AGENTS_DECK_NO_INSTALL=1`. A root-owned prefix, pnpm, yarn or bun, or an old `agents-deck` or `agent-dag` install is left to you: **Settings › About** shows the command, and why an automatic install failed when one did. An install that failed is tried again after half an hour.
836
843
 
844
+ ### Windows update says installed but the version stays old
845
+
846
+ Newer ccdeck versions target the npm prefix of the running copy and verify its version after installation. A different Node installation on PATH no longer redirects that update into another copy.
847
+
848
+ An older installation already stuck in this state needs one manual update to receive that fix. For a Windows **npm installation**, run this in PowerShell to update the copy owning the `ccdeck.cmd` command, then close and reopen ccdeck:
849
+
850
+ ```powershell
851
+ npm install -g --prefix (Split-Path (Get-Command ccdeck.cmd).Source) ccdeck@latest
852
+ ```
853
+
854
+ For the **desktop app**, run the latest [Windows installer](https://github.com/BarganConstantin/ccdeck/releases/latest) instead; updating npm does not replace the desktop app's bundled copy. Your accounts and settings are kept.
855
+
837
856
  ### Restarting
838
857
 
839
858
  ccdeck runs as a two-process pair: a supervisor that owns nothing but the lifecycle, and the deck itself. When newer code is found, the deck exits with code 75 and the supervisor brings it back **on the port it actually bound**, which is not always the one it asked for. Both live in their own process group since 3.20, so stdout goes to `deck.log` rather than to the terminal you started from — `ccdeck --logs` reads it back. The supervisor also puts the deck back after a crash, five times in ten minutes with the wait doubling, and then stops and says why rather than spinning.
package/bin/cli/tui.js CHANGED
@@ -20,6 +20,7 @@
20
20
  // terminal handed back on every way out — q, a signal, a closed connection, a
21
21
  // throw.
22
22
  import { spawn } from "node:child_process";
23
+ import { randomUUID } from "node:crypto";
23
24
  import { join } from "node:path";
24
25
  import { emitKeypressEvents } from "node:readline";
25
26
  import {
@@ -33,7 +34,18 @@ import { G, LINKS, P, PROFILE, UNICODE } from "./screen.js";
33
34
  /** How often each reading is taken while the screen is up. The sessions are
34
35
  * the ones a person is waiting to see change; the roster is the deck's own
35
36
  * cached read, which its panel polls about as often. */
36
- export const POLL_MS = Object.freeze({ sessions: 3_000, auto: 10_000, roster: 15_000, find: 5_000 });
37
+ export const POLL_MS = Object.freeze({
38
+ sessions: 3_000, system: 3_000, auto: 10_000, roster: 15_000, find: 5_000, history: 60_000,
39
+ // The Codex side, as its panel reads it (CodexProfilesSection.tsx,
40
+ // codex-accounts.ts): the list every 15 s and every 2 while a switch waits
41
+ // on the running Codex; the default's quota every minute, the others' every
42
+ // five; the sign-in every second and a half.
43
+ codex: 15_000, codexWaiting: 2_000, codexQuota: 15_000, quotaDefault: 60_000, quotaOther: 300_000, codexSignin: 1_500,
44
+ // The Local network as its section reads it while on screen (every 5 s,
45
+ // use-lan-section.ts); off its tab often enough that a deck asking to pair
46
+ // is said within half a minute.
47
+ lan: 5_000, lanAway: 30_000,
48
+ });
37
49
 
38
50
  /** How long a deck started from here is waited for before saying it did not
39
51
  * come up. A first run installs hooks and claude-swap before it listens. */
@@ -61,6 +73,9 @@ export async function runTui(flags, out, deps = {}) {
61
73
  const view = await load("src/server/tui-view.mjs");
62
74
  const { createScreen } = await load("src/server/tui-screen.mjs");
63
75
  const { accountName, bestAccount } = await load("src/server/account-pick.mjs");
76
+ const { HISTORY_GROUPS, historyMachine, withReading } = await load("src/server/tui-machine.mjs");
77
+ const { CODEX_REFUSED, codexLiveSaid, codexSigninRunning } = await load("src/server/tui-codex.mjs");
78
+ const { LAN_REFUSED } = await load("src/server/tui-network.mjs");
64
79
  const port = flags.port != null ? Number(flags.port) : null;
65
80
  const src = deps.source ?? deckSource(port);
66
81
  const look = {
@@ -77,7 +92,7 @@ export async function runTui(flags, out, deps = {}) {
77
92
  }
78
93
 
79
94
  let state = { ...view.initialState(), deck: deck ? { port: deck.port, version: deck.version ?? null } : null };
80
- const last = { roster: 0, auto: 0, sessions: 0, signin: 0, find: clock() };
95
+ const last = { roster: 0, auto: 0, sessions: 0, system: 0, history: 0, signin: 0, codex: 0, codexQuota: 0, codexSignin: 0, lan: 0, find: clock() };
81
96
  const inflight = new Set();
82
97
  const screen = createScreen(s => output.write(s));
83
98
  let done = null;
@@ -114,7 +129,12 @@ export async function runTui(flags, out, deps = {}) {
114
129
  * in the meantime. */
115
130
  const lost = () => {
116
131
  deck = null;
117
- set({ deck: null, auto: null, sessions: null });
132
+ set({ deck: null, auto: null, sessions: null, codexAuto: null, lanPrefs: null });
133
+ state = view.withLan(state, null);
134
+ state = view.withCodex(state, null);
135
+ if (codexSigninRunning(state.codexSignin)) {
136
+ set({ codexSignin: { ...state.codexSignin, login: { state: "failed", reason: "the deck stopped answering, and the sign-in ended with it" } } });
137
+ }
118
138
  // A sign-in lives in the deck; one that stopped answering took it along.
119
139
  if (view.signinRunning(state.signin)) {
120
140
  state = view.withLogin(state, { state: "failed", error: "the deck stopped answering, and the sign-in ended with it", local: true });
@@ -155,6 +175,25 @@ export async function runTui(flags, out, deps = {}) {
155
175
  } else if (r.status === 0) lost();
156
176
  });
157
177
 
178
+ // The machine, as the deck samples it: one answer a reading, kept. An answer
179
+ // that did not come is a gap in the charts, not a zero.
180
+ const readSystem = once("system", async () => {
181
+ if (!deck) return;
182
+ const r = await src.ask(deck, { path: "/api/system", timeoutMs: 3_000 });
183
+ if (r.ok && r.body && typeof r.body === "object") set({ machine: withReading(state.machine, r.body, clock()) });
184
+ else if (r.status === 0) lost();
185
+ });
186
+
187
+ // The deck's minutes, while the hours are on screen: a day at the most, one
188
+ // section a request, the way its history charts ask.
189
+ const readHistory = once("history", async () => {
190
+ if (!deck || state.machineView !== "hours") return;
191
+ const answers = await Promise.all(HISTORY_GROUPS.map(group => src.ask(deck, { path: `/api/system/history?group=${group}`, timeoutMs: 5_000 })));
192
+ if (answers.some(r => r.status === 0)) return lost();
193
+ const history = historyMachine(answers.map(r => (r.ok ? r.body : null)), state.machine, clock());
194
+ if (state.machineView === "hours") set({ history });
195
+ });
196
+
158
197
  // Where the deck's sign-in is, while the page is up and the deck has one —
159
198
  // never before the start was answered, when "idle" would only mean "not yet".
160
199
  const readSignin = once("signin", async () => {
@@ -165,7 +204,76 @@ export async function runTui(flags, out, deps = {}) {
165
204
  } else if (r.status === 0) lost();
166
205
  });
167
206
 
168
- const readAll = (force) => Promise.all([readRoster(force), readAuto(), readSessions()]);
207
+ // ── the Codex side ───────────────────────────────────────────────────────
208
+
209
+ /** When each Codex account's quota was last asked for, and for which login. */
210
+ const quotaAt = new Map();
211
+ const codexWaiting = () => {
212
+ const live = state.codex?.live;
213
+ return live?.state === "waiting" || live?.continuation === "waiting";
214
+ };
215
+
216
+ // The accounts and Codex Auto-switch together, as the panel reads them. A
217
+ // deck from before the Codex accounts answers 404: no Codex side at all.
218
+ const readCodex = once("codex", async () => {
219
+ if (!deck) return;
220
+ const [r, a] = await Promise.all([src.ask(deck, { path: "/api/codex-profiles" }), src.ask(deck, { path: "/api/codex-auto" })]);
221
+ if (r.status === 0 || a.status === 0) return lost();
222
+ state = view.withCodex(state, r.ok && Array.isArray(r.body?.profiles) ? r.body : null);
223
+ set({ codexAuto: a.ok && a.body && typeof a.body === "object" && a.body.ok !== false ? a.body : null });
224
+ last.codexQuota = 0;
225
+ });
226
+
227
+ // Each account's quota when it is due: at once for one new or signed in
228
+ // again, then the default's every minute and the others' every five. A
229
+ // failed reading keeps the last good one to draw, marked stale.
230
+ const readCodexQuotas = once("codexQuota", async () => {
231
+ if (!deck) return;
232
+ const now = clock();
233
+ const every = (p) => (p.active ? POLL_MS.quotaDefault : POLL_MS.quotaOther);
234
+ const due = (state.codex?.profiles ?? []).filter(p => p.available !== false && typeof p.id === "string" && (() => {
235
+ const seen = quotaAt.get(p.id);
236
+ return !seen || seen.identity !== p.identityVersion || now - seen.at >= every(p);
237
+ })());
238
+ if (!due.length) return;
239
+ const answers = await Promise.all(due.map(p => src.ask(deck, { path: `/api/codex-profile-quota?id=${encodeURIComponent(p.id)}`, timeoutMs: 20_000 })));
240
+ if (answers.some(r => r.status === 0)) return lost();
241
+ const next = { ...state.codexQuota };
242
+ due.forEach((p, i) => {
243
+ const r = answers[i];
244
+ const body = r.body && typeof r.body === "object" ? r.body : { ok: false, reason: "unknown" };
245
+ // A login that moved while it was read is asked again in 15 s, as the panel does.
246
+ const at = body.reason === "profile_changed" ? clock() - every(p) + 15_000 : clock();
247
+ quotaAt.set(p.id, { at, identity: p.identityVersion });
248
+ if (r.ok && body.ok !== false) next[p.id] = body;
249
+ else {
250
+ const prev = next[p.id];
251
+ next[p.id] = { ...body, ok: false, lastGood: prev?.ok === false ? prev.lastGood ?? null : prev ?? null };
252
+ }
253
+ });
254
+ set({ codexQuota: next });
255
+ });
256
+
257
+ // Where the deck's codex login is, while the page waits on it.
258
+ const readCodexSignin = once("codexSignin", async () => {
259
+ const si = state.codexSignin;
260
+ if (!deck || !si?.id || !si.login) return;
261
+ const r = await src.ask(deck, { path: `/api/codex-profile-login-state?id=${encodeURIComponent(si.id)}` });
262
+ if (r.status === 0) return lost();
263
+ if (!r.ok || typeof r.body?.state !== "string" || state.codexSignin?.id !== si.id) return;
264
+ // The deck says "idle" for a flow it no longer has: one that ended before
265
+ // this read, which only a fresh start can tell apart.
266
+ if (r.body.state === "idle") return;
267
+ set({ codexSignin: { ...state.codexSignin, login: r.body } });
268
+ if (r.body.state === "done") {
269
+ await readCodex();
270
+ const who = (state.codex?.profiles ?? []).find(p => p.id === si.id);
271
+ if (state.codexSignin) set({ codexSignin: { ...state.codexSignin, account: who?.account ?? null } });
272
+ quotaAt.delete(si.id);
273
+ }
274
+ });
275
+
276
+ const readAll = (force) => Promise.all([readRoster(force), readAuto(), readSessions(), readSystem(), readCodex(), readLan()]);
169
277
 
170
278
  const lookForDeck = once("find", async () => {
171
279
  const found = await src.find();
@@ -247,6 +355,87 @@ export async function runTui(flags, out, deps = {}) {
247
355
  await readAuto();
248
356
  }
249
357
 
358
+ // ── an account's actions, through the deck's own routes ─────────────────
359
+ //
360
+ // The ones the Accounts panel's menu posts (use-account-menu.ts,
361
+ // AccountsPanel.tsx): home and rotation are Auto-switch's, the alias, the
362
+ // slot and the removal are claude-swap's, behind the deck's store lock. A
363
+ // refusal keeps the menu up, the reason under its items; what worked closes
364
+ // it and says so.
365
+
366
+ /** Why the deck would not, when it said so by name and gave no sentence. */
367
+ const ACTION_REFUSED = {
368
+ bad_value: "claude-swap takes letters, digits, spaces and . _ - only",
369
+ bad_slot: "a slot is a number from 1 to 999",
370
+ bad_account: "the deck does not know that slot any more",
371
+ not_confirmed: "claude-swap did not remove it",
372
+ };
373
+
374
+ async function act(text, body, path, timeoutMs = 60_000) {
375
+ set({ busy: { text, since: clock() }, notice: null });
376
+ render();
377
+ const r = await src.ask(deck, { method: "POST", path, body, timeoutMs });
378
+ set({ busy: null });
379
+ if (r.ok && r.body?.ok !== false) return { ok: true, body: r.body };
380
+ if (r.status === 0) lost();
381
+ const b = r.body && typeof r.body === "object" ? r.body : {};
382
+ const why = b.detail ?? ACTION_REFUSED[b.reason] ?? CODEX_REFUSED[b.reason] ?? b.error ?? b.reason ?? deckTrouble(deck ?? { port: "?" }, r);
383
+ return { ok: false, why: String(why) };
384
+ }
385
+
386
+ /** What worked: the menu closed and a notice. What did not: the menu up, saying why. */
387
+ function settle(result, said, tone = "ok") {
388
+ if (result.ok) {
389
+ set({ menu: null });
390
+ tell(tone, said);
391
+ } else if (state.menu) set({ menu: { ...state.menu, error: result.why } });
392
+ else tell("err", result.why);
393
+ }
394
+
395
+ async function doHome(row, home) {
396
+ if (!deck) return;
397
+ const name = accountName(row);
398
+ const r = await act(home ? `making ${name} home` : `taking home away from ${name}`, { action: "home", account: home ? row.num : null }, "/api/cswap-auto");
399
+ settle(r, home ? `${name} is home ${g.dash} Auto-switch comes back to it once its 5-hour window resets` : `${name} is no longer home`);
400
+ last.auto = 0;
401
+ await readAuto();
402
+ }
403
+
404
+ async function doHold(row, out) {
405
+ if (!deck) return;
406
+ const name = accountName(row);
407
+ const r = await act(out ? `holding ${name} out` : `putting ${name} back`, { action: "account", account: row.num, enabled: !out }, "/api/cswap-auto");
408
+ settle(r, out ? `${name} is held out of rotation ${g.dash} o puts it back` : `${name} is back in rotation`);
409
+ last.auto = 0;
410
+ await Promise.all([readRoster(true), readAuto()]);
411
+ }
412
+
413
+ async function doAlias(row, alias) {
414
+ if (!deck) return;
415
+ const r = await act(`renaming #${row.num}`, { action: "alias", account: row.num, alias }, ADMIN);
416
+ settle(r, alias ? `#${row.num} is ${alias}` : `#${row.num} has no alias now`);
417
+ await readRoster(true);
418
+ }
419
+
420
+ async function doMove(row, slot) {
421
+ if (!deck) return;
422
+ const name = accountName(row);
423
+ const r = await act(`moving ${name} to slot ${slot}`, { action: "move", account: row.num, slot }, ADMIN);
424
+ const to = r.body?.to ?? null;
425
+ settle(r, r.body?.swapped ? `${name} is in slot ${slot} ${g.dash} the account there took slot ${row.num}` : `${name} is in slot ${to ?? slot}`);
426
+ await readRoster(true);
427
+ // The selection follows the account to its new slot.
428
+ if (r.ok) state = view.selectSlot(state, Number(to ?? slot));
429
+ }
430
+
431
+ async function doRemove(row) {
432
+ if (!deck) return;
433
+ const name = accountName(row);
434
+ const r = await act(`removing ${name}`, { action: "remove", account: row.num }, ADMIN);
435
+ settle(r, `removed ${name}`);
436
+ await readRoster(true);
437
+ }
438
+
250
439
  // ── adding an account, through the deck's sign-in ───────────────────────
251
440
 
252
441
  const ADMIN = "/api/claude-accounts/admin";
@@ -370,11 +559,230 @@ export async function runTui(flags, out, deps = {}) {
370
559
  else tell("err", `the deck did not come up ${g.dash} \`${COMMAND} --logs\` shows what it wrote`);
371
560
  }
372
561
 
562
+ // ── the Codex side's actions, through the deck's own routes ─────────────
563
+ //
564
+ // The ones the Codex panel posts: every change names the list's revision it
565
+ // was made against, and one the deck has moved since is refused, not
566
+ // applied to the wrong account.
567
+
568
+ async function doCodexSelect(row) {
569
+ if (!deck) return;
570
+ const name = accountName(row);
571
+ const r = await act(`switching Codex to ${name}`, { id: row.id, expectedRevision: state.codex?.revision, operationId: randomUUID() }, "/api/codex-profile-select", 30_000);
572
+ if (r.ok) {
573
+ const said = codexLiveSaid(r.body?.live, name);
574
+ tell(said.tone, said.text);
575
+ } else tell("err", `could not switch Codex to ${name} ${g.dash} ${r.why}`);
576
+ await readCodex();
577
+ }
578
+
579
+ async function doCodexAuto(enabled) {
580
+ if (!deck) return;
581
+ const r = await act(`turning Codex Auto-switch ${enabled ? "on" : "off"}`, { action: "enable", enabled }, "/api/codex-auto");
582
+ if (r.ok) tell("ok", `Codex Auto-switch ${enabled ? "on" : "off"}`);
583
+ else tell("err", `could not turn Codex Auto-switch ${enabled ? "on" : "off"} ${g.dash} ${r.why}`);
584
+ await readCodex();
585
+ }
586
+
587
+ async function doCodexHold(row, out) {
588
+ if (!deck) return;
589
+ const name = accountName(row);
590
+ const r = await act(out ? `holding ${name} out` : `putting ${name} back`, { action: "account", id: row.id, enabled: !out }, "/api/codex-auto");
591
+ settle(r, out ? `${name} is held out of Codex's rotation ${g.dash} o puts it back` : `${name} is back in Codex's rotation`);
592
+ await readCodex();
593
+ }
594
+
595
+ async function doCodexHome(row, home) {
596
+ if (!deck) return;
597
+ const name = accountName(row);
598
+ const r = await act(home ? `making ${name} home` : `taking home away from ${name}`, { action: "home", id: home ? row.id : null }, "/api/codex-auto");
599
+ settle(r, home ? `${name} is home ${g.dash} Codex Auto-switch comes back to it once it has room again` : `${name} is no longer home`);
600
+ await readCodex();
601
+ }
602
+
603
+ async function doCodexRename(row, label) {
604
+ if (!deck) return;
605
+ const r = await act(`renaming #${row.num}`, { id: row.id, label: label || null, expectedRevision: state.codex?.revision }, "/api/codex-profile-rename");
606
+ settle(r, label ? `#${row.num} is ${label}` : `#${row.num} has no name now`);
607
+ await readCodex();
608
+ }
609
+
610
+ async function doCodexRemove(row) {
611
+ if (!deck) return;
612
+ const name = accountName(row);
613
+ const r = await act(`removing ${name}`, { id: row.id, expectedRevision: state.codex?.revision, operationId: randomUUID() }, "/api/codex-profile-remove");
614
+ settle(r, `removed ${name} ${g.dash} its sign-in and history are kept aside in the deck's data folder`);
615
+ quotaAt.delete(row.id);
616
+ await readCodex();
617
+ }
618
+
619
+ /** The Codex sign-in: a new account made first when it is one, then the
620
+ * deck's codex login for it, which the page follows until it ends. */
621
+ async function doCodexSigninStart() {
622
+ const si = state.codexSignin;
623
+ if (!si || !deck) return;
624
+ const failed = (r) => {
625
+ const b = r.body && typeof r.body === "object" ? r.body : {};
626
+ const reason = CODEX_REFUSED[b.reason] ?? b.reason ?? deckTrouble(deck, r);
627
+ if (state.codexSignin) set({ codexSignin: { ...state.codexSignin, login: { state: "failed", reason } } });
628
+ };
629
+ let id = si.id;
630
+ if (!id) {
631
+ const made = await src.ask(deck, { method: "POST", path: "/api/codex-profile-add", body: { operationId: randomUUID(), expectedRevision: state.codex?.revision }, timeoutMs: 15_000 });
632
+ if (made.status === 0) return lost();
633
+ if (!made.ok || made.body?.ok === false || typeof made.body?.id !== "string") return failed(made);
634
+ id = made.body.id;
635
+ if (!state.codexSignin) return;
636
+ set({ codexSignin: { ...state.codexSignin, id } });
637
+ readCodex();
638
+ }
639
+ const r = await src.ask(deck, { method: "POST", path: "/api/codex-profile-login-start", body: { id }, timeoutMs: 15_000 });
640
+ if (r.status === 0) return lost();
641
+ if (!state.codexSignin || state.codexSignin.id !== id) return;
642
+ if (r.ok && r.body?.ok !== false && typeof r.body?.state === "string") {
643
+ set({ codexSignin: { ...state.codexSignin, login: r.body.state === "idle" ? { state: "starting" } : r.body } });
644
+ last.codexSignin = clock();
645
+ } else failed(r);
646
+ }
647
+
648
+ async function doCodexSigninCancel(id) {
649
+ if (!deck) return;
650
+ await src.ask(deck, { method: "POST", path: "/api/codex-profile-login-cancel", body: { id }, timeoutMs: 3_000 }).catch(() => null);
651
+ await readCodex();
652
+ }
653
+
654
+ async function doCodexSigninDone() {
655
+ await readCodex();
656
+ tell("ok", "signed in to Codex");
657
+ }
658
+
659
+ // ── the Local network ────────────────────────────────────────────────────
660
+
661
+ /** The decks that asked to pair, so each one is said once. */
662
+ const askedBefore = new Set();
663
+
664
+ /** A Local network status in, as every write of it answers with one too:
665
+ * drawn, and a deck newly asking to pair said while the list is elsewhere. */
666
+ const landLan = (body) => {
667
+ const status = { ...body };
668
+ for (const k of ["ok", "added", "done", "peer", "tried"]) delete status[k];
669
+ state = view.withLan(state, status);
670
+ for (const p of status.enabled ? status.pending ?? [] : []) {
671
+ if (!p?.fp || askedBefore.has(p.fp)) continue;
672
+ askedBefore.add(p.fp);
673
+ if (!view.onLan(state)) tell("warn", `${p.name || p.addr || "a deck"} wants to pair ${g.dash} l answers it`);
674
+ }
675
+ };
676
+
677
+ // The status, and on its tab the settings it does not carry — the addresses
678
+ // this deck calls. A deck from before Local network answers 404.
679
+ const readLan = once("lan", async () => {
680
+ if (!deck) return;
681
+ const tab = view.onLan(state);
682
+ const [r, p] = await Promise.all([
683
+ src.ask(deck, { path: "/api/lan" }),
684
+ tab ? src.ask(deck, { path: "/api/prefs" }) : null,
685
+ ]);
686
+ if (r.status === 0) return lost();
687
+ if (r.status === 404) { state = view.withLan(state, null, { missing: true }); return; }
688
+ if (!r.ok || !r.body || typeof r.body !== "object") return;
689
+ landLan(r.body);
690
+ const prefs = p?.ok ? p.body?.prefs?.lan : null;
691
+ if (prefs && typeof prefs === "object") set({ lanPrefs: prefs });
692
+ });
693
+
694
+ /** One Local network write, its refusal in the deck's words. */
695
+ async function lanAct(doing, path, body) {
696
+ set({ busy: { text: doing, since: clock() }, notice: null });
697
+ render();
698
+ const r = await src.ask(deck, { method: "POST", path, body, timeoutMs: 30_000 });
699
+ set({ busy: null });
700
+ if (r.status === 0) { lost(); return { ok: false, why: "the deck stopped answering" }; }
701
+ const b = r.body && typeof r.body === "object" ? r.body : {};
702
+ if (r.ok && b.ok !== false) return { ok: true, body: b };
703
+ const why = LAN_REFUSED[b.reason] ?? (b.reason ? `the deck refused it (${b.reason})` : b.error ?? deckTrouble(deck ?? { port: "?" }, r));
704
+ return { ok: false, why: String(why), body: b };
705
+ }
706
+
707
+ function lanSettle(result, said) {
708
+ if (result.ok) {
709
+ if (state.lanForm && state.lanForm.view !== "invite") set({ lanForm: null });
710
+ if (said) tell("ok", said);
711
+ } else if (state.lanForm) {
712
+ set({ lanForm: { ...state.lanForm, error: result.why, ...(Array.isArray(result.body?.tried) ? { tried: result.body.tried } : {}) } });
713
+ } else tell("err", result.why);
714
+ }
715
+
716
+ /** What a settings write changes in the status, drawn before the next read
717
+ * confirms it. */
718
+ const PREF_IN_STATUS = { tailscale: ["tailscale", "on"], tailscaleAsk: ["tailscale", "ask"], tailscaleAccept: ["tailscale", "accept"] };
719
+
720
+ async function doLanPrefs(e) {
721
+ if (!deck) return;
722
+ const r = await lanAct(e.doing, "/api/prefs", { lan: e.patch });
723
+ if (r.ok && state.lan) {
724
+ let lan = { ...state.lan };
725
+ for (const [k, v] of Object.entries(e.patch)) {
726
+ const [obj, field] = PREF_IN_STATUS[k] ?? [];
727
+ if (obj) lan = { ...lan, [obj]: { ...lan[obj], [field]: v } };
728
+ else if (k !== "manual") lan[k] = v;
729
+ }
730
+ state = view.withLan(state, lan);
731
+ if (e.patch.manual) set({ lanPrefs: { ...state.lanPrefs, manual: e.patch.manual } });
732
+ }
733
+ lanSettle(r, e.said);
734
+ last.lan = 0;
735
+ }
736
+
737
+ async function doLanPeer(e) {
738
+ if (!deck) return;
739
+ const r = await lanAct(e.doing, "/api/lan/peer", { action: e.action, fp: e.fp, ...(e.name != null ? { name: e.name } : {}) });
740
+ if (r.ok) landLan(r.body);
741
+ lanSettle(r, e.said);
742
+ last.lan = 0;
743
+ }
744
+
745
+ async function doLanInvite(e) {
746
+ if (!deck) return;
747
+ const r = await lanAct(e.doing, "/api/lan/invite", { action: e.action, ...(e.token ? { token: e.token } : {}) });
748
+ if (r.body && typeof r.body.enabled === "boolean") landLan(r.body);
749
+ if (e.action === "join") {
750
+ if (r.ok) {
751
+ set({ lanForm: null });
752
+ tell("ok", `paired with ${r.body.peer?.name || "that deck"} ${g.dash} logins go between the two from the next round`);
753
+ } else lanSettle(r);
754
+ } else if (e.action === "make") {
755
+ if (!r.ok) lanSettle(r);
756
+ } else lanSettle(r, e.said);
757
+ last.lan = 0;
758
+ }
759
+
760
+ async function doLanSync(e) {
761
+ if (!deck) return;
762
+ const r = await lanAct(e.doing, "/api/lan/sync", e.fp ? { fp: e.fp } : {});
763
+ if (r.ok) landLan(r.body);
764
+ lanSettle(r, e.said);
765
+ last.lan = 0;
766
+ }
767
+
373
768
  const effects = {
374
- switch: (e) => doSwitch(e.account),
769
+ "lan-prefs": (e) => doLanPrefs(e),
770
+ "lan-peer": (e) => doLanPeer(e),
771
+ "lan-invite": (e) => doLanInvite(e),
772
+ "lan-sync": (e) => doLanSync(e),
773
+ switch: (e) => (e.account?.codex ? doCodexSelect(e.account) : doSwitch(e.account)),
375
774
  best: () => doBest(),
376
- auto: (e) => doAuto(e.enabled),
377
- refresh: () => readAll(true),
775
+ auto: (e) => (e.codex ? doCodexAuto(e.enabled) : doAuto(e.enabled)),
776
+ refresh: () => { quotaAt.clear(); return readAll(true); },
777
+ history: () => readHistory(),
778
+ home: (e) => (e.account?.codex ? doCodexHome(e.account, e.set) : doHome(e.account, e.set)),
779
+ hold: (e) => (e.account?.codex ? doCodexHold(e.account, e.out) : doHold(e.account, e.out)),
780
+ alias: (e) => (e.account?.codex ? doCodexRename(e.account, e.alias) : doAlias(e.account, e.alias)),
781
+ move: (e) => doMove(e.account, e.slot),
782
+ remove: (e) => (e.account?.codex ? doCodexRemove(e.account) : doRemove(e.account)),
783
+ "codex-signin-start": () => doCodexSigninStart(),
784
+ "codex-signin-cancel": (e) => doCodexSigninCancel(e.id),
785
+ "codex-signin-done": () => doCodexSigninDone(),
378
786
  start: () => doStart(),
379
787
  "signin-start": () => doSigninStart(),
380
788
  "signin-code": (e) => doSigninCode(e.code),
@@ -416,12 +824,17 @@ export async function runTui(flags, out, deps = {}) {
416
824
  const leave = (code) => {
417
825
  if (done || leaving) return;
418
826
  const si = state.signin;
419
- if (!deck || !si?.started || si.login?.state === "done" || si.login?.local) return finish(code);
827
+ const csi = state.codexSignin;
828
+ const claude = deck && si?.started && si.login?.state !== "done" && !si.login?.local;
829
+ const codex = deck && csi?.id && csi.started && codexSigninRunning(csi);
830
+ if (!claude && !codex) return finish(code);
420
831
  leaving = true;
421
832
  set({ busy: { text: "cancelling the sign-in", since: clock() } });
422
833
  render();
423
- const cancel = src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 3_000 }).catch(() => null);
424
- Promise.race([cancel, src.wait(3_500)]).then(() => finish(code));
834
+ const cancel = claude
835
+ ? src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 3_000 })
836
+ : src.ask(deck, { method: "POST", path: "/api/codex-profile-login-cancel", body: { id: csi.id }, timeoutMs: 3_000 });
837
+ Promise.race([cancel.catch(() => null), src.wait(3_500)]).then(() => finish(code));
425
838
  };
426
839
  const onSignal = () => leave(EXIT.OK);
427
840
  const onExit = () => screen.leave();
@@ -434,7 +847,10 @@ export async function runTui(flags, out, deps = {}) {
434
847
  function onKey(str, key) {
435
848
  if (done || leaving) return;
436
849
  const { state: next, effect } = view.tuiKey(state, str, key ?? {}, { now: clock(), g });
850
+ // The Local network's tab opened: read it now, with the settings it needs.
851
+ const opened = view.onLan(next) && !view.onLan(state);
437
852
  state = next;
853
+ if (opened) readLan();
438
854
  if (effect?.type === "quit") return leave(EXIT.OK);
439
855
  if (effect?.type === "redraw") screen.invalidate();
440
856
  else if (effect && effects[effect.type]) {
@@ -453,9 +869,15 @@ export async function runTui(flags, out, deps = {}) {
453
869
  if (now - last.roster >= POLL_MS.roster * 2) readRoster(false);
454
870
  } else {
455
871
  if (now - last.sessions >= POLL_MS.sessions) readSessions();
872
+ if (now - last.system >= POLL_MS.system) readSystem();
873
+ if (state.machineView === "hours" && now - last.history >= POLL_MS.history) readHistory();
456
874
  if (now - last.auto >= POLL_MS.auto) readAuto();
457
875
  if (now - last.roster >= POLL_MS.roster) readRoster(false);
458
876
  if (view.signinRunning(state.signin) && now - last.signin >= view.signinPollMs(state.signin)) readSignin();
877
+ if (now - last.codex >= (codexWaiting() ? POLL_MS.codexWaiting : POLL_MS.codex)) readCodex();
878
+ if (state.codex && now - last.codexQuota >= POLL_MS.codexQuota) readCodexQuotas();
879
+ if (state.codexSignin?.login && codexSigninRunning(state.codexSignin) && now - last.codexSignin >= POLL_MS.codexSignin) readCodexSignin();
880
+ if (now - last.lan >= (view.onLan(state) ? POLL_MS.lan : POLL_MS.lanAway)) readLan();
459
881
  }
460
882
  render();
461
883
  };
@@ -488,7 +910,7 @@ const KEPT = Object.freeze({
488
910
 
489
911
  /** What each reading is called when it fails; looking for a deck that is not
490
912
  * there is not a failure. */
491
- const READINGS = Object.freeze({ roster: "the accounts", auto: "Auto-switch", sessions: "the sessions" });
913
+ const READINGS = Object.freeze({ roster: "the accounts", auto: "Auto-switch", sessions: "the sessions", lan: "the Local network" });
492
914
 
493
915
  // SIGHUP is a closed SSH connection, and on Windows a closed console window;
494
916
  // SIGBREAK is Windows' Ctrl+Break.