@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,337 @@
1
+ /**
2
+ * Containers — a PtyKit backend whose "process" is a shell inside a container.
3
+ *
4
+ * `PtyBackend` is the seam PtyKit already uses to talk to bun-pty, and the SSH
5
+ * client has shown it will just as happily front a remote channel. A container
6
+ * shell is the third case, and the only one that has to be both: on this
7
+ * machine it is `docker exec -it` under a real pty, and on a saved SSH host it
8
+ * is the same command run through an exec channel with a pty requested. One
9
+ * backend serves both so the local and remote shells are not two features that
10
+ * drift apart — the only difference is which of the two `open` paths runs.
11
+ *
12
+ * Two things are deliberately not trusted here. The target is decoded from the
13
+ * session namespace, which the server stamps and `authorize` has already
14
+ * checked, so a client cannot name one host and open a shell on another. And
15
+ * the container is verified against a live listing before anything is spawned,
16
+ * because an id that existed when the panel rendered may since have been
17
+ * removed and reused.
18
+ */
19
+
20
+ import type {
21
+ PtyBackend,
22
+ PtyDisposable,
23
+ PtyExitEvent,
24
+ PtyProcessHandle,
25
+ PtySpawnOptions
26
+ } from '@myrialabs/ptykit/core';
27
+ import { loadBackend } from '@myrialabs/ptykit/core';
28
+ import type { ClientChannel } from 'ssh2';
29
+ import { LOCAL_HOST_ID } from '$shared/types/host';
30
+ import { containerMonitor } from './monitor';
31
+ import { containerArgv, detectRuntime } from './runtime';
32
+ import { isContainerId } from './actions';
33
+ import { detectRemotePlatform, localPlatform } from '../host/runner';
34
+ import { shellQuote } from '../ssh/connect';
35
+ import { sshClientPool, type SshLease } from '../ssh/client-pool';
36
+ import { sshConnectionQueries } from '../database/queries';
37
+ import { debug } from '$shared/utils/logger';
38
+
39
+ /**
40
+ * The `file` PtyKit passes to `spawn`. PtyKit hands `shell` through untouched,
41
+ * so this is the one per-session channel available to name the target — and the
42
+ * value is stamped server-side (never taken from the client) in
43
+ * ws/containers/tunnel.ts.
44
+ */
45
+ const TARGET_PREFIX = 'clopen-container:';
46
+
47
+ export interface ContainerTarget {
48
+ hostId: string;
49
+ containerId: string;
50
+ }
51
+
52
+ export function encodeContainerTarget(target: ContainerTarget): string {
53
+ return `${TARGET_PREFIX}${target.hostId}:${target.containerId}`;
54
+ }
55
+
56
+ function decodeContainerTarget(file: string): ContainerTarget {
57
+ if (!file.startsWith(TARGET_PREFIX)) {
58
+ throw new Error('Container shells must name a container.');
59
+ }
60
+ const rest = file.slice(TARGET_PREFIX.length);
61
+ const split = rest.lastIndexOf(':');
62
+ if (split <= 0) throw new Error('Container shells must name a container.');
63
+ return { hostId: rest.slice(0, split), containerId: rest.slice(split + 1) };
64
+ }
65
+
66
+ /**
67
+ * Pick a shell inside the container without a probe round trip.
68
+ *
69
+ * Images built on Alpine have no `bash` and images built on Debian usually do;
70
+ * asking first would cost an extra exec and still race a container that is
71
+ * shutting down. `sh` is the one binary a container image can be relied on to
72
+ * have, so it is used to choose — and then replaced, so the user's shell is the
73
+ * process, not a child of one.
74
+ */
75
+ const SHELL_PICK = 'if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi';
76
+
77
+ const ANSI_DIM = '\u001b[2m';
78
+ const ANSI_RED = '\u001b[31m';
79
+ const ANSI_RESET = '\u001b[0m';
80
+
81
+ /** Terminals expect CRLF; a lone \n leaves the cursor mid-line. */
82
+ function terminalLine(text: string): string {
83
+ return `${text.replace(/\n/g, '\r\n')}\r\n`;
84
+ }
85
+
86
+ /** Distinct per-session ids so the tab list can tell sessions apart. */
87
+ let nextSyntheticPid = 1;
88
+
89
+ class ContainerShellHandle implements PtyProcessHandle {
90
+ readonly pid: number;
91
+ cols: number;
92
+ rows: number;
93
+
94
+ private readonly dataListeners = new Set<(data: string) => void>();
95
+ private readonly exitListeners = new Set<(event: PtyExitEvent) => void>();
96
+ private readonly pendingInput: string[] = [];
97
+
98
+ /** Set on this machine: the real pty running `docker exec`. */
99
+ private local: PtyProcessHandle | null = null;
100
+ /** Set on a saved SSH host: the exec channel running the same command. */
101
+ private channel: ClientChannel | null = null;
102
+ private lease: SshLease | null = null;
103
+ private finished = false;
104
+
105
+ constructor(target: ContainerTarget, options: PtySpawnOptions) {
106
+ this.pid = nextSyntheticPid++;
107
+ this.cols = options.cols;
108
+ this.rows = options.rows;
109
+ // Deferred by one microtask on purpose: PtyKit subscribes to `onData` only
110
+ // after `spawn` returns, so anything emitted from this constructor — the
111
+ // "Attaching…" line, or an immediate failure — would go to nobody.
112
+ queueMicrotask(() => void this.open(target, options));
113
+ }
114
+
115
+ private emitData(data: string): void {
116
+ for (const listener of this.dataListeners) listener(data);
117
+ }
118
+
119
+ private finish(exitCode: number, signal?: string | number): void {
120
+ if (this.finished) return;
121
+ this.finished = true;
122
+ this.lease?.release();
123
+ this.lease = null;
124
+ for (const listener of this.exitListeners) listener({ exitCode, signal });
125
+ }
126
+
127
+ private fail(message: string, exitCode = 1): void {
128
+ this.emitData(terminalLine(`${ANSI_RED}${message}${ANSI_RESET}`));
129
+ this.finish(exitCode);
130
+ }
131
+
132
+ private async open(target: ContainerTarget, options: PtySpawnOptions): Promise<void> {
133
+ if (!isContainerId(target.containerId)) {
134
+ this.fail('That is not a container id.');
135
+ return;
136
+ }
137
+
138
+ let container;
139
+ try {
140
+ container = await containerMonitor.findContainer(target.hostId, target.containerId);
141
+ } catch (error) {
142
+ this.fail(error instanceof Error ? error.message : String(error));
143
+ return;
144
+ }
145
+ if (!container) {
146
+ this.fail('That container no longer exists on this host.');
147
+ return;
148
+ }
149
+ if (container.state !== 'running') {
150
+ // Stated rather than attempted: `exec` on a stopped container fails with
151
+ // a message about the daemon, which reads like a bug rather than the
152
+ // obvious thing it is.
153
+ this.fail(`${container.name} is not running, so there is nothing to attach to.`);
154
+ return;
155
+ }
156
+
157
+ this.emitData(terminalLine(`${ANSI_DIM}Attaching to ${container.name}…${ANSI_RESET}`));
158
+
159
+ try {
160
+ if (target.hostId === LOCAL_HOST_ID) await this.openLocal(target, options);
161
+ else await this.openRemote(target, options);
162
+ } catch (error) {
163
+ this.fail(error instanceof Error ? error.message : String(error));
164
+ }
165
+ }
166
+
167
+ /** The argv both paths run: an interactive shell inside the container. */
168
+ private async execArgv(target: ContainerTarget, platform: ReturnType<typeof localPlatform>): Promise<string[]> {
169
+ const info = await containerMonitor.withHost(target.hostId, (runner) =>
170
+ detectRuntime(target.hostId, runner, platform)
171
+ );
172
+ if (info.problem !== 'none' || !info.runtime) {
173
+ throw new Error('This host has no container runtime available right now.');
174
+ }
175
+ // `locale: null` because this one is a shell a person types into: forcing
176
+ // the C locale on it would break every non-ASCII character they enter.
177
+ return containerArgv(
178
+ info.runtime,
179
+ platform,
180
+ ['exec', '--interactive', '--tty', target.containerId, 'sh', '-c', SHELL_PICK],
181
+ { locale: null }
182
+ );
183
+ }
184
+
185
+ private async openLocal(target: ContainerTarget, options: PtySpawnOptions): Promise<void> {
186
+ const argv = await this.execArgv(target, localPlatform());
187
+ if (this.finished) return;
188
+
189
+ // PtyKit's own backend, borrowed: this is a real local process and deserves
190
+ // the real pty, rather than a second implementation of one.
191
+ const backend = await loadBackend();
192
+ if (this.finished) return;
193
+
194
+ const handle = backend.spawn(argv[0], argv.slice(1), {
195
+ ...options,
196
+ cols: this.cols,
197
+ rows: this.rows
198
+ });
199
+ this.local = handle;
200
+
201
+ handle.onData((data) => this.emitData(data));
202
+ handle.onExit((event) => {
203
+ this.local = null;
204
+ this.finish(event.exitCode, event.signal);
205
+ });
206
+
207
+ for (const queued of this.pendingInput) handle.write(queued);
208
+ this.pendingInput.length = 0;
209
+ handle.resize(this.cols, this.rows);
210
+ }
211
+
212
+ private async openRemote(target: ContainerTarget, options: PtySpawnOptions): Promise<void> {
213
+ const connection = sshConnectionQueries.get(target.hostId);
214
+ if (!connection) throw new Error('That SSH host no longer exists.');
215
+
216
+ const platform = await containerMonitor.withHost(target.hostId, (runner) =>
217
+ detectRemotePlatform(target.hostId, runner)
218
+ );
219
+ const argv = await this.execArgv(target, platform);
220
+ if (this.finished) return;
221
+
222
+ // Its own lease rather than the shared queued runner: this channel stays
223
+ // open for as long as the shell does, and everything queued behind it
224
+ // would wait just as long.
225
+ const lease = await sshClientPool.acquire(target.hostId);
226
+ if (this.finished) {
227
+ lease.release();
228
+ return;
229
+ }
230
+ this.lease = lease;
231
+
232
+ const command = argv.map(shellQuote).join(' ');
233
+ const term = options.name ?? 'xterm-256color';
234
+
235
+ await new Promise<void>((resolve, reject) => {
236
+ lease.client.exec(
237
+ command,
238
+ { pty: { term, cols: this.cols, rows: this.rows, width: 0, height: 0 } },
239
+ (error, channel) => {
240
+ if (error) {
241
+ reject(new Error(`Could not open a shell in the container: ${error.message}`));
242
+ return;
243
+ }
244
+ if (this.finished) {
245
+ channel.end();
246
+ resolve();
247
+ return;
248
+ }
249
+
250
+ this.channel = channel;
251
+
252
+ channel.on('data', (chunk: Buffer) => this.emitData(chunk.toString('utf8')));
253
+ channel.stderr.on('data', (chunk: Buffer) => this.emitData(chunk.toString('utf8')));
254
+ channel.on('close', (code?: number, signal?: string) => {
255
+ this.channel = null;
256
+ this.finish(typeof code === 'number' ? code : 0, signal);
257
+ });
258
+ channel.on('error', (channelError: Error) => {
259
+ this.emitData(terminalLine(`${ANSI_RED}${channelError.message}${ANSI_RESET}`));
260
+ });
261
+
262
+ for (const queued of this.pendingInput) channel.write(queued);
263
+ this.pendingInput.length = 0;
264
+ channel.setWindow(this.rows, this.cols, 0, 0);
265
+ debug.log('containers', `shell opened in ${target.containerId} on ${connection.name}`);
266
+ resolve();
267
+ }
268
+ );
269
+ });
270
+ }
271
+
272
+ write(data: string): void {
273
+ if (this.finished) return;
274
+ if (this.local) {
275
+ this.local.write(data);
276
+ return;
277
+ }
278
+ if (this.channel) {
279
+ this.channel.write(data);
280
+ return;
281
+ }
282
+ this.pendingInput.push(data);
283
+ }
284
+
285
+ resize(cols: number, rows: number): void {
286
+ this.cols = cols;
287
+ this.rows = rows;
288
+ this.local?.resize(cols, rows);
289
+ this.channel?.setWindow(rows, cols, 0, 0);
290
+ }
291
+
292
+ kill(signal?: string): void {
293
+ const local = this.local;
294
+ this.local = null;
295
+ try {
296
+ local?.kill(signal);
297
+ } catch {
298
+ // Already gone.
299
+ }
300
+
301
+ // SSH has no signal to send an exec channel, so closing it is the kill:
302
+ // the remote `docker exec` sees its pty go away and exits, taking the
303
+ // shell inside the container with it.
304
+ const channel = this.channel;
305
+ this.channel = null;
306
+ try {
307
+ channel?.end();
308
+ } catch {
309
+ // Already gone.
310
+ }
311
+
312
+ this.finish(0);
313
+ }
314
+
315
+ onData(listener: (data: string) => void): PtyDisposable {
316
+ this.dataListeners.add(listener);
317
+ return { dispose: () => this.dataListeners.delete(listener) };
318
+ }
319
+
320
+ onExit(listener: (event: PtyExitEvent) => void): PtyDisposable {
321
+ this.exitListeners.add(listener);
322
+ return { dispose: () => this.exitListeners.delete(listener) };
323
+ }
324
+ }
325
+
326
+ /**
327
+ * PtyKit's backend contract, satisfied by container shells. The name has to be
328
+ * one of PtyKit's two known backend identifiers — it is only used for
329
+ * diagnostics, and the session engine never branches on it.
330
+ */
331
+ export const containerPtyBackend: PtyBackend = {
332
+ name: 'node-pty',
333
+ experimental: false,
334
+ spawn(file: string, _args: string[], options: PtySpawnOptions): PtyProcessHandle {
335
+ return new ContainerShellHandle(decodeContainerTarget(file), options);
336
+ }
337
+ };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Containers — the PtyKit session engine for shells inside containers.
3
+ *
4
+ * A third `PtyKitManager` alongside the local-terminal and SSH ones, differing
5
+ * only in its injected backend. Everything downstream — scrollback, serialized
6
+ * reattach, collaborative rooms, reconnect after a dropped socket — is PtyKit's
7
+ * and is not reimplemented here.
8
+ *
9
+ * The namespace is `container:<hostId>:<containerId>`. That is the whole
10
+ * security design: it is the only statement of intent the client makes,
11
+ * `authorize` checks it, and the spawn target is derived from it rather than
12
+ * from anything else in the frame — so a client cannot ask for a container on a
13
+ * host it may not reach. It also scopes the collaborative room to one
14
+ * container, which is what a second admin opening the same shell should join.
15
+ *
16
+ * A shell inside a container is usually root inside it and can reach every
17
+ * volume that container mounts, so `authorize` requires an admin. Reading the
18
+ * list, the detail and the logs stays open to any member.
19
+ */
20
+
21
+ import { PtyKitManager } from '@myrialabs/ptykit/core';
22
+ import { createPtyKitServer } from '@myrialabs/ptykit/server';
23
+ import { LOCAL_HOST_ID } from '$shared/types/host';
24
+ import { sshConnectionQueries } from '../database/queries';
25
+ import { containerPtyBackend } from './pty-backend';
26
+ import { isContainerId } from './actions';
27
+
28
+ const NAMESPACE_PREFIX = 'container:';
29
+
30
+ export function containerNamespaceFor(hostId: string, containerId: string): string {
31
+ return `${NAMESPACE_PREFIX}${hostId}:${containerId}`;
32
+ }
33
+
34
+ /** The target a namespace refers to, or null when it is not one of ours. */
35
+ export function targetFromNamespace(
36
+ namespace: string
37
+ ): { hostId: string; containerId: string } | null {
38
+ if (!namespace.startsWith(NAMESPACE_PREFIX)) return null;
39
+ const rest = namespace.slice(NAMESPACE_PREFIX.length);
40
+ const split = rest.lastIndexOf(':');
41
+ if (split <= 0) return null;
42
+
43
+ const hostId = rest.slice(0, split);
44
+ const containerId = rest.slice(split + 1);
45
+ if (!hostId || !isContainerId(containerId)) return null;
46
+ return { hostId, containerId };
47
+ }
48
+
49
+ /**
50
+ * Container shells outlive a browser refresh the same way local and remote
51
+ * ones do, so the settings mirror the other two managers. Env injection is
52
+ * omitted: the environment that matters belongs to the container, not to this
53
+ * process.
54
+ */
55
+ export const containerPtyKitManager = new PtyKitManager({
56
+ backend: containerPtyBackend,
57
+ scrollback: 5000,
58
+ idleTtl: null,
59
+ retainExitedMs: 5 * 60_000
60
+ });
61
+
62
+ export const containerPtyKitServer = createPtyKitServer(containerPtyKitManager, {
63
+ room: (ctx) => ctx.namespace,
64
+ authorize: (ctx) => {
65
+ const userId = ctx.conn.data.userId;
66
+ const isAdmin = ctx.conn.data.isAdmin === true;
67
+ if (typeof userId !== 'string' || !userId) return false;
68
+ // A container shell can do anything the container can, so it is gated the
69
+ // same way stopping a port is.
70
+ if (!isAdmin) return false;
71
+
72
+ const target = targetFromNamespace(ctx.namespace);
73
+ if (!target) return false;
74
+ if (target.hostId === LOCAL_HOST_ID) return true;
75
+
76
+ return sshConnectionQueries.getForUser(target.hostId, userId, isAdmin) !== null;
77
+ }
78
+ });
79
+
80
+ /** Kill every container shell open on a host. */
81
+ export function killContainerSessionsForHost(hostId: string): number {
82
+ let killed = 0;
83
+ const prefix = `${NAMESPACE_PREFIX}${hostId}:`;
84
+ // PtyKit lists per namespace and a namespace names one container, so every
85
+ // container that has a shell open on this host is asked in turn.
86
+ for (const namespace of listNamespaces()) {
87
+ if (!namespace.startsWith(prefix)) continue;
88
+ for (const session of containerPtyKitManager.list(namespace)) {
89
+ containerPtyKitManager.killSession(session.sessionId, 'SIGKILL');
90
+ killed++;
91
+ }
92
+ }
93
+ return killed;
94
+ }
95
+
96
+ /**
97
+ * Namespaces with at least one live session.
98
+ *
99
+ * PtyKit's manager lists sessions per namespace and does not enumerate the
100
+ * namespaces themselves, so they are tracked here as sessions are created —
101
+ * which is also what lets a host-wide teardown find them.
102
+ */
103
+ const namespaces = new Set<string>();
104
+
105
+ export function rememberNamespace(namespace: string): void {
106
+ if (targetFromNamespace(namespace)) namespaces.add(namespace);
107
+ }
108
+
109
+ function listNamespaces(): string[] {
110
+ for (const namespace of [...namespaces]) {
111
+ if (containerPtyKitManager.list(namespace).length === 0) namespaces.delete(namespace);
112
+ }
113
+ return [...namespaces];
114
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Containers — which runtime this host has, decided by asking it.
3
+ *
4
+ * There is no setting for this and no toggle in the UI. A host either answers
5
+ * `docker`, or answers `podman`, or has neither, and any of those three is a
6
+ * fact Clopen can establish in one command. Docker is asked first because a
7
+ * machine with both almost always means Podman installed alongside a Docker
8
+ * that is actually in use; if Docker cannot answer, Podman is asked and used.
9
+ *
10
+ * The failure modes matter as much as the success. "No runtime installed",
11
+ * "installed but the daemon is not running" and "installed but this account may
12
+ * not talk to the socket" need three different things from the user, and
13
+ * reporting all three as "no containers" would be a lie the user cannot debug.
14
+ * Clopen never runs any of this through `sudo`.
15
+ */
16
+
17
+ import type { ContainerRuntime, ContainerRuntimeInfo } from '$shared/types/containers';
18
+ import { posixArgv, type CommandRunner, type ProbePlatform, type RunResult } from '../host/runner';
19
+ import { debug } from '$shared/utils/logger';
20
+
21
+ /** How long a working runtime is trusted before it is asked again. */
22
+ const OK_TTL_MS = 10 * 60_000;
23
+ /**
24
+ * How long a broken or missing one is. Short on purpose: someone who has just
25
+ * started Docker Desktop should see the panel come alive without reopening it.
26
+ */
27
+ const PROBLEM_TTL_MS = 20_000;
28
+
29
+ interface CachedRuntime {
30
+ info: ContainerRuntimeInfo;
31
+ expiresAt: number;
32
+ }
33
+
34
+ const cache = new Map<string, CachedRuntime>();
35
+
36
+ /**
37
+ * Build the argv for a runtime command on this platform.
38
+ *
39
+ * POSIX hosts go through `env` for a predictable PATH and a C locale — a
40
+ * non-interactive SSH session routinely lacks `/usr/local/bin`, which is
41
+ * exactly where Docker Desktop and Homebrew put these binaries, and a localised
42
+ * date is one nothing can parse. Windows has neither problem and no `env`, so
43
+ * the argv is passed through untouched.
44
+ */
45
+ export function containerArgv(
46
+ runtime: ContainerRuntime,
47
+ platform: ProbePlatform,
48
+ args: string[],
49
+ options: { locale?: string | null } = {}
50
+ ): string[] {
51
+ const argv = [runtime, ...args];
52
+ return platform === 'win32' ? argv : posixArgv(argv, options);
53
+ }
54
+
55
+ /**
56
+ * Run a runtime command, reporting a missing binary as a failed command rather
57
+ * than an exception. `Bun.spawn` throws when the executable does not exist,
58
+ * which is a normal answer here — most hosts have no container runtime at all.
59
+ */
60
+ export async function tryRun(
61
+ runner: CommandRunner,
62
+ argv: string[],
63
+ timeoutMs?: number
64
+ ): Promise<RunResult> {
65
+ try {
66
+ return await runner.run(argv, timeoutMs);
67
+ } catch (error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ return { stdout: '', stderr: message, code: 127 };
70
+ }
71
+ }
72
+
73
+ const NOT_INSTALLED = /not found|no such file|not recognized|executablenotfound|enoent/i;
74
+ const PERMISSION_DENIED = /permission denied|dial unix.*permission|got permission denied/i;
75
+ const DAEMON_DOWN =
76
+ /cannot connect to the docker daemon|is the docker daemon running|cannot connect to podman|connection refused|no such host|error during connect|the system cannot find the file specified/i;
77
+
78
+ /** Turn a failed probe into the reason a user can act on. */
79
+ function classify(result: RunResult): ContainerRuntimeInfo['problem'] {
80
+ const text = `${result.stderr}\n${result.stdout}`;
81
+ if (PERMISSION_DENIED.test(text)) return 'permission-denied';
82
+ if (DAEMON_DOWN.test(text)) return 'daemon-unreachable';
83
+ if (result.code === 127 || NOT_INSTALLED.test(text)) return 'not-installed';
84
+ // An exit code with nothing recognisable in it is still not a usable runtime;
85
+ // treat it as unreachable, which is the reading that invites a retry.
86
+ return 'daemon-unreachable';
87
+ }
88
+
89
+ /** The first line of a runtime's error, which is the part worth showing. */
90
+ function firstLine(text: string): string | null {
91
+ const line = text
92
+ .split('\n')
93
+ .map((value) => value.trim())
94
+ .find((value) => value.length > 0);
95
+ return line ?? null;
96
+ }
97
+
98
+ /**
99
+ * Ask one runtime whether it is usable.
100
+ *
101
+ * `version` is the probe because it is the only command that talks to the
102
+ * daemon while doing nothing to it, and because its failure text is what names
103
+ * the three problems apart.
104
+ */
105
+ async function probe(
106
+ runtime: ContainerRuntime,
107
+ runner: CommandRunner,
108
+ platform: ProbePlatform
109
+ ): Promise<ContainerRuntimeInfo> {
110
+ const result = await tryRun(runner, containerArgv(runtime, platform, ['version', '--format', '{{json .}}']), 10_000);
111
+
112
+ if (result.code !== 0) {
113
+ return {
114
+ runtime: null,
115
+ version: null,
116
+ problem: classify(result),
117
+ detail: firstLine(result.stderr) ?? firstLine(result.stdout)
118
+ };
119
+ }
120
+
121
+ let version: string | null = null;
122
+ try {
123
+ const parsed = JSON.parse(result.stdout.trim()) as {
124
+ Server?: { Version?: string };
125
+ Client?: { Version?: string };
126
+ };
127
+ version = parsed.Server?.Version ?? parsed.Client?.Version ?? null;
128
+ } catch {
129
+ // A version string Clopen cannot read does not make the runtime unusable.
130
+ }
131
+
132
+ return { runtime, version, problem: 'none', detail: null };
133
+ }
134
+
135
+ /**
136
+ * The runtime this host has, cached.
137
+ *
138
+ * Cached because the answer costs a round trip on an SSH connection the
139
+ * terminal and file browser are also using, and it cannot change between two
140
+ * ticks of a one-second poll.
141
+ */
142
+ export async function detectRuntime(
143
+ hostId: string,
144
+ runner: CommandRunner,
145
+ platform: ProbePlatform,
146
+ now = Date.now()
147
+ ): Promise<ContainerRuntimeInfo> {
148
+ const cached = cache.get(hostId);
149
+ if (cached && cached.expiresAt > now) return cached.info;
150
+
151
+ const docker = await probe('docker', runner, platform);
152
+ let info = docker;
153
+
154
+ if (docker.problem !== 'none') {
155
+ const podman = await probe('podman', runner, platform);
156
+ // A runtime that is installed but unhappy is more useful to report than
157
+ // one that is simply absent — it is the one the user can fix.
158
+ info = podman.problem === 'none' || docker.problem === 'not-installed' ? podman : docker;
159
+ }
160
+
161
+ if (info.problem !== 'none') {
162
+ debug.log('containers', `no usable runtime on ${runner.label}: ${info.problem}`);
163
+ }
164
+
165
+ cache.set(hostId, {
166
+ info,
167
+ expiresAt: now + (info.problem === 'none' ? OK_TTL_MS : PROBLEM_TTL_MS)
168
+ });
169
+ return info;
170
+ }
171
+
172
+ /**
173
+ * Drop a host's cached answer, so the next scan asks again.
174
+ *
175
+ * Called when a command fails in a way that says the daemon went away: the
176
+ * cached "docker works" would otherwise keep a panel showing an empty table for
177
+ * ten minutes after Docker Desktop was quit.
178
+ */
179
+ export function forgetRuntime(hostId: string): void {
180
+ cache.delete(hostId);
181
+ }
182
+
183
+ /** True when a command failed because the runtime itself became unusable. */
184
+ export function looksLikeRuntimeFailure(result: RunResult): boolean {
185
+ if (result.code === 0) return false;
186
+ const text = `${result.stderr}\n${result.stdout}`;
187
+ return NOT_INSTALLED.test(text) || PERMISSION_DENIED.test(text) || DAEMON_DOWN.test(text);
188
+ }
189
+
190
+ /** The sentence shown when a host has no usable runtime. */
191
+ export function limitationFor(info: ContainerRuntimeInfo, hostLabel: string): string {
192
+ switch (info.problem) {
193
+ case 'not-installed':
194
+ return `No container runtime found on ${hostLabel}. Install Docker or Podman and it will appear here — nothing needs configuring.`;
195
+ case 'daemon-unreachable':
196
+ return `A container runtime is installed on ${hostLabel} but is not running${
197
+ info.detail ? `: ${info.detail}` : '.'
198
+ }`;
199
+ case 'permission-denied':
200
+ return `This account may not talk to the container runtime on ${hostLabel}. Add it to the runtime's group, or use a rootless runtime — Clopen never runs commands through sudo.`;
201
+ default:
202
+ return '';
203
+ }
204
+ }
205
+
206
+ /**
207
+ * The line of a failure worth showing.
208
+ *
209
+ * The runtimes write several lines when they refuse something, and the first is
210
+ * the reason — "volume is in use", "image has dependent child images". The rest
211
+ * is usually the id repeated back.
212
+ */
213
+ export function firstProblem(stderr: string, stdout: string, code: number): string {
214
+ const line =
215
+ stderr.trim().split('\n')[0] || stdout.trim().split('\n')[0] || `exit status ${code}`;
216
+ // Both runtimes prefix errors with a level that means nothing to a reader.
217
+ return line.replace(/^(Error(:| response from daemon:)|ERRO\[\d+\])\s*/i, '').trim() || line;
218
+ }