@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,235 @@
1
+ /**
2
+ * Host metrics — hardware identity and the live process table.
3
+ *
4
+ * One module because Settings → Device and Project Info both ask, and their
5
+ * numbers only compare if measured the same way. `si.processes()` reports CPU
6
+ * against a different basis per platform (total capacity on Linux, one core on
7
+ * macOS/BSD, consumed CPU on Windows), so everything is normalised here to
8
+ * percent of machine capacity — the basis `si.currentLoad()` already uses.
9
+ */
10
+
11
+ import os from 'node:os';
12
+ import si from 'systeminformation';
13
+ import type { Systeminformation } from 'systeminformation';
14
+ import { debug } from '$shared/utils/logger';
15
+
16
+ /** Race a promise against a deadline. Without a fallback, a timeout gives null. */
17
+ export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null>;
18
+ export function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T>;
19
+ export function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T | null = null): Promise<T | null> {
20
+ let timer: ReturnType<typeof setTimeout> | undefined;
21
+ const timeout = new Promise<never>((_, reject) => {
22
+ timer = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
23
+ });
24
+ return Promise.race([promise, timeout])
25
+ .then((value) => {
26
+ clearTimeout(timer);
27
+ return value;
28
+ })
29
+ .catch(() => {
30
+ clearTimeout(timer);
31
+ return fallback;
32
+ });
33
+ }
34
+
35
+ // ── Static facts ─────────────────────────────────────────────────────────────
36
+
37
+ export interface HostFacts {
38
+ hostname: string;
39
+ platform: string;
40
+ distro: string;
41
+ release: string;
42
+ kernel: string;
43
+ arch: string;
44
+ isVirtual: boolean;
45
+ cpuBrand: string;
46
+ cpuManufacturer: string;
47
+ physicalCores: number;
48
+ logicalCores: number;
49
+ cpuSpeedGhz: number | null;
50
+ /** The single denominator behind every "percent of host memory" figure. */
51
+ totalMemBytes: number;
52
+ gpus: Array<{ model: string; vendor: string; vramMb: number | null }>;
53
+ }
54
+
55
+ let hostFactsPromise: Promise<HostFacts> | null = null;
56
+
57
+ /** Hardware identity, probed once per process. */
58
+ export function getHostFacts(): Promise<HostFacts> {
59
+ if (!hostFactsPromise) {
60
+ hostFactsPromise = probeHostFacts().catch((error) => {
61
+ // Don't cache a failed probe — let the next request retry.
62
+ hostFactsPromise = null;
63
+ throw error;
64
+ });
65
+ }
66
+ return hostFactsPromise;
67
+ }
68
+
69
+ async function probeHostFacts(): Promise<HostFacts> {
70
+ const [osInfo, cpu, system, graphics, memory] = await Promise.all([
71
+ withTimeout(si.osInfo(), 4000),
72
+ withTimeout(si.cpu(), 4000),
73
+ withTimeout(si.system(), 4000),
74
+ withTimeout(si.graphics(), 4000),
75
+ withTimeout(si.mem(), 4000)
76
+ ]);
77
+
78
+ return {
79
+ hostname: osInfo?.hostname || os.hostname(),
80
+ platform: osInfo?.platform || os.platform(),
81
+ distro: osInfo?.distro || '',
82
+ release: osInfo?.release || os.release(),
83
+ kernel: osInfo?.kernel || os.version(),
84
+ arch: osInfo?.arch || os.arch(),
85
+ isVirtual: Boolean(system?.virtual),
86
+ cpuBrand: cpu?.brand || '',
87
+ cpuManufacturer: cpu?.manufacturer || '',
88
+ physicalCores: cpu?.physicalCores || cpu?.cores || os.cpus().length,
89
+ logicalCores: cpu?.cores || os.cpus().length,
90
+ cpuSpeedGhz: typeof cpu?.speed === 'number' && cpu.speed > 0 ? cpu.speed : null,
91
+ totalMemBytes: typeof memory?.total === 'number' && memory.total > 0 ? memory.total : os.totalmem(),
92
+ gpus: (graphics?.controllers ?? []).map((controller) => ({
93
+ model: controller.model || 'Unknown GPU',
94
+ vendor: controller.vendor || 'Unknown',
95
+ vramMb: typeof controller.vram === 'number' && controller.vram > 0 ? controller.vram : null
96
+ }))
97
+ };
98
+ }
99
+
100
+ // ── Process table ────────────────────────────────────────────────────────────
101
+
102
+ /** Longer than the 500ms window `si` caches its own table for, so a hit here
103
+ * can never pair a stale table with a fresh `os.cpus()` snapshot. */
104
+ const PROCESS_CACHE_TTL_MS = 2_000;
105
+ /** `si.processes()` shells out — to PowerShell on Windows, which can hang. */
106
+ const PROCESS_PROBE_TIMEOUT_MS = 10_000;
107
+
108
+ export interface ProbedProcess {
109
+ pid: number;
110
+ parentPid: number;
111
+ name: string;
112
+ /** Raw `si` percentage — multiply by `cpuFactor` for a share of capacity. */
113
+ cpu: number;
114
+ /** `si` reports RSS in KB on every platform. */
115
+ memRss: number;
116
+ command: string;
117
+ }
118
+
119
+ export interface ProcessTable {
120
+ list: ProbedProcess[];
121
+ /** null when no honest conversion to a capacity share exists yet. */
122
+ cpuFactor: number | null;
123
+ }
124
+
125
+ let cachedTable: { table: ProcessTable | null; at: number } | null = null;
126
+ let inFlightTable: Promise<ProcessTable | null> | null = null;
127
+ let lastCpuTicks: { busy: number; total: number } | null = null;
128
+ let probeCount = 0;
129
+
130
+ function readCpuTicks(): { busy: number; total: number } {
131
+ let busy = 0;
132
+ let total = 0;
133
+ for (const core of os.cpus()) {
134
+ const active = core.times.user + core.times.nice + core.times.sys + core.times.irq;
135
+ busy += active;
136
+ total += active + core.times.idle;
137
+ }
138
+ return { busy, total };
139
+ }
140
+
141
+ /**
142
+ * Multiplier turning one `si` CPU percentage into a share of machine capacity.
143
+ * Linux is already capacity-relative; macOS/BSD count one core as 100%; Windows
144
+ * is relative to CPU the processes consumed, so it scales by the busy fraction.
145
+ */
146
+ export function cpuCapacityFactor(
147
+ platform: NodeJS.Platform,
148
+ logicalCores: number,
149
+ busyFraction: number | null,
150
+ hasDelta: boolean
151
+ ): number | null {
152
+ if (platform === 'linux') return hasDelta ? 1 : null;
153
+ if (platform === 'win32') return hasDelta && busyFraction !== null ? busyFraction : null;
154
+ return logicalCores > 0 ? 1 / logicalCores : null;
155
+ }
156
+
157
+ /**
158
+ * Every descendant of `roots`, via a parent → children index walked once.
159
+ * Exact at any depth, and `seen` guards the pid cycles Windows can report.
160
+ */
161
+ export function collectProcessTree(
162
+ list: Array<{ pid: number; parentPid: number }>,
163
+ roots: number[]
164
+ ): Set<number> {
165
+ const children = new Map<number, number[]>();
166
+ for (const entry of list) {
167
+ if (entry.parentPid === entry.pid) continue;
168
+ const siblings = children.get(entry.parentPid);
169
+ if (siblings) siblings.push(entry.pid);
170
+ else children.set(entry.parentPid, [entry.pid]);
171
+ }
172
+
173
+ const seen = new Set<number>(roots);
174
+ const queue = [...roots];
175
+ for (let head = 0; head < queue.length; head++) {
176
+ for (const child of children.get(queue[head]) ?? []) {
177
+ if (seen.has(child)) continue;
178
+ seen.add(child);
179
+ queue.push(child);
180
+ }
181
+ }
182
+
183
+ return seen;
184
+ }
185
+
186
+ async function probeProcessTable(): Promise<ProcessTable | null> {
187
+ // Sampled at the instant `si` takes its own sample, so both deltas span the
188
+ // same interval and the Windows conversion stays sound.
189
+ const ticks = readCpuTicks();
190
+ const previous = lastCpuTicks;
191
+ lastCpuTicks = ticks;
192
+
193
+ const totalDelta = previous ? ticks.total - previous.total : 0;
194
+ const busyFraction = previous && totalDelta > 0 ? (ticks.busy - previous.busy) / totalDelta : null;
195
+
196
+ const result = await withTimeout(si.processes(), PROCESS_PROBE_TIMEOUT_MS);
197
+ if (!result) {
198
+ // A timed-out probe still lands later and moves `si`'s delta base at a
199
+ // moment we no longer know, so drop our base rather than mismatch it.
200
+ debug.warn('host', 'si.processes() unavailable — reporting process metrics as unknown');
201
+ lastCpuTicks = null;
202
+ probeCount = 0;
203
+ return null;
204
+ }
205
+
206
+ probeCount++;
207
+
208
+ return {
209
+ list: (result.list ?? []).map((entry: Systeminformation.ProcessesProcessData) => ({
210
+ pid: entry.pid,
211
+ parentPid: entry.parentPid,
212
+ name: entry.name,
213
+ cpu: typeof entry.cpu === 'number' && Number.isFinite(entry.cpu) ? entry.cpu : 0,
214
+ memRss: typeof entry.memRss === 'number' && Number.isFinite(entry.memRss) ? entry.memRss : 0,
215
+ command: entry.command
216
+ })),
217
+ // Linux and Windows need a second sample before a delta exists.
218
+ cpuFactor: cpuCapacityFactor(process.platform, os.cpus().length, busyFraction, probeCount >= 2)
219
+ };
220
+ }
221
+
222
+ /** Cached and single-flighted: N panels polling in step cost one probe. */
223
+ export function getProcessTable(): Promise<ProcessTable | null> {
224
+ if (cachedTable && Date.now() - cachedTable.at < PROCESS_CACHE_TTL_MS) {
225
+ return Promise.resolve(cachedTable.table);
226
+ }
227
+ if (inFlightTable) return inFlightTable;
228
+
229
+ inFlightTable = probeProcessTable().then((table) => {
230
+ cachedTable = { table, at: Date.now() };
231
+ inFlightTable = null;
232
+ return table;
233
+ });
234
+ return inFlightTable;
235
+ }
@@ -1,15 +1,19 @@
1
1
  /**
2
- * Port manager — one command interface, two transports.
2
+ * Host commands — one command interface, two transports.
3
3
  *
4
- * Every probe in this feature is a small POSIX/Windows command, and the same
5
- * probe has to run on the machine hosting Clopen and on a saved SSH host. So
6
- * the probes are written once against `CommandRunner` and the transport is
7
- * swapped underneath: `Bun.spawn` locally, an exec channel remotely.
4
+ * Every host-scoped feature in Clopen — the port table, and the container list
5
+ * that followed it — is built out of small POSIX/Windows commands, and the same
6
+ * command has to run on the machine hosting Clopen and on a saved SSH host. So
7
+ * they are written once against `CommandRunner` and the transport is swapped
8
+ * underneath: `Bun.spawn` locally, an exec channel remotely.
8
9
  *
9
10
  * Commands are argv arrays rather than shell strings. Locally that removes
10
11
  * quoting from the picture entirely; remotely each argument is quoted by
11
- * `shellQuote` on the way out, so a hostile process name in an argument can
12
- * never turn into a second command.
12
+ * `shellQuote` on the way out, so a hostile process or container name in an
13
+ * argument can never turn into a second command.
14
+ *
15
+ * This lives outside `ports/` because `local` is not a special case and neither
16
+ * is any one feature: whatever asks a host a question asks it through here.
13
17
  */
