ccdeck 3.47.0 → 3.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +27 -3
  2. package/bin/cli/commands.js +17 -9
  3. package/bin/cli/help.js +9 -4
  4. package/bin/cli/second-start.js +4 -2
  5. package/bin/cli/startup.js +3 -2
  6. package/bin/cli/tui.js +544 -0
  7. package/dist/web/assets/BrowserWatchModal-DuopT2Oa.js +1 -0
  8. package/dist/web/assets/IntegrationModal-CszT-tts.js +7 -0
  9. package/dist/web/assets/{RadioPanel-DbmJJPsz.js → RadioPanel-Cn3WvPUG.js} +1 -1
  10. package/dist/web/assets/{TrafficRadar-CPjAXd5e.js → TrafficRadar-DZA8XSi7.js} +1 -1
  11. package/dist/web/assets/UsageHistoryModal-MgZJLXbF.js +1 -0
  12. package/dist/web/assets/app-DjlHxWHg.css +1 -0
  13. package/dist/web/assets/app-F1xryJpn.js +321 -0
  14. package/dist/web/assets/{index-Ca87aJP9.js → index-BK9avF1k.js} +1 -1
  15. package/dist/web/index.html +3 -3
  16. package/package.json +1 -1
  17. package/release-notes.json +28 -2
  18. package/src/server/args.mjs +1 -0
  19. package/src/server/cli-lines.mjs +46 -0
  20. package/src/server/gpu-metrics.mjs +78 -0
  21. package/src/server/integrations/jira-move.mjs +239 -0
  22. package/src/server/integrations/jira.mjs +30 -8
  23. package/src/server/integrations/proxy.mjs +3 -4
  24. package/src/server/integrations/routes.mjs +19 -5
  25. package/src/server/system-metrics.mjs +4 -0
  26. package/src/server/term.mjs +14 -5
  27. package/src/server/tui-screen.mjs +110 -0
  28. package/src/server/tui-view.mjs +1072 -0
  29. package/src/server/way-back.mjs +27 -0
  30. package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +0 -1
  31. package/dist/web/assets/IntegrationModal-8tTi25gA.js +0 -6
  32. package/dist/web/assets/UsageHistoryModal-qfmvXdWJ.js +0 -1
  33. package/dist/web/assets/app-BFFG6Wz8.js +0 -321
  34. package/dist/web/assets/app-DfcfHvcX.css +0 -1
