claude-rpc 1.4.0 → 1.4.2
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/package.json +2 -2
- package/src/atomic-rename.js +46 -0
- package/src/daemon.js +40 -2
- package/src/default-config.js +10 -0
- package/src/discord-ipc.js +53 -21
- package/src/doctor.js +31 -2
- package/src/install.js +16 -5
- package/src/notify.js +10 -3
- package/src/presence.js +15 -2
- package/src/scanner.js +4 -3
- package/src/server/sse.js +48 -10
- package/src/state.js +2 -2
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-rpc",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.2",
|
|
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",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"prep:dashboard": "node ./scripts/prep-dashboard.js",
|
|
32
32
|
"dist:mac": "npm run build:exe && npm run prep:dashboard && npm --prefix dashboard run dist:mac",
|
|
33
33
|
"dist:win": "npm run build:exe && npm run prep:dashboard && npm --prefix dashboard run dist:win",
|
|
34
|
-
"test": "node
|
|
34
|
+
"test": "node ./scripts/run-tests.mjs",
|
|
35
35
|
"lint": "eslint src test vscode-extension",
|
|
36
36
|
"format": "prettier --write \"src/**/*.js\" \"test/**/*.js\"",
|
|
37
37
|
"format:check": "prettier --check \"src/**/*.js\" \"test/**/*.js\"",
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Windows can transiently refuse a rename onto an existing path — EPERM (or
|
|
2
|
+
// occasionally EBUSY/EACCES) — while something else briefly holds a handle
|
|
3
|
+
// on the destination: AV/Search-Indexer scans, or (confirmed live in CI) a
|
|
4
|
+
// directory being watched via fs.watch/ReadDirectoryChangesW, which every
|
|
5
|
+
// file this guards (state.json, the scan cache, aggregate.json) sits under.
|
|
6
|
+
// POSIX rename() is atomic and doesn't contend like this, so this is a
|
|
7
|
+
// no-op there. The lock is held single-digit milliseconds; a handful of
|
|
8
|
+
// immediate retries clears it without changing behavior anywhere else.
|
|
9
|
+
import { renameSync } from 'node:fs';
|
|
10
|
+
|
|
11
|
+
const RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
|
12
|
+
const MAX_ATTEMPTS = 5;
|
|
13
|
+
const RETRY_DELAY_MS = 20;
|
|
14
|
+
|
|
15
|
+
// Blocks the calling thread synchronously — the standard dependency-free way
|
|
16
|
+
// to sleep inside a sync call. Best-effort: if SharedArrayBuffer is ever
|
|
17
|
+
// unavailable, the retry loop just spins with no delay instead of failing.
|
|
18
|
+
function sleepSync(ms) {
|
|
19
|
+
try {
|
|
20
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
21
|
+
} catch {
|
|
22
|
+
/* no SharedArrayBuffer — retry immediately instead */
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Drop-in for fs.renameSync that tolerates Windows' transient rename locks.
|
|
27
|
+
// `platform`/`rename`/`sleep` are injectable so the retry loop is testable
|
|
28
|
+
// without a real Windows filesystem.
|
|
29
|
+
export function renameSyncRetry(src, dest, {
|
|
30
|
+
platform = process.platform,
|
|
31
|
+
rename = renameSync,
|
|
32
|
+
sleep = sleepSync,
|
|
33
|
+
} = {}) {
|
|
34
|
+
if (platform !== 'win32') return rename(src, dest);
|
|
35
|
+
let lastErr;
|
|
36
|
+
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
|
37
|
+
try {
|
|
38
|
+
return rename(src, dest);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
lastErr = e;
|
|
41
|
+
if (!RETRY_CODES.has(e.code)) throw e;
|
|
42
|
+
sleep(RETRY_DELAY_MS);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
throw lastErr;
|
|
46
|
+
}
|
package/src/daemon.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import './safe-stdio.js';
|
|
3
3
|
import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, renameSync, readdirSync } from 'node:fs';
|
|
4
4
|
import { basename, dirname, join } from 'node:path';
|
|
5
|
-
import { Client } from './discord-ipc.js';
|
|
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
8
|
import { buildVars, fillTemplate, framePasses, applyIdle, applyShipped, applyTrigger } from './format.js';
|
|
@@ -110,6 +110,11 @@ let claudeProcAlive = null;
|
|
|
110
110
|
let client = null;
|
|
111
111
|
let connected = false;
|
|
112
112
|
let connecting = false; // login() in flight — see the watchdog note in connect()
|
|
113
|
+
// True when the READY handshake identified an arRPC-style bridge (Vesktop/
|
|
114
|
+
// Equibop/web client) rather than the real Discord desktop client — see
|
|
115
|
+
// isBridgeUser in discord-ipc.js. Bridges never replay the current activity
|
|
116
|
+
// after their web client blips, so the keepalive below runs tighter there.
|
|
117
|
+
let bridgeClient = false;
|
|
113
118
|
// ── Outbound presence throttle ──────────────────────────────────────────────
|
|
114
119
|
// Discord rate-limits SET_ACTIVITY hard (~5 writes per 20s); a burst past it
|
|
115
120
|
// makes the client blank the presence until the writes stop — the actual
|
|
@@ -491,6 +496,25 @@ function maxActivityWrites() {
|
|
|
491
496
|
return Math.max(2, config.maxActivityWrites || 4);
|
|
492
497
|
}
|
|
493
498
|
|
|
499
|
+
// Presence keepalive — after this much wire silence, re-send the current frame
|
|
500
|
+
// even though it hasn't changed. The real Discord client holds an activity
|
|
501
|
+
// until told otherwise, so 60s there is pure insurance; arRPC-style bridges
|
|
502
|
+
// lose the activity whenever their web client blips and never replay it, so
|
|
503
|
+
// the interval tightens once the handshake identifies one (issue #37 — card
|
|
504
|
+
// gone on Vesktop while every write is acked). config.presenceKeepaliveSec
|
|
505
|
+
// overrides (floored at 15s); 0/false disables. Costs one SET_ACTIVITY per
|
|
506
|
+
// interval at most — far under the 4-per-20s window cap.
|
|
507
|
+
const KEEPALIVE_DESKTOP_SEC = 60;
|
|
508
|
+
const KEEPALIVE_BRIDGE_SEC = 20;
|
|
509
|
+
function presenceKeepaliveMs() {
|
|
510
|
+
const v = config.presenceKeepaliveSec;
|
|
511
|
+
if (v === 0 || v === false) return 0;
|
|
512
|
+
const sec = typeof v === 'number' && v > 0
|
|
513
|
+
? Math.max(15, v)
|
|
514
|
+
: (bridgeClient ? KEEPALIVE_BRIDGE_SEC : KEEPALIVE_DESKTOP_SEC);
|
|
515
|
+
return sec * 1000;
|
|
516
|
+
}
|
|
517
|
+
|
|
494
518
|
// Sentinel for a clear — can never collide with a real activity hash, since
|
|
495
519
|
// JSON.stringify of an activity object always begins with '{'.
|
|
496
520
|
const CLEAR_HASH = 'cleared';
|
|
@@ -500,12 +524,18 @@ const CLEAR_HASH = 'cleared';
|
|
|
500
524
|
// timer; 'skip' means the wire already shows this exact frame.
|
|
501
525
|
function transmit(kind, activity, logMsg) {
|
|
502
526
|
const hash = kind === 'clear' ? CLEAR_HASH : JSON.stringify(activity);
|
|
527
|
+
// Keepalive only re-asserts a VISIBLE frame — re-writing an already-cleared
|
|
528
|
+
// presence would burn rate-limited writes on a no-op, all night, every night.
|
|
529
|
+
const keepaliveMs = kind === 'clear' ? 0 : presenceKeepaliveMs();
|
|
530
|
+
const reassert = hash === lastSentHash; // only possible via keepalive expiry
|
|
503
531
|
const d = throttleDecision({
|
|
504
532
|
hash, lastSentHash, lastSentAt,
|
|
505
533
|
now: Date.now(), gapMs: activityGapMs(), flushPending: !!flushTimer,
|
|
506
534
|
recentSends, windowMs: activityWindowMs(), maxPerWindow: maxActivityWrites(),
|
|
535
|
+
keepaliveMs,
|
|
507
536
|
});
|
|
508
537
|
if (d.action === 'skip') { pendingSend = null; return; }
|
|
538
|
+
if (reassert) logMsg = `${logMsg} · keepalive re-assert`;
|
|
509
539
|
if (d.action === 'send') { doSend({ kind, activity, hash, logMsg }); return; }
|
|
510
540
|
// defer — remember the LATEST payload and flush it once when the gap expires.
|
|
511
541
|
pendingSend = { kind, activity, hash, logMsg };
|
|
@@ -593,7 +623,15 @@ async function connect() {
|
|
|
593
623
|
connected = true;
|
|
594
624
|
// Reset backoff so the next outage also starts at RECONNECT_BASE_MS.
|
|
595
625
|
reconnectDelayMs = RECONNECT_BASE_MS;
|
|
596
|
-
|
|
626
|
+
bridgeClient = isBridgeUser(client.user);
|
|
627
|
+
if (bridgeClient) {
|
|
628
|
+
// Doctor greps this line: "connected as" feeds ipcStateFromLog, "arrpc"
|
|
629
|
+
// feeds bridgeFromLog — keep both tokens if rewording.
|
|
630
|
+
log(`Discord RPC connected as ${client.user?.username} — arRPC-style bridge (Vesktop/Equibop/web client). ` +
|
|
631
|
+
`Bridges don't replay presence after their web client reconnects; keepalive re-asserts every ${Math.round(presenceKeepaliveMs() / 1000)}s.`);
|
|
632
|
+
} else {
|
|
633
|
+
log('Discord RPC connected as', client.user?.username);
|
|
634
|
+
}
|
|
597
635
|
resetTransmit();
|
|
598
636
|
pushPresence();
|
|
599
637
|
});
|
package/src/default-config.js
CHANGED
|
@@ -39,6 +39,16 @@ export const DEFAULT_CONFIG = {
|
|
|
39
39
|
// headroom under Discord's ~5-per-20s ceiling.
|
|
40
40
|
maxActivityWrites: 4,
|
|
41
41
|
activityWindowMs: 20000,
|
|
42
|
+
// Presence keepalive (seconds). A frame that hasn't changed is normally
|
|
43
|
+
// never re-sent — correct against Discord desktop, which holds an activity
|
|
44
|
+
// until told otherwise. arRPC-style bridges (Vesktop/Equibop/web clients)
|
|
45
|
+
// instead LOSE the activity whenever their renderer blips (background
|
|
46
|
+
// throttling of an unfocused window, a reload) and never replay it, leaving
|
|
47
|
+
// the card blank while the daemon's writes are still acked. After this much
|
|
48
|
+
// write silence the daemon re-asserts the current frame. null = auto: 60s
|
|
49
|
+
// against Discord desktop, 20s when the handshake identifies a bridge.
|
|
50
|
+
// Floored at 15; set 0 to disable.
|
|
51
|
+
presenceKeepaliveSec: null,
|
|
42
52
|
rescanIntervalSec: 300,
|
|
43
53
|
idleThresholdSec: 60,
|
|
44
54
|
// Time (minutes) of no hook activity AND no live transcripts on disk before
|
package/src/discord-ipc.js
CHANGED
|
@@ -73,6 +73,21 @@ export function candidatePaths(platform = process.platform) {
|
|
|
73
73
|
return out;
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
+
// arRPC — the open-source RPC bridge that Vesktop/Equibop bundle and web-client
|
|
77
|
+
// setups run standalone — answers the handshake READY with a mock user instead
|
|
78
|
+
// of the real account: id 1045800378228281345, username "arrpc". Detecting it
|
|
79
|
+
// matters because bridges do NOT replay the current activity when their web
|
|
80
|
+
// client reconnects (arRPC keeps no last-activity state), so presence silently
|
|
81
|
+
// vanishes on any renderer blip — background throttling of an unfocused window,
|
|
82
|
+
// a reload — until the daemon happens to write a *different* frame. The daemon
|
|
83
|
+
// tightens its keepalive re-assert when this returns true.
|
|
84
|
+
export const ARRPC_USER_ID = '1045800378228281345';
|
|
85
|
+
export function isBridgeUser(user) {
|
|
86
|
+
if (!user) return false;
|
|
87
|
+
if (String(user.id || '') === ARRPC_USER_ID) return true;
|
|
88
|
+
return /^arrpc$/i.test(String(user.username || ''));
|
|
89
|
+
}
|
|
90
|
+
|
|
76
91
|
// Encode one IPC frame: 8-byte little-endian header + JSON body.
|
|
77
92
|
export function encodeFrame(op, data) {
|
|
78
93
|
const body = data === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(data));
|
|
@@ -169,29 +184,46 @@ export class Client extends EventEmitter {
|
|
|
169
184
|
this._decode = null;
|
|
170
185
|
}
|
|
171
186
|
|
|
187
|
+
// Try one candidate path; resolves the connected socket, or null on
|
|
188
|
+
// error/timeout. Never rejects — callers race/sequence these freely.
|
|
189
|
+
_tryConnect(p) {
|
|
190
|
+
return new Promise((resolve) => {
|
|
191
|
+
const s = net.createConnection(p);
|
|
192
|
+
let timer = null;
|
|
193
|
+
const cleanup = () => {
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
s.removeListener('connect', onOk);
|
|
196
|
+
s.removeListener('error', onErr);
|
|
197
|
+
};
|
|
198
|
+
const onErr = () => { cleanup(); resolve(null); };
|
|
199
|
+
const onOk = () => { cleanup(); resolve(s); };
|
|
200
|
+
// A peer that accepts then stalls would otherwise never settle this
|
|
201
|
+
// candidate and block the rest each discovery cycle (and leak the fd).
|
|
202
|
+
timer = setTimeout(() => { cleanup(); s.destroy(); resolve(null); }, SOCKET_CONNECT_TIMEOUT_MS);
|
|
203
|
+
if (typeof timer === 'object' && 'unref' in timer) timer.unref();
|
|
204
|
+
s.once('connect', onOk);
|
|
205
|
+
s.once('error', onErr);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
172
209
|
async _openSocket() {
|
|
173
210
|
const paths = this._pathList ?? candidatePaths();
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
s.once('error', onErr);
|
|
191
|
-
});
|
|
192
|
-
if (socket) return socket;
|
|
193
|
-
}
|
|
194
|
-
return null;
|
|
211
|
+
// Race every candidate concurrently rather than trying them one at a
|
|
212
|
+
// time. On posix this list is already existence-filtered (usually just
|
|
213
|
+
// one path), so it barely matters — but on Windows all 10 named-pipe
|
|
214
|
+
// paths are probed unconditionally (no existence pre-check is possible),
|
|
215
|
+
// so a sequential loop pays up to 10× SOCKET_CONNECT_TIMEOUT_MS in the
|
|
216
|
+
// worst case (Discord not running). Racing caps discovery at one timeout
|
|
217
|
+
// regardless of candidate count. `Promise.all` (not `race`) so a losing
|
|
218
|
+
// socket can still be found and destroyed rather than leaked, and so the
|
|
219
|
+
// winner is picked by path order — preserving "prefer discord-ipc-0" even
|
|
220
|
+
// when more than one candidate accepts (e.g. a bridge alongside real
|
|
221
|
+
// Discord).
|
|
222
|
+
const sockets = await Promise.all(paths.map((p) => this._tryConnect(p)));
|
|
223
|
+
const winner = sockets.findIndex((s) => s !== null);
|
|
224
|
+
if (winner === -1) return null;
|
|
225
|
+
sockets.forEach((s, i) => { if (s && i !== winner) { try { s.destroy(); } catch { /* already gone */ } } });
|
|
226
|
+
return sockets[winner];
|
|
195
227
|
}
|
|
196
228
|
|
|
197
229
|
// Connect, handshake, and resolve once Discord sends READY (which also
|
package/src/doctor.js
CHANGED
|
@@ -134,6 +134,21 @@ export function ipcStateFromLog(logText) {
|
|
|
134
134
|
return ipc;
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
// Which client answered the RPC handshake, from the most recent "connected as"
|
|
138
|
+
// line: 'arrpc' for an arRPC-style bridge (Vesktop/Equibop/web client — the
|
|
139
|
+
// bridge's mock user is literally named arrpc), 'discord' for the real desktop
|
|
140
|
+
// client, null when the log has no connect line. Most-recent-wins, like
|
|
141
|
+
// ipcStateFromLog — a user who switches from Vesktop to stock Discord mid-run
|
|
142
|
+
// should not keep the bridge caveat.
|
|
143
|
+
export function bridgeFromLog(logText) {
|
|
144
|
+
let kind = null;
|
|
145
|
+
for (const line of String(logText || '').split('\n').slice(-200)) {
|
|
146
|
+
const m = line.match(/Discord RPC connected as\s+(\S+)/i);
|
|
147
|
+
if (m) kind = /arrpc/i.test(m[1]) ? 'arrpc' : 'discord';
|
|
148
|
+
}
|
|
149
|
+
return kind;
|
|
150
|
+
}
|
|
151
|
+
|
|
137
152
|
function checkConfig() {
|
|
138
153
|
if (!existsSync(CONFIG_PATH)) {
|
|
139
154
|
check('config.json present', 'fail', CONFIG_PATH,
|
|
@@ -310,11 +325,25 @@ function checkDaemonLog() {
|
|
|
310
325
|
// Ns" / "login failed" / "disconnected" line means it dropped. Whichever
|
|
311
326
|
// happened most recently wins.
|
|
312
327
|
let ipc = 'unknown';
|
|
313
|
-
|
|
314
|
-
|
|
328
|
+
let bridge = null;
|
|
329
|
+
try {
|
|
330
|
+
const logText = readFileSync(LOG_PATH, 'utf8');
|
|
331
|
+
ipc = ipcStateFromLog(logText);
|
|
332
|
+
bridge = bridgeFromLog(logText);
|
|
333
|
+
} catch { /* log unreadable — ipc stays 'unknown', warn renders */ }
|
|
315
334
|
if (ipc === 'up') {
|
|
316
335
|
check('discord IPC connection', 'pass',
|
|
317
336
|
`connected · ${sizeKB} KB log · last write ${ageMin.toFixed(1)} min ago`);
|
|
337
|
+
if (bridge === 'arrpc') {
|
|
338
|
+
// The single most-reported "presence vanished but doctor is green" cause:
|
|
339
|
+
// an arRPC bridge acks every write on the socket, but loses the activity
|
|
340
|
+
// whenever its web client blips (unfocused window throttled, reload) and
|
|
341
|
+
// never replays it. The daemon's keepalive re-asserts within ~20s of the
|
|
342
|
+
// client being able to display again — but while the renderer is down,
|
|
343
|
+
// nothing any RPC app writes will show.
|
|
344
|
+
check('discord client', 'info', 'arRPC bridge (Vesktop/Equibop/web) — not Discord desktop',
|
|
345
|
+
'bridges drop presence while their window is unfocused/reloading; the daemon re-asserts it every ~20s. if the card stays gone, focus the client window — or use Discord desktop');
|
|
346
|
+
}
|
|
318
347
|
} else if (ipc === 'down') {
|
|
319
348
|
check('discord IPC connection', 'warn', 'daemon is reconnecting to Discord',
|
|
320
349
|
'is the discord desktop client running? rpc only works via desktop, not browser', 'discord');
|
package/src/install.js
CHANGED
|
@@ -200,6 +200,20 @@ export function launchdPlist({ exe, args }) {
|
|
|
200
200
|
].join('\n');
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
+
// Windows Run-key command + windowless .vbs shim content — pure, exported so
|
|
204
|
+
// they're unit-testable without touching reg.exe/wscript or the real
|
|
205
|
+
// filesystem (mirrors launchdPlist/systemdUnit above).
|
|
206
|
+
export function windowsRunCommand({ exe, args }) {
|
|
207
|
+
return [exe, ...args].map((p) => `"${p}"`).join(' ');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function windowsVbsShim({ exe, args }) {
|
|
211
|
+
// In a VBS string literal a doubled quote is an escaped quote, so each
|
|
212
|
+
// `""x""` below reaches the shell as `"x"`.
|
|
213
|
+
const vbsCmd = [exe, ...args].map((p) => `""${p}""`).join(' ');
|
|
214
|
+
return `CreateObject("WScript.Shell").Run "${vbsCmd}", 0, False\r\n`;
|
|
215
|
+
}
|
|
216
|
+
|
|
203
217
|
export function systemdUnit({ exe, args }) {
|
|
204
218
|
const execStart = [exe, ...args].map((a) => `"${a}"`).join(' '); // quote each token (paths with spaces)
|
|
205
219
|
return [
|
|
@@ -289,13 +303,10 @@ export async function addStartupEntry(exePath) {
|
|
|
289
303
|
// a Run entry of `"node.exe" daemon` (no script path) and login-autostart
|
|
290
304
|
// silently launched nothing.
|
|
291
305
|
const launch = daemonLaunch(exePath);
|
|
292
|
-
let runCmd =
|
|
306
|
+
let runCmd = windowsRunCommand(launch);
|
|
293
307
|
try {
|
|
294
308
|
mkdirSync(CANONICAL_INSTALL_DIR, { recursive: true });
|
|
295
|
-
|
|
296
|
-
// `""x""` below reaches the shell as `"x"`.
|
|
297
|
-
const vbsCmd = [launch.exe, ...launch.args].map((p) => `""${p}""`).join(' ');
|
|
298
|
-
writeFileSync(STARTUP_VBS, `CreateObject("WScript.Shell").Run "${vbsCmd}", 0, False\r\n`);
|
|
309
|
+
writeFileSync(STARTUP_VBS, windowsVbsShim(launch));
|
|
299
310
|
runCmd = `wscript.exe "${STARTUP_VBS}"`;
|
|
300
311
|
} catch { /* couldn't write the shim — fall back to the direct (windowed) entry */ }
|
|
301
312
|
await regCommand([
|
package/src/notify.js
CHANGED
|
@@ -29,9 +29,9 @@ export function sanitizeLabel(s) {
|
|
|
29
29
|
* @param {string} [body] - Notification body text.
|
|
30
30
|
* @returns {boolean} true if a notifier was spawned, false on failure.
|
|
31
31
|
*/
|
|
32
|
-
export function desktopNotify(title, body = '', { spawn: spawnFn = spawn } = {}) {
|
|
32
|
+
export function desktopNotify(title, body = '', { spawn: spawnFn = spawn, platform: platformFn = platform } = {}) {
|
|
33
33
|
try {
|
|
34
|
-
const p =
|
|
34
|
+
const p = platformFn();
|
|
35
35
|
// A missing notifier binary (e.g. no `notify-send`) makes spawn emit an
|
|
36
36
|
// async 'error' event — with no listener that surfaces as an UNCAUGHT
|
|
37
37
|
// exception that the sync try/catch below can't stop, which would crash
|
|
@@ -45,10 +45,17 @@ export function desktopNotify(title, body = '', { spawn: spawnFn = spawn } = {})
|
|
|
45
45
|
const script = `display notification ${JSON.stringify(body)} with title ${JSON.stringify(title)}`;
|
|
46
46
|
swallow(spawnFn('osascript', ['-e', script], { stdio: 'ignore', detached: true }));
|
|
47
47
|
} else if (p === 'win32') {
|
|
48
|
+
// ShowBalloonTip is async — it returns as soon as the toast is queued,
|
|
49
|
+
// not once it's rendered. Without holding the process open, PowerShell
|
|
50
|
+
// reaches end-of-script and exits immediately after, tearing down the
|
|
51
|
+
// NotifyIcon before Windows ever draws the balloon, so it silently
|
|
52
|
+
// never appears. Sleep past the tip's own 5s display window before
|
|
53
|
+
// disposing, so the process outlives what it just asked for.
|
|
48
54
|
const script = `Add-Type -AssemblyName System.Windows.Forms;`
|
|
49
55
|
+ `$n=New-Object System.Windows.Forms.NotifyIcon;`
|
|
50
56
|
+ `$n.Icon=[System.Drawing.SystemIcons]::Information;$n.Visible=$true;`
|
|
51
|
-
+ `$n.ShowBalloonTip(5000, ${JSON.stringify(title)}, ${JSON.stringify(body)}, 'Info')
|
|
57
|
+
+ `$n.ShowBalloonTip(5000, ${JSON.stringify(title)}, ${JSON.stringify(body)}, 'Info');`
|
|
58
|
+
+ `Start-Sleep -Seconds 6;$n.Dispose()`;
|
|
52
59
|
swallow(spawnFn('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { stdio: 'ignore', detached: true, windowsHide: true }));
|
|
53
60
|
} else {
|
|
54
61
|
swallow(spawnFn('notify-send', ['-a', 'Claude Code', title, body], { stdio: 'ignore', detached: true }));
|
package/src/presence.js
CHANGED
|
@@ -130,8 +130,21 @@ export function shouldShowGithubButton(p, state) {
|
|
|
130
130
|
// in the window expires, guaranteeing no more than `maxPerWindow` writes in any
|
|
131
131
|
// `windowMs` no matter how many triggers fire. Omitting them keeps the old
|
|
132
132
|
// gap-only behavior (used by tests that predate the cap).
|
|
133
|
-
|
|
134
|
-
|
|
133
|
+
//
|
|
134
|
+
// `keepaliveMs` (optional) re-opens the identical-hash skip after that much
|
|
135
|
+
// wire silence. Against the real Discord client an unchanged frame never needs
|
|
136
|
+
// re-sending — the client holds an activity until told otherwise — but arRPC-
|
|
137
|
+
// style bridges (Vesktop/Equibop/web) lose the activity whenever their web
|
|
138
|
+
// client blips and never replay it (arRPC keeps no last-activity state), so a
|
|
139
|
+
// quiet single-frame status would stay invisible forever while every doctor
|
|
140
|
+
// check reads green (#37). Once `now - lastSentAt >= keepaliveMs` the frame is
|
|
141
|
+
// treated as changed and flows through the same gap/window limiting as any
|
|
142
|
+
// other write. Omitted/0 keeps the pure skip.
|
|
143
|
+
export function throttleDecision({ hash, lastSentHash, lastSentAt, now, gapMs, flushPending, recentSends, windowMs, maxPerWindow, keepaliveMs }) {
|
|
144
|
+
if (hash === lastSentHash) {
|
|
145
|
+
const due = keepaliveMs > 0 && lastSentAt > 0 && now - lastSentAt >= keepaliveMs;
|
|
146
|
+
if (!due) return { action: 'skip', waitMs: 0 };
|
|
147
|
+
}
|
|
135
148
|
let waitMs = Math.max(0, (lastSentAt || 0) + gapMs - now);
|
|
136
149
|
if (maxPerWindow && windowMs && Array.isArray(recentSends)) {
|
|
137
150
|
// Strict window (age < windowMs) so a write exactly windowMs old has already
|
package/src/scanner.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { readdirSync, readFileSync, statSync, existsSync, writeFileSync, mkdirSync,
|
|
1
|
+
import { readdirSync, readFileSync, statSync, existsSync, writeFileSync, mkdirSync, openSync, readSync, closeSync, realpathSync } from 'node:fs';
|
|
2
2
|
import { join, dirname, basename } from 'node:path';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { CLAUDE_PROJECTS, SCAN_CACHE_PATH, AGGREGATE_PATH, DATA_DIR, EVENTS_LOG_PATH } from './paths.js';
|
|
5
5
|
import { languageOf } from './languages.js';
|
|
6
6
|
import { costFor, pricingKeyFor } from './pricing.js';
|
|
7
7
|
import { classifyShip } from './ships.js';
|
|
8
|
+
import { renameSyncRetry } from './atomic-rename.js';
|
|
8
9
|
|
|
9
10
|
// Bumping this forces a full re-parse on next scan. Increment whenever the
|
|
10
11
|
// per-transcript summary schema changes in a way old caches can't satisfy.
|
|
@@ -783,7 +784,7 @@ function writeCache(cache) {
|
|
|
783
784
|
// rename land a half-written file (or ENOENT the other's rename).
|
|
784
785
|
const tmp = `${SCAN_CACHE_PATH}.${process.pid}.tmp`;
|
|
785
786
|
writeFileSync(tmp, JSON.stringify(cache));
|
|
786
|
-
|
|
787
|
+
renameSyncRetry(tmp, SCAN_CACHE_PATH);
|
|
787
788
|
}
|
|
788
789
|
|
|
789
790
|
// Per-day notification counts come from a hook-side append log, since
|
|
@@ -818,7 +819,7 @@ function writeAggregate(agg) {
|
|
|
818
819
|
ensureDataDir();
|
|
819
820
|
const tmp = `${AGGREGATE_PATH}.${process.pid}.tmp`;
|
|
820
821
|
writeFileSync(tmp, JSON.stringify(agg, null, 2));
|
|
821
|
-
|
|
822
|
+
renameSyncRetry(tmp, AGGREGATE_PATH);
|
|
822
823
|
}
|
|
823
824
|
|
|
824
825
|
export function readAggregate() {
|
package/src/server/sse.js
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
// Replaces the old 2-second poll. Two debounced fs.watch handles, one
|
|
4
4
|
// shared client set.
|
|
5
5
|
|
|
6
|
-
import { watch } from 'node:fs';
|
|
6
|
+
import { watch, existsSync, statSync } from 'node:fs';
|
|
7
7
|
import { dirname, basename } from 'node:path';
|
|
8
8
|
import { STATE_PATH, AGGREGATE_PATH } from '../paths.js';
|
|
9
|
+
import { pollDecision, pollIntervalMs } from '../watch-poll.js';
|
|
9
10
|
|
|
10
11
|
export const sseClients = new Set();
|
|
11
12
|
|
|
@@ -60,14 +61,51 @@ export function watchFile(filePath, callback) {
|
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
64
|
+
function statMtime(filePath) {
|
|
65
|
+
try {
|
|
66
|
+
return existsSync(filePath) ? statSync(filePath).mtimeMs : undefined;
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined; // mid-rename; a later observation records it
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
63
72
|
export function watchSources() {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
+
const targets = [
|
|
74
|
+
{ path: STATE_PATH, type: 'state' },
|
|
75
|
+
{ path: AGGREGATE_PATH, type: 'aggregate' },
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
// Last mtime we've reacted to, per target. Updated by BOTH the watcher and
|
|
79
|
+
// the poll fallback below, so a change one path already handled resolves
|
|
80
|
+
// to a no-op for the other instead of a duplicate broadcast — same shared-
|
|
81
|
+
// baseline trick the daemon's own watchFiles() uses.
|
|
82
|
+
const lastMtime = new Map();
|
|
83
|
+
const debounceTimers = new Map();
|
|
84
|
+
const recordMtime = (t) => {
|
|
85
|
+
const m = statMtime(t.path);
|
|
86
|
+
if (m !== undefined) lastMtime.set(t.path, m);
|
|
87
|
+
};
|
|
88
|
+
targets.forEach(recordMtime); // seed baselines before watching starts
|
|
89
|
+
|
|
90
|
+
const fire = (t) => {
|
|
91
|
+
recordMtime(t); // record before the debounced broadcast so a re-entrant tick can't double-fire
|
|
92
|
+
clearTimeout(debounceTimers.get(t.path));
|
|
93
|
+
debounceTimers.set(t.path, setTimeout(() => broadcast({ type: t.type }), 200));
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
for (const t of targets) watchFile(t.path, () => fire(t));
|
|
97
|
+
|
|
98
|
+
// Mtime-poll fallback. fs.watch drops atomic-rename events on Windows (see
|
|
99
|
+
// watch-poll.js), and unlike the daemon this watcher previously had no
|
|
100
|
+
// backstop at all — a missed event left the dashboard silently stale until
|
|
101
|
+
// some unrelated broadcast happened to fire. Same cadence as the daemon's
|
|
102
|
+
// fallback: fast on Windows, lazy on macOS/Linux.
|
|
103
|
+
setInterval(() => {
|
|
104
|
+
for (const t of targets) {
|
|
105
|
+
const cur = statMtime(t.path);
|
|
106
|
+
const decision = pollDecision(lastMtime.get(t.path), cur);
|
|
107
|
+
if (decision === 'seed') lastMtime.set(t.path, cur);
|
|
108
|
+
else if (decision === 'fire') fire(t);
|
|
109
|
+
}
|
|
110
|
+
}, pollIntervalMs());
|
|
73
111
|
}
|
package/src/state.js
CHANGED
|
@@ -3,7 +3,6 @@ import {
|
|
|
3
3
|
mkdirSync,
|
|
4
4
|
readFileSync,
|
|
5
5
|
writeFileSync,
|
|
6
|
-
renameSync,
|
|
7
6
|
openSync,
|
|
8
7
|
closeSync,
|
|
9
8
|
unlinkSync,
|
|
@@ -14,6 +13,7 @@ import {
|
|
|
14
13
|
import { basename, join } from 'node:path';
|
|
15
14
|
import { STATE_PATH, STATE_DIR } from './paths.js';
|
|
16
15
|
import { pickActiveSession } from './presence.js';
|
|
16
|
+
import { renameSyncRetry } from './atomic-rename.js';
|
|
17
17
|
|
|
18
18
|
const DEFAULT_STATE = {
|
|
19
19
|
sessionStart: null,
|
|
@@ -190,7 +190,7 @@ export function writeState(next, sessionId) {
|
|
|
190
190
|
// atomic-rename guarantee intact even on the best-effort lockless path.
|
|
191
191
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
192
192
|
writeFileSync(tmp, JSON.stringify(next, null, 2));
|
|
193
|
-
|
|
193
|
+
renameSyncRetry(tmp, path);
|
|
194
194
|
}
|
|
195
195
|
|
|
196
196
|
// Best-effort sweep of orphaned per-pid tmp files (`state.json.<pid>.tmp`) left
|