ccdeck 3.46.0 → 3.47.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 (54) hide show
  1. package/README.md +72 -43
  2. package/bin/cli/startup.js +23 -0
  3. package/bin/deck.js +32 -1
  4. package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +1 -0
  5. package/dist/web/assets/IntegrationModal-8tTi25gA.js +6 -0
  6. package/dist/web/assets/{RadioPanel-biw_BbZq.js → RadioPanel-DbmJJPsz.js} +1 -1
  7. package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
  8. package/dist/web/assets/{UsageHistoryModal-Bd-JRAa4.js → UsageHistoryModal-qfmvXdWJ.js} +1 -1
  9. package/dist/web/assets/app-BFFG6Wz8.js +321 -0
  10. package/dist/web/assets/app-DfcfHvcX.css +1 -0
  11. package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
  12. package/dist/web/assets/{index-DmENqVdt.js → index-Ca87aJP9.js} +1 -1
  13. package/dist/web/index.html +3 -3
  14. package/package.json +1 -1
  15. package/release-notes.json +30 -0
  16. package/src/server/ccusage-install.mjs +58 -1
  17. package/src/server/ccusage-registry.mjs +289 -0
  18. package/src/server/ccusage-runner.mjs +9 -2
  19. package/src/server/claude-accounts.mjs +21 -0
  20. package/src/server/claude-login.mjs +21 -3
  21. package/src/server/claude-settings-catalog.d.mts +37 -0
  22. package/src/server/claude-settings-catalog.mjs +169 -0
  23. package/src/server/claude-settings-docs.mjs +109 -0
  24. package/src/server/claude-settings-index.json +251 -0
  25. package/src/server/claude-settings-routes.mjs +46 -0
  26. package/src/server/claude-settings.mjs +406 -0
  27. package/src/server/cli-arrival.mjs +64 -0
  28. package/src/server/index.mjs +18 -2
  29. package/src/server/integrations/proxy.mjs +11 -2
  30. package/src/server/integrations/routes.mjs +6 -4
  31. package/src/server/quota-close-watch.mjs +81 -0
  32. package/src/server/quota-closes.mjs +181 -0
  33. package/src/server/quota-history.mjs +8 -1
  34. package/src/server/quota-shape.mjs +12 -0
  35. package/src/server/quota.mjs +28 -1
  36. package/src/server/request-gates.mjs +3 -1
  37. package/src/server/tool-audit-operations.mjs +30 -10
  38. package/src/server/tool-audit-report.mjs +79 -7
  39. package/src/server/tool-audit-routes.mjs +1 -1
  40. package/src/server/tool-audit-skills.mjs +8 -3
  41. package/src/server/tool-audit.mjs +55 -5
  42. package/src/server/traffic-radar-capture.mjs +3 -3
  43. package/src/server/traffic-radar-config.mjs +10 -3
  44. package/src/server/traffic-radar-monitor.mjs +8 -5
  45. package/src/server/traffic-radar-permission.mjs +162 -0
  46. package/src/server/traffic-radar-platform.mjs +9 -3
  47. package/src/server/traffic-radar-routes.mjs +8 -18
  48. package/src/server/traffic-radar-service.mjs +76 -92
  49. package/src/server/usage-routes.mjs +14 -2
  50. package/dist/web/assets/BrowserWatchModal-CoX9FIUE.js +0 -1
  51. package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
  52. package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
  53. package/dist/web/assets/app-BlRY6EME.css +0 -1
  54. package/dist/web/assets/app-DhGvSH7o.js +0 -319
@@ -1,136 +1,120 @@
1
1
  import { CaptureSetupError } from './traffic-radar-platform.mjs';
2
2
  import { isIP } from 'node:net';
3
+ import { lookup } from 'node:dns/promises';
3
4
 
