@kabmo-labs/kabmo 0.15.0 → 0.16.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.
Files changed (53) hide show
  1. package/README.md +1 -0
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +374 -356
  4. package/dist/client/static/js/{index-mx658m43.js → index-cpydmygd.js} +644 -644
  5. package/dist/client/static/js/index-fjnq2z2d.css +1 -0
  6. package/marketplace/plugins/stats/README.md +27 -8
  7. package/marketplace/plugins/stats/package.json +2 -2
  8. package/marketplace/plugins/stats/src/HeaderReadout.test.tsx +2 -1
  9. package/marketplace/plugins/stats/src/HeaderReadout.tsx +6 -2
  10. package/marketplace/plugins/stats/src/KillConfirm.test.tsx +159 -0
  11. package/marketplace/plugins/stats/src/KillConfirm.tsx +145 -0
  12. package/marketplace/plugins/stats/src/ProcessTable.tsx +54 -8
  13. package/marketplace/plugins/stats/src/TotalsBar.test.tsx +5 -2
  14. package/marketplace/plugins/stats/src/TotalsBar.tsx +13 -3
  15. package/marketplace/plugins/stats/src/app.test.tsx +100 -4
  16. package/marketplace/plugins/stats/src/app.tsx +51 -4
  17. package/marketplace/plugins/stats/src/groups.test.ts +1 -1
  18. package/marketplace/plugins/stats/src/kill.test.ts +131 -0
  19. package/marketplace/plugins/stats/src/kill.ts +74 -0
  20. package/marketplace/plugins/stats/src/labels.test.ts +1 -0
  21. package/marketplace/plugins/stats/src/machine.test.ts +77 -0
  22. package/marketplace/plugins/stats/src/machine.ts +115 -0
  23. package/marketplace/plugins/stats/src/proc/darwin.ts +38 -0
  24. package/marketplace/plugins/stats/src/proc/linux.ts +4 -0
  25. package/marketplace/plugins/stats/src/proc/ps.ts +1 -0
  26. package/marketplace/plugins/stats/src/proc/types.ts +11 -0
  27. package/marketplace/plugins/stats/src/sampler.test.ts +42 -4
  28. package/marketplace/plugins/stats/src/sampler.ts +32 -18
  29. package/marketplace/plugins/stats/src/server.ts +29 -2
  30. package/marketplace/plugins/stats/src/snapshot.ts +31 -3
  31. package/package.json +3 -2
  32. package/src/client/components/common/Modal.tsx +7 -0
  33. package/src/client/components/layout/LeftDock.tsx +1 -0
  34. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +1 -0
  35. package/src/client/components/mobile/RightSidebar.tsx +1 -0
  36. package/src/client/components/mobile/mobile-session-sidebar/use-dock.ts +1 -0
  37. package/src/client/components/workspace/model-dropdown/Panel.tsx +7 -2
  38. package/src/client/components/workspace/model-dropdown/Section.test.tsx +13 -0
  39. package/src/client/components/workspace/model-dropdown/Section.tsx +5 -1
  40. package/src/client/components/workspace/panels/builtin.tsx +7 -0
  41. package/src/client/components/workspace/wiki-panel/NavModal.test.tsx +136 -0
  42. package/src/client/components/workspace/wiki-panel/NavModal.tsx +94 -0
  43. package/src/client/components/workspace/wiki-panel/PageView.tsx +16 -10
  44. package/src/client/components/workspace/wiki-panel/index.tsx +44 -9
  45. package/src/server/lib/db/schema.ts +11 -0
  46. package/src/server/lib/lifecycle/memory.test.ts +41 -1
  47. package/src/server/lib/lifecycle/memory.ts +131 -14
  48. package/src/server/lib/omp/session/subagent-presence-scan.test.ts +137 -0
  49. package/src/server/lib/omp/session/subagent-presence-scan.ts +120 -0
  50. package/src/server/lib/omp/session/subagent-presence-store.test.ts +120 -0
  51. package/src/server/lib/omp/session/subagent-presence-store.ts +65 -0
  52. package/src/server/lib/omp/session/subagent-presence.ts +52 -15
  53. package/dist/client/static/js/index-28pwtt69.css +0 -1
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The kill dialog: the states that decide whether a destructive control is
8
+ * usable or dangerous.
9
+ *
10
+ * The table's `×` is 16px in a dense row, so the dialog is the whole safety
11
+ * margin. What this pins:
12
+ *
13
+ * - Cancel holds focus on open, so Enter on an accidental open does nothing;
14
+ * - Escape cancels;
15
+ * - a refusal from the server is rendered INSIDE the dialog (a close-and-drop
16
+ * would leave the reader pressing a button that never works);
17
+ * - while the call is in flight the stop button is disabled and says so.
18
+ */
19
+
20
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
21
+ import { Window } from 'happy-dom';
22
+ import { render } from 'preact';
23
+
24
+ import { KillConfirm } from './KillConfirm';
25
+ import type { ProcessRow } from './snapshot';
26
+
27
+ // `requestAnimationFrame` is part of the list because Preact's effects are
28
+ // flushed on the next frame when one is available: without it the hooks module
29
+ // waits out its own 100 ms fallback, and every assertion here reads a dialog
30
+ // whose listeners are not attached yet.
31
+ const DOM_GLOBALS = [
32
+ 'window',
33
+ 'document',
34
+ 'navigator',
35
+ 'HTMLElement',
36
+ 'Node',
37
+ 'Text',
38
+ 'Element',
39
+ 'SVGElement',
40
+ 'requestAnimationFrame',
41
+ 'cancelAnimationFrame',
42
+ ] as const;
43
+ type DomGlobal = (typeof DOM_GLOBALS)[number];
44
+ const saved = new Map<DomGlobal, unknown>();
45
+
46
+ beforeAll(() => {
47
+ const win = new Window({ url: 'http://localhost/' });
48
+ for (const key of DOM_GLOBALS) {
49
+ saved.set(key, Reflect.get(globalThis, key));
50
+ Reflect.set(globalThis, key, (win as unknown as Record<string, unknown>)[key]);
51
+ }
52
+ });
53
+
54
+ afterAll(() => {
55
+ for (const key of DOM_GLOBALS) Reflect.set(globalThis, key, saved.get(key));
56
+ });
57
+
58
+ afterEach(() => {
59
+ document.body.innerHTML = '';
60
+ });
61
+
62
+ const ROW: ProcessRow = {
63
+ pid: 4242,
64
+ ppid: 100,
65
+ title: 'omp · rpc-ui · kabmo',
66
+ detail: '/Users/me/projects/kabmo · 12m',
67
+ groupKey: 'session',
68
+ depth: 1,
69
+ memory: 134 * 1024 * 1024,
70
+ memorySource: 'footprint',
71
+ rss: 317 * 1024 * 1024,
72
+ cpuPercent: 3.5,
73
+ threads: 12,
74
+ };
75
+
76
+ /**
77
+ * Preact runs effects after paint, so a mount is not "ready" until one tick has
78
+ * passed. Without the tick the Escape listener is not attached yet and the
79
+ * autofocus has not happened — and the effect lands AFTER the test's cleanup,
80
+ * which is how this suite used to fail between tests instead of inside one.
81
+ */
82
+ async function settle(): Promise<void> {
83
+ await new Promise((resolve) => setTimeout(resolve, 80));
84
+ }
85
+
86
+ async function dialogFor(overrides: Partial<Parameters<typeof KillConfirm>[0]> = {}) {
87
+ const calls = { cancel: 0, confirm: 0 };
88
+ const container = document.createElement('div');
89
+ document.body.appendChild(container);
90
+ render(
91
+ <KillConfirm
92
+ row={ROW}
93
+ pending={false}
94
+ error={null}
95
+ onCancel={() => {
96
+ calls.cancel += 1;
97
+ }}
98
+ onConfirm={() => {
99
+ calls.confirm += 1;
100
+ }}
101
+ {...overrides}
102
+ />,
103
+ container,
104
+ );
105
+ await settle();
106
+ return { container, calls };
107
+ }
108
+
109
+ describe('KillConfirm', () => {
110
+ test('names the process, its pid and the memory it holds', async () => {
111
+ const { container } = await dialogFor();
112
+ const text = container.textContent ?? '';
113
+ expect(text).toContain('Stop pid 4242?');
114
+ expect(text).toContain('omp · rpc-ui · kabmo');
115
+ expect(text).toContain('134.0 MB');
116
+ expect(text).toContain('SIGTERM');
117
+ });
118
+
119
+ test('Cancel holds focus on open, so Enter cannot kill anything', async () => {
120
+ const { container } = await dialogFor();
121
+ const buttons = [...container.querySelectorAll('button')];
122
+ expect(document.activeElement).toBe(buttons[0]);
123
+ expect(buttons[0].textContent).toBe('Cancel');
124
+ });
125
+
126
+ test('Escape cancels', async () => {
127
+ const { container, calls } = await dialogFor();
128
+ const event = new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true });
129
+ window.dispatchEvent(event);
130
+ expect(calls.cancel).toBe(1);
131
+ expect(container.querySelector('[role="dialog"]')).not.toBeNull();
132
+ });
133
+
134
+ test('a refusal from the server is shown inside the dialog', async () => {
135
+ const { container } = await dialogFor({ error: 'pid 4242 belongs to another user, so it cannot be signalled.' });
136
+ const alert = container.querySelector('[role="alert"]');
137
+ expect(alert?.textContent).toContain('another user');
138
+ });
139
+
140
+ test('the stop button disables and relabels itself while in flight', async () => {
141
+ const { container } = await dialogFor({ pending: true });
142
+ const buttons = [...container.querySelectorAll('button')];
143
+ const stop = buttons.find((button) => button.textContent?.includes('Stopping'));
144
+ expect(stop).toBeDefined();
145
+ expect((stop as HTMLButtonElement).disabled).toBe(true);
146
+ });
147
+
148
+ test('Stop process confirms, and the backdrop dismisses', async () => {
149
+ const { container, calls } = await dialogFor();
150
+ const buttons = [...container.querySelectorAll('button')];
151
+ const stop = buttons.find((button) => button.textContent === 'Stop process');
152
+ stop?.click();
153
+ expect(calls.confirm).toBe(1);
154
+
155
+ const backdrop = container.querySelector('.fixed');
156
+ backdrop?.dispatchEvent(new window.MouseEvent('mousedown', { bubbles: true }));
157
+ expect(calls.cancel).toBe(1);
158
+ });
159
+ });
@@ -0,0 +1,145 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The confirmation a kill gets — the only destructive control in this panel.
8
+ *
9
+ * A process row is 22px tall and the table is dense, so a bare `×` beside it is
10
+ * one mis-click from killing the run the user is reading. This dialog is what
11
+ * stands between them, and it names the process, its pid and what it is holding
12
+ * so the reader can tell whether it is the one they meant.
13
+ *
14
+ * Three behaviours, each a correctness rule rather than polish:
15
+ *
16
+ * - **Cancel is focused first.** Enter on an accidental open must not kill.
17
+ * - **Escape cancels, and Tab stays inside.** A destructive dialog that lets
18
+ * focus wander into the table behind it is a dialog the keyboard can defeat.
19
+ * The trap is small on purpose: two buttons.
20
+ * - **The panel's own refusal is shown here, inline.** The server answers
21
+ * `{ killed: false, reason }` for a pid it will not signal (a stale row, a
22
+ * foreign process); closing the dialog and dropping the sentence would leave
23
+ * the user pressing a button that does nothing.
24
+ */
25
+
26
+ import { useEffect, useRef } from 'preact/hooks';
27
+
28
+ import { formatBytes } from './format';
29
+ import type { ProcessRow } from './snapshot';
30
+
31
+ export interface KillConfirmProps {
32
+ row: ProcessRow;
33
+ /** The kill call is in flight. */
34
+ pending: boolean;
35
+ /** The server's refusal for this attempt, or a transport error. */
36
+ error: string | null;
37
+ onCancel: () => void;
38
+ onConfirm: () => void;
39
+ }
40
+
41
+ const FOCUSABLE = 'button:not([disabled])';
42
+
43
+ export function KillConfirm({ row, pending, error, onCancel, onConfirm }: KillConfirmProps) {
44
+ const cancelRef = useRef<HTMLButtonElement>(null);
45
+ const dialogRef = useRef<HTMLDivElement>(null);
46
+
47
+ useEffect(() => {
48
+ cancelRef.current?.focus();
49
+ }, []);
50
+
51
+ useEffect(() => {
52
+ const onKeyDown = (event: KeyboardEvent) => {
53
+ if (event.key === 'Escape') {
54
+ event.preventDefault();
55
+ onCancel();
56
+ return;
57
+ }
58
+ if (event.key !== 'Tab') return;
59
+ const dialog = dialogRef.current;
60
+ if (!dialog) return;
61
+ const targets = [...dialog.querySelectorAll<HTMLElement>(FOCUSABLE)];
62
+ if (targets.length === 0) return;
63
+ const first = targets[0];
64
+ const last = targets[targets.length - 1];
65
+ const active = document.activeElement;
66
+ if (event.shiftKey && (active === first || !dialog.contains(active))) {
67
+ event.preventDefault();
68
+ last.focus();
69
+ } else if (!event.shiftKey && (active === last || !dialog.contains(active))) {
70
+ event.preventDefault();
71
+ first.focus();
72
+ }
73
+ };
74
+ window.addEventListener('keydown', onKeyDown);
75
+ return () => window.removeEventListener('keydown', onKeyDown);
76
+ }, [onCancel]);
77
+
78
+ return (
79
+ <div
80
+ class="fixed inset-0 z-50 flex items-center justify-center bg-ink/35 p-4"
81
+ onMouseDown={(event) => {
82
+ if (event.target === event.currentTarget) onCancel();
83
+ }}
84
+ >
85
+ <div
86
+ ref={dialogRef}
87
+ role="dialog"
88
+ aria-modal="true"
89
+ aria-labelledby="stats-kill-title"
90
+ aria-describedby="stats-kill-body"
91
+ class="w-full max-w-sm flex flex-col gap-3 rounded-lg border border-ink/15 bg-paper p-3 shadow-xl"
92
+ >
93
+ <div class="flex flex-col gap-1">
94
+ <h2 id="stats-kill-title" class="font-sans text-sm font-semibold text-ink">
95
+ Stop pid {row.pid}?
96
+ </h2>
97
+ <p id="stats-kill-body" class="font-sans text-xs text-ink/70">
98
+ {row.title}
99
+ {row.detail ? <span class="block font-mono text-[10px] text-ink/45">{row.detail}</span> : null}
100
+ </p>
101
+ </div>
102
+
103
+ <dl class="grid grid-cols-2 gap-1 font-mono text-[10px] text-ink/50">
104
+ <dt>memory</dt>
105
+ <dd class="text-right text-ink/70">
106
+ {formatBytes(row.memory)}
107
+ {row.memorySource === 'footprint' ? ' footprint' : ' rss'}
108
+ </dd>
109
+ <dt>threads</dt>
110
+ <dd class="text-right text-ink/70">{row.threads > 0 ? row.threads : '—'}</dd>
111
+ </dl>
112
+
113
+ <p class="font-sans text-[11px] text-ink/60">
114
+ Sends <span class="font-mono">SIGTERM</span>: the process flushes and exits. Work it was running is lost.
115
+ A process that ignores the signal stays in the table — press again to re-send.
116
+ </p>
117
+
118
+ {error ? (
119
+ <p role="alert" class="rounded border border-error/30 bg-error/10 px-2 py-1 font-sans text-[11px] text-error">
120
+ {error}
121
+ </p>
122
+ ) : null}
123
+
124
+ <div class="flex items-center justify-end gap-2">
125
+ <button
126
+ ref={cancelRef}
127
+ type="button"
128
+ onClick={onCancel}
129
+ class="inline-flex items-center px-2.5 py-1.5 text-xs rounded border border-ink/15 text-ink hover:bg-ink/5"
130
+ >
131
+ Cancel
132
+ </button>
133
+ <button
134
+ type="button"
135
+ onClick={onConfirm}
136
+ disabled={pending}
137
+ class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded border border-error/40 bg-error/10 font-semibold text-error transition-colors hover:bg-error/15 disabled:opacity-40 disabled:cursor-default"
138
+ >
139
+ {pending ? 'Stopping…' : 'Stop process'}
140
+ </button>
141
+ </div>
142
+ </div>
143
+ </div>
144
+ );
145
+ }
@@ -36,6 +36,8 @@ import type { GroupSummary, ProcessRow, StatsSnapshot } from './sampler';
36
36
 