@@ -0,0 +1,1072 @@
1
+ // What `ccdeck tui` shows, and what each key does to it.
2
+ //
3
+ // The view is for somebody on the machine over SSH who wants the deck's
4
+ // Accounts panel without a browser: every Claude account with its room, which
5
+ // one is live, Auto-switch's state, and the sessions waiting on them — and the
6
+ // switch, through the deck, a key away.
7
+ //
8
+ // Pure, both halves. `tuiFrame` is a state and a screen size in and the rows to
9
+ // paint out, every one inside the width and exactly as many as the screen has,
10
+ // so the layout can be pinned at 40 columns and at 160 without a terminal.
11
+ // `tuiKey` is a state and a key in and the next state out, with the one thing
12
+ // the app has to go and do (`effect`) when the key asks for more than a
13
+ // redraw. Neither reads the clock, the deck or the terminal: bin/cli/tui.js
14
+ // does that and hands the answers in.
15
+ //
16
+ // The words, the marks and the colours are the commands' own (cli-lines.mjs,
17
+ // term.mjs), so the screen reads like `ccdeck accounts` and `ccdeck sessions`
18
+ // do. What the screen adds is the frame around them — panels, a lit
19
+ // selection, finer meters — drawn as far as the terminal's colour tier
20
+ // reaches, and in plain ASCII on a console that cannot draw a box.
21
+ import { accountName, switchable } from "./account-pick.mjs";
22
+ import {
23
+ accountTrouble, clip, fitPainted, meter, oneLine, pctTone, shortModel, sliceCells, textWidth, untilReset,
24
+ } from "./cli-lines.mjs";
25
+ import { accountKey } from "./lan-copies.mjs";
26
+ import { fg, link, sinceLabel, spinnerFrames, stripAnsi } from "./term.mjs";
27
+
28
+ /** Text from elsewhere — the deck's own sentences, an alias — on a console
29
+ * that draws ASCII alone: its punctuation in ASCII's, anything else a "?". */
30
+ const ASCII_FOR = Object.freeze({ "—": "-", "–": "-", "…": "...", "‘": "'", "’": "'", "“": '"', "”": '"', "·": ".", "×": "x" });
31
+ export const asciiOnly = (s) => s.replace(/[^\x00-\x7f]/gu, (c) => ASCII_FOR[c] ?? "?");
32
+
33
+ /** Below this the view says so instead of drawing a screen nothing fits on. */
34
+ export const MIN_COLUMNS = 40;
35
+ export const MIN_ROWS = 12;
36
+
37
+ /** How long a notice that something worked stays on screen. A failure stays
38
+ * until the next key, since it may be the only account of what happened. */
39
+ export const NOTICE_MS = 8_000;
40
+
41
+ /** The state before anything has been read. */
42
+ export function initialState() {
43
+ return {
44
+ deck: null, // { port, version } while a deck answers
45
+ readAt: null, // when the deck last answered a reading, for "live"
46
+ source: null, // "deck" | "local": where the roster was read
47
+ silent: [], // decks alive but not answering, which hold the store's lock
48
+ roster: null, // the roster as the deck serves it
49
+ trouble: null, // why the roster has no rows, as lines, when it has none
50
+ auto: null, // GET /api/cswap-auto, or null
51
+ sessions: null, // GET /api/sessions' rows, or null
52
+ skew: 0, // the deck's clock minus this one, for the sessions' ages
53
+ at: 0, // the selected account, by index
54
+ top: 0, // the first account row on screen
55
+ help: false,
56
+ notice: null, // { tone, text, until }
57
+ busy: null, // { text, since } while a switch or a start is under way
58
+ starting: false,
59
+ signin: null, // the sign-in page while it is up (openSignin)
60
+ };
61
+ }
62
+
63
+ /** A notice. `until` null keeps it until the next key. */
64
+ export function note(tone, text, now) {
65
+ return { tone, text, until: tone === "err" || tone === "warn" ? null : now + NOTICE_MS };
66
+ }
67
+
68
+ const accountsOf = (state) => (state.roster?.ok && Array.isArray(state.roster.accounts) ? state.roster.accounts : []);
69
+
70
+ /** Auto-switch's home account, by slot, or null. */
71
+ export function homeSlot(state) {
72
+ const home = state.auto?.choice?.home;
73
+ if (!home || typeof home.email !== "string") return null;
74
+ const key = accountKey(home.email, home.orgUuid);
75
+ return accountsOf(state).find(a => accountKey(a.email, a.orgUuid) === key)?.num ?? null;
76
+ }
77
+
78
+ /** The selection moved onto the account in slot `num`, if there is one. */
79
+ export function selectSlot(state, num) {
80
+ const i = accountsOf(state).findIndex(a => a.num === num);
81
+ return i === -1 ? state : { ...state, at: i };
82
+ }
83
+
84
+ /**
85
+ * A fresh roster in place of the old one, the selection kept on the account it
86
+ * was on — the list's order is the rotation's and can change under it — or,
87
+ * on the first read, put on the account in use.
88
+ */
89
+ export function withRoster(state, roster, trouble = null) {
90
+ const before = accountsOf(state)[state.at]?.num;
91
+ const next = { ...state, roster, trouble };
92
+ const rows = accountsOf(next);
93
+ const kept = before == null ? -1 : rows.findIndex(a => a.num === before);
94
+ const at = kept !== -1 ? kept : Math.max(0, rows.findIndex(a => a.active));
95
+ return { ...next, at: Math.min(at, Math.max(0, rows.length - 1)) };
96
+ }
97
+
98
+ // ── the keys ────────────────────────────────────────────────────────────────
99
+
100
+ /**
101
+ * What a key does: `{ state, effect }`. `effect` is null or one of
102
+ *
103
+ * { type: "quit" } q, Esc, Ctrl+C
104
+ * { type: "redraw" } Ctrl+L
105
+ * { type: "switch", account }
106
+ * { type: "best" } select what Auto-switch would pick
107
+ * { type: "auto", enabled }
108
+ * { type: "refresh" }
109
+ * { type: "start" } start a deck, when none is running
110
+ * { type: "signin-start" } ask the deck for a sign-in link
111
+ * { type: "signin-code", code } hand it the code the page showed
112
+ * { type: "signin-cancel", quiet } let go of the deck's sign-in
113
+ * { type: "signin-done", account } the page closed on a sign-in that took
114
+ *
115
+ * The refusals a switch can be told before it is asked for — the account in
116
+ * use, a deck that is running and not answering — are answered here, in the
117
+ * words `ccdeck switch` uses; a login known to be dead opens the sign-in page
118
+ * for it instead. While that page is up every key is its own.
119
+ */
120
+ export function tuiKey(state, str, key = {}, { now = 0, g } = {}) {
121
+ const name = key.name ?? "";
122
+ if (key.ctrl && name === "c") return { state, effect: { type: "quit" } };
123
+ if (key.ctrl && name === "l") return { state, effect: { type: "redraw" } };
124
+ if (state.signin) return signinKey(state, str, key, { now, g });
125
+ // Help is a page over the view: any key puts the view back, and the key is
126
+ // spent doing it — q there closes the page, it does not quit.
127
+ if (state.help) return { state: { ...state, help: false }, effect: null };
128
+ if (str === "q" || name === "escape") return { state, effect: { type: "quit" } };
129
+ if (str === "?") return { state: { ...state, help: true }, effect: null };
130
+
131
+ const rows = accountsOf(state);
132
+ const s = { ...state, notice: null };
133
+ const go = (at) => ({ state: { ...s, at }, effect: null });
134
+ const last = Math.max(0, rows.length - 1);
135
+ if (name === "up" || str === "k") return go(rows.length ? (state.at - 1 + rows.length) % rows.length : 0);
136
+ if (name === "down" || str === "j" || (name === "tab" && !key.shift)) return go(rows.length ? (state.at + 1) % rows.length : 0);
137
+ if (name === "home" || str === "g") return go(0);
138
+ if (name === "end" || str === "G") return go(last);
139
+ if (name === "pageup") return go(Math.max(0, state.at - 5));
140
+ if (name === "pagedown") return go(Math.min(last, state.at + 5));
141
+ if (/^[1-9]$/.test(str ?? "")) {
142
+ const i = rows.findIndex(a => a.num === Number(str));
143
+ return i === -1 ? { state: s, effect: null } : go(i);
144
+ }
145
+ if (name === "return" || name === "enter" || str === "s") return switchKey(s, rows[state.at], { now, g });
146
+ if (str === "b") {
147
+ if (!rows.length) return { state: s, effect: null };
148
+ return { state: s, effect: { type: "best" } };
149
+ }
150
+ if (str === "a") return autoKey(s, { now, g });
151
+ if (str === "+") return addKey(s, { now, g });
152
+ if (str === "r") return { state: s, effect: { type: "refresh" } };
153
+ if (str === "d") {
154
+ if (state.deck) return { state: { ...s, notice: note("info", `the deck is already running on ${state.deck.port}`, now) }, effect: null };
155
+ if (state.starting) return { state: s, effect: null };
156
+ return { state: s, effect: { type: "start" } };
157
+ }
158
+ return { state, effect: null };
159
+ }
160
+
161
+ function switchKey(state, row, { now, g }) {
162
+ if (!row) return { state, effect: null };
163
+ const told = (tone, text) => ({ state: { ...state, notice: note(tone, text, now) }, effect: null });
164
+ if (state.busy) return told("info", `${state.busy.text} ${g.dash} one thing at a time`);
165
+ // A login known to be dead: switching to it signs every running session out,
166
+ // so enter offers the one remedy instead, where the panel offers it — the
167
+ // sign-in, for this account, which replaces its login in place. In use or
168
+ // not. A disabled slot is a person's own "keep out of rotation" and switches.
169
+ if (!switchable(row) && !row.disabled) {
170
+ if (state.deck && row.email) return { state: { ...state, signin: openSignin(row.email) }, effect: null };
171
+ return told("err", `${accountName(row)} needs a fresh sign-in ${g.dash} d starts the deck, which signs it in again`);
172
+ }
173
+ if (row.active) return told("ok", `already on ${accountName(row)}`);
174
+ // A deck that is alive and did not answer holds the store's lock in its own
175
+ // process: switching beside it is the race #1039 closed.
176
+ if (!state.deck && state.silent.length) {
177
+ return told("err", `the deck on ${state.silent.map(d => d.port).join(", ")} is running but did not answer ${g.dash} not switching behind its back`);
178
+ }
179
+ return { state, effect: { type: "switch", account: row } };
180
+ }
181
+
182
+ function autoKey(state, { now, g }) {
183
+ const told = (tone, text) => ({ state: { ...state, notice: note(tone, text, now) }, effect: null });
184
+ if (!state.deck) return told("info", `Auto-switch runs inside the deck ${g.dash} d starts one`);
185
+ if (state.busy) return told("info", `${state.busy.text} ${g.dash} one thing at a time`);
186
+ if (!state.auto) return told("info", `the deck has not said whether Auto-switch is on yet`);
187
+ return { state, effect: { type: "auto", enabled: state.auto.enabled !== true } };
188
+ }
189
+
190
+ function addKey(state, { now, g }) {
191
+ const told = (tone, text) => ({ state: { ...state, notice: note(tone, text, now) }, effect: null });
192
+ if (!state.deck) return told("info", `accounts are added through the deck ${g.dash} d starts one`);
193
+ if (state.busy) return told("info", `${state.busy.text} ${g.dash} one thing at a time`);
194
+ // claude-swap keeps the accounts: missing, refused or still being installed,
195
+ // a sign-in would end at its last step with nowhere to put the account.
196
+ if (state.roster && !state.roster.ok && state.roster.reason !== "no_accounts") {
197
+ return told("err", String([].concat(state.trouble ?? "could not read the accounts")[0]));
198
+ }
199
+ return { state: { ...state, signin: openSignin() }, effect: null };
200
+ }
201
+
202
+
203
+ // ── the frame ───────────────────────────────────────────────────────────────
204
+
205
+ /** From this many columns the detail and the waiting sessions sit side by side. */
206
+ export const WIDE_COLUMNS = 120;
207
+
208
+ /**
209
+ * The screen: `{ lines, top }`, `lines` exactly `rows` long and none of them
210
+ * reaching the last column, `top` the first account row shown — kept by the
211
+ * app and handed back, so the list scrolls only when the selection leaves it.
212
+ *
213
+ * ccdeck Claude accounts ● live · deck 4317
214
+ * ╭─ Accounts ───────────────────────────────────────────────────────╮
215
+ * │ › ● 1 ⌂ work alice@corp.example 5h ███▍ 20% 7d ██▊ … │
216
+ * ╰─ 1–6 of 9 ──────────── Auto-switch on · at 90% · next: most room ─╯
217
+ * ╭─ #1 alice@corp.example (work) ───────────── in use · read 1m ago ─╮
218
+ * │ 5h ████████▍ 20% resets in 1h │
219
+ * ╰──────────────────────────────────────────────────────────────────╯
220
+ * ╭─ Waiting on you · 2 ──────────────────────────────── 1 working ─╮
221
+ * │ ⚠ 12m docs Codex │
222
+ * │ Which branch? │
223
+ * ╰──────────────────────────────────────────────────────────────────╯
224
+ * ✓ switched to #1 alice@corp.example
225
+ * enter switch b best a auto-switch r refresh ? keys q quit
226
+ *
227
+ * From WIDE_COLUMNS the detail and the waiting sessions sit side by side under
228
+ * the list. On a short screen what gives way first is what is said elsewhere
229
+ * too: waiting sessions beyond the first, then the detail, then the question
230
+ * under the one left, then account rows (the list scrolls, its border saying
231
+ * where), and the waiting panel last of all. The last panel takes the rows
232
+ * left over, so the frame ends at the foot of the screen whatever its height.
233
+ *
234
+ * `profile` is the colour tier (term.mjs colorProfile): the backgrounds — the
235
+ * title bar, the lit row, the keys — reach as far as it does, and under
236
+ * "none" there is not one escape on the screen. `links` says the terminal
237
+ * takes OSC 8 links (term.mjs supportsHyperlinks).
238
+ *
239
+ * While the sign-in page is up the panels give way to it, and the frame may
240
+ * carry a `run` (tui-screen.mjs): the sign-in link, edge to edge, its rows in
241
+ * `lines` as the pieces the terminal will wrap it into.
242
+ */
243
+ export function tuiFrame(state, { columns = 80, rows = 24, tone, g, unicode = true, now = 0, profile, links = false } = {}) {
244
+ // The last column stays empty, the way statusLine leaves it (term.mjs): a
245
+ // terminal that does not honour the wrap-off mode would wrap a full row.
246
+ // The run is the one exception, and wraps on purpose.
247
+ const width = columns - 1;
248
+ const plain = unicode ? (l) => l : asciiOnly;
249
+ const fill = (lines, run = null) => {
250
+ const out = lines.slice(0, rows).map((l, i) => (run && i >= run.row && i < run.row + run.rows ? l : fitPainted(plain(l), width, g.ellipsis)));
251
+ while (out.length < rows) out.push("");
252
+ return out;
253
+ };
254
+ if (columns < MIN_COLUMNS || rows < MIN_ROWS) {
255
+ const times = unicode ? "×" : "x";
256
+ return { lines: fill([`${tone.muted}too small ${g.dash} ${MIN_COLUMNS}${times}${MIN_ROWS} at least${tone.reset}`]), top: state.top, run: null };
257
+ }
258
+ const look = { tone, g, unicode, now, links, skin: skinOf(profile ?? (tone.reset ? "ansi16" : "none")) };
259
+ if (state.signin) {
260
+ const page = signinLines(state, rows - 3, width, columns, look);
261
+ const run = page.run ? { ...page.run, row: page.run.row + 1 } : null;
262
+ const lines = [titleBar(state, width, look), ...page.lines, noticeLine(state, look), footerLine(state, width, look)];
263
+ return { lines: fill(lines, run), top: state.top, run };
264
+ }
265
+ const body = bodyLines(state, rows - 3, width, look);
266
+ const lines = [titleBar(state, width, look), ...body.lines, noticeLine(state, look), footerLine(state, width, look)];
267
+ return { lines: fill(state.help ? withHelp(lines, width, look) : lines), top: body.top, run: null };
268
+ }
269
+
270
+ // ── the look ────────────────────────────────────────────────────────────────
271
+
272
+ // Rider Black's own (src/web/themes), the deck's default theme, so the
273
+ // terminal and the page are one product: the chrome, the selection, the text
274
+ // on them. Every background carries its own text colour, since the terminal's
275
+ // may be a dark one on a light theme.
276
+ const LIGHT = [223, 225, 229];
277
+ const CHROME = [43, 45, 48];
278
+ const SELECTION = [46, 67, 110];
279
+ const KEYCAP = [57, 59, 64];
280
+ const TRACK = [78, 81, 88];
281
+ const FADED = [92, 95, 102];
282
+
283
+ /**
284
+ * The backgrounds, as far as the profile reaches, and the two greys drawn on
285
+ * the terminal's own: the meters' track and the screen under the keys. 16
286
+ * colours keep two backgrounds — the lit row and the keys — in the terminal's
287
+ * own blue and in reverse; "none" keeps none, and the pointer alone says
288
+ * which row is selected.
289
+ */
290
+ function skinOf(profile) {
291
+ const deep = profile === "truecolor" || profile === "ansi256";
292
+ const paint = (layer, rgb) => (deep ? fg(rgb, profile, "").replace("\x1b[38;", `\x1b[${layer};`) : "");
293
+ const on = (rgb) => (deep ? `${paint(48, rgb)}${paint(38, LIGHT)}` : "");
294
+ const sixteen = profile === "ansi16";
295
+ return {
296
+ raised: on(CHROME),
297
+ select: deep ? on(SELECTION) : sixteen ? "\x1b[44;97m" : "",
298
+ cap: deep ? on(KEYCAP) : sixteen ? "\x1b[7m" : "",
299
+ track: deep ? paint(38, TRACK) : sixteen ? "\x1b[2m" : "",
300
+ faded: deep ? paint(38, FADED) : sixteen ? "\x1b[2m" : "",
301
+ };
302
+ }
303
+
304
+ /** `s` on a background, put back after every reset inside it. */
305
+ const onBg = (s, bg) => (bg ? `${bg}${s.replaceAll("\x1b[0m", `\x1b[0m${bg}`)}\x1b[0m` : s);
306
+ const padEnd = (s, n) => s + " ".repeat(Math.max(0, n - textWidth(s)));
307
+ const padStart = (s, n) => " ".repeat(Math.max(0, n - textWidth(s))) + s;
308
+ /** A painted line exactly `n` columns wide: cut, or padded. */
309
+ function cells(s, n, ellipsis) {
310
+ const fitted = fitPainted(s, n, ellipsis);
311
+ return fitted + " ".repeat(Math.max(0, n - textWidth(fitted)));
312
+ }
313
+ const pad = (n) => Array.from({ length: Math.max(0, n) }, () => "");
314
+
315
+ const BOX = {
316
+ unicode: { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│" },
317
+ ascii: { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" },
318
+ };
319
+
320
+ /**
321
+ * A panel `width` by `height`, borders included: its title and `note` on the
322
+ * top border, `footLeft` and `footRight` on the bottom one, `lines` inside and
323
+ * the `selected` one lit across the whole row. A note or a foot may be a list,
324
+ * longest first: the border takes the first that fits.
325
+ */
326
+ function panel(width, height, { title = "", note = "", footLeft = "", footRight = "", lines = [], selected = -1 }, look) {
327
+ const { tone, g, unicode, skin } = look;
328
+ const b = unicode ? BOX.unicode : BOX.ascii;
329
+ const inner = width - 4;
330
+ const side = `${tone.muted}${b.v}${tone.reset}`;
331
+ const body = [];
332
+ for (let i = 0; i < height - 2; i++) {
333
+ const cell = cells(lines[i] ?? "", inner, g.ellipsis);
334
+ body.push(i === selected && skin.select ? `${side}${onBg(` ${cell} `, skin.select)}${side}` : `${side} ${cell} ${side}`);
335
+ }
336
+ return [rule(width, b.tl, b.tr, title, note, look), ...body, rule(width, b.bl, b.br, footLeft, footRight, look)];
337
+ }
338
+
339
+ /** A border: a corner, the left words, the rule, the right words, a corner. */
340
+ function rule(width, l, r, left, right, { tone, g, unicode }) {
341
+ const h = unicode ? BOX.unicode.h : BOX.ascii.h;
342
+ const room = width - 4;
343
+ const lefts = [].concat(left);
344
+ left = lefts.find(t => !t || textWidth(t) + 3 <= room) ?? fitPainted(lefts.at(-1), Math.max(0, room - 3), g.ellipsis);
345
+ const lw = left ? textWidth(left) + 2 : 0;
346
+ const said = [].concat(right).find(t => !t || lw + textWidth(t) + 3 <= room) ?? "";
347
+ const rw = said ? textWidth(said) + 2 : 0;
348
+ const line = (n) => `${tone.muted}${h.repeat(Math.max(0, n))}${tone.reset}`;
349
+ return `${tone.muted}${l}${h}${tone.reset}${left ? ` ${left} ` : ""}${line(room - lw - rw)}${said ? ` ${said} ` : ""}`
350
+ + `${tone.muted}${h}${r}${tone.reset}`;
351
+ }
352
+
353
+ /**
354
+ * A meter `width` cells long: a heavy line for what is used, to the half
355
+ * cell, over a light one for the rest. Thin, so a column of them reads as a
356
+ * table rather than as blocks, and drawn in text colour alone, so it sits as
357
+ * well on a light terminal as on a dark one — and the two weights tell used
358
+ * from free with no colour at all. ASCII is the commands' own `#` and `.`.
359
+ */
360
+ function gauge(pct, width, { tone, unicode, skin }) {
361
+ const colour = pctTone(pct, tone);
362
+ if (!unicode) return `${colour}${meter(pct, { cells: width, unicode })}${tone.reset}`;
363
+ const p = Math.min(100, Math.max(0, Number(pct) || 0));
364
+ const halves = Math.round((p / 100) * width * 2);
365
+ const full = Math.floor(halves / 2);
366
+ const half = halves % 2;
367
+ return `${colour}${"━".repeat(full)}${half ? "╸" : ""}${tone.reset}${skin.track}${"─".repeat(width - full - half)}${tone.reset}`;
368
+ }
369
+
370
+ // ── the rows around the panels ──────────────────────────────────────────────
371
+
372
+ /** A reading this recent says the screen is live. The sessions are read every
373
+ * three seconds, so a deck that answers never lets it lapse. */
374
+ const LIVE_MS = 10_000;
375
+
376
+ function titleBar(state, width, { tone, g, unicode, now, skin }) {
377
+ const left = ` ${tone.accent}${tone.bold}ccdeck${tone.reset} ${tone.bold}Claude accounts${tone.reset}`;
378
+ let right = "";
379
+ if (state.deck) {
380
+ const ago = state.readAt == null ? null : now - state.readAt;
381
+ const where = `deck ${state.deck.port}`;
382
+ right = ago == null ? `${tone.muted}${where}${tone.reset}`
383
+ : ago < LIVE_MS ? `${tone.ok}${unicode ? "●" : "*"}${tone.reset} ${tone.muted}live ${g.bullet} ${where}${tone.reset}`
384
+ : `${tone.warn}${unicode ? "○" : "o"}${tone.reset} ${tone.muted}read ${sinceLabel(ago)} ago ${g.bullet} ${where}${tone.reset}`;
385
+ } else if (state.starting) right = `${tone.muted}starting the deck${g.ellipsis}${tone.reset}`;
386
+ else if (state.silent.length) right = `${tone.warn}deck ${state.silent.map(d => d.port).join(", ")} not answering${tone.reset}`;
387
+ else if (state.source === "local") right = `${tone.muted}no deck ${g.bullet} claude-swap's store${tone.reset}`;
388
+ const gap = width - textWidth(left) - textWidth(right) - 2;
389
+ const line = right && gap >= 2 ? `${left}${" ".repeat(gap)}${right} ` : left;
390
+ return skin.raised ? onBg(cells(line, width, g.ellipsis), skin.raised) : line;
391
+ }
392
+
393
+ const NOTICE_MARK = { ok: ["ok", "ok"], err: ["err", "fail"], warn: ["warn", "warn"], info: ["accent", "arrow"] };
394
+
395
+ function noticeLine(state, { tone, g, unicode, now }) {
396
+ if (state.busy) {
397
+ const frames = spinnerFrames(unicode);
398
+ const spin = frames[Math.floor((now - state.busy.since) / 100) % frames.length];
399
+ return ` ${tone.accent}${spin}${tone.reset} ${tone.muted}${state.busy.text}${g.ellipsis}${tone.reset}`;
400
+ }
401
+ const n = state.notice;
402
+ if (!n || (n.until != null && now > n.until)) return "";
403
+ const [toneName, glyph] = NOTICE_MARK[n.tone] ?? NOTICE_MARK.info;
404
+ return ` ${tone[toneName]}${g[glyph]}${tone.reset} ${n.tone === "err" ? tone.err : ""}${oneLine(n.text)}${tone.reset}`;
405
+ }
406
+
407
+ /** The keys, as many as fit, the ones that leave and explain kept to the last.
408
+ * Each key is a cap where the terminal can draw one. */
409
+ function footerLine(state, width, { tone, unicode, skin }) {
410
+ const keys = state.signin ? signinKeys(state.signin) : [
411
+ [unicode ? "↑↓" : "up/down", "move"],
412
+ ["enter", "switch"],
413
+ ["b", "best"],
414
+ state.deck ? ["a", "auto-switch"] : ["d", "start the deck"],
415
+ ["+", "add"],
416
+ ["r", "refresh"],
417
+ ["?", "keys"],
418
+ ["q", "quit"],
419
+ ];
420
+ const cap = (k) => (skin.cap ? `${skin.cap} ${k} ${tone.reset}` : `${tone.bold}${k}${tone.reset}`);
421
+ const draw = (list) => `${skin.cap ? " " : " "}${list.map(([k, what]) => `${cap(k)} ${tone.muted}${what}${tone.reset}`).join(" ")}`;
422
+ const list = keys.slice();
423
+ // r goes first, then the moves, then b: the screen says what they do, and ?
424
+ // and q are how to find out and how to leave.
425
+ for (const drop of ["r", unicode ? "↑↓" : "up/down", "b", "+", "a", "d", "enter"]) {
426
+ if (textWidth(draw(list)) <= width) break;
427
+ const i = list.findIndex(([k]) => k === drop);
428
+ if (i !== -1) list.splice(i, 1);
429
+ }
430
+ return draw(list);
431
+ }
432
+
433
+ // ── the panels ──────────────────────────────────────────────────────────────
434
+
435
+ function bodyLines(state, room, width, look) {
436
+ const { tone, g, unicode } = look;
437
+ const rows = accountsOf(state);
438
+ const home = homeSlot(state);
439
+ const selected = rows[state.at] ?? null;
440
+ const inner = width - 4;
441
+
442
+ let accounts;
443
+ if (!state.roster) accounts = [`${tone.muted}reading the accounts${g.ellipsis}${tone.reset}`];
444
+ else if (!state.roster.ok && state.roster.reason === "no_accounts" && state.deck) {
445
+ accounts = [`${tone.muted}no Claude accounts yet ${g.dash} + signs one in${tone.reset}`];
446
+ } else if (!state.roster.ok) {
447
+ // Wrapped, not cut: these are what to do next, a command among them.
448
+ accounts = [].concat(state.trouble ?? "could not read the accounts")
449
+ .flatMap((l, i) => wrap(String(l), inner).map(part => `${i ? tone.muted : tone.warn}${part}${tone.reset}`));
450
+ } else if (!rows.length) accounts = [`${tone.muted}no Claude accounts yet${tone.reset}`];
451
+ else accounts = accountRows(rows, { home, at: state.at, width: inner }, look);
452
+ const listed = rows.length > 0 && Boolean(state.roster?.ok);
453
+ const auto = autoSummary(state, look);
454
+ const waiting = waitingOf(state);
455
+
456
+ // The list, scrolled so the selection is on it; when it does not fit whole
457
+ // its bottom border says which rows are showing.
458
+ const accountsPanel = (shownRows, height) => {
459
+ let top = 0;
460
+ let shown = accounts;
461
+ let where = "";
462
+ if (shownRows < accounts.length) {
463
+ top = listed ? Math.min(Math.max(0, state.top, state.at - shownRows + 1), state.at, accounts.length - shownRows) : 0;
464
+ shown = accounts.slice(top, top + shownRows);
465
+ if (listed) where = `${tone.muted}${top + 1}${unicode ? "–" : "-"}${top + shown.length} of ${accounts.length}${tone.reset}`;
466
+ }
467
+ const lines = panel(width, height, {
468
+ title: `${tone.bold}Accounts${tone.reset}`, footLeft: where, footRight: auto, lines: shown, selected: listed ? state.at - top : -1,
469
+ }, look);
470
+ return { lines, top };
471
+ };
472
+
473
+ const stacked = () => {
474
+ const detail = selected ? detailPanel(selected, home, inner, look) : null;
475
+ let accountRoom = accounts.length;
476
+ let showDetail = Boolean(detail);
477
+ let max = waiting.list.length;
478
+ let asks = true;
479
+ let showWaiting = true;
480
+ const sessions = () => sessionsPanel(state, waiting, { max, asks, width: inner }, look);
481
+ const need = () => 2 + accountRoom + (showDetail ? 2 + detail.lines.length : 0) + (showWaiting ? 2 + sessions().lines.length : 0);
482
+ const giveWay = [
483
+ () => max > 1 && (max--, true),
484
+ () => showDetail && !(showDetail = false),
485
+ () => asks && waiting.list.length > 0 && !(asks = false),
486
+ () => accountRoom > 3 && (accountRoom--, true),
487
+ () => showWaiting && !(showWaiting = false),
488
+ () => accountRoom > 1 && (accountRoom--, true),
489
+ ];
490
+ while (need() > room && giveWay.some(step => step()));
491
+ // What the detail gave up may hold a waiting session it cost.
492
+ while (showWaiting && max < waiting.list.length && (max++, need() > room ? (max--, false) : true));
493
+ // The last panel takes the rows left over.
494
+ const spare = Math.max(0, room - need());
495
+ const list = accountsPanel(accountRoom, 2 + accountRoom + (showDetail || showWaiting ? 0 : spare));
496
+ const out = [...list.lines];
497
+ if (showDetail) out.push(...panel(width, 2 + detail.lines.length + (showWaiting ? 0 : spare), detail, look));
498
+ if (showWaiting) {
499
+ const s = sessions();
500
+ out.push(...panel(width, 2 + s.lines.length + spare, s, look));
501
+ }
502
+ return { lines: out, top: list.top };
503
+ };
504
+
505
+ const sideBySide = () => {
506
+ const leftW = Math.floor((width - 1) / 2);
507
+ const rightW = width - 1 - leftW;
508
+ const detail = detailPanel(selected, home, leftW - 4, look);
509
+ let accountRoom = accounts.length;
510
+ let max = waiting.list.length;
511
+ let asks = true;
512
+ const sessions = () => sessionsPanel(state, waiting, { max, asks, width: rightW - 4 }, look);
513
+ const need = () => 2 + accountRoom + 2 + Math.max(detail.lines.length, sessions().lines.length);
514
+ const giveWay = [
515
+ () => max > 1 && (max--, true),
516
+ () => accountRoom > 3 && (accountRoom--, true),
517
+ () => asks && waiting.list.length > 0 && !(asks = false),
518
+ ];
519
+ while (need() > room && giveWay.some(step => step()));
520
+ if (need() > room) return null;
521
+ const list = accountsPanel(accountRoom, 2 + accountRoom);
522
+ const height = room - list.lines.length;
523
+ const left = panel(leftW, height, detail, look);
524
+ const right = panel(rightW, height, sessions(), look);
525
+ return { lines: [...list.lines, ...left.map((l, i) => `${l} ${right[i]}`)], top: list.top };
526
+ };
527
+
528
+ const laid = (width >= WIDE_COLUMNS - 1 && selected && sideBySide()) || stacked();
529
+ return { lines: [...laid.lines, ...pad(room - laid.lines.length)].slice(0, room), top: laid.top };
530
+ }
531
+
532
+ const LANE_IDS = ["five_hour", "seven_day"];
533
+
534
+ /** A lane's columns: its label, the meter and the percentage, and the reset —
535
+ * all of it (A), without the reset (B), or the percentage alone (C). */
536
+ const laneWidth = (kind, bar, labelW) => (kind === "A" ? labelW + bar + 17 : kind === "B" ? labelW + bar + 6 : labelW + 5);
537
+
538
+ /**
539
+ * The roster, one account per row: the pointer, the account in use, the slot,
540
+ * the home mark, the alias, the email and its two lanes.
541
+ *
542
+ * The lanes take the room the names leave them: a meter and the reset each on
543
+ * a wide screen, the meter alone on a middling one, the percentages on a
544
+ * narrow one — and only then the alias goes. The email keeps twenty columns,
545
+ * or all of itself when it is shorter; on a wide screen what it does not need
546
+ * goes to the meters.
547
+ */
548
+ function accountRows(rows, { home, at, width }, look) {
549
+ const { tone, g, unicode } = look;
550
+ const aliasOf = (a) => oneLine(a.alias);
551
+ const emailOf = (a) => oneLine(a.email) || "(no email)";
552
+ const numW = Math.max(...rows.map(a => String(a.num).length));
553
+ const showHome = home != null && rows.some(a => a.num === home);
554
+ const labelW = Math.max(2, ...rows.flatMap(a => (a.lanes ?? []).filter(l => LANE_IDS.includes(l.id)).map(l => textWidth(oneLine(l.label)))));
555
+ const longest = Math.max(...rows.map(a => textWidth(emailOf(a))));
556
+ const aliasW = Math.min(14, Math.max(0, ...rows.map(a => textWidth(aliasOf(a)))));
557
+ const lead = (alias) => 2 + 2 + numW + 1 + (showHome ? 2 : 0) + (alias ? aliasW + 2 : 0);
558
+ const lanesW = ({ kind, bar }) => 2 * laneWidth(kind, bar, labelW) + 3;
559
+ const want = Math.min(longest, 20);
560
+ const tries = [["A", 10], ["A", 8], ["A", 6], ["B", 10], ["B", 8], ["B", 6], ["B", 4], ["C", 0]];
561
+ let pick = null;
562
+ for (const alias of aliasW ? [true, false] : [false]) {
563
+ const fit = tries.find(([kind, bar]) => width - lead(alias) - 2 - lanesW({ kind, bar }) >= want);
564
+ if (fit) { pick = { alias, kind: fit[0], bar: fit[1] }; break; }
565
+ }
566
+ pick ??= { alias: false, kind: "C", bar: 0 };
567
+ const emailW = Math.max(6, Math.min(longest, width - lead(pick.alias) - 2 - lanesW(pick)));
568
+ if (pick.kind !== "C") {
569
+ const spare = width - lead(pick.alias) - emailW - 2 - lanesW(pick);
570
+ pick.bar = Math.min(20, pick.bar + Math.max(0, Math.floor(spare / 2)));
571
+ }
572
+
573
+ return rows.map((a, i) => {
574
+ const pointer = i === at ? `${tone.accent}${tone.bold}${unicode ? "›" : ">"}${tone.reset}` : " ";
575
+ const mark = a.active ? `${tone.ok}${g.pulse}${tone.reset}` : " ";
576
+ const num = `${a.active ? tone.bold : ""}${padStart(String(a.num), numW)}${tone.reset}`;
577
+ const house = !showHome ? "" : a.num === home ? `${tone.accent}${unicode ? "⌂" : "H"}${tone.reset} ` : " ";
578
+ const alias = pick.alias ? `${tone.accent}${padEnd(clip(aliasOf(a), aliasW, g.ellipsis), aliasW)}${tone.reset} ` : "";
579
+ const email = `${a.disabled ? tone.muted : ""}${padEnd(clip(emailOf(a), emailW, g.ellipsis), emailW)}${tone.reset}`;
580
+ const trouble = accountTrouble(a);
581
+ const status = trouble ? `${tone[trouble.tone]}${trouble.word}${tone.reset}` : laneCells(a, pick, labelW, look);
582
+ return `${pointer} ${mark} ${num} ${house}${alias}${email} ${status}`;
583
+ });
584
+ }
585
+
586
+ function laneCells(a, { kind, bar }, labelW, look) {
587
+ const { tone, g, now } = look;
588
+ const lanes = LANE_IDS.map(id => (a.lanes ?? []).find(l => l.id === id) ?? null);
589
+ if (!lanes.some(Boolean)) return `${tone.muted}${a.fetchedAt == null ? "not read yet" : "no usage reading"}${tone.reset}`;
590
+ return lanes.map(l => {
591
+ if (!l) return " ".repeat(laneWidth(kind, bar, labelW));
592
+ const head = `${tone.muted}${padEnd(oneLine(l.label), labelW)}${tone.reset} `;
593
+ const pct = `${pctTone(l.pct, tone)}${padStart(`${Math.round(l.pct)}%`, 4)}${tone.reset}`;
594
+ if (kind === "C") return `${head}${pct}`;
595
+ if (kind === "B") return `${head}${gauge(l.pct, bar, look)} ${pct}`;
596
+ const until = untilReset(l.resetAt, now);
597
+ return `${head}${gauge(l.pct, bar, look)} ${pct} ${tone.muted}${padEnd(until ? `${g.restart} ${until}` : "", 9)}${tone.reset}`;
598
+ }).join(" ");
599
+ }
600
+
601
+ /** What the trouble on an account means for a switch to it. */
602
+ const TROUBLE_SAYS = {
603
+ "sign-in needed": "its login has expired; enter signs it in again, keeping its slot, alias and history",
604
+ disabled: "kept out of Auto-switch's rotation; enter still switches to it",
605
+ "not collecting usage": "nothing has been read for it in half a day, so these are its last numbers",
606
+ };
607
+
608
+ /** The selected account at length: what it is, what is wrong, every lane. */
609
+ function detailPanel(a, home, width, look) {
610
+ const { tone, g, now } = look;
611
+ const sep = ` ${tone.muted}${g.bullet}${tone.reset} `;
612
+ const tags = [
613
+ a.active ? `${tone.ok}in use${tone.reset}` : "",
614
+ a.num === home ? `${tone.accent}home${tone.reset}` : "",
615
+ ].filter(Boolean);
616
+ const read = a.fetchedAt != null ? `${a.stale ? tone.warn : tone.muted}read ${sinceLabel(now - a.fetchedAt)} ago${tone.reset}` : "";
617
+ const note = [[...tags, read].filter(Boolean).join(sep), tags.join(sep)];
618
+ const title = `${tone.bold}${accountName(a)}${tone.reset}`;
619
+ const trouble = accountTrouble(a);
620
+ const said = trouble
621
+ ? wrap(`${trouble.word} ${g.dash} ${TROUBLE_SAYS[trouble.word] ?? ""}`, width).map(l => `${tone[trouble.tone]}${l}${tone.reset}`)
622
+ : [];
623
+ const lanes = a.lanes ?? [];
624
+ if (!lanes.length) {
625
+ return { title, note, lines: [...said, `${tone.muted}${a.fetchedAt == null ? "not read yet" : "no usage reading"}${tone.reset}`] };
626
+ }
627
+ const labelW = Math.max(2, ...lanes.map(l => textWidth(oneLine(l.label))));
628
+ const untils = lanes.map(l => untilReset(l.resetAt, now));
629
+ const untilW = Math.max(0, ...untils.map(u => u.length));
630
+ // The reset in words where it fits, as a mark where it does not, and not at
631
+ // all on a screen that would have to cut the meter for it.
632
+ const fixed = labelW + 2 + 5;
633
+ const words = untilW ? 3 + "resets in ".length + untilW : 0;
634
+ const mark = untilW ? 2 + 2 + untilW : 0;
635
+ const tail = width - fixed - words >= 12 ? words : width - fixed - mark >= 8 ? mark : 0;
636
+ const bar = Math.max(4, Math.min(40, width - fixed - tail));
637
+ return {
638
+ title,
639
+ note,
640
+ lines: [...said, ...lanes.map((l, i) => {
641
+ const u = untils[i];
642
+ const reset = !tail || !u ? "" : tail === words ? ` ${tone.muted}resets in ${u}${tone.reset}` : ` ${tone.muted}${g.restart} ${u}${tone.reset}`;
643
+ return `${tone.muted}${padEnd(oneLine(l.label), labelW)}${tone.reset} ${gauge(l.pct, bar, look)}`
644
+ + `${pctTone(l.pct, tone)}${padStart(`${Math.round(l.pct)}%`, 5)}${tone.reset}${reset}`;
645
+ })],
646
+ };
647
+ }
648
+
649
+ const NEXT_WORDS = { room: "most room", weekly: "soonest weekly reset" };
650
+
651
+ /** Auto-switch in the list's bottom border, longest first. */
652
+ function autoSummary(state, { tone, g }) {
653
+ const auto = state.deck ? state.auto : null;
654
+ if (!auto || auto.ok === false) return "";
655
+ const sep = ` ${g.bullet} `;
656
+ const external = auto.external ? `${sep}${tone.warn}your own cswap auto is running${tone.reset}` : "";
657
+ if (auto.enabled !== true) return [`${tone.muted}Auto-switch off${tone.reset}${external}`, `${tone.muted}Auto-switch off${tone.reset}`, `${tone.muted}auto off${tone.reset}`];
658
+ const threshold = Number(auto.settings?.["autoswitch.threshold"]?.value);
659
+ const parts = [Number.isFinite(threshold) ? `at ${Math.round(threshold)}%` : "", `next: ${NEXT_WORDS[auto.choice?.next] ?? NEXT_WORDS.room}`].filter(Boolean);
660
+ const on = `${tone.muted}Auto-switch${tone.reset} ${tone.ok}on${tone.reset}`;
661
+ return [
662
+ `${on}${tone.muted}${sep}${parts.join(sep)}${tone.reset}${external}`,
663
+ `${on}${tone.muted}${sep}${parts.join(sep)}${tone.reset}`,
664
+ `${on}${parts[0] && parts.length > 1 ? `${tone.muted}${sep}${parts[0]}${tone.reset}` : ""}`,
665
+ on,
666
+ `${tone.muted}auto${tone.reset} ${tone.ok}on${tone.reset}`,
667
+ ];
668
+ }
669
+
670
+ function waitingOf(state) {
671
+ if (!state.deck || !Array.isArray(state.sessions)) return { read: false, list: [], working: 0, skew: 0 };
672
+ // The one waiting longest first: it is the one most likely to have stopped
673
+ // someone's work.
674
+ const list = state.sessions.filter(s => s.state === "waiting")
675
+ .sort((x, y) => (x.since ?? x.lastEventAt ?? 0) - (y.since ?? y.lastEventAt ?? 0));
676
+ const working = state.sessions.filter(s => s.state === "working").length;
677
+ return { read: true, list, working, skew: state.skew ?? 0 };
678
+ }
679
+
680
+ /** The sessions waiting on you, the first `max` of them, the question under
681
+ * each while `asks`; or what stands in for them with no deck. */
682
+ function sessionsPanel(state, waiting, { max, asks, width }, look) {
683
+ const { tone, g, now } = look;
684
+ const plain = (toneCode, text) => wrap(text, width).map(l => `${toneCode}${l}${tone.reset}`);
685
+ const sessionsTitle = `${tone.bold}Sessions${tone.reset}`;
686
+ if (!state.deck) {
687
+ const lines = state.starting ? plain(tone.muted, `starting the deck${g.ellipsis}`)
688
+ : state.silent.length ? plain(tone.warn, `the deck on ${state.silent.map(d => d.port).join(", ")} is running but did not answer`)
689
+ : state.source === "local" ? plain(tone.muted, `no deck is running ${g.dash} d starts one in the background`)
690
+ : plain(tone.muted, `looking for the deck${g.ellipsis}`);
691
+ return { title: sessionsTitle, lines };
692
+ }
693
+ if (!waiting.read) return { title: sessionsTitle, lines: plain(tone.muted, `reading the sessions${g.ellipsis}`) };
694
+ const working = waiting.working ? `${tone.muted}${waiting.working} working${tone.reset}` : "";
695
+ if (!waiting.list.length) return { title: sessionsTitle, note: working, lines: plain(tone.muted, "nobody is waiting on you") };
696
+ const shown = waiting.list.slice(0, max);
697
+ const more = waiting.list.length - shown.length;
698
+ return {
699
+ title: `${tone.warn}${tone.bold}Waiting on you${tone.reset} ${tone.muted}${g.bullet} ${waiting.list.length}${tone.reset}`,
700
+ note: working,
701
+ footLeft: more > 0 ? [`${tone.muted}${more} more ${g.dash} ccdeck sessions${tone.reset}`, `${tone.muted}${more} more${tone.reset}`] : "",
702
+ lines: waitingRows(shown, { asks, width, now: now + waiting.skew }, look),
703
+ };
704
+ }
705
+
706
+ /** One row a session — the mark, how long it has waited, its name, the agent —
707
+ * and its question under the name, in its own words. */
708
+ function waitingRows(list, { asks, width, now }, { tone, g }) {
709
+ const label = (s) => oneLine(s.name) || oneLine(s.project) || oneLine(s.id).slice(0, 8);
710
+ const ages = list.map(s => sinceLabel(now - (s.since ?? s.lastEventAt ?? now)));
711
+ const ageW = Math.max(...ages.map(a => a.length));
712
+ const lead = textWidth(g.warn) + 2 + ageW + 2;
713
+ const agentOf = (s) => (s.provider === "codex" ? "Codex" : "Claude");
714
+ // The agent column gives way first — the model, then the agent — so the
715
+ // name, which is how a person tells two sessions apart, keeps its room.
716
+ const tails = [
717
+ (s) => `${agentOf(s)}${shortModel(s.model) ? ` ${g.bullet} ${shortModel(s.model)}` : ""}`,
718
+ (s) => agentOf(s),
719
+ () => "",
720
+ ];
721
+ const longest = Math.max(...list.map(s => textWidth(label(s))));
722
+ const tailOf = tails.find(t => width - lead - 2 - Math.max(...list.map(s => textWidth(t(s)))) >= Math.min(longest, 12)) ?? tails[2];
723
+ const tailW = Math.max(...list.map(s => textWidth(tailOf(s))));
724
+ const labelW = Math.max(1, Math.min(longest, width - lead - (tailW ? tailW + 2 : 0)));
725
+ const out = [];
726
+ list.forEach((s, i) => {
727
+ const tail = tailOf(s);
728
+ const named = padEnd(clip(label(s), labelW, g.ellipsis), labelW);
729
+ out.push(`${tone.warn}${g.warn}${tone.reset} ${tone.muted}${padStart(ages[i], ageW)}${tone.reset} ${tone.bold}${named}${tone.reset}`
730
+ + `${tail ? ` ${tone.muted}${tail}${tone.reset}` : ""}`);
731
+ if (!asks) return;
732
+ const what = oneLine(s.waiting?.message) || (s.waiting?.kind === "asked" ? "asked a question" : "needs your permission");
733
+ // The tool the prompt is most likely about, unless Claude Code's own
734
+ // sentence already names it — "permission to use Bash (Bash)" says
735
+ // nothing twice over.
736
+ const tool = oneLine(s.waiting?.tool);
737
+ const toolText = tool && !what.includes(tool) ? ` (${tool})` : "";
738
+ const room = Math.max(8, width - lead - textWidth(toolText));
739
+ out.push(`${" ".repeat(lead)}${clip(what, room, g.ellipsis)}${toolText ? `${tone.muted}${toolText}${tone.reset}` : ""}`);
740
+ });
741
+ return out;
742
+ }
743
+
744
+ // ── adding an account ───────────────────────────────────────────────────────
745
+ //
746
+ // The deck's own sign-in (cswap-admin.mjs startLogin), the one the Accounts
747
+ // panel's Add dialog drives (AddAccountDialog.tsx, signin-stages.ts):
748
+ // `claude auth login` on this machine prints a link, the person approves it in
749
+ // a browser, and either the CLI hears back by itself — a browser on this
750
+ // machine reaches its loopback port — or the page shows a code, which is typed
751
+ // or pasted here. Over SSH it is the code. The deck does the rest: who signed
752
+ // in, `cswap add`, and the account in use put back in front.
753
+
754
+ /** The sign-in page before anything is asked: a new account, or `email`'s
755
+ * expired login signed in again in place. `login` is the deck's
756
+ * loginState() once it has one. */
757
+ export function openSignin(email = null) {
758
+ return { email, started: false, login: null, code: "", sending: false, lastLive: null };
759
+ }
760
+
761
+ /** The stages, in order (signin-stages.ts), and where `registering`'s steps
762
+ * sit among them. */
763
+ export const SIGNIN_STAGES = Object.freeze(["link", "approve", "confirm", "save"]);
764
+ const STEP_STAGE = Object.freeze({ confirm: "confirm", save: "save", restore: "save" });
765
+
766
+ /**
767
+ * Where a started sign-in is, from the deck's own state: `{ live }` while it
768
+ * runs, `{ failed }` once it stopped, `{ done: true }`. A flow the deck no
769
+ * longer has (`idle`) ended at the stage last seen (`vanished`).
770
+ */
771
+ export function signinStage(si) {
772
+ const login = si?.login;
773
+ switch (login?.state) {
774
+ case "done": return { done: true };
775
+ case "failed": return { failed: STEP_STAGE[login.step] ?? (login.url ? "approve" : "link") };
776
+ case "idle": return { failed: si.lastLive ?? "link", vanished: true };
777
+ case "registering": return { live: STEP_STAGE[login.step] ?? "confirm" };
778
+ case "awaiting_code": return { live: "approve" };
779
+ default: return { live: "link" };
780
+ }
781
+ }
782
+
783
+ /** The deck's answer in place of the last, keeping the stage it was at, so a
784
+ * flow that vanishes can still say where. */
785
+ export function withLogin(state, login) {
786
+ const si = state.signin;
787
+ if (!si?.started) return state;
788
+ const next = { ...si, login };
789
+ return { ...state, signin: { ...next, lastLive: signinStage(next).live ?? si.lastLive } };
790
+ }
791
+
792
+ /** Whether the deck is still at it: what the app asks about, and what leaving
793
+ * has to cancel. */
794
+ export function signinRunning(si) {
795
+ return Boolean(si?.started) && Boolean(signinStage(si).live);
796
+ }
797
+
798
+ /** How often the deck is asked where the sign-in is: a person reading a
799
+ * consent page, or three short commands (signin-stages.ts loginPollMs). */
800
+ export function signinPollMs(si) {
801
+ return si?.login?.state === "registering" ? 400 : 1_500;
802
+ }
803
+
804
+ /** The longest code taken: the CLI's is well under it, a paste of a page is not. */
805
+ const CODE_MAX = 1_024;
806
+
807
+ function signinKey(state, str, key, { now, g }) {
808
+ const si = state.signin;
809
+ const name = key.name ?? "";
810
+ const enter = name === "return" || name === "enter";
811
+ const back = name === "escape" || str === "q";
812
+ const stay = { state, effect: null };
813
+ const close = (effect = null) => ({ state: { ...state, signin: null }, effect });
814
+ if (!si.started) {
815
+ if (enter) return { state, effect: { type: "signin-start" } };
816
+ return back ? close() : stay;
817
+ }
818
+ const at = signinStage(si);
819
+ if (at.done) return enter || back ? close({ type: "signin-done", account: si.login?.account ?? null }) : stay;
820
+ if (at.failed) {
821
+ if (enter) return { state, effect: { type: "signin-start" } };
822
+ // The deck may still hold the flow that failed. Letting go of it is what
823
+ // the panel's dialog does on every way out but a success (login-flow.ts) —
824
+ // unless the deck never started ours (`local`), when the only sign-in it
825
+ // holds is somebody else's.
826
+ if (!back) return stay;
827
+ return close(si.login?.local ? null : { type: "signin-cancel", quiet: true });
828
+ }
829
+ if (name === "escape") {
830
+ // Past the code the deck is writing the account, and the dialog offers no
831
+ // cancel there either: stopping half-way is how a store loses a record.
832
+ if (at.live === "confirm" || at.live === "save") {
833
+ return { state: { ...state, notice: note("info", `saving the account ${g.dash} a moment`, now) }, effect: null };
834
+ }
835
+ return close({ type: "signin-cancel" });
836
+ }
837
+ // The code's field: q and every other letter are its characters here.
838
+ if (at.live !== "approve") return stay;
839
+ const edit = (code) => ({ state: { ...state, signin: { ...si, code } }, effect: null });
840
+ if (enter) {
841
+ const code = si.code.trim();
842
+ if (!code || si.sending) return stay;
843
+ return { state: { ...state, signin: { ...si, sending: true } }, effect: { type: "signin-code", code } };
844
+ }
845
+ if (name === "backspace") return edit([...si.code].slice(0, -1).join(""));
846
+ if (key.ctrl && name === "u") return edit("");
847
+ // A code is printable ASCII with no spaces; anything else is a key that
848
+ // means nothing here rather than a character of it.
849
+ if (str && !key.ctrl && !key.meta && /^[\x21-\x7e]+$/.test(str)) return edit((si.code + str).slice(0, CODE_MAX));
850
+ return stay;
851
+ }
852
+
853
+ /** The page's keys, for the footer. */
854
+ function signinKeys(si) {
855
+ if (!si.started) return [["enter", "get the sign-in link"], ["esc", "back"]];
856
+ const at = signinStage(si);
857
+ if (at.done) return [["enter", "done"]];
858
+ if (at.failed) return [["enter", "try again"], ["esc", "back"]];
859
+ if (at.live === "approve") return [["enter", "send the code"], ["esc", "cancel"]];
860
+ if (at.live === "link") return [["esc", "cancel"]];
861
+ return [];
862
+ }
863
+
864
+ /** Each stage's words: still to come, under way, done (signin-stages.ts). */
865
+ const STAGE_WORDS = Object.freeze({
866
+ link: ["Get a sign-in link", "Asking the claude CLI for a sign-in link", "Sign-in link ready"],
867
+ approve: ["Approve in your browser", "Waiting for you to approve in the browser", "Approved in the browser"],
868
+ confirm: ["Confirm who signed in", "Confirming who signed in", "Sign-in confirmed"],
869
+ save: ["Save the credentials", "Saving the credentials", "Credentials saved"],
870
+ });
871
+ const STAGE_FAILED = Object.freeze({
872
+ link: "No sign-in link came",
873
+ approve: "The sign-in did not finish in the browser",
874
+ confirm: "The sign-in could not be confirmed",
875
+ save: "claude-swap could not save the account",
876
+ });
877
+ /** login-flow.ts LOGIN_VANISHED, for a sign-in the deck no longer has. */
878
+ const SIGNIN_VANISHED = "the sign-in ended before it finished — the deck restarted, or it was cancelled elsewhere";
879
+
880
+ /** A link the page may draw edge to edge: https, and nothing in it a
881
+ * terminal could read as anything but a character. */
882
+ const safeLink = (url) => (typeof url === "string" && /^https:\/\/[\x21-\x7e]+$/.test(url) ? url : null);
883
+
884
+ /** A reason as a sentence: a capital unless it opens on a lower-case name. */
885
+ function sentence(text) {
886
+ const t = String(text ?? "").trim();
887
+ if (!t) return "";
888
+ const head = /^(?:claude|claude-swap|cswap|ccdeck)\b/.test(t) ? t : t[0].toUpperCase() + t.slice(1);
889
+ return /[.!?…]$/.test(head) ? head : `${head}.`;
890
+ }
891
+
892
+ /** login-flow.ts restoreWarning: the account in use did not go back. */
893
+ function restoreWarning(login, g) {
894
+ if (login?.restored !== false) return null;
895
+ const a = login.activeAccount;
896
+ const who = oneLine(a?.email) || (a?.num != null ? `account ${a.num}` : null);
897
+ return who
898
+ ? `This machine is now signed in as ${who} ${g.dash} the account you were using could not be put back. Switch back from the list.`
899
+ : `The account you were using could not be put back ${g.dash} check which account is in use in the list.`;
900
+ }
901
+
902
+ /**
903
+ * The page, `room` rows: the stages in a panel and under it what the person
904
+ * does next — on the approve stage the link, edge to edge, and the code's
905
+ * field. What gives way on a short screen is the explaining, then the panel;
906
+ * the link and the field go last.
907
+ */
908
+ function signinLines(state, room, width, columns, look) {
909
+ const { tone, g, unicode, now, links } = look;
910
+ const si = state.signin;
911
+ const inner = width - 4;
912
+ // Everything the deck wrote — an address, the CLI's own last words — on one
913
+ // line, with nothing in it a terminal could take for an instruction.
914
+ const email = oneLine(si.email);
915
+ const error = oneLine(si.login?.error);
916
+ const title = `${tone.bold}${email ? "Sign in again" : "Add a Claude account"}${tone.reset}`;
917
+ const say = (text, t = tone.muted) => wrap(text, width - 2).map(l => ` ${t}${l}${tone.reset}`);
918
+ const out = (lines, run = null) => ({ lines: [...lines, ...pad(room - lines.length)].slice(0, room), run });
919
+
920
+ if (!si.started) {
921
+ const what = email
922
+ ? `claude-swap replaces the expired login in place ${g.dash} the account keeps its slot, its alias and its history ${g.dash} and the account you use now stays active.`
923
+ : "claude-swap records the account, and the account you use now stays active.";
924
+ const lines = [
925
+ `${tone.bold}${email ? `Sign in again as ${email}` : "Sign in to Anthropic"}${tone.reset}`,
926
+ "",
927
+ ...wrap("The claude CLI on this machine makes a sign-in link to open in any browser. If that browser runs on this machine, the sign-in finishes by itself; anywhere else the page shows a code to paste here.", inner),
928
+ "",
929
+ ...wrap(what, inner),
930
+ ].map((l, i) => (i ? `${tone.muted}${l}${tone.reset}` : l));
931
+ return out(panel(width, Math.min(room, lines.length + 2), { title, lines }, look));
932
+ }
933
+
934
+ const at = signinStage(si);
935
+ const frames = spinnerFrames(unicode);
936
+ const spin = frames[Math.floor(now / 100) % frames.length];
937
+ const stages = SIGNIN_STAGES.map((id, i) => {
938
+ const pos = at.done ? SIGNIN_STAGES.length : SIGNIN_STAGES.indexOf(at.live ?? at.failed);
939
+ const [later, under, did] = STAGE_WORDS[id];
940
+ if (i < pos) return `${tone.ok}${g.ok}${tone.reset} ${tone.muted}${did}${tone.reset}`;
941
+ if (i > pos) return `${tone.muted}${unicode ? "·" : "."} ${later}${tone.reset}`;
942
+ if (at.failed) return `${tone.err}${g.fail} ${at.vanished ? "Sign-in ended" : STAGE_FAILED[id]}${tone.reset}`;
943
+ return `${tone.accent}${spin}${tone.reset} ${under}`;
944
+ });
945
+ const left = at.live === "approve" && typeof si.login?.expiresAt === "number"
946
+ ? Math.ceil((si.login.expiresAt - (now + (state.skew ?? 0))) / 60_000) : null;
947
+ const clock = left >= 1 && left <= 5 ? `${tone.muted}${left} min left${tone.reset}` : "";
948
+ const box = panel(width, stages.length + 2, { title, note: clock, lines: stages }, look);
949
+
950
+ if (at.done) {
951
+ const acc = si.login?.account ?? {};
952
+ const warn = restoreWarning(si.login, g);
953
+ const headline = acc.added === false ? "Credentials refreshed" : acc.num != null ? `Account ${acc.num} added` : "Account added";
954
+ const who = oneLine(acc.email) || "the account";
955
+ const lines = [
956
+ ...box, "",
957
+ ` ${tone.ok}${g.ok}${tone.reset} ${tone.bold}${headline}${tone.reset}`,
958
+ ...say(acc.added === false
959
+ ? `${who} was already in the rotation, so its stored login was replaced with this one.`
960
+ : warn ? `${who} is in the rotation.` : `${who} is in the rotation. The account you were using is still active.`),
961
+ ...(warn ? say(warn, tone.warn) : []),
962
+ ];
963
+ return out(lines);
964
+ }
965
+ if (at.failed) {
966
+ return out([...box, "", ...say(sentence(at.vanished ? SIGNIN_VANISHED : error || "the deck gave no reason"))]);
967
+ }
968
+ if (at.live !== "approve") {
969
+ const doing = {
970
+ link: "Asking the claude CLI on this machine for a sign-in link.",
971
+ confirm: "Asking the claude CLI which account just signed in.",
972
+ save: si.login?.step === "restore" ? "Switching this machine back to the account you were using." : "claude-swap is recording the account.",
973
+ }[at.live];
974
+ return out([...box, "", ...say(doing)]);
975
+ }
976
+
977
+ // The link, and the field for the code the page shows.
978
+ const url = safeLink(si.login?.url);
979
+ const caret = unicode ? "▏" : "_";
980
+ const shown = si.code.length > width - 8 ? `${g.ellipsis}${si.code.slice(-(width - 9))}` : si.code;
981
+ const field = si.sending
982
+ ? ` ${tone.accent}${unicode ? "›" : ">"}${tone.reset} ${shown} ${tone.muted}sending the code${g.ellipsis}${tone.reset}`
983
+ : ` ${tone.accent}${unicode ? "›" : ">"}${tone.reset} ${shown}${tone.accent}${caret}${tone.reset}`;
984
+ const refused = !si.sending && error
985
+ ? wrap(error, width - 5).map((l, i) => ` ${tone.err}${i ? " " : `${g.fail} `}${l}${tone.reset}`) : [];
986
+ const pieces = [];
987
+ if (url) for (let i = 0; i < url.length; i += columns) pieces.push(url.slice(i, i + columns));
988
+ const blocks = {
989
+ box: [...box, ""],
990
+ open: say("Open this link in any browser and approve the sign-in:", ""),
991
+ link: url ? pieces : say(`the deck's sign-in link could not be shown ${g.dash} sign in from its Accounts panel`, tone.warn),
992
+ gap: [""],
993
+ paste: say("If that browser runs on this machine, this finishes by itself. Anywhere else the page shows a code: paste it here and press enter."),
994
+ field: [field, ...refused],
995
+ kept: say("The code goes only to the claude CLI on this machine, and is not kept."),
996
+ };
997
+ const order = ["box", "open", "link", "gap", "paste", "field", "kept"];
998
+ const shownBlocks = new Set(order);
999
+ const height = () => order.filter(b => shownBlocks.has(b)).reduce((n, b) => n + blocks[b].length, 0);
1000
+ for (const drop of ["kept", "gap", "paste", "box", "open"]) {
1001
+ if (height() <= room) break;
1002
+ shownBlocks.delete(drop);
1003
+ }
1004
+ // A link that does not fit whole is no link at all: say so instead.
1005
+ if (height() > room) blocks.link = say(`make the window taller to see the sign-in link ${g.dash} it needs ${pieces.length} rows`, tone.warn);
1006
+ const lines = [];
1007
+ let run = null;
1008
+ for (const b of order) {
1009
+ if (!shownBlocks.has(b)) continue;
1010
+ if (b === "link" && url && blocks.link === pieces) {
1011
+ run = { row: lines.length, rows: pieces.length, full: url.length % columns === 0, text: `${tone.accent}${link(url, url, links)}${tone.reset}` };
1012
+ }
1013
+ lines.push(...blocks[b]);
1014
+ }
1015
+ return out(lines, run && run.row + run.rows <= room ? run : null);
1016
+ }
1017
+
1018
+ // ── help ────────────────────────────────────────────────────────────────────
1019
+
1020
+ /** The keys, in a box over the screen, the screen under it faded. */
1021
+ function withHelp(base, width, look) {
1022
+ const { tone, g, unicode, skin } = look;
1023
+ const keys = [
1024
+ [unicode ? "↑ ↓ j k" : "up down j k", "move"],
1025
+ ["1-9", "the account in that slot"],
1026
+ ["enter s", "switch to the selected account, or sign it in again"],
1027
+ ["b", "select the account Auto-switch would pick"],
1028
+ ["a", "turn Auto-switch on or off"],
1029
+ ["+", "add a Claude account, signed in from any browser"],
1030
+ ["r", "read the usage again"],
1031
+ ["d", "start the deck, when none is running"],
1032
+ ["ctrl+l", "draw the screen again"],
1033
+ ["q esc", "quit"],
1034
+ ];
1035
+ const marks = [
1036
+ [g.pulse, "the account in use"],
1037
+ [unicode ? "⌂" : "H", "Auto-switch's home account"],
1038
+ ];
1039
+ const boxW = Math.min(width - 2, 66);
1040
+ const inner = boxW - 4;
1041
+ const keyW = Math.max(...keys.map(([k]) => textWidth(k))) + 3;
1042
+ const entry = ([k, what]) => wrap(what, Math.max(8, inner - keyW))
1043
+ .map((part, i) => `${tone.bold}${padEnd(i ? "" : k, keyW)}${tone.reset}${tone.muted}${part}${tone.reset}`);
1044
+ const lines = [
1045
+ ...keys.flatMap(entry),
1046
+ "",
1047
+ ...marks.flatMap(entry),
1048
+ "",
1049
+ ...wrap("A switch moves the live Claude login. Every running Claude session uses the new account from its next message.", inner)
1050
+ .map(l => `${tone.muted}${l}${tone.reset}`),
1051
+ ];
1052
+ const height = Math.min(base.length - 2, lines.length + 2);
1053
+ const box = panel(boxW, height, { title: `${tone.bold}Keys${tone.reset}`, footRight: `${tone.muted}any key closes${tone.reset}`, lines }, look);
1054
+ const x = Math.floor((width - boxW) / 2);
1055
+ const y = Math.max(1, Math.floor((base.length - height) / 2));
1056
+ const faded = (s) => (s && skin.faded ? `${skin.faded}${s}${tone.reset}` : s);
1057
+ return base.map((line, i) => {
1058
+ const plain = stripAnsi(line);
1059
+ if (i < y || i >= y + height) return faded(plain);
1060
+ return `${faded(sliceCells(plain, 0, x))}${onBg(box[i - y], skin.raised)}${faded(sliceCells(plain, x + boxW, width))}`;
1061
+ });
1062
+ }
1063
+
1064
+ function wrap(text, width) {
1065
+ const out = [];
1066
+ let line = "";
1067
+ for (const word of text.split(" ")) {
1068
+ if (line && textWidth(`${line} ${word}`) > width) { out.push(line); line = word; } else line = line ? `${line} ${word}` : word;
1069
+ }
1070
+ if (line) out.push(line);
1071
+ return out;
1072
+ }