claude-rpc 1.5.2 → 1.5.4

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 (46) hide show
  1. package/README.md +34 -24
  2. package/SECURITY.md +99 -20
  3. package/package.json +1 -1
  4. package/src/atomic-rename.js +45 -2
  5. package/src/badge.js +3 -4
  6. package/src/card.js +1 -22
  7. package/src/cli-path.js +286 -0
  8. package/src/cli.js +310 -383
  9. package/src/community.js +101 -60
  10. package/src/config.js +4 -1
  11. package/src/daemon.js +45 -47
  12. package/src/default-config.js +4 -3
  13. package/src/discord-ipc.js +24 -13
  14. package/src/doctor.js +63 -37
  15. package/src/ensure-daemon.js +11 -4
  16. package/src/fmt.js +8 -6
  17. package/src/format.js +8 -13
  18. package/src/gist.js +8 -18
  19. package/src/git.js +4 -1
  20. package/src/hook.js +27 -32
  21. package/src/insights.js +3 -4
  22. package/src/install.js +100 -79
  23. package/src/leaderboard.js +3 -2
  24. package/src/mcp.js +2 -8
  25. package/src/nudge.js +8 -3
  26. package/src/pricing.js +24 -2
  27. package/src/privacy.js +22 -7
  28. package/src/profile.js +0 -6
  29. package/src/recap.js +4 -17
  30. package/src/scanner.js +103 -71
  31. package/src/server/api.js +64 -36
  32. package/src/server/assets/dashboard.client.js +75 -44
  33. package/src/server/assets/dashboard.css +18 -18
  34. package/src/server/assets/dashboard.html +13 -15
  35. package/src/server/assets/wrapped.client.js +26 -11
  36. package/src/server/assets/wrapped.css +2 -2
  37. package/src/server/index.js +43 -32
  38. package/src/server/page.js +6 -3
  39. package/src/server/sse.js +90 -34
  40. package/src/session-card.js +3 -1
  41. package/src/state.js +14 -24
  42. package/src/tui.js +3 -12
  43. package/src/ui.js +7 -5
  44. package/src/verify.js +3 -7
  45. package/src/version.js +1 -1
  46. package/src/week.js +4 -4
package/src/community.js CHANGED
@@ -3,33 +3,48 @@
3
3
  // pre-v0.7 config keep the explicit-opt-in flow via `claude-rpc community
4
4
  // on`. Reads aggregate.json + a small cursor file to compute counter
5
5
  // DELTAs (not absolute values — the cursor moves forward as we report),
6
- // then POSTs to the configured worker endpoint.
6
+ // then POSTs to the configured worker endpoint. Also builds and sends the
7
+ // opt-in leaderboard profile (/profile) and the one-shot Claude Wrapped
8
+ // (/wrapped) payloads.
7
9
  //
8
10
  // Three guarantees this module owes the rest of the codebase:
9
11
  //
10
12
  // 1. Never throws. The daemon calls this from a setInterval and must
11
13
  // not crash on a network burp or a malformed response. All failure
12
14
  // modes resolve to `{ ok: false, reason }` and move on.
13
- // 2. Never sends anything beyond the documented payload. No file paths,
14
- // no prompts, no models, no cwd — the buildPayload function is the
15
- // complete schema, and it's audited by the worker's validateReport.
15
+ // 2. Never sends anything beyond the documented payloads. Each build*Payload
16
+ // function is the complete schema for its endpoint, mirrored by the
17
+ // worker's validators. The anonymous /report carries only counter
18
+ // deltas, version and OS family. The opt-in /profile adds the chosen
19
+ // identity, lifetime totals and a per-day token/active-time series.
20
+ // /wrapped (sent only by `wrapped --publish`, after showing the user the
21
+ // payload) adds that year's stats, including privacy-filtered project
22
+ // names, the model mix, languages and the top file's basename. Never
23
+ // file paths, prompts or cwd.
16
24
  // 3. Never advances the cursor on a failed flush. A 5xx today + a
17
25
  // successful flush tomorrow still reports today's deltas.
18
26
  //
19
27
  // See worker/src/index.js for the receiving end.
20
28
 
