ccdeck 3.49.1 → 3.51.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 (114) hide show
  1. package/README.md +7 -3
  2. package/THIRD_PARTY_NOTICES.md +28 -0
  3. package/bin/cli/commands.js +34 -3
  4. package/bin/cli/second-start.js +6 -1
  5. package/dist/web/assets/BrowserWatchModal-CDpunrq9.js +1 -0
  6. package/dist/web/assets/IntegrationModal-BctMcNU8.js +7 -0
  7. package/dist/web/assets/{RadioPanel-gFYxdsBg.js → RadioPanel-DQNFtYOx.js} +1 -1
  8. package/dist/web/assets/{TrafficRadar-B9MfKca4.js → TrafficRadar-DRt3Al7E.js} +1 -1
  9. package/dist/web/assets/UsageHistoryModal-DlgPufgs.js +1 -0
  10. package/dist/web/assets/{app-D2NP6IPl.js → app-4x4wTE-L.js} +73 -73
  11. package/dist/web/assets/{app-DfGYllmZ.css → app-o4kL0FgZ.css} +1 -1
  12. package/dist/web/assets/{index-Be6Ox-74.js → index-CWUj8Kqh.js} +1 -1
  13. package/dist/web/index.html +3 -3
  14. package/node_modules/bare-addon-resolve/LICENSE +201 -0
  15. package/node_modules/bare-addon-resolve/README.md +226 -0
  16. package/node_modules/bare-addon-resolve/index.d.ts +100 -0
  17. package/node_modules/bare-addon-resolve/index.js +531 -0
  18. package/node_modules/bare-addon-resolve/lib/errors.d.ts +16 -0
  19. package/node_modules/bare-addon-resolve/lib/errors.js +21 -0
  20. package/node_modules/bare-addon-resolve/package.json +57 -0
  21. package/node_modules/bare-module-resolve/LICENSE +201 -0
  22. package/node_modules/bare-module-resolve/README.md +322 -0
  23. package/node_modules/bare-module-resolve/index.d.ts +171 -0
  24. package/node_modules/bare-module-resolve/index.js +899 -0
  25. package/node_modules/bare-module-resolve/lib/errors.d.ts +31 -0
  26. package/node_modules/bare-module-resolve/lib/errors.js +37 -0
  27. package/node_modules/bare-module-resolve/package.json +56 -0
  28. package/node_modules/bare-semver/LICENSE +201 -0
  29. package/node_modules/bare-semver/README.md +147 -0
  30. package/node_modules/bare-semver/index.d.ts +61 -0
  31. package/node_modules/bare-semver/index.js +13 -0
  32. package/node_modules/bare-semver/lib/comparator.js +37 -0
  33. package/node_modules/bare-semver/lib/constants.js +7 -0
  34. package/node_modules/bare-semver/lib/errors.js +22 -0
  35. package/node_modules/bare-semver/lib/range.js +256 -0
  36. package/node_modules/bare-semver/lib/version.js +240 -0
  37. package/node_modules/bare-semver/package.json +43 -0
  38. package/node_modules/fs-native-extensions/CMakeLists.txt +118 -0
  39. package/node_modules/fs-native-extensions/LICENSE +201 -0
  40. package/node_modules/fs-native-extensions/README.md +160 -0
  41. package/node_modules/fs-native-extensions/binding.c +1825 -0
  42. package/node_modules/fs-native-extensions/binding.js +3 -0
  43. package/node_modules/fs-native-extensions/include/fs-ext.h +193 -0
  44. package/node_modules/fs-native-extensions/index.js +356 -0
  45. package/node_modules/fs-native-extensions/package.json +72 -0
  46. package/node_modules/fs-native-extensions/prebuilds/android-arm/fs-native-extensions.bare +0 -0
  47. package/node_modules/fs-native-extensions/prebuilds/android-arm/fs-native-extensions.node +0 -0
  48. package/node_modules/fs-native-extensions/prebuilds/android-arm64/fs-native-extensions.bare +0 -0
  49. package/node_modules/fs-native-extensions/prebuilds/android-arm64/fs-native-extensions.node +0 -0
  50. package/node_modules/fs-native-extensions/prebuilds/android-ia32/fs-native-extensions.bare +0 -0
  51. package/node_modules/fs-native-extensions/prebuilds/android-ia32/fs-native-extensions.node +0 -0
  52. package/node_modules/fs-native-extensions/prebuilds/android-x64/fs-native-extensions.bare +0 -0
  53. package/node_modules/fs-native-extensions/prebuilds/android-x64/fs-native-extensions.node +0 -0
  54. package/node_modules/fs-native-extensions/prebuilds/darwin-arm64/fs-native-extensions.bare +0 -0
  55. package/node_modules/fs-native-extensions/prebuilds/darwin-arm64/fs-native-extensions.node +0 -0
  56. package/node_modules/fs-native-extensions/prebuilds/darwin-x64/fs-native-extensions.bare +0 -0
  57. package/node_modules/fs-native-extensions/prebuilds/darwin-x64/fs-native-extensions.node +0 -0
  58. package/node_modules/fs-native-extensions/prebuilds/ios-arm64/fs-native-extensions.bare +0 -0
  59. package/node_modules/fs-native-extensions/prebuilds/ios-arm64-simulator/fs-native-extensions.bare +0 -0
  60. package/node_modules/fs-native-extensions/prebuilds/ios-x64-simulator/fs-native-extensions.bare +0 -0
  61. package/node_modules/fs-native-extensions/prebuilds/linux-arm64/fs-native-extensions.bare +0 -0
  62. package/node_modules/fs-native-extensions/prebuilds/linux-arm64/fs-native-extensions.node +0 -0
  63. package/node_modules/fs-native-extensions/prebuilds/linux-x64/fs-native-extensions.bare +0 -0
  64. package/node_modules/fs-native-extensions/prebuilds/linux-x64/fs-native-extensions.node +0 -0
  65. package/node_modules/fs-native-extensions/prebuilds/win32-arm64/fs-native-extensions.bare +0 -0
  66. package/node_modules/fs-native-extensions/prebuilds/win32-arm64/fs-native-extensions.node +0 -0
  67. package/node_modules/fs-native-extensions/prebuilds/win32-x64/fs-native-extensions.bare +0 -0
  68. package/node_modules/fs-native-extensions/prebuilds/win32-x64/fs-native-extensions.node +0 -0
  69. package/node_modules/fs-native-extensions/src/apple.c +197 -0
  70. package/node_modules/fs-native-extensions/src/linux.c +146 -0
  71. package/node_modules/fs-native-extensions/src/platform.h +51 -0
  72. package/node_modules/fs-native-extensions/src/posix.c +33 -0
  73. package/node_modules/fs-native-extensions/src/shared.c +397 -0
  74. package/node_modules/fs-native-extensions/src/win32/nt.h +226 -0
  75. package/node_modules/fs-native-extensions/src/win32.c +531 -0
  76. package/node_modules/require-addon/LICENSE +201 -0
  77. package/node_modules/require-addon/README.md +19 -0
  78. package/node_modules/require-addon/lib/bare.js +1 -0
  79. package/node_modules/require-addon/lib/default.js +7 -0
  80. package/node_modules/require-addon/lib/node.js +79 -0
  81. package/node_modules/require-addon/package.json +64 -0
  82. package/node_modules/which-runtime/LICENSE +201 -0
  83. package/node_modules/which-runtime/README.md +29 -0
  84. package/node_modules/which-runtime/index.js +36 -0
  85. package/node_modules/which-runtime/package.json +32 -0
  86. package/package.json +12 -2
  87. package/release-notes.json +25 -0
  88. package/src/server/claude-accounts.mjs +19 -3
  89. package/src/server/claude-collector.mjs +18 -2
  90. package/src/server/cswap-install.mjs +60 -18
  91. package/src/server/integrations/jira-comment.mjs +37 -0
  92. package/src/server/integrations/jira-move.mjs +37 -11
  93. package/src/server/integrations/jira-transition.mjs +43 -0
  94. package/src/server/integrations/jira-write-guard.mjs +218 -0
  95. package/src/server/integrations/jira.mjs +16 -0
  96. package/src/server/integrations/routes.mjs +70 -7
  97. package/src/server/lan-deck.mjs +9 -0
  98. package/src/server/lan-engine.mjs +17 -2
  99. package/src/server/lan-manifest.mjs +10 -3
  100. package/src/server/lifecycle.mjs +27 -2
  101. package/src/server/login-guard.mjs +4 -0
  102. package/src/server/npm-upgrade.mjs +46 -18
  103. package/src/server/pinned-build.mjs +5 -0
  104. package/src/server/quota-store-resets.mjs +13 -6
  105. package/src/server/quota.mjs +8 -1
  106. package/src/server/running-deck.mjs +14 -0
  107. package/src/server/static-cache.mjs +34 -16
  108. package/src/server/terminal-cli-update.mjs +189 -0
  109. package/src/server/terminal-cli.mjs +93 -0
  110. package/src/server/traffic-radar-wire.mjs +6 -0
  111. package/src/server/usage-share.mjs +444 -0
  112. package/dist/web/assets/BrowserWatchModal-CCARqAMn.js +0 -1
  113. package/dist/web/assets/IntegrationModal-B8t53aE5.js +0 -7
  114. package/dist/web/assets/UsageHistoryModal-DvYWhsYv.js +0 -1
