ccdeck 3.47.0 → 3.48.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.
- package/README.md +28 -4
- package/bin/cli/commands.js +17 -9
- package/bin/cli/help.js +9 -4
- package/bin/cli/second-start.js +4 -2
- package/bin/cli/startup.js +3 -2
- package/bin/cli/tui.js +544 -0
- package/dist/web/assets/BrowserWatchModal-Dfsuy2cT.js +1 -0
- package/dist/web/assets/IntegrationModal-CcSR7YB-.js +7 -0
- package/dist/web/assets/{RadioPanel-DbmJJPsz.js → RadioPanel-s7WXdS6v.js} +1 -1
- package/dist/web/assets/{TrafficRadar-CPjAXd5e.js → TrafficRadar-C5GXMIwi.js} +1 -1
- package/dist/web/assets/UsageHistoryModal-CiExD9wF.js +1 -0
- package/dist/web/assets/app-BFaxhiED.js +321 -0
- package/dist/web/assets/app-DjlHxWHg.css +1 -0
- package/dist/web/assets/{index-Ca87aJP9.js → index-ByovgZ_7.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +30 -3
- package/src/server/args.mjs +1 -0
- package/src/server/cli-lines.mjs +46 -0
- package/src/server/deck-prefs.mjs +23 -13
- package/src/server/gpu-metrics.mjs +78 -0
- package/src/server/integrations/jira-move.mjs +239 -0
- package/src/server/integrations/jira.mjs +30 -8
- package/src/server/integrations/proxy.mjs +3 -4
- package/src/server/integrations/routes.mjs +19 -5
- package/src/server/lan-deck.mjs +2 -1
- package/src/server/system-metrics.mjs +4 -0
- package/src/server/term.mjs +14 -5
- package/src/server/tui-screen.mjs +110 -0
- package/src/server/tui-view.mjs +1072 -0
- package/src/server/way-back.mjs +27 -0
- package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +0 -1
- package/dist/web/assets/IntegrationModal-8tTi25gA.js +0 -6
- package/dist/web/assets/UsageHistoryModal-qfmvXdWJ.js +0 -1
- package/dist/web/assets/app-BFFG6Wz8.js +0 -321
- package/dist/web/assets/app-DfcfHvcX.css +0 -1
package/bin/cli/tui.js
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
// `ccdeck tui`: the deck's accounts and the sessions waiting on you, on one
|
|
2
|
+
// screen that stays up, for somebody who reached the machine over SSH.
|
|
3
|
+
//
|
|
4
|
+
// The one-shot commands (commands.js) answer and leave. This keeps the answer
|
|
5
|
+
// on screen and lets the next question be a key: move to an account, Enter
|
|
6
|
+
// switches to it, b selects what Auto-switch would pick, a turns Auto-switch on
|
|
7
|
+
// or off. It is a CLIENT of the running deck, as they are, and asks it through
|
|
8
|
+
// their own helpers — so a switch from here takes the deck's route, its store
|
|
9
|
+
// lock and its refusals, and a deck that is alive but silent is never switched
|
|
10
|
+
// behind. With no deck it reads claude-swap's store, as `ccdeck accounts` does,
|
|
11
|
+
// and offers to start one.
|
|
12
|
+
//
|
|
13
|
+
// What it does not do: start, attach to, resume or stop an agent. That is the
|
|
14
|
+
// Command Panel's, and a second way of doing it here would be a second set of
|
|
15
|
+
// rules to keep in step.
|
|
16
|
+
//
|
|
17
|
+
// The view and the keys are pure (src/server/tui-view.mjs) and the painting is
|
|
18
|
+
// a row diff over the alternate screen (src/server/tui-screen.mjs). This file is
|
|
19
|
+
// the rest: the readings, on a timer each, the effects a key asks for, and the
|
|
20
|
+
// terminal handed back on every way out — q, a signal, a closed connection, a
|
|
21
|
+
// throw.
|
|
22
|
+
import { spawn } from "node:child_process";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
import { emitKeypressEvents } from "node:readline";
|
|
25
|
+
import {
|
|
26
|
+
EXIT, ask, autoRules, deckTrouble, load, rosterTrouble, silentDecks, switchHere, switchThroughDeck,
|
|
27
|
+
} from "./commands.js";
|
|
28
|
+
import { oneLine } from "../../src/server/cli-lines.mjs";
|
|
29
|
+
import { stripAnsi } from "../../src/server/term.mjs";
|
|
30
|
+
import { COMMAND, PKG_ROOT } from "./package.js";
|
|
31
|
+
import { G, LINKS, P, PROFILE, UNICODE } from "./screen.js";
|
|
32
|
+
|
|
33
|
+
/** How often each reading is taken while the screen is up. The sessions are
|
|
34
|
+
* the ones a person is waiting to see change; the roster is the deck's own
|
|
35
|
+
* 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
|
+
|
|
38
|
+
/** How long a deck started from here is waited for before saying it did not
|
|
39
|
+
* come up. A first run installs hooks and claude-swap before it listens. */
|
|
40
|
+
export const START_WAIT_MS = 90_000;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Run the screen until q, resolving to the exit code. `deps` replaces the
|
|
44
|
+
* terminal, the clock and the deck for a test: `input`, `output`, `now`,
|
|
45
|
+
* `source` (see deckSource), `tone`, `g`, `unicode`, `profile`, `links`,
|
|
46
|
+
* `tickMs`.
|
|
47
|
+
*/
|
|
48
|
+
export async function runTui(flags, out, deps = {}) {
|
|
49
|
+
const input = deps.input ?? process.stdin;
|
|
50
|
+
const output = deps.output ?? process.stdout;
|
|
51
|
+
if (out.json) {
|
|
52
|
+
return out.fail(EXIT.USAGE, "interactive_only", [
|
|
53
|
+
`\`${COMMAND} tui\` is a screen for a person ${G.dash} \`${COMMAND} accounts --json\` and \`${COMMAND} sessions --json\` are the ones for a script`,
|
|
54
|
+
]);
|
|
55
|
+
}
|
|
56
|
+
if (!input.isTTY || !output.isTTY) {
|
|
57
|
+
return out.fail(EXIT.USAGE, "not_a_terminal", [
|
|
58
|
+
`\`${COMMAND} tui\` needs a terminal at both ends ${G.dash} \`${COMMAND} accounts\` and \`${COMMAND} sessions\` print the same thing once`,
|
|
59
|
+
]);
|
|
60
|
+
}
|
|
61
|
+
const view = await load("src/server/tui-view.mjs");
|
|
62
|
+
const { createScreen } = await load("src/server/tui-screen.mjs");
|
|
63
|
+
const { accountName, bestAccount } = await load("src/server/account-pick.mjs");
|
|
64
|
+
const port = flags.port != null ? Number(flags.port) : null;
|
|
65
|
+
const src = deps.source ?? deckSource(port);
|
|
66
|
+
const look = {
|
|
67
|
+
tone: deps.tone ?? P, g: deps.g ?? G, unicode: deps.unicode ?? UNICODE, profile: deps.profile ?? PROFILE, links: deps.links ?? LINKS,
|
|
68
|
+
};
|
|
69
|
+
const g = look.g;
|
|
70
|
+
const clock = deps.now ?? Date.now;
|
|
71
|
+
|
|
72
|
+
// The deck is looked for before the screen is taken, so a `--port` nobody
|
|
73
|
+
// listens on is answered on the command line, the way the commands answer it.
|
|
74
|
+
let deck = await src.find();
|
|
75
|
+
if (!deck && port != null) {
|
|
76
|
+
return out.fail(EXIT.NO_DECK, "no_deck", `no deck is listening on ${port} ${G.dash} \`${COMMAND} status\` lists them`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
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() };
|
|
81
|
+
const inflight = new Set();
|
|
82
|
+
const screen = createScreen(s => output.write(s));
|
|
83
|
+
let done = null;
|
|
84
|
+
|
|
85
|
+
const set = (patch) => { state = { ...state, ...patch }; };
|
|
86
|
+
const tell = (tone, text) => set({ notice: view.note(tone, text, clock()) });
|
|
87
|
+
const size = () => ({
|
|
88
|
+
columns: Number.isInteger(output.columns) && output.columns > 0 ? output.columns : 80,
|
|
89
|
+
rows: Number.isInteger(output.rows) && output.rows > 0 ? output.rows : 24,
|
|
90
|
+
});
|
|
91
|
+
const render = () => {
|
|
92
|
+
if (done) return;
|
|
93
|
+
const frame = view.tuiFrame(state, { ...size(), ...look, now: clock() });
|
|
94
|
+
if (frame.top !== state.top) set({ top: frame.top });
|
|
95
|
+
screen.paint(frame.lines, frame.run);
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** One reading at a time of each kind: a slow deck answers late, not twice.
|
|
99
|
+
* Timed from when it was asked, so a reading that finds the deck gone can
|
|
100
|
+
* make the next one due at once (`lost`). */
|
|
101
|
+
const once = (kind, work) => async (...args) => {
|
|
102
|
+
if (inflight.has(kind)) return;
|
|
103
|
+
inflight.add(kind);
|
|
104
|
+
last[kind] = clock();
|
|
105
|
+
try { await work(...args); } catch (e) {
|
|
106
|
+
if (READINGS[kind]) tell("err", `could not read ${READINGS[kind]} ${g.dash} ${e?.message ?? e}`);
|
|
107
|
+
} finally {
|
|
108
|
+
inflight.delete(kind);
|
|
109
|
+
render();
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** The deck stopped answering: back to looking for one, and to the store
|
|
114
|
+
* in the meantime. */
|
|
115
|
+
const lost = () => {
|
|
116
|
+
deck = null;
|
|
117
|
+
set({ deck: null, auto: null, sessions: null });
|
|
118
|
+
// A sign-in lives in the deck; one that stopped answering took it along.
|
|
119
|
+
if (view.signinRunning(state.signin)) {
|
|
120
|
+
state = view.withLogin(state, { state: "failed", error: "the deck stopped answering, and the sign-in ended with it", local: true });
|
|
121
|
+
}
|
|
122
|
+
last.find = 0;
|
|
123
|
+
last.roster = 0;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const readRoster = once("roster", async (force = false) => {
|
|
127
|
+
if (deck) {
|
|
128
|
+
const r = await src.ask(deck, { path: force ? "/api/claude-accounts?refresh=1" : "/api/claude-accounts" });
|
|
129
|
+
if (r.ok && r.body) {
|
|
130
|
+
state = view.withRoster(state, r.body, r.body.ok ? null : [].concat(rosterTrouble(r.body)));
|
|
131
|
+
set({ source: "deck", silent: [], readAt: clock() });
|
|
132
|
+
} else if (r.status === 0) lost();
|
|
133
|
+
else tell("err", deckTrouble(deck, r));
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const silent = await src.silent();
|
|
137
|
+
const roster = await src.localRoster();
|
|
138
|
+
state = view.withRoster(state, roster, roster?.ok ? null : [].concat(rosterTrouble(roster)));
|
|
139
|
+
set({ source: "local", silent });
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const readAuto = once("auto", async () => {
|
|
143
|
+
if (!deck) return;
|
|
144
|
+
const r = await src.ask(deck, { path: "/api/cswap-auto" });
|
|
145
|
+
if (r.ok && r.body && typeof r.body === "object") set({ auto: r.body, readAt: clock() });
|
|
146
|
+
else if (r.status === 0) lost();
|
|
147
|
+
else set({ auto: null });
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const readSessions = once("sessions", async () => {
|
|
151
|
+
if (!deck) return;
|
|
152
|
+
const r = await src.ask(deck, { path: "/api/sessions", timeoutMs: 3_000 });
|
|
153
|
+
if (r.ok && Array.isArray(r.body?.sessions)) {
|
|
154
|
+
set({ sessions: r.body.sessions, skew: typeof r.body.now === "number" ? r.body.now - clock() : 0, readAt: clock() });
|
|
155
|
+
} else if (r.status === 0) lost();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// Where the deck's sign-in is, while the page is up and the deck has one —
|
|
159
|
+
// never before the start was answered, when "idle" would only mean "not yet".
|
|
160
|
+
const readSignin = once("signin", async () => {
|
|
161
|
+
if (!deck || !state.signin?.login) return;
|
|
162
|
+
const r = await src.ask(deck, { path: "/api/claude-accounts/login" });
|
|
163
|
+
if (r.ok && typeof r.body?.state === "string" && view.signinRunning(state.signin)) {
|
|
164
|
+
state = view.withLogin(state, r.body);
|
|
165
|
+
} else if (r.status === 0) lost();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
const readAll = (force) => Promise.all([readRoster(force), readAuto(), readSessions()]);
|
|
169
|
+
|
|
170
|
+
const lookForDeck = once("find", async () => {
|
|
171
|
+
const found = await src.find();
|
|
172
|
+
if (!found) return;
|
|
173
|
+
deck = found;
|
|
174
|
+
set({ deck: { port: found.port, version: found.version ?? null }, silent: [] });
|
|
175
|
+
readAll(true);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// ── what a key asks for ──────────────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
async function doSwitch(row) {
|
|
181
|
+
// A deck that came up since the last look owns the switch now.
|
|
182
|
+
if (!deck) {
|
|
183
|
+
const found = await src.find();
|
|
184
|
+
if (found) {
|
|
185
|
+
deck = found;
|
|
186
|
+
set({ deck: { port: found.port, version: found.version ?? null } });
|
|
187
|
+
} else {
|
|
188
|
+
const silent = await src.silent();
|
|
189
|
+
if (silent.length) {
|
|
190
|
+
set({ silent });
|
|
191
|
+
tell("err", `the deck on ${silent.map(d => d.port).join(", ")} is running but did not answer ${g.dash} not switching behind its back`);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
set({ busy: { text: `switching to ${accountName(row)}`, since: clock() }, notice: null });
|
|
197
|
+
render();
|
|
198
|
+
const result = deck ? await src.switchDeck(deck, row.num) : await src.switchHere(row.num);
|
|
199
|
+
set({ busy: null });
|
|
200
|
+
if (!result.ok && result.reason === "deck_timeout") {
|
|
201
|
+
tell("warn", `the deck has not finished switching to ${accountName(row)} ${g.dash} it may still land`);
|
|
202
|
+
} else if (!result.ok && result.reason === "login_expired") {
|
|
203
|
+
tell("err", `${accountName(row)}'s login expired ${g.dash} switching to it would sign every running session out`);
|
|
204
|
+
} else if (!result.ok) {
|
|
205
|
+
const why = result.reason === "no_cswap" ? `claude-swap is not installed`
|
|
206
|
+
: result.reason === "timeout" ? `claude-swap took too long to answer`
|
|
207
|
+
: result.output ? String(result.output).trim().split("\n").pop()
|
|
208
|
+
: result.reason ?? "the switch failed";
|
|
209
|
+
tell("err", `could not switch to ${accountName(row)} ${g.dash} ${why}`);
|
|
210
|
+
} else {
|
|
211
|
+
// Who follows the switch: every running Claude session, from its next
|
|
212
|
+
// message — the whole effect, and nowhere else on screen (? says when).
|
|
213
|
+
const live = Array.isArray(state.sessions)
|
|
214
|
+
? state.sessions.filter(s => s.provider !== "codex" && s.state !== "ended").length
|
|
215
|
+
: 0;
|
|
216
|
+
const follows = live > 0
|
|
217
|
+
? ` ${g.bullet} ${live} Claude session${live === 1 ? " moves" : "s move"} with it`
|
|
218
|
+
: "";
|
|
219
|
+
tell("ok", `switched to ${accountName(row)}${follows}`);
|
|
220
|
+
}
|
|
221
|
+
await readRoster(true);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function doBest() {
|
|
225
|
+
const rows = state.roster?.ok ? state.roster.accounts : [];
|
|
226
|
+
const best = bestAccount(rows, await src.rules(deck, rows));
|
|
227
|
+
if (best.none) return tell("err", `no account can take the login ${g.dash} every one is disabled or needs a fresh sign-in`);
|
|
228
|
+
// What to do first, then why: the notice is one row, and at 80 columns
|
|
229
|
+
// its end is what a long email cuts off.
|
|
230
|
+
if (best.already) {
|
|
231
|
+
state = view.selectSlot(state, best.already.num);
|
|
232
|
+
return tell("ok", `already on ${KEPT[best.rule] ?? KEPT["most-room"]}: ${accountName(best.already)}`);
|
|
233
|
+
}
|
|
234
|
+
state = view.selectSlot(state, best.account.num);
|
|
235
|
+
tell("info", `enter switches to ${accountName(best.account)} ${g.dash} ${PICKED[best.rule] ?? PICKED["most-room"]}`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function doAuto(enabled) {
|
|
239
|
+
if (!deck) return;
|
|
240
|
+
set({ busy: { text: `turning Auto-switch ${enabled ? "on" : "off"}`, since: clock() }, notice: null });
|
|
241
|
+
render();
|
|
242
|
+
const r = await src.ask(deck, { method: "POST", path: "/api/cswap-auto", body: { action: "enable", enabled } });
|
|
243
|
+
set({ busy: null });
|
|
244
|
+
if (r.ok && r.body?.ok !== false) tell("ok", `Auto-switch ${enabled ? "on" : "off"}`);
|
|
245
|
+
else tell("err", `could not turn Auto-switch ${enabled ? "on" : "off"} ${g.dash} ${r.body?.reason ?? (r.status ? `the deck answered ${r.status}` : r.reason ?? "no reply")}`);
|
|
246
|
+
last.auto = 0;
|
|
247
|
+
await readAuto();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ── adding an account, through the deck's sign-in ───────────────────────
|
|
251
|
+
|
|
252
|
+
const ADMIN = "/api/claude-accounts/admin";
|
|
253
|
+
/** Why the deck would not start a sign-in, when it said so by name. */
|
|
254
|
+
const START_REFUSED = {
|
|
255
|
+
already_running: "another sign-in is saving an account right now — try again in a moment",
|
|
256
|
+
bad_email: "the deck would not sign in with that address",
|
|
257
|
+
no_url: "the claude CLI did not print a sign-in link",
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/** Why the deck would not take a code, when it said so by name and gave no
|
|
261
|
+
* sentence of its own. */
|
|
262
|
+
const CODE_REFUSED = {
|
|
263
|
+
not_prompted: "the claude CLI has not asked for a code yet — paste it once the page shows one",
|
|
264
|
+
not_waiting: "the deck is no longer waiting for a code",
|
|
265
|
+
};
|
|
266
|
+
// Which start is the latest: a page closed while the deck was still starting
|
|
267
|
+
// its sign-in is cancelled again once the deck answers, unless a newer one
|
|
268
|
+
// has the deck by then.
|
|
269
|
+
let attempt = 0;
|
|
270
|
+
|
|
271
|
+
async function doSigninStart() {
|
|
272
|
+
if (!deck || !state.signin) return;
|
|
273
|
+
const mine = ++attempt;
|
|
274
|
+
const { email } = state.signin;
|
|
275
|
+
set({ signin: { ...state.signin, started: true, login: null, code: "", sending: false, lastLive: "link" }, notice: null });
|
|
276
|
+
render();
|
|
277
|
+
// The deck answers once the CLI has printed its link, or has died trying.
|
|
278
|
+
const r = await src.ask(deck, { method: "POST", path: ADMIN, body: email ? { action: "login", email } : { action: "login" }, timeoutMs: 30_000 });
|
|
279
|
+
const body = r.body && typeof r.body === "object" ? r.body : null;
|
|
280
|
+
if (mine !== attempt || !view.signinRunning(state.signin)) {
|
|
281
|
+
// The cancel sent when the page closed can have found nothing to cancel
|
|
282
|
+
// yet, and the CLI would sit on its five minutes.
|
|
283
|
+
if (mine === attempt && deck && body?.state === "awaiting_code") {
|
|
284
|
+
src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 15_000 }).catch(() => {});
|
|
285
|
+
}
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (r.ok && body?.ok !== false && typeof body?.state === "string") {
|
|
289
|
+
state = view.withLogin(state, body);
|
|
290
|
+
} else {
|
|
291
|
+
const why = body?.detail ?? (body?.reason ? START_REFUSED[body.reason] ?? body.error ?? body.reason : null)
|
|
292
|
+
?? (r.status === 0 ? `the deck did not answer (${r.reason ?? "no reply"})` : deckTrouble(deck, r));
|
|
293
|
+
// `local`: the deck holds no sign-in of ours to let go of — only for a
|
|
294
|
+
// missing link did it start one, and fail it.
|
|
295
|
+
state = view.withLogin(state, { state: "failed", error: why, url: null, step: null, local: body?.reason !== "no_url" });
|
|
296
|
+
}
|
|
297
|
+
last.signin = clock();
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function doSigninCode(code) {
|
|
301
|
+
if (!deck || !state.signin) return;
|
|
302
|
+
// Answered when the CLI took it and the account is saved, or asked again —
|
|
303
|
+
// a minute at the most for the CLI, and the store's lock on top of it.
|
|
304
|
+
const r = await src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-code", code }, timeoutMs: 150_000 });
|
|
305
|
+
if (!state.signin?.started) return;
|
|
306
|
+
// The code is not kept, whatever the answer: a wrong one is copied again.
|
|
307
|
+
set({ signin: { ...state.signin, code: "", sending: false } });
|
|
308
|
+
const body = r.body && typeof r.body === "object" ? r.body : null;
|
|
309
|
+
if (body?.reason === "empty_code") return;
|
|
310
|
+
const why = () => body?.error ?? CODE_REFUSED[body?.reason] ?? body?.reason ?? deckTrouble(deck, r);
|
|
311
|
+
// A refusal names its reason even when the deck wrote no sentence for it:
|
|
312
|
+
// a code sent before the CLI asked for one would otherwise just vanish.
|
|
313
|
+
if (typeof body?.state === "string" && (body.ok !== false || body.state !== "idle")) {
|
|
314
|
+
state = view.withLogin(state, body.ok === false ? { ...body, error: why() } : body);
|
|
315
|
+
} else if (r.status === 0) lost();
|
|
316
|
+
else state = view.withLogin(state, { ...state.signin.login, error: why() });
|
|
317
|
+
last.signin = 0;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Let go of the deck's sign-in, and say so when the account in use did not
|
|
321
|
+
* go back — the one outcome the person must not miss. */
|
|
322
|
+
async function doSigninCancel({ quiet = false } = {}) {
|
|
323
|
+
if (!deck) return;
|
|
324
|
+
const r = await src.ask(deck, { method: "POST", path: ADMIN, body: { action: "login-cancel" }, timeoutMs: 15_000 });
|
|
325
|
+
const a = r.body?.activeAccount;
|
|
326
|
+
if (r.body?.restored === false) {
|
|
327
|
+
const who = a?.email || (a?.num != null ? `account ${a.num}` : null);
|
|
328
|
+
tell("warn", who ? `this machine is now signed in as ${who} ${g.dash} the account you were using could not be put back`
|
|
329
|
+
: `the account you were using could not be put back ${g.dash} check which one is in use`);
|
|
330
|
+
} else if (!quiet) tell("info", "sign-in cancelled");
|
|
331
|
+
await readRoster(true);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function doSigninDone(account) {
|
|
335
|
+
await readRoster(true);
|
|
336
|
+
if (account?.num != null) state = view.selectSlot(state, Number(account.num));
|
|
337
|
+
if (account?.email) tell("ok", `${account.added === false ? "signed in again" : "added"}: ${account.email}`);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async function doStart() {
|
|
341
|
+
set({ starting: true, busy: { text: "starting the deck", since: clock() }, notice: null });
|
|
342
|
+
render();
|
|
343
|
+
let launcher;
|
|
344
|
+
try {
|
|
345
|
+
launcher = src.startDeck();
|
|
346
|
+
} catch (e) {
|
|
347
|
+
set({ starting: false, busy: null });
|
|
348
|
+
return tell("err", `could not start the deck ${g.dash} ${e?.message ?? e}`);
|
|
349
|
+
}
|
|
350
|
+
// The launcher stays until the deck answers and leaves with an error when
|
|
351
|
+
// it will not — a UI that was never built, a port it cannot have — so its
|
|
352
|
+
// last line is the reason, said at once rather than after the wait.
|
|
353
|
+
let failed = null;
|
|
354
|
+
launcher?.exited?.then(r => { if (r && r.code !== 0) failed = r; });
|
|
355
|
+
const until = clock() + START_WAIT_MS;
|
|
356
|
+
while (!done && clock() < until && !failed) {
|
|
357
|
+
await src.wait(1_000);
|
|
358
|
+
const found = await src.find();
|
|
359
|
+
if (found) {
|
|
360
|
+
deck = found;
|
|
361
|
+
set({ deck: { port: found.port, version: found.version ?? null }, starting: false, busy: null, silent: [] });
|
|
362
|
+
tell("ok", `the deck is running on ${found.port}`);
|
|
363
|
+
await readAll(true);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
set({ starting: false, busy: null });
|
|
368
|
+
if (done) return;
|
|
369
|
+
if (failed?.said) tell("err", `the deck did not start ${g.dash} ${failed.said}`);
|
|
370
|
+
else tell("err", `the deck did not come up ${g.dash} \`${COMMAND} --logs\` shows what it wrote`);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const effects = {
|
|
374
|
+
switch: (e) => doSwitch(e.account),
|
|
375
|
+
best: () => doBest(),
|
|
376
|
+
auto: (e) => doAuto(e.enabled),
|
|
377
|
+
refresh: () => readAll(true),
|
|
378
|
+
start: () => doStart(),
|
|
379
|
+
"signin-start": () => doSigninStart(),
|
|
380
|
+
"signin-code": (e) => doSigninCode(e.code),
|
|
381
|
+
"signin-cancel": (e) => doSigninCancel(e),
|
|
382
|
+
"signin-done": (e) => doSigninDone(e.account),
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
return new Promise(resolve => {
|
|
386
|
+
const wasRaw = input.isRaw === true;
|
|
387
|
+
let timer = null;
|
|
388
|
+
const finish = (code = EXIT.OK) => {
|
|
389
|
+
if (done) return;
|
|
390
|
+
done = { code };
|
|
391
|
+
clearInterval(timer);
|
|
392
|
+
input.off("keypress", onKey);
|
|
393
|
+
output.off?.("resize", onResize);
|
|
394
|
+
output.off?.("error", onGone);
|
|
395
|
+
for (const sig of SIGNALS) process.off(sig, onSignal);
|
|
396
|
+
process.off("exit", onExit);
|
|
397
|
+
process.off("uncaughtException", onCrash);
|
|
398
|
+
process.off("unhandledRejection", onCrash);
|
|
399
|
+
// The keys stop being read before the mode goes back. On Windows, raw
|
|
400
|
+
// mode ended while they were still read left the PowerShell that ran us
|
|
401
|
+
// dead behind us: not one more line ran, and an SSH session closed.
|
|
402
|
+
input.pause();
|
|
403
|
+
try { input.setRawMode?.(wasRaw); } catch { /* the terminal went away */ }
|
|
404
|
+
screen.leave();
|
|
405
|
+
resolve(code);
|
|
406
|
+
};
|
|
407
|
+
// Every way out hands the terminal back: a signal (the SSH connection
|
|
408
|
+
// closing is a SIGHUP), the process ending under us, and a throw — which
|
|
409
|
+
// is printed after the screen is left, or the alternate screen would take
|
|
410
|
+
// the only account of it away with it.
|
|
411
|
+
// Out, with the deck's sign-in let go of first when this screen started
|
|
412
|
+
// one: left running, `claude auth login` would hold the next attempt for
|
|
413
|
+
// the rest of its five minutes. Not one refused before it began — the deck
|
|
414
|
+
// has only the sign-in somebody else is running then.
|
|
415
|
+
let leaving = false;
|
|
416
|
+
const leave = (code) => {
|
|
417
|
+
if (done || leaving) return;
|
|
418
|
+
const si = state.signin;
|
|
419
|
+
if (!deck || !si?.started || si.login?.state === "done" || si.login?.local) return finish(code);
|
|
420
|
+
leaving = true;
|
|
421
|
+
set({ busy: { text: "cancelling the sign-in", since: clock() } });
|
|
422
|
+
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));
|
|
425
|
+
};
|
|
426
|
+
const onSignal = () => leave(EXIT.OK);
|
|
427
|
+
const onExit = () => screen.leave();
|
|
428
|
+
const onGone = () => finish(EXIT.FAILED);
|
|
429
|
+
const onCrash = (e) => {
|
|
430
|
+
finish(EXIT.FAILED);
|
|
431
|
+
process.stderr.write(`${COMMAND} tui: ${e?.stack ?? e}\n`);
|
|
432
|
+
};
|
|
433
|
+
const onResize = () => { screen.invalidate(); render(); };
|
|
434
|
+
function onKey(str, key) {
|
|
435
|
+
if (done || leaving) return;
|
|
436
|
+
const { state: next, effect } = view.tuiKey(state, str, key ?? {}, { now: clock(), g });
|
|
437
|
+
state = next;
|
|
438
|
+
if (effect?.type === "quit") return leave(EXIT.OK);
|
|
439
|
+
if (effect?.type === "redraw") screen.invalidate();
|
|
440
|
+
else if (effect && effects[effect.type]) {
|
|
441
|
+
Promise.resolve(effects[effect.type](effect)).catch(e => tell("err", String(e?.message ?? e))).finally(render);
|
|
442
|
+
}
|
|
443
|
+
render();
|
|
444
|
+
}
|
|
445
|
+
// The timer that keeps the screen current: the readings when they are due,
|
|
446
|
+
// and a repaint for the clock — the ages and the resets move, and a
|
|
447
|
+
// spinner while something is under way.
|
|
448
|
+
const tick = () => {
|
|
449
|
+
if (done) return;
|
|
450
|
+
const now = clock();
|
|
451
|
+
if (!deck) {
|
|
452
|
+
if (!state.starting && now - last.find >= POLL_MS.find) lookForDeck();
|
|
453
|
+
if (now - last.roster >= POLL_MS.roster * 2) readRoster(false);
|
|
454
|
+
} else {
|
|
455
|
+
if (now - last.sessions >= POLL_MS.sessions) readSessions();
|
|
456
|
+
if (now - last.auto >= POLL_MS.auto) readAuto();
|
|
457
|
+
if (now - last.roster >= POLL_MS.roster) readRoster(false);
|
|
458
|
+
if (view.signinRunning(state.signin) && now - last.signin >= view.signinPollMs(state.signin)) readSignin();
|
|
459
|
+
}
|
|
460
|
+
render();
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
emitKeypressEvents(input);
|
|
464
|
+
try { input.setRawMode?.(true); } catch { /* not a terminal after all: the keys still arrive */ }
|
|
465
|
+
input.resume();
|
|
466
|
+
input.on("keypress", onKey);
|
|
467
|
+
output.on?.("resize", onResize);
|
|
468
|
+
output.on?.("error", onGone);
|
|
469
|
+
for (const sig of SIGNALS) process.on(sig, onSignal);
|
|
470
|
+
process.on("exit", onExit);
|
|
471
|
+
process.on("uncaughtException", onCrash);
|
|
472
|
+
process.on("unhandledRejection", onCrash);
|
|
473
|
+
screen.enter();
|
|
474
|
+
render();
|
|
475
|
+
readAll(true);
|
|
476
|
+
timer = setInterval(tick, deps.tickMs ?? 100);
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** Why b went where it went, and where it stayed — `switch --best`'s rules
|
|
481
|
+
* (account-pick.mjs bestAccount), in the fewer words one row has room for. */
|
|
482
|
+
const PICKED = Object.freeze({ "most-room": "the most room", home: "your home account", "weekly-reset": "the soonest weekly reset" });
|
|
483
|
+
const KEPT = Object.freeze({
|
|
484
|
+
"most-room": "the account with the most room",
|
|
485
|
+
home: "your home account",
|
|
486
|
+
rules: "the account Auto-switch's rules keep",
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
/** What each reading is called when it fails; looking for a deck that is not
|
|
490
|
+
* there is not a failure. */
|
|
491
|
+
const READINGS = Object.freeze({ roster: "the accounts", auto: "Auto-switch", sessions: "the sessions" });
|
|
492
|
+
|
|
493
|
+
// SIGHUP is a closed SSH connection, and on Windows a closed console window;
|
|
494
|
+
// SIGBREAK is Windows' Ctrl+Break.
|
|
495
|
+
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", ...(process.platform === "win32" ? ["SIGBREAK"] : [])];
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Where the screen's answers come from: the running deck through the commands'
|
|
499
|
+
* own helpers, and — with none — claude-swap's store in this process.
|
|
500
|
+
*/
|
|
501
|
+
export function deckSource(port) {
|
|
502
|
+
return {
|
|
503
|
+
find: async () => {
|
|
504
|
+
const { findDeck } = await load("src/server/deck-client.mjs");
|
|
505
|
+
return findDeck({ port });
|
|
506
|
+
},
|
|
507
|
+
silent: () => silentDecks(port).catch(() => []),
|
|
508
|
+
ask: (deck, opts) => ask(deck, opts),
|
|
509
|
+
localRoster: async () => {
|
|
510
|
+
const { fetchClaudeAccounts } = await load("src/server/claude-accounts.mjs");
|
|
511
|
+
return fetchClaudeAccounts({ force: true });
|
|
512
|
+
},
|
|
513
|
+
switchDeck: (deck, num) => switchThroughDeck(deck, num),
|
|
514
|
+
switchHere: (num) => switchHere(num),
|
|
515
|
+
rules: (deck, accounts) => autoRules(deck, accounts),
|
|
516
|
+
// The bare start, as typed: it detaches itself and its launcher leaves
|
|
517
|
+
// once the deck is up. Never a browser — over SSH there is none to open,
|
|
518
|
+
// and at a desk the person asked for this screen, not a tab. `exited` is
|
|
519
|
+
// the launcher's code and the last line it printed, which on a failure is
|
|
520
|
+
// the reason.
|
|
521
|
+
startDeck: () => {
|
|
522
|
+
const child = spawn(process.execPath, [join(PKG_ROOT, "bin", "agent-dag.js"), "--no-open"], {
|
|
523
|
+
stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true,
|
|
524
|
+
env: { ...process.env, NO_COLOR: "1" },
|
|
525
|
+
});
|
|
526
|
+
let tail = "";
|
|
527
|
+
const keep = (d) => { tail = (tail + String(d)).slice(-4_000); };
|
|
528
|
+
child.stdout.on("data", keep);
|
|
529
|
+
child.stderr.on("data", keep);
|
|
530
|
+
const exited = new Promise(resolve => {
|
|
531
|
+
child.on("error", e => resolve({ code: -1, said: e.message }));
|
|
532
|
+
child.on("exit", code => {
|
|
533
|
+
const lines = tail.split(/\r?\n/).map(l => oneLine(stripAnsi(l))).filter(Boolean);
|
|
534
|
+
resolve({ code, said: lines.at(-1) ?? "" });
|
|
535
|
+
});
|
|
536
|
+
});
|
|
537
|
+
child.unref();
|
|
538
|
+
child.stdout.unref?.();
|
|
539
|
+
child.stderr.unref?.();
|
|
540
|
+
return { exited };
|
|
541
|
+
},
|
|
542
|
+
wait: (ms) => new Promise(r => setTimeout(r, ms)),
|
|
543
|
+
};
|
|
544
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e,b as r,W as J,X as Q,Y,Z as X,_ as Z,$ as z,a0 as V,h as ee,s as se,n as te,o as ne,a1 as ae,a2 as ie,R as re,d as oe}from"./app-BFaxhiED.js";function le({snap:s}){return e.jsxs("section",{className:"bw-feed",children:[e.jsxs("h4",{className:"bw-sec-head bw-head-row",children:["Live activity",e.jsxs("span",{className:"bw-feed-count",children:[s.log.length," ",s.log.length===1?"event":"events"]})]}),e.jsx("p",{className:"bw-since bw-feed-note",children:"Pages you opened yourself — counted to run the rule, never written down. Addresses appear under Findings, and only for pages a program opened."}),e.jsx("div",{className:"bw-log","aria-live":"polite","aria-relevant":"additions",children:s.log.length===0?e.jsx("p",{className:"bw-note",children:"The deck writes a line here each time it looks at a profile."}):s.log.map(a=>e.jsxs("div",{className:`bw-log-line ${a.level}${a.parts?"":" sys"}`,children:[e.jsx("span",{className:"bw-log-time",children:new Date(a.atMs).toLocaleTimeString("en-GB",{hour12:!1})}),a.parts?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"bw-log-browser",children:a.parts.browser}),e.jsx("span",{className:"bw-log-profile",title:a.parts.profile,children:a.parts.profile}),e.jsxs("span",{className:"bw-log-value",children:[a.parts.value,a.parts.flagged>0&&e.jsxs("span",{className:"bw-log-flag",children:[" · ",a.parts.flagged," flagged"]})]})]}):e.jsx("span",{className:"bw-log-sys",children:a.text})]},`${a.atMs}-${a.level}-${a.text}`))})]})}const E=s=>`${s.host}-${s.startMs}`;function ce(s){const a=h=>new Date(h).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1});return s.count===1||s.endMs-s.startMs<6e4?a(s.startMs):`${a(s.startMs)} → ${a(s.endMs)}`}function de(s){return new Date(s).toLocaleDateString(void 0,{weekday:"short",day:"numeric",month:"short"})}function K(s){const a=Math.round((s.endMs-s.startMs)/6e4);return a<1?"":`${a} min`}function he({snap:s,dismiss:a,refreshRef:h}){const[c,d]=r.useState(null),u=r.useRef(new Map),t=r.useRef(null);r.useEffect(()=>{var i,w;const o=t.current;!o||s.episodes.some(b=>E(b)===o.id)||(t.current=null,J(((i=document.activeElement)==null?void 0:i.tagName)??null)&&((w=(o.next?u.current.get(o.next):void 0)??h.current)==null||w.focus()))},[s]);const n=o=>{t.current={id:E(o),next:Q(s.episodes.map(E),E(o))},a(o)},l=r.useMemo(()=>{const o=[];for(const i of s.episodes){const w=de(i.startMs),b=o[o.length-1];b&&b.label===w?b.episodes.push(i):o.push({label:w,episodes:[i]})}return o},[s]);return e.jsxs("section",{className:"bw-findings",children:[e.jsxs("h4",{className:"bw-sec-head bw-head-row",children:["Findings",s.episodes.length>0&&e.jsxs("span",{className:"bw-feed-count",children:[s.episodes.length," ",s.episodes.length===1?"episode":"episodes"]})]}),e.jsx("div",{className:"bw-eps",children:l.length===0?e.jsxs("div",{className:"bw-empty",children:[e.jsx("p",{className:"bw-empty-head",children:"Nothing found yet"}),e.jsxs("p",{className:"bw-empty-note",children:["An episode lands here when a program opens pages in a browser nobody has touched for"," ",s.settings.quietMinutes," ",s.settings.quietMinutes===1?"minute":"minutes",". On most machines that is rare, so an empty list is the ordinary result rather than a sign something is wrong."]}),!s.settings.enabled&&e.jsx("p",{className:"bw-empty-note",children:"Watching is off, so this shows only what this deck has seen since it started. Anything an earlier run recorded comes back when you switch it on."})]}):l.map(o=>e.jsxs("div",{className:"bw-day",children:[e.jsx("h4",{className:"bw-sec-head",children:o.label}),o.episodes.map(i=>{const w=E(i),b=c===w;return e.jsxs("div",{className:`bw-ep${b?" open":""}`,children:[e.jsxs("div",{className:"bw-ep-row",children:[e.jsxs("button",{className:"bw-ep-head",ref:p=>{p?u.current.set(w,p):u.current.delete(w)},onClick:()=>d(b?null:w),"aria-expanded":b,children:[e.jsx("span",{className:"bw-chev","aria-hidden":!0,children:b?"▾":"▸"}),e.jsx("span",{className:"bw-ep-host",children:i.host}),e.jsxs("span",{className:"bw-ep-meta",children:[ce(i),K(i)&&e.jsxs(e.Fragment,{children:[" · ",K(i)]}),i.provisional&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{title:"Its quiet window has not closed yet. If somebody used the browser in the minutes after it, it is withdrawn; until then it is not written down and no reaction runs.",children:"provisional"})]})]}),e.jsxs("span",{className:"bw-ep-count",children:[i.count," ",i.count===1?"page":"pages"]})]}),e.jsx("button",{className:"glyph-btn bw-ep-x",onClick:()=>n(i),"aria-label":`Dismiss ${i.host}`,title:"Dismiss — it leaves this list for good, and stays in the log file",children:"×"})]}),b&&e.jsx("ul",{className:"bw-urls",children:i.urls.map((p,y)=>e.jsxs("li",{children:[e.jsx("span",{className:"bw-url-time",children:new Date(p.timeMs).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1})}),e.jsx("span",{className:"bw-url",children:p.url})]},`${p.url}-${p.timeMs}-${y}`))})]},w)})]},o.label))})]})}function ue(s){const a=/^#?([0-9a-f]{6})$/i.exec((s??"").trim());if(!a)return!1;const h=parseInt(a[1],16),c=[h>>16&255,h>>8&255,h&255].map(d=>{const u=d/255;return u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4)});return .2126*c[0]+.7152*c[1]+.0722*c[2]>.5}const U=1e4,we=12e3;function me({browsers:s,findings:a,watching:h,palette:c}){const d=r.useRef(null),u=r.useRef(null);return u.current={browsers:s,findings:a,watching:h},r.useEffect(()=>{var b;const t=d.current;if(!t)return;const n=t.getContext("2d");if(!n)return;const l=((b=window.matchMedia)==null?void 0:b.call(window,"(prefers-reduced-motion: reduce)").matches)??!1;let o=0,i=!1;const w=()=>{var q;if(i)return;const p=u.current;if(!p)return;const{browsers:y,findings:j,watching:P}=p,S=c["--accent"]||"#7dd3fc",g=c["--line"]||"#1f2229",v=c["--text-dim"]||"#6e727c",$=ue(c["--bg"]),N=$?42:26,k=$?.85:.65,A=Date.now(),R=Math.min(window.devicePixelRatio||1,2),C=t.clientWidth,W=t.clientHeight;(t.width!==C*R||t.height!==W*R)&&(t.width=C*R,t.height=W*R),n.setTransform(R,0,0,R,0,0),n.clearRect(0,0,C,W);const m=C/2,x=W/2,M=Math.min(C,W)/2-6;n.strokeStyle=g,n.lineWidth=1,n.globalAlpha=$?1:.9;for(const f of[.4,.7,1])n.beginPath(),n.arc(m,x,M*f,0,Math.PI*2),n.stroke();n.beginPath(),n.moveTo(m-M,x),n.lineTo(m+M,x),n.moveTo(m,x-M),n.lineTo(m,x+M),n.stroke(),n.globalAlpha=1;const I=(P&&!l?A%U/U:0)*Math.PI*2-Math.PI/2;if(P){const f=(q=n.createConicGradient)==null?void 0:q.call(n,I-.85,m,x);f&&(f.addColorStop(0,"transparent"),f.addColorStop(.85/(Math.PI*2),`color-mix(in srgb, ${S} ${N}%, transparent)`),f.addColorStop(1,"transparent"),n.fillStyle=f,n.beginPath(),n.moveTo(m,x),n.arc(m,x,M,I-.85,I),n.closePath(),n.fill()),n.strokeStyle=S,n.globalAlpha=k,n.beginPath(),n.moveTo(m,x),n.lineTo(m+Math.cos(I)*M,x+Math.sin(I)*M),n.stroke(),n.globalAlpha=1}y.forEach((f,T)=>{const B=T/Math.max(y.length,1)*Math.PI*2-Math.PI/2,D=f.lastReadMs===null?1:Math.min(1,(A-f.lastReadMs)/12e4),O=M*(.42+D*.5),F=m+Math.cos(B)*O,L=x+Math.sin(B)*O,_=Math.abs((I-B+Math.PI*3)%(Math.PI*2)-Math.PI),G=P?Math.max(0,1-_/.55):0;n.beginPath(),n.arc(F,L,3+G*1.6,0,Math.PI*2),n.fillStyle=f.running?S:v,n.globalAlpha=f.running?.55+G*.45:.35,n.fill(),n.globalAlpha=1});for(const f of j){const T=(A-f.atMs)/we;if(T<0||T>1)continue;const D=Math.max(0,y.findIndex(L=>L.key===f.browser))/Math.max(y.length,1)*Math.PI*2-Math.PI/2,O=m+Math.cos(D)*M*.6,F=x+Math.sin(D)*M*.6;n.beginPath(),n.arc(O,F,4+T*22,0,Math.PI*2),n.strokeStyle=S,n.globalAlpha=(1-T)*.8,n.lineWidth=1.5,n.stroke(),n.globalAlpha=1}o=requestAnimationFrame(w)};return w(),()=>{i=!0,cancelAnimationFrame(o)}},[c]),e.jsx("canvas",{ref:d,className:"bw-radar",role:"img","aria-label":h?`Watching ${s.length} browser${s.length===1?"":"s"}`:"Not watching"})}function be({snap:s,watching:a,palette:h}){const[c,d]=r.useState(!1),[u,t]=r.useState(()=>Date.now());r.useEffect(()=>{const l=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(l)},[]);const n=Y(s.coverage.lastHumanMs,s.coverage.quietMs,u);return e.jsxs("section",{className:"bw-sec",children:[e.jsxs("h4",{className:"bw-sec-head",children:["Activity overview",e.jsx("button",{className:"bw-help",onClick:()=>d(l=>!l),"aria-expanded":c,"aria-label":"What the sweep and the dots mean",children:"?"})]}),e.jsxs("div",{className:"bw-glance",children:[e.jsx(me,{browsers:a.map(l=>{var o;return{key:l.key,name:l.name,running:l.running,lastReadMs:((o=s.profiles.find(i=>i.browser===l.key))==null?void 0:o.lastWrittenMs)??null}}),findings:s.episodes.slice(0,6).map(l=>({browser:l.browser??null,atMs:l.endMs})),watching:s.settings.enabled,palette:h}),e.jsx("ul",{className:"bw-counts",children:X(a,s.profiles).map(l=>e.jsxs("li",{children:[e.jsx("span",{className:"bw-count-n",children:l.visits.toLocaleString("en-US")}),e.jsx("span",{className:"bw-count-of",children:l.name})]},l.key))})]}),e.jsx("p",{className:"bw-since",children:"Pages a program opened, since this deck started"}),s.coverage.checkedMs>0&&e.jsxs("p",{className:"bw-since",children:["Last checked ",Z(s.coverage.checkedMs,u),s.coverage.checks>0&&e.jsxs(e.Fragment,{children:[" · ",s.coverage.checks.toLocaleString("en-US")," ",s.coverage.checks===1?"check":"checks"]})]}),n!==null&&e.jsxs("p",{className:"bw-gate",children:["You are browsing — a program page would count in ",z(n)]}),c&&e.jsxs("dl",{className:"bw-key",children:[e.jsx("dt",{children:"Sweep"}),e.jsx("dd",{children:"one poll of every watched profile"}),e.jsx("dt",{children:"Dot"}),e.jsx("dd",{children:"a browser, further out the longer since it last wrote history"}),e.jsx("dt",{children:"Ring"}),e.jsx("dd",{children:"a finding, leaving the browser it came from"})]})]})}function pe({watching:s,rest:a}){const[h,c]=r.useState(!1),[d,u]=r.useState(!1);return e.jsxs("section",{className:"bw-sec",children:[e.jsxs("h4",{className:"bw-sec-head",children:["Watched profiles",e.jsx("button",{className:"bw-help",onClick:()=>c(t=>!t),"aria-expanded":h,"aria-label":"What running, idle and connected to Anthropic mean",children:"?"})]}),h&&e.jsxs("dl",{className:"bw-key",children:[e.jsx("dt",{children:"Running"}),e.jsx("dd",{children:"the browser has a process on this machine right now"}),e.jsx("dt",{children:"Connected"}),e.jsx("dd",{children:"an open connection to an address Anthropic's relay uses — which it shares with claude.ai, so an open tab looks the same as an agent channel"})]}),e.jsx("ul",{className:"bw-profiles",children:s.map(t=>e.jsxs("li",{children:[e.jsx("span",{className:`bw-prof-dot${t.running?" on":""}`,"aria-hidden":!0}),e.jsx("span",{className:"bw-prof-name",children:t.name}),e.jsx("span",{className:"bw-prof-state",children:t.running?"running":"idle"}),t.running&&t.relay.state==="live"&&e.jsx("span",{className:"bw-relay",children:"connected to Anthropic"})]},t.key))}),a.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"bw-why bw-rest-head",onClick:()=>u(t=>!t),"aria-expanded":d,children:[e.jsx("span",{className:"bw-chev","aria-hidden":!0,children:d?"▾":"▸"})," ",a.length," not watched"]}),d&&e.jsxs("p",{className:"bw-rest",children:[a.map(t=>t.name).join(", ")," — not installed, or installed and never opened, so there is no history to read."]})]})]})}function ge({snap:s,quiet:a,setQuiet:h,save:c,access:d,setAccess:u}){return e.jsxs("div",{className:"bw-settings",children:[e.jsxs("label",{title:"A program opening a page counts as a finding only if nobody had touched the browser for this long. Shorter catches more and reports more of your own work; longer is quieter.",children:[e.jsx("span",{children:"Nobody browsing for"}),e.jsxs("select",{value:a??s.settings.quietMinutes,onChange:t=>{h(Number(t.target.value)),c({quietMinutes:Number(t.target.value)})},children:[e.jsx("option",{value:1,children:"1 min"}),e.jsx("option",{value:5,children:"5 min"}),e.jsx("option",{value:15,children:"15 min"}),e.jsx("option",{value:30,children:"30 min"}),e.jsx("option",{value:60,children:"60 min"})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"When it finds one"}),e.jsx("select",{value:s.settings.reaction,onChange:t=>void c({reaction:t.target.value}),disabled:!s.settings.enabled,title:s.settings.enabled?"What to do besides writing it down.":"Turn watching on to arm a reaction.",children:(s.reactions??["notify"]).map(t=>e.jsx("option",{value:t,children:t==="notify"?"notify me":t==="close-tab"?"close the tab":"quit the browser"},t))})]}),e.jsxs("div",{className:"bw-settings-note",children:[e.jsxs("p",{children:["Chrome marks a navigation that came from an extension or a command rather than from a click. These are the ones that happened while nobody had touched the browser for the time above. ",e.jsx("strong",{children:"Usually that is your own agent doing what you asked."})]}),e.jsxs("button",{className:"bw-why",onClick:()=>u(t=>!t),"aria-expanded":d,children:[e.jsx("span",{className:"bw-chev","aria-hidden":!0,children:d?"▾":"▸"})," What Browser Watch can access"]}),d&&e.jsxs("dl",{className:"bw-access",children:[e.jsx("dt",{children:"Reads"}),e.jsxs("dd",{children:["A copy of each browser's own history database — the live file is locked while the browser holds it. Only rows newer than the moment this deck started:"," ",new Date(s.coverage.startedMs).toLocaleString(),"."]}),e.jsx("dt",{children:"Keeps"}),e.jsxs("dd",{children:["Only while the switch is on, and only the episodes it flagged — never your ordinary browsing. In ",e.jsx("code",{className:"bw-path",children:s.coverage.logPath}),typeof s.coverage.logBytes=="number"?` (${V(s.coverage.logBytes)})`:"",", with every address written in full so you can check it yourself."]}),e.jsx("dt",{children:"Sends"}),e.jsx("dd",{children:"Nothing. No part of this reads or writes over the network; the deck serves on 127.0.0.1 and this panel talks only to it."}),e.jsx("dt",{children:"Never reads"}),e.jsx("dd",{children:"Anything from before this deck started, cookies, saved passwords, page contents, or any browser profile with no history file."})]})]})]})}function H(s,a){return a?{kind:"saving",word:"Saving"}:s.settings.enabled?{kind:"on",word:"Watching"}:{kind:"off",word:"Paused"}}function fe({snap:s,saving:a,save:h,why:c,setWhy:d}){return e.jsxs("footer",{className:"bw-status",children:[e.jsx("span",{className:`bw-mode-dot${s.settings.enabled?" on":""}`,"aria-hidden":!0}),e.jsx("span",{className:"bw-mode-word",children:H(s,a).word},H(s,a).kind),e.jsx("span",{className:"bw-status-text",children:s.coverage.archived===0?s.settings.enabled?"No episodes recorded yet":"No episodes on disk":`${s.coverage.archived} ${s.coverage.archived===1?"episode":"episodes"} on disk`}),e.jsx("button",{className:`glyph-btn bw-gear${c?" on":""}`,onClick:()=>d(u=>!u),"aria-expanded":c,"aria-label":"Settings",title:"Settings",children:e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":!0,children:[e.jsx("circle",{cx:"7",cy:"7",r:"2.1"}),e.jsx("path",{d:"M7 1.2v1.6M7 11.2v1.6M1.2 7h1.6M11.2 7h1.6M2.9 2.9l1.1 1.1M10 10l1.1 1.1M11.1 2.9L10 4M4 10l-1.1 1.1"})]})}),e.jsxs("label",{className:"bw-switch",htmlFor:"bw-enabled",children:[e.jsx("span",{className:"bw-switch-label",id:"bw-enabled-label",children:"Watch browser activity"}),e.jsx("button",{id:"bw-enabled",type:"button",role:"switch","aria-checked":s.settings.enabled,"aria-labelledby":"bw-enabled-label",className:"switch",onClick:()=>void h({enabled:!s.settings.enabled}),title:s.settings.enabled?"On — every episode it finds is written down, so the list outlives the browsing history being cleared":"Off — showing only what this deck has seen since it started. Anything an earlier run archived is hidden until you switch back on, and nothing new is kept",children:e.jsx("span",{className:"switch-knob"})})]})]})}function xe({relay:s}){const[a,h]=r.useState(!1),[c,d]=r.useState(!1),u=s.killswitch.blocked?"unblock":"block",t=s.command[u],n=r.useCallback(async()=>{await ee(t.command)&&(d(!0),window.setTimeout(()=>d(!1),1600))},[t.command]),l=s.profiles.filter(i=>{var w;return(w=i.report)==null?void 0:w.present}),o=s.profiles.filter(i=>i.report===null);return e.jsxs("section",{className:"bw-sec",children:[e.jsx("h4",{className:"bw-sec-head",children:"Remote control"}),e.jsx("p",{className:`bw-rc-verdict ${s.verdict}`,role:"status",children:s.verdict==="exposed"?"Claude in Chrome is live here, so any Claude Code session signed in to your Anthropic account can drive this browser — from any machine, with no prompt on this one.":s.verdict==="protected"?`The relay is black-holed in ${s.hostsPath}, so no new connection to it can be made from this machine.`:"Claude in Chrome is not installed and enabled in any profile here, so there is nothing for the relay to drive."}),s.killswitch.foreign.length>0&&e.jsxs("p",{className:"bw-rc-foreign",children:["Another entry for this host is already in ",s.hostsPath,", and ccdeck will not touch it:",s.killswitch.foreign.map(i=>e.jsx("code",{className:"bw-path",children:i},i))]}),e.jsxs("button",{className:"bw-why",onClick:()=>h(i=>!i),"aria-expanded":a,children:[e.jsx("span",{className:"bw-chev","aria-hidden":!0,children:a?"▾":"▸"})," ",s.verdict==="protected"?"How to undo the block":"What it can reach, and how to stop it"]}),a&&e.jsxs("div",{className:"bw-rc-body",children:[l.length>0&&e.jsx("dl",{className:"bw-key",children:l.map(i=>e.jsxs(r.Fragment,{children:[e.jsxs("dt",{children:[i.name,i.profile==="Default"?"":` · ${i.profile}`]}),e.jsxs("dd",{children:[i.report.enabled?"enabled":"installed but switched off",i.report.allUrls?", can act on every site":", limited to the sites it was granted",i.report.sensitiveApis.length>0&&e.jsxs(e.Fragment,{children:[" — ",i.report.sensitiveApis.join(", ")]})]})]},`${i.browser}/${i.profile}`))}),o.length>0&&e.jsxs("p",{className:"bw-rc-note",children:[o.map(i=>i.name).join(", ")," — its settings file could not be read, so nothing is claimed about it either way."]}),!s.hostsRead&&e.jsxs("p",{className:"bw-rc-note",children:[s.hostsPath," could not be read, so whether the relay is already blocked is unknown."]}),l.some(i=>i.report.allUrls)&&e.jsxs("p",{className:"bw-rc-note",children:["Narrowing the sites in ",e.jsx("code",{className:"bw-path",children:"chrome://extensions"})," does not change this: the grant is held at the browser level and the per-site list is enforced inside the extension, by the extension."]}),e.jsxs("div",{className:"bw-rc-cmd",children:[e.jsx("code",{children:t.command}),e.jsx("button",{className:"btn bw-rc-copy",onClick:n,children:c?"Copied":"Copy"})]}),e.jsx("p",{className:"bw-rc-note",children:t.note})]})]})}function je(s){const[a,h]=r.useState(null),[c,d]=r.useState(null),[u,t]=r.useState(null),[n,l]=r.useState(!1),o=r.useRef(!1),[i,w]=r.useState(null),[b,p]=r.useState(!1),y=r.useRef(!1),j=r.useCallback(async g=>{var v,$;if(!(g&&!se(o.current))){g&&(o.current=!0,l(!0));try{const N=await fetch(`/api/browser-watch${g?"?refresh=1":""}`);if(!N.ok)throw new Error(`the deck answered ${N.status}`);const k=await N.json();h(k),y.current||w(((v=k==null?void 0:k.settings)==null?void 0:v.quietMinutes)??15),s((($=k==null?void 0:k.settings)==null?void 0:$.enabled)===!0),d(null)}catch(N){d(N instanceof Error?N.message:String(N))}finally{g&&(o.current=!1,l(!1))}}},[s]);r.useEffect(()=>{j(!1)},[j]),r.useEffect(()=>{const g=setInterval(()=>{j(!1)},1e4);return()=>clearInterval(g)},[j]);const P=r.useCallback(async g=>{try{await fetch("/api/browser-watch/dismiss",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({host:g.host,startMs:g.startMs})})}finally{await j(!1)}},[j]),S=r.useCallback(async g=>{y.current=!0,p(!0);try{const v=await fetch("/api/browser-watch",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g)});if(!v.ok)throw new Error(`the deck answered ${v.status}`);await j(!1),t(null)}catch(v){t(v instanceof Error?v.message:String(v))}finally{y.current=!1,p(!1)}},[j]);return{snap:a,error:c,writeError:u,setWriteError:t,busy:n,quiet:i,setQuiet:w,saving:b,load:j,dismiss:P,save:S}}function Ne({onClose:s,onSeen:a,onWatching:h,palette:c}){const d=te(s),u=ne(s),{snap:t,error:n,writeError:l,setWriteError:o,busy:i,quiet:w,setQuiet:b,saving:p,load:y,dismiss:j,save:P}=je(h),[S,g]=r.useState(!1),[v,$]=r.useState(!1),N=r.useRef(null),k=r.useRef(a);k.current=a,r.useEffect(()=>()=>k.current(Date.now()),[]);const A=ae(t==null?void 0:t.browsers),R=((t==null?void 0:t.browsers)??[]).filter(m=>!(m.installed&&m.profiles>0)),C=t?ie(t):null,W=A.reduce((m,x)=>m+x.profiles,0);return e.jsx("div",{className:"modal-backdrop",...u,role:"presentation",children:e.jsxs("div",{ref:d,className:"modal bw-modal",onClick:m=>m.stopPropagation(),role:"dialog","aria-modal":"true","aria-labelledby":"bw-title",children:[e.jsxs("header",{className:"modal-head",children:[e.jsxs("div",{className:"modal-title",children:[e.jsx("span",{className:"modal-tool-name",id:"bw-title",children:"Browser watch"}),e.jsx("span",{className:"modal-tool-id",children:t?`${W} ${W===1?"profile":"profiles"} · local only`:"local only"})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{ref:N,className:"glyph-btn",onClick:()=>void y(!0),...oe(i),"aria-label":"Re-read every profile now",title:"Re-read every profile now",children:i?"…":e.jsx(re,{})}),e.jsx("button",{className:"glyph-btn",onClick:s,"aria-label":"Close (Esc)",title:"Close (Esc)",children:"×"})]})]}),e.jsxs("div",{className:"modal-body bw-body",children:[!t&&!n&&e.jsxs("div",{className:"bw-loading",children:[e.jsx("span",{className:"bw-loading-bar","aria-hidden":!0}),e.jsx("p",{children:"Reading each browser's history. The first look copies the file, which takes a moment."})]}),n&&e.jsx("div",{className:"bw-state",children:e.jsxs("div",{className:"bw-row err",children:[e.jsx("span",{className:"bw-dot","aria-hidden":!0}),e.jsx("span",{className:"bw-row-label",children:"Could not read"}),e.jsx("span",{className:"bw-row-detail",children:n})]})}),t&&C&&e.jsx("p",{className:`bw-trouble ${C.kind}`,role:"status",children:C.text}),t&&e.jsxs("div",{className:"bw-work",children:[e.jsxs("aside",{className:"bw-side",children:[e.jsx(be,{snap:t,watching:A,palette:c}),e.jsx(pe,{watching:A,rest:R}),t.relay&&e.jsx(xe,{relay:t.relay})]}),e.jsxs("div",{className:"bw-main",children:[e.jsx(he,{snap:t,dismiss:j,refreshRef:N}),e.jsx(le,{snap:t})]})]}),t&&S&&e.jsx(ge,{snap:t,quiet:w,setQuiet:b,save:P,access:v,setAccess:$}),l&&e.jsx("div",{className:"bw-state bw-write-err",role:"alert",children:e.jsxs("div",{className:"bw-row err",children:[e.jsx("span",{className:"bw-dot","aria-hidden":!0}),e.jsx("span",{className:"bw-row-label",children:"Could not save that setting"}),e.jsxs("span",{className:"bw-row-detail",children:[l," — the switches below show what is stored, not what you pressed."]}),e.jsx("button",{className:"glyph-btn bw-write-err-x",onClick:()=>o(null),"aria-label":"Dismiss",title:"Dismiss",children:"×"})]})}),t&&e.jsx(fe,{snap:t,saving:p,save:P,why:S,setWhy:g})]})]})})}export{Ne as default};
|