21
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
22
- import { join, dirname } from 'node:path';
29
+ import { readFileSync, existsSync } from 'node:fs';
30
+ import { join } from 'node:path';
23
31
  import { platform } from 'node:os';
24
- import { AGGREGATE_PATH, STATE_DIR } from './paths.js';
32
+ import { AGGREGATE_PATH, DATA_DIR, STATE_DIR } from './paths.js';
25
33
  import { VERSION } from './version.js';
26
34
  import { profileIsPublishable } from './leaderboard.js';
27
35
  import { projectNameIsPrivate } from './privacy.js';
28
36
  import { cleanProjectName, dayKey } from './scanner.js';
29
37
  import { HEATMAP_DAYS } from './heatmap.js';
30
38
  import { humanModel } from './format.js';
39
+ import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
31
40
 
32
- const CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
41
+ // How much of this install's lifetime has already been reported. It must
42
+ // survive reboots: the worker adds every delta blindly, so a lost cursor
43
+ // re-sends the whole lifetime and inflates the public counter. Through v1.5.2
44
+ // it lived in os.tmpdir() (LEGACY_CURSOR_PATH), which a reboot or temp purge
45
+ // wipes; ensureCursor / markCursorFresh move it here once.
46
+ export const CURSOR_PATH = join(DATA_DIR, 'community-cursor.json');
47
+ export const LEGACY_CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
33
48
 
