claude-rpc 1.7.4 → 1.8.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.8.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
@@ -2482,7 +2482,7 @@ process.on('unhandledRejection', (e) => {
2482
2482
  // Fast-exit commands touch none of the core graph (they import their own
2483
2483
  // module, if any); daemon control needs only ensure-daemon. Everything else
2484
2484
  // 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']);
2485
+ 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
2486
  // `<command> --help` → that command's page (before it runs at all).
2487
2487
  if (cmd && (args.includes('--help') || args.includes('-h')) && !['hook', 'scan-worker', '__complete'].includes(cmd)) {
2488
2488
  const { findCommand } = await import('./commands.js');
@@ -2646,6 +2646,8 @@ process.on('unhandledRejection', (e) => {
2646
2646
  case 'wrapped':
2647
2647
  if (args.includes('--publish')) { await doWrappedPublish(args); break; }
2648
2648
  process.env.CLAUDE_RPC_OPEN_PATH = '/wrapped'; await import('./server/index.js'); break;
2649
+ case 'settings':
2650
+ process.env.CLAUDE_RPC_OPEN_PATH = '/settings'; await import('./server/index.js'); break;
2649
2651
  case 'pause': await doPause(args); break;
2650
2652
  case 'resume':
2651
2653
  case 'unpause': await doResume(); break;
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
 
@@ -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
+ }
@@ -28,6 +28,7 @@
28
28
  <button data-range="all">All</button>
29
29
  </div>
30
30
  <a class="wrapped-link" href="/wrapped" title="Your animated year-in-review">✦ Wrapped</a>
31
+ <a class="wrapped-link" href="/settings" title="Card, daemon and privacy settings">Settings</a>
31
32
  <span class="model" id="model">—</span>
32
33
  <span class="status"><span id="statustext">—</span></span>
33
34
  </div>
@@ -0,0 +1,422 @@
1
+ // /settings runtime — vanilla, one IIFE, no build step.
2
+ //
3
+ // `base` is the config as the server showed it; `cfg` is the working copy the
4
+ // form edits. Save sends both, and the server writes only what differs (see
5
+ // src/config-edit.js), so defaults are never frozen into the user's file.
6
+ (function () {
7
+ const $ = (id) => document.getElementById(id);
8
+ const clone = (v) => JSON.parse(JSON.stringify(v));
9
+
10
+ let base = null; // config as loaded
11
+ let cfg = null; // working copy
12
+ let live = {}; // live template variables, for the preview
13
+ let statuses = [];
14
+ let status = 'working';
15
+ let lastTemplateInput = null;
16
+
17
+ // ── tiny DOM helper ────────────────────────────────────────────────────
18
+ function el(tag, attrs, children) {
19
+ const n = document.createElement(tag);
20
+ for (const [k, v] of Object.entries(attrs || {})) {
21
+ if (k === 'class') n.className = v;
22
+ else if (k === 'text') n.textContent = v;
23
+ else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
24
+ else if (v !== false && v != null) n.setAttribute(k, v === true ? '' : v);
25
+ }
26
+ for (const c of [].concat(children || [])) if (c) n.appendChild(c);
27
+ return n;
28
+ }
29
+
30
+ async function api(path, body) {
31
+ const opts = body === undefined ? {} : {
32
+ method: 'POST',
33
+ headers: { 'content-type': 'application/json' },
34
+ body: JSON.stringify(body),
35
+ };
36
+ let res;
37
+ try { res = await fetch(path, opts); }
38
+ catch { return { error: "Can't reach the dashboard — is `claude-rpc serve` still running?" }; }
39
+ try { return await res.json(); }
40
+ catch { return { error: 'Unexpected reply from the dashboard (' + res.status + ')' }; }
41
+ }
42
+
43
+ // ── config accessors ───────────────────────────────────────────────────
44
+ function statusBlock() {
45
+ cfg.presence = cfg.presence || {};
46
+ cfg.presence.byStatus = cfg.presence.byStatus || {};
47
+ return (cfg.presence.byStatus[status] = cfg.presence.byStatus[status] || {});
48
+ }
49
+ function frames() {
50
+ const b = statusBlock();
51
+ return Array.isArray(b.rotation) ? b.rotation : [];
52
+ }
53
+ // An emptied list is stored as [] when the loaded config had frames there:
54
+ // deleting the key would bring the default frames back on the next load.
55
+ function storeFrames(block, name, list) {
56
+ const had = Array.isArray((((base.presence || {}).byStatus || {})[name] || {}).rotation);
57
+ if (list.length || had) block.rotation = list;
58
+ else delete block.rotation;
59
+ }
60
+ function setFrames(list) { storeFrames(statusBlock(), status, list); }
61
+
62
+ // ── template preview ───────────────────────────────────────────────────
63
+ // Same shape as the daemon's fill: unknown or empty variables render as
64
+ // nothing, then separators left dangling by an empty value are tidied.
65
+ function fill(tpl) {
66
+ if (!tpl) return '';
67
+ return String(tpl)
68
+ .replace(/\{(\w+)\}/g, (m, k) => (live[k] === undefined || live[k] === null ? '' : String(live[k])))
69
+ .replace(/(\s*·\s*)+/g, ' · ')
70
+ .replace(/^\s*·\s*|\s*·\s*$/g, '')
71
+ .trim();
72
+ }
73
+
74
+ function renderPreview() {
75
+ const b = statusBlock();
76
+ $('pv-app').textContent = cfg.appName || 'Claude Code';
77
+ $('pv-details').textContent = fill(b.details) || '—';
78
+ $('pv-state').textContent = fill(b.state);
79
+ const url = (cfg.statusAssets || {})[status] || (cfg.presence || {}).largeImageKey || '';
80
+ const av = $('pv-avatar');
81
+ av.textContent = '';
82
+ if (/^https?:\/\//i.test(url)) av.appendChild(el('img', { src: url, alt: '' }));
83
+ }
84
+
85
+ // ── Card section ───────────────────────────────────────────────────────
86
+ function renderTabs() {
87
+ const root = $('status-tabs');
88
+ root.textContent = '';
89
+ for (const s of statuses) {
90
+ root.appendChild(el('button', {
91
+ role: 'tab', 'aria-selected': String(s === status), text: s,
92
+ onclick: () => { status = s; renderCard(); },
93
+ }));
94
+ }
95
+ }
96
+
97
+ function requiresText(f) {
98
+ return Array.isArray(f.requires) ? f.requires.join(', ') : (f.requires || '');
99
+ }
100
+ function parseRequires(text) {
101
+ const parts = text.split(',').map((s) => s.trim()).filter(Boolean);
102
+ return parts.length === 0 ? undefined : parts.length === 1 ? parts[0] : parts;
103
+ }
104
+
105
+ function templateInput(value, placeholder, label, oninput) {
106
+ return el('input', {
107
+ type: 'text', value: value || '', placeholder, 'aria-label': label, autocomplete: 'off',
108
+ 'data-template': true, oninput: (e) => oninput(e.target.value),
109
+ });
110
+ }
111
+
112
+ function renderFrames() {
113
+ const root = $('frames');
114
+ root.textContent = '';
115
+ const list = frames();
116
+ if (!list.length) root.appendChild(el('div', { class: 'empty', text: 'No extra frames for this status.' }));
117
+ list.forEach((f, i) => {
118
+ const update = (key, val) => {
119
+ const next = clone(frames());
120
+ if (val === undefined || val === '') delete next[i][key];
121
+ else next[i][key] = val;
122
+ setFrames(next);
123
+ changed();
124
+ };
125
+ root.appendChild(el('div', { class: 'frame-row' }, [
126
+ templateInput(f.details, 'Top line', 'Frame ' + (i + 1) + ' top line', (v) => update('details', v)),
127
+ templateInput(f.state, 'Bottom line', 'Frame ' + (i + 1) + ' bottom line', (v) => update('state', v)),
128
+ el('input', {
129
+ type: 'text', value: requiresText(f), placeholder: 'Only when…', autocomplete: 'off',
130
+ 'aria-label': 'Frame ' + (i + 1) + ' condition', title: 'Value name that must be non-empty, e.g. streak',
131
+ oninput: (e) => update('requires', parseRequires(e.target.value)),
132
+ }),
133
+ el('button', {
134
+ class: 'x', text: '×', 'aria-label': 'Remove frame ' + (i + 1),
135
+ onclick: () => { const next = clone(frames()); next.splice(i, 1); setFrames(next); renderFrames(); changed(); },
136
+ }),
137
+ ]));
138
+ });
139
+ }
140
+
141
+ function renderCard() {
142
+ renderTabs();
143
+ const b = statusBlock();
144
+ $('f-details').value = b.details || '';
145
+ $('f-state').value = b.state || '';
146
+ $('f-hover').value = b.largeImageText || '';
147
+ $('f-asset').value = (cfg.statusAssets || {})[status] || '';
148
+ renderFrames();
149
+ renderPreview();
150
+ }
151
+
152
+ // ── Discord section ────────────────────────────────────────────────────
153
+ function buttons() { return Array.isArray((cfg.presence || {}).buttons) ? cfg.presence.buttons : []; }
154
+ function setButtons(list) { cfg.presence = cfg.presence || {}; cfg.presence.buttons = list; }
155
+
156
+ function renderButtons() {
157
+ const root = $('buttons');
158
+ root.textContent = '';
159
+ const list = buttons();
160
+ if (!list.length) root.appendChild(el('div', { class: 'empty', text: 'No buttons.' }));
161
+ list.forEach((b, i) => {
162
+ const update = (key, val) => { const next = clone(buttons()); next[i][key] = val; setButtons(next); changed(); };
163
+ root.appendChild(el('div', { class: 'button-row' }, [
164
+ el('input', { type: 'text', value: b.label || '', placeholder: 'Label', 'aria-label': 'Button ' + (i + 1) + ' label', maxlength: 32, oninput: (e) => update('label', e.target.value) }),
165
+ el('input', { type: 'url', value: b.url || '', placeholder: 'https://…', 'aria-label': 'Button ' + (i + 1) + ' link', oninput: (e) => update('url', e.target.value.trim()) }),
166
+ el('button', { class: 'x', text: '×', 'aria-label': 'Remove button ' + (i + 1), onclick: () => { const next = clone(buttons()); next.splice(i, 1); setButtons(next); renderButtons(); changed(); } }),
167
+ ]));
168
+ });
169
+ $('add-button').disabled = list.length >= 2;
170
+ }
171
+
172
+ function renderForm() {
173
+ renderCard();
174
+ $('f-appName').value = cfg.appName || '';
175
+ $('f-clientId').value = cfg.clientId || '';
176
+ $('f-activityType').value = String(cfg.activityType == null ? 0 : cfg.activityType);
177
+ $('f-showElapsed').checked = cfg.showElapsed !== false;
178
+ $('f-githubButton').checked = (cfg.presence || {}).githubButton !== false;
179
+ renderButtons();
180
+ $('f-rotation').value = cfg.rotationIntervalMs == null ? '' : Math.round(cfg.rotationIntervalMs / 1000);
181
+ $('f-idle').value = cfg.idleThresholdSec == null ? '' : cfg.idleThresholdSec;
182
+ $('f-stale').value = cfg.staleSessionMin == null ? '' : cfg.staleSessionMin;
183
+ $('f-shipped').value = cfg.shippedFrameSec == null ? '' : cfg.shippedFrameSec;
184
+ $('f-hideWhenStale').checked = cfg.hideWhenStale !== false;
185
+ $('f-notify').checked = !!(cfg.notify && cfg.notify.enabled);
186
+ }
187
+
188
+ // ── form → cfg bindings ────────────────────────────────────────────────
189
+ function bind(id, apply, event) {
190
+ $(id).addEventListener(event || 'input', (e) => { apply(e.target); changed(); });
191
+ }
192
+ // A cleared text line is removed from the block, so the daemon uses its default.
193
+ const setOrDelete = (obj, key, val) => { if (val === '') delete obj[key]; else obj[key] = val; };
194
+ // A cleared number is removed too; a typed one is stored scaled (sec → ms).
195
+ const numOrDelete = (key, scale) => (t) => {
196
+ if (t.value === '' || !Number.isFinite(Number(t.value))) delete cfg[key];
197
+ else cfg[key] = Math.max(0, Number(t.value)) * (scale || 1);
198
+ };
199
+
200
+ function wire() {
201
+ bind('f-details', (t) => { setOrDelete(statusBlock(), 'details', t.value); renderPreview(); });
202
+ bind('f-state', (t) => { setOrDelete(statusBlock(), 'state', t.value); renderPreview(); });
203
+ bind('f-hover', (t) => setOrDelete(statusBlock(), 'largeImageText', t.value));
204
+ bind('f-asset', (t) => {
205
+ cfg.statusAssets = cfg.statusAssets || {};
206
+ setOrDelete(cfg.statusAssets, status, t.value.trim());
207
+ renderPreview();
208
+ });
209
+ bind('f-appName', (t) => { setOrDelete(cfg, 'appName', t.value.trim()); renderPreview(); });
210
+ bind('f-clientId', (t) => { cfg.clientId = t.value.trim(); });
211
+ bind('f-activityType', (t) => { cfg.activityType = Number(t.value) || 0; }, 'change');
212
+ bind('f-showElapsed', (t) => { cfg.showElapsed = t.checked; }, 'change');
213
+ bind('f-githubButton', (t) => { cfg.presence = cfg.presence || {}; cfg.presence.githubButton = t.checked; }, 'change');
214
+ bind('f-rotation', numOrDelete('rotationIntervalMs', 1000));
215
+ bind('f-idle', numOrDelete('idleThresholdSec'));
216
+ bind('f-stale', numOrDelete('staleSessionMin'));
217
+ bind('f-shipped', numOrDelete('shippedFrameSec'));
218
+ bind('f-hideWhenStale', (t) => { cfg.hideWhenStale = t.checked; }, 'change');
219
+ bind('f-notify', (t) => { cfg.notify = cfg.notify || {}; cfg.notify.enabled = t.checked; }, 'change');
220
+
221
+ $('add-frame').addEventListener('click', () => {
222
+ setFrames(clone(frames()).concat([{ details: '', state: '' }]));
223
+ renderFrames();
224
+ changed();
225
+ const rows = $('frames').querySelectorAll('.frame-row');
226
+ if (rows.length) rows[rows.length - 1].querySelector('input').focus();
227
+ });
228
+ $('add-button').addEventListener('click', () => {
229
+ if (buttons().length >= 2) return;
230
+ setButtons(clone(buttons()).concat([{ label: '', url: '' }]));
231
+ renderButtons();
232
+ changed();
233
+ const rows = $('buttons').querySelectorAll('.button-row');
234
+ rows[rows.length - 1].querySelector('input').focus();
235
+ });
236
+
237
+ // "Insert value" — drops {name} at the cursor of the last template line
238
+ // the user was in.
239
+ const noteTemplateInput = (e) => {
240
+ if (e.target.matches && e.target.matches('#f-details, #f-state, #f-hover, [data-template]')) lastTemplateInput = e.target;
241
+ };
242
+ document.addEventListener('focusin', noteTemplateInput);
243
+ document.addEventListener('input', noteTemplateInput);
244
+ $('var-pick').addEventListener('change', (e) => {
245
+ const name = e.target.value;
246
+ e.target.value = '';
247
+ const input = lastTemplateInput && document.contains(lastTemplateInput) ? lastTemplateInput : $('f-details');
248
+ if (!name) return;
249
+ const at = input.selectionStart == null ? input.value.length : input.selectionStart;
250
+ const end = input.selectionEnd == null ? at : input.selectionEnd;
251
+ input.value = input.value.slice(0, at) + '{' + name + '}' + input.value.slice(end);
252
+ input.focus();
253
+ input.setSelectionRange(at + name.length + 2, at + name.length + 2);
254
+ input.dispatchEvent(new Event('input', { bubbles: true }));
255
+ });
256
+
257
+ $('save').addEventListener('click', save);
258
+ $('revert').addEventListener('click', () => { cfg = clone(base); renderForm(); changed(); });
259
+ document.addEventListener('keydown', (e) => {
260
+ if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); if (dirty()) save(); }
261
+ });
262
+ window.addEventListener('beforeunload', (e) => { if (dirty()) { e.preventDefault(); e.returnValue = ''; } });
263
+
264
+ $('daemon-start').addEventListener('click', () => daemon('start'));
265
+ $('daemon-stop').addEventListener('click', () => daemon('stop'));
266
+ $('daemon-restart').addEventListener('click', () => daemon('restart'));
267
+ $('log-details').addEventListener('toggle', () => { if ($('log-details').open) refreshLog(); });
268
+ }
269
+
270
+ // ── save bar ───────────────────────────────────────────────────────────
271
+ const dirty = () => !!base && JSON.stringify(base) !== JSON.stringify(cfg);
272
+ let noticeTimer = null;
273
+
274
+ function bar(kind, msg) {
275
+ const b = $('savebar');
276
+ b.className = 'savebar' + (kind ? ' ' + kind : '');
277
+ $('save-msg').textContent = msg;
278
+ const editing = kind === '' || kind === 'err';
279
+ $('save').hidden = !editing || !dirty();
280
+ $('revert').hidden = !editing || !dirty();
281
+ b.hidden = false;
282
+ }
283
+ function changed() {
284
+ clearTimeout(noticeTimer);
285
+ if (dirty()) bar('', 'Unsaved changes');
286
+ else $('savebar').hidden = true;
287
+ }
288
+
289
+ // Rows the user added and left blank aren't settings — drop them rather
290
+ // than write empty frames/buttons into the file.
291
+ function pruneBlanks() {
292
+ for (const [name, block] of Object.entries((cfg.presence || {}).byStatus || {})) {
293
+ if (!Array.isArray(block.rotation)) continue;
294
+ storeFrames(block, name, block.rotation.filter((f) => f && (f.details || f.state)));
295
+ }
296
+ if (Array.isArray((cfg.presence || {}).buttons)) {
297
+ cfg.presence.buttons = cfg.presence.buttons.filter((b) => b && (b.label || b.url));
298
+ }
299
+ }
300
+
301
+ async function save() {
302
+ pruneBlanks();
303
+ $('save').disabled = true;
304
+ const r = await api('/api/settings', { base, edited: cfg });
305
+ $('save').disabled = false;
306
+ if (r.error) { bar('err', r.error); return; }
307
+ base = r.config;
308
+ cfg = clone(base);
309
+ renderForm();
310
+ bar('ok', 'Saved. The card updates within a few seconds.');
311
+ noticeTimer = setTimeout(() => { if (!dirty()) $('savebar').hidden = true; }, 3500);
312
+ }
313
+
314
+ // ── daemon ─────────────────────────────────────────────────────────────
315
+ function renderDaemon(d, note) {
316
+ const dot = $('daemon-dot');
317
+ let title, sub, cls;
318
+ if (!d.running) {
319
+ cls = 'down'; title = 'Stopped'; sub = 'Your Discord card is not being updated.';
320
+ } else if (d.ipc === 'up') {
321
+ cls = 'up'; title = 'Running · connected to Discord';
322
+ sub = d.client === 'arrpc' ? 'Through a bridge client (Vesktop, arRPC).' : 'pid ' + d.pid;
323
+ } else {
324
+ cls = 'wait'; title = 'Running · waiting for Discord';
325
+ sub = 'Open the Discord desktop app. It connects within about 15 seconds.';
326
+ }
327
+ dot.className = 'dot ' + cls;
328
+ $('daemon-title').textContent = title;
329
+ $('daemon-sub').textContent = note || sub;
330
+ $('daemon-start').disabled = d.running;
331
+ $('daemon-stop').disabled = !d.running;
332
+ $('daemon-restart').disabled = !d.running;
333
+ }
334
+
335
+ async function daemon(action) {
336
+ for (const id of ['daemon-start', 'daemon-stop', 'daemon-restart']) $(id).disabled = true;
337
+ $('daemon-title').textContent = action === 'stop' ? 'Stopping…' : action === 'start' ? 'Starting…' : 'Restarting…';
338
+ $('daemon-sub').textContent = '';
339
+ $('daemon-dot').className = 'dot wait';
340
+ const r = await api('/api/daemon', { action });
341
+ renderDaemon(r.daemon || { running: false }, r.error || '');
342
+ if (r.error) $('log-details').open = true;
343
+ if ($('log-details').open) refreshLog();
344
+ }
345
+
346
+ async function refreshLog() {
347
+ const r = await api('/api/log');
348
+ const pre = $('log');
349
+ pre.textContent = r.error ? r.error : (r.content || 'The log is empty.');
350
+ pre.scrollTop = pre.scrollHeight;
351
+ }
352
+
353
+ async function pollDaemon() {
354
+ if (document.hidden) return;
355
+ const r = await api('/api/settings');
356
+ if (r.error || !r.daemon) return;
357
+ renderDaemon(r.daemon);
358
+ live = r.live || live;
359
+ if (cfg) renderPreview();
360
+ }
361
+
362
+ // ── privacy ────────────────────────────────────────────────────────────
363
+ const LEVELS = [['public', 'Public'], ['name-only', 'Name only'], ['hidden', 'Hidden']];
364
+
365
+ async function loadWorkspaces() {
366
+ const root = $('workspaces');
367
+ const r = await api('/api/workspaces');
368
+ root.textContent = '';
369
+ if (r.error) { root.appendChild(el('div', { class: 'empty', text: r.error })); return; }
370
+ if (!r.workspaces.length) {
371
+ root.appendChild(el('div', { class: 'empty', text: 'No projects yet. Use Claude Code in a project and it will appear here.' }));
372
+ return;
373
+ }
374
+ for (const ws of r.workspaces) {
375
+ const current = r.visibility[ws.cwd] || 'public';
376
+ const seg = el('div', { class: 'seg', role: 'group', 'aria-label': 'Visibility of ' + ws.name });
377
+ for (const [level, label] of LEVELS) {
378
+ seg.appendChild(el('button', {
379
+ text: label, 'aria-pressed': String(level === current),
380
+ onclick: async (e) => {
381
+ const res = await api('/api/workspaces', { cwd: ws.cwd, level });
382
+ if (res.error) { bar('err', res.error); return; }
383
+ for (const b of seg.children) b.setAttribute('aria-pressed', String(b === e.target));
384
+ },
385
+ }));
386
+ }
387
+ root.appendChild(el('div', { class: 'ws-row' }, [
388
+ el('div', { class: 'ws-meta' }, [
389
+ el('div', { class: 'ws-name', text: ws.name }),
390
+ el('div', { class: 'ws-path', text: ws.cwd, title: ws.cwd }),
391
+ ]),
392
+ seg,
393
+ ]));
394
+ }
395
+ }
396
+
397
+ // ── boot ───────────────────────────────────────────────────────────────
398
+ async function boot() {
399
+ const r = await api('/api/settings');
400
+ if (r.error) {
401
+ $('load-error').textContent = r.error;
402
+ $('load-error').hidden = false;
403
+ return;
404
+ }
405
+ base = r.config;
406
+ cfg = clone(base);
407
+ live = r.live || {};
408
+ statuses = r.statuses || ['working', 'idle'];
409
+ status = statuses[0];
410
+ const pick = $('var-pick');
411
+ for (const v of r.vars || []) pick.appendChild(el('option', { value: v, text: v }));
412
+ $('config-path').textContent = r.configPath;
413
+ $('version').textContent = 'v' + r.version;
414
+ wire();
415
+ renderForm();
416
+ renderDaemon(r.daemon);
417
+ loadWorkspaces();
418
+ setInterval(pollDaemon, 5000);
419
+ }
420
+
421
+ boot();
422
+ })();