@myrialabs/clopen 0.4.34 → 0.4.36

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 (125) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/auth/permissions.ts +7 -0
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  20. package/backend/database/migrations/index.ts +7 -0
  21. package/backend/database/queries/index.ts +1 -0
  22. package/backend/database/queries/session-queries.ts +50 -11
  23. package/backend/database/queries/worktree-queries.ts +148 -0
  24. package/backend/engine/adapters/opencode/server.ts +389 -83
  25. package/backend/engine/adapters/opencode/stream.ts +14 -14
  26. package/backend/engine/hot-reload.ts +25 -10
  27. package/backend/files/file-watcher.test.ts +105 -0
  28. package/backend/files/file-watcher.ts +80 -10
  29. package/backend/git/git-service.test.ts +33 -0
  30. package/backend/git/git-service.ts +7 -3
  31. package/backend/git/nested-repos.test.ts +292 -1
  32. package/backend/git/nested-repos.ts +330 -17
  33. package/backend/host/metrics.test.ts +110 -0
  34. package/backend/host/metrics.ts +235 -0
  35. package/backend/{ports → host}/runner.ts +19 -10
  36. package/backend/index.ts +16 -4
  37. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  38. package/backend/ports/attribute.test.ts +3 -2
  39. package/backend/ports/attribute.ts +6 -45
  40. package/backend/ports/kill.ts +1 -1
  41. package/backend/ports/monitor.ts +1 -1
  42. package/backend/ports/processes.ts +1 -1
  43. package/backend/ports/scan-host.ts +77 -8
  44. package/backend/ports/scan.test.ts +1 -1
  45. package/backend/ports/scan.ts +1 -1
  46. package/backend/ports/ssh-lineage.ts +1 -1
  47. package/backend/preview/browser/browser-pool.ts +81 -0
  48. package/backend/preview/browser/browser-preview-service.ts +142 -32
  49. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  50. package/backend/preview/browser/browser-video-capture.ts +84 -31
  51. package/backend/preview/browser/types.ts +9 -0
  52. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  53. package/backend/projects/project-cleanup.ts +7 -1
  54. package/backend/projects/shell-ownership.ts +65 -0
  55. package/backend/snapshot/snapshot-service.ts +6 -2
  56. package/backend/terminal/ptykit.ts +35 -6
  57. package/backend/utils/ws.ts +21 -1
  58. package/backend/worktrees/clone.ts +222 -0
  59. package/backend/worktrees/index.ts +29 -0
  60. package/backend/worktrees/merge.test.ts +93 -0
  61. package/backend/worktrees/merge.ts +232 -0
  62. package/backend/worktrees/paths.test.ts +60 -0
  63. package/backend/worktrees/paths.ts +60 -0
  64. package/backend/worktrees/resolve.ts +67 -0
  65. package/backend/worktrees/service.ts +315 -0
  66. package/backend/worktrees/tree.ts +59 -0
  67. package/backend/ws/access.ts +18 -0
  68. package/backend/ws/artifacts/generate.ts +2 -2
  69. package/backend/ws/chat/stream.ts +9 -2
  70. package/backend/ws/containers/actions.ts +156 -0
  71. package/backend/ws/containers/index.ts +43 -0
  72. package/backend/ws/containers/list.ts +146 -0
  73. package/backend/ws/containers/logs.ts +43 -0
  74. package/backend/ws/containers/tunnel.ts +101 -0
  75. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  76. package/backend/ws/files/path-access.test.ts +93 -1
  77. package/backend/ws/files/path-access.ts +54 -5
  78. package/backend/ws/files/read.ts +15 -10
  79. package/backend/ws/files/search.ts +7 -7
  80. package/backend/ws/files/state.ts +70 -8
  81. package/backend/ws/files/watch.ts +16 -14
  82. package/backend/ws/git/branch-name.ts +3 -3
  83. package/backend/ws/git/branch.ts +15 -15
  84. package/backend/ws/git/commit-message.ts +3 -3
  85. package/backend/ws/git/commit.ts +17 -17
  86. package/backend/ws/git/conflict.ts +10 -10
  87. package/backend/ws/git/diff.ts +9 -9
  88. package/backend/ws/git/ignored.ts +9 -9
  89. package/backend/ws/git/log.ts +6 -4
  90. package/backend/ws/git/remote.ts +43 -43
  91. package/backend/ws/git/staging.ts +16 -16
  92. package/backend/ws/git/status.ts +47 -37
  93. package/backend/ws/index.ts +6 -0
  94. package/backend/ws/message-rate-limiter.test.ts +45 -0
  95. package/backend/ws/message-rate-limiter.ts +34 -3
  96. package/backend/ws/preview/access.ts +11 -3
  97. package/backend/ws/projects/index.ts +5 -1
  98. package/backend/ws/projects/info.test.ts +54 -0
  99. package/backend/ws/projects/info.ts +398 -0
  100. package/backend/ws/sessions/crud.ts +21 -6
  101. package/backend/ws/snapshot/restore.ts +11 -14
  102. package/backend/ws/ssh/connections.ts +8 -0
  103. package/backend/ws/system/device-info.ts +70 -96
  104. package/backend/ws/worktrees/crud.ts +187 -0
  105. package/backend/ws/worktrees/index.ts +33 -0
  106. package/backend/ws/worktrees/transfer.ts +88 -0
  107. package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
  108. package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
  109. package/dist/assets/main-9G7IpQpK.css +1 -0
  110. package/dist/assets/main-BofFsH8E.js +1085 -0
  111. package/dist/index.html +2 -2
  112. package/dist/manifest.json +9 -2
  113. package/package.json +1 -1
  114. package/shared/types/containers/container.ts +366 -0
  115. package/shared/types/containers/index.ts +5 -0
  116. package/shared/types/database/schema.ts +26 -0
  117. package/shared/types/host/index.ts +18 -0
  118. package/shared/types/ports/port.ts +47 -9
  119. package/shared/utils/logger.ts +3 -0
  120. package/shared/utils/workspace-scope.test.ts +80 -0
  121. package/shared/utils/workspace-scope.ts +57 -0
  122. package/shared/utils/ws-client.ts +92 -17
  123. package/shared/utils/ws-server.ts +83 -16
  124. package/dist/assets/main-CYCMEbXB.css +0 -1
  125. package/dist/assets/main-ZCojSzvW.js +0 -1060
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Materialization must be IDEMPOTENT on disk, not just in outcome.
3
+ *
4
+ * `materializeArtifacts` runs at every stream start. It used to rewrite each
5
+ * enabled artifact unconditionally, which left the content identical but moved
6
+ * the file's mtime — and the Open Code pool fingerprints exactly these files to
7
+ * decide whether its baked config changed. The result was a brand-new
8
+ * `opencode serve` process for every single turn. These tests pin the property
9
+ * that prevents it: no content change, no write.
10
+ */
11
+
12
+ import { describe, expect, test, afterAll } from 'bun:test';
13
+ import { rm, stat, readFile } from 'node:fs/promises';
14
+ import { join } from 'node:path';
15
+
16
+ import { materializeArtifacts } from './sync';
17
+ import { resolveArtifact } from './matrix';
18
+ import type { ArtifactContext } from './types';
19
+
20
+ const CONTEXT: ArtifactContext = { engine: 'opencode', scope: 'global' };
21
+ const SLUG = 'sync-idempotence-fixture';
22
+
23
+ const targetDir = resolveArtifact('command', CONTEXT).locateEffective(CONTEXT);
24
+ const targetFile = targetDir ? join(targetDir, `${SLUG}.md`) : '';
25
+
26
+ /** Materialize a single command whose body is `document`. */
27
+ async function materialize(document: string): Promise<void> {
28
+ await materializeArtifacts('command', CONTEXT, {
29
+ enabled: [{ slug: SLUG, name: 'Fixture', description: 'sync test', document }],
30
+ managedSlugs: [SLUG]
31
+ });
32
+ }
33
+
34
+ afterAll(async () => {
35
+ if (targetFile) await rm(targetFile, { force: true });
36
+ });
37
+
38
+ describe('materializeArtifacts', () => {
39
+ test('an unchanged artifact is not rewritten', async () => {
40
+ expect(targetDir).toBeTruthy();
41
+
42
+ await materialize('# Fixture\n\noriginal body\n');
43
+ const firstWrite = (await stat(targetFile)).mtimeMs;
44
+
45
+ // Space the calls out: two writes inside the same millisecond would pass
46
+ // this assertion even if the file had genuinely been rewritten.
47
+ await Bun.sleep(20);
48
+ await materialize('# Fixture\n\noriginal body\n');
49
+
50
+ expect((await stat(targetFile)).mtimeMs).toBe(firstWrite);
51
+ });
52
+
53
+ test('a changed artifact is written', async () => {
54
+ await materialize('# Fixture\n\noriginal body\n');
55
+ const firstWrite = (await stat(targetFile)).mtimeMs;
56
+
57
+ await Bun.sleep(20);
58
+ await materialize('# Fixture\n\nedited body\n');
59
+
60
+ expect((await stat(targetFile)).mtimeMs).toBeGreaterThan(firstWrite);
61
+ expect(await readFile(targetFile, 'utf8')).toContain('edited body');
62
+ });
63
+ });
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import { join } from 'path';
13
- import { mkdir, readdir, rm, writeFile, cp, stat } from 'node:fs/promises';
13
+ import { mkdir, readdir, readFile, rm, writeFile, cp, stat } from 'node:fs/promises';
14
14
  import { resolveArtifact } from './matrix';
