claude-rpc 1.7.3 → 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 +5 -4
- package/SECURITY.md +20 -0
- package/package.json +1 -1
- package/src/cli.js +3 -1
- package/src/commands.js +1 -0
- package/src/config-edit.js +59 -0
- package/src/pricing.js +87 -43
- package/src/scanner.js +8 -4
- package/src/server/assets/dashboard.html +1 -0
- package/src/server/assets/settings.client.js +422 -0
- package/src/server/assets/settings.css +145 -0
- package/src/server/assets/settings.html +176 -0
- package/src/server/index.js +67 -16
- package/src/server/page.js +17 -3
- package/src/server/routes.js +16 -0
- package/src/server/settings.js +234 -0
- package/src/version.js +1 -1
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
6
|
+
<title>Claude · Settings</title>
|
|
7
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
8
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
9
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;700&family=Space+Grotesk:wght@500;700&display=swap" rel="stylesheet">
|
|
10
|
+
<style>
|
|
11
|
+
{{STYLES}}</style>
|
|
12
|
+
</head>
|
|
13
|
+
<body class="settings">
|
|
14
|
+
<main class="page">
|
|
15
|
+
|
|
16
|
+
<header class="topbar">
|
|
17
|
+
<div class="brand">
|
|
18
|
+
<span class="mark">◆</span>
|
|
19
|
+
<span>Settings</span>
|
|
20
|
+
</div>
|
|
21
|
+
<div class="top-right">
|
|
22
|
+
<a class="wrapped-link" href="/">← Stats</a>
|
|
23
|
+
</div>
|
|
24
|
+
</header>
|
|
25
|
+
|
|
26
|
+
<div class="set-error" id="load-error" hidden></div>
|
|
27
|
+
|
|
28
|
+
<!-- ── Daemon ──────────────────────────────────────── -->
|
|
29
|
+
<section class="set-card" aria-labelledby="h-daemon">
|
|
30
|
+
<div class="set-head">
|
|
31
|
+
<h2 id="h-daemon">Daemon</h2>
|
|
32
|
+
<span class="set-hint">The background process that updates your Discord card.</span>
|
|
33
|
+
</div>
|
|
34
|
+
<div class="daemon-row">
|
|
35
|
+
<span class="dot" id="daemon-dot"></span>
|
|
36
|
+
<div class="daemon-text">
|
|
37
|
+
<div class="daemon-title" id="daemon-title">Checking…</div>
|
|
38
|
+
<div class="daemon-sub" id="daemon-sub"></div>
|
|
39
|
+
</div>
|
|
40
|
+
<div class="btn-row">
|
|
41
|
+
<button class="btn" id="daemon-start">Start</button>
|
|
42
|
+
<button class="btn" id="daemon-restart">Restart</button>
|
|
43
|
+
<button class="btn" id="daemon-stop">Stop</button>
|
|
44
|
+
</div>
|
|
45
|
+
</div>
|
|
46
|
+
<details class="log" id="log-details">
|
|
47
|
+
<summary>Log</summary>
|
|
48
|
+
<pre id="log" tabindex="0"></pre>
|
|
49
|
+
</details>
|
|
50
|
+
</section>
|
|
51
|
+
|
|
52
|
+
<!-- ── Card ────────────────────────────────────────── -->
|
|
53
|
+
<section class="set-card" aria-labelledby="h-card">
|
|
54
|
+
<div class="set-head">
|
|
55
|
+
<h2 id="h-card">Card</h2>
|
|
56
|
+
<span class="set-hint">What Discord shows for each thing Claude is doing.</span>
|
|
57
|
+
</div>
|
|
58
|
+
<div class="seg" id="status-tabs" role="tablist" aria-label="Status"></div>
|
|
59
|
+
|
|
60
|
+
<div class="preview" aria-live="polite">
|
|
61
|
+
<div class="avatar" id="pv-avatar"></div>
|
|
62
|
+
<div class="pv-text">
|
|
63
|
+
<div class="pv-app" id="pv-app"></div>
|
|
64
|
+
<div class="pv-details" id="pv-details"></div>
|
|
65
|
+
<div class="pv-state" id="pv-state"></div>
|
|
66
|
+
</div>
|
|
67
|
+
</div>
|
|
68
|
+
|
|
69
|
+
<div class="grid2">
|
|
70
|
+
<label class="field">Top line
|
|
71
|
+
<input type="text" id="f-details" autocomplete="off" />
|
|
72
|
+
</label>
|
|
73
|
+
<label class="field">Bottom line
|
|
74
|
+
<input type="text" id="f-state" autocomplete="off" />
|
|
75
|
+
</label>
|
|
76
|
+
<label class="field">Image
|
|
77
|
+
<input type="text" id="f-asset" autocomplete="off" placeholder="Image link or Discord asset key" />
|
|
78
|
+
</label>
|
|
79
|
+
<label class="field">Image hover text
|
|
80
|
+
<input type="text" id="f-hover" autocomplete="off" />
|
|
81
|
+
</label>
|
|
82
|
+
</div>
|
|
83
|
+
<div class="insert">
|
|
84
|
+
<label for="var-pick">Insert a live value</label>
|
|
85
|
+
<select id="var-pick"><option value="">Choose…</option></select>
|
|
86
|
+
<span class="set-hint">Adds it to the line you were last typing in, like <code>{project}</code>.</span>
|
|
87
|
+
</div>
|
|
88
|
+
|
|
89
|
+
<div class="sub-head">
|
|
90
|
+
<h3>Extra frames</h3>
|
|
91
|
+
<span class="set-hint">Shown in turn after the lines above. A frame is skipped while its condition is empty.</span>
|
|
92
|
+
</div>
|
|
93
|
+
<div id="frames"></div>
|
|
94
|
+
<button class="btn ghost" id="add-frame">+ Add frame</button>
|
|
95
|
+
</section>
|
|
96
|
+
|
|
97
|
+
<!-- ── Discord ─────────────────────────────────────── -->
|
|
98
|
+
<section class="set-card" aria-labelledby="h-discord">
|
|
99
|
+
<div class="set-head"><h2 id="h-discord">Discord</h2></div>
|
|
100
|
+
<div class="grid2">
|
|
101
|
+
<label class="field">App name
|
|
102
|
+
<input type="text" id="f-appName" autocomplete="off" />
|
|
103
|
+
</label>
|
|
104
|
+
<label class="field">Application ID
|
|
105
|
+
<input type="text" id="f-clientId" inputmode="numeric" autocomplete="off" />
|
|
106
|
+
</label>
|
|
107
|
+
<label class="field">Shown as
|
|
108
|
+
<select id="f-activityType">
|
|
109
|
+
<option value="0">Playing</option>
|
|
110
|
+
<option value="2">Listening to</option>
|
|
111
|
+
<option value="3">Watching</option>
|
|
112
|
+
<option value="5">Competing in</option>
|
|
113
|
+
</select>
|
|
114
|
+
</label>
|
|
115
|
+
<div class="checks">
|
|
116
|
+
<label class="check"><input type="checkbox" id="f-showElapsed" /> Show elapsed time</label>
|
|
117
|
+
<label class="check"><input type="checkbox" id="f-githubButton" /> Link public GitHub repos</label>
|
|
118
|
+
</div>
|
|
119
|
+
</div>
|
|
120
|
+
<div class="sub-head">
|
|
121
|
+
<h3>Buttons</h3>
|
|
122
|
+
<span class="set-hint">Up to 2. Only other people see them on your card.</span>
|
|
123
|
+
</div>
|
|
124
|
+
<div id="buttons"></div>
|
|
125
|
+
<button class="btn ghost" id="add-button">+ Add button</button>
|
|
126
|
+
</section>
|
|
127
|
+
|
|
128
|
+
<!-- ── Behaviour ───────────────────────────────────── -->
|
|
129
|
+
<section class="set-card" aria-labelledby="h-behaviour">
|
|
130
|
+
<div class="set-head"><h2 id="h-behaviour">Behaviour</h2></div>
|
|
131
|
+
<div class="grid3">
|
|
132
|
+
<label class="field">Rotate frames every
|
|
133
|
+
<span class="unit"><input type="number" id="f-rotation" min="5" step="1" /> sec</span>
|
|
134
|
+
</label>
|
|
135
|
+
<label class="field">Idle after
|
|
136
|
+
<span class="unit"><input type="number" id="f-idle" min="0" step="1" /> sec</span>
|
|
137
|
+
</label>
|
|
138
|
+
<label class="field">Clear card after
|
|
139
|
+
<span class="unit"><input type="number" id="f-stale" min="0" step="1" /> min</span>
|
|
140
|
+
</label>
|
|
141
|
+
<label class="field">"Just shipped" stays
|
|
142
|
+
<span class="unit"><input type="number" id="f-shipped" min="0" step="1" /> sec</span>
|
|
143
|
+
</label>
|
|
144
|
+
</div>
|
|
145
|
+
<div class="checks row">
|
|
146
|
+
<label class="check"><input type="checkbox" id="f-hideWhenStale" /> Hide the card when Claude Code is closed</label>
|
|
147
|
+
<label class="check"><input type="checkbox" id="f-notify" /> Desktop notification when Claude needs you</label>
|
|
148
|
+
</div>
|
|
149
|
+
</section>
|
|
150
|
+
|
|
151
|
+
<!-- ── Privacy ─────────────────────────────────────── -->
|
|
152
|
+
<section class="set-card" aria-labelledby="h-privacy">
|
|
153
|
+
<div class="set-head">
|
|
154
|
+
<h2 id="h-privacy">Privacy</h2>
|
|
155
|
+
<span class="set-hint">Per project. Changes apply right away.</span>
|
|
156
|
+
</div>
|
|
157
|
+
<div id="workspaces"></div>
|
|
158
|
+
</section>
|
|
159
|
+
|
|
160
|
+
<footer>
|
|
161
|
+
<span id="config-path"></span>
|
|
162
|
+
<span>127.0.0.1:{{PORT}} · <span id="version"></span></span>
|
|
163
|
+
</footer>
|
|
164
|
+
</main>
|
|
165
|
+
|
|
166
|
+
<!-- Sticky save bar: only visible with unsaved changes or a result to report -->
|
|
167
|
+
<div class="savebar" id="savebar" hidden>
|
|
168
|
+
<span class="save-msg" id="save-msg" role="status"></span>
|
|
169
|
+
<button class="btn" id="revert">Discard</button>
|
|
170
|
+
<button class="btn primary" id="save">Save</button>
|
|
171
|
+
</div>
|
|
172
|
+
|
|
173
|
+
<script>
|
|
174
|
+
{{SCRIPT}}</script>
|
|
175
|
+
</body>
|
|
176
|
+
</html>
|
package/src/server/index.js
CHANGED
|
@@ -17,7 +17,8 @@ import { exec } from 'node:child_process';
|
|
|
17
17
|
import { ROUTES, JSON_HEADERS } from './routes.js';
|
|
18
18
|
import { projectDrilldown, dayDetail } from './api.js';
|
|
19
19
|
import { watchSources, addClient, removeClient } from './sse.js';
|
|
20
|
-
import { buildHtml, buildWrappedHtml } from './page.js';
|
|
20
|
+
import { buildHtml, buildWrappedHtml, buildSettingsHtml } from './page.js';
|
|
21
|
+
import { writeAllowed } from './settings.js';
|
|
21
22
|
|
|
22
23
|
const PORT = Number(process.env.CLAUDE_RPC_PORT) || 47474;
|
|
23
24
|
|
|
@@ -25,8 +26,10 @@ const PORT = Number(process.env.CLAUDE_RPC_PORT) || 47474;
|
|
|
25
26
|
// (shown in the footer), which is fixed for the life of the process.
|
|
26
27
|
const HTML = buildHtml({ port: PORT });
|
|
27
28
|
const WRAPPED_HTML = buildWrappedHtml();
|
|
29
|
+
const SETTINGS_HTML = buildSettingsHtml({ port: PORT });
|
|
28
30
|
const PAGES = new Map([
|
|
29
31
|
['/', HTML], ['/index.html', HTML],
|
|
32
|
+
['/settings', SETTINGS_HTML], ['/settings.html', SETTINGS_HTML], // config, daemon, privacy
|
|
30
33
|
['/wrapped', WRAPPED_HTML], ['/wrapped.html', WRAPPED_HTML], // animated year-in-review
|
|
31
34
|
]);
|
|
32
35
|
|
|
@@ -85,8 +88,9 @@ function dispatch(req, res) {
|
|
|
85
88
|
}
|
|
86
89
|
|
|
87
90
|
// Static /api/* endpoints (state, wrapped, aggregate, insights, badge.svg,
|
|
88
|
-
// card.svg, export.json, export.csv) — see routes.js.
|
|
91
|
+
// card.svg, export.json, export.csv, settings) — see routes.js.
|
|
89
92
|
const handler = ROUTES.get(key);
|
|
93
|
+
if (handler && req.method === 'POST') return handleWrite(req, res, handler, query);
|
|
90
94
|
if (handler) return handler(req, res, { query });
|
|
91
95
|
|
|
92
96
|
const page = req.method === 'GET' && PAGES.get(path);
|
|
@@ -99,6 +103,31 @@ function dispatch(req, res) {
|
|
|
99
103
|
res.writeHead(404).end('not found');
|
|
100
104
|
}
|
|
101
105
|
|
|
106
|
+
const MAX_BODY_BYTES = 512 * 1024;
|
|
107
|
+
|
|
108
|
+
function handleWrite(req, res, handler, query) {
|
|
109
|
+
const fail = (code, error) => {
|
|
110
|
+
if (!res.headersSent) res.writeHead(code, JSON_HEADERS).end(JSON.stringify({ error }));
|
|
111
|
+
};
|
|
112
|
+
if (!writeAllowed(req.headers)) return fail(403, 'forbidden');
|
|
113
|
+
const chunks = [];
|
|
114
|
+
let size = 0;
|
|
115
|
+
req.on('data', (c) => {
|
|
116
|
+
size += c.length;
|
|
117
|
+
if (size > MAX_BODY_BYTES) { fail(413, 'request too large'); req.destroy(); return; }
|
|
118
|
+
chunks.push(c);
|
|
119
|
+
});
|
|
120
|
+
req.on('error', () => fail(400, 'bad request'));
|
|
121
|
+
req.on('end', async () => {
|
|
122
|
+
if (res.headersSent) return;
|
|
123
|
+
let body;
|
|
124
|
+
try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); }
|
|
125
|
+
catch { return fail(400, 'body is not valid JSON'); }
|
|
126
|
+
try { await handler(req, res, { query, body }); }
|
|
127
|
+
catch { fail(500, 'internal error'); }
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
102
131
|
const server = createServer((req, res) => {
|
|
103
132
|
try {
|
|
104
133
|
dispatch(req, res);
|
|
@@ -117,14 +146,45 @@ const server = createServer((req, res) => {
|
|
|
117
146
|
// `claude-rpc serve`, or the tray and the Stats tab each spawning one. Say why
|
|
118
147
|
// in one line and exit non-zero instead. Once listening, an 'error' is logged
|
|
119
148
|
// and the dashboard keeps running (same policy as the floor).
|
|
120
|
-
|
|
149
|
+
// `claude-rpc wrapped` / `settings` set CLAUDE_RPC_OPEN_PATH to land on that
|
|
150
|
+
// page instead of the dashboard.
|
|
151
|
+
const OPEN_PATH = process.env.CLAUDE_RPC_OPEN_PATH || '';
|
|
152
|
+
|
|
153
|
+
function openBrowser(url) {
|
|
154
|
+
if (process.env.CLAUDE_RPC_NO_OPEN) return;
|
|
155
|
+
const opener = process.platform === 'win32' ? `start "" "${url}"`
|
|
156
|
+
: process.platform === 'darwin' ? `open "${url}"`
|
|
157
|
+
: `xdg-open "${url}"`;
|
|
158
|
+
// windowsHide so the cmd.exe that runs `start` doesn't flash a console.
|
|
159
|
+
exec(opener, { windowsHide: true }, () => {});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Is the thing already on our port a claude-rpc dashboard new enough to have
|
|
163
|
+
// the page we want? /api/settings exists on every build that serves /settings.
|
|
164
|
+
async function dashboardAlreadyUp(base) {
|
|
165
|
+
try {
|
|
166
|
+
const res = await fetch(`${base}/api/settings`, { signal: AbortSignal.timeout(1500) });
|
|
167
|
+
return res.ok && typeof (await res.json()).version === 'string';
|
|
168
|
+
} catch { return false; }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
server.on('error', async (e) => {
|
|
121
172
|
if (server.listening) {
|
|
122
173
|
try { console.error('dashboard error:', e?.message || e); } catch { /* ignore */ }
|
|
123
174
|
return;
|
|
124
175
|
}
|
|
125
176
|
const base = `http://127.0.0.1:${PORT}`;
|
|
177
|
+
// A dashboard is already running (another terminal, a previous `serve`):
|
|
178
|
+
// that's not a failure — open the page in it.
|
|
179
|
+
if (e?.code === 'EADDRINUSE' && await dashboardAlreadyUp(base)) {
|
|
180
|
+
console.log(`◆ Claude RPC dashboard is already running: ${base}${OPEN_PATH}`);
|
|
181
|
+
openBrowser(base + OPEN_PATH);
|
|
182
|
+
// Let the opener spawn before exiting.
|
|
183
|
+
setTimeout(() => process.exit(0), 300);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
126
186
|
console.error(e?.code === 'EADDRINUSE'
|
|
127
|
-
? `✗ Port ${PORT} is
|
|
187
|
+
? `✗ Port ${PORT} is in use by another program or an older claude-rpc dashboard — stop it, or set CLAUDE_RPC_PORT to use another port.`
|
|
128
188
|
: `✗ Dashboard could not listen on 127.0.0.1:${PORT}: ${e?.message || e}`);
|
|
129
189
|
process.exit(1);
|
|
130
190
|
});
|
|
@@ -134,19 +194,10 @@ server.listen(PORT, '127.0.0.1', () => {
|
|
|
134
194
|
// without leaving watchers behind.
|
|
135
195
|
watchSources();
|
|
136
196
|
const base = `http://127.0.0.1:${PORT}`;
|
|
137
|
-
|
|
138
|
-
// animated year-in-review instead of the dashboard.
|
|
139
|
-
const openPath = process.env.CLAUDE_RPC_OPEN_PATH || '';
|
|
140
|
-
const url = base + openPath;
|
|
197
|
+
const url = base + OPEN_PATH;
|
|
141
198
|
console.log(`◆ Claude RPC dashboard: ${base}`);
|
|
142
|
-
console.log(` ${
|
|
143
|
-
|
|
144
|
-
const opener = process.platform === 'win32' ? `start "" "${url}"`
|
|
145
|
-
: process.platform === 'darwin' ? `open "${url}"`
|
|
146
|
-
: `xdg-open "${url}"`;
|
|
147
|
-
// windowsHide so the cmd.exe that runs `start` doesn't flash a console.
|
|
148
|
-
exec(opener, { windowsHide: true }, () => {});
|
|
149
|
-
}
|
|
199
|
+
console.log(` ${OPEN_PATH ? 'opening ' + url + ' · ' : ''}Ctrl-C to stop.`);
|
|
200
|
+
openBrowser(url);
|
|
150
201
|
});
|
|
151
202
|
|
|
152
203
|
process.on('SIGINT', () => process.exit(0));
|
package/src/server/page.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// Composes the local web dashboard's
|
|
1
|
+
// Composes the local web dashboard's pages from on-disk assets (plus the
|
|
2
|
+
// settings.html / settings.css / settings.client.js trio for /settings):
|
|
2
3
|
// assets/dashboard.html — scaffold with {{STYLES}} {{SCRIPT}} {{PORT}}
|
|
3
4
|
// assets/dashboard.css — stylesheet
|
|
4
5
|
// assets/dashboard.client.js — vanilla browser runtime (one IIFE)
|
|
@@ -11,7 +12,7 @@
|
|
|
11
12
|
// them from disk in dev/npm and from the SEA blob in the packaged exe
|
|
12
13
|
// (see src/server/assets.js + sea-config.json).
|
|
13
14
|
//
|
|
14
|
-
//
|
|
15
|
+
// Exports buildHtml({ port }), buildWrappedHtml() and buildSettingsHtml(). The server
|
|
15
16
|
// composes each once at startup and reuses the string for every request.
|
|
16
17
|
|
|
17
18
|
import { loadAsset } from './assets.js';
|
|
@@ -22,6 +23,10 @@ const TEMPLATE = loadAsset('dashboard.html');
|
|
|
22
23
|
const STYLES = loadAsset('dashboard.css');
|
|
23
24
|
const SCRIPT = loadAsset('dashboard.client.js');
|
|
24
25
|
|
|
26
|
+
const SETTINGS_TEMPLATE = loadAsset('settings.html');
|
|
27
|
+
const SETTINGS_STYLES = loadAsset('settings.css');
|
|
28
|
+
const SETTINGS_SCRIPT = loadAsset('settings.client.js');
|
|
29
|
+
|
|
25
30
|
const WRAPPED_TEMPLATE = loadAsset('wrapped.html');
|
|
26
31
|
const WRAPPED_STYLES = loadAsset('wrapped.css');
|
|
27
32
|
const WRAPPED_SCRIPT = loadAsset('wrapped.client.js');
|
|
@@ -44,4 +49,13 @@ function buildWrappedHtml() {
|
|
|
44
49
|
.replace('{{SCRIPT}}', () => WRAPPED_SCRIPT);
|
|
45
50
|
}
|
|
46
51
|
|
|
47
|
-
|
|
52
|
+
// /settings — config editor, daemon controls, per-project privacy. Shares the
|
|
53
|
+
// dashboard's stylesheet (tokens, type, buttons) and adds its own on top.
|
|
54
|
+
function buildSettingsHtml({ port }) {
|
|
55
|
+
return SETTINGS_TEMPLATE
|
|
56
|
+
.replace('{{STYLES}}', () => STYLES + '\n' + SETTINGS_STYLES)
|
|
57
|
+
.replace('{{SCRIPT}}', () => SETTINGS_SCRIPT)
|
|
58
|
+
.replaceAll('{{PORT}}', String(port));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { buildHtml, buildWrappedHtml, buildSettingsHtml };
|
package/src/server/routes.js
CHANGED
|
@@ -9,6 +9,7 @@ import { generateInsights } from '../insights.js';
|
|
|
9
9
|
import { badgeSvg } from '../badge.js';
|
|
10
10
|
import { renderCard } from '../card.js';
|
|
11
11
|
import { snapshot, windowedAggregate, aggregateToCsv, wrappedData } from './api.js';
|
|
12
|
+
import { getSettings, saveSettings, daemonAction, getLog, listWorkspaces, setWorkspaceVisibility } from './settings.js';
|
|
12
13
|
|
|
13
14
|
export const JSON_HEADERS = {
|
|
14
15
|
'content-type': 'application/json',
|
|
@@ -89,3 +90,18 @@ ROUTES.set('GET /api/card.svg', (req, res, { query }) => {
|
|
|
89
90
|
});
|
|
90
91
|
res.end(svg);
|
|
91
92
|
});
|
|
93
|
+
|
|
94
|
+
// ── Settings page (/settings) ───────────────────────────────────────────
|
|
95
|
+
// POST handlers receive the parsed JSON body as `body`; index.js has already
|
|
96
|
+
// checked the request is same-origin JSON before it gets here.
|
|
97
|
+
const sendJson = (res, obj) => {
|
|
98
|
+
res.writeHead(obj && obj.error ? 400 : 200, JSON_HEADERS);
|
|
99
|
+
res.end(JSON.stringify(obj));
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
ROUTES.set('GET /api/settings', (req, res) => sendJson(res, getSettings()));
|
|
103
|
+
ROUTES.set('POST /api/settings', (req, res, { body }) => sendJson(res, saveSettings(body)));
|
|
104
|
+
ROUTES.set('POST /api/daemon', async (req, res, { body }) => sendJson(res, await daemonAction(body && body.action)));
|
|
105
|
+
ROUTES.set('GET /api/log', (req, res) => sendJson(res, getLog()));
|
|
106
|
+
ROUTES.set('GET /api/workspaces', (req, res) => sendJson(res, listWorkspaces()));
|
|
107
|
+
ROUTES.set('POST /api/workspaces', (req, res, { body }) => sendJson(res, setWorkspaceVisibility(body)));
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// Settings API for the local dashboard's /settings page — the config editor,
|
|
2
|
+
// daemon controls and per-project privacy that used to live in a separate
|
|
3
|
+
// Electron app. Everything here runs in-process against the same modules the
|
|
4
|
+
// CLI uses, so the page and `claude-rpc start|stop|private` can't disagree.
|
|
5
|
+
//
|
|
6
|
+
// Routes (registered in routes.js):
|
|
7
|
+
// GET /api/settings effective config + daemon status + template vars
|
|
8
|
+
// POST /api/settings { base, edited } → write only what changed
|
|
9
|
+
// POST /api/daemon { action: start|stop|restart }
|
|
10
|
+
// GET /api/log tail of daemon.log
|
|
11
|
+
// GET /api/workspaces known project dirs + their visibility
|
|
12
|
+
// POST /api/workspaces { cwd, level }
|
|
13
|
+
//
|
|
14
|
+
// The write routes are guarded in index.js (same-origin + JSON body), since a
|
|
15
|
+
// localhost server is reachable from any page the user has open.
|
|
16
|
+
|
|
17
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
18
|
+
import { basename, resolve as resolvePath } from 'node:path';
|
|
19
|
+
import { CONFIG_PATH, LOG_PATH, SCAN_CACHE_PATH } from '../paths.js';
|
|
20
|
+
import { DEFAULT_CONFIG } from '../default-config.js';
|
|
21
|
+
import { loadConfig, mergeConfig } from '../config.js';
|
|
22
|
+
import { applyEdits } from '../config-edit.js';
|
|
23
|
+
import { writeFileAtomic } from '../atomic-rename.js';
|
|
24
|
+
import { daemonAlive, spawnDaemonDetached } from '../ensure-daemon.js';
|
|
25
|
+
import { ipcStateFromLog, bridgeFromLog, classifyClientId } from '../doctor.js';
|
|
26
|
+
import { readActiveState } from '../state.js';
|
|
27
|
+
import { findLiveSessions, readAggregate } from '../scanner.js';
|
|
28
|
+
import { buildVars, applyIdle } from '../format.js';
|
|
29
|
+
import { readUsageCache } from '../usage.js';
|
|
30
|
+
import { listVisibility, setCwdVisibility } from '../privacy.js';
|
|
31
|
+
import { VERSION } from '../version.js';
|
|
32
|
+
|
|
33
|
+
// Every status the card can render, in the order the page lists them.
|
|
34
|
+
export const STATUSES = ['working', 'thinking', 'compacting', 'shipped', 'notification', 'idle'];
|
|
35
|
+
const VIS_LEVELS = ['public', 'name-only', 'hidden'];
|
|
36
|
+
const MAX_CONFIG_BYTES = 256 * 1024;
|
|
37
|
+
|
|
38
|
+
// Write routes change the user's config and start/stop their daemon, and a
|
|
39
|
+
// localhost server is reachable from every page open in the browser. Two
|
|
40
|
+
// checks keep other sites out:
|
|
41
|
+
// - Origin, when sent (browsers always send it on POST), must be this exact
|
|
42
|
+
// host:port — not merely "some localhost page".
|
|
43
|
+
// - The body must be application/json. A cross-site form can't send that
|
|
44
|
+
// without a CORS preflight, which this server never answers.
|
|
45
|
+
export function writeAllowed(headers) {
|
|
46
|
+
const type = String(headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
|
47
|
+
if (type !== 'application/json') return false;
|
|
48
|
+
const origin = headers.origin;
|
|
49
|
+
if (origin === undefined) return true; // non-browser client (curl, tests)
|
|
50
|
+
try { return new URL(origin).host === headers.host; } catch { return false; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
54
|
+
|
|
55
|
+
function tailLog(lines = 80) {
|
|
56
|
+
try {
|
|
57
|
+
if (!existsSync(LOG_PATH)) return '';
|
|
58
|
+
return readFileSync(LOG_PATH, 'utf8').split('\n').slice(-lines).join('\n').trimEnd();
|
|
59
|
+
} catch { return ''; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// running/pid from the pid file; ipc ('up'|'down'|'unknown') and the client
|
|
63
|
+
// kind from the log tail — the same reading `claude-rpc doctor` reports.
|
|
64
|
+
export function daemonStatus() {
|
|
65
|
+
const pid = daemonAlive();
|
|
66
|
+
if (!pid) return { running: false, pid: null, ipc: 'down', client: null };
|
|
67
|
+
const log = tailLog(200);
|
|
68
|
+
return { running: true, pid, ipc: ipcStateFromLog(log), client: bridgeFromLog(log) };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Live template variables, for the card preview and the {variable} picker.
|
|
72
|
+
function liveVars(config) {
|
|
73
|
+
try {
|
|
74
|
+
let state = readActiveState();
|
|
75
|
+
state.liveSessions = findLiveSessions({ thresholdMs: 90_000 });
|
|
76
|
+
state = applyIdle(state, config);
|
|
77
|
+
state.usage = readUsageCache();
|
|
78
|
+
return buildVars(state, config, readAggregate() || {});
|
|
79
|
+
} catch { return {}; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function getSettings() {
|
|
83
|
+
const config = loadConfig();
|
|
84
|
+
const live = liveVars(config);
|
|
85
|
+
return {
|
|
86
|
+
version: VERSION,
|
|
87
|
+
configPath: CONFIG_PATH,
|
|
88
|
+
config,
|
|
89
|
+
statuses: STATUSES,
|
|
90
|
+
daemon: daemonStatus(),
|
|
91
|
+
vars: Object.keys(live).sort(),
|
|
92
|
+
live,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The file as it is on disk right now. A missing file is an empty config; an
|
|
97
|
+
// unreadable or half-written one throws, because overwriting it would lose
|
|
98
|
+
// whatever is in it.
|
|
99
|
+
function readRawConfig(path) {
|
|
100
|
+
let text;
|
|
101
|
+
try { text = readFileSync(path, 'utf8'); }
|
|
102
|
+
catch (e) {
|
|
103
|
+
if (e.code === 'ENOENT') return {};
|
|
104
|
+
throw new Error(`couldn't read ${path} (${e.message})`, { cause: e });
|
|
105
|
+
}
|
|
106
|
+
let raw;
|
|
107
|
+
try { raw = JSON.parse(text); }
|
|
108
|
+
catch (e) { throw new Error(`${path} isn't valid JSON (${e.message}) — fix or delete it first`, { cause: e }); }
|
|
109
|
+
if (!isPlainObject(raw)) throw new Error(`${path} isn't a JSON object`);
|
|
110
|
+
return raw;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Reject edits that would leave the daemon unable to render anything. Kept
|
|
114
|
+
// short on purpose: the daemon already tolerates odd values by falling back
|
|
115
|
+
// to defaults, so this only catches what would silently break the card.
|
|
116
|
+
export function validateConfig(merged) {
|
|
117
|
+
if (classifyClientId(merged.clientId) !== 'ok') {
|
|
118
|
+
return 'Discord application ID must be the 17–21 digit number from the Discord developer portal';
|
|
119
|
+
}
|
|
120
|
+
for (const b of merged.presence?.buttons || []) {
|
|
121
|
+
if (!b || typeof b.label !== 'string' || !/^https?:\/\//i.test(b.url || '')) {
|
|
122
|
+
return 'Each button needs a label and an http(s) link';
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if ((merged.presence?.buttons || []).length > 2) return 'Discord shows at most 2 buttons';
|
|
126
|
+
for (const k of ['updateIntervalMs', 'rotationIntervalMs', 'idleThresholdSec', 'staleSessionMin', 'shippedFrameSec']) {
|
|
127
|
+
const v = merged[k];
|
|
128
|
+
if (v !== undefined && v !== null && !(typeof v === 'number' && Number.isFinite(v) && v >= 0)) {
|
|
129
|
+
return `${k} must be a number, 0 or more`;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// { base, edited } → writes only the keys that differ between them onto the
|
|
136
|
+
// file as it is on disk now. Returns { ok, config } or { error }.
|
|
137
|
+
// `path` is overridable for tests only.
|
|
138
|
+
export function saveSettings(body, { path = CONFIG_PATH } = {}) {
|
|
139
|
+
const { base, edited } = body || {};
|
|
140
|
+
if (!isPlainObject(base) || !isPlainObject(edited)) return { error: 'Nothing to save' };
|
|
141
|
+
let raw;
|
|
142
|
+
try { raw = readRawConfig(path); } catch (e) { return { error: `Not saved: ${e.message}` }; }
|
|
143
|
+
const next = applyEdits(raw, base, edited);
|
|
144
|
+
const problem = validateConfig(mergeConfig(DEFAULT_CONFIG, next));
|
|
145
|
+
if (problem) return { error: problem };
|
|
146
|
+
const text = JSON.stringify(next, null, 2) + '\n';
|
|
147
|
+
if (Buffer.byteLength(text) > MAX_CONFIG_BYTES) return { error: 'Config is too large to save' };
|
|
148
|
+
try { writeFileAtomic(path, text); }
|
|
149
|
+
catch (e) { return { error: `Not saved: ${e.message}` }; }
|
|
150
|
+
return { ok: true, config: loadConfig({ path }) };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
154
|
+
|
|
155
|
+
// Poll until the daemon's liveness matches `want` (true = up), or time out.
|
|
156
|
+
async function waitDaemon(want, timeoutMs) {
|
|
157
|
+
const deadline = Date.now() + timeoutMs;
|
|
158
|
+
for (;;) {
|
|
159
|
+
if (!!daemonAlive() === want) return true;
|
|
160
|
+
if (Date.now() >= deadline) return false;
|
|
161
|
+
await sleep(100);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function signal(pid, sig) {
|
|
166
|
+
try { process.kill(pid, sig); return true; } catch { return false; }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function stop() {
|
|
170
|
+
const pid = daemonAlive();
|
|
171
|
+
if (!pid) return true;
|
|
172
|
+
signal(pid, 'SIGTERM');
|
|
173
|
+
if (await waitDaemon(false, 3000)) return true;
|
|
174
|
+
// Wedged: it ignored SIGTERM for 3s. Don't leave the user with a daemon
|
|
175
|
+
// they asked to stop.
|
|
176
|
+
signal(pid, 'SIGKILL');
|
|
177
|
+
return waitDaemon(false, 1500);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function start() {
|
|
181
|
+
if (daemonAlive()) return true;
|
|
182
|
+
const child = spawnDaemonDetached();
|
|
183
|
+
if (!child || !child.pid) return false;
|
|
184
|
+
// A detached spawn can die a millisecond later (bad path, startup throw), so
|
|
185
|
+
// confirm through the pid file the daemon claims early in startup.
|
|
186
|
+
return waitDaemon(true, 3000);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export async function daemonAction(action) {
|
|
190
|
+
let ok;
|
|
191
|
+
if (action === 'start') ok = await start();
|
|
192
|
+
else if (action === 'stop') ok = await stop();
|
|
193
|
+
else if (action === 'restart') ok = (await stop()) && (await start());
|
|
194
|
+
else return { error: 'unknown action' };
|
|
195
|
+
const daemon = daemonStatus();
|
|
196
|
+
if (ok) return { ok: true, daemon };
|
|
197
|
+
const what = action === 'stop' ? "The daemon didn't stop" : "The daemon didn't come up";
|
|
198
|
+
return { error: `${what} — see the log below`, daemon };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function getLog() {
|
|
202
|
+
return { path: LOG_PATH, content: tailLog(80) };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Project directories the scanner has seen, newest activity first. Read from
|
|
206
|
+
// the scan cache (each transcript summary carries its cwd) rather than
|
|
207
|
+
// re-walking ~/.claude/projects. Subagent transcripts share their parent's cwd
|
|
208
|
+
// and collapse into it.
|
|
209
|
+
export function listWorkspaces() {
|
|
210
|
+
const seen = new Map(); // resolved cwd → { name, cwd, lastTs }
|
|
211
|
+
try {
|
|
212
|
+
const cache = JSON.parse(readFileSync(SCAN_CACHE_PATH, 'utf8'));
|
|
213
|
+
for (const f of Object.values(cache.files || {})) {
|
|
214
|
+
if (!f || typeof f.cwd !== 'string' || !f.cwd) continue;
|
|
215
|
+
const cwd = resolvePath(f.cwd);
|
|
216
|
+
const lastTs = Number(f.lastTs) || 0;
|
|
217
|
+
const prev = seen.get(cwd);
|
|
218
|
+
if (!prev || lastTs > prev.lastTs) seen.set(cwd, { name: basename(cwd) || cwd, cwd, lastTs });
|
|
219
|
+
}
|
|
220
|
+
} catch { /* no scan yet — empty list */ }
|
|
221
|
+
return {
|
|
222
|
+
workspaces: [...seen.values()].sort((a, b) => b.lastTs - a.lastTs),
|
|
223
|
+
visibility: listVisibility(),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// level: public | name-only | hidden; anything else clears the override.
|
|
228
|
+
export function setWorkspaceVisibility(body) {
|
|
229
|
+
const cwd = body && typeof body.cwd === 'string' && body.cwd ? body.cwd : null;
|
|
230
|
+
if (!cwd) return { error: 'no project given' };
|
|
231
|
+
const level = VIS_LEVELS.includes(body.level) ? body.level : null;
|
|
232
|
+
try { return { ok: true, visibility: setCwdVisibility(cwd, level) }; }
|
|
233
|
+
catch (e) { return { error: e.message }; }
|
|
234
|
+
}
|