@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.
- package/README.md +1 -0
- package/dist/client/index.html +1 -1
- package/dist/client/index.js +374 -356
- package/dist/client/static/js/{index-mx658m43.js → index-cpydmygd.js} +644 -644
- package/dist/client/static/js/index-fjnq2z2d.css +1 -0
- package/marketplace/plugins/stats/README.md +27 -8
- package/marketplace/plugins/stats/package.json +2 -2
- package/marketplace/plugins/stats/src/HeaderReadout.test.tsx +2 -1
- package/marketplace/plugins/stats/src/HeaderReadout.tsx +6 -2
- package/marketplace/plugins/stats/src/KillConfirm.test.tsx +159 -0
- package/marketplace/plugins/stats/src/KillConfirm.tsx +145 -0
- package/marketplace/plugins/stats/src/ProcessTable.tsx +54 -8
- package/marketplace/plugins/stats/src/TotalsBar.test.tsx +5 -2
- package/marketplace/plugins/stats/src/TotalsBar.tsx +13 -3
- package/marketplace/plugins/stats/src/app.test.tsx +100 -4
- package/marketplace/plugins/stats/src/app.tsx +51 -4
- package/marketplace/plugins/stats/src/groups.test.ts +1 -1
- package/marketplace/plugins/stats/src/kill.test.ts +131 -0
- package/marketplace/plugins/stats/src/kill.ts +74 -0
- package/marketplace/plugins/stats/src/labels.test.ts +1 -0
- package/marketplace/plugins/stats/src/machine.test.ts +77 -0
- package/marketplace/plugins/stats/src/machine.ts +115 -0
- package/marketplace/plugins/stats/src/proc/darwin.ts +38 -0
- package/marketplace/plugins/stats/src/proc/linux.ts +4 -0
- package/marketplace/plugins/stats/src/proc/ps.ts +1 -0
- package/marketplace/plugins/stats/src/proc/types.ts +11 -0
- package/marketplace/plugins/stats/src/sampler.test.ts +42 -4
- package/marketplace/plugins/stats/src/sampler.ts +32 -18
- package/marketplace/plugins/stats/src/server.ts +29 -2
- package/marketplace/plugins/stats/src/snapshot.ts +31 -3
- package/package.json +3 -2
- package/src/client/components/common/Modal.tsx +7 -0
- package/src/client/components/layout/LeftDock.tsx +1 -0
- package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +1 -0
- package/src/client/components/mobile/RightSidebar.tsx +1 -0
- package/src/client/components/mobile/mobile-session-sidebar/use-dock.ts +1 -0
- package/src/client/components/workspace/model-dropdown/Panel.tsx +7 -2
- package/src/client/components/workspace/model-dropdown/Section.test.tsx +13 -0
- package/src/client/components/workspace/model-dropdown/Section.tsx +5 -1
- package/src/client/components/workspace/panels/builtin.tsx +7 -0
- package/src/client/components/workspace/wiki-panel/NavModal.test.tsx +136 -0
- package/src/client/components/workspace/wiki-panel/NavModal.tsx +94 -0
- package/src/client/components/workspace/wiki-panel/PageView.tsx +16 -10
- package/src/client/components/workspace/wiki-panel/index.tsx +44 -9
- package/src/server/lib/db/schema.ts +11 -0
- package/src/server/lib/lifecycle/memory.test.ts +41 -1
- package/src/server/lib/lifecycle/memory.ts +131 -14
- package/src/server/lib/omp/session/subagent-presence-scan.test.ts +137 -0
- package/src/server/lib/omp/session/subagent-presence-scan.ts +120 -0
- package/src/server/lib/omp/session/subagent-presence-store.test.ts +120 -0
- package/src/server/lib/omp/session/subagent-presence-store.ts +65 -0
- package/src/server/lib/omp/session/subagent-presence.ts +52 -15
- package/dist/client/static/js/index-28pwtt69.css +0 -1
|
@@ -30,12 +30,14 @@ import { definePluginApp } from '@kabmo-labs/kabmo-sdk/app';
|
|
|
30
30
|
import { usePanelHost, useRealtime, useRpc } from '@kabmo-labs/kabmo-ui';
|
|
31
31
|
import { Empty, Note, Panel } from '@kabmo-labs/kabmo-ui/components';
|
|
32
32
|
|
|
33
|
+
import { KillConfirm } from './KillConfirm';
|
|
33
34
|
import { ProcessTable } from './ProcessTable';
|
|
34
35
|
import { Sparkline } from './Sparkline';
|
|
35
36
|
import { MachineFacts, TotalsBar } from './TotalsBar';
|
|
36
37
|
import { StatsHeaderReadout } from './HeaderReadout';
|
|
37
38
|
import { formatAge, formatBytes, formatPercent } from './format';
|
|
38
|
-
import type {
|
|
39
|
+
import type { KillOutcome } from './kill';
|
|
40
|
+
import type { ProcessRow, StatsSnapshot } from './sampler';
|
|
39
41
|
|
|
40
42
|
function StatsPanel() {
|
|
41
43
|
const host = usePanelHost();
|
|
@@ -48,6 +50,12 @@ function StatsPanel() {
|
|
|
48
50
|
// subscriber, and the force call publishes to it, so reading the RPC's own
|
|
49
51
|
// reply would put a second copy of the same snapshot on screen.
|
|
50
52
|
const sample = useRpc<{ force?: boolean }, StatsSnapshot>('snapshot');
|
|
53
|
+
// The kill call and the row it is aimed at. A refusal comes back as a RESULT
|
|
54
|
+
// (the server never throws for one), so the sentence belongs in the dialog
|
|
55
|
+
// rather than in a toast that can vanish while the reader looks away.
|
|
56
|
+
const kill = useRpc<{ pid: number }, KillOutcome>('kill');
|
|
57
|
+
const [killTarget, setKillTarget] = useState<ProcessRow | null>(null);
|
|
58
|
+
const [killError, setKillError] = useState<string | null>(null);
|
|
51
59
|
const [now, setNow] = useState(() => Date.now());
|
|
52
60
|
|
|
53
61
|
// Arm the server's sampler while this panel is on screen, and disarm it on
|
|
@@ -76,6 +84,26 @@ function StatsPanel() {
|
|
|
76
84
|
// in-flight flag — the RPC call's own `pending` is the honest spinner.
|
|
77
85
|
const refreshing = sample.pending;
|
|
78
86
|
|
|
87
|
+
/** Run the confirmed kill, then take a sample so the row disappears. */
|
|
88
|
+
async function confirmKill(): Promise<void> {
|
|
89
|
+
if (!killTarget) return;
|
|
90
|
+
const outcome = await kill.call({ pid: killTarget.pid });
|
|
91
|
+
if (!outcome.ok) {
|
|
92
|
+
setKillError(outcome.error.message);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const value = outcome.value as KillOutcome;
|
|
96
|
+
if (!value.killed) {
|
|
97
|
+
setKillError(value.reason);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
setKillTarget(null);
|
|
101
|
+
setKillError(null);
|
|
102
|
+
// The row is still in the snapshot the table is drawing; a forced sample
|
|
103
|
+
// publishes the table without it instead of leaving a dead pid on screen.
|
|
104
|
+
void sample.call({ force: true });
|
|
105
|
+
}
|
|
106
|
+
|
|
79
107
|
// The arm attempt is also the LIVENESS probe: a plugin whose server half is
|
|
80
108
|
// not loaded answers this route with a 404, which the kit reports as
|
|
81
109
|
// `plugin_not_loaded`. That is the state a plugin installed into a running
|
|
@@ -120,12 +148,18 @@ function StatsPanel() {
|
|
|
120
148
|
|
|
121
149
|
{history ? (
|
|
122
150
|
<div class="flex flex-col gap-1.5 border-b border-ink/10 px-3 py-2">
|
|
123
|
-
<Sparkline values={history.
|
|
151
|
+
<Sparkline values={history.memory} label={snapshot.memorySource === 'rss' ? 'rss' : 'mem'} tone="text-info" format={formatBytes} />
|
|
124
152
|
<Sparkline values={history.cpuPercent} label="cpu" tone="text-warning" format={(value) => formatPercent(value)} />
|
|
125
153
|
</div>
|
|
126
154
|
) : null}
|
|
127
155
|
|
|
128
|
-
<ProcessTable
|
|
156
|
+
<ProcessTable
|
|
157
|
+
snapshot={snapshot}
|
|
158
|
+
onRequestKill={(row) => {
|
|
159
|
+
setKillError(null);
|
|
160
|
+
setKillTarget(row);
|
|
161
|
+
}}
|
|
162
|
+
/>
|
|
129
163
|
|
|
130
164
|
<div class="flex flex-col gap-2 px-3 py-3 border-t border-ink/10">
|
|
131
165
|
<div class="flex items-center gap-2">
|
|
@@ -162,9 +196,22 @@ function StatsPanel() {
|
|
|
162
196
|
) : null}
|
|
163
197
|
|
|
164
198
|
<span class="text-[10px] font-mono text-ink/35">
|
|
165
|
-
{formatBytes(snapshot.total.
|
|
199
|
+
{formatBytes(snapshot.total.memory)} across {snapshot.total.processes} processes
|
|
166
200
|
</span>
|
|
167
201
|
</div>
|
|
202
|
+
|
|
203
|
+
{killTarget ? (
|
|
204
|
+
<KillConfirm
|
|
205
|
+
row={killTarget}
|
|
206
|
+
pending={kill.pending}
|
|
207
|
+
error={killError}
|
|
208
|
+
onCancel={() => {
|
|
209
|
+
setKillTarget(null);
|
|
210
|
+
setKillError(null);
|
|
211
|
+
}}
|
|
212
|
+
onConfirm={() => void confirmKill()}
|
|
213
|
+
/>
|
|
214
|
+
) : null}
|
|
168
215
|
</div>
|
|
169
216
|
</Panel>
|
|
170
217
|
);
|
|
@@ -21,7 +21,7 @@ import type { ProcessInfo } from './proc/types';
|
|
|
21
21
|
const SERVER_PID = 100;
|
|
22
22
|
|
|
23
23
|
function proc(pid: number, ppid: number, argv: string[] | null): ProcessInfo {
|
|
24
|
-
return { pid, ppid, rss: 1024, cpuNs: 0, threads: 1, argv, cwd: null, startedAt: 1 };
|
|
24
|
+
return { pid, ppid, rss: 1024, footprint: null, cpuNs: 0, threads: 1, argv, cwd: null, startedAt: 1 };
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
function daemon(name: string, pid: number, brokerPid: number | null, state = 'ready'): DaemonEntry {
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The kill rules. Each refusal here is a way a panel button could destroy
|
|
8
|
+
* something the user did not point at, so the tests are about the refusals
|
|
9
|
+
* more than about the happy path:
|
|
10
|
+
*
|
|
11
|
+
* - `0` and `-1` are process-group / machine-wide signals to `kill(2)`, and a
|
|
12
|
+
* JSON body can carry either;
|
|
13
|
+
* - the server that HOSTS this panel is a row in the table, so its own pid has
|
|
14
|
+
* to be refused by name rather than by absence;
|
|
15
|
+
* - a pid read off a stale table may have been recycled, so membership is
|
|
16
|
+
* checked against a fresh sample, and a signal that is never called is the
|
|
17
|
+
* proof.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { describe, expect, test } from 'bun:test';
|
|
21
|
+
|
|
22
|
+
import { killStackProcess } from './kill';
|
|
23
|
+
import type { ProcessRow, StatsSnapshot } from './snapshot';
|
|
24
|
+
|
|
25
|
+
const SERVER_PID = 100;
|
|
26
|
+
|
|
27
|
+
function row(pid: number, title = `process ${pid}`): ProcessRow {
|
|
28
|
+
return {
|
|
29
|
+
pid,
|
|
30
|
+
ppid: pid === SERVER_PID ? 1 : SERVER_PID,
|
|
31
|
+
title,
|
|
32
|
+
detail: 'detail',
|
|
33
|
+
groupKey: 'session',
|
|
34
|
+
depth: pid === SERVER_PID ? 0 : 1,
|
|
35
|
+
memory: 1024,
|
|
36
|
+
memorySource: 'footprint',
|
|
37
|
+
rss: 2048,
|
|
38
|
+
cpuPercent: null,
|
|
39
|
+
threads: 1,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function snapshot(pids: number[]): StatsSnapshot {
|
|
44
|
+
const rows = pids.map((pid) => row(pid));
|
|
45
|
+
return {
|
|
46
|
+
sampledAt: 0,
|
|
47
|
+
probe: { name: 'fake', supported: true },
|
|
48
|
+
rows,
|
|
49
|
+
groups: [],
|
|
50
|
+
total: { processes: rows.length, memory: 1024 * rows.length, cpuPercent: 0 },
|
|
51
|
+
memorySource: 'footprint',
|
|
52
|
+
machine: { totalMemBytes: 1, freeMemBytes: 1, cpuCount: 1, loadPerCore: 0 },
|
|
53
|
+
daemons: [],
|
|
54
|
+
serverPid: SERVER_PID,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Deps whose `signal` records instead of killing, so a test cannot hurt the runner. */
|
|
59
|
+
function deps(pids: number[], signal?: (pid: number, sig: 'SIGTERM') => void) {
|
|
60
|
+
const calls: Array<{ pid: number; signal: string }> = [];
|
|
61
|
+
return {
|
|
62
|
+
calls,
|
|
63
|
+
value: {
|
|
64
|
+
sample: () => snapshot(pids),
|
|
65
|
+
serverPid: SERVER_PID,
|
|
66
|
+
signal: signal ?? ((pid: number, sig: 'SIGTERM') => calls.push({ pid, signal: sig })),
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
describe('killStackProcess', () => {
|
|
72
|
+
test('signals a pid the fresh sample measured', () => {
|
|
73
|
+
const { calls, value } = deps([SERVER_PID, 101]);
|
|
74
|
+
expect(killStackProcess(101, value)).toEqual({ killed: true, pid: 101, title: 'process 101', signal: 'SIGTERM' });
|
|
75
|
+
expect(calls).toEqual([{ pid: 101, signal: 'SIGTERM' }]);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('refuses the process group (0), the machine (-1) and init (1)', () => {
|
|
79
|
+
for (const pid of [0, -1, 1]) {
|
|
80
|
+
const { calls, value } = deps([SERVER_PID, 101]);
|
|
81
|
+
const outcome = killStackProcess(pid, value);
|
|
82
|
+
expect(outcome.killed).toBe(false);
|
|
83
|
+
expect(calls).toHaveLength(0);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('refuses a non-integer or non-number pid', () => {
|
|
88
|
+
for (const pid of [1.5, '101', null, undefined, { pid: 101 }]) {
|
|
89
|
+
const { calls, value } = deps([SERVER_PID, 101]);
|
|
90
|
+
expect(killStackProcess(pid, value).killed).toBe(false);
|
|
91
|
+
expect(calls).toHaveLength(0);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('refuses the Kabmo server even though it is a row in the table', () => {
|
|
96
|
+
const { calls, value } = deps([SERVER_PID, 101]);
|
|
97
|
+
const outcome = killStackProcess(SERVER_PID, value);
|
|
98
|
+
expect(outcome.killed).toBe(false);
|
|
99
|
+
expect(outcome.killed === false && outcome.reason).toContain('kabmo stop');
|
|
100
|
+
expect(calls).toHaveLength(0);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('refuses a pid outside the measured union — a stale row may be recycled', () => {
|
|
104
|
+
const { calls, value } = deps([SERVER_PID, 101]);
|
|
105
|
+
const outcome = killStackProcess(999, value);
|
|
106
|
+
expect(outcome.killed).toBe(false);
|
|
107
|
+
expect(calls).toHaveLength(0);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('an already-exited pid is a refusal, not a thrown error', () => {
|
|
111
|
+
const { value } = deps([SERVER_PID, 101], () => {
|
|
112
|
+
const error = new Error('kill ESRCH') as NodeJS.ErrnoException;
|
|
113
|
+
error.code = 'ESRCH';
|
|
114
|
+
throw error;
|
|
115
|
+
});
|
|
116
|
+
const outcome = killStackProcess(101, value);
|
|
117
|
+
expect(outcome.killed).toBe(false);
|
|
118
|
+
expect(outcome.killed === false && outcome.reason).toContain('already exited');
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('a process owned by another user says so', () => {
|
|
122
|
+
const { value } = deps([SERVER_PID, 101], () => {
|
|
123
|
+
const error = new Error('kill EPERM') as NodeJS.ErrnoException;
|
|
124
|
+
error.code = 'EPERM';
|
|
125
|
+
throw error;
|
|
126
|
+
});
|
|
127
|
+
const outcome = killStackProcess(101, value);
|
|
128
|
+
expect(outcome.killed).toBe(false);
|
|
129
|
+
expect(outcome.killed === false && outcome.reason).toContain('another user');
|
|
130
|
+
});
|
|
131
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Stopping one process from the panel — the rules, kept out of the RPC
|
|
8
|
+
* registration so they can be tested without a host around them.
|
|
9
|
+
*
|
|
10
|
+
* A kill button is the one control in this panel that can destroy work, so
|
|
11
|
+
* every refusal below is a thing that must not happen rather than an edge case:
|
|
12
|
+
*
|
|
13
|
+
* - **`pid > 1` and an integer.** `process.kill(0, …)` signals the CALLER's
|
|
14
|
+
* process group and `-1` signals every process the user may signal. A row
|
|
15
|
+
* can carry neither, and a JSON body can carry anything.
|
|
16
|
+
* - **The Kabmo's own pid is refused.** This panel's server half runs INSIDE
|
|
17
|
+
* the server it measures, so a kill row for it would take the UI, every live
|
|
18
|
+
* session and the sampler down together — and the CLI already owns stopping
|
|
19
|
+
* the server (`kabmo stop`).
|
|
20
|
+
* - **The pid must be in the union a FRESH sample measured.** The table on
|
|
21
|
+
* screen is up to a sampling interval old, and a pid recycled in between
|
|
22
|
+
* belongs to a process the user never looked at. The union is also the whole
|
|
23
|
+
* authority: a pid outside it is not something this panel offers to stop.
|
|
24
|
+
*
|
|
25
|
+
* `SIGTERM`, not `SIGKILL`: omp children flush their transcript on the polite
|
|
26
|
+
* signal, and a process that ignores it should be visible as still running
|
|
27
|
+
* rather than silently destroyed. Pressing again re-sends.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import type { StatsSnapshot } from './snapshot';
|
|
31
|
+
|
|
32
|
+
/** What the panel is told after asking for a kill. */
|
|
33
|
+
export type KillOutcome =
|
|
34
|
+
| { killed: true; pid: number; title: string; signal: 'SIGTERM' }
|
|
35
|
+
| { killed: false; reason: string };
|
|
36
|
+
|
|
37
|
+
export interface KillDeps {
|
|
38
|
+
/** A fresh sample; its rows are the only pids this may signal. */
|
|
39
|
+
sample: () => StatsSnapshot;
|
|
40
|
+
/** The Kabmo's own pid. */
|
|
41
|
+
serverPid: number;
|
|
42
|
+
/** The signalling call, injected so a test never kills anything. */
|
|
43
|
+
signal?: (pid: number, signal: 'SIGTERM') => void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Signal one process in the measured stack, or explain why not.
|
|
48
|
+
*
|
|
49
|
+
* Never throws: every failure is an outcome the panel renders in its dialog.
|
|
50
|
+
*/
|
|
51
|
+
export function killStackProcess(pid: unknown, deps: KillDeps): KillOutcome {
|
|
52
|
+
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 1) {
|
|
53
|
+
return { killed: false, reason: 'That request did not name a process id above 1.' };
|
|
54
|
+
}
|
|
55
|
+
if (pid === deps.serverPid) {
|
|
56
|
+
return { killed: false, reason: 'Refusing to stop the Kabmo server from its own panel — that is `kabmo stop`.' };
|
|
57
|
+
}
|
|
58
|
+
const row = deps.sample().rows.find((candidate) => candidate.pid === pid);
|
|
59
|
+
if (!row) {
|
|
60
|
+
return {
|
|
61
|
+
killed: false,
|
|
62
|
+
reason: `pid ${pid} is not part of the stack this panel measures — the table may be stale, so refresh and try again.`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
(deps.signal ?? ((target, signal) => process.kill(target, signal)))(pid, 'SIGTERM');
|
|
67
|
+
} catch (error) {
|
|
68
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
69
|
+
if (code === 'ESRCH') return { killed: false, reason: `pid ${pid} already exited.` };
|
|
70
|
+
if (code === 'EPERM') return { killed: false, reason: `pid ${pid} belongs to another user, so it cannot be signalled.` };
|
|
71
|
+
return { killed: false, reason: error instanceof Error ? error.message : String(error) };
|
|
72
|
+
}
|
|
73
|
+
return { killed: true, pid, title: row.title, signal: 'SIGTERM' };
|
|
74
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The machine reading — `os.freemem()` is not "memory available" on macOS.
|
|
8
|
+
*
|
|
9
|
+
* Measured on this host while 5.60 GB was actually available: `os.freemem()`
|
|
10
|
+
* and `Pages free` both read 1.05 GB, because the runtime counts only free
|
|
11
|
+
* pages and ignores the 4.53 GB of inactive ones the kernel hands out again
|
|
12
|
+
* without swapping. A panel that shows the stack's usage against 1 GB while
|
|
13
|
+
* 5.6 GB is available tells the reader the machine is full when it is not.
|
|
14
|
+
*
|
|
15
|
+
* The parsers are pinned here; the spawn (`vm_stat`, 8.8 ms) is not exercised,
|
|
16
|
+
* because a test that spawns a platform tool is a test that skips on the
|
|
17
|
+
* platform CI runs it on.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { describe, expect, test } from 'bun:test';
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
|
|
23
|
+
import { freeMemBytes, freeMemBytesFromMeminfo, freeMemBytesFromVmStat } from './machine';
|
|
24
|
+
|
|
25
|
+
const VM_STAT = `Mach Virtual Memory Statistics: (page size of 16384 bytes)
|
|
26
|
+
Pages free: 68590.
|
|
27
|
+
Pages active: 286755.
|
|
28
|
+
Pages inactive: 296680.
|
|
29
|
+
Pages speculative: 2081.
|
|
30
|
+
Pages throttled: 0.
|
|
31
|
+
Pages wired down: 63387.
|
|
32
|
+
Pages purgeable: 7201.
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
describe('freeMemBytesFromVmStat', () => {
|
|
36
|
+
test('counts free + inactive + speculative, at the reported page size', () => {
|
|
37
|
+
expect(freeMemBytesFromVmStat(VM_STAT)).toBe((68590 + 296680 + 2081) * 16384);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('reads the page size from the header, not a constant', () => {
|
|
41
|
+
// Intel Macs report 4096; assuming Apple silicon's 16384 would be 4x off.
|
|
42
|
+
const intel = VM_STAT.replace('page size of 16384 bytes', 'page size of 4096 bytes');
|
|
43
|
+
expect(freeMemBytesFromVmStat(intel)).toBe((68590 + 296680 + 2081) * 4096);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('a report with no page size is unusable rather than zero', () => {
|
|
47
|
+
expect(freeMemBytesFromVmStat('Mach Virtual Memory Statistics:')).toBeNull();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('a report with counters but no usable page is unusable too', () => {
|
|
51
|
+
expect(freeMemBytesFromVmStat('page size of 16384 bytes\nPages active: 10.')).toBeNull();
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe('freeMemBytesFromMeminfo', () => {
|
|
56
|
+
test('reads MemAvailable, not MemFree', () => {
|
|
57
|
+
const meminfo = `MemTotal: 16000000 kB
|
|
58
|
+
MemFree: 1000000 kB
|
|
59
|
+
MemAvailable: 8123456 kB
|
|
60
|
+
`;
|
|
61
|
+
expect(freeMemBytesFromMeminfo(meminfo)).toBe(8_123_456 * 1024);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('a kernel without MemAvailable answers null, never MemFree', () => {
|
|
65
|
+
// Pre-3.14 kernels have no MemAvailable. Falling back to MemFree would
|
|
66
|
+
// understate the same way `os.freemem()` does on macOS, under another name.
|
|
67
|
+
expect(freeMemBytesFromMeminfo('MemFree: 1000000 kB\n')).toBeNull();
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('freeMemBytes', () => {
|
|
72
|
+
test('answers a plausible figure for this host', () => {
|
|
73
|
+
const bytes = freeMemBytes(Date.now() + 60_000);
|
|
74
|
+
expect(bytes).toBeGreaterThan(0);
|
|
75
|
+
expect(bytes).toBeLessThanOrEqual(Number(os.totalmem()));
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The machine's own numbers: total and AVAILABLE memory, cores, load.
|
|
8
|
+
*
|
|
9
|
+
* `os.freemem()` is the wrong answer on macOS, and it was the wrong answer for
|
|
10
|
+
* this panel: it reports `Pages free` alone. Measured on this host while the
|
|
11
|
+
* system had 5.60 GB available:
|
|
12
|
+
*
|
|
13
|
+
* ```
|
|
14
|
+
* os.freemem() 1.05 GB
|
|
15
|
+
* Pages free 1.04 GB
|
|
16
|
+
* Pages inactive 4.53 GB
|
|
17
|
+
* Pages speculative 0.03 GB
|
|
18
|
+
* free + inactive + speculative 5.60 GB
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* Inactive and speculative pages are memory the kernel hands out again without
|
|
22
|
+
* touching swap, so a reader comparing the stack's usage against the 1 GB
|
|
23
|
+
* denominator concludes the machine is nearly full when it is not. "Available"
|
|
24
|
+
* here is `free + inactive + speculative`; `Pages purgeable` is deliberately
|
|
25
|
+
* NOT added, because it is already counted in the inactive total.
|
|
26
|
+
*
|
|
27
|
+
* Linux needs no new source: `/proc/meminfo`'s `MemAvailable` is the kernel's
|
|
28
|
+
* own estimate of what a new allocation can get without swapping, which is a
|
|
29
|
+
* better figure than `MemFree` for exactly the same reason.
|
|
30
|
+
*
|
|
31
|
+
* Windows keeps `os.freemem()`: it reports the same "Available" figure the
|
|
32
|
+
* task manager does.
|
|
33
|
+
*
|
|
34
|
+
* `vm_stat` costs 8.8 ms measured (a spawn), while a sample lands every
|
|
35
|
+
* second, so the reading is cached for `FREE_MEMORY_TTL_MS`. Free memory moves
|
|
36
|
+
* on the scale of seconds, not ticks; the panel's own totals are re-read every
|
|
37
|
+
* sample regardless.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import { readFileSync } from 'node:fs';
|
|
41
|
+
import os from 'node:os';
|
|
42
|
+
|
|
43
|
+
import type { MachineContext } from './snapshot';
|
|
44
|
+
|
|
45
|
+
/** How long a free-memory reading is reused. */
|
|
46
|
+
export const FREE_MEMORY_TTL_MS = 5_000;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `free + inactive + speculative`, from `vm_stat`.
|
|
50
|
+
*
|
|
51
|
+
* The page size is taken from the report's own header (`page size of 16384
|
|
52
|
+
* bytes` on Apple silicon, 4096 on Intel) rather than assumed: a page count
|
|
53
|
+
* read against the wrong size is silently off by 4x.
|
|
54
|
+
*/
|
|
55
|
+
export function freeMemBytesFromVmStat(output: string): number | null {
|
|
56
|
+
const pageSize = Number(/page size of (\d+) bytes/.exec(output)?.[1] ?? 0);
|
|
57
|
+
if (!Number.isFinite(pageSize) || pageSize <= 0) return null;
|
|
58
|
+
const pages = (label: string): number => {
|
|
59
|
+
const match = new RegExp(`^${label}:\\s+(\\d+)\\.?$`, 'm').exec(output);
|
|
60
|
+
return match ? Number(match[1]) : 0;
|
|
61
|
+
};
|
|
62
|
+
const free = pages('Pages free');
|
|
63
|
+
const inactive = pages('Pages inactive');
|
|
64
|
+
const speculative = pages('Pages speculative');
|
|
65
|
+
if (free === 0 && inactive === 0 && speculative === 0) return null;
|
|
66
|
+
return (free + inactive + speculative) * pageSize;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** `MemAvailable: 12345 kB` from `/proc/meminfo`, in bytes. */
|
|
70
|
+
export function freeMemBytesFromMeminfo(text: string): number | null {
|
|
71
|
+
const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(text);
|
|
72
|
+
return match ? Number(match[1]) * 1024 : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let cached: { at: number; bytes: number } | null = null;
|
|
76
|
+
|
|
77
|
+
/** Available memory on this host, in bytes. Cached; never throws. */
|
|
78
|
+
export function freeMemBytes(now = Date.now()): number {
|
|
79
|
+
if (cached && now - cached.at < FREE_MEMORY_TTL_MS) return cached.bytes;
|
|
80
|
+
let bytes: number | null = null;
|
|
81
|
+
if (process.platform === 'darwin') {
|
|
82
|
+
try {
|
|
83
|
+
bytes = freeMemBytesFromVmStat(Bun.spawnSync(['vm_stat']).stdout.toString());
|
|
84
|
+
} catch {
|
|
85
|
+
// No `vm_stat` on this host: the runtime's own number is the fallback.
|
|
86
|
+
bytes = null;
|
|
87
|
+
}
|
|
88
|
+
} else if (process.platform === 'linux') {
|
|
89
|
+
try {
|
|
90
|
+
bytes = freeMemBytesFromMeminfo(readFileSync('/proc/meminfo', 'utf8'));
|
|
91
|
+
} catch {
|
|
92
|
+
bytes = null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const answer = bytes ?? Number(os.freemem());
|
|
96
|
+
cached = { at: now, bytes: answer };
|
|
97
|
+
return answer;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Everything the panel reports about the machine itself. */
|
|
101
|
+
export function readMachine(): MachineContext {
|
|
102
|
+
const cpuCount = os.cpus().length;
|
|
103
|
+
const load = os.loadavg()[0];
|
|
104
|
+
return {
|
|
105
|
+
totalMemBytes: Number(os.totalmem()),
|
|
106
|
+
freeMemBytes: freeMemBytes(),
|
|
107
|
+
cpuCount,
|
|
108
|
+
loadPerCore: cpuCount > 0 ? load / cpuCount : load,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Drop the cached reading. For tests; the panel never needs it. */
|
|
113
|
+
export function clearMachineCache(): void {
|
|
114
|
+
cached = null;
|
|
115
|
+
}
|
|
@@ -40,6 +40,7 @@ import type { ProcProbe, ProcessInfo } from './types';
|
|
|
40
40
|
const LIBPROC_SYMBOLS = {
|
|
41
41
|
proc_listpids: { args: [FFIType.u32, FFIType.u32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
|
|
42
42
|
proc_pidinfo: { args: [FFIType.i32, FFIType.i32, FFIType.u64, FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
|
|
43
|
+
proc_pid_rusage: { args: [FFIType.i32, FFIType.i32, FFIType.ptr], returns: FFIType.i32 },
|
|
43
44
|
} satisfies Record<string, FFIFunction>;
|
|
44
45
|
|
|
45
46
|
const LIBC_SYMBOLS = {
|
|
@@ -76,6 +77,15 @@ const TASKINFO_SYSTEM_OFFSET = 24;
|
|
|
76
77
|
const TASKINFO_THREADS_OFFSET = 84;
|
|
77
78
|
/** `PROC_PIDVNODEPATHINFO`, and `pvi_cdir.vip_path` inside its reply. */
|
|
78
79
|
const PROC_PIDVNODEPATHINFO = 9;
|
|
80
|
+
/** `RUSAGE_INFO_V4` — the flavor whose struct carries `ri_phys_footprint`. */
|
|
81
|
+
const RUSAGE_INFO_V4 = 4;
|
|
82
|
+
/**
|
|
83
|
+
* `ri_phys_footprint` inside `struct rusage_info_v4`: 16 bytes of uuid, then
|
|
84
|
+
* seven u64 fields (user/system time, wakeups, pageins, wired, resident).
|
|
85
|
+
* Verified on this host against `footprint -p`: the same pid read
|
|
86
|
+
* 134,252,248 bytes here and `Footprint: 128 MB` there.
|
|
87
|
+
*/
|
|
88
|
+
const RUSAGE_FOOTPRINT_OFFSET = 72;
|
|
79
89
|
/**
|
|
80
90
|
* `sizeof(struct proc_vnodepathinfo)` — TWO `vnode_info_path`s (the cwd and the
|
|
81
91
|
* root dir), so 2 × (152 + 1024) = 2352. A buffer of one `vnode_info_path` is
|
|
@@ -146,6 +156,10 @@ const argvView = new DataView(argvBuffer.buffer);
|
|
|
146
156
|
const argvMib = new Int32Array([CTL_KERN, KERN_PROCARGS2, 0]);
|
|
147
157
|
const argvSize = new BigUint64Array([BigInt(ARGV_BUFFER_BYTES)]);
|
|
148
158
|
const cwdBuffer = new Uint8Array(VNODE_PATH_BYTES);
|
|
159
|
+
/** `struct rusage_info_v4` is ~300 bytes; the kernel writes the flavor's own
|
|
160
|
+
* size, so a generous buffer is the safe read. */
|
|
161
|
+
const rusageBuffer = new Uint8Array(1024);
|
|
162
|
+
const rusageView = new DataView(rusageBuffer.buffer);
|
|
149
163
|
const decoder = new TextDecoder();
|
|
150
164
|
|
|
151
165
|
/** Every pid on the system, via the documented two-call sizing pattern. */
|
|
@@ -208,6 +222,29 @@ function usageOf(bound: DarwinLibs, pid: number): { rss: number; cpuNs: number;
|
|
|
208
222
|
};
|
|
209
223
|
}
|
|
210
224
|
|
|
225
|
+
/**
|
|
226
|
+
* `ri_phys_footprint` for one pid, or null.
|
|
227
|
+
*
|
|
228
|
+
* This is the number `footprint -p` prints and `vmmap` calls "Physical
|
|
229
|
+
* footprint" — what the OS actually charges the process, after Bun (or any
|
|
230
|
+
* other allocator) frees an arena it does not return. Verified on this host
|
|
231
|
+
* against the live server: this call read 134,252,248 bytes while `footprint`
|
|
232
|
+
* printed `128 MB`, and `pti_resident_size` read 317 MB for the same process.
|
|
233
|
+
*
|
|
234
|
+
* A note for whoever reads the old doc first: `proc_pid_rusage` is not a decoy
|
|
235
|
+
* for footprint — it is a decoy for RESIDENT, whose field here is the one at
|
|
236
|
+
* offset 64 (`ri_resident_size`). The earlier measurement that dismissed the
|
|
237
|
+
* call read its first u64s, which are CPU times.
|
|
238
|
+
*
|
|
239
|
+
* A pid owned by another user, or one that exited mid-sweep, answers non-zero
|
|
240
|
+
* and yields null; the sampler then falls back to RSS for that row.
|
|
241
|
+
*/
|
|
242
|
+
function footprintOf(bound: DarwinLibs, pid: number): number | null {
|
|
243
|
+
if (bound.libproc.symbols.proc_pid_rusage(pid, RUSAGE_INFO_V4, ptr(rusageBuffer)) !== 0) return null;
|
|
244
|
+
const bytes = Number(rusageView.getBigUint64(RUSAGE_FOOTPRINT_OFFSET, true));
|
|
245
|
+
return bytes > 0 ? bytes : null;
|
|
246
|
+
}
|
|
247
|
+
|
|
211
248
|
/**
|
|
212
249
|
* argv for one pid, or null.
|
|
213
250
|
*
|
|
@@ -256,6 +293,7 @@ export const darwinProbe: ProcProbe = {
|
|
|
256
293
|
pid,
|
|
257
294
|
ppid: parent?.ppid ?? 0,
|
|
258
295
|
rss: usage.rss,
|
|
296
|
+
footprint: footprintOf(bound, pid),
|
|
259
297
|
cpuNs: usage.cpuNs,
|
|
260
298
|
threads: usage.threads,
|
|
261
299
|
argv: argvOf(bound, pid),
|
|
@@ -174,6 +174,10 @@ export const linuxProbe: ProcProbe = {
|
|
|
174
174
|
pid,
|
|
175
175
|
ppid: stat.ppid,
|
|
176
176
|
rss: status.rss,
|
|
177
|
+
// No Linux analogue at this budget: `Pss` would mean a
|
|
178
|
+
// `/proc/<pid>/smaps_rollup` read per process per tick, and Linux RSS
|
|
179
|
+
// does not carry macOS's freed-arena gap. The sampler falls back.
|
|
180
|
+
footprint: null,
|
|
177
181
|
cpuNs: stat.cpuNs,
|
|
178
182
|
threads: status.threads,
|
|
179
183
|
argv: argvOf(pid),
|
|
@@ -105,6 +105,7 @@ export const psProbe: ProcProbe = {
|
|
|
105
105
|
ppid: Number(match[2]),
|
|
106
106
|
// `ps rss` is kB on every platform this runs on.
|
|
107
107
|
rss: Number(match[3]) * 1024,
|
|
108
|
+
footprint: null,
|
|
108
109
|
cpuNs: cpuNs ?? 0,
|
|
109
110
|
threads: 0,
|
|
110
111
|
argv: match[6].trim() ? [match[6].trim()] : null,
|
|
@@ -28,6 +28,17 @@ export interface ProcessInfo {
|
|
|
28
28
|
ppid: number;
|
|
29
29
|
/** Resident set size in bytes. */
|
|
30
30
|
rss: number;
|
|
31
|
+
/**
|
|
32
|
+
* The operating system's charge for this process, in bytes, or null.
|
|
33
|
+
*
|
|
34
|
+
* Not the same quantity as `rss`: on macOS a Bun process that has read and
|
|
35
|
+
* dropped a transcript keeps the freed pages resident, so RSS read 317 MB for
|
|
36
|
+
* a process whose physical footprint was 134 MB (measured on the live server
|
|
37
|
+
* with `proc_pid_rusage(RUSAGE_INFO_V4).ri_phys_footprint` against
|
|
38
|
+
* `footprint -p`). Linux has no such gap at this scale, so its probe answers
|
|
39
|
+
* null and the sampler falls back to RSS there.
|
|
40
|
+
*/
|
|
41
|
+
footprint: number | null;
|
|
31
42
|
/** Cumulative CPU time (user + system) in nanoseconds. */
|
|
32
43
|
cpuNs: number;
|
|
33
44
|
/** Thread count, 0 when the platform cannot report it. */
|