37
37
  interface ProcessTableProps {
38
38
  snapshot: StatsSnapshot;
39
+ /** Ask before signalling: the table never kills anything itself. */
40
+ onRequestKill: (row: ProcessRow) => void;
39
41
  }
40
42
 
41
43
  /** The colour a group's dot takes, so the list is scannable. */
@@ -95,7 +97,15 @@ function indent(depth: number): string {
95
97
  return ' '.repeat(Math.min(depth, 4));
96
98
  }
97
99
 
98
- function ProcessRowView({ row, serverPid }: { row: ProcessRow; serverPid: number }) {
100
+ function ProcessRowView({
101
+ row,
102
+ serverPid,
103
+ onRequestKill,
104
+ }: {
105
+ row: ProcessRow;
106
+ serverPid: number;
107
+ onRequestKill: (row: ProcessRow) => void;
108
+ }) {
99
109
  const pad = indent(row.depth);
100
110
  return (
101
111
  <tr class="border-t border-ink/5 hover:bg-ink/[0.02]">
@@ -115,8 +125,15 @@ function ProcessRowView({ row, serverPid }: { row: ProcessRow; serverPid: number
115
125
  </div>
116
126
  ) : null}
117
127
  </td>
118
- <td class="py-1 pr-2 align-top text-right font-mono text-[11px] text-ink whitespace-nowrap w-16">
119
- {formatBytes(row.rss)}
128
+ <td
129
+ class="py-1 pr-2 align-top text-right font-mono text-[11px] text-ink whitespace-nowrap w-16"
130
+ title={
131
+ row.memorySource === 'footprint'
132
+ ? `Physical footprint ${formatBytes(row.memory)} (resident ${formatBytes(row.rss)})`
133
+ : `Resident size ${formatBytes(row.rss)} — this process reports no footprint`
134
+ }
135
+ >
136
+ {formatBytes(row.memory)}
120
137
  </td>
121
138
  <td class="py-1 pr-2 align-top text-right font-mono text-[11px] text-ink/70 whitespace-nowrap w-14 @max-[360px]:hidden">
122
139
  {formatPercent(row.cpuPercent)}
@@ -124,6 +141,23 @@ function ProcessRowView({ row, serverPid }: { row: ProcessRow; serverPid: number
124
141
  <td class="py-1 pr-2 align-top text-right font-mono text-[10px] text-ink/40 w-9 @max-[300px]:hidden">
125
142
  {row.threads > 0 ? row.threads : ''}
126
143
  </td>
144
+ <td class="py-1 align-top text-right w-6">
145
+ {/* No button for the server that hosts this panel: it would take the
146
+ UI, every live session and the sampler with it, and stopping it is
147
+ `kabmo stop` — the refusal is stated by omission, and the server
148
+ half refuses it too. */}
149
+ {row.pid === serverPid ? null : (
150
+ <button
151
+ type="button"
152
+ onClick={() => onRequestKill(row)}
153
+ aria-label={`Stop pid ${row.pid}`}
154
+ title={`Stop pid ${row.pid}`}
155
+ class="inline-flex h-4 w-4 items-center justify-center rounded text-[11px] leading-none text-ink/30 hover:bg-error/10 hover:text-error"
156
+ >
157
+ ×
158
+ </button>
159
+ )}
160
+ </td>
127
161
  </tr>
128
162
  );
129
163
  }
@@ -162,17 +196,18 @@ function GroupRow({ group }: { group: GroupSummary }) {
162
196
  ) : null}
163
197
  </td>
164
198
  <td class="py-1.5 pr-2 text-right font-mono text-[10px] text-ink/60 whitespace-nowrap w-16">
165
- {formatBytes(group.rss)}
199
+ {formatBytes(group.memory)}
166
200
  </td>
167
201
  <td class="py-1.5 pr-2 text-right font-mono text-[10px] text-ink/60 whitespace-nowrap w-14 @max-[360px]:hidden">
168
202
  {formatPercent(group.cpuPercent)}
169
203
  </td>
170
204
  <td class="py-1.5 pr-2 w-9 @max-[300px]:hidden" />
205
+ <td class="py-1.5 w-6" />
171
206
  </tr>
172
207
  );
173
208
  }
