@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,91 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { ContainerScanResult } from '$shared/types/containers';
3
+ import { addressesOverlap, containerPortIndex, noteContainerScan } from './port-index';
4
+ import { parseDockerPs } from './parse';
5
+
6
+ function scanOf(listing: string, hostId: string): ContainerScanResult {
7
+ return {
8
+ hostId,
9
+ scannedAt: '2026-08-25T02:02:11.000Z',
10
+ runtime: 'docker',
11
+ runtimeVersion: '27.0.0',
12
+ runtimeProblem: 'none',
13
+ entries: parseDockerPs(listing, hostId),
14
+ images: [],
15
+ volumes: [],
16
+ networks: [],
17
+ limitations: [],
18
+ error: null
19
+ };
20
+ }
21
+
22
+ describe('the index the port table reads', () => {
23
+ const listing = [
24
+ JSON.stringify({
25
+ ID: 'a1b2c3d4e5f60718293a4b5c6d7e8f9012345678901234567890abcdefabcdef',
26
+ Names: 'shop-api-1',
27
+ Image: 'shop/api:2.1',
28
+ State: 'running',
29
+ Status: 'Up 3 hours',
30
+ Ports: '0.0.0.0:8080->80/tcp, :::8080->80/tcp, 9000/tcp'
31
+ }),
32
+ JSON.stringify({
33
+ ID: 'bb22cc33dd44ee55ff6600112233445566778899aabbccddeeff001122334455',
34
+ Names: 'shop-db-1',
35
+ Image: 'postgres:16',
36
+ State: 'exited',
37
+ Status: 'Exited (0) 4 minutes ago',
38
+ Ports: '0.0.0.0:5432->5432/tcp'
39
+ })
40
+ ].join('\n');
41
+
42
+ // The index is process-wide state keyed by host, so each test uses its own.
43
+ noteContainerScan(scanOf(listing, 'index-test'));
44
+ const index = containerPortIndex('index-test');
45
+
46
+ test('maps a published port to the container that publishes it', () => {
47
+ expect(index.get('tcp:8080')?.ref).toMatchObject({
48
+ name: 'shop-api-1',
49
+ image: 'shop/api:2.1',
50
+ containerPort: 80,
51
+ runtime: 'docker'
52
+ });
53
+ });
54
+
55
+ test('carries the address the mapping was published on', () => {
56
+ // One address, not two: the IPv6 twin Docker prints for every published
57
+ // port was already folded into its IPv4 partner when the row was parsed,
58
+ // because they are one mapping to anyone reading the table.
59
+ expect(index.get('tcp:8080')?.addresses).toEqual(['0.0.0.0']);
60
+ });
61
+
62
+ test('ignores a port that is exposed but not published — it holds nothing', () => {
63
+ expect(index.has('tcp:9000')).toBe(false);
64
+ });
65
+
66
+ test('ignores a stopped container, which is holding no host port at all', () => {
67
+ expect(index.has('tcp:5432')).toBe(false);
68
+ });
69
+
70
+ test('reports an empty index for a host that has never been scanned', () => {
71
+ expect(containerPortIndex('never-scanned').size).toBe(0);
72
+ });
73
+ });
74
+
75
+ describe('addressesOverlap', () => {
76
+ test('a wildcard on either side matches anything', () => {
77
+ expect(addressesOverlap(['*'], ['127.0.0.1'])).toBe(true);
78
+ expect(addressesOverlap(['192.168.1.5'], ['0.0.0.0'])).toBe(true);
79
+ expect(addressesOverlap(['::1', '127.0.0.1'], ['::'])).toBe(true);
80
+ });
81
+
82
+ test('a shared address matches', () => {
83
+ expect(addressesOverlap(['127.0.0.1', '::1'], ['127.0.0.1'])).toBe(true);
84
+ });
85
+
86
+ test('two disjoint addresses do not', () => {
87
+ // A container published on loopback must not claim an unrelated process
88
+ // holding the same port on a LAN address.
89
+ expect(addressesOverlap(['192.168.1.5'], ['127.0.0.1'])).toBe(false);
90
+ });
91
+ });
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Containers — what the port table needs to know about them.
3
+ *
4
+ * A published container port is the one case where the process holding a socket
5
+ * is not the thing a user means. On Linux the listener is `docker-proxy`; with
6
+ * the userland proxy disabled there is no listening socket at all and the port
7
+ * is reached through a firewall rule, so the port scan cannot see it however
8
+ * hard it looks. Either way the answer is the container, and only the runtime
9
+ * can give it.
10
+ *
11
+ * So the port scan reads this index — and refreshes it through the transport it
12
+ * already holds open for that host, rather than making the container monitor
13
+ * open a second SSH lease for a host nobody is watching. The read is
14
+ * deliberately synchronous and may be a few seconds stale: a port table that
15
+ * ticks every second must never wait on a `docker ps`, and a mapping that
16
+ * appears one tick late is invisible next to one that made the whole table
17
+ * stutter.
18
+ */
19
+
20
+ import type { ContainerScanResult } from '$shared/types/containers';
21
+ import type { PortContainerRef } from '$shared/types/ports';
22
+ import type { CommandRunner, ProbePlatform } from '../host/runner';
23
+ import { containerArgv, detectRuntime, tryRun } from './runtime';
24
+ import { parseDockerPs, parsePodmanPs } from './parse';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ /** How stale the index may get before a port scan asks for a refresh. */
28
+ const TTL_MS = 5_000;
29
+
30
+ /**
31
+ * One published port, as the port table needs it: who publishes it, and on
32
+ * which addresses — the second half matters because a mapping with no listening
33
+ * socket has no row to borrow an address from.
34
+ */
35
+ export interface ContainerPortMapping {
36
+ ref: PortContainerRef;
37
+ addresses: string[];
38
+ }
39
+
40
+ /** Keyed `protocol:hostPort`. */
41
+ export type ContainerPortIndex = Map<string, ContainerPortMapping>;
42
+
43
+ interface HostIndex {
44
+ index: ContainerPortIndex;
45
+ readAt: number;
46
+ refreshing: boolean;
47
+ }
48
+
49
+ const hosts = new Map<string, HostIndex>();
50
+
51
+ function buildIndex(result: ContainerScanResult): ContainerPortIndex {
52
+ const index: ContainerPortIndex = new Map();
53
+ if (!result.runtime) return index;
54
+
55
+ for (const entry of result.entries) {
56
+ // Only a running container holds a host port. A stopped one still lists
57
+ // its mappings, and claiming those would blame it for someone else's port.
58
+ if (entry.state !== 'running' && entry.state !== 'paused') continue;
59
+
60
+ for (const binding of entry.ports) {
61
+ if (binding.hostPort === null) continue;
62
+ const key = `${binding.protocol}:${binding.hostPort}`;
63
+ const address = binding.hostAddress || '*';
64
+
65
+ // The same mapping arrives once per address family; the second one adds
66
+ // an address to the first rather than becoming a second row.
67
+ const existing = index.get(key);
68
+ if (existing) {
69
+ if (!existing.addresses.includes(address)) existing.addresses.push(address);
70
+ continue;
71
+ }
72
+
73
+ index.set(key, {
74
+ ref: {
75
+ runtime: result.runtime,
76
+ id: entry.id,
77
+ shortId: entry.shortId,
78
+ name: entry.name,
79
+ image: entry.image,
80
+ containerPort: binding.containerPort
81
+ },
82
+ addresses: [address]
83
+ });
84
+ }
85
+ }
86
+
87
+ return index;
88
+ }
89
+
90
+ /**
91
+ * Feed a full container scan into the index.
92
+ *
93
+ * Called by the container monitor for every scan it runs, so a host whose
94
+ * Containers panel is open never pays for a second listing to keep its ports
95
+ * annotated.
96
+ */
97
+ export function noteContainerScan(result: ContainerScanResult, now = Date.now()): void {
98
+ hosts.set(result.hostId, {
99
+ index: buildIndex(result),
100
+ readAt: now,
101
+ refreshing: hosts.get(result.hostId)?.refreshing ?? false
102
+ });
103
+ }
104
+
105
+ /** The mappings last seen on a host, keyed `protocol:hostPort`. */
106
+ export function containerPortIndex(hostId: string): ContainerPortIndex {
107
+ return hosts.get(hostId)?.index ?? new Map();
108
+ }
109
+
110
+ /**
111
+ * Refresh a host's index in the background, using the caller's own transport.
112
+ *
113
+ * Costs nothing on a host with no runtime: `detectRuntime` remembers that
114
+ * answer, so this returns before running anything.
115
+ */
116
+ export function refreshContainerPortIndex(
117
+ hostId: string,
118
+ runner: CommandRunner,
119
+ platform: ProbePlatform,
120
+ now = Date.now()
121
+ ): void {
122
+ const existing = hosts.get(hostId);
123
+ if (existing?.refreshing) return;
124
+ if (existing && now - existing.readAt < TTL_MS) return;
125
+
126
+ const state: HostIndex = existing ?? { index: new Map(), readAt: 0, refreshing: false };
127
+ state.refreshing = true;
128
+ hosts.set(hostId, state);
129
+
130
+ void (async () => {
131
+ try {
132
+ const info = await detectRuntime(hostId, runner, platform, now);
133
+ if (info.problem !== 'none' || !info.runtime) {
134
+ state.index = new Map();
135
+ return;
136
+ }
137
+
138
+ // Running containers only: the index exists to explain live ports.
139
+ const listing = await tryRun(
140
+ runner,
141
+ containerArgv(info.runtime, platform, [
142
+ 'ps',
143
+ '--no-trunc',
144
+ '--format',
145
+ info.runtime === 'docker' ? '{{json .}}' : 'json'
146
+ ]),
147
+ 15_000
148
+ );
149
+ if (listing.code !== 0) return;
150
+
151
+ const entries =
152
+ info.runtime === 'docker'
153
+ ? parseDockerPs(listing.stdout, hostId)
154
+ : parsePodmanPs(listing.stdout, hostId);
155
+
156
+ state.index = buildIndex({
157
+ hostId,
158
+ scannedAt: new Date(now).toISOString(),
159
+ runtime: info.runtime,
160
+ runtimeVersion: info.version,
161
+ runtimeProblem: 'none',
162
+ entries,
163
+ images: [],
164
+ volumes: [],
165
+ networks: [],
166
+ limitations: [],
167
+ error: null
168
+ });
169
+ } catch (error) {
170
+ debug.log('containers', `could not refresh the port index for ${hostId}:`, error);
171
+ } finally {
172
+ state.readAt = Date.now();
173
+ state.refreshing = false;
174
+ }
175
+ })();
176
+ }
177
+
178
+ /**
179
+ * Whether a socket's addresses and a mapping's could be the same thing.
180
+ *
181
+ * Almost always they are: a published port and its proxy socket cannot both
182
+ * exist on a host without being the same path to the same container, because
183
+ * the second bind would fail. The exception is narrow and real — a container
184
+ * published on loopback while an unrelated process holds the same port on a LAN
185
+ * address — and claiming that process for the container would be a confident
186
+ * lie. A wildcard on either side overlaps everything, which is the common case.
187
+ */
188
+ export function addressesOverlap(sockets: string[], mapped: string[]): boolean {
189
+ const wildcard = (address: string): boolean =>
190
+ address === '*' || address === '0.0.0.0' || address === '::' || address === '';
191
+ if (sockets.some(wildcard) || mapped.some(wildcard)) return true;
192
+ return sockets.some((address) => mapped.includes(address));
193
+ }
194
+
195
+ /** Drop a host's index when its connection goes away. */
196
+ export function forgetContainerPortIndex(hostId: string): void {
197
+ hosts.delete(hostId);
198
+ }
@@ -0,0 +1,148 @@
1
+ import { beforeEach, describe, expect, test } from 'bun:test';
2
+ import { dismissPrune, pruneJobFor, resetPruneJobs, startPrune } from './prune-job';
3
+ import type { PruneKind, PruneOutcome } from '$shared/types/containers';
4
+
5
+ const HOST = 'local';
6
+ const USER = 'user-1';
7
+
8
+ /** A sweep the test finishes by hand, so a job can be observed mid-flight. */
9
+ function deferredSweep() {
10
+ let finish: (outcomes: PruneOutcome[]) => void = () => {};
11
+ let fail: (error: Error) => void = () => {};
12
+ let calls = 0;
13
+ const sweep = (): Promise<PruneOutcome[]> => {
14
+ calls += 1;
15
+ return new Promise<PruneOutcome[]>((resolve, reject) => {
16
+ finish = resolve;
17
+ fail = reject;
18
+ });
19
+ };
20
+ return {
21
+ sweep,
22
+ get calls() {
23
+ return calls;
24
+ },
25
+ finish: (outcomes: PruneOutcome[] = []) => finish(outcomes),
26
+ fail: (error: Error) => fail(error)
27
+ };
28
+ }
29
+
30
+ /** Let the job's own `.then` chain run before asserting on what it wrote. */
31
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
32
+
33
+ const outcome = (kind: PruneKind): PruneOutcome => ({
34
+ kind,
35
+ ok: true,
36
+ removed: 3,
37
+ reclaimed: '1.2GB',
38
+ error: null
39
+ });
40
+
41
+ beforeEach(() => resetPruneJobs());
42
+
43
+ describe('startPrune', () => {
44
+ test('a started sweep is running and carries what it is sweeping', () => {
45
+ const driver = deferredSweep();
46
+ const job = startPrune(HOST, ['volumes'], USER, driver.sweep);
47
+
48
+ expect(job.hostId).toBe(HOST);
49
+ expect(job.kinds).toEqual(['volumes']);
50
+ expect(job.finishedAt).toBeNull();
51
+ expect(job.outcomes).toBeNull();
52
+ expect(driver.calls).toBe(1);
53
+ });
54
+
55
+ test('asking again while one runs returns that job and starts nothing', () => {
56
+ const driver = deferredSweep();
57
+ const first = startPrune(HOST, ['volumes'], USER, driver.sweep);
58
+ // The case this guards: a user who lost track of the first sweep. Two
59
+ // prunes racing on the same disk report two sets of half-true numbers.
60
+ const second = startPrune(HOST, ['images'], 'user-2', driver.sweep);
61
+
62
+ expect(second).toBe(first);
63
+ expect(second.kinds).toEqual(['volumes']);
64
+ expect(driver.calls).toBe(1);
65
+ });
66
+
67
+ test('a finished sweep keeps its outcomes for whoever reads next', async () => {
68
+ const driver = deferredSweep();
69
+ startPrune(HOST, ['volumes'], USER, driver.sweep);
70
+ driver.finish([outcome('volumes')]);
71
+ await settle();
72
+
73
+ const job = pruneJobFor(HOST, USER);
74
+ expect(job?.finishedAt).not.toBeNull();
75
+ expect(job?.outcomes).toEqual([outcome('volumes')]);
76
+ });
77
+
78
+ test('a sweep that throws finishes as a failure rather than staying running', async () => {
79
+ const driver = deferredSweep();
80
+ startPrune(HOST, ['volumes', 'images'], USER, driver.sweep);
81
+ driver.fail(new Error('daemon went away'));
82
+ await settle();
83
+
84
+ const job = pruneJobFor(HOST, USER);
85
+ // Left running, the host would refuse every later sweep forever.
86
+ expect(job?.finishedAt).not.toBeNull();
87
+ expect(job?.outcomes).toHaveLength(2);
88
+ expect(job?.outcomes?.every((entry) => !entry.ok)).toBe(true);
89
+ expect(job?.outcomes?.[0]?.error).toBe('daemon went away');
90
+ });
91
+
92
+ test('a new sweep may start once the last one finished', async () => {
93
+ const first = deferredSweep();
94
+ startPrune(HOST, ['volumes'], USER, first.sweep);
95
+ first.finish([outcome('volumes')]);
96
+ await settle();
97
+
98
+ const second = deferredSweep();
99
+ const job = startPrune(HOST, ['images'], USER, second.sweep);
100
+ expect(job.kinds).toEqual(['images']);
101
+ expect(job.finishedAt).toBeNull();
102
+ expect(second.calls).toBe(1);
103
+ });
104
+
105
+ test('each host sweeps independently', () => {
106
+ const local = deferredSweep();
107
+ const remote = deferredSweep();
108
+ startPrune('local', ['volumes'], USER, local.sweep);
109
+ startPrune('ssh-host', ['images'], USER, remote.sweep);
110
+
111
+ expect(pruneJobFor('local', USER)?.kinds).toEqual(['volumes']);
112
+ expect(pruneJobFor('ssh-host', USER)?.kinds).toEqual(['images']);
113
+ });
114
+ });
115
+
116
+ describe('pruneJobFor', () => {
117
+ test('a host that never swept has no job', () => {
118
+ expect(pruneJobFor(HOST, USER)).toBeNull();
119
+ });
120
+
121
+ test('a sweep started by someone else is still found', () => {
122
+ const driver = deferredSweep();
123
+ startPrune(HOST, ['volumes'], 'user-1', driver.sweep);
124
+ // The refresh-and-second-device case: whoever looks sees the real state.
125
+ expect(pruneJobFor(HOST, 'user-2')?.kinds).toEqual(['volumes']);
126
+ });
127
+ });
128
+
129
+ describe('dismissPrune', () => {
130
+ test('a finished report is forgotten once acknowledged', async () => {
131
+ const driver = deferredSweep();
132
+ startPrune(HOST, ['volumes'], USER, driver.sweep);
133
+ driver.finish([outcome('volumes')]);
134
+ await settle();
135
+
136
+ dismissPrune(HOST);
137
+ expect(pruneJobFor(HOST, USER)).toBeNull();
138
+ });
139
+
140
+ test('a running sweep is never dismissed', () => {
141
+ const driver = deferredSweep();
142
+ startPrune(HOST, ['volumes'], USER, driver.sweep);
143
+
144
+ dismissPrune(HOST);
145
+ // Forgetting it here would hand the next caller a second concurrent sweep.
146
+ expect(pruneJobFor(HOST, USER)?.finishedAt).toBeNull();
147
+ });
148
+ });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Containers — a cleanup sweep that outlives the dialog that started it.
3
+ *
4
+ * A prune is the longest thing this feature does. Sweeping a few hundred unused
5
+ * volumes is minutes of the daemon unlinking files, and nothing about closing a
6
+ * modal should change that: the runtime carries on regardless, so the only
7
+ * question is whether Clopen still knows what it is doing.
8
+ *
9
+ * Keeping that in the browser answered it badly. Component state dies with the
10
+ * modal, so a sweep that finished while it was closed left no trace; store
11
+ * state dies with a refresh, so the button came back enabled while the daemon
12
+ * was still deleting and invited a second sweep on top of the first; and
13
+ * neither was ever visible to a second device looking at the same host.
14
+ *
15
+ * So the job belongs to the host. Starting one returns the job, asking for it
16
+ * returns whatever is current, and the result is pushed to everyone attached
17
+ * when it lands. A host may only have one sweep at a time — asking again while
18
+ * one runs hands back the running job rather than starting a second.
19
+ */
20
+
21
+ import type { PruneJob, PruneKind, PruneOutcome } from '$shared/types/containers';
22
+ import { pruneResources } from './actions';
23
+ import { ws } from '../utils/ws';
24
+ import { debug } from '$shared/utils/logger';
25
+
26
+ interface HostJob {
27
+ job: PruneJob;
28
+ /** Users to push the result to, and to notify when it lands. */
29
+ attached: Set<string>;
30
+ }
31
+
32
+ const hosts = new Map<string, HostJob>();
33
+
34
+ /** True while the host's last job has not finished. */
35
+ function isRunning(entry: HostJob | undefined): boolean {
36
+ return entry !== undefined && entry.job.finishedAt === null;
37
+ }
38
+
39
+ /**
40
+ * Start a sweep, or hand back the one already running.
41
+ *
42
+ * Never starts a second sweep on a host: two prunes racing on the same disk
43
+ * produce two sets of half-true numbers, and the caller asking again is far
44
+ * more likely to have lost track of the first than to actually want another.
45
+ */
46
+ export function startPrune(
47
+ hostId: string,
48
+ kinds: PruneKind[],
49
+ userId: string,
50
+ /** The sweep itself, taken as an argument so it can be driven in a test. */
51
+ sweep: (hostId: string, kinds: PruneKind[]) => Promise<PruneOutcome[]> = pruneResources
52
+ ): PruneJob {
53
+ const existing = hosts.get(hostId);
54
+ if (isRunning(existing)) {
55
+ existing!.attached.add(userId);
56
+ return existing!.job;
57
+ }
58
+
59
+ const entry: HostJob = {
60
+ job: {
61
+ hostId,
62
+ kinds,
63
+ startedAt: new Date().toISOString(),
64
+ finishedAt: null,
65
+ outcomes: null
66
+ },
67
+ attached: new Set([userId])
68
+ };
69
+ hosts.set(hostId, entry);
70
+
71
+ void (async () => {
72
+ let outcomes;
73
+ try {
74
+ outcomes = await sweep(hostId, kinds);
75
+ } catch (error) {
76
+ debug.warn('containers', `prune failed on ${hostId}:`, error);
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ outcomes = kinds.map((kind) => ({
79
+ kind,
80
+ ok: false,
81
+ removed: 0,
82
+ reclaimed: null,
83
+ error: message
84
+ }));
85
+ }
86
+
87
+ entry.job.outcomes = outcomes;
88
+ entry.job.finishedAt = new Date().toISOString();
89
+
90
+ // Everyone who attached hears how it went, whether or not their dialog is
91
+ // still open — that is what makes closing it safe.
92
+ for (const id of entry.attached) {
93
+ ws.emit.user(id, 'containers:prune-changed', { job: entry.job });
94
+ }
95
+ })();
96
+
97
+ return entry.job;
98
+ }
99
+
100
+ /**
101
+ * The host's current sweep, or the last one whose result nobody has seen yet.
102
+ *
103
+ * Attaches the caller either way, so a dialog opened halfway through a sweep is
104
+ * told when it ends without having to poll for it.
105
+ */
106
+ export function pruneJobFor(hostId: string, userId: string): PruneJob | null {
107
+ const entry = hosts.get(hostId);
108
+ if (!entry) return null;
109
+ entry.attached.add(userId);
110
+ return entry.job;
111
+ }
112
+
113
+ /**
114
+ * Forget a finished sweep, once someone has actually read the result.
115
+ *
116
+ * Explicit rather than timed: the report is the only record of what a sweep
117
+ * removed, and dropping it on a schedule would mean a user who stepped away
118
+ * comes back to a panel that quietly pretends nothing happened. A running job
119
+ * is never dismissed — there is nothing to acknowledge yet.
120
+ */
121
+ export function dismissPrune(hostId: string): void {
122
+ const entry = hosts.get(hostId);
123
+ if (entry && !isRunning(entry)) hosts.delete(hostId);
124
+ }
125
+
126
+ /** Drop every remembered job. Only for tests, which must not share a registry. */
127
+ export function resetPruneJobs(): void {
128
+ hosts.clear();
129
+ }