14
18
 
15
19
  import type { Client as SshClient } from 'ssh2';
@@ -34,9 +38,14 @@ const PROBE_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
34
38
  * arguments stay arguments — while fixing both problems a bare command has on
35
39
  * a remote host: a PATH too narrow to find the tool, and a locale that renders
36
40
  * dates in words nothing can parse.
41
+ *
42
+ * `locale: null` drops the `LC_ALL=C` half. A probe wants a machine-readable
43
+ * locale; an interactive shell opened through the same PATH fix does not —
44
+ * forcing C on one would leave the user unable to type a non-ASCII character.
37
45
  */
38
- export function posixArgv(argv: string[]): string[] {
39
- return ['env', 'LC_ALL=C', `PATH=${PROBE_PATH}`, ...argv];
46
+ export function posixArgv(argv: string[], options: { locale?: string | null } = {}): string[] {
47
+ const locale = options.locale === undefined ? 'C' : options.locale;
48
+ return ['env', ...(locale === null ? [] : [`LC_ALL=${locale}`]), `PATH=${PROBE_PATH}`, ...argv];
40
49
  }
41
50
 
42
51
  export interface RunResult {
@@ -171,7 +180,7 @@ export async function detectRemotePlatform(cacheKey: string, runner: CommandRunn
171
180
  else if (name.includes('bsd')) platform = 'linux';
172
181
  }
173
182
  } catch (error) {
174
- debug.log('ports', `uname failed on ${runner.label}:`, error);
183
+ debug.log('host', `uname failed on ${runner.label}:`, error);
175
184
  }
176
185
 
177
186
  // No `uname` usually means a Windows host answering over OpenSSH, where the
package/backend/index.ts CHANGED
@@ -65,6 +65,8 @@ import { authQueries } from './database/queries';
65
65
  import { authRateLimiter } from './auth';
66
66
  import { sessionCleanupScheduler } from './auth/session-cleanup';
67
67
  import { portMonitor } from './ports/monitor';
68
+ import { containerMonitor } from './containers/monitor';
69
+ import { stopAllLogStreams as stopAllContainerLogStreams } from './containers/logs';
68
70
  import { uploadTempCleanup } from './http/upload-temp-cleanup';
69
71
  import { ws as wsServer } from './utils/ws';
70
72
  import { messageRateLimiter } from './ws/message-rate-limiter';
@@ -102,8 +104,8 @@ wsRouter.setAuthMiddleware(async (conn, action) => {
102
104
  });
103
105
 
104
106
  // Register message rate limiter on WebSocket router — prevents DoS via message spam
105
- wsRouter.setRateLimiter((conn, action) => {
106
- return messageRateLimiter.checkRateLimit(conn, action);
107
+ wsRouter.setRateLimiter((conn, action, isRequest) => {
108
+ return messageRateLimiter.checkRateLimit(conn, action, isRequest);
107
109
  });
108
110
 
109
111
  /**
@@ -274,6 +276,10 @@ async function startServer() {
274
276
  // terminal sessions running there are no session-born ports to count, so
275
277
  // the tick skips the scan entirely.
276
278
  portMonitor.start();
279
+ // Sidebar count for the container manager: containers running on this
280
+ // machine. Idle-cheap too — a machine with no runtime is remembered as
281
+ // having none, so the tick costs a cached lookup and no command at all.
282
+ containerMonitor.start();
277
283
  } catch (error) {
278
284
  console.error('❌ Database initialization failed — refusing to start:', error);
279
285
  console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
@@ -327,6 +333,11 @@ async function gracefulShutdown() {
327
333
  // and browser teardown below — otherwise the old process keeps those
328
334
  // sockets open long enough to overlap the new process ("too many clients").
329
335
  await connectionManager.closeAll();
336
+ // Engines next, because they own CHILD PROCESSES. Everything below is
337
+ // in-process cleanup that dies with us anyway, but an `opencode serve`
338
+ // we fail to kill outlives the restart holding its port and data-dir
339
+ // lock — and the 5s force-exit above used to fire before we got here.
340
+ await disposeAllEngines();
330
341
  // Same reasoning for SSH: stop the forwards' listeners and close every
331
342
  // transport so their remote sessions and bound ports are released now.
332
343
  await sshForwardManager.stopAll();
@@ -339,6 +350,9 @@ async function gracefulShutdown() {
339
350
  uploadTempCleanup.dispose();
340
351
  // Stop port polling and release any SSH leases it holds
341
352
  portMonitor.stop();
353
+ // Same for the container list, and the log streams it may still be pumping
354
+ stopAllContainerLogStreams();
355
+ containerMonitor.stop();
342
356
  // Close MCP remote server (before engines, as they may still reference it)
343
357
  await closeMcpServer();
344
358
  // Cleanup browser preview sessions
@@ -350,8 +364,6 @@ async function gracefulShutdown() {
350
364
  stopMemoryMaintenance();
351
365
  stopExtractionRunner();
352
366
  await flushEpisodicIngest();
353
- // Dispose all AI engines
354
- await disposeAllEngines();
355
367
  // Close database connection
356
368
  closeDatabase();
357
369
  debug.log('server', '✅ Graceful shutdown completed');
@@ -11,6 +11,8 @@
11
11
  import { browserMcpControl, browserPreviewServiceManager, type BrowserPreviewService } from '$backend/preview';
12
12
  import type { BrowserTab } from '$backend/preview/browser/types';
13
13
  import { projectContextService } from '$backend/mcp/internal/project-context';
14
+ import { sessionQueries } from '$backend/database/queries';
15
+ import { makeScopeKey } from '$shared/utils/workspace-scope';
14
16
  import { debug } from '$shared/utils/logger';
15
17
 
16
18
  /**
@@ -22,10 +24,10 @@ import { debug } from '$shared/utils/logger';
22
24
  * because acting on a guessed project is worth noticing in the logs.
23
25
  */
24
26
  export function getPreviewService(projectId?: string): BrowserPreviewService {
25
- if (projectId) return browserPreviewServiceManager.getService(projectId);
27
+ if (projectId) return browserPreviewServiceManager.getService(scopeForProject(projectId));
26
28
 
27
29
  const contextProjectId = projectContextService.getCurrentProjectId();
28
- if (contextProjectId) return browserPreviewServiceManager.getService(contextProjectId);
30
+ if (contextProjectId) return browserPreviewServiceManager.getService(scopeForProject(contextProjectId));
29
31
 
30
32
  const activeProjects = browserPreviewServiceManager.getActiveProjects();
31
33
  if (activeProjects.length > 0) {
@@ -36,6 +38,18 @@ export function getPreviewService(projectId?: string): BrowserPreviewService {
36
38
  throw new Error('No active browser preview service found. Project isolation requires projectId.');
37
39
  }
38
40
 
41
+ /**
42
+ * Workspace scope of the session driving this call, so an agent working in a
43
+ * worktree drives that worktree's browser rather than the main tree's.
44
+ */
45
+ function scopeForProject(projectId: string): string {
46
+ const chatSessionId = projectContextService.getCurrentChatSessionId();
47
+ const worktreeId = chatSessionId
48
+ ? sessionQueries.getById(chatSessionId)?.worktree_id ?? null
49
+ : null;
50
+ return makeScopeKey(projectId, worktreeId);
51
+ }
52
+
39
53
  /** The chat session driving this call — MCP control is scoped to it. */
40
54
  export function getChatSessionId(): string {
41
55
  const chatSessionId = projectContextService.getCurrentChatSessionId();
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
2
  import type { PortProcess, PortSocket } from '$shared/types/ports';
3
- import { findClopenPids, groupListenerPids, traceAncestry, type SessionPid } from './attribute';
3
+ import { findClopenPids, groupListenerPids, traceAncestry } from './attribute';
4
+ import type { ProjectShell } from '../projects/shell-ownership';
4
5
  import { findConnectionSshd, parseEnvironProbe, sameConnection } from './ssh-lineage';
5
6
 
6
7
  function proc(pid: number, parentPid: number | null, command: string): PortProcess {
@@ -75,7 +76,7 @@ describe('groupListenerPids', () => {
75
76
  });
76
77
 
77
78
  describe('traceAncestry', () => {
78
- const sessions = new Map<number, SessionPid>([
79
+ const sessions = new Map<number, ProjectShell>([
79
80
  [400, { pid: 400, sessionId: 'sess-1', projectId: 'proj-1', projectName: 'shop', cwd: '/srv/shop' }]
80
81
  ]);
81
82
 
@@ -22,48 +22,9 @@
22
22
  */
23
23
 
24
24
  import type { PortOrigin, PortProcess, PortSocket } from '$shared/types/ports';
25
- import type { ProbePlatform } from './runner';
26
- import { ptyKitManager } from '../terminal/ptykit';
27
- import { projectQueries } from '../database/queries';
25
+ import type { ProbePlatform } from '../host/runner';
26
+ import { collectSessionPids, type ProjectShell } from '../projects/shell-ownership';
28
27
  import { collectOwnedPorts, ownedPortKey, type OwnedPort } from './registry';
29
- import { debug } from '$shared/utils/logger';
30
-
31
- /** A live Clopen terminal session, keyed by the pid of its shell. */
32
- export interface SessionPid {
33
- pid: number;
34
- sessionId: string;
35
- projectId: string;
36
- projectName: string | null;
37
- cwd: string;
38
- }
39
-
40
- /**
41
- * Shell pids of every active PTY session. The manager lists per namespace and
42
- * a namespace is a project, so every project is asked in turn.
43
- */
44
- export function collectSessionPids(): Map<number, SessionPid> {
45
- const sessions = new Map<number, SessionPid>();
46
-
47
- try {
48
- for (const project of projectQueries.getAll()) {
49
- for (const session of ptyKitManager.list(project.id)) {
50
- const info = session.info();
51
- if (info.status !== 'active' || !info.pid) continue;
52
- sessions.set(info.pid, {
53
- pid: info.pid,
54
- sessionId: info.sessionId,
55
- projectId: project.id,
56
- projectName: project.name ?? null,
57
- cwd: info.cwd
58
- });
59
- }
60
- }
61
- } catch (error) {
62
- debug.log('ports', 'could not read terminal sessions:', error);
63
- }
64
-
65
- return sessions;
66
- }
67
28
 
68
29
  /** Guard against a malformed parent chain looping forever. */
69
30
  const MAX_ANCESTRY_DEPTH = 40;
@@ -118,7 +79,7 @@ export interface Ancestry {
118
79
  /** The chain from the process itself up to init, self first. */
119
80
  chain: PortProcess[];
120
81
  /** The Clopen terminal session it descends from, if any. */
121
- session: SessionPid | null;
82
+ session: ProjectShell | null;
122
83
  /**
123
84
  * True when the chain reaches a process Clopen is: one of its own instances
124
85
  * locally, or the sshd session it is using on a remote host.
@@ -137,13 +98,13 @@ function sshdUserOf(command: string): string | null {
137
98
  export function traceAncestry(
138
99
  pid: number,
139
100
  processes: Map<number, PortProcess>,
140
- sessions: Map<number, SessionPid>,
101
+ sessions: Map<number, ProjectShell>,
141
102
  clopenRootPids: ReadonlySet<number> = new Set()
142
103
  ): Ancestry {
143
104
  const chain: PortProcess[] = [];
144
105
  const seen = new Set<number>();
145
106
 
146
- let session: SessionPid | null = null;
107
+ let session: ProjectShell | null = null;
147
108
  let sshdUser: string | null = null;
148
109
  let fromClopen = false;
149
110
  let current: number | null = pid;
@@ -218,7 +179,7 @@ export interface AttributionContext {
218
179
  /** Ports Clopen opened on this host, whichever host it is. */
219
180
  owned: Map<string, OwnedPort>;
220
181
  /** Shell pids of local terminal sessions; empty on an SSH host. */
221
- sessions: Map<number, SessionPid>;
182
+ sessions: Map<number, ProjectShell>;
222
183
  /**
223
184
  * The processes that count as "Clopen" on this host: its own instances
224
185
  * locally, and remotely everything found to belong to Clopen's own SSH
@@ -19,7 +19,7 @@
19
19
 
20
20
  import type { PortKillResult, PortOwnerFeature } from '$shared/types/ports';
21
21
  import { parsePsOutput, unixPsArgv } from './processes';
22
- import type { CommandRunner, ProbePlatform } from './runner';
22
+ import type { CommandRunner, ProbePlatform } from '../host/runner';
23
23
  import { sshForwardManager } from '../ssh/forwards';
24
24
  import { connectionManager } from '../db-client/connection-manager';
25
25
  import { debug } from '$shared/utils/logger';
@@ -33,7 +33,7 @@ import {
33
33
  localPlatform,
34
34
  type CommandRunner,
35
35
  type ProbePlatform
36
- } from './runner';
36
+ } from '../host/runner';
37
37
  import { sshClientPool, type SshLease } from '../ssh/client-pool';
38
38
  import { forgetClopenRootPid } from './ssh-lineage';
39
39
  import { sshConnectionQueries } from '../database/queries';
@@ -19,7 +19,7 @@
19
19
  */
20
20
 
21
21
  import type { PortLimitation, PortProcess } from '$shared/types/ports';
22
- import type { CommandRunner, ProbePlatform } from './runner';
22
+ import type { CommandRunner, ProbePlatform } from '../host/runner';
23
23
  import { debug } from '$shared/utils/logger';
24
24
 
25
25
  /** How often the whole table is re-read, so exited pids stop being reported. */
@@ -8,9 +8,12 @@
8
8
 
9
9
  import os from 'node:os';
10
10
  import type {
11
+ PortContainerRef,
11
12
  PortEntry,
13
+ PortIpVersion,
12
14
  PortKillBlockedReason,
13
15
  PortLimitation,
16
+ PortOrigin,
14
17
  PortPeer,
15
18
  PortProtocol,
16
19
  PortScanResult,
@@ -22,7 +25,12 @@ import { ProcessTable } from './processes';
22
25
  import { attribute, buildContext, groupListenerPids } from './attribute';
23
26
  import { collectExposedPorts } from './registry';
24
27
  import { resolveClopenPids } from './ssh-lineage';
25
- import type { CommandRunner, ProbePlatform } from './runner';
28
+ import {
29
+ addressesOverlap,
30
+ containerPortIndex,
31
+ refreshContainerPortIndex
32
+ } from '../containers/port-index';
33
+ import type { CommandRunner, ProbePlatform } from '../host/runner';
26
34
 
27
35
  /** Who the scan is running as, which decides what it may signal. */
28
36
  export interface ScanPrincipal {
@@ -50,6 +58,18 @@ const NO_CLOPEN_LINEAGE: PortLimitation = {
50
58
  'Nothing listening here belongs to Clopen’s own SSH connection. If you started a server from a Clopen terminal on this host and it is not listed under “Started from Clopen”, this host does not let Clopen read a process’s environment.'
51
59
  };
52
60
 
61
+ /** How a published port describes itself: by the container, not the proxy. */
62
+ function containerOrigin(ref: PortContainerRef): PortOrigin {
63
+ return {
64
+ kind: 'container',
65
+ // The runtime states this outright — there is nothing to infer.
66
+ confidence: 'certain',
67
+ label: ref.name,
68
+ detail: `${ref.image} · container port ${ref.containerPort}`,
69
+ containerId: ref.id
70
+ };
71
+ }
72
+
53
73
  function protocolPortKey(protocol: PortProtocol, port: number): string {
54
74
  return `${protocol}:${port}`;
55
75
  }
@@ -184,6 +204,11 @@ export class HostPortScanner {
184
204
  });
185
205
  const peers = collectPeers(sockets);
186
206
  const exposed = this.isLocal ? collectExposedPorts() : new Map<number, string>();
207
+ // Read now, refresh behind us: a table that ticks every second must never
208
+ // wait on a `docker ps`, and a mapping that lands one tick late is
209
+ // invisible next to one that made the whole table stutter.
210
+ const containers = containerPortIndex(this.hostId);
211
+ refreshContainerPortIndex(this.hostId, this.runner, this.platform, now);
187
212
 
188
213
  // Bucket the listening sockets per protocol+port first; a port is the
189
214
  // unit the user thinks in, and the addresses under it are detail.
@@ -196,6 +221,8 @@ export class HostPortScanner {
196
221
  }
197
222
 
198
223
  const entries: PortEntry[] = [];
224
+ /** Mappings that found a socket to sit on; the rest get their own row. */
225
+ const annotated = new Set<string>();
199
226
 
200
227
  for (const [key, bucket] of buckets) {
201
228
  const { protocol, port } = bucket[0];
@@ -218,19 +245,27 @@ export class HostPortScanner {
218
245
  const representative = groupSockets[0];
219
246
  const pid = owner === -1 ? null : owner;
220
247
  const process = pid !== null ? (processes.get(pid) ?? null) : null;
221
- const origin = attribute({ ...representative, pid }, context);
248
+ const attributed = attribute({ ...representative, pid }, context);
249
+ // A published container port outranks whatever holds the socket: the
250
+ // listener is the runtime's own proxy, and signalling it would either
251
+ // fail or be undone by the daemon a moment later. Clopen's own
252
+ // listeners are the exception — those it does know better.
253
+ const candidate = attributed.kind === 'clopen' ? undefined : containers.get(key);
254
+ const groupAddresses = unique(groupSockets.map((socket) => socket.address));
255
+ const mapping =
256
+ candidate && addressesOverlap(groupAddresses, candidate.addresses) ? candidate : undefined;
257
+ if (mapping) annotated.add(key);
258
+ const origin = mapping ? containerOrigin(mapping.ref) : attributed;
222
259
  const ownerUser = process?.user ?? representative.user;
223
- const { canKill, reason } = this.killability(
224
- pid,
225
- ownerUser,
226
- origin.ownerFeature === 'server'
227
- );
260
+ const { canKill, reason } = mapping
261
+ ? { canKill: false, reason: 'managed-by-container' as PortKillBlockedReason }
262
+ : this.killability(pid, ownerUser, origin.ownerFeature === 'server');
228
263
 
229
264
  entries.push({
230
265
  key: `${this.hostId}:${key}:${pid ?? 'unknown'}`,
231
266
  protocol,
232
267
  port,
233
- addresses: unique(groupSockets.map((socket) => socket.address)).sort(),
268
+ addresses: [...groupAddresses].sort(),
234
269
  ipVersions: unique(groupSockets.map((socket) => socket.ipVersion)).sort(),
235
270
  pid,
236
271
  process,
@@ -239,12 +274,46 @@ export class HostPortScanner {
239
274
  peers: peers.get(key) ?? [],
240
275
  peerCount: (peers.get(key) ?? []).length,
241
276
  publicUrl: exposed.get(port) ?? null,
277
+ container: mapping?.ref ?? null,
242
278
  canKill,
243
279
  killBlockedReason: reason
244
280
  });
245
281
  }
246
282
  }
247
283
 
284
+ // Mappings with no socket behind them still get a row. Docker publishes
285
+ // through a firewall rule when its userland proxy is off, and Podman's
286
+ // rootless networking often leaves nothing for the probe to find either —
287
+ // so without this the port a user can actually reach would be missing from
288
+ // the one table that claims to list what is reachable.
289
+ for (const [mappingKey, mapping] of containers) {
290
+ if (annotated.has(mappingKey)) continue;
291
+ const [protocolText, portText] = mappingKey.split(':');
292
+ const port = Number(portText);
293
+ if (!Number.isFinite(port)) continue;
294
+ const protocol = protocolText === 'udp' ? 'udp' : 'tcp';
295
+
296
+ entries.push({
297
+ key: `${this.hostId}:${mappingKey}:container`,
298
+ protocol,
299
+ port,
300
+ addresses: [...mapping.addresses].sort(),
301
+ ipVersions: unique(
302
+ mapping.addresses.map((address): PortIpVersion => (address.includes(':') ? 'v6' : 'v4'))
303
+ ).sort(),
304
+ pid: null,
305
+ process: null,
306
+ workerPids: [],
307
+ origin: containerOrigin(mapping.ref),
308
+ peers: peers.get(mappingKey) ?? [],
309
+ peerCount: (peers.get(mappingKey) ?? []).length,
310
+ publicUrl: exposed.get(port) ?? null,
311
+ container: mapping.ref,
312
+ canKill: false,
313
+ killBlockedReason: 'managed-by-container'
314
+ });
315
+ }
316
+
248
317
  entries.sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol));
249
318
 
250
319
  return {