clavarium 0.2.231-beta.1 → 0.2.232-beta.1
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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +2 -0
- package/server/apikeys.mjs +56 -4
- package/server/grants.mjs +4 -3
- package/server/main.mjs +11 -2
- package/server/profile.mjs +123 -0
- package/server/serverlogs.mjs +7 -2
- package/server/settingswords.mjs +3 -1
- package/server/vm.mjs +6 -4
- package/web/app.js +47 -5
- package/web/index.html +6 -1
- package/web/style.css +1 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.232-beta.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.232-beta.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -143,6 +143,7 @@
|
|
|
143
143
|
* POST /api/server/vm-manager {mode: night|always|ask}: when it hangs, restarted by itself at night (default), always, or never
|
|
144
144
|
* POST /api/server/vm-manager/restart {confirm: true}: restarted now; every machine is suspended and resumed
|
|
145
145
|
* GET /api/server/load host commands by 5-minute window, event-loop delay
|
|
146
|
+
* POST /api/server/profile {seconds}: this server sampled by its own profiler (2-30 s), what holds it
|
|
146
147
|
* GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart POST /api/server/reboot (the whole server)
|
|
147
148
|
* GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
|
|
148
149
|
* POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
|
|
@@ -770,6 +771,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
770
771
|
const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
|
|
771
772
|
if (reactSet && reacting) { const n = decodeURIComponent(reactSet[1]); if (!conversations.list().some((c) => c.name === n)) throw new Refusal(404, 'No such conversation.'); return send(200, reacting.set(n, body)), true; }
|
|
772
773
|
if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
|
|
774
|
+
if (pathname === '/api/server/profile' && serverLogs) return send(200, await serverLogs.profile(body?.seconds ?? 10)), true;
|
|
773
775
|
if (pathname === '/api/server/restart' && serverLogs) return send(202, await serverLogs.restart()), true;
|
|
774
776
|
if (pathname === '/api/server/reboot' && serverLogs) return send(202, await serverLogs.reboot()), true;
|
|
775
777
|
if (pathname === '/api/machines/grow' && machinesMove) return send(200, await machinesMove.grow(String(body.mount ?? ''))), true;
|
package/server/apikeys.mjs
CHANGED
|
@@ -13,6 +13,9 @@
|
|
|
13
13
|
* moved, restarted, its own updates of the day -- and each
|
|
14
14
|
* job's log, as Settings shows them (jobs.mjs; secrets
|
|
15
15
|
* masked) server:jobs r
|
|
16
|
+
* diagnostics the server's load (host commands by 5 min, its event loop),
|
|
17
|
+
* 10 s of its own profiler (what holds it), its logs (as
|
|
18
|
+
* Settings reads them, secrets masked) server:diagnostics r
|
|
16
19
|
*
|
|
17
20
|
* a conversation, given ONE BY ONE (never "all, and those to come"):
|
|
18
21
|
* read read its chat conversation:<name> r
|
|
@@ -89,6 +92,7 @@
|
|
|
89
92
|
* POST /api/apikeys {label, scopes, conversations: {name: 'read'|'talk'}, days|null}
|
|
90
93
|
* -> {key, secret}: the secret this once
|
|
91
94
|
* POST /api/apikeys/<id>/conversations {conversation, level: 'read'|'talk'|null}: one given, changed, taken back
|
|
95
|
+
* POST /api/apikeys/<id>/scopes {scope, on: true|false}: one scope given or taken back afterwards (18-11)
|
|
92
96
|
* POST /api/apikeys/<id>/rooms {room, level: 'read'|'talk'|null}
|
|
93
97
|
* POST /api/apikeys/<id>/boxes {box, level: 'state'|'speak'|null}
|
|
94
98
|
* POST /api/apikeys/<id>/binders {binder, level: 'read'|'write'|null}
|
|
@@ -164,6 +168,7 @@ export const EXT_PREFIX = '/api/ext/';
|
|
|
164
168
|
/* The scopes a key may be given: [asset, rights] in the table. */
|
|
165
169
|
export const SCOPES = Object.freeze({ status: { asset: 'server:status', rights: 'r', label: 'Its state (memory, disk, versions)' },
|
|
166
170
|
jobs: { asset: 'server:jobs', rights: 'r', label: 'Jobs: read what Clavarium does and its logs' },
|
|
171
|
+
diagnostics: { asset: 'server:diagnostics', rights: 'r', label: 'Diagnostics: load, measure, logs' },
|
|
167
172
|
'create-rooms': { asset: 'server:rooms', rights: 'w', label: 'Create rooms' } });
|
|
168
173
|
/* What a key may do in one conversation: [rights in the table]. */
|
|
169
174
|
export const LEVELS = Object.freeze({ read: 'r', talk: 'rw', act: 'rwm' });
|
|
@@ -300,6 +305,16 @@ export class ApiKeys {
|
|
|
300
305
|
return this.get(id);
|
|
301
306
|
}
|
|
302
307
|
|
|
308
|
+
/* One scope of the server given to a key afterwards, or taken back (18-11: the owner, rather than a new key). */
|
|
309
|
+
setScope(id, scope, on) {
|
|
310
|
+
if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
311
|
+
if (!Object.hasOwn(SCOPES, scope)) throw new Refusal(400, `Scopes are among: ${Object.keys(SCOPES).join(', ')}.`);
|
|
312
|
+
if (on === true) this.#grants.give(apiKeySubject(id), SCOPES[scope].asset, SCOPES[scope].rights);
|
|
313
|
+
else if (on === false) this.#grants.take(apiKeySubject(id), SCOPES[scope].asset);
|
|
314
|
+
else throw new Refusal(400, 'on: true or false.');
|
|
315
|
+
return this.get(id);
|
|
316
|
+
}
|
|
317
|
+
|
|
303
318
|
/* A new key: its secret is in the answer, this once. `days`: its life (null: it does not expire).
|
|
304
319
|
`conversations`: { name: 'read' | 'talk' }, each named -- there is no "all". */
|
|
305
320
|
create({ label, scopes = [], conversations = {}, rooms = {}, boxes = {}, binders = {}, days = DEFAULT_DAYS } = {}, who = '') {
|
|
@@ -566,6 +581,28 @@ export const JOB_LOG_TOOL = {
|
|
|
566
581
|
inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'The job\'s id, as clavarium_jobs gives it.' } }, required: ['id'], additionalProperties: false },
|
|
567
582
|
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
568
583
|
};
|
|
584
|
+
/* Diagnostics (18-11: to see the owner's server from here when it is slow, without the owner copying). */
|
|
585
|
+
export const LOAD_TOOL = {
|
|
586
|
+
name: 'clavarium_load',
|
|
587
|
+
title: 'Load of this Clavarium',
|
|
588
|
+
description: 'Read-only: what this server asked of the host, by 5-minute window (each kind of command, how many, the time), its own event loop delay (p50/p99/max ms) and processor time. The newest window first.',
|
|
589
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
590
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
591
|
+
};
|
|
592
|
+
export const PROFILE_TOOL = {
|
|
593
|
+
name: 'clavarium_profile',
|
|
594
|
+
title: 'What holds this Clavarium',
|
|
595
|
+
description: 'Read-only: this server sampled by its own profiler for a few seconds (2 to 30, 10 by default): the functions that took the most time themselves (self) and with what they called (total), idle, garbage collection, processor time. Waits that long.',
|
|
596
|
+
inputSchema: { type: 'object', properties: { seconds: { type: 'integer', minimum: 2, maximum: 30 } }, additionalProperties: false },
|
|
597
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
598
|
+
};
|
|
599
|
+
export const LOGS_TOOL = {
|
|
600
|
+
name: 'clavarium_logs',
|
|
601
|
+
title: 'Logs of this Clavarium',
|
|
602
|
+
description: 'Read-only: what one of the server\'s programs said over a span, as Settings reads it (secrets masked). source: clavarium (default), machines, updates, web, signin, tunnel, system. span: 10m (default), 1, 6, 24, 168 (hours) or boot. A big journal takes a while: {pending: true} means ask again in a moment.',
|
|
603
|
+
inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' } }, additionalProperties: false },
|
|
604
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
605
|
+
};
|
|
569
606
|
export const CONVERSATIONS_TOOL = {
|
|
570
607
|
name: 'clavarium_conversations',
|
|
571
608
|
title: 'Conversations of this key',
|
|
@@ -696,10 +733,10 @@ export const BINDER_ARCHIVE_TOOL = tool('clavarium_binder_archive', 'Archive a r
|
|
|
696
733
|
'Archive a record (or restore it: "restore": true). Never deleted: only a person deletes. The list must have been given to this key to write.',
|
|
697
734
|
{ binder: BINDER_ARG, record: RECORD_ARG, restore: { type: 'boolean' } }, ['binder', 'record'], true);
|
|
698
735
|
const BINDER_TOOLS = [BINDERS_TOOL, BINDER_RECORDS_TOOL, BINDER_RECORD_TOOL, BINDER_ADD_TOOL, BINDER_EDIT_TOOL, BINDER_MOVE_TOOL, BINDER_NOTE_TOOL, BINDER_ARCHIVE_TOOL];
|
|
699
|
-
export const TOOLS = [STATUS_TOOL, JOBS_TOOL, JOB_LOG_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
|
|
736
|
+
export const TOOLS = [STATUS_TOOL, JOBS_TOOL, JOB_LOG_TOOL, LOAD_TOOL, PROFILE_TOOL, LOGS_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
|
|
700
737
|
ROOMS_TOOL, ROOM_READ_TOOL, ROOM_SAY_TOOL, ROOM_CREATE_TOOL, ROOM_CHANGE_TOOL, ROOM_REMOVE_TOOL, BOXES_TOOL, BOX_SAY_TOOL, ...BINDER_TOOLS];
|
|
701
738
|
/* The tools that need a scope of the server: listed only to a key given it. */
|
|
702
|
-
const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.name]: 'jobs', [JOB_LOG_TOOL.name]: 'jobs', [ROOM_CREATE_TOOL.name]: 'create-rooms' });
|
|
739
|
+
const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.name]: 'jobs', [JOB_LOG_TOOL.name]: 'jobs', [LOAD_TOOL.name]: 'diagnostics', [PROFILE_TOOL.name]: 'diagnostics', [LOGS_TOOL.name]: 'diagnostics', [ROOM_CREATE_TOOL.name]: 'create-rooms' });
|
|
703
740
|
|
|
704
741
|
/* Returns true when the request was under /api/ext/ (answered here). `status()`: the state, as statusOf
|
|
705
742
|
makes it. `chats`: { list() -> [{ id, name }], read(name, part) -> talk.of's answer, chatOn(name),
|
|
@@ -714,8 +751,9 @@ const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.nam
|
|
|
714
751
|
07-11: `reminders`: { of(name) -> { on, plans: [{ id, text, cron, next }] }, set(name, { at, cron, text }, by) -> plan,
|
|
715
752
|
cancel(name, plan) -> bool } -- a conversation's Docket (dockets.mjs). `binder`: { act(op, args, who) -> { ok, text, data } }
|
|
716
753
|
-- Binder's keeper, asked as the key (an agent): its rules are Binder's.
|
|
717
|
-
14-11: `jobs`: { list() -> { running, done }, log(id) -> the job with its log | undefined } (jobs.mjs, withUpdates).
|
|
718
|
-
|
|
754
|
+
14-11: `jobs`: { list() -> { running, done }, log(id) -> the job with its log | undefined } (jobs.mjs, withUpdates).
|
|
755
|
+
18-11: `diagnostics`: { load() -> HostTally windows, profile(seconds) -> profile.mjs's, logs(source, span) -> serverlogs.mjs start's }. */
|
|
756
|
+
export async function handleExternal(request, response, { keys, status, chats = null, rooms = null, boxes = null, reminders = null, binder = null, jobs = null, diagnostics = null, events = null, headers = {}, originOk = () => false, version = null }) {
|
|
719
757
|
const url = new URL(request.url ?? '/', 'http://local');
|
|
720
758
|
const { pathname } = url;
|
|
721
759
|
if (!pathname.startsWith(EXT_PREFIX) && pathname !== EXT_PREFIX.slice(0, -1)) return false;
|
|
@@ -1190,6 +1228,14 @@ export async function handleExternal(request, response, { keys, status, chats =
|
|
|
1190
1228
|
return result(await status());
|
|
1191
1229
|
}
|
|
1192
1230
|
if (name === JOBS_TOOL.name) return result(jobsListed(id));
|
|
1231
|
+
if (name === LOAD_TOOL.name || name === PROFILE_TOOL.name || name === LOGS_TOOL.name) {
|
|
1232
|
+
if (!keys.may(id, 'diagnostics')) throw new Refusal(403, `This key was not given the scope "${SCOPES.diagnostics.label}".`);
|
|
1233
|
+
if (!diagnostics) throw new Refusal(404, 'Not available on this server.');
|
|
1234
|
+
if (name === LOAD_TOOL.name) return result(diagnostics.load());
|
|
1235
|
+
if (name === PROFILE_TOOL.name) return result(await diagnostics.profile(args.seconds ?? 10));
|
|
1236
|
+
const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m');
|
|
1237
|
+
return result(r.pending ? r : { ...r, text: masked(r.text ?? '') });
|
|
1238
|
+
}
|
|
1193
1239
|
if (name === JOB_LOG_TOOL.name) {
|
|
1194
1240
|
if (typeof args.id !== 'string') return fail(-32602, 'id: the id of a job, as clavarium_jobs gives it.');
|
|
1195
1241
|
return result(jobRead(id, args.id));
|
|
@@ -1282,6 +1328,12 @@ export async function handleApiKeys(request, response, keys, originOk, headers =
|
|
|
1282
1328
|
events?.add({ kind: 'access', text: `API key "${made.key.label}" made${what.length ? ` (${what.join(', ')})` : ' (no scope)'}`, who: who || null });
|
|
1283
1329
|
return send(201, made);
|
|
1284
1330
|
}
|
|
1331
|
+
const scoping = /^\/api\/apikeys\/([0-9a-f-]{36})\/scopes$/.exec(pathname);
|
|
1332
|
+
if (scoping) {
|
|
1333
|
+
const key = keys.setScope(scoping[1], body.scope, body.on);
|
|
1334
|
+
events?.add({ kind: 'access', text: `API key "${key.label}": ${String(body.scope).slice(0, 40)} ${body.on ? 'given' : 'taken back'}`, who: who || null });
|
|
1335
|
+
return send(200, { key });
|
|
1336
|
+
}
|
|
1285
1337
|
const giving = /^\/api\/apikeys\/([0-9a-f-]{36})\/conversations$/.exec(pathname);
|
|
1286
1338
|
if (giving) {
|
|
1287
1339
|
const level = body.level === undefined ? null : body.level;
|
package/server/grants.mjs
CHANGED
|
@@ -35,7 +35,8 @@
|
|
|
35
35
|
* in the table: the owner may do everything, always.
|
|
36
36
|
*
|
|
37
37
|
* An API key is not a device and not a conversation: it is given only what
|
|
38
|
-
* its scopes name -- "server:status" (read), "server:jobs" (read its jobs and their logs), "server:
|
|
38
|
+
* its scopes name -- "server:status" (read), "server:jobs" (read its jobs and their logs), "server:diagnostics"
|
|
39
|
+
* (read the server's load, measure what holds it, read its logs, masked), "server:rooms"
|
|
39
40
|
* (make rooms), and conversations one by one,
|
|
40
41
|
* their chat to read ("r") or to talk in ("rw"), never their terminal ("x")
|
|
41
42
|
* -- rooms one by one, their thread to read ("r") or to post in ("rw"), and
|
|
@@ -65,9 +66,9 @@ import { Refusal } from './conversations.mjs';
|
|
|
65
66
|
|
|
66
67
|
export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
|
|
67
68
|
/* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
|
|
68
|
-
const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w' });
|
|
69
|
+
const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w', 'server:diagnostics': 'r' });
|
|
69
70
|
const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
|
|
70
|
-
const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
71
|
+
const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms|diagnostics)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
71
72
|
|
|
72
73
|
export const typeOf = (asset) => String(asset).split(':')[0];
|
|
73
74
|
export const nameOf = (asset) => String(asset).slice(String(asset).indexOf(':') + 1);
|
package/server/main.mjs
CHANGED
|
@@ -80,6 +80,8 @@ import { McpOAuth } from './mcpoauth.mjs';
|
|
|
80
80
|
import { Browsers } from './browsers.mjs';
|
|
81
81
|
import { Accounts } from './accounts.mjs';
|
|
82
82
|
import { ServerLogs } from './serverlogs.mjs';
|
|
83
|
+
import { Profiler, AutoProfile } from './profile.mjs';
|
|
84
|
+
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
83
85
|
import { History, STEP_MS as HISTORY_STEP_MS } from './history.mjs';
|
|
84
86
|
import { Events } from './events.mjs';
|
|
85
87
|
import { Bundles } from './bundle.mjs';
|
|
@@ -253,7 +255,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
253
255
|
/* THE DOOR FOR PROGRAMS (apikeys.mjs): an API key is the right, never the gate -- the front lets
|
|
254
256
|
/api/ext/ through without sign-on, and strips the identity headers there. */
|
|
255
257
|
if (apikeys && (pathname === '/api/ext' || pathname.startsWith('/api/ext/'))) {
|
|
256
|
-
await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, rooms: apikeys.rooms, boxes: apikeys.boxes, reminders: apikeys.reminders, binder: apikeys.binder, jobs: apikeys.jobs, events, headers: HEADERS, originOk, version: platform?.version ?? null });
|
|
258
|
+
await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, rooms: apikeys.rooms, boxes: apikeys.boxes, reminders: apikeys.reminders, binder: apikeys.binder, jobs: apikeys.jobs, diagnostics: apikeys.diagnostics, events, headers: HEADERS, originOk, version: platform?.version ?? null });
|
|
257
259
|
return;
|
|
258
260
|
}
|
|
259
261
|
if (door && pathname.startsWith('/c/')) {
|
|
@@ -838,7 +840,12 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
838
840
|
/* All the machines to another disk, from Settings (machinesmove.mjs). */
|
|
839
841
|
const machinesMove = new MachinesMove({ host: asHost, usedMb: () => capacity.machinesUsedMb() });
|
|
840
842
|
/* What the server's programs said, and this server started again, from Settings (serverlogs.mjs). */
|
|
841
|
-
|
|
843
|
+
/* What holds this server: measured on demand (Settings, Load, Measure; MCP), and by itself when its loop is slow (profile.mjs). */
|
|
844
|
+
const profiler = new Profiler();
|
|
845
|
+
const loopWatch = monitorEventLoopDelay({ resolution: 20 }); loopWatch.enable();
|
|
846
|
+
const autoProfile = new AutoProfile({ profiler, file: new JsonFile(`${dataDir}/profiles.json`, {}),
|
|
847
|
+
delay: () => { if (!loopWatch.count) return null; const d = { p50: Math.round(loopWatch.percentile(50) / 1e6), p99: Math.round(loopWatch.percentile(99) / 1e6) }; loopWatch.reset(); return d; } }).start();
|
|
848
|
+
const serverLogs = new ServerLogs({ host: asHost, load: () => ({ ...hostTally.windows(), profiles: autoProfile.kept() }), profiler });
|
|
842
849
|
/* This server's Wi-Fi, from Settings (wifi.mjs): how a switch ended, said in What happened. */
|
|
843
850
|
const wifi = new Wifi({ host: asHost, said: (text) => events.add({ kind: 'server', text }) });
|
|
844
851
|
/* The remote screen (MeshCentral), from Settings (meshcentral.mjs): how a turn-on ended, said in What happened. */
|
|
@@ -916,6 +923,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
916
923
|
const apikeys = { keys: apiKeys, status: () => statusOf({ conversations: all, talk, health, answerer, capacity: briefly, history, platform, updates, components }),
|
|
917
924
|
/* What Clavarium does (jobs.mjs), as Settings shows it: the list without logs, one job with its log. */
|
|
918
925
|
jobs: { list: () => withUpdates(all.jobs, all.list(), updates?.about().history ?? []), log: (id) => all.jobs.log(id) },
|
|
926
|
+
/* Diagnostics (scope "diagnostics"): what Settings > Diagnostics > Load and Logs show. */
|
|
927
|
+
diagnostics: { load: () => serverLogs.load(), profile: (seconds) => serverLogs.profile(seconds), logs: (source, span) => serverLogs.start(source, span) },
|
|
919
928
|
/* A key's conversations (their chat, through talk.mjs): read as the page reads it; a message posted as the page
|
|
920
929
|
posts one (its secrets lifted the same way), signed with the key's name. */
|
|
921
930
|
chats: {
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/* WHAT HOLDS THIS SERVER, measured (18-11: the owner's server waited about a second at every turn of its
|
|
2
|
+
* event loop, with little CPU seen -- Settings, Load): a few seconds of this server sampled by its own
|
|
3
|
+
* V8 profiler (node:inspector, in-process: no port opened), then said in short, the functions that
|
|
4
|
+
* took the most time themselves and with what they called. Text only, nothing kept.
|
|
5
|
+
*
|
|
6
|
+
* profile(seconds) { seconds, sampledMs, idleMs, gcMs, programMs, self: [{ fn, at, ms }], total: [...] }
|
|
7
|
+
* one at a time: asked again while one runs, the same one
|
|
8
|
+
*/
|
|
9
|
+
import { Session } from 'node:inspector/promises';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
export const PROFILE_MIN_S = 2;
|
|
13
|
+
export const PROFILE_MAX_S = 30;
|
|
14
|
+
export const PROFILE_TOP = 15;
|
|
15
|
+
const APP = fileURLToPath(new URL('..', import.meta.url));
|
|
16
|
+
|
|
17
|
+
/* Where a function is, short: within the application from its folder, a package by its name, else the file's name. */
|
|
18
|
+
export function placeOf(url, line) {
|
|
19
|
+
let path = String(url ?? '');
|
|
20
|
+
if (!path) return '';
|
|
21
|
+
if (path.startsWith('file://')) { try { path = fileURLToPath(path); } catch { /* left as it is */ } }
|
|
22
|
+
const inModules = path.lastIndexOf('/node_modules/');
|
|
23
|
+
if (inModules >= 0) path = path.slice(inModules + '/node_modules/'.length);
|
|
24
|
+
else if (path.startsWith(APP)) path = path.slice(APP.length);
|
|
25
|
+
else if (path.startsWith('/')) path = path.split('/').pop();
|
|
26
|
+
return line >= 0 ? `${path}:${line + 1}` : path;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/* A V8 CPU profile told in short: each sample's time to its node, then by function. */
|
|
30
|
+
export function summarize(profile, seconds, top = PROFILE_TOP) {
|
|
31
|
+
const nodes = new Map((profile.nodes ?? []).map((n) => [n.id, n]));
|
|
32
|
+
const selfUs = new Map();
|
|
33
|
+
const samples = profile.samples ?? []; const deltas = profile.timeDeltas ?? [];
|
|
34
|
+
for (let i = 0; i < samples.length; i++) selfUs.set(samples[i], (selfUs.get(samples[i]) ?? 0) + Math.max(0, deltas[i] ?? 0));
|
|
35
|
+
const parent = new Map();
|
|
36
|
+
for (const n of nodes.values()) for (const c of n.children ?? []) parent.set(c, n.id);
|
|
37
|
+
const special = { '(idle)': 0, '(garbage collector)': 0, '(program)': 0, '(root)': 0 };
|
|
38
|
+
const self = new Map(); const total = new Map();
|
|
39
|
+
const keyOf = (n) => { const f = n.callFrame ?? {}; return `${f.functionName || '(anonymous)'}\t${placeOf(f.url, f.lineNumber)}`; };
|
|
40
|
+
for (const [id, us] of selfUs) {
|
|
41
|
+
const n = nodes.get(id); if (!n) continue;
|
|
42
|
+
const name = n.callFrame?.functionName ?? '';
|
|
43
|
+
if (name in special && !n.callFrame?.url) { special[name] += us; continue; }
|
|
44
|
+
const k = keyOf(n); self.set(k, (self.get(k) ?? 0) + us);
|
|
45
|
+
/* Its time counted once to every function above it (a recursive one once). */
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
for (let at = id; at !== undefined; at = parent.get(at)) {
|
|
48
|
+
const up = nodes.get(at); if (!up || (up.callFrame?.functionName === '(root)' && !up.callFrame?.url)) break;
|
|
49
|
+
const uk = keyOf(up); if (seen.has(uk)) continue; seen.add(uk);
|
|
50
|
+
total.set(uk, (total.get(uk) ?? 0) + us);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const list = (m) => [...m].sort((a, b) => b[1] - a[1]).slice(0, top).map(([k, us]) => { const [fn, at] = k.split('\t'); return { fn, at, ms: Math.round(us / 1000) }; });
|
|
54
|
+
const all = [...selfUs.values()].reduce((a, b) => a + b, 0);
|
|
55
|
+
return {
|
|
56
|
+
seconds, sampledMs: Math.round(all / 1000), idleMs: Math.round(special['(idle)'] / 1000),
|
|
57
|
+
gcMs: Math.round(special['(garbage collector)'] / 1000), programMs: Math.round(special['(program)'] / 1000),
|
|
58
|
+
self: list(self), total: list(total),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class Profiler {
|
|
63
|
+
#running = null; #session; #wait;
|
|
64
|
+
constructor({ session = () => new Session(), wait = (ms) => new Promise((ok) => { setTimeout(ok, ms); }) } = {}) { this.#session = session; this.#wait = wait; }
|
|
65
|
+
profile(seconds = 10) {
|
|
66
|
+
const s = Math.min(PROFILE_MAX_S, Math.max(PROFILE_MIN_S, Math.round(Number(seconds) || 10)));
|
|
67
|
+
if (this.#running) return this.#running;
|
|
68
|
+
this.#running = (async () => {
|
|
69
|
+
const session = this.#session();
|
|
70
|
+
session.connect();
|
|
71
|
+
try {
|
|
72
|
+
await session.post('Profiler.enable');
|
|
73
|
+
await session.post('Profiler.setSamplingInterval', { interval: 1000 });
|
|
74
|
+
await session.post('Profiler.start');
|
|
75
|
+
const began = process.cpuUsage();
|
|
76
|
+
await this.#wait(s * 1000);
|
|
77
|
+
const { profile } = await session.post('Profiler.stop');
|
|
78
|
+
const cpu = process.cpuUsage(began);
|
|
79
|
+
return { ...summarize(profile, s), cpuMs: Math.round((cpu.user + cpu.system) / 1000) };
|
|
80
|
+
} finally {
|
|
81
|
+
try { await session.post('Profiler.disable'); } catch { /* closing anyway */ }
|
|
82
|
+
session.disconnect();
|
|
83
|
+
}
|
|
84
|
+
})().finally(() => { this.#running = null; });
|
|
85
|
+
return this.#running;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* MEASURED BY ITSELF (18-11, the owner: an intermittent stall needs nobody before the screen): every
|
|
90
|
+
WATCH_EVERY_MS the event loop's delay of the last minute is looked at; past SLOW_P50_MS, a measure is
|
|
91
|
+
taken (as Measure 10 s), at most once in AUTO_EVERY_MS (a measure costs a little itself), the last
|
|
92
|
+
AUTO_KEPT kept with when and why, in `file` (JsonFile: they outlive a restart). */
|
|
93
|
+
export const WATCH_EVERY_MS = 60_000;
|
|
94
|
+
export const SLOW_P50_MS = 200;
|
|
95
|
+
export const AUTO_EVERY_MS = 30 * 60_000;
|
|
96
|
+
export const AUTO_KEPT = 5;
|
|
97
|
+
export const AUTO_SECONDS = 10;
|
|
98
|
+
export class AutoProfile {
|
|
99
|
+
#profiler; #file; #now; #delay; #log; #last = 0; #timer = null;
|
|
100
|
+
/* `delay()`: the loop's delay of the last minute, { p50, p99 } in ms, then started again (a histogram of its own). */
|
|
101
|
+
constructor({ profiler, file, now = () => Date.now(), delay, log = (line) => console.log(line) }) {
|
|
102
|
+
this.#profiler = profiler; this.#file = file; this.#now = now; this.#delay = delay; this.#log = log;
|
|
103
|
+
const kept = this.kept(); this.#last = kept[0] ? Date.parse(kept[0].at) || 0 : 0;
|
|
104
|
+
}
|
|
105
|
+
kept() { const v = this.#file?.get(); return Array.isArray(v?.profiles) ? v.profiles : []; }
|
|
106
|
+
start(everyMs = WATCH_EVERY_MS) { this.#timer = setInterval(() => { void this.check(); }, everyMs); this.#timer.unref?.(); return this; }
|
|
107
|
+
stop() { clearInterval(this.#timer); }
|
|
108
|
+
async check() {
|
|
109
|
+
const d = this.#delay();
|
|
110
|
+
if (!d || !(d.p50 > SLOW_P50_MS)) return null;
|
|
111
|
+
if (this.#now() - this.#last < AUTO_EVERY_MS) return null;
|
|
112
|
+
this.#last = this.#now();
|
|
113
|
+
const why = `loop p50 ${d.p50} ms, p99 ${d.p99} ms over the last minute`;
|
|
114
|
+
this.#log(`profile: measuring ${AUTO_SECONDS} s by itself (${why})`);
|
|
115
|
+
try {
|
|
116
|
+
const p = await this.#profiler.profile(AUTO_SECONDS);
|
|
117
|
+
const entry = { at: new Date(this.#last).toISOString(), why, ...p };
|
|
118
|
+
this.#file?.set({ profiles: [entry, ...this.kept()].slice(0, AUTO_KEPT) });
|
|
119
|
+
this.#log(`profile: ${p.self.slice(0, 5).map((f) => `${f.fn} ${f.ms}ms ${f.at}`).join('; ')}`);
|
|
120
|
+
return entry;
|
|
121
|
+
} catch (error) { this.#log(`profile: not measured (${error?.message ?? error})`); return null; }
|
|
122
|
+
}
|
|
123
|
+
}
|
package/server/serverlogs.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* any run of 32 letters and digits or more (a key, a token)
|
|
9
9
|
* `note`: why it may be short (the journal too slow, journalctl's last word)
|
|
10
10
|
* load() the host commands of the last windows (vm.mjs HostTally): Settings, Load
|
|
11
|
+
* profile(seconds) this server sampled by its own profiler (profile.mjs): what holds it
|
|
11
12
|
* restart() this server starts again in two seconds (its machines go on)
|
|
12
13
|
*/
|
|
13
14
|
import { Refusal } from './conversations.mjs';
|
|
@@ -36,9 +37,13 @@ export const NOISE = / (sudo|pkexec)\[\d+\]: | pam_unix\((sudo|sudo-i|pkexec):se
|
|
|
36
37
|
const lastWord = (text) => String(text ?? '').trim().split('\n').pop()?.replace(/^(REFUSED|NOTE): /, '').slice(0, 200) ?? '';
|
|
37
38
|
|
|
38
39
|
export class ServerLogs {
|
|
39
|
-
#host; #reads = new Map(); #now; #load;
|
|
40
|
-
constructor({ host, now = () => Date.now(), load = () => ({ everyMs: 0, windows: [] }) }) { this.#host = host; this.#now = now; this.#load = load; }
|
|
40
|
+
#host; #reads = new Map(); #now; #load; #profiler;
|
|
41
|
+
constructor({ host, now = () => Date.now(), load = () => ({ everyMs: 0, windows: [] }), profiler = null }) { this.#host = host; this.#now = now; this.#load = load; this.#profiler = profiler; }
|
|
41
42
|
load() { return this.#load(); }
|
|
43
|
+
profile(seconds) {
|
|
44
|
+
if (!this.#profiler) throw new Refusal(404, 'The profiler is not available on this server.');
|
|
45
|
+
return this.#profiler.profile(seconds);
|
|
46
|
+
}
|
|
42
47
|
|
|
43
48
|
/* The same read asked again while it runs is the same read; once done, kept a moment for
|
|
44
49
|
the page that comes back for it. Resolves { pending: true } past `wait`. */
|
package/server/settingswords.mjs
CHANGED
|
@@ -60,6 +60,7 @@ export const SETTINGS_WORDS_FR = {
|
|
|
60
60
|
/* Diagnostics › Charge (vm.mjs HostTally): les commandes à l'hôte, par fenêtre de 5 minutes. */
|
|
61
61
|
'set-ch-s-load': 'Charge', 'set-load-about': 'Commandes à l\'hôte, par 5 minutes', 'set-load-copy': 'Copier',
|
|
62
62
|
'set-load-open': 'maintenant', 'set-load-line': '{n} commandes · {s} s', 'set-load-loop': 'boucle {p50}/{p99} ms',
|
|
63
|
+
'set-load-profile': 'Mesurer 10 s', 'set-load-profiling': 'Mesure en cours…', 'set-load-cpu': 'processeur {p} %', 'set-load-auto': 'Mesuré seul à {at}',
|
|
63
64
|
'set-load-none': 'Rien de compté pour le moment', 'set-load-unread': 'Illisible pour le moment', 'set-load-copied': 'Copié',
|
|
64
65
|
/* Mises à jour: sudo discret (deploy/updater.mjs ensureQuietSudo). */
|
|
65
66
|
'set-sudo-on': 'Sudo discret : oui ({setting})', 'set-sudo-off': 'Sudo discret : non appliqué : {why}',
|
|
@@ -102,11 +103,12 @@ export const SETTINGS_WORDS_FR = {
|
|
|
102
103
|
'set-apikeys-never': 'Jamais', 'set-apikeys-cancel': 'Annuler', 'set-apikeys-create': 'Créer', 'set-apikeys-new': 'Nouvelle clé',
|
|
103
104
|
'set-apikeys-never-by-key': 'Jamais : secrets, clés, comptes, droits', 'set-apikeys-scope-status': 'Son état (mémoire, disque, versions)',
|
|
104
105
|
'set-apikeys-scope-jobs': 'Tâches : ce que fait Clavarium, ses journaux',
|
|
106
|
+
'set-apikeys-scope-diagnostics': 'Diagnostics : charge, mesure, journaux',
|
|
105
107
|
'set-apikeys-scope-create-rooms': 'Créer des salons', 'set-apikeys-act': 'Agir', 'set-apikeys-manage': 'Gérer',
|
|
106
108
|
'set-apikeys-no-scope': 'Aucune portée', 'set-apikeys-by-you': 'par vous', 'set-apikeys-used': 'Utilisée {when}', 'set-apikeys-unused': 'Jamais utilisée',
|
|
107
109
|
'set-apikeys-expired': 'Expirée', 'set-apikeys-expires-on': 'Expire le {date}', 'set-apikeys-no-expiry': 'N\'expire pas',
|
|
108
110
|
'set-apikeys-created': 'Créée le {date}', 'set-apikeys-revoke': 'Révoquer', 'set-apikeys-revoke-q': 'Révoquer maintenant ?',
|
|
109
|
-
'set-apikeys-convs': 'Conversations', 'set-apikeys-convs-hint': 'Une par une : lire, parler ou agir', 'set-apikeys-off': 'Non',
|
|
111
|
+
'set-apikeys-perms': 'Permissions', 'set-apikeys-convs': 'Conversations', 'set-apikeys-convs-hint': 'Une par une : lire, parler ou agir', 'set-apikeys-off': 'Non',
|
|
110
112
|
'set-apikeys-read': 'Lire', 'set-apikeys-talk': 'Parler', 'set-apikeys-no-convs': 'Aucune conversation pour l\'instant',
|
|
111
113
|
'set-apikeys-journal': 'Journal', 'set-apikeys-no-use': 'Aucun appel pour l\'instant',
|
|
112
114
|
'set-apikeys-rooms': 'Salons', 'set-apikeys-rooms-hint': 'Un par un : lire, parler ou gérer', 'set-apikeys-no-rooms': 'Aucun salon pour l\'instant',
|
package/server/vm.mjs
CHANGED
|
@@ -115,10 +115,10 @@ export class VmUnknown extends Error {
|
|
|
115
115
|
a server stalled by itself, not by the host). */
|
|
116
116
|
export const LOAD_KEPT = 12;
|
|
117
117
|
export class HostTally {
|
|
118
|
-
#now; #log; #kinds = new Map(); #from = 0; #beats = [0, 0]; #kept = []; #loop = null;
|
|
118
|
+
#now; #log; #kinds = new Map(); #from = 0; #beats = [0, 0]; #kept = []; #loop = null; #cpu = null;
|
|
119
119
|
constructor({ now = () => Date.now(), log = (line) => console.log(line), loop = false } = {}) {
|
|
120
120
|
this.#now = now; this.#log = log;
|
|
121
|
-
if (loop) { this.#loop = monitorEventLoopDelay({ resolution: 20 }); this.#loop.enable(); }
|
|
121
|
+
if (loop) { this.#loop = monitorEventLoopDelay({ resolution: 20 }); this.#loop.enable(); this.#cpu = process.cpuUsage(); }
|
|
122
122
|
}
|
|
123
123
|
/* A look of health answered by its heartbeat (`read`: no command; beat.mjs), or by a command after all. */
|
|
124
124
|
noteBeat(read) { this.#beats[read ? 0 : 1] += 1; }
|
|
@@ -137,15 +137,17 @@ export class HostTally {
|
|
|
137
137
|
const kinds = [...this.#kinds].sort((a, b) => b[1][1] - a[1][1]).map(([kind, [count, ms, maxMs]]) => ({ kind, count, ms, maxMs }));
|
|
138
138
|
const ms = (n) => Math.round(n / 1e6);
|
|
139
139
|
const loop = this.#loop && this.#loop.count ? { p50: ms(this.#loop.percentile(50)), p99: ms(this.#loop.percentile(99)), max: ms(this.#loop.max) } : null;
|
|
140
|
+
/* Its own processor time over the window (user + system, ms), with the loop: a stalled loop with it high is this server's own work. */
|
|
141
|
+
if (loop && this.#cpu) { const c = process.cpuUsage(this.#cpu); loop.cpuMs = Math.round((c.user + c.system) / 1000); }
|
|
140
142
|
return { from: this.#from || now, to: now, commands: kinds.reduce((n, k) => n + k.count, 0), ms: kinds.reduce((n, k) => n + k.ms, 0), kinds, beats: { read: this.#beats[0], fallback: this.#beats[1] }, loop };
|
|
141
143
|
}
|
|
142
144
|
#close(now) {
|
|
143
145
|
const w = this.#window(now);
|
|
144
146
|
const beats = w.beats.read + w.beats.fallback ? `; beat read ${w.beats.read}x, fallback ${w.beats.fallback}x` : '';
|
|
145
|
-
const loop = w.loop ? `; loop p50 ${w.loop.p50}ms p99 ${w.loop.p99}ms` : '';
|
|
147
|
+
const loop = w.loop ? `; loop p50 ${w.loop.p50}ms p99 ${w.loop.p99}ms${w.loop.cpuMs !== undefined ? ` cpu ${Math.round(w.loop.cpuMs / 1000)}s` : ''}` : '';
|
|
146
148
|
this.#log(`host: ${w.commands} commands in ${Math.round((now - w.from) / 60_000)} min, ${Math.round(w.ms / 1000)} s spent; ${w.kinds.slice(0, 8).map((k) => `${k.kind} ${k.count}x ${Math.round(k.ms / 1000)}s max ${Math.round(k.maxMs / 1000)}s`).join('; ')}${beats}${loop}`);
|
|
147
149
|
this.#kept = [{ ...w, kinds: w.kinds.slice(0, 20) }, ...this.#kept].slice(0, LOAD_KEPT);
|
|
148
|
-
this.#kinds = new Map(); this.#from = now; this.#beats = [0, 0]; this.#loop?.reset();
|
|
150
|
+
this.#kinds = new Map(); this.#from = now; this.#beats = [0, 0]; this.#loop?.reset(); if (this.#cpu) this.#cpu = process.cpuUsage();
|
|
149
151
|
}
|
|
150
152
|
/* The windows, the newest first: the one under way (`open`), then the closed ones. A window past its
|
|
151
153
|
time with no command since is closed here: an idle server still says so. */
|
package/web/app.js
CHANGED
|
@@ -8384,11 +8384,25 @@
|
|
|
8384
8384
|
const more = el('div', 'apikey-more'); more.hidden = true;
|
|
8385
8385
|
const open = async (kind) => {
|
|
8386
8386
|
apiKeyOpen = apiKeyOpen?.id === k.id && apiKeyOpen.what === kind ? null : { id: k.id, what: kind };
|
|
8387
|
-
for (const b of acts.querySelectorAll('button[data-act="convs"], button[data-act="rooms"], button[data-act="boxes"], button[data-act="binders"], button[data-act="journal"]')) b.setAttribute('aria-expanded', String(apiKeyOpen?.id === k.id && apiKeyOpen.what === b.dataset.act));
|
|
8387
|
+
for (const b of acts.querySelectorAll('button[data-act="scopes"], button[data-act="convs"], button[data-act="rooms"], button[data-act="boxes"], button[data-act="binders"], button[data-act="journal"]')) b.setAttribute('aria-expanded', String(apiKeyOpen?.id === k.id && apiKeyOpen.what === b.dataset.act));
|
|
8388
8388
|
more.hidden = apiKeyOpen?.id !== k.id;
|
|
8389
8389
|
more.replaceChildren();
|
|
8390
8390
|
if (!apiKeyOpen || apiKeyOpen.id !== k.id) return;
|
|
8391
8391
|
if (kind === 'journal') { more.dataset.what = 'journal'; await paintApiKeyJournal(more, k.id); return; }
|
|
8392
|
+
/* Its scopes of the server, ticked or not, changed afterwards (18-11). */
|
|
8393
|
+
if (kind === 'scopes') {
|
|
8394
|
+
more.dataset.what = 'scopes';
|
|
8395
|
+
for (const sc of got.scopes) {
|
|
8396
|
+
const l = el('label', 'check'); const box = document.createElement('input'); box.type = 'checkbox'; box.value = sc.id; box.checked = k.scopes.includes(sc.id);
|
|
8397
|
+
box.addEventListener('change', async () => {
|
|
8398
|
+
$('apikeys-error').hidden = true;
|
|
8399
|
+
try { await post(`${API}/apikeys/${k.id}/scopes`, { scope: sc.id, on: box.checked }); } catch (error) { $('apikeys-error').textContent = error.message; $('apikeys-error').hidden = false; }
|
|
8400
|
+
await paintApiKeys();
|
|
8401
|
+
});
|
|
8402
|
+
l.append(box, ' ', el('span', '', scopeWord(sc.id))); more.append(l);
|
|
8403
|
+
}
|
|
8404
|
+
return;
|
|
8405
|
+
}
|
|
8392
8406
|
more.dataset.what = kind;
|
|
8393
8407
|
if (kind === 'rooms' || kind === 'boxes' || kind === 'binders') {
|
|
8394
8408
|
more.append(apiKeyOnePicker(kind, new Map((k[kind] ?? []).map((x) => [x.id, x.level])), async (ref, level) => {
|
|
@@ -8406,9 +8420,11 @@
|
|
|
8406
8420
|
};
|
|
8407
8421
|
const convs = el('button', '', uiSaid('set-apikeys-convs', 'Conversations')); convs.type = 'button'; convs.dataset.act = 'convs';
|
|
8408
8422
|
const journal = el('button', '', uiSaid('set-apikeys-journal', 'Journal')); journal.type = 'button'; journal.dataset.act = 'journal';
|
|
8423
|
+
const perms = el('button', '', uiSaid('set-apikeys-perms', 'Permissions')); perms.type = 'button'; perms.dataset.act = 'scopes';
|
|
8424
|
+
perms.addEventListener('click', () => void open('scopes'));
|
|
8409
8425
|
convs.addEventListener('click', () => void open('convs'));
|
|
8410
8426
|
journal.addEventListener('click', () => void open('journal'));
|
|
8411
|
-
acts.append(convs);
|
|
8427
|
+
acts.append(perms, convs);
|
|
8412
8428
|
/* Rooms, voice boxes, binders: offered when there are some (or the key has some still). */
|
|
8413
8429
|
for (const [kind, word] of [['rooms', uiSaid('set-apikeys-rooms', 'Rooms')], ['boxes', uiSaid('set-apikeys-boxes', 'Voice boxes')], ['binders', uiSaid('set-apikeys-binders', 'Binders')]]) {
|
|
8414
8430
|
if (!apiKeyItems(kind).length && !(k[kind] ?? []).length) continue;
|
|
@@ -9659,7 +9675,8 @@
|
|
|
9659
9675
|
const loadKind = (k) => `${k.kind} ${k.count}× ${loadSec(k.ms)} s (max ${loadSec(k.maxMs)} s)`;
|
|
9660
9676
|
const loadHead = (w) => [`${loadClock(w.from)}–${w.open ? uiSaid('set-load-open', 'now') : loadClock(w.to)}`,
|
|
9661
9677
|
uiSaid('set-load-line', '{n} commands · {s} s', { n: w.commands, s: loadSec(w.ms) }),
|
|
9662
|
-
w.loop ? uiSaid('set-load-loop', 'loop {p50}/{p99} ms', { p50: w.loop.p50, p99: w.loop.p99 }) : ''
|
|
9678
|
+
w.loop ? uiSaid('set-load-loop', 'loop {p50}/{p99} ms', { p50: w.loop.p50, p99: w.loop.p99 }) : '',
|
|
9679
|
+
w.loop?.cpuMs !== undefined && w.to > w.from ? uiSaid('set-load-cpu', 'CPU {p} %', { p: Math.round((100 * w.loop.cpuMs) / (w.to - w.from)) }) : ''].filter(Boolean).join(' · ');
|
|
9663
9680
|
async function paintLoad() {
|
|
9664
9681
|
clearTimeout(loadTimer);
|
|
9665
9682
|
if (!$('settings-load-top').open) return;
|
|
@@ -9673,6 +9690,14 @@
|
|
|
9673
9690
|
return row;
|
|
9674
9691
|
});
|
|
9675
9692
|
$('load-list').replaceChildren(...rows);
|
|
9693
|
+
/* The measures it took by itself, the newest first: when, why, the functions that held it most. */
|
|
9694
|
+
const auto = (got.profiles ?? []).map((p) => {
|
|
9695
|
+
const row = el('div', 'load-row');
|
|
9696
|
+
row.append(el('span', '', `${uiSaid('set-load-auto', 'Measured by itself at {at}', { at: `${new Date(p.at).toLocaleDateString([], { day: 'numeric', month: 'short' })} ${loadClock(p.at)}` })} · ${p.why}`));
|
|
9697
|
+
row.append(el('span', 'load-kinds', (p.self ?? []).slice(0, 3).map((f) => `${f.fn} ${f.ms} ms`).join(' · ')));
|
|
9698
|
+
return row;
|
|
9699
|
+
});
|
|
9700
|
+
$('load-auto').replaceChildren(...auto); $('load-auto').hidden = !auto.length;
|
|
9676
9701
|
const any = (got.windows ?? []).some((w) => w.commands);
|
|
9677
9702
|
$('load-said').textContent = any ? '' : uiSaid('set-load-none', 'Nothing counted yet');
|
|
9678
9703
|
$('load-copy').hidden = !rows.length;
|
|
@@ -9682,11 +9707,28 @@
|
|
|
9682
9707
|
$('load-copy').addEventListener('click', async () => {
|
|
9683
9708
|
if (!loadShown) return;
|
|
9684
9709
|
/* All of it, as text: each window, then every kind it counted. */
|
|
9685
|
-
const
|
|
9710
|
+
const line = (f) => ` ${f.ms} ms ${f.fn} ${f.at}`;
|
|
9711
|
+
const autoText = (loadShown.profiles ?? []).map((p) => [`auto ${p.at} · ${p.why} · cpu ${p.cpuMs} ms · idle ${p.idleMs} · gc ${p.gcMs}`, 'self:', ...(p.self ?? []).map(line), 'with what they call:', ...(p.total ?? []).map(line), ''].join('\n'));
|
|
9712
|
+
const text = [...($('load-profile-out').hidden ? [] : [$('load-profile-out').textContent, '']), ...autoText, ...(loadShown.windows ?? []).map((w) => [loadHead(w), ...(w.kinds ?? []).map((k) => ` ${loadKind(k)}`),
|
|
9686
9713
|
...(w.beats && (w.beats.read || w.beats.fallback) ? [` beat read ${w.beats.read}×, fallback ${w.beats.fallback}×`] : []),
|
|
9687
|
-
...(w.loop ? [` loop max ${w.loop.max} ms`] : [])].join('\n')).join('\n');
|
|
9714
|
+
...(w.loop ? [` loop max ${w.loop.max} ms`] : [])].join('\n'))].join('\n');
|
|
9688
9715
|
try { await navigator.clipboard.writeText(text); $('load-said').textContent = uiSaid('set-load-copied', 'Copied'); } catch { $('load-said').textContent = 'The clipboard is not available here.'; }
|
|
9689
9716
|
});
|
|
9717
|
+
/* WHAT HOLDS THE SERVER: 10 s of its own profiler, the functions that took the most time, as text
|
|
9718
|
+
(server/profile.mjs) -- copied with the windows. */
|
|
9719
|
+
$('load-profile').addEventListener('click', async () => {
|
|
9720
|
+
const out = $('load-profile-out'); $('load-profile').disabled = true;
|
|
9721
|
+
$('load-said').textContent = uiSaid('set-load-profiling', 'Measuring…');
|
|
9722
|
+
try {
|
|
9723
|
+
const r = await fetch(`${API}/server/profile`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ seconds: 10 }) });
|
|
9724
|
+
const p = await r.json().catch(() => null);
|
|
9725
|
+
if (!r.ok || !p) { $('load-said').textContent = p?.error ?? `Not measured (${r.status}).`; return; }
|
|
9726
|
+
const line = (f) => ` ${f.ms} ms ${f.fn} ${f.at}`;
|
|
9727
|
+
out.textContent = [`profile ${p.seconds} s · cpu ${p.cpuMs} ms · sampled ${p.sampledMs} ms · idle ${p.idleMs} · gc ${p.gcMs} · program ${p.programMs}`,
|
|
9728
|
+
'self:', ...p.self.map(line), 'with what they call:', ...p.total.map(line)].join('\n');
|
|
9729
|
+
out.hidden = false; $('load-copy').hidden = false; $('load-said').textContent = '';
|
|
9730
|
+
} catch { $('load-said').textContent = 'Not measured.'; } finally { $('load-profile').disabled = false; }
|
|
9731
|
+
});
|
|
9690
9732
|
/* WHAT THE SERVER'S PROGRAMS SAID: one source over a span, to read, copy whole or keep as a file. */
|
|
9691
9733
|
let logsShown = null;
|
|
9692
9734
|
$('logs-show').addEventListener('click', async () => {
|
package/web/index.html
CHANGED
|
@@ -1377,7 +1377,12 @@
|
|
|
1377
1377
|
<div class="chapter-body">
|
|
1378
1378
|
<div id="load-list" class="load-list" aria-live="polite"></div>
|
|
1379
1379
|
<p class="hint" id="load-said" role="status"></p>
|
|
1380
|
-
<div class="row"><button type="button" id="load-copy" data-said="set-load-copy" hidden>Copy</button
|
|
1380
|
+
<div class="row"><button type="button" id="load-copy" data-said="set-load-copy" hidden>Copy</button>
|
|
1381
|
+
<button type="button" id="load-profile" data-said="set-load-profile">Measure 10 s</button></div>
|
|
1382
|
+
<!-- What holds this server, from its own profiler (server/profile.mjs; POST /api/server/profile). -->
|
|
1383
|
+
<pre id="load-profile-out" class="load-profile" hidden></pre>
|
|
1384
|
+
<!-- The measures it took by itself when its loop was slow (server/profile.mjs AutoProfile). -->
|
|
1385
|
+
<div id="load-auto" class="load-list" hidden></div>
|
|
1381
1386
|
</div>
|
|
1382
1387
|
</details>
|
|
1383
1388
|
<!-- WHAT THE SERVER'S PROGRAMS SAID, to read, copy whole or keep (server/serverlogs.mjs);
|
package/web/style.css
CHANGED
|
@@ -1766,6 +1766,7 @@ svg.u-spark .u-oom { fill: var(--danger); stroke: var(--panel); stroke-width: 1.
|
|
|
1766
1766
|
.load-list { display: flex; flex-direction: column; gap: 6px; margin: 8px 0; font-size: .875rem; }
|
|
1767
1767
|
.load-list .load-row { display: flex; flex-direction: column; min-width: 0; }
|
|
1768
1768
|
.load-list .load-kinds { font-size: .75rem; color: var(--ink2); overflow-wrap: anywhere; }
|
|
1769
|
+
.load-profile { font-size: .75rem; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 24rem; overflow: auto; margin: 8px 0; }
|
|
1769
1770
|
.job-line { border-bottom: 1px solid var(--line); }
|
|
1770
1771
|
.job-line > summary { display: grid; grid-template-columns: 16px 1fr; gap: 2px 8px; padding: 4px 0; cursor: pointer; list-style: none; }
|
|
1771
1772
|
.job-line > summary::-webkit-details-marker { display: none; }
|