34
49
  export function readCursor(path = CURSOR_PATH) {
35
50
  if (!existsSync(path)) return { sessions: 0, tokens: 0, ts: 0 };
@@ -39,8 +54,7 @@ export function readCursor(path = CURSOR_PATH) {
39
54
 
40
55
  export function writeCursor(c, path = CURSOR_PATH) {
41
56
  try {
42
- mkdirSync(dirname(path), { recursive: true });
43
- writeFileSync(path, JSON.stringify(c, null, 2));
57
+ writeFileAtomic(path, JSON.stringify(c, null, 2));
44
58
  } catch {
45
59
  // Cursor write failure is recoverable — the next flush will resend
46
60
  // the same delta, which the worker accepts (we accumulate at the
@@ -48,6 +62,45 @@ export function writeCursor(c, path = CURSOR_PATH) {
48
62
  }
49
63
  }
50
64
 
65
+ // A parsed cursor file, or null when it's missing or unreadable.
66
+ function loadCursorFile(path) {
67
+ try {
68
+ const c = JSON.parse(readFileSync(path, 'utf8'));
69
+ return c && typeof c === 'object' ? { sessions: 0, tokens: 0, ts: 0, ...c } : null;
70
+ } catch { return null; }
71
+ }
72
+
73
+ // A new identity has reported nothing yet: write an explicit zero cursor so
74
+ // its first flush sends the install's whole history. Called wherever an
75
+ // instanceId is minted (setup's seeded config, `community on`, `profile on`).
76
+ // Leaves an existing cursor alone (adopting a legacy one), so a reused machine
77
+ // only ever reports new growth. Returns true when it wrote the zero cursor.
78
+ export function markCursorFresh({ path = CURSOR_PATH, legacyPath = LEGACY_CURSOR_PATH } = {}) {
79
+ adoptLegacyFile(path, legacyPath);
80
+ if (existsSync(path)) return false;
81
+ writeCursor({ sessions: 0, tokens: 0, ts: 0 }, path);
82
+ return true;
83
+ }
84
+
85
+ // The cursor flushCommunity diffs against, in order:
86
+ // 1. the cursor at `path` (the normal case);
87
+ // 2. the legacy tmpdir cursor, moved into `path` (first flush after upgrade);
88
+ // 3. neither (or an unreadable file): seed it from the current aggregate, so
89
+ // only growth from now on is reported. A missing cursor does NOT mean
90
+ // "never reported" — a new identity gets an explicit zero cursor from
91
+ // markCursorFresh — so landing here means an install from before the move
92
+ // whose tmp cursor was wiped. Re-sending its lifetime would double-count
93
+ // it on the public counter; seeding at worst skips history it never got
94
+ // to report, the much smaller error.
95
+ export function ensureCursor(aggregate, { path = CURSOR_PATH, legacyPath = LEGACY_CURSOR_PATH, now = Date.now() } = {}) {
96
+ adoptLegacyFile(path, legacyPath);
97
+ const existing = loadCursorFile(path);
98
+ if (existing) return existing;
99
+ const seeded = { sessions: aggregate?.sessions || 0, tokens: totalTokens(aggregate), ts: now, seeded: true };
100
+ writeCursor(seeded, path);
101
+ return seeded;
102
+ }
103
+
51
104
  export function osFamily() {
52
105
  const p = platform();
53
106
  if (p === 'win32') return 'win32';
@@ -71,10 +124,7 @@ const MAX_REPORT_TOKENS = 5_000_000_000;
71
124
  // here, add it there too.
72
125
  export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }) {
73
126
  const sessions = aggregate?.sessions || 0;
74
- const tokens = (aggregate?.inputTokens || 0)
75
- + (aggregate?.outputTokens || 0)
76
- + (aggregate?.cacheReadTokens || 0)
77
- + (aggregate?.cacheWriteTokens || 0);
127
+ const tokens = totalTokens(aggregate);
78
128
  return {
79
129
  instanceId,
80
130
  sessionsDelta: Math.min(MAX_REPORT_SESSIONS, Math.max(0, sessions - (cursor.sessions || 0))),
@@ -85,13 +135,6 @@ export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }
85
135
  };
86
136
  }
87
137
 
88
- // ── leaderboard profile flush ──────────────────────────────────────────
89
- // Publishes the opt-in public profile (identity + lifetime totals) to the
90
- // worker's /profile endpoint. Reuses the anonymous community instanceId as the
91
- // profile's row key. Unlike flushCommunity this is cursor-free and idempotent —
92
- // it POSTs absolute totals, so the worker SETs (never accumulates) and a resend
93
- // is a no-op. Same safety guarantees: never throws, sends only documented fields.
94
-
95
138
  function totalTokens(aggregate) {
96
139
  return (aggregate?.inputTokens || 0)
97
140
  + (aggregate?.outputTokens || 0)
@@ -99,11 +142,13 @@ function totalTokens(aggregate) {
99
142
  + (aggregate?.cacheWriteTokens || 0);
100
143
  }
101
144
 
102
- // A profile reports ABSOLUTE lifetime totals (not deltas). It's per-user and
103
- // keyed by the instanceId, so the server just stores the latest value — no
104
- // cursor, no double-count risk, and the board matches your real aggregate
105
- // exactly. (Deltas were wrong here: the first publish carried the entire
106
- // lifetime total, which blew past the per-report caps for any established user.)
145
+ // ── leaderboard profile flush ──────────────────────────────────────────
146
+ // Publishes the opt-in public profile (identity + lifetime totals) to the
147
+ // worker's /profile endpoint. Reuses the anonymous community instanceId as the
148
+ // profile's row key. Unlike flushCommunity this is cursor-free and idempotent —
149
+ // it POSTs absolute totals, so the worker SETs (never accumulates) and a resend
150
+ // is a no-op. Same safety guarantees: never throws, sends only documented fields.
151
+
107
152
  // The last year of per-day tokens + active minutes, for the live heatmap
108
153
  // (/heatmap/<h>.svg, /stats/<h>.svg). Keyed by LOCAL date like aggregate.byDay;
109
154
  // oldest → newest with leading empty days trimmed. Only day totals — nothing
@@ -126,6 +171,11 @@ export function buildDailySeries(aggregate, now = Date.now(), days = HEATMAP_DAY
126
171
  return { end, tokens: tokens.slice(first), activeMin: activeMin.slice(first) };
127
172
  }
128
173
 
174
+ // A profile reports ABSOLUTE lifetime totals (not deltas). It's per-user and
175
+ // keyed by the instanceId, so the server just stores the latest value — no
176
+ // cursor, no double-count risk, and the board matches your real aggregate
177
+ // exactly. (Deltas were wrong here: the first publish carried the entire
178
+ // lifetime total, which blew past the per-report caps for any established user.)
129
179
  export function buildProfilePayload(aggregate, profileCfg, { instanceId, now = Date.now() }) {
130
180
  return {
131
181
  instanceId,
@@ -264,23 +314,31 @@ export function buildWrappedPayload(aggregate, config, { instanceId, year, now =
264
314
  };
265
315
  }
266
316
 
267
- // One-shot POST of a built wrapped payload. Mirrors flushProfile's error
268
- // contract: never throws, returns { ok, reason?, url? }.
269
- export async function publishWrapped(cfg, payload, { fetchImpl = globalThis.fetch } = {}) {
270
- const community = cfg?.community || {};
271
- if (!community.endpoint) return { ok: false, reason: 'no-endpoint' };
272
- const url = community.endpoint.replace(/\/+$/, '') + '/wrapped';
273
- let res;
317
+ // POST a JSON payload to `<endpoint><route>`. Resolves { res }, or { fail }:
318
+ // the { ok:false, reason:'network' } result callers return as-is. Bare fetch
319
+ // never times out; a hung peer would wedge the 30-min flush loop.
320
+ async function postJson(fetchImpl, endpoint, route, payload) {
321
+ const url = endpoint.replace(/\/+$/, '') + route;
274
322
  try {
275
- res = await fetchImpl(url, {
323
+ const res = await fetchImpl(url, {
276
324
  method: 'POST',
277
325
  headers: { 'Content-Type': 'application/json' },
278
326
  body: JSON.stringify(payload),
279
327
  signal: AbortSignal.timeout(10_000),
280
328
  });
329
+ return { res };
281
330
  } catch (e) {
282
- return { ok: false, reason: 'network', error: e.message };
331
+ return { fail: { ok: false, reason: 'network', error: e.message } };
283
332
  }
333
+ }
334
+
335
+ // One-shot POST of a built wrapped payload. Mirrors flushProfile's error
336
+ // contract: never throws, returns { ok, reason?, url? }.
337
+ export async function publishWrapped(cfg, payload, { fetchImpl = globalThis.fetch } = {}) {
338
+ const community = cfg?.community || {};
339
+ if (!community.endpoint) return { ok: false, reason: 'no-endpoint' };
340
+ const { res, fail } = await postJson(fetchImpl, community.endpoint, '/wrapped', payload);
341
+ if (fail) return fail;
284
342
  let body = null;
285
343
  try { body = await res.json(); } catch { /* non-JSON error body */ }
286
344
  if (!res.ok) {
@@ -308,18 +366,8 @@ export async function flushProfile(cfg, {
308
366
  catch { return { ok: false, reason: 'unreadable-aggregate' }; }
309
367
 
310
368
  const payload = buildProfilePayload(aggregate, profile, { instanceId });
311
- const url = community.endpoint.replace(/\/+$/, '') + '/profile';
312
- let res;
313
- try {
314
- res = await fetchImpl(url, {
315
- method: 'POST',
316
- headers: { 'Content-Type': 'application/json' },
317
- body: JSON.stringify(payload),
318
- signal: AbortSignal.timeout(10_000), // bare fetch never times out; a hung peer would wedge the 30-min flush loop
319
- });
320
- } catch (e) {
321
- return { ok: false, reason: 'network', error: e.message };
322
- }
369
+ const { res, fail } = await postJson(fetchImpl, community.endpoint, '/profile', payload);
370
+ if (fail) return fail;
323
371
  if (!res.ok) {
324
372
  if (res.status === 429) return { ok: false, reason: 'rate-limited' };
325
373
  return { ok: false, reason: `http-${res.status}` };
@@ -333,6 +381,9 @@ export async function flushProfile(cfg, {
333
381
  export async function flushCommunity(cfg, {
334
382
  aggregatePath = AGGREGATE_PATH,
335
383
  cursorPath = CURSOR_PATH,
384
+ // Only the real cursor migrates from its old tmpdir home; a caller-supplied
385
+ // path (tests) never touches it.
386
+ legacyCursorPath = cursorPath === CURSOR_PATH ? LEGACY_CURSOR_PATH : null,
336
387
  fetchImpl = globalThis.fetch,
337
388
  } = {}) {
338
389
  const community = cfg?.community || {};
@@ -345,24 +396,14 @@ export async function flushCommunity(cfg, {
345
396
  try { aggregate = JSON.parse(readFileSync(aggregatePath, 'utf8')); }
346
397
  catch { return { ok: false, reason: 'unreadable-aggregate' }; }
347
398
 
348
- const cursor = readCursor(cursorPath);
399
+ const cursor = ensureCursor(aggregate, { path: cursorPath, legacyPath: legacyCursorPath });
349
400
  const payload = buildPayload(aggregate, cursor, { instanceId: community.instanceId });
350
401
  if (payload.sessionsDelta === 0 && payload.tokensDelta === 0) {
351
402
  return { ok: true, reason: 'no-delta' };
352
403
  }
353
404
 
354
- const url = community.endpoint.replace(/\/+$/, '') + '/report';
355
- let res;
356
- try {
357
- res = await fetchImpl(url, {
358
- method: 'POST',
359
- headers: { 'Content-Type': 'application/json' },
360
- body: JSON.stringify(payload),
361
- signal: AbortSignal.timeout(10_000), // bare fetch never times out; a hung peer would wedge the 30-min flush loop
362
- });
363
- } catch (e) {
364
- return { ok: false, reason: 'network', error: e.message };
365
- }
405
+ const { res, fail } = await postJson(fetchImpl, community.endpoint, '/report', payload);
406
+ if (fail) return fail;
366
407
  if (!res.ok) {
367
408
  // 429 is rate-limit — not actually a failure, just "come back later".
368
409
  if (res.status === 429) return { ok: false, reason: 'rate-limited' };
package/src/config.js CHANGED
@@ -17,10 +17,13 @@
17
17
  // All callers (daemon, server/api, tui, cli) should go through
18
18
  // `loadConfig()` rather than reading CONFIG_PATH directly.
19
19
 
20
- import { readFileSync, existsSync } from 'node:fs';
20
+ import { createRequire } from 'node:module';
21
21
  import { CONFIG_PATH } from './paths.js';
22
22
  import { DEFAULT_CONFIG } from './default-config.js';
23
23
 
24
+ // require()d, not imported — on the hook hot path; see hook.js.
25
+ const { readFileSync, existsSync } = createRequire(import.meta.url)('node:fs');
26
+
24
27
  // "Has the user run setup?" — a separate signal from `loadConfig` because
25
28
  // loadConfig now always returns merged defaults (the daemon needs them
26
29
  // even if the file isn't there yet). Callers that want to distinguish
package/src/daemon.js CHANGED
@@ -5,7 +5,7 @@ import { basename, dirname, join } from 'node:path';
5
5
  import { Client, isBridgeUser } from './discord-ipc.js';
6
6
  import { readState, sweepStaleStateTmp, listSessionStates, sweepStaleSessionStates } from './state.js';
7
7
  import { makeRotationCursor, pickFrames, selectFrame, resolveLargeImageKey, shouldShowGithubButton, pickActiveSession, throttleDecision } from './presence.js';
8
- import { buildVars, fillTemplate, framePasses, applyIdle, applyShipped, applyTrigger } from './format.js';
8
+ import { buildVars, fillTemplate, framePasses, applyIdle, applyShipped, applyTrigger, humanProject } from './format.js';
9
9
  import { scan, readAggregate, findLiveSessions, readSessionTokens, readSessionModel } from './scanner.js';
10
10
  import { detectClaudeProcess } from './claude-proc.js';
11
11
  import { detectGithubUrl } from './git.js';
@@ -15,7 +15,6 @@ import { loadConfig } from './config.js';
15
15
  import { selfHealOnUpdate } from './install.js';
16
16
  import { VERSION } from './version.js';
17
17
  import { desktopNotify, postWebhook, shouldWebhook, shouldNotify, sanitizeLabel } from './notify.js';
18
- import { humanProject } from './format.js';
19
18
  import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH } from './paths.js';
20
19
  import { readUsageCache, pollUsage } from './usage.js';
21
20
  import { pollDecision, pollIntervalMs } from './watch-poll.js';
@@ -77,19 +76,14 @@ function loadConfigWithLog() {
77
76
  return loadConfig({ onError: (msg) => log(msg) });
78
77
  }
79
78
 
80
- // Bring an existing config.json up to date with the current defaults before
81
- // we load it. This is how upgrades reach users who just `npm update` + restart
82
- // the daemon without re-running `claude-rpc setup` — e.g. the v0.8.1 button-URL
83
- // move. Idempotent: only writes when something actually changes, so steady-state
84
- // restarts are a no-op and can't loop the config watcher. Best-effort — a
85
- // migration failure must never stop the daemon from starting.
86
79
  // Self-heal on update — when this daemon is a newer version than the last one
87
80
  // that ran, re-wire hooks (their command/path drifts across versions) and
88
81
  // migrate config to the current shape, then stamp the version. This is how an
89
82
  // `npm update` reaches users who never re-run setup: there is no install script
90
83
  // (by design), so the daemon — itself brought up by the SessionStart self-heal —
91
84
  // carries the update forward. A since-0.1.0 install converges to the current
92
- // hooks + config the first time it's used after updating.
85
+ // hooks + config the first time it's used after updating. Runs before the
86
+ // config load below; best-effort — a failure must never stop the daemon.
93
87
  try {
94
88
  const healed = selfHealOnUpdate({ silent: true });
95
89
  if (healed.changed) {
@@ -206,36 +200,31 @@ if (sweepTimer.unref) sweepTimer.unref();
206
200
  // clear-vs-push decision and the rendered frame are guaranteed to agree —
207
201
  // previously this chain ran twice and only buildActivity applied the trigger
208
202
  // overlay, so the two could diverge.
209
- function resolvePresence(opts = {}) {
203
+ function resolvePresence() {
210
204
  let state;
211
- if (opts.state) {
212
- state = opts.state; // standalone caller (preview/api) passes an explicit state
205
+ // Multi-session: each session writes its own state-<id>.json. Pick which one
206
+ // to show, sticking with the current session while it's active so the card
207
+ // doesn't thrash between projects (which also stabilizes the elapsed timer
208
+ // and the GitHub button — both follow the displayed session). Fall back to
209
+ // the legacy global state.json when there are no per-session files.
210
+ const sessions = listSessionStates();
211
+ if (sessions.length) {
212
+ const idleMs = Math.max(30_000, (config.idleThresholdSec || 60) * 1000);
213
+ const picked = pickActiveSession(sessions, displayedSessionId, Date.now(), idleMs);
214
+ displayedSessionId = picked.sessionId;
215
+ state = picked.state || readState();
216
+ // Party count from the SAME per-session list we selected from, so the
217
+ // "N sessions" field stays consistent with the card instead of wobbling
218
+ // on transcript-mtime timing.
219
+ state._liveCount = picked.liveCount;
213
220
  } else {
214
- // Multi-session: each session writes its own state-<id>.json. Pick which one
215
- // to show, sticking with the current session while it's active so the card
216
- // doesn't thrash between projects (which also stabilizes the elapsed timer
217
- // and the GitHub button — both follow the displayed session). Fall back to
218
- // the legacy global state.json when there are no per-session files.
219
- const sessions = listSessionStates();
220
- if (sessions.length) {
221
- const idleMs = Math.max(30_000, (config.idleThresholdSec || 60) * 1000);
222
- const picked = pickActiveSession(sessions, displayedSessionId, Date.now(), idleMs);
223
- displayedSessionId = picked.sessionId;
224
- state = picked.state || readState();
225
- // Party count from the SAME per-session list we selected from, so the
226
- // "N sessions" field stays consistent with the card instead of wobbling
227
- // on transcript-mtime timing.
228
- state._liveCount = picked.liveCount;
229
- } else {
230
- state = readState();
231
- }
221
+ state = readState();
232
222
  }
233
223
  // Attach live sessions BEFORE applyIdle so the stale/idle decision can
234
224
  // see ongoing transcript activity, not just this daemon's hook state.
235
- state.liveSessions = opts.liveSessions || liveSessions;
236
- // Same injection pattern for OS-level process liveness — standalone callers
237
- // (preview/api) that pass an explicit state simply leave it undefined and
238
- // get the historical transcript-only behavior.
225
+ state.liveSessions = liveSessions;
226
+ // Same for OS-level process liveness (claude-proc poll), unless the state
227
+ // already carries a verdict.
239
228
  if (state.claudeProcessAlive === undefined) state.claudeProcessAlive = claudeProcAlive;
240
229
  state = applyIdle(state, config);
241
230
  // Shipped overlay sits on top of idle/working/thinking — but never over
@@ -298,15 +287,13 @@ function resolvePresence(opts = {}) {
298
287
  return state;
299
288
  }
300
289
 
301
- function buildActivity(opts = {}) {
302
- // opts.resolved is an already-resolved state (the common path, from
303
- // pushPresence). Fall back to resolving here for any standalone caller.
304
- const state = opts.resolved || resolvePresence(opts);
305
-
290
+ // Render the Discord activity for a state resolvePresence() already resolved
291
+ // (pushPresence's single resolution per tick).
292
+ function buildActivity(state) {
306
293
  // Subscription usage rides in like liveSessions: injected onto state so
307
294
  // buildVars stays pure. Stale/missing cache → null → usage frames vanish.
308
295
  state.usage = readUsageCache();
309
- const vars = buildVars(state, config, opts.aggregate || aggregate);
296
+ const vars = buildVars(state, config, aggregate);
310
297
  const p = config.presence || {};
311
298
 
312
299
  // Pick the active set of frames + any status-level largeImageText override.
@@ -471,7 +458,7 @@ function pushPresence() {
471
458
  return;
472
459
  }
473
460
 
474
- const activity = buildActivity({ resolved });
461
+ const activity = buildActivity(resolved);
475
462
  transmit('set', activity, `Presence updated: ${activity.details || '-'} | ${activity.state || '-'}`);
476
463
  } catch (e) {
477
464
  log('pushPresence failed:', e.message);
@@ -618,9 +605,19 @@ async function connect() {
618
605
  // both hold, so the watchdog's "down, nothing pending" branch would spawn a
619
606
  // second connect() that overwrites `client` and orphans this socket. Block it.
620
607
  connecting = true;
621
- client = new Client({ clientId: config.clientId, transport: { type: 'ipc' } });
608
+ // Retire the previous client before replacing it. Left alive, a socket it
609
+ // still held (e.g. from a login that timed out) would close later and its
610
+ // 'disconnected' would mark the NEW, healthy client down and reconnect.
611
+ if (client) {
612
+ client.removeAllListeners();
613
+ try { client.destroy(); } catch { /* already gone */ }
614
+ }
615
+ const self = new Client({ clientId: config.clientId, transport: { type: 'ipc' } });
616
+ client = self;
622
617
 
623
- client.on('ready', () => {
618
+ // Every handler ignores events from a client that has since been replaced.
619
+ self.on('ready', () => {
620
+ if (client !== self) return;
624
621
  connected = true;
625
622
  // Reset backoff so the next outage also starts at RECONNECT_BASE_MS.
626
623
  reconnectDelayMs = RECONNECT_BASE_MS;
@@ -636,15 +633,16 @@ async function connect() {
636
633
  resetTransmit();
637
634
  pushPresence();
638
635
  });
639
- client.on('disconnected', () => {
636
+ self.on('disconnected', () => {
637
+ if (client !== self) return;
640
638
  connected = false;
641
639
  scheduleReconnect('Discord disconnected');
642
640
  });
643
- try { await client.login(); }
641
+ try { await self.login(); }
644
642
  catch (e) {
645
- scheduleReconnect(`Discord login failed: ${e.message}`);
643
+ if (client === self) scheduleReconnect(`Discord login failed: ${e.message}`);
646
644
  } finally {
647
- connecting = false;
645
+ if (client === self) connecting = false;
648
646
  }
649
647
  }
650
648
 
@@ -16,9 +16,10 @@ export const DEFAULT_CONFIG = {
16
16
  rotationIntervalMs: 12000,
17
17
  // Self-heal: the SessionStart hook (re)starts the daemon whenever it isn't
18
18
  // already running, so presence is assured whenever you use Claude Code —
19
- // surviving reboots, crashes, OS sleep, and platforms with no login-autostart
20
- // entry (macOS/Linux). Set false to disable that and manage the daemon
21
- // yourself with `claude-rpc start` / `stop`.
19
+ // surviving reboots, crashes, OS sleep, and a login-autostart entry (Run key
20
+ // / LaunchAgent / systemd --user) that's missing or unsupported. Set false
21
+ // to disable that and manage the daemon yourself with `claude-rpc start` /
22
+ // `stop`.
22
23
  autostart: true,
23
24
  // Minimum gap (ms) between Discord SET_ACTIVITY writes. Discord hard-limits
24
25
  // activity updates (~5 per 20s); blowing past it makes the client EMPTY the
@@ -177,6 +177,8 @@ export class Client extends EventEmitter {
177
177
  // pathList override is used by tests to point at a fake server; production
178
178
  // leaves it undefined and we discover the real Discord socket.
179
179
  this._pathList = options.transport?.pathList;
180
+ // Likewise test-only: how long login() waits for READY.
181
+ this._readyTimeoutMs = options.readyTimeoutMs ?? CONNECT_TIMEOUT_MS;
180
182
  this.socket = null;
181
183
  this.user = null;
182
184
  this._pending = new Map(); // nonce → { resolve, reject }
@@ -243,7 +245,7 @@ export class Client extends EventEmitter {
243
245
  const err = new Error('Connection timed out');
244
246
  err.code = 'ETIMEDOUT';
245
247
  reject(err);
246
- }, CONNECT_TIMEOUT_MS);
248
+ }, this._readyTimeoutMs);
247
249
  if (typeof timer === 'object' && 'unref' in timer) timer.unref();
248
250
  this._readyResolve = () => {
249
251
  clearTimeout(timer);
@@ -261,7 +263,18 @@ export class Client extends EventEmitter {
261
263
 
262
264
  this._send(OP_HANDSHAKE, { v: 1, client_id: this.clientId });
263
265
 
264
- await ready;
266
+ try {
267
+ await ready;
268
+ } catch (e) {
269
+ // A failed login must not leave its socket behind. After a READY timeout
270
+ // it used to stay open, and when the peer closed it later this client
271
+ // emitted 'disconnected' — which the daemon read as its (by then
272
+ // replaced, healthy) connection dropping, and reconnected again.
273
+ this._readyResolve = this._readyReject = null;
274
+ this._teardownSocket();
275
+ this._connected = false;
276
+ throw e;
277
+ }
265
278
  // No OAuth scopes are ever requested, so READY === ready, same as the lib.
266
279
  this.emit('ready');
267
280
  }
@@ -355,16 +368,20 @@ export class Client extends EventEmitter {
355
368
  };
356
369
  }
357
370
 
358
- _onClose(reason) {
359
- const wasConnected = this._connected || !!this.socket;
360
- // Fail any in-flight requests so awaiters don't hang forever.
371
+ // Fail every in-flight request so awaiters don't hang forever.
372
+ _rejectPending(message) {
361
373
  for (const { reject, timer } of this._pending.values()) {
362
374
  clearTimeout(timer);
363
- const err = new Error(typeof reason === 'string' ? reason : 'Connection closed');
375
+ const err = new Error(message);
364
376
  err.code = 'ECONNRESET';
365
377
  reject(err);
366
378
  }
367
379
  this._pending.clear();
380
+ }
381
+
382
+ _onClose(reason) {
383
+ const wasConnected = this._connected || !!this.socket;
384
+ this._rejectPending(typeof reason === 'string' ? reason : 'Connection closed');
368
385
  if (this._readyReject && !this._connected) {
369
386
  const err = new Error('Connection closed before ready');
370
387
  err.code = 'ECONNRESET';
@@ -394,13 +411,7 @@ export class Client extends EventEmitter {
394
411
  // Reject in-flight requests (mirrors _onClose) — a pushPresence parked on
395
412
  // `await setActivity` when the watchdog tears the client down must settle,
396
413
  // not leak as a forever-pending promise.
397
- for (const { reject, timer } of this._pending.values()) {
398
- clearTimeout(timer);
399
- const err = new Error('Client destroyed');
400
- err.code = 'ECONNRESET';
401
- reject(err);
402
- }
403
- this._pending.clear();
414
+ this._rejectPending('Client destroyed');
404
415
  this._teardownSocket();
405
416
  this._connected = false;
406
417
  }