15
15
  import { markersFor, writeManagedBlock } from './markers';
16
16
  import type { ArtifactContext, ArtifactType, ManagedArtifact } from './types';
@@ -37,10 +37,63 @@ async function pathExists(path: string): Promise<boolean> {
37
37
  }
38
38
  }
39
39
 
40
- /** Mirror one canonical folder into a destination dir under `<slug>/` (replacing any stale copy). */
40
+ /**
41
+ * Write only when the bytes differ.
42
+ *
43
+ * This runs at every stream start, and a no-op rewrite still moves mtime. The
44
+ * Open Code pool fingerprints these files to decide whether its baked config
45
+ * changed, so an unconditional write made every single turn spawn a fresh
46
+ * `opencode serve` process for a config that was byte-identical.
47
+ */
48
+ async function writeFileIfChanged(filePath: string, content: string): Promise<void> {
49
+ try {
50
+ if ((await readFile(filePath, 'utf8')) === content) return;
51
+ } catch { /* missing or unreadable — fall through and write */ }
52
+ await writeFile(filePath, content, 'utf8');
53
+ }
54
+
55
+ /** Every file under `dir`, keyed by path relative to it. Missing dir → empty map. */
56
+ async function fileStats(dir: string): Promise<Map<string, { size: number; mtimeMs: number }>> {
57
+ const out = new Map<string, { size: number; mtimeMs: number }>();
58
+ const walk = async (current: string, prefix: string): Promise<void> => {
59
+ let entries;
60
+ try {
61
+ entries = await readdir(current, { withFileTypes: true });
62
+ } catch {
63
+ return;
64
+ }
65
+ for (const entry of entries) {
66
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
67
+ if (entry.isDirectory()) {
68
+ await walk(join(current, entry.name), relative);
69
+ continue;
70
+ }
71
+ try {
72
+ const info = await stat(join(current, entry.name));
73
+ out.set(relative, { size: info.size, mtimeMs: info.mtimeMs });
74
+ } catch { /* raced away */ }
75
+ }
76
+ };
77
+ await walk(dir, '');
78
+ return out;
79
+ }
80
+
81
+ /** True when `destDir` already holds a current copy — same files, same sizes, none of them older than the source. */
82
+ async function folderInSync(sourceDir: string, destDir: string): Promise<boolean> {
83
+ const [source, dest] = await Promise.all([fileStats(sourceDir), fileStats(destDir)]);
84
+ if (source.size === 0 || source.size !== dest.size) return false;
85
+ for (const [relative, sourceInfo] of source) {
86
+ const destInfo = dest.get(relative);
87
+ if (!destInfo || destInfo.size !== sourceInfo.size || destInfo.mtimeMs < sourceInfo.mtimeMs) return false;
88
+ }
89
+ return true;
90
+ }
91
+
92
+ /** Mirror one canonical folder into a destination dir under `<slug>/`, skipping the copy when it is already current. */
41
93
  async function mirrorFolder(sourceDir: string, destDir: string, slug: string): Promise<void> {
42
94
  if (!(await pathExists(sourceDir))) return;
43
95
  const dest = join(destDir, slug);
96
+ if (await folderInSync(sourceDir, dest)) return;
44
97
  await rm(dest, { recursive: true, force: true });
45
98
  await mkdir(destDir, { recursive: true });
46
99
  await cp(sourceDir, dest, { recursive: true });
@@ -104,7 +157,7 @@ export async function materializeArtifacts(
104
157
  if (resolution.format === 'folder-md') {
105
158
  if (item.sourceDir) await mirrorFolder(item.sourceDir, target, item.slug);
106
159
  } else if (item.document != null) {
107
- await writeFile(join(target, `${item.slug}.md`), item.document, 'utf8');
160
+ await writeFileIfChanged(join(target, `${item.slug}.md`), item.document);
108
161
  }
109
162
  }
110
163
 
@@ -46,6 +46,13 @@ export const ADMIN_ONLY_ROUTES = new Set([
46
46
  // Port manager — anyone signed in may see what is listening, but ending a
47
47
  // process can take down another member's work, so stopping is admin-only.
48
48
  'ports:kill',
49
+ // Containers — anyone signed in may see what is running, but starting or
50
+ // stopping one takes down whatever it serves for everyone else. Opening a
51
+ // shell inside a container is gated separately, in the PtyKit authorize.
52
+ 'containers:action',
53
+ 'containers:remove',
54
+ 'containers:prune',
55
+ 'containers:prune-dismiss',
49
56
  // Stack — binary installation is an admin-only operation.
50
57
  'stack:status',
51
58
  'stack:status-all',
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Containers — starting, stopping, removing, and clearing up after.
3
+ *
4
+ * Every action addresses a container or an image by its full id, and a volume
5
+ * or a network by its name, and every one of those is checked against a
6
+ * pattern before it reaches a command line. Names arrive over a socket, and an
7
+ * argument that begins with a dash is a flag; `assertContainerId` and
8
+ * `assertResourceName` are the gate that stops one becoming the other. Nothing
9
+ * here ever runs through `sudo`: an account that may not talk to the runtime is
10
+ * told so.
11
+ */
12
+
13
+ import type {
14
+ ContainerAction,
15
+ ContainerActionResult,
16
+ ContainerDetail,
17
+ ContainerResourceKind,
18
+ ContainerRuntime,
19
+ ContainerStats,
20
+ PruneKind,
21
+ PruneOutcome
22
+ } from '$shared/types/containers';
23
+ import { CONTAINER_TIMEOUTS } from '$shared/types/containers';
24
+ import { containerMonitor } from './monitor';
25
+ import { invalidateDiskUsage } from './disk-usage';
26
+ import { containerArgv, detectRuntime, firstProblem, tryRun } from './runtime';
27
+ import { parseInspect, parsePruneOutput, parseStats } from './parse';
28
+ import { debug } from '$shared/utils/logger';
29
+
30
+ /** Both runtimes identify a container or an image with hex. */
31
+ const CONTAINER_ID = /^[a-f0-9]{12,64}$/i;
32
+ /** An image id may carry the digest algorithm that produced it. */
33
+ const IMAGE_ID = /^(sha256:)?[a-f0-9]{12,64}$/i;
34
+ /**
35
+ * The character set both runtimes allow in a volume or network name. Anchored
36
+ * at both ends and required to start with an alphanumeric, so nothing that
37
+ * could be read as a flag or a path ever gets through.
38
+ */
39
+ const RESOURCE_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/;
40
+
41
+ export function isContainerId(value: string): boolean {
42
+ return CONTAINER_ID.test(value);
43
+ }
44
+
45
+ export function assertContainerId(value: string): string {
46
+ if (!isContainerId(value)) throw new Error('That is not a container id.');
47
+ return value;
48
+ }
49
+
50
+ /** Validate whatever identifies a resource of this kind, or refuse it. */
51
+ export function assertResourceId(kind: ContainerResourceKind, value: string): string {
52
+ const ok =
53
+ kind === 'container'
54
+ ? CONTAINER_ID.test(value)
55
+ : kind === 'image'
56
+ ? IMAGE_ID.test(value)
57
+ : RESOURCE_NAME.test(value);
58
+ if (!ok) throw new Error(`That is not a ${kind} Clopen can address.`);
59
+ return value;
60
+ }
61
+
62
+
63
+ /** The argv for each action, which is where `remove` stops being one word. */
64
+ function actionArgv(action: ContainerAction, containerId: string): string[] {
65
+ switch (action) {
66
+ case 'remove':
67
+ return ['rm', containerId];
68
+ case 'force-remove':
69
+ // The runtime stops it first. Offered separately from `remove` so the
70
+ // confirmation can say that outright rather than surprising anyone.
71
+ return ['rm', '--force', containerId];
72
+ default:
73
+ return [action, containerId];
74
+ }
75
+ }
76
+
77
+ export async function runContainerAction(
78
+ hostId: string,
79
+ containerId: string,
80
+ action: ContainerAction
81
+ ): Promise<ContainerActionResult> {
82
+ assertContainerId(containerId);
83
+
84
+ const result = await containerMonitor.withHost(hostId, async (runner, platform) => {
85
+ const info = await detectRuntime(hostId, runner, platform);
86
+ if (info.problem !== 'none' || !info.runtime) {
87
+ return { ok: false, error: 'This host has no container runtime available right now.' };
88
+ }
89
+
90
+ const outcome = await tryRun(
91
+ runner,
92
+ containerArgv(info.runtime, platform, actionArgv(action, containerId)),
93
+ CONTAINER_TIMEOUTS.action
94
+ );
95
+ if (outcome.code === 0) return { ok: true, error: null };
96
+
97
+ const reason = firstProblem(outcome.stderr, outcome.stdout, outcome.code);
98
+ debug.warn('containers', `${action} failed for ${containerId} on ${hostId}: ${reason}`);
99
+ return { ok: false, error: reason };
100
+ });
101
+
102
+ // The table is a second or two old at most, but an action is the one moment
103
+ // a user expects it to be instant.
104
+ containerMonitor.invalidate(hostId);
105
+ // Starting and stopping do not move the disk figures enough to be worth
106
+ // re-measuring for; removing a container does.
107
+ if (action === 'remove' || action === 'force-remove') invalidateDiskUsage(hostId);
108
+ return result;
109
+ }
110
+
111
+ /** The argv that removes one resource of each kind. */
112
+ function removeArgv(kind: ContainerResourceKind, id: string, force: boolean): string[] {
113
+ switch (kind) {
114
+ case 'container':
115
+ return force ? ['rm', '--force', id] : ['rm', id];
116
+ case 'image':
117
+ return force ? ['image', 'rm', '--force', id] : ['image', 'rm', id];
118
+ case 'volume':
119
+ return force ? ['volume', 'rm', '--force', id] : ['volume', 'rm', id];
120
+ case 'network':
121
+ return ['network', 'rm', id];
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Remove one image, volume or network.
127
+ *
128
+ * Deliberately not forgiving: the runtime refuses to remove anything still in
129
+ * use, and that refusal is passed straight through rather than being retried
130
+ * with `--force`. A volume a running container has mounted is not a volume the
131
+ * user meant to delete, whatever the button said.
132
+ */
133
+ export async function removeResource(
134
+ hostId: string,
135
+ kind: ContainerResourceKind,
136
+ id: string,
137
+ force = false
138
+ ): Promise<ContainerActionResult> {
139
+ assertResourceId(kind, id);
140
+
141
+ const result = await containerMonitor.withHost(hostId, async (runner, platform) => {
142
+ const info = await detectRuntime(hostId, runner, platform);
143
+ if (info.problem !== 'none' || !info.runtime) {
144
+ return { ok: false, error: 'This host has no container runtime available right now.' };
145
+ }
146
+
147
+ const outcome = await tryRun(
148
+ runner,
149
+ containerArgv(info.runtime, platform, removeArgv(kind, id, force)),
150
+ CONTAINER_TIMEOUTS.action
151
+ );
152
+ if (outcome.code === 0) return { ok: true, error: null };
153
+
154
+ const reason = firstProblem(outcome.stderr, outcome.stdout, outcome.code);
155
+ debug.warn('containers', `could not remove ${kind} ${id} on ${hostId}: ${reason}`);
156
+ return { ok: false, error: reason };
157
+ });
158
+
159
+ containerMonitor.invalidate(hostId);
160
+ invalidateDiskUsage(hostId);
161
+ return result;
162
+ }
163
+
164
+ /**
165
+ * The argv for a sweep.
166
+ *
167
+ * `volumes` is the one place the two runtimes had to be reconciled rather than
168
+ * passed through. Podman's `volume prune` removes every unused volume; Docker's
169
+ * removes only the anonymous ones unless it is given `--all`, which older
170
+ * Docker does not have. So Docker is asked with `--all` and falls back without
171
+ * it, and both runtimes end up meaning the same thing — which is what the
172
+ * confirmation says they mean.
173
+ */
174
+ function pruneArgv(kind: PruneKind, runtime: ContainerRuntime): string[] {
175
+ switch (kind) {
176
+ case 'containers':
177
+ return ['container', 'prune', '--force'];
178
+ case 'dangling-images':
179
+ return ['image', 'prune', '--force'];
180
+ case 'images':
181
+ return ['image', 'prune', '--all', '--force'];
182
+ case 'volumes':
183
+ return runtime === 'docker'
184
+ ? ['volume', 'prune', '--all', '--force']
185
+ : ['volume', 'prune', '--force'];
186
+ case 'networks':
187
+ return ['network', 'prune', '--force'];
188
+ case 'build-cache':
189
+ return ['builder', 'prune', '--force'];
190
+ }
191
+ }
192
+
193
+ /** True when a command failed because the runtime is too old for a flag. */
194
+ function unknownFlag(stderr: string): boolean {
195
+ return /unknown flag|unknown shorthand|flag provided but not defined|unrecognized option/i.test(
196
+ stderr
197
+ );
198
+ }
199
+
200
+ /**
201
+ * Run a set of sweeps, one after another.
202
+ *
203
+ * Sequential rather than parallel: both runtimes serialise this work behind
204
+ * their own lock anyway, and on an SSH host every one of these is a command on
205
+ * a shared connection. A failure in one kind does not stop the rest — a host
206
+ * with no build cache should not cost the user their volume sweep.
207
+ */
208
+ export async function pruneResources(hostId: string, kinds: PruneKind[]): Promise<PruneOutcome[]> {
209
+ const outcomes = await containerMonitor.withHost(hostId, async (runner, platform) => {
210
+ const info = await detectRuntime(hostId, runner, platform);
211
+ if (info.problem !== 'none' || !info.runtime) {
212
+ return kinds.map((kind) => ({
213
+ kind,
214
+ ok: false,
215
+ removed: 0,
216
+ reclaimed: null,
217
+ error: 'This host has no container runtime available right now.'
218
+ }));
219
+ }
220
+ const runtime = info.runtime;
221
+
222
+ const results: PruneOutcome[] = [];
223
+ for (const kind of kinds) {
224
+ let outcome = await tryRun(
225
+ runner,
226
+ containerArgv(runtime, platform, pruneArgv(kind, runtime)),
227
+ CONTAINER_TIMEOUTS.prune
228
+ );
229
+
230
+ // Docker before 23 has no `volume prune --all`, and removed every unused
231
+ // volume without it. Dropping the flag there keeps the meaning identical.
232
+ if (outcome.code !== 0 && kind === 'volumes' && unknownFlag(outcome.stderr)) {
233
+ outcome = await tryRun(
234
+ runner,
235
+ containerArgv(runtime, platform, ['volume', 'prune', '--force']),
236
+ CONTAINER_TIMEOUTS.prune
237
+ );
238
+ }
239
+
240
+ if (outcome.code !== 0) {
241
+ const error = firstProblem(outcome.stderr, outcome.stdout, outcome.code);
242
+ debug.warn('containers', `prune ${kind} failed on ${hostId}: ${error}`);
243
+ results.push({ kind, ok: false, removed: 0, reclaimed: null, error });
244
+ continue;
245
+ }
246
+
247
+ const { removed, reclaimed } = parsePruneOutput(outcome.stdout);
248
+ results.push({ kind, ok: true, removed, reclaimed, error: null });
249
+ }
250
+ return results;
251
+ });
252
+
253
+ containerMonitor.invalidate(hostId);
254
+ // A sweep is exactly when these numbers move, and showing the figures it was
255
+ // meant to fix would read as the sweep having done nothing.
256
+ invalidateDiskUsage(hostId);
257
+ return outcomes;
258
+ }
259
+
260
+ /**
261
+ * One sample of what a container is consuming, read when asked for.
262
+ *
263
+ * Not polled and not part of the listing: `stats` samples over a window and
264
+ * takes a second or more even with `--no-stream`, which is fine for a question
265
+ * someone asked and far too expensive for a table that ticks.
266
+ */
267
+ export async function readStats(hostId: string, containerId: string): Promise<ContainerStats | null> {
268
+ assertContainerId(containerId);
269
+
270
+ return containerMonitor.withHost(hostId, async (runner, platform) => {
271
+ const info = await detectRuntime(hostId, runner, platform);
272
+ if (info.problem !== 'none' || !info.runtime) return null;
273
+
274
+ const result = await tryRun(
275
+ runner,
276
+ containerArgv(info.runtime, platform, [
277
+ 'stats',
278
+ '--no-stream',
279
+ '--format',
280
+ info.runtime === 'docker' ? '{{json .}}' : 'json',
281
+ containerId
282
+ ]),
283
+ CONTAINER_TIMEOUTS.stats
284
+ );
285
+ if (result.code !== 0) {
286
+ debug.log('containers', `stats failed for ${containerId}:`, result.stderr);
287
+ return null;
288
+ }
289
+ return parseStats(result.stdout);
290
+ });
291
+ }
292
+
293
+ /** Everything `inspect` knows, read only when a detail pane asks for it. */
294
+ export async function inspectContainer(
295
+ hostId: string,
296
+ containerId: string
297
+ ): Promise<ContainerDetail | null> {
298
+ assertContainerId(containerId);
299
+
300
+ return containerMonitor.withHost(hostId, async (runner, platform) => {
301
+ const info = await detectRuntime(hostId, runner, platform);
302
+ if (info.problem !== 'none' || !info.runtime) return null;
303
+
304
+ const result = await tryRun(
305
+ runner,
306
+ containerArgv(info.runtime, platform, ['inspect', '--format', '{{json .}}', containerId]),
307
+ CONTAINER_TIMEOUTS.inspect
308
+ );
309
+ if (result.code !== 0) {
310
+ debug.log('containers', `inspect failed for ${containerId}:`, result.stderr);
311
+ return null;
312
+ }
313
+ return parseInspect(result.stdout);
314
+ });
315
+ }
316
+
@@ -0,0 +1,68 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { isDiskUsageStale } from './disk-usage';
3
+ import {
4
+ CONTAINER_TIMEOUTS,
5
+ DISK_USAGE_STALE_MS,
6
+ TRANSPORT_GRACE_MS,
7
+ type ContainerDiskUsage
8
+ } from '$shared/types/containers';
9
+
10
+ const NOW = Date.parse('2026-09-01T12:00:00.000Z');
11
+
12
+ function reading(measuredAt: string | null): ContainerDiskUsage {
13
+ return { rows: [], error: null, measuredAt };
14
+ }
15
+
16
+ describe('isDiskUsageStale', () => {
17
+ test('a reading taken just now is still good', () => {
18
+ expect(isDiskUsageStale(reading(new Date(NOW - 1_000).toISOString()), NOW)).toBe(false);
19
+ });
20
+
21
+ test('a reading goes stale once it passes the window', () => {
22
+ const justInside = new Date(NOW - DISK_USAGE_STALE_MS + 1_000).toISOString();
23
+ const justOutside = new Date(NOW - DISK_USAGE_STALE_MS - 1_000).toISOString();
24
+ expect(isDiskUsageStale(reading(justInside), NOW)).toBe(false);
25
+ expect(isDiskUsageStale(reading(justOutside), NOW)).toBe(true);
26
+ });
27
+
28
+ test('having no reading at all is stale', () => {
29
+ expect(isDiskUsageStale(null, NOW)).toBe(true);
30
+ });
31
+
32
+ test('a reading that did not say when it was taken is stale', () => {
33
+ // Rather than being treated as current, which would pin a number that
34
+ // nothing would ever replace.
35
+ expect(isDiskUsageStale(reading(null), NOW)).toBe(true);
36
+ expect(isDiskUsageStale(reading('not a date'), NOW)).toBe(true);
37
+ });
38
+
39
+ test('a reading stamped in the future is not treated as stale', () => {
40
+ // A host whose clock runs ahead should not make the panel re-measure on
41
+ // every open — the invalidation after a prune is what keeps it honest.
42
+ expect(isDiskUsageStale(reading(new Date(NOW + 60_000).toISOString()), NOW)).toBe(false);
43
+ });
44
+ });
45
+
46
+ describe('command budgets', () => {
47
+ // The bug this guards against: the transport gave up at 30s while the backend
48
+ // was still allowed 300s for a prune, so a sweep that was still deleting came
49
+ // back as six failures and the user was invited to run it again.
50
+ test('every command budget leaves room for the transport to outlast it', () => {
51
+ for (const [name, budget] of Object.entries(CONTAINER_TIMEOUTS)) {
52
+ expect(budget + TRANSPORT_GRACE_MS, `${name} must outlast its command`).toBeGreaterThan(
53
+ budget
54
+ );
55
+ }
56
+ });
57
+
58
+ test('a full scan is allowed more than any single listing it runs', () => {
59
+ expect(CONTAINER_TIMEOUTS.scan).toBeGreaterThan(CONTAINER_TIMEOUTS.list);
60
+ });
61
+
62
+ test('a prune is allowed the longest, because it walks what it deletes', () => {
63
+ const others = Object.entries(CONTAINER_TIMEOUTS)
64
+ .filter(([name]) => name !== 'prune')
65
+ .map(([, budget]) => budget);
66
+ expect(CONTAINER_TIMEOUTS.prune).toBeGreaterThan(Math.max(...others));
67
+ });
68
+ });