@@ -0,0 +1,444 @@
1
+ // Usage readings between paired decks (#930).
2
+ //
3
+ // Anthropic budgets GET /api/oauth/usage per account — roughly thirty calls a
4
+ // rolling hour, shared by every machine holding that account, whatever token
5
+ // each one uses (claude-swap's poll_policy.py, realiti4/claude-swap#152). Each
6
+ // deck's claude-swap polls on its own plan, so ten machines on the same
7
+ // accounts spend ten budgets' worth, and the accounts panel shows them as rate
8
+ // limited.
9
+ //
10
+ // So among paired decks one polls each account and the others take its
11
+ // reading. Nothing is voted on: every deck ranks the decks it hears from that
12
+ // hold the account with a working login and speak this — first the ones on
13
+ // that account right now, then by a hash of the account and the deck — and the
14
+ // top one is the account's owner (rendezvous hashing). On it first, because
15
+ // that is the machine whose claude-swap reads it often: every five minutes at
16
+ // most and every minute close to a limit, where an account a machine is not on
17
+ // waits up to ten and never hurries. The owner puts its claude-swap row for the
18
+ // account into the manifest it already exchanges every round, sealed like the
19
+ // card; a deck that
20
+ // ranks lower hands it to its own claude-swap with `cswap import-usage --hold`,
21
+ // which keeps every collector on that machine off the account until the
22
+ // owner's next poll is due plus two rounds. A hold always ends on its own, so a
23
+ // deck that stops hearing goes back to polling for itself — today's behaviour —
24
+ // and two decks that disagree for a moment cost one fetch each, not a stall.
25
+ //
26
+ // Pairing is per pair and an account appears in a manifest only when it is
27
+ // ticked for that deck, so two decks can see different candidates. The rule
28
+ // that keeps that safe is the receiving one: a reading's hold is applied only
29
+ // when its sender outranks this deck for that account, so two decks that both
30
+ // believe they own it end with the higher one polling, never with neither.
31
+ //
32
+ // Times travel as ages, never as wall-clock times, so skewed clocks between the
33
+ // machines do not matter.
34
+ import { createHash } from "node:crypto";
35
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
36
+ import { tmpdir } from "node:os";
37
+ import { join } from "node:path";
38
+ import { run } from "./exec.mjs";
39
+ import { accountKey, heardCurrent, open, seal } from "./lan-sync.mjs";
40
+
41
+ const VERSION = 1;
42
+ // A paired deck stays a candidate this long after its last manifest: a round
43
+ // runs every minute each way (lan-round-timer.mjs), so this rides out one that
44
+ // failed without counting a deck that has gone.
45
+ const HEARD_FRESH_MS = 150_000;
46
+ // The hold runs to the owner's next planned poll (or the end of its backoff)
47
+ // plus two rounds, so the next reading arrives before the hold ends.
48
+ const SLACK_S = 120;
49
+ // claude-swap's own bounds: it never holds past an hour from the measurement
50
+ // (usage_store.TRUST_MAX_AGE_S), so an older reading is not worth sending.
51
+ const MAX_HOLD_S = 3600;
52
+ const MAX_AGE_S = 3600;
53
+ // When the owner's plan cannot be read: claude-swap's ceiling for an active
54
+ // account (poll_policy.py).
55
+ const DEFAULT_NEXT_S = 300;
56
+ // A reading goes out only while the deck that took it keeps its plan: its
57
+ // planned poll no further overdue than a few rounds to nudge the collector and
58
+ // let it fetch, or, with no plan to read, no older than claude-swap's widest
59
+ // normal cadence (CANDIDATE_MAX_INTERVAL_S) and a round.
60
+ const OVERDUE_MS = 180_000;
61
+ const UNPLANNED_MAX_AGE_S = 660;
62
+ // What claude-swap records for a fetch the account's own budget refused.
63
+ const RATE_LIMITED = "http-429";
64
+ // A reading already handed over is handed over again only when it is a new
65
+ // measurement, or when its hold would end within this.
66
+ const RENEW_BEFORE_MS = 90_000;
67
+ // Two readings of one account taken this close together are the same one.
68
+ const SAME_MEASUREMENT_MS = 5_000;
69
+ const MAX_READINGS = 50;
70
+ const MAX_SCOPED = 16;
71
+ // The readings' JSON, before sealing, is kept to this, well inside a frame
72
+ // (lan-lines.mjs MAX_FRAME_BYTES, 128 KiB) beside the manifest's own fifty
73
+ // accounts and the card: past it the rest are not sent, and the decks that
74
+ // would have taken them read for themselves.
75
+ const MAX_FIELD_BYTES = 32 * 1024;
76
+
77
+ /** The rendezvous score of deck `fp` for account `key`: the highest owns it. */
78
+ export function rank(key, fp) {
79
+ return createHash("sha256").update(`${key}|${fp}`).digest("hex");
80
+ }
81
+
82
+ /** Where deck `fp` stands for account `key`: on it now first, then by rank.
83
+ * Every rank is the same length, so the strings compare as the pair would. */
84
+ export function standing(key, fp, onIt) {
85
+ return `${onIt ? 1 : 0}${rank(key, fp)}`;
86
+ }
87
+
88
+ /** Bound to one connection AND one direction, like the card (lan-about.mjs). */
89
+ const usageAad = (fromFp, toFp) => `${fromFp}->${toFp}|usage`;
90
+
91
+ /** One window from claude-swap's store, in `cswap list --json`'s shape. */
92
+ function windowJson(w) {
93
+ if (!w || typeof w.pct !== "number" || !Number.isFinite(w.pct) || w.pct < 0) return null;
94
+ return { pct: w.pct, ...(typeof w.resets_at === "string" ? { resetsAt: w.resets_at } : {}) };
95
+ }
96
+
97
+ /**
98
+ * A store row's `lastGood` as `cswap list --json` prints `usage`, which is what
99
+ * `import-usage` reads back. The windows only: spend is not what the budget
100
+ * problem is about, and an import replaces the whole reading.
101
+ */
102
+ export function usageJson(lastGood) {
103
+ const out = {};
104
+ const five = windowJson(lastGood?.five_hour);
105
+ const seven = windowJson(lastGood?.seven_day);
106
+ if (five) out.fiveHour = five;
107
+ if (seven) out.sevenDay = seven;
108
+ const scoped = (Array.isArray(lastGood?.scoped) ? lastGood.scoped : []).slice(0, MAX_SCOPED).flatMap(s => {
109
+ const w = windowJson(s);
110
+ return w && typeof s.name === "string" && s.name ? [{ name: s.name, ...w }] : [];
111
+ });
112
+ if (scoped.length) out.scoped = scoped;
113
+ return Object.keys(out).length ? out : null;
114
+ }
115
+
116
+ /** A peer's window, or null — numbers in range and a reset that parses. */
117
+ function readWindow(w) {
118
+ if (!w || typeof w !== "object") return null;
119
+ if (typeof w.pct !== "number" || !Number.isFinite(w.pct) || w.pct < 0 || w.pct > 1000) return null;
120
+ if (w.resetsAt === undefined) return { pct: w.pct };
121
+ if (typeof w.resetsAt !== "string" || w.resetsAt.length > 64 || !Number.isFinite(Date.parse(w.resetsAt))) return null;
122
+ return { pct: w.pct, resetsAt: w.resetsAt };
123
+ }
124
+
125
+ /** A peer's `usage`, rebuilt from what checks out — never forwarded as sent. */
126
+ function readUsage(u) {
127
+ if (!u || typeof u !== "object") return null;
128
+ const out = {};
129
+ for (const k of ["fiveHour", "sevenDay"]) {
130
+ if (u[k] === undefined) continue;
131
+ const w = readWindow(u[k]);
132
+ if (!w) return null;
133
+ out[k] = w;
134
+ }
135
+ if (u.scoped !== undefined) {
136
+ if (!Array.isArray(u.scoped) || u.scoped.length > MAX_SCOPED) return null;
137
+ const scoped = [];
138
+ for (const s of u.scoped) {
139
+ const w = readWindow(s);
140
+ if (!w || typeof s.name !== "string" || !s.name || s.name.length > 64) return null;
141
+ scoped.push({ name: s.name, ...w });
142
+ }
143
+ if (scoped.length) out.scoped = scoped;
144
+ }
145
+ return Object.keys(out).length ? out : null;
146
+ }
147
+
148
+ const seconds = v => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 86_400 * 7 ? v : null;
149
+
150
+ /** One reading off the wire, or null. `key` must be the account it names. */
151
+ function readReading(r) {
152
+ if (!r || typeof r !== "object") return null;
153
+ if (typeof r.email !== "string" || !r.email || r.email.length > 320) return null;
154
+ if (typeof r.organizationUuid !== "string" || r.organizationUuid.length > 64) return null;
155
+ const key = accountKey(r.email, r.organizationUuid);
156
+ if (r.key !== key) return null;
157
+ const ageS = seconds(r.ageS);
158
+ if (ageS == null || ageS > MAX_AGE_S) return null;
159
+ const usage = readUsage(r.usage);
160
+ if (!usage) return null;
161
+ const nextS = r.nextS === undefined ? null : seconds(r.nextS);
162
+ const backoffS = r.backoffS === undefined ? null : seconds(r.backoffS);
163
+ if ((r.nextS !== undefined && nextS == null) || (r.backoffS !== undefined && backoffS == null)) return null;
164
+ return { key, email: r.email, organizationUuid: r.organizationUuid, ageS, usage, nextS, backoffS };
165
+ }
166
+
167
+ /** How long a reading holds this deck's collectors off its account, in s. */
168
+ export function holdFor({ nextS, backoffS }) {
169
+ const until = backoffS ?? nextS ?? DEFAULT_NEXT_S;
170
+ return Math.min(MAX_HOLD_S, Math.ceil(until + SLACK_S));
171
+ }
172
+
173
+ // Who each account's reading here came from, for the accounts panel: one map
174
+ // for the deck's one engine, read by claude-accounts.mjs. `{ name, until }` by
175
+ // account key.
176
+ const _sources = new Map();
177
+
178
+ /** The paired deck this account's current reading came from, or null. */
179
+ export function sharedReadingFrom(key, now = Date.now()) {
180
+ const s = _sources.get(key);
181
+ return s && s.until > now ? s.name : null;
182
+ }
183
+
184
+ /**
185
+ * Hand readings to this machine's claude-swap: `cswap import-usage <file>
186
+ * --hold <s>`. A file rather than stdin because `run` closes stdin; it holds
187
+ * account addresses and numbers, no credential, and is removed straight after.
188
+ */
189
+ export async function importUsage(doc, holdS) {
190
+ const { cswapBin } = await import("./cswap-install.mjs");
191
+ const dir = await mkdtemp(join(tmpdir(), "ccdeck-usage-"));
192
+ const file = join(dir, "usage.json");
193
+ try {
194
+ await writeFile(file, JSON.stringify(doc), { mode: 0o600 });
195
+ const r = await run(await cswapBin(), ["import-usage", file, "--hold", String(holdS)], { timeout: 30_000 });
196
+ if (r.ok) (await import("./claude-accounts.mjs")).invalidateClaudeAccountsCache();
197
+ return r.ok;
198
+ } finally {
199
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
200
+ }
201
+ }
202
+
203
+ /**
204
+ * One deck's side of it, for its LAN engine.
205
+ *
206
+ * `readStore` answers claude-swap's stored readings (storedUsageReadings), and
207
+ * `canImport` whether this deck's claude-swap has `import-usage`. A deck
208
+ * without it says nothing and polls for itself, and nobody counts it as a
209
+ * candidate. `peerName` names a paired deck for the panel. `register` makes
210
+ * this instance the one sharedReadingFrom answers for; only the deck's own
211
+ * engine sets it.
212
+ */
213
+ export function createUsageShare({
214
+ now = Date.now, myFp, readStore, canImport, importUsage: handOver = importUsage,
215
+ peerName = () => null, register = false,
216
+ } = {}) {
217
+ /** Fingerprint → `{ at, keys, all, current }`: the accounts each deck that
218
+ * speaks this offered in its last manifest — alive (`keys`, which make it a
219
+ * candidate) and at all (`all`, which it can be sent readings for) — and
220
+ * the one of them it is on, if it said. */
221
+ const heardBy = new Map();
222
+ /** Account key → `{ fp, measuredAt, holdUntil }`, for what was handed over. */
223
+ const handed = new Map();
224
+ /** The last store read: account key → stored reading. */
225
+ let store = new Map();
226
+ let capable = false;
227
+ // Every account this deck holds, and the ones whose stored login works: a
228
+ // reading is taken for any of them, but only a working login can poll.
229
+ let mine = new Set();
230
+ let mineAlive = new Set();
231
+ // The account this deck is on, or null.
232
+ let myCurrent = null;
233
+ let chain = Promise.resolve();
234
+
235
+ /** Read the store and the capability, and note which accounts this deck
236
+ * holds. Called with the accounts the manifest is built from, and never
237
+ * throws into that round: anything wrong here sits this deck out of the
238
+ * sharing, polling for itself as before. */
239
+ const refresh = async accounts => {
240
+ try {
241
+ mine = new Set((accounts ?? []).map(a => a.key));
242
+ mineAlive = new Set((accounts ?? []).filter(a => a.alive).map(a => a.key));
243
+ myCurrent = (accounts ?? []).find(a => a.active)?.key ?? null;
244
+ try { capable = (await canImport()) === true; } catch { capable = false; }
245
+ if (!capable) return;
246
+ try {
247
+ const rows = await readStore();
248
+ store = new Map(rows.map(r => [accountKey(r.email, r.organizationUuid), r]));
249
+ } catch { store = new Map(); }
250
+ release();
251
+ } catch {
252
+ capable = false;
253
+ }
254
+ };
255
+
256
+ /** The decks that compete for `key`, this one included when it qualifies,
257
+ * each with where it stands. */
258
+ const candidates = key => {
259
+ const t = now();
260
+ const out = [];
261
+ if (capable && mineAlive.has(key)) out.push({ fp: myFp(), at: standing(key, myFp(), myCurrent === key) });
262
+ for (const [fp, h] of heardBy) {
263
+ if (t - h.at <= HEARD_FRESH_MS && h.keys.has(key)) out.push({ fp, at: standing(key, fp, h.current === key) });
264
+ }
265
+ return out;
266
+ };
267
+
268
+ const ownerOf = key => {
269
+ let best = null;
270
+ let bestAt = "";
271
+ for (const c of candidates(key)) if (c.at > bestAt) { best = c.fp; bestAt = c.at; }
272
+ return best;
273
+ };
274
+
275
+ /** This deck's reading of `key` for the wire, or null. */
276
+ const readingOf = key => {
277
+ const r = store.get(key);
278
+ const t = now();
279
+ if (!r || typeof r.fetchedAt !== "number") return null;
280
+ // Held is somebody else's reading, kept here: not this deck's to pass on.
281
+ if (typeof r.heldUntil === "number" && r.heldUntil > t) return null;
282
+ const ageS = Math.max(0, (t - r.fetchedAt) / 1000);
283
+ if (ageS > MAX_AGE_S) return null;
284
+ // Only while this deck's own reads of it work. A fetch that failed for any
285
+ // reason but the account's rate limit — this machine's network, its login,
286
+ // a timeout — says nothing about the account, so the others are not held
287
+ // on it: their holds run out and they read for themselves, as before. A
288
+ // 429 is the account's budget, the same on every machine, so that one is
289
+ // passed on with its backoff.
290
+ if (typeof r.lastError === "string" && r.lastError !== RATE_LIMITED) return null;
291
+ const backingOff = typeof r.backoffUntil === "number" && r.backoffUntil > t;
292
+ // Nor once its plan has lapsed: a collector that has stopped here.
293
+ if (!backingOff && (typeof r.nextPollAt === "number" ? t - r.nextPollAt > OVERDUE_MS : ageS > UNPLANNED_MAX_AGE_S)) return null;
294
+ const usage = usageJson(r.lastGood);
295
+ if (!usage) return null;
296
+ const reading = { key, email: r.email, organizationUuid: r.organizationUuid, ageS: Math.round(ageS), usage };
297
+ if (typeof r.backoffUntil === "number" && r.backoffUntil > t) reading.backoffS = Math.ceil((r.backoffUntil - t) / 1000);
298
+ if (typeof r.nextPollAt === "number") reading.nextS = Math.max(0, Math.ceil((r.nextPollAt - t) / 1000));
299
+ return reading;
300
+ };
301
+
302
+ /**
303
+ * The `usage` field for the manifest to `toFp` over `connKey`, or nothing
304
+ * for a deck that cannot take part. `sent` is the list the manifest itself
305
+ * carries: a reading goes only for an account in it, so nothing reaches a
306
+ * deck that this deck did not already name to it.
307
+ */
308
+ const fieldFor = (connKey, toFp, sent) => {
309
+ if (!capable || !connKey) return {};
310
+ // Never in the way of the manifest itself: a field that cannot be built
311
+ // leaves the frame as an older deck sends it.
312
+ try {
313
+ const theirs = heardBy.get(toFp);
314
+ const readings = [];
315
+ let bytes = 0;
316
+ for (const a of sent ?? []) {
317
+ if (readings.length >= MAX_READINGS) break;
318
+ if (!a?.alive || !theirs?.all.has(a.key) || ownerOf(a.key) !== myFp()) continue;
319
+ const r = readingOf(a.key);
320
+ if (!r) continue;
321
+ bytes += Buffer.byteLength(JSON.stringify(r)) + 1;
322
+ if (bytes > MAX_FIELD_BYTES) break;
323
+ readings.push(r);
324
+ }
325
+ return { usage: seal(connKey, JSON.stringify({ v: VERSION, readings }), usageAad(myFp(), toFp)) };
326
+ } catch {
327
+ return {};
328
+ }
329
+ };
330
+
331
+ /** Run one hand-over at a time: claude-swap writes one store. The chain
332
+ * settles and never rejects: nothing awaits it but a test, and a rejection
333
+ * nobody handles ends the deck's process. */
334
+ const enqueue = job => (chain = chain.then(job).catch(() => {}));
335
+
336
+ /**
337
+ * Lift the holds this deck took from a deck it now outranks, rather than sit
338
+ * them out: that deck moved off the account, this one moved onto it, or that
339
+ * one went quiet. `import-usage --hold 0` with this deck's own reading, a
340
+ * second older than the stored one so it replaces nothing (usage_store.adopt),
341
+ * and claude-swap reads the account on its own plan again. A deck that has
342
+ * just started took nothing from anyone, and lets a hold it finds run out.
343
+ */
344
+ const release = () => {
345
+ const t = now();
346
+ for (const [key, h] of handed) {
347
+ if (h.holdUntil <= t) { handed.delete(key); continue; }
348
+ if (ownerOf(key) !== myFp()) continue;
349
+ handed.delete(key);
350
+ if (register) _sources.delete(key);
351
+ const r = store.get(key);
352
+ const usage = r && typeof r.heldUntil === "number" && r.heldUntil > t ? usageJson(r.lastGood) : null;
353
+ if (!usage) continue;
354
+ const doc = {
355
+ schemaVersion: 1,
356
+ accounts: [{
357
+ email: r.email, organizationUuid: r.organizationUuid,
358
+ usageStatus: "ok", usageAgeSeconds: Math.max(0, (t - r.fetchedAt) / 1000) + 1, usage,
359
+ }],
360
+ };
361
+ // A lift that fails leaves a hold that ends on its own.
362
+ enqueue(async () => { try { await handOver(doc, 0); } catch { /* as above */ } });
363
+ }
364
+ };
365
+
366
+ /**
367
+ * What `fromFp` said in its manifest: whether it speaks this, which
368
+ * accounts it offers alive (`list`, as keepManifest read it), and the
369
+ * readings it sends. Answers the hand-over it started, for tests. Whatever
370
+ * a paired deck sent, the manifest it came in is kept as before: this never
371
+ * throws, and what it answers never rejects.
372
+ */
373
+ const heard = (connKey, frame, fromFp, list) => {
374
+ try {
375
+ return hear(connKey, frame, fromFp, list);
376
+ } catch {
377
+ heardBy.delete(fromFp);
378
+ return Promise.resolve();
379
+ }
380
+ };
381
+
382
+ const hear = (connKey, frame, fromFp, list) => {
383
+ const text = frame?.usage && typeof frame.usage === "object" ? open(connKey, frame.usage, usageAad(fromFp, myFp())) : null;
384
+ let payload = null;
385
+ try { payload = text == null ? null : JSON.parse(text); } catch { payload = null; }
386
+ if (!payload || payload.v !== VERSION || !Array.isArray(payload.readings) || payload.readings.length > MAX_READINGS) {
387
+ heardBy.delete(fromFp);
388
+ return Promise.resolve();
389
+ }
390
+ const offeredAlive = new Set((list ?? []).filter(a => a.alive).map(a => a.key));
391
+ const current = heardCurrent(frame.current, list ?? [])?.key ?? null;
392
+ heardBy.set(fromFp, { at: now(), keys: offeredAlive, all: new Set((list ?? []).map(a => a.key)), current });
393
+ if (!capable) return Promise.resolve();
394
+
395
+ const t = now();
396
+ const groups = new Map();
397
+ for (const raw of payload.readings) {
398
+ const r = readReading(raw);
399
+ if (!r || !offeredAlive.has(r.key) || !mine.has(r.key)) continue;
400
+ // Only from a deck that outranks this one for the account, unless this
401
+ // one cannot poll it at all. A lower one that believes it owns it will
402
+ // hear this deck's readings and stop.
403
+ if (mineAlive.has(r.key)
404
+ && !(standing(r.key, fromFp, current === r.key) > standing(r.key, myFp(), myCurrent === r.key))) continue;
405
+ const measuredAt = t - r.ageS * 1000;
406
+ const holdS = holdFor(r);
407
+ const prev = handed.get(r.key);
408
+ if (prev && prev.fp === fromFp && Math.abs(prev.measuredAt - measuredAt) < SAME_MEASUREMENT_MS
409
+ && prev.holdUntil - t > RENEW_BEFORE_MS) continue;
410
+ // One import per hold, rounded up to 30 s so a round's readings share one.
411
+ const bucket = Math.ceil(holdS / 30) * 30;
412
+ if (!groups.has(bucket)) groups.set(bucket, []);
413
+ groups.get(bucket).push({ r, measuredAt });
414
+ }
415
+ if (!groups.size) return Promise.resolve();
416
+
417
+ return enqueue(async () => {
418
+ for (const [holdS, items] of groups) {
419
+ const doc = {
420
+ schemaVersion: 1,
421
+ accounts: items.map(({ r }) => ({
422
+ email: r.email, organizationUuid: r.organizationUuid,
423
+ usageStatus: "ok", usageAgeSeconds: Math.max(0, (now() - t) / 1000 + r.ageS), usage: r.usage,
424
+ })),
425
+ };
426
+ let ok = false;
427
+ try { ok = await handOver(doc, holdS); } catch { ok = false; }
428
+ if (!ok) continue;
429
+ const until = t + holdS * 1000;
430
+ for (const { r, measuredAt } of items) {
431
+ handed.set(r.key, { fp: fromFp, measuredAt, holdUntil: until });
432
+ if (register) _sources.set(r.key, { name: peerName(fromFp), until });
433
+ }
434
+ }
435
+ });
436
+ };
437
+
438
+ /** Settles once every hand-over and lift queued so far has run, for tests. */
439
+ const settled = () => chain;
440
+
441
+ // A deck that was unpaired sends no manifest, and stops counting once it has
442
+ // not been heard for HEARD_FRESH_MS.
443
+ return { refresh, fieldFor, heard, ownerOf, settled };
444
+ }
@@ -1 +0,0 @@
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-D2NP6IPl.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};