4
5
  export function radarTargets(snapshot) {
5
6
  // A running Claude's launch environment names a collector as settings do.
6
7
  const variables = [...(snapshot?.config?.variables ?? []), ...(snapshot?.environment ?? [])];
7
- const configured = variables.filter(v => v.key.endsWith('ENDPOINT')).flatMap(({ value }) => {
8
- try {
9
- const url = new URL(value);
10
- return ['http:', 'https:'].includes(url.protocol) && isIP(url.hostname) === 4
11
- ? [`${url.hostname}:${url.port || (url.protocol === 'https:' ? 443 : 80)}`] : [];
12
- } catch { return []; }
13
- });
8
+ const configured = [], named = [];
9
+ for (const { key, value } of variables) {
10
+ if (!key.endsWith('ENDPOINT')) continue;
11
+ let url;
12
+ try { url = new URL(value); } catch { continue; }
13
+ if (!['http:', 'https:'].includes(url.protocol)) continue;
14
+ const port = url.port || (url.protocol === 'https:' ? 443 : 80);
15
+ if (isIP(url.hostname) === 4) configured.push(`${url.hostname}:${port}`);
16
+ // A name is looked up before capture (resolveCollector); an IPv6 literal,
17
+ // which URL keeps in brackets, is neither.
18
+ else if (url.hostname && !url.hostname.startsWith('[')) named.push(`${url.hostname}:${port}`);
19
+ }
14
20
  // An arbitrary Claude HTTPS connection is not evidence of a collector, nor an
15
21
  // attempt nothing has answered.
16
22
  const observed = (snapshot?.connections ?? []).filter(c => c.active === true && !c.connecting && /:4317$/.test(c.destination) && isIP(c.destination.slice(0, c.destination.lastIndexOf(':'))) === 4).map(c => c.destination);
17
- return { configured: [...new Set(configured)], observed: [...new Set(observed)] };
23
+ return { configured: [...new Set(configured)], named: [...new Set(named)], observed: [...new Set(observed)] };
24
+ }
25
+
26
+ /** A collector named by host, such as otel.example.com:4317, as the IPv4
27
+ * address Claude reaches it at. Capture filters on an address, and with no
28
+ * destination picker any more a name is the only way such a collector is
29
+ * found. A lookup that fails or hangs past `ms` names nothing. */
30
+ export async function resolveCollector(target, find = lookup, ms = 2000) {
31
+ const at = target.lastIndexOf(':');
32
+ let timer;
33
+ const late = new Promise(resolve => { timer = setTimeout(resolve, ms, null); timer.unref?.(); });
34
+ try {
35
+ const found = await Promise.race([find(target.slice(0, at), { family: 4 }).catch(() => null), late]);
36
+ return found && isIP(found.address) === 4 ? `${found.address}:${target.slice(at + 1)}` : null;
37
+ } finally { clearTimeout(timer); }
18
38
  }
19
39
 
20
40
  const savedDestinations = value => Array.isArray(value)
21
41
  ? value.filter(v => typeof v === 'string' && /^\d+\.\d+\.\d+\.\d+:\d+$/.test(v)).slice(0, 8) : [];
22
42
 
23
- /** Own the automatic-monitoring preference independently of whether capture is ready yet.
43
+ /** Radar monitors by itself, always: there is no switch and no Start (the
44
+ * owner, 2026-10-23, reversing v3.44.0's opt-in). The service finds Claude
45
+ * Code's collector — configured endpoints first, named ones looked up, then the
46
+ * collectors it remembers and active OTLP/gRPC connections on port 4317 — and
47
+ * keeps capture on it, retrying while none is found or capture is not ready.
24
48
  *
25
- * AUTOMATIC MONITORING IS OPT-IN. `enabled` here is Settings › Radar's switch,
26
- * kept in its own file (`preferences`, radar-settings-<port>.json) and on only
27
- * where that file says `automatic: true`. A fresh deck, and a deck upgraded
28
- * from a release that never wrote the file, has it off: nothing is discovered,
29
- * nothing is retried, and the capture behaves exactly as it did before, with
30
- * the person choosing a destination and starting it in Radar's Monitor view
31
- * (`capture.prepare`/`capture.stop`, which keep their own radar-monitor-<port>
32
- * .json opt-in and resume a monitor the person started, as they always did).
33
- * Only while the switch is on does the service find the collector itself and
34
- * retry every `pollMs`. */
35
- export function createRadarService({ capture, preferences, discover, pollMs = 5000 }) {
36
- let enabled = false, port = null, remembered = [], revision = 0, timer = null, disposed = false;
37
- let ready = Promise.resolve(), syncing = null, setupError = null;
38
- const settings = () => ({ ok: true, enabled, setupError });
39
- const save = () => preferences.write(port, { automatic: enabled, destinations: remembered });
40
- const stopLoop = () => { clearInterval(timer); timer = null; };
41
- const startLoop = () => {
42
- stopLoop();
43
- if (enabled && !disposed) { timer = setInterval(() => void sync(), pollMs); timer.unref?.(); }
44
- };
49
+ * Discovery samples Claude's processes (ps and lsof, /proc, or PowerShell), so
50
+ * every deck pays for it: it runs every `pollMs` only while Radar is open,
51
+ * which the page shows by reading the capture, and every `idleMs` otherwise.
52
+ * `radar-settings-<port>.json` keeps the collectors found, so a restart goes
53
+ * back to them; a monitor started by hand in an earlier release resumes too,
54
+ * and is where discovery looks first when no setting names a collector. */
55
+ export function createRadarService({ capture, preferences, discover, resolve = resolveCollector, pollMs = 5000, idleMs = 60000, openMs = 15000, now = Date.now }) {
56
+ let port = null, remembered = [], timer = null, disposed = false;
57
+ let syncing = null, setupError = null, syncedAt = -Infinity, readAt = -Infinity;
58
+ const save = () => preferences.write(port, { destinations: remembered });
45
59
  async function sync() {
46
- if (!enabled || disposed || !port) return;
60
+ if (disposed || !port) return;
47
61
  if (syncing) return syncing;
48
- const operation = revision;
62
+ syncedAt = now();
49
63
  syncing = (async () => {
50
64
  try {
51
- const { configured, observed } = radarTargets(await discover());
52
- if (operation !== revision || !enabled || disposed) return;
53
- const targets = [...new Set(configured.length ? configured : [...remembered, ...observed])].sort().slice(0, 8);
65
+ const { configured, named, observed } = radarTargets(await discover());
66
+ const looked = (await Promise.all(named.map(target => resolve(target)))).filter(Boolean);
67
+ if (disposed) return;
68
+ const settings = [...configured, ...looked];
69
+ const targets = [...new Set(settings.length ? settings : [...remembered, ...observed])].sort().slice(0, 8);
54
70
  if (!targets.length) { setupError = null; return; }
55
71
  const current = capture.read();
56
72
  const existing = (current.sources ?? []).map(s => s.destination).sort();
57
73
  if (current.enabled && JSON.stringify(existing) === JSON.stringify(targets)) { setupError = null; return; }
58
74
  await capture.prepare(targets, port);
59
- // Stopped with its opt-in saved off: a setup that lands after the switch
60
- // went off must not leave a monitor that resumes after a restart.
61
- if (operation !== revision || !enabled || disposed) { await capture.stop('stopped', !disposed); return; }
75
+ // A setup that lands after the deck shut the service down must not
76
+ // leave a monitor running, or one that resumes after a restart.
77
+ if (disposed) { await capture.stop('stopped', false); return; }
62
78
  remembered = targets;
63
79
  setupError = null;
64
80
  await save();
65
81
  } catch (error) {
66
- if (operation === revision && enabled && !disposed) setupError = error instanceof CaptureSetupError ? error.message : 'Monitoring setup failed. Retrying automatically.';
82
+ if (!disposed) setupError = error instanceof CaptureSetupError ? error.message : 'Monitoring setup failed. Retrying automatically.';
67
83
  }
68
84
  })().finally(() => { syncing = null; });
69
85
  return syncing;
70
86
  }
87
+ const tick = () => { if (now() - readAt < openMs || now() - syncedAt >= idleMs) void sync(); };
71
88
  return {
72
89
  ...capture,
73
- resume(requestedPort) {
90
+ async resume(requestedPort) {
74
91
  port = requestedPort;
75
- const operation = ++revision;
76
- ready = (async () => {
77
- const saved = await preferences.read(port);
78
- if (operation !== revision || disposed) return;
79
- enabled = saved?.automatic === true;
80
- remembered = savedDestinations(saved?.destinations);
81
- if (enabled) startLoop();
82
- // Off: the capture's own opt-in, as before — a monitor resumes only
83
- // where the person started one and did not stop it.
84
- else await capture.resume(port);
85
- })();
86
- return ready.then(sync);
87
- },
88
- async settings() { await ready; return settings(); },
89
- async setEnabled(next) {
90
- if (typeof next !== 'boolean') throw new Error('Radar enabled must be a boolean.');
91
- await ready;
92
- if (!port || disposed) throw new Error('Radar is not ready.');
93
- const previous = enabled, operation = ++revision;
94
- enabled = next;
95
- stopLoop();
96
- if (next) {
97
- // A monitor the person started by hand is where automatic monitoring
98
- // looks first when Claude's settings name no collector.
99
- const running = (capture.read().sources ?? []).map(s => s.destination);
100
- if (running.length) remembered = savedDestinations(running);
101
- } else { setupError = null; await capture.stop(); }
102
- try { await save(); }
103
- catch (error) {
104
- if (operation === revision) { enabled = previous; startLoop(); if (enabled) void sync(); }
105
- throw error;
106
- }
107
- if (operation === revision && enabled) {
108
- startLoop();
109
- // A slow older setup must finish/cancel before starting a new one.
110
- if (syncing) void syncing.then(sync); else void sync();
111
- }
112
- return settings();
92
+ const saved = await preferences.read(port);
93
+ if (disposed) return;
94
+ remembered = savedDestinations(saved?.destinations);
95
+ await capture.resume(port);
96
+ if (disposed) return;
97
+ if (!remembered.length) remembered = savedDestinations((capture.read().sources ?? []).map(s => s.destination));
98
+ clearInterval(timer);
99
+ timer = setInterval(tick, pollMs); timer.unref?.();
100
+ return sync();
113
101
  },
114
- async prepare(destination, requestedPort) {
115
- await ready;
116
- // Off: the Monitor view's own Start, unchanged.
117
- if (!enabled) return capture.prepare(destination, requestedPort);
118
- const operation = ++revision;
119
- const result = await capture.prepare(destination, requestedPort);
120
- if (operation !== revision || !enabled || disposed) { await capture.stop('stopped', !disposed); throw new Error('Radar setup was cancelled.'); }
121
- remembered = Array.isArray(destination) ? destination : [destination];
122
- await save();
123
- return result;
102
+ /** Start capture again now: permission was just granted (traffic-radar-permission.mjs). */
103
+ async retry() {
104
+ setupError = null;
105
+ const running = (capture.read().sources ?? []).map(s => s.destination);
106
+ if (!running.length || disposed || !port) return sync();
107
+ try { await capture.prepare(running, port); }
108
+ catch (error) { setupError = error instanceof CaptureSetupError ? error.message : 'Monitoring setup failed. Retrying automatically.'; }
124
109
  },
125
- // Off, Stop monitoring is the Monitor view's, as before; on, stopping is
126
- // turning automatic monitoring off.
127
- stop(...args) { return enabled ? this.setEnabled(false) : capture.stop(...args); },
128
110
  read() {
111
+ // Radar is open: look now rather than waiting out the idle interval.
112
+ readAt = now();
113
+ if (now() - syncedAt >= pollMs) void sync();
129
114
  const value = capture.read();
130
- if (!enabled) return { ...value, automatic: false };
131
115
  return { ...value, automatic: true, featureEnabled: true, setupError,
132
116
  state: setupError && !value.enabled ? 'error' : value.state };
133
117
  },
134
- dispose() { disposed = true; revision++; stopLoop(); capture.dispose(); },
118
+ dispose() { disposed = true; clearInterval(timer); timer = null; capture.dispose(); },
135
119
  };
136
120
  }
@@ -13,6 +13,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
13
13
  import { deckProviders } from "./deck-scope.mjs";
14
14
  import { send } from "./http-io.mjs";
15
15
  import { quotaHistoryReport } from "./quota-history.mjs";
16
+ import { quotaClosesReport } from "./quota-closes.mjs";
16
17
  import { validSessionLookup } from "./ccusage-session.mjs";
17
18
 
18
19
  // Resolved the way pinned-build.mjs resolves it, from a file in the same
@@ -28,13 +29,13 @@ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
28
29
  * carries on behind it and publishes for the next poll.
29
30
  */
30
31
  export async function handleQuota(req, res) {
31
- const { fetchClaudeQuota, QUOTA_DEADLINE_MS } = await import(
32
+ const { fetchClaudeQuota, withClaudePlan, QUOTA_DEADLINE_MS } = await import(
32
33
  pathToFileURL(join(PKG_ROOT, "src/server/quota.mjs")).href
33
34
  );
34
35
  const url = new URL(req.url, "http://localhost");
35
36
  const force = url.searchParams.get("refresh") === "1";
36
37
  const quota = await fetchClaudeQuota({ force, deadlineMs: QUOTA_DEADLINE_MS });
37
- send(res, 200, quota);
38
+ send(res, 200, await withClaudePlan(quota));
38
39
  }
39
40
 
40
41
  export async function handleCodexUsage(req, res) {
@@ -131,3 +132,14 @@ export async function handleQuotaHistory(req, res) {
131
132
  }
132
133
  send(res, 200, await quotaHistoryReport(provider, account));
133
134
  }
135
+
136
+ /** How full each of an account's windows was at its reset; never fetches. */
137
+ export async function handleQuotaCloses(req, res) {
138
+ const url = new URL(req.url, "http://localhost");
139
+ const provider = url.searchParams.get("provider");
140
+ const account = url.searchParams.get("account");
141
+ if (!["claude", "codex"].includes(provider) || !/^[a-f0-9]{64}$/.test(account ?? "")) {
142
+ return send(res, 400, { ok: false, reason: "bad_closes_scope" });
143
+ }
144
+ send(res, 200, await quotaClosesReport(provider, account));
145
+ }
@@ -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,i 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-DhGvSH7o.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};