claude-rpc 1.7.4 → 1.9.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.
package/README.md CHANGED
@@ -70,7 +70,7 @@ brew install rar-file/claude-rpc/claude-rpc && claude-rpc setup
70
70
  .\claude-rpc.exe setup
71
71
  ```
72
72
 
73
- `setup` copies the exe to a fixed per-user location (so the download can go afterwards) and adds that folder to your user PATH, so `claude-rpc <command>` works in any new terminal. Prefer a GUI? The release's `claude-rpc-<version>-x64-setup.exe` (installer, auto-updates) and `claude-rpc-<version>-x64-portable.exe` (no install) are the desktop dashboard app, which runs the same `setup` for you on first launch.
73
+ `setup` copies the exe to a fixed per-user location (so the download can go afterwards) and adds that folder to your user PATH, so `claude-rpc <command>` works in any new terminal. Prefer a GUI? The release's `claude-rpc-<version>-x64-setup.exe` (installer, auto-updates) and `claude-rpc-<version>-x64-portable.exe` (no install) are the desktop app: it runs the same `setup` for you on first launch, then gives you the settings page in a window and daemon controls in the tray.
74
74
 
75
75
  That's the whole pitch.
76
76
 
@@ -120,12 +120,12 @@ A rotation frame can show your **subscription usage** — `Usage · 34% weekly`
120
120
 
121
121
  ### on your machine
122
122
 
123
- Three local surfaces, all reading the same `~/.claude-rpc/aggregate.json`:
123
+ Local surfaces, all served from your own machine:
124
124
 
125
125
  <table>
126
126
  <tr>
127
127
  <td align="center" width="50%"><b>web dashboard</b><br/><sub><code>claude-rpc serve</code> · port 47474</sub><br/><br/><img src="docs/dashboard.png" alt="Web dashboard with range selector, activity chart, heatmap, cost panel, languages stack, and leaderboards" /></td>
128
- <td align="center" width="50%"><b>settings gui</b><br/><sub><code>npm run dashboard</code> · Electron</sub><br/><br/><img src="docs/electron.png" alt="Electron config editor with Presence / Discord / Assets / Timing / Daemon / Privacy / Stats tabs" /></td>
128
+ <td align="center" width="50%"><b>settings</b><br/><sub><code>claude-rpc settings</code> · same port</sub><br/><br/><img src="docs/settings.png" alt="Settings page with daemon status and controls, and a card editor with a live preview per status" /></td>
129
129
  </tr>
130
130
  </table>
131
131
 
@@ -326,6 +326,7 @@ It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@l
326
326
  | `insights` | 3–5 auto-generated lines about your history |
327
327
  | `wrapped` | Your animated year in review; `--publish` puts it on `claude-rpc.com/wrapped/<handle>` |
328
328
  | `serve` | The local web dashboard (port 47474) |
329
+ | `settings` | Edit the card, daemon and per-project privacy in the browser |
329
330
  | `export` | The aggregate as JSON, or daily rows as CSV (`--csv` `--out`) |
330
331
  | **Share** | |
331
332
  | `share [week\|month\|year\|all]` | Saves the poster PNG and copies a caption with your numbers and a link (`--no-png`, `--no-copy`, `--png <file>`) |
@@ -444,7 +445,7 @@ npm test # 550+ tests, a few seconds
444
445
  npm run lint # eslint over src + test + vscode-extension
445
446
  npm run start # run daemon in foreground
446
447
  npm run serve # web dashboard against your real data
447
- npm run dashboard # Electron settings GUI (dev mode)
448
+ npm run dashboard # desktop app shell (dev mode; shows the settings page)
448
449
  npm run build:exe # SEA single-file binary for the current OS
449
450
  ```
450
451
 
package/SECURITY.md CHANGED
@@ -415,6 +415,26 @@ No subprocess passes untrusted or remote input to a shell — arguments are
415
415
  static or escaped. The historical `shell: true` paths (`verifyHookPipe`, and the
416
416
  gist `gh` wrapper on Windows) use only trusted args.
417
417
 
418
+ ## 4a. Local dashboard server — only while `serve`, `wrapped` or `settings` runs
419
+
420
+ **Source:** `src/server/index.js`, `src/server/settings.js`. The daemon serves
421
+ no HTTP. `claude-rpc serve` / `wrapped` / `settings` (and the desktop app, which
422
+ runs `serve` for its window) start a server bound to **127.0.0.1 only**, port
423
+ 47474 (`CLAUDE_RPC_PORT`).
424
+
425
+ - **Host allowlist:** requests whose `Host` isn't `localhost` / `127.0.0.1` /
426
+ `::1` get 403, which closes DNS rebinding.
427
+ - **Read routes** return your own stats and config to the page.
428
+ - **Write routes** (`POST /api/settings`, `/api/daemon`, `/api/workspaces`)
429
+ save `config.json`, start/stop the daemon, and set per-project visibility.
430
+ Because any site open in your browser can send requests to localhost, they
431
+ are accepted only when the `Origin` header is this exact host and port and
432
+ the body is `application/json` (which a cross-site form cannot send without a
433
+ CORS preflight the server never answers). A save is validated and written
434
+ atomically; it can only change the claude-rpc config file.
435
+ - The desktop app's window gets no extra access: no preload script, no IPC,
436
+ `sandbox` on, `nodeIntegration` off. It is the same page a browser tab gets.
437
+
418
438
  ## 5. What it stores locally