174
209
 
175
- export function ProcessTable({ snapshot }: ProcessTableProps) {
210
+ export function ProcessTable({ snapshot, onRequestKill }: ProcessTableProps) {
176
211
  const rowsByGroup = new Map<string, ProcessRow[]>();
177
212
  for (const row of snapshot.rows) {
178
213
  const bucket = rowsByGroup.get(row.groupKey);
@@ -204,7 +239,12 @@ export function ProcessTable({ snapshot }: ProcessTableProps) {
204
239
  <tr>
205
240
  <HeaderCell label="PID" align="right" title="Operating-system process id" class="w-14" />
206
241
  <HeaderCell label="Process" title="What it is, and the project, session and age behind it" />
207
- <HeaderCell label="Memory" align="right" title="Resident set size (RSS)" class="w-16" />
242
+ <HeaderCell
243
+ label="Memory"
244
+ align="right"
245
+ title="Physical footprint where the OS reports one (macOS); resident size otherwise"
246
+ class="w-16"
247
+ />
208
248
  <HeaderCell
209
249
  label="CPU"
210
250
  align="right"
@@ -212,6 +252,7 @@ export function ProcessTable({ snapshot }: ProcessTableProps) {
212
252
  class="w-14 @max-[360px]:hidden"
213
253
  />
214
254
  <HeaderCell label="Thr" align="right" title="Thread count" class="w-9 @max-[300px]:hidden" />
255
+ <HeaderCell label="" class="w-6" />
215
256
  </tr>
216
257
  </thead>
217
258
  {snapshot.groups.map((group) => {
@@ -224,9 +265,14 @@ export function ProcessTable({ snapshot }: ProcessTableProps) {
224
265
  // Owner first, then the tree in BFS order, and only then by size:
225
266
  // sorting by RSS alone put a 719 MB grandchild above the process
226
267
  // that spawned it, which is the one row the group is about.
227
- .sort((a, b) => a.depth - b.depth || b.rss - a.rss)
268
+ .sort((a, b) => a.depth - b.depth || b.memory - a.memory)
228
269
  .map((row) => (
229
- <ProcessRowView key={row.pid} row={row} serverPid={snapshot.serverPid} />
270
+ <ProcessRowView
271
+ key={row.pid}
272
+ row={row}
273
+ serverPid={snapshot.serverPid}
274
+ onRequestKill={onRequestKill}
275
+ />
230
276
  ))}
231
277
  </tbody>
232
278
  );
@@ -33,6 +33,8 @@ function row(overrides: Partial<ProcessRow> = {}): ProcessRow {
33
33
  detail: 'the server itself',
34
34
  groupKey: 'kabmo',
35
35
  depth: 0,
36
+ memory: 1024 * 1024,
37
+ memorySource: 'rss',
36
38
  rss: 1024 * 1024,
37
39
  cpuPercent: null,
38
40
  threads: 4,
@@ -53,11 +55,12 @@ function snapshot(rows: ProcessRow[]): StatsSnapshot {
53
55
  title: 'Kabmo server',
54
56
  detail: 'the server itself',
55
57
  processes: rows.length,
56
- rss: 1024 * 1024,
58
+ memory: 1024 * 1024,
57
59
  cpuPercent: 0,
58
60
  },
59
61
  ],
60
- total: { processes: rows.length, rss: 1024 * 1024, cpuPercent: 0 },
62
+ total: { processes: rows.length, memory: 1024 * 1024, cpuPercent: 0 },
63
+ memorySource: 'rss',
61
64
  machine: { totalMemBytes: 16 * 1024 ** 3, freeMemBytes: 4 * 1024 ** 3, cpuCount: 8, loadPerCore: 0.25 },
62
65
  daemons: [],
63
66
  serverPid: 100,
@@ -29,7 +29,12 @@ interface TotalsBarProps {
29
29
 
30
30
  export function TotalsBar({ snapshot, onRefresh, refreshing }: TotalsBarProps) {
31
31
  const { total, machine, probe } = snapshot;
32
- const memoryShare = machine.totalMemBytes > 0 ? (total.rss / machine.totalMemBytes) * 100 : null;
32
+ const memoryShare = machine.totalMemBytes > 0 ? (total.memory / machine.totalMemBytes) * 100 : null;
33
+ // Which figure the column and the totals carry. A sum of two different
34
+ // quantities must not be labelled as one of them, so `mixed` says so.
35
+ const memoryLabel = snapshot.memorySource === 'footprint' ? 'footprint'
36
+ : snapshot.memorySource === 'mixed' ? 'footprint + rss'
37
+ : 'resident';
33
38
 
34
39
  return (
35
40
  <div class="flex flex-col gap-3 border-b border-ink/10 px-3 py-3">
@@ -43,9 +48,10 @@ export function TotalsBar({ snapshot, onRefresh, refreshing }: TotalsBarProps) {
43
48
  <div class="grid grid-cols-3 gap-3">
44
49
  <div class="flex flex-col gap-0.5">
45
50
  <span class="text-[10px] uppercase font-mono text-ink/40">Memory</span>
46
- <span class="text-sm font-semibold font-mono text-ink">{formatBytes(total.rss)}</span>
51
+ <span class="text-sm font-semibold font-mono text-ink">{formatBytes(total.memory)}</span>
47
52
  <span class="text-[10px] font-mono text-ink/45">
48
53
  {memoryShare === null ? 'machine unknown' : `${memoryShare.toFixed(1)}% of ${formatBytes(machine.totalMemBytes)}`}
54
+ {` · ${memoryLabel}`}
49
55
  </span>
50
56
  </div>
51
57
  <div class="flex flex-col gap-0.5">
@@ -88,7 +94,11 @@ export function MachineFacts({ snapshot }: { snapshot: StatsSnapshot }) {
88
94
  return (
89
95
  <FieldList>
90
96
  <Field label="total memory" value={formatBytes(machine.totalMemBytes)} />
91
- <Field label="free memory" value={formatBytes(machine.freeMemBytes)} />
97
+ {/* "available", not "free": this is free + inactive + speculative on
98
+ macOS and `MemAvailable` on Linux — the memory a new allocation can
99
+ get without swapping. `os.freemem()` reported 1.05 GB here while
100
+ 5.60 GB was available. */}
101
+ <Field label="memory available" value={formatBytes(machine.freeMemBytes)} />
92
102
  <Field label="cores" value={String(machine.cpuCount)} />
93
103
  <Field label="load (1m/core)" value={machine.loadPerCore.toFixed(3)} />
94
104
  </FieldList>
@@ -107,6 +107,8 @@ function snapshot(overrides: Partial<StatsSnapshot> = {}): StatsSnapshot {
107
107
  detail: 'the server itself · 1m',
108
108
  groupKey: 'kabmo',
109
109
  depth: 0,
110
+ memory: 2 * 1024 * 1024,
111
+ memorySource: 'rss',
110
112
  rss: 2 * 1024 * 1024,
111
113
  cpuPercent: 1.5,
112
114
  threads: 4,
@@ -120,11 +122,12 @@ function snapshot(overrides: Partial<StatsSnapshot> = {}): StatsSnapshot {
120
122
  title: 'Kabmo server',
121
123
  detail: 'the server itself · 1m',
122
124
  processes: 1,
123
- rss: 2 * 1024 * 1024,
125
+ memory: 2 * 1024 * 1024,
124
126
  cpuPercent: 1.5,
125
127
  },
126
128
  ],
127
- total: { processes: 1, rss: 2 * 1024 * 1024, cpuPercent: 1.5 },
129
+ total: { processes: 1, memory: 2 * 1024 * 1024, cpuPercent: 1.5 },
130
+ memorySource: 'rss',
128
131
  machine: { totalMemBytes: 8 * 1024 ** 3, freeMemBytes: 1024 ** 3, cpuCount: 8, loadPerCore: 0.1 },
129
132
  daemons: [],
130
133
  serverPid: 1,
@@ -192,7 +195,8 @@ describe('StatsPanel server-half state', () => {
192
195
  probe: { name: 'win32', supported: false, reason: 'no subprocess-free route' },
193
196
  rows: [],
194
197
  groups: [],
195
- total: { processes: 0, rss: 0, cpuPercent: 0 },
198
+ total: { processes: 0, memory: 0, cpuPercent: 0 },
199
+ memorySource: 'rss',
196
200
  error: 'no subprocess-free route',
197
201
  }),
198
202
  });
@@ -206,7 +210,7 @@ describe('StatsPanel server-half state', () => {
206
210
  const text = await textFor({
207
211
  live: true,
208
212
  publish: snapshot({
209
- history: { rss: [1_400_000_000, 1_500_000_000], cpuPercent: [2.5, 12.0] },
213
+ history: { memory: [1_400_000_000, 1_500_000_000], cpuPercent: [2.5, 12.0] },
210
214
  }),
211
215
  });
212
216
  expect(text).not.toMatch(/\d{9,}\.\d/);
@@ -226,3 +230,95 @@ describe('StatsPanel server-half state', () => {
226
230
  expect(html).toContain('@max-[300px]:hidden');
227
231
  });
228
232
  });
233
+
234
+ /** A row the panel may stop, beside the one it may not. */
235
+ function killableSnapshot(): StatsSnapshot {
236
+ const base = snapshot();
237
+ const server = base.rows[0];
238
+ const host = {
239
+ ...server,
240
+ pid: 101,
241
+ ppid: server.pid,
242
+ title: 'omp · rpc-ui',
243
+ detail: 'project · 2m',
244
+ groupKey: 'session',
245
+ depth: 1,
246
+ };
247
+ return {
248
+ ...base,
249
+ rows: [server, host],
250
+ // The table renders GROUPS and then their rows, so a row without a group
251
+ // is a row the panel never draws.
252
+ groups: [base.groups[0], { ...base.groups[0], key: 'session', kind: 'session', ownerPid: 101, title: host.title, detail: host.detail }],
253
+ };
254
+ }
255
+
256
+ describe('StatsPanel kill control', () => {
257
+ test('the × exists for a measured process and never for the server itself', async () => {
258
+ const { harness } = loadPluginApp(pluginDefinition);
259
+ harness.services.rpc.stub('watch', { watching: 1 });
260
+ harness.services.publishTopic(killableSnapshot());
261
+ const rendered = await renderStatsPanel(harness);
262
+
263
+ expect(rendered.html).toContain('aria-label="Stop pid 101"');
264
+ expect(rendered.html).not.toContain('aria-label="Stop pid 1"');
265
+
266
+ rendered.unmount();
267
+ harness.dispose();
268
+ configureUiKit(uiKitServices() ?? harness.services);
269
+ });
270
+
271
+ test('clicking × opens the dialog, and Cancel closes it without a kill', async () => {
272
+ const { harness } = loadPluginApp(pluginDefinition);
273
+ harness.services.rpc.stub('watch', { watching: 1 });
274
+ harness.services.rpc.stub('kill', { killed: true, pid: 101, title: 'omp · rpc-ui', signal: 'SIGTERM' });
275
+ harness.services.publishTopic(killableSnapshot());
276
+ const rendered = await renderStatsPanel(harness);
277
+
278
+ const container = document.body.lastElementChild as HTMLElement;
279
+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Stop pid 101"]');
280
+ expect(button).not.toBeNull();
281
+ await act(async () => {
282
+ button?.click();
283
+ });
284
+ expect(container.textContent).toContain('Stop pid 101?');
285
+
286
+ const cancel = [...container.querySelectorAll('button')].find((candidate) => candidate.textContent === 'Cancel');
287
+ await act(async () => {
288
+ cancel?.click();
289
+ });
290
+ expect(container.textContent).not.toContain('Stop pid 101?');
291
+ expect(harness.services.rpc.calls.filter((call) => call.method === 'kill')).toHaveLength(0);
292
+
293
+ rendered.unmount();
294
+ harness.dispose();
295
+ configureUiKit(uiKitServices() ?? harness.services);
296
+ });
297
+
298
+ test('confirming sends the pid and forces a sample so the row disappears', async () => {
299
+ const { harness } = loadPluginApp(pluginDefinition);
300
+ harness.services.rpc.stub('watch', { watching: 1 });
301
+ harness.services.rpc.stub('kill', { killed: true, pid: 101, title: 'omp · rpc-ui', signal: 'SIGTERM' });
302
+ harness.services.rpc.stub('snapshot', killableSnapshot());
303
+ harness.services.publishTopic(killableSnapshot());
304
+ const rendered = await renderStatsPanel(harness);
305
+
306
+ const container = document.body.lastElementChild as HTMLElement;
307
+ await act(async () => {
308
+ container.querySelector<HTMLButtonElement>('button[aria-label="Stop pid 101"]')?.click();
309
+ });
310
+ const stop = [...container.querySelectorAll('button')].find((candidate) => candidate.textContent === 'Stop process');
311
+ await act(async () => {
312
+ stop?.click();
313
+ await new Promise((resolve) => setTimeout(resolve, 0));
314
+ });
315
+
316
+ const calls = harness.services.rpc.calls;
317
+ expect(calls.filter((call) => call.method === 'kill').map((call) => call.input)).toEqual([{ pid: 101 }]);
318
+ expect(calls.some((call) => call.method === 'snapshot' && (call.input as { force?: boolean } | undefined)?.force === true)).toBe(true);
319
+
320
+ rendered.unmount();
321
+ harness.dispose();
322
+ configureUiKit(uiKitServices() ?? harness.services);
323
+ });
324
+ });