419
439
 
420
440
  Three per-user locations (paths are defined in `src/paths.js`):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.7.4",
3
+ "version": "1.9.0",
4
4
  "description": "Discord Rich Presence for Claude Code — live model, project, tokens, and lifetime stats driven by Claude Code's hook system.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli.js CHANGED
@@ -5,7 +5,7 @@ import './safe-stdio.js';
5
5
  import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync } from 'node:fs';
6
6
  import process from 'node:process';
7
7
  import { basename, join } from 'node:path';
8
- import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, USER_CONFIG_DIR, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
8
+ import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, USER_CONFIG_DIR, IS_PACKAGED, IS_NPX, EXE_PATH, ROOT } from './paths.js';
9
9
  import { VERSION } from './version.js';
10
10
  import { c, fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
11
11
  import * as lb from './leaderboard.js';
@@ -21,13 +21,14 @@ import { writeFileAtomic } from './atomic-rename.js';
21
21
  // node:crypto, node:readline, node:child_process) are imported inside that
22
22
  // command's handler, like doctor.js/card.js/mcp.js always were.
23
23
  let readActiveState, statePathFor, loadConfig, hasUserConfig, spawnDaemonDetached, daemonAlive;
24
+ let stopDaemonAndWait, markStopped, clearStopped, isStopped, readDaemonInfo, shouldReplaceDaemon;
24
25
  let buildVars, fillTemplate, humanProject, humanTool, applyIdle, framePasses, fmtNum, fmtHours;
25
26
  let scan, readAggregate, findLiveSessions, dayKey, weekKey;
26
27
  let fmtCost;
27
28
  let readUsageCache, fetchUsage, writeUsageCache, fmtResetTime, fmtResetDay;
28
29
 
29
30
  async function loadDaemonCtl() {
30
- ({ spawnDaemonDetached, daemonAlive } = await import('./ensure-daemon.js'));
31
+ ({ spawnDaemonDetached, daemonAlive, stopDaemonAndWait, markStopped, clearStopped, isStopped, readDaemonInfo, shouldReplaceDaemon } = await import('./ensure-daemon.js'));
31
32
  }
32
33
 
33
34
  // Idempotent — repeat imports resolve from the module cache.
@@ -91,7 +92,19 @@ function splitEqArgs(argv) {
91
92
  return out;
92
93
  }
93
94
 
95
+ // " · v1.8.0 (update installed — restarting)" when the running daemon is not
96
+ // this copy's version, so a stale daemon is visible instead of silent.
97
+ function daemonVersionNote(pid) {
98
+ const info = readDaemonInfo();
99
+ if (!info || info.pid !== pid) return `${c.dim} · version unknown (pre-1.9 daemon — claude-rpc restart)${c.reset}`;
100
+ if (info.version === VERSION) return '';
101
+ return `${c.yellow} · running v${info.version}, installed v${VERSION} — claude-rpc restart${c.reset}`;
102
+ }
103
+
104
+ // An explicit start always clears a previous `stop` (the marker every launcher
105
+ // honors), so `start` after `stop` behaves the way it reads.
94
106
  function startDaemon({ quiet = false } = {}) {
107
+ clearStopped();
95
108
  const pid = daemonAlive();
96
109
  if (pid) {
97
110
  if (!quiet) console.log(` ${c.yellow}!${c.reset} ${'daemon running'.padEnd(16)}${c.dim}already up (pid ${pid}) · bounce it with ${c.reset}${c.cyan}claude-rpc restart${c.reset}`);
@@ -130,41 +143,40 @@ async function confirmDaemonUp({ timeoutMs = 3000, intervalMs = 100 } = {}) {
130
143
  }
131
144
  }
132
145
 
133
- function stopDaemon({ quiet = false } = {}) {
146
+ // `stop` is durable: the marker keeps the SessionStart hook, the login
147
+ // autostart and any straggler daemon from bringing it back until `start`.
148
+ // Waits for the process to actually exit (hard-kill after 3s) instead of
149
+ // reporting success for a signal that may not have landed.
150
+ async function stopDaemon({ quiet = false } = {}) {
151
+ markStopped();
134
152
  const pid = daemonAlive();
135
- if (!pid) { if (!quiet) console.log(` ${c.cyan}·${c.reset} daemon not running`); return false; }
136
- try {
137
- process.kill(pid, 'SIGTERM');
138
- if (!quiet) console.log(` ${c.green}✓${c.reset} ${'daemon stopping'.padEnd(16)}${c.dim}sent SIGTERM to pid ${pid}${c.reset}`);
153
+ if (!pid) {
154
+ if (!quiet) console.log(` ${c.cyan}·${c.reset} ${'daemon stopped'.padEnd(16)}${c.dim}wasn't running · stays off until ${c.reset}${c.cyan}claude-rpc start${c.reset}`);
139
155
  return true;
140
- } catch (e) {
141
- if (!quiet) console.log(` ${c.red}✗${c.reset} ${'stop failed'.padEnd(16)}${c.dim}${e.message}${c.reset}`);
142
- return false;
143
156
  }
157
+ const ok = await stopDaemonAndWait();
158
+ if (quiet) return ok;
159
+ if (ok) console.log(` ${c.green}✓${c.reset} ${'daemon stopped'.padEnd(16)}${c.dim}pid ${pid} · stays off until ${c.reset}${c.cyan}claude-rpc start${c.reset}`);
160
+ else console.log(` ${c.red}✗${c.reset} ${'stop failed'.padEnd(16)}${c.dim}pid ${pid} is still running — it will exit at its next check (≤30s)${c.reset}`);
161
+ return ok;
144
162
  }
145
163
 
146
- // Resolves once the replacement daemon has been spawned (true) or couldn't be
147
- // (false), so callers can confirm it and a following `stop` finds its pid.
148
- function restartDaemon() {
149
- return new Promise((resolve) => {
150
- if (!stopDaemon({ quiet: true })) { resolve(startDaemon()); return; }
151
- // Poll for the old daemon to release the PID file rather than guessing with a
152
- // fixed sleep — under load 600ms wasn't always enough, and startDaemon would
153
- // then see it "still up" and no-op, leaving NO daemon running once the old
154
- // one exited. Give up after ~3s, force-kill the wedged pid, and start anyway.
155
- const deadline = Date.now() + 3000;
156
- const tick = () => {
157
- if (!daemonAlive()) { resolve(startDaemon()); return; }
158
- if (Date.now() >= deadline) {
159
- const pid = daemonAlive();
160
- if (pid) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
161
- resolve(startDaemon());
162
- return;
163
- }
164
- setTimeout(tick, 50);
165
- };
166
- setTimeout(tick, 50);
167
- });
164
+ // Stop (and wait for) the running daemon, then start a fresh one. Resolves
165
+ // once the replacement has been spawned (true) or couldn't be (false).
166
+ async function restartDaemon() {
167
+ clearStopped();
168
+ await stopDaemonAndWait();
169
+ return startDaemon();
170
+ }
171
+
172
+ // After an update the running daemon still executes the OLD code. setup (and
173
+ // the desktop app's post-update setup) replaces a daemon older than this copy,
174
+ // or one too old to report its version.
175
+ async function replaceOutdatedDaemon() {
176
+ const pid = daemonAlive();
177
+ if (!pid || !shouldReplaceDaemon({ info: readDaemonInfo(), pid, version: VERSION })) return false;
178
+ await stopDaemonAndWait();
179
+ return true;
168
180
  }
169
181
 
170
182
  // ── Box drawing — auto-widens to fit longest line ────────────────────────────
@@ -422,7 +434,8 @@ async function showStatus() {
422
434
  console.log('');
423
435
 
424
436
  box('daemon', [
425
- pair('status', pid ? `${c.green}● running${c.reset} pid ${pid}` : `${c.red}○ not running${c.reset}`, ''),
437
+ pair('status', pid ? `${c.green}● running${c.reset} pid ${pid}${daemonVersionNote(pid)}`
438
+ : isStopped() ? `${c.yellow}○ stopped${c.reset} ${c.dim}(claude-rpc start to resume)${c.reset}` : `${c.red}○ not running${c.reset}`, ''),
426
439
  pair('client', config.clientId || '—'),
427
440
  pair('config', shortPath(CONFIG_PATH), c.gray),
428
441
  // The file behind the session shown below (hooks write one per session),
@@ -1779,8 +1792,9 @@ function profileNextStep() {
1779
1792
  }
1780
1793
  }
1781
1794
 
1782
- function profileStatus() {
1795
+ async function profileStatus() {
1783
1796
  const p = (loadConfig().profile) || {};
1797
+ const { readProfileResult } = await import('./community.js');
1784
1798
  const handleOk = lb.isValidHandle(p.handle);
1785
1799
  const boardUrl = handleOk ? `https://claude-rpc.com/u/${encodeURIComponent(p.handle)}` : '';
1786
1800
 
@@ -1791,8 +1805,22 @@ function profileStatus() {
1791
1805
  const githubLine = p.githubUser
1792
1806
  ? `${p.githubUser}${p.verified ? ` ${c.green}✓ verified${c.reset}` : ` ${c.dim}(unverified)${c.reset}`}`
1793
1807
  : `${c.dim}—${c.reset}`;
1808
+ const last = readProfileResult();
1809
+ const ago = (t) => {
1810
+ const m = Math.round((Date.now() - t) / 60_000);
1811
+ return m < 60 ? `${m}m ago` : m < 2880 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`;
1812
+ };
1813
+ const lastLines = [];
1814
+ if (p.enabled && last) {
1815
+ if (last.ok === false) {
1816
+ lastLines.push(pair('last', `${c.red}✗ refused ${ago(last.failedAt)}${c.reset} ${c.dim}${last.reason}${last.error ? ` · ${last.error}` : ''}${c.reset}`, ''));
1817
+ } else if (last.at) {
1818
+ lastLines.push(pair('last', `${c.green}✓${c.reset} ${c.dim}published ${ago(last.at)}${c.reset}`, ''));
1819
+ }
1820
+ }
1794
1821
  box('profile', [
1795
1822
  pair('state', p.enabled ? `${c.green}● publishing${c.reset}` : `${c.dim}○ off${c.reset}`, ''),
1823
+ ...lastLines,
1796
1824
  pair('handle', handleOk ? `${c.cyan}${p.handle}${c.reset}` : `${c.dim}(unset)${c.reset}`, ''),
1797
1825
  pair('name', p.displayName || `${c.dim}—${c.reset}`, ''),
1798
1826
  pair('github', githubLine, ''),
@@ -1803,6 +1831,15 @@ function profileStatus() {
1803
1831
  // Setup checklist — same shape every time, so the user always sees where
1804
1832
  // they are and the exact next command. This is the screen the daemon's
1805
1833
  // breadcrumbs point back to.
1834
+ if (p.enabled && last?.ok === false) {
1835
+ const hint = publishFailHint(last);
1836
+ for (const h of [].concat(hint)) console.log(` ${c.yellow}!${c.reset} ${c.dim}${h}${c.reset}`);
1837
+ console.log('');
1838
+ }
1839
+ if (p.enabled && last?.site) {
1840
+ for (const line of siteBreakdown(last)) console.log(` ${line}`);
1841
+ console.log('');
1842
+ }
1806
1843
  const steps = profileSteps(p);
1807
1844
  if (steps.every((s) => s.done)) {
1808
1845
  console.log(` ${c.green}✓${c.reset} all set — you're live at ${c.cyan}${boardUrl}${c.reset}`);
@@ -1912,16 +1949,51 @@ async function profilePublish() {
1912
1949
  hint: 'claude-rpc profile set --handle <name> && claude-rpc profile on', code: EX_BAD_STATE,
1913
1950
  });
1914
1951
  }
1915
- const { flushProfile } = await import('./community.js');
1952
+ const { flushProfile, recordProfileResult } = await import('./community.js');
1916
1953
  console.log(` ${c.dim}publishing @${cfg.profile.handle} to the board…${c.reset}`);
1917
1954
  const r = await flushProfile(cfg);
1955
+ recordProfileResult(r);
1918
1956
  if (r.ok) {
1919
1957
  console.log(` ${c.green}✓${c.reset} published — see it at ${c.cyan}https://claude-rpc.com/u/${encodeURIComponent(cfg.profile.handle)}${c.reset}`);
1958
+ for (const line of siteBreakdown({ ok: true, at: Date.now(), totals: r.totals, site: r.site })) console.log(` ${line}`);
1920
1959
  } else if (r.reason === 'rate-limited') {
1921
1960
  console.log(` ${c.yellow}!${c.reset} rate-limited — already published in the last minute; the board has you`);
1922
1961
  } else {
1923
- return fail(`publish failed: ${r.reason}${r.error ? ' (' + r.error + ')' : ''}`, { code: EX_SYS_ERROR });
1962
+ return fail(`publish failed: ${r.reason}${r.error ? ' (' + r.error + ')' : ''}`, { hint: publishFailHint(r), code: EX_SYS_ERROR });
1963
+ }
1964
+ }
1965
+
1966
+ // Why a publish was refused, in terms of what to do. A 409 is almost always a
1967
+ // second machine that was never linked: its local handle is the one its main
1968
+ // machine already owns, so every flush is refused and its usage never reaches
1969
+ // the board.
1970
+ function publishFailHint(r) {
1971
+ if (r.reason === 'http-409') {
1972
+ return ['this machine isn\'t linked to the identity that owns that handle',
1973
+ 'run `claude-rpc link` on a linked machine, then `claude-rpc link <code>` here'];
1974
+ }
1975
+ if (r.reason === 'network') return 'no connection to the board — the daemon retries every 30 min';
1976
+ return 'run `claude-rpc doctor`';
1977
+ }
1978
+
1979
+ // Lines describing where the board's number comes from: this machine's share,
1980
+ // the identity total, and any linked machine that has stopped reporting.
1981
+ function siteBreakdown(rec) {
1982
+ const out = [];
1983
+ if (!rec?.site) return out;
1984
+ const ms = rec.site.machines;
1985
+ const n = Array.isArray(ms) ? ms.length : null;
1986
+ const mine = rec.totals?.tokens;
1987
+ out.push(`${c.dim}this machine ${fmtNum(mine || 0)} tokens · board total ${fmtNum(rec.site.tokens || 0)}${n && n > 1 ? ` across ${n} linked machines` : ''}${c.reset}`);
1988
+ if (n && n > 1) {
1989
+ const quietDays = 3;
1990
+ const stale = ms.filter((m) => !m.self && m.updatedAt && Date.now() - m.updatedAt > quietDays * 86_400_000);
1991
+ for (const m of stale) {
1992
+ const days = Math.round((Date.now() - m.updatedAt) / 86_400_000);
1993
+ out.push(`${c.yellow}!${c.reset} ${c.dim}a linked machine (${fmtNum(m.tokens)} tokens) hasn't published in ${days} days — run ${c.reset}${c.cyan}claude-rpc profile publish${c.reset}${c.dim} there; if its daemon is down, ${c.reset}${c.cyan}claude-rpc start${c.reset}`);
1994
+ }
1924
1995
  }
1996
+ return out;
1925
1997
  }
1926
1998
 
1927
1999
  // The gist-verification dance shared by `profile verify` and setup's optional
@@ -2204,8 +2276,27 @@ async function doUpdate(argv) {
2204
2276
  }
2205
2277
  if (sub === 'status') {
2206
2278
  const st = readUpdateState();
2279
+ const ago = (t) => {
2280
+ const m = Math.round((Date.now() - t) / 60_000);
2281
+ return m < 60 ? `${m}m ago` : m < 2880 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`;
2282
+ };
2207
2283
  console.log(` ${c.cyan}·${c.reset} v${VERSION} · installed via ${kind} · auto-update ${auto && kind === 'npm-global' ? 'on' : kind === 'npm-global' ? 'off' : 'n/a'}`);
2208
- if (st.updatedTo) console.log(` ${c.dim}last auto-update: ${st.updatedFrom} → ${st.updatedTo}${c.reset}`);
2284
+ const { daemonAlive: alive, readDaemonInfo: info } = await import('./ensure-daemon.js');
2285
+ const pid = alive();
2286
+ const di = info();
2287
+ if (pid) {
2288
+ const dv = di && di.pid === pid ? di.version : null;
2289
+ if (!dv) console.log(` ${c.yellow}!${c.reset} ${c.dim}the running daemon predates version reporting — ${c.reset}${c.cyan}claude-rpc restart${c.reset}${c.dim} to run v${VERSION}${c.reset}`);
2290
+ else if (dv !== VERSION) console.log(` ${c.yellow}!${c.reset} ${c.dim}the running daemon is v${dv} — ${c.reset}${c.cyan}claude-rpc restart${c.reset}${c.dim} to run v${VERSION}${c.reset}`);
2291
+ }
2292
+ if (st.checkedAt) console.log(` ${c.dim}last check: ${ago(st.checkedAt)}${st.latest ? ` · latest v${st.latest}` : ' · registry unreachable'}${c.reset}`);
2293
+ else console.log(` ${c.dim}no check yet — the daemon checks 5 min after it starts, then every 6h${c.reset}`);
2294
+ if (st.latest && isNewer(st.latest, VERSION)) {
2295
+ const why = st.lastPlan?.latest === st.latest ? st.lastPlan.reason : null;
2296
+ console.log(` ${c.yellow}!${c.reset} v${st.latest} is out${why ? ` ${c.dim}(${why})${c.reset}` : ''} — ${c.cyan}${kind === 'npm-global' ? 'claude-rpc update now' : updateCommand(kind)}${c.reset}`);
2297
+ }
2298
+ if (st.failed) console.log(` ${c.red}✗${c.reset} ${c.dim}install of v${st.failed.version} failed ${ago(st.failed.at)}: ${String(st.failed.output || '').split('\n').pop().slice(0, 160)}${c.reset}`);
2299
+ if (st.updatedTo) console.log(` ${c.dim}last auto-update: ${st.updatedFrom} → ${st.updatedTo}${st.updatedAt ? ` (${ago(st.updatedAt)})` : ''}${c.reset}`);
2209
2300
  return;
2210
2301
  }
2211
2302
  if (sub !== 'check' && sub !== 'now') {
@@ -2226,9 +2317,17 @@ async function doUpdate(argv) {
2226
2317
  console.log(` ${c.dim}installing…${c.reset}`);
2227
2318
  const res = await installVersion(latest);
2228
2319
  if (!res.ok) fail('install failed', { hint: [res.output.slice(-300) || 'npm exited non-zero', `try: ${updateCommand(kind)}`], code: EX_BAD_STATE });
2320
+ const { installedVersion } = await import('./updater.js');
2321
+ if (installedVersion() !== latest) {
2322
+ fail(`npm finished, but this copy is still v${VERSION}`, {
2323
+ hint: [`npm installs its globals somewhere other than ${ROOT} (npm prefix / volta / pnpm)`, 'update with the tool that installed claude-rpc'],
2324
+ code: EX_BAD_STATE,
2325
+ });
2326
+ }
2229
2327
  writeUpdateState({ updatedFrom: VERSION, updatedTo: latest, updatedAt: Date.now(), failed: null });
2230
2328
  console.log(` ${c.green}✓${c.reset} updated to v${latest}`);
2231
- await restartDaemon();
2329
+ // Restart a running daemon onto the new code; a stopped one stays stopped.
2330
+ if (daemonAlive()) await restartDaemon();
2232
2331
  }
2233
2332
 
2234
2333
  function tailLog() {
@@ -2286,6 +2385,7 @@ function overview() {
2286
2385
  const vars = buildVars(state, cfg, aggregate);
2287
2386
  const dot = pid
2288
2387
  ? `${c.green}●${c.reset} running ${c.dim}pid ${pid}${c.reset}`
2388
+ : isStopped() ? `${c.yellow}○${c.reset} ${c.dim}daemon stopped — ${c.reset}${c.cyan}claude-rpc start${c.reset}${c.dim} to resume${c.reset}`
2289
2389
  : `${c.yellow}○${c.reset} ${c.dim}daemon not running${c.reset}`;
2290
2390
  if (pid) {
2291
2391
  console.log(` ${dot} ${c.gray}·${c.reset} ${c.bold}${vars.modelPretty}${c.reset} in ${c.bold}${vars.project}${c.reset} ${c.gray}·${c.reset} ${statusColor(vars.status)}${vars.statusVerbose}${c.reset}`);
@@ -2482,7 +2582,7 @@ process.on('unhandledRejection', (e) => {
2482
2582
  // Fast-exit commands touch none of the core graph (they import their own
2483
2583
  // module, if any); daemon control needs only ensure-daemon. Everything else
2484
2584
  // loads the core once up front, so its bindings are set for every handler.
2485
- const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', '__complete', 'hook', 'mcp', 'daemon', 'serve', 'wrapped', 'scan-worker', 'tail', 'logs', 'log', 'pause', 'resume', 'unpause']);
2585
+ const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', '__complete', 'hook', 'mcp', 'daemon', 'serve', 'wrapped', 'settings', 'scan-worker', 'tail', 'logs', 'log', 'pause', 'resume', 'unpause']);
2486
2586
  // `<command> --help` → that command's page (before it runs at all).
2487
2587
  if (cmd && (args.includes('--help') || args.includes('-h')) && !['hook', 'scan-worker', '__complete'].includes(cmd)) {
2488
2588
  const { findCommand } = await import('./commands.js');
@@ -2517,7 +2617,13 @@ process.on('unhandledRejection', (e) => {
2517
2617
  // immediately, instead of making the user run a separate `start`.
2518
2618
  // Best-effort — a start hiccup must never make `setup` look failed.
2519
2619
  try {
2520
- if (IS_NPX) {
2620
+ // `--auto` = the desktop app re-running setup after its own update:
2621
+ // it must not undo a `claude-rpc stop`. A person running setup means it.
2622
+ if (!args.includes('--auto')) clearStopped();
2623
+ if (!isStopped()) await replaceOutdatedDaemon();
2624
+ if (isStopped()) {
2625
+ console.log(` ${c.cyan}·${c.reset} ${'daemon stopped'.padEnd(16)}${c.dim}left off (you ran stop) · ${c.reset}${c.cyan}claude-rpc start${c.reset}${c.dim} to resume${c.reset}`);
2626
+ } else if (IS_NPX) {
2521
2627
  // Our own tree is npm's throwaway _npx cache; launch from the global
2522
2628
  // install setup just promoted to. The global copy must be resolved
2523
2629
  // EXPLICITLY (npm root -g): inside an npx run, PATH has the _npx
@@ -2601,7 +2707,7 @@ process.on('unhandledRejection', (e) => {
2601
2707
  if (!(await import('./install.js')).migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
2602
2708
  break;
2603
2709
  case 'start': if (startDaemon()) await confirmDaemonUp(); break;
2604
- case 'stop': stopDaemon(); break;
2710
+ case 'stop': await stopDaemon(); break;
2605
2711
  case 'restart': if (await restartDaemon()) await confirmDaemonUp(); break;
2606
2712
  case 'status': {
2607
2713
  const dumpFlag = args.some((a) => a === '--dump' || a === '-d');
@@ -2646,6 +2752,8 @@ process.on('unhandledRejection', (e) => {
2646
2752
  case 'wrapped':
2647
2753
  if (args.includes('--publish')) { await doWrappedPublish(args); break; }
2648
2754
  process.env.CLAUDE_RPC_OPEN_PATH = '/wrapped'; await import('./server/index.js'); break;
2755
+ case 'settings':
2756
+ process.env.CLAUDE_RPC_OPEN_PATH = '/settings'; await import('./server/index.js'); break;
2649
2757
  case 'pause': await doPause(args); break;
2650
2758
  case 'resume':
2651
2759
  case 'unpause': await doResume(); break;
@@ -2745,14 +2853,11 @@ process.on('unhandledRejection', (e) => {
2745
2853
  } catch (e) {
2746
2854
  console.warn(` ${c.yellow}!${c.reset} ${'refresh skipped'.padEnd(16)}${c.dim}${e.message}${c.reset}`);
2747
2855
  }
2748
- const wasRunning = stopDaemon({ quiet: true });
2856
+ // Wait for the old daemon to really exit (a fixed 700ms sleep let
2857
+ // startDaemon see it "still up" and no-op, leaving none running).
2858
+ await stopDaemonAndWait();
2749
2859
  try { if (existsSync(STATE_PATH)) unlinkSync(STATE_PATH); } catch { /* state.json locked or already gone — next hook will recreate it */ }
2750
- if (wasRunning) {
2751
- // Brief wait for the OS to release the pid file before we spawn.
2752
- setTimeout(() => startDaemon(), 700);
2753
- } else {
2754
- startDaemon();
2755
- }
2860
+ startDaemon();
2756
2861
  }
2757
2862
  } else if (!cmd) {
2758
2863
  // True no-args invocation in dev/npm mode → one-screen overview.
package/src/commands.js CHANGED
@@ -63,6 +63,7 @@ export const COMMANDS = [
63
63
  { name: 'wrapped', group: 'stats', summary: 'Your animated year in review',
64
64
  flags: [['--publish', 'Put it on claude-rpc.com/wrapped/<handle>'], ['--year', 'Which year', 'any'], ['--yes', 'Skip the confirm']] },
65
65
  { name: 'serve', group: 'stats', summary: 'Open the live web dashboard' },
66
+ { name: 'settings', group: 'start', summary: 'Edit your card, daemon and privacy in the browser' },
66
67
  { name: 'export', group: 'stats', summary: 'Everything as JSON, or daily rows as CSV',
67
68
  flags: [['--csv', 'Daily rows as CSV'], ['--out', 'Write to a file', 'file']] },
68
69
 
package/src/community.js CHANGED
@@ -45,6 +45,10 @@ import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
45
45
  // wipes; ensureCursor / markCursorFresh move it here once.
46
46
  export const CURSOR_PATH = join(DATA_DIR, 'community-cursor.json');
47
47
  export const LEGACY_CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
48
+ // Last profile publish result — what `claude-rpc profile` shows, so a machine
49
+ // whose publishes are rejected (unlinked → "handle taken"), or a linked machine
50
+ // that went quiet, is visible instead of a silently low site total.
51
+ export const PROFILE_STATUS_PATH = join(DATA_DIR, 'profile-status.json');
48
52
 
49
53
  export function readCursor(path = CURSOR_PATH) {
50
54
  if (!existsSync(path)) return { sessions: 0, tokens: 0, ts: 0 };
@@ -368,11 +372,41 @@ export async function flushProfile(cfg, {
368
372
  const payload = buildProfilePayload(aggregate, profile, { instanceId });
369
373
  const { res, fail } = await postJson(fetchImpl, community.endpoint, '/profile', payload);
370
374
  if (fail) return fail;
375
+ let body = null;
376
+ try { body = await res.json(); } catch { /* non-JSON body */ }
371
377
  if (!res.ok) {
372
378
  if (res.status === 429) return { ok: false, reason: 'rate-limited' };
373
- return { ok: false, reason: `http-${res.status}` };
379
+ return { ok: false, reason: `http-${res.status}`, ...(body?.error ? { error: String(body.error).slice(0, 200) } : {}) };
374
380
  }
375
- return { ok: true, totals: { tokens: payload.tokens, sessions: payload.sessions, activeMs: payload.activeMs } };
381
+ return {
382
+ ok: true,
383
+ totals: { tokens: payload.tokens, sessions: payload.sessions, activeMs: payload.activeMs },
384
+ // What the board shows for the whole identity, and per linked machine
385
+ // (no ids — just "this one" and when each last reported). Older workers
386
+ // don't send `machines`.
387
+ site: body?.profile ? {
388
+ tokens: body.profile.tokens || 0,
389
+ machines: Array.isArray(body.machines) ? body.machines.map((m) => ({
390
+ self: !!m.self, tokens: Number(m.tokens) || 0, updatedAt: Number(m.updatedAt) || null,
391
+ })) : null,
392
+ } : null,
393
+ };
394
+ }
395
+
396
+ // Persist a flushProfile result for `claude-rpc profile`. Rate-limited results
397
+ // carry no news and are skipped; a failure keeps the last success alongside it.
398
+ export function recordProfileResult(result, { path = PROFILE_STATUS_PATH, now = Date.now() } = {}) {
399
+ if (!result || result.reason === 'rate-limited' || result.reason === 'disabled') return;
400
+ let prev = {};
401
+ try { prev = JSON.parse(readFileSync(path, 'utf8')) || {}; } catch { /* first write */ }
402
+ const next = result.ok
403
+ ? { ok: true, at: now, totals: result.totals, site: result.site || null }
404
+ : { ...prev, ok: false, failedAt: now, reason: result.reason, error: result.error || null };
405
+ try { writeFileAtomic(path, JSON.stringify(next)); } catch { /* advisory */ }
406
+ }
407
+
408
+ export function readProfileResult(path = PROFILE_STATUS_PATH) {
409
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
376
410
  }
377
411
 
378
412
  // Single best-effort flush. Returns { ok, reason, delta? } — never throws.
@@ -0,0 +1,59 @@
1
+ // Config save helper for the settings page (src/server/settings.js). Pure —
2
+ // no fs — so test/config-edit.test.js can exercise it directly.
3
+ //
4
+ // The user's config.json holds OVERRIDES only. loadConfig deep-merges it over
5
+ // DEFAULT_CONFIG, and arrays REPLACE on that merge. The settings page therefore
6
+ // displays the merged view, but a save must write back only what the user
7
+ // changed. Writing the whole view would freeze every default into the file.
8
+ // Writing an untouched empty field would do worse: `presence.buttons: []`
9
+ // deletes the default button, because an array in the file replaces the default.
10
+
11
+ function isPlainObject(v) {
12
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
13
+ }
14
+
15
+ export function deepEqual(a, b) {
16
+ if (a === b) return true;
17
+ if (Array.isArray(a) || Array.isArray(b)) {
18
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
19
+ return a.every((v, i) => deepEqual(v, b[i]));
20
+ }
21
+ if (!isPlainObject(a) || !isPlainObject(b)) return false;
22
+ const ka = Object.keys(a);
23
+ if (ka.length !== Object.keys(b).length) return false;
24
+ return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
25
+ }
26
+
27
+ // Returns a copy of `raw` (the user's config.json as it is on disk now) with
28
+ // only the edits applied. `base` is what the page showed before the user
29
+ // touched anything, and `edited` is the same view after their edits. A key
30
+ // whose value is the same in both is left exactly as it is in `raw`: it isn't
31
+ // added, rewritten or removed. That also keeps keys another tool wrote while
32
+ // the page was open. A changed key is written. A changed array is written
33
+ // whole, which matches the merge rule. A key the page removed (a cleared
34
+ // field) is deleted, so the daemon falls back to its default.
35
+ export function applyEdits(raw, base, edited) {
36
+ const out = isPlainObject(raw) ? structuredClone(raw) : {};
37
+ patch(out, isPlainObject(base) ? base : {}, isPlainObject(edited) ? edited : {});
38
+ return out;
39
+ }
40
+
41
+ function patch(target, base, edited) {
42
+ for (const k of new Set([...Object.keys(base), ...Object.keys(edited)])) {
43
+ // Never let a crafted key reach Object.prototype through the save path.
44
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
45
+ const a = base[k];
46
+ const b = edited[k];
47
+ if (deepEqual(a, b)) continue;
48
+ if (b === undefined) { delete target[k]; continue; }
49
+ if (isPlainObject(a) && isPlainObject(b)) {
50
+ const had = Object.prototype.hasOwnProperty.call(target, k);
51
+ if (!isPlainObject(target[k])) target[k] = {};
52
+ patch(target[k], a, b);
53
+ // Removing a key the file never had shouldn't leave an empty `{}` behind.
54
+ if (!had && Object.keys(target[k]).length === 0) delete target[k];
55
+ continue;
56
+ }
57
+ target[k] = structuredClone(b);
58
+ }
59
+ }