@myrialabs/clopen 0.4.34 → 0.4.35

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 (60) hide show
  1. package/backend/auth/permissions.ts +7 -0
  2. package/backend/containers/actions.ts +316 -0
  3. package/backend/containers/disk-usage.test.ts +68 -0
  4. package/backend/containers/disk-usage.ts +170 -0
  5. package/backend/containers/logs.ts +335 -0
  6. package/backend/containers/monitor.ts +410 -0
  7. package/backend/containers/parse.test.ts +599 -0
  8. package/backend/containers/parse.ts +905 -0
  9. package/backend/containers/port-index.test.ts +91 -0
  10. package/backend/containers/port-index.ts +198 -0
  11. package/backend/containers/prune-job.test.ts +148 -0
  12. package/backend/containers/prune-job.ts +129 -0
  13. package/backend/containers/pty-backend.ts +337 -0
  14. package/backend/containers/pty.ts +114 -0
  15. package/backend/containers/runtime.ts +218 -0
  16. package/backend/containers/scan.ts +293 -0
  17. package/backend/files/file-watcher.test.ts +105 -0
  18. package/backend/files/file-watcher.ts +45 -1
  19. package/backend/git/git-service.test.ts +33 -0
  20. package/backend/git/git-service.ts +7 -3
  21. package/backend/git/nested-repos.test.ts +292 -1
  22. package/backend/git/nested-repos.ts +330 -17
  23. package/backend/{ports → host}/runner.ts +19 -10
  24. package/backend/index.ts +11 -2
  25. package/backend/ports/attribute.ts +1 -1
  26. package/backend/ports/kill.ts +1 -1
  27. package/backend/ports/monitor.ts +1 -1
  28. package/backend/ports/processes.ts +1 -1
  29. package/backend/ports/scan-host.ts +77 -8
  30. package/backend/ports/scan.test.ts +1 -1
  31. package/backend/ports/scan.ts +1 -1
  32. package/backend/ports/ssh-lineage.ts +1 -1
  33. package/backend/preview/browser/browser-video-capture.ts +84 -31
  34. package/backend/ws/containers/actions.ts +156 -0
  35. package/backend/ws/containers/index.ts +43 -0
  36. package/backend/ws/containers/list.ts +146 -0
  37. package/backend/ws/containers/logs.ts +43 -0
  38. package/backend/ws/containers/tunnel.ts +101 -0
  39. package/backend/ws/git/log.ts +3 -1
  40. package/backend/ws/git/status.ts +37 -27
  41. package/backend/ws/index.ts +2 -0
  42. package/backend/ws/message-rate-limiter.test.ts +45 -0
  43. package/backend/ws/message-rate-limiter.ts +34 -3
  44. package/backend/ws/ssh/connections.ts +8 -0
  45. package/backend/ws/system/device-info.ts +99 -43
  46. package/dist/assets/{index-vW2RpdHu.js → index-B0iIhSO9.js} +1 -1
  47. package/dist/assets/{index-gGTMFUa8.js → index-BRJqss6F.js} +1 -1
  48. package/dist/assets/main-Buko4D0t.css +1 -0
  49. package/dist/assets/{main-ZCojSzvW.js → main-C_iGUZyL.js} +467 -449
  50. package/dist/index.html +2 -2
  51. package/dist/manifest.json +9 -2
  52. package/package.json +1 -1
  53. package/shared/types/containers/container.ts +366 -0
  54. package/shared/types/containers/index.ts +5 -0
  55. package/shared/types/host/index.ts +18 -0
  56. package/shared/types/ports/port.ts +47 -9
  57. package/shared/utils/logger.ts +2 -0
  58. package/shared/utils/ws-client.ts +67 -12
  59. package/shared/utils/ws-server.ts +64 -13
  60. package/dist/assets/main-CYCMEbXB.css +0 -1
@@ -76,6 +76,221 @@ const IGNORED_DESCENT_LEVELS = 1;
76
76
  /** Depth limit below the project root — a runaway walk helps nobody. */
77
77
  const MAX_DEPTH = 12;
78
78
 
79
+ /**
80
+ * Discovery caching, and who is allowed to decide it is stale.
81
+ *
82
+ * Every `git:status` / `git:branches` used to re-answer "which directories
83
+ * under this root are repos" from scratch: an `fs.readdir` over the whole tree
84
+ * plus a `git check-ignore` spawn per repo per depth level, then one
85
+ * `git status` per repo sitting inside an ignored tree. Measured on a real
86
+ * project that is 132ms and 7 spawns for the walk alone, and the panel fires it
87
+ * three or four times a second while staging. On Windows every spawn and every
88
+ * readdir also pays for Defender, which is what made Stage All look frozen.
89
+ *
90
+ * The answer barely ever changes, and the file watcher already knows exactly
91
+ * when it does. So the watcher, not a clock, is the invalidation authority:
92
+ *
93
+ * - `beginWatchedDiscovery` / `endWatchedDiscovery` — a root is "watched"
94
+ * while a live watcher is feeding it signals.
95
+ * - `invalidateRepoSet` — a `.git` appeared or vanished, or `.gitignore` /
96
+ * `.gitmodules` changed. The set of repos may be different.
97
+ * - `invalidateLocalWork` — something was written inside one repo, so only
98
+ * that repo's "does it have work to show" verdict is suspect.
99
+ *
100
+ * THE SAFETY RULE, which every change here must preserve: **the watcher only
101
+ * ever makes an answer fresher, never staler.** A TTL is always the floor, so
102
+ * losing every signal degrades to re-walking on a timer — never to an answer
103
+ * that is wrong forever. That failure mode is not hypothetical: `resolveGitDirs`
104
+ * decides which git dirs get watched at all and rejects unaccounted-for ones
105
+ * permanently, so one stale walk there took a sub-repo out of the panel for the
106
+ * whole session.
107
+ *
108
+ * The two halves have different exposure, so they are cached separately:
109
+ *
110
+ * - The WALK (which dirs hold a `.git`) is stable, and the signal for it —
111
+ * a `.git` entry appearing — is one the watcher sees reliably on every
112
+ * platform, because the repo's parent directory is watched. Long floor.
113
+ * - LOCAL WORK (whether a repo inside an ignored tree has anything to show)
114
+ * changes with ordinary file writes, and the watcher is blind inside the
115
+ * directories it prunes by name. Cached ONLY for watched roots, where a
116
+ * write lands as an invalidation; an unwatched caller (the snapshot
117
+ * scanner, a CLI path) still probes live, exactly as before. Hiding a
118
+ * sub-repo the user edits is the worst failure this module can produce, so
119
+ * it does not get cached on a guess.
120
+ *
121
+ * What is never cached, at any point: file status. Staged, unstaged, untracked
122
+ * and conflicted entries come from a live `git status` per repo on every call.
123
+ * The Changes tab cannot go stale through this module.
124
+ */
125
+
126
+ /** Floor for a root nobody is invalidating — the clock is the only signal. */
127
+ const UNWATCHED_TTL_MS = process.platform === 'win32' ? 5000 : 3000;
128
+
129
+ /**
130
+ * Floor for a watched root. Long, because the watcher normally invalidates
131
+ * within milliseconds; this only bounds the damage if a signal is ever missed
132
+ * (a platform that drops an event, a watcher that faulted and is restarting).
133
+ */
134
+ const WATCHED_TTL_MS = 60_000;
135
+
136
+ interface WalkEntryCache {
137
+ found: string[];
138
+ provisional: string[];
139
+ expiresAt: number;
140
+ }
141
+
142
+ /** Whether a sub-repo has anything the panel could show. Watched roots only. */
143
+ interface LocalWorkCache {
144
+ hasWork: boolean;
145
+ expiresAt: number;
146
+ }
147
+
148
+ const nestedRepoWalkCache = new Map<string, WalkEntryCache>();
149
+ const nestedRepoInflight = new Map<string, Promise<string[]>>();
150
+ const localWorkCache = new Map<string, LocalWorkCache>();
151
+
152
+ /**
153
+ * Project roots a live file watcher is feeding signals for, and how many
154
+ * watchers are doing so. Refcounted because two projects can be opened at the
155
+ * same directory: without it the first one to close would revoke the claim
156
+ * while the second is still reporting, and discovery would quietly go back to
157
+ * the clock while a perfectly good signal source was still running.
158
+ */
159
+ const watchedRoots = new Map<string, number>();
160
+
161
+ /**
162
+ * The key every cache and the watched-root set is stored under. Callers reach
163
+ * this module from both sides of a `path.normalize()` — the watcher normalises
164
+ * the project path before registering, `git:status` passes `project.path`
165
+ * straight through — and on Windows those differ by separator alone. Keying on
166
+ * the raw string would put them in two entries: the watcher would invalidate
167
+ * one while the panel read the other, silently turning the signal off.
168
+ * Values keep their native separators; only keys are folded.
169
+ */
170
+ function cacheKey(inputPath: string): string {
171
+ return inputPath.replace(/\\/g, '/').replace(/\/+$/, '');
172
+ }
173
+
174
+ /** Whether `candidate` is `base` or sits underneath it. */
175
+ function isUnder(base: string, candidate: string): boolean {
176
+ const baseKey = cacheKey(base);
177
+ const candidateKey = cacheKey(candidate);
178
+ return candidateKey === baseKey || candidateKey.startsWith(baseKey + '/');
179
+ }
180
+
181
+ function isWatched(rootPath: string): boolean {
182
+ return (watchedRoots.get(cacheKey(rootPath)) ?? 0) > 0;
183
+ }
184
+
185
+ function ttlFor(rootPath: string): number {
186
+ return isWatched(rootPath) ? WATCHED_TTL_MS : UNWATCHED_TTL_MS;
187
+ }
188
+
189
+ /**
190
+ * Declare that a live file watcher will report changes for `rootPath`. Until
191
+ * `endWatchedDiscovery`, discovery may lean on those signals instead of the
192
+ * short clock — and `hasLocalWork` verdicts become cacheable at all.
193
+ */
194
+ export function beginWatchedDiscovery(rootPath: string): void {
195
+ const key = cacheKey(rootPath);
196
+ watchedRoots.set(key, (watchedRoots.get(key) ?? 0) + 1);
197
+ }
198
+
199
+ /**
200
+ * The watcher for `rootPath` is gone. Drop everything that was only safe
201
+ * because it was being invalidated, so the next call re-probes live.
202
+ */
203
+ export function endWatchedDiscovery(rootPath: string): void {
204
+ const key = cacheKey(rootPath);
205
+ const remaining = (watchedRoots.get(key) ?? 0) - 1;
206
+ if (remaining > 0) {
207
+ watchedRoots.set(key, remaining);
208
+ return;
209
+ }
210
+ watchedRoots.delete(key);
211
+ nestedRepoWalkCache.delete(key);
212
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
213
+ if (isUnder(rootPath, cachedRepoKey)) localWorkCache.delete(cachedRepoKey);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * The set of repos under `rootPath` may have changed — a `.git` appeared or
219
+ * vanished, or the rules that decide what counts (`.gitignore`, `.gitmodules`)
220
+ * were edited. Forces a fresh walk on the next call.
221
+ */
222
+ export function invalidateRepoSet(rootPath: string): void {
223
+ nestedRepoWalkCache.delete(cacheKey(rootPath));
224
+ }
225
+
226
+ /**
227
+ * Whether a changed path is one that can change WHICH repos are reported, as
228
+ * opposed to what is inside one.
229
+ *
230
+ * These live here rather than in the watcher on purpose. They are facts about
231
+ * the sub-repo policy at the top of this file, not about filesystem events, so
232
+ * extending that policy has to mean editing one place. Splitting them across
233
+ * the two files is what let discovery and its invalidation drift apart in the
234
+ * first place.
235
+ */
236
+ function isRepoSetRule(changedPath: string): boolean {
237
+ const segments = cacheKey(changedPath).split('/');
238
+ const basename = segments[segments.length - 1];
239
+
240
+ // The repository itself appearing or vanishing.
241
+ if (basename === '.git') return true;
242
+
243
+ // Rule (2) and rule (3): what the project ignores, and what it declares.
244
+ if (basename === '.gitignore' || basename === '.gitmodules') return true;
245
+
246
+ // `.git/info/exclude` is a per-repo ignore file `git check-ignore` obeys
247
+ // exactly like `.gitignore`, so it moves the same boundary. The watcher
248
+ // filters it out of the panel's git-state events — correctly, the panel has
249
+ // nothing to show for it — which is precisely why discovery has to ask for
250
+ // it by name instead of riding along with those.
251
+ return (
252
+ basename === 'exclude' &&
253
+ segments[segments.length - 2] === 'info' &&
254
+ segments[segments.length - 3] === '.git'
255
+ );
256
+ }
257
+
258
+ /**
259
+ * A path under `rootPath` changed. The single entry point the file watcher
260
+ * uses: it forwards raw paths and this module decides what each one means, so
261
+ * no caller has to carry a copy of the sub-repo policy.
262
+ *
263
+ * Ignored entirely for a root nobody claimed — an unwatched root caches
264
+ * nothing that a signal could correct, and answering it here would only hide
265
+ * that fact.
266
+ */
267
+ export function notifyPathChanged(rootPath: string, changedPath: string): void {
268
+ if (!isWatched(rootPath)) return;
269
+ if (isRepoSetRule(changedPath)) invalidateRepoSet(rootPath);
270
+ dropLocalWorkUnder(changedPath);
271
+ }
272
+
273
+ /**
274
+ * Something at or under `changedPath` moved, so the "has work to show" verdict
275
+ * of every cached repo containing it is suspect.
276
+ *
277
+ * Matching by containment rather than taking a repo path directly is what makes
278
+ * the important case work. A pristine sub-repo inside an ignored tree is NOT in
279
+ * the watcher's repo list — it is deliberately unreported until it has
280
+ * something to show, so the watcher has never resolved a git dir for it. The
281
+ * transition that must be caught is exactly the first write into it, and at
282
+ * that moment the only place it is known by name is this cache, holding the
283
+ * `false` verdict that is about to become wrong.
284
+ *
285
+ * Still scoped: a write in one sub-repo says nothing about its siblings, and
286
+ * re-probing all of them is the cost this cache exists to avoid.
287
+ */
288
+ function dropLocalWorkUnder(changedPath: string): void {
289
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
290
+ if (isUnder(cachedRepoKey, changedPath)) localWorkCache.delete(cachedRepoKey);
291
+ }
292
+ }
293
+
79
294
  /**
80
295
  * Upper bound on reported sub-repos. A project with more than this is either
81
296
  * pathological or hit a detection hole; either way the UI cannot usefully show
@@ -141,7 +356,7 @@ async function filterIgnored(repoRoot: string, relPaths: string[]): Promise<Set<
141
356
  * A repo we cannot read is reported as having work: hiding a sub-repo the user
142
357
  * edits is a far worse failure than showing one they do not care about.
143
358
  */
144
- async function hasLocalWork(repoPath: string): Promise<boolean> {
359
+ async function probeLocalWork(repoPath: string): Promise<boolean> {
145
360
  try {
146
361
  const result = await execGit(['status', '--porcelain', '-z'], repoPath, { timeout: 15000 });
147
362
  if (result.exitCode !== 0) return true;
@@ -151,6 +366,29 @@ async function hasLocalWork(repoPath: string): Promise<boolean> {
151
366
  }
152
367
  }
153
368
 
369
+ /**
370
+ * `probeLocalWork` with the verdict remembered — but only under a root the
371
+ * watcher is invalidating, where a write inside the repo lands as an
372
+ * `invalidateLocalWork` before anyone can read a stale answer. Unwatched roots
373
+ * probe live every time: this is the verdict that decides whether a sub-repo is
374
+ * shown at all, and a cached "nothing to show" with no signal behind it would
375
+ * hide a repo the user is working in.
376
+ */
377
+ async function hasLocalWork(rootPath: string, repoPath: string): Promise<boolean> {
378
+ if (!isWatched(rootPath)) return probeLocalWork(repoPath);
379
+
380
+ const cached = localWorkCache.get(cacheKey(repoPath));
381
+ if (cached && Date.now() < cached.expiresAt) return cached.hasWork;
382
+
383
+ const hasWork = await probeLocalWork(repoPath);
384
+ // Re-read the flag: the watcher may have stopped while the probe ran, and a
385
+ // verdict nobody will invalidate must not be left behind.
386
+ if (isWatched(rootPath)) {
387
+ localWorkCache.set(cacheKey(repoPath), { hasWork, expiresAt: Date.now() + WATCHED_TTL_MS });
388
+ }
389
+ return hasWork;
390
+ }
391
+
154
392
  /** Whether `dirPath` is a git repo (`.git` is a dir for clones, a file for worktrees/submodules). */
155
393
  async function isRepoDir(dirPath: string): Promise<boolean> {
156
394
  try {
@@ -165,8 +403,76 @@ async function isRepoDir(dirPath: string): Promise<boolean> {
165
403
  * Find every nested git repo under `rootPath`, skipping dependency caches and
166
404
  * ignored trees (see the module comment for the exact policy). Does NOT scan
167
405
  * the repos — just returns their absolute paths, sorted for stable UI order.
406
+ *
407
+ * The filesystem walk is cached for a few seconds (longer on Windows) and
408
+ * concurrent callers for the same root share a single walk via inflight
409
+ * deduplication. The provisional → found filtering is re-run on every call
410
+ * so a newly-dirtied repo appears immediately.
168
411
  */
169
412
  export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
413
+ const cachedWalk = nestedRepoWalkCache.get(cacheKey(rootPath));
414
+ if (cachedWalk && Date.now() < cachedWalk.expiresAt) {
415
+ return resolveProvisional(rootPath, cachedWalk.found, cachedWalk.provisional);
416
+ }
417
+
418
+ // A caller that arrives while a walk is running shares it instead of
419
+ // starting a second one, but gets its own copy of the result: the array
420
+ // goes out to unrelated call sites, and one of them mutating it in place
421
+ // would corrupt the others.
422
+ const inflight = nestedRepoInflight.get(cacheKey(rootPath));
423
+ if (inflight) return [...(await inflight)];
424
+
425
+ const promise = (async (): Promise<string[]> => {
426
+ const walk = await walkNestedRepos(rootPath);
427
+ nestedRepoWalkCache.set(cacheKey(rootPath), {
428
+ found: walk.found,
429
+ provisional: walk.provisional,
430
+ expiresAt: Date.now() + ttlFor(rootPath)
431
+ });
432
+ return resolveProvisional(rootPath, walk.found, walk.provisional);
433
+ })();
434
+
435
+ nestedRepoInflight.set(cacheKey(rootPath), promise);
436
+ try {
437
+ return await promise;
438
+ } finally {
439
+ nestedRepoInflight.delete(cacheKey(rootPath));
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Decide which provisional repos (those found inside an ignored tree) earn a
445
+ * place in the result, and return the sorted list. Deliberately outside the
446
+ * WALK cache: a repo qualifies the moment it gains local work, so a cached walk
447
+ * must never carry a cached verdict with it. The verdicts have their own,
448
+ * signal-backed cache — see `hasLocalWork`.
449
+ */
450
+ async function resolveProvisional(rootPath: string, found: string[], provisional: string[]): Promise<string[]> {
451
+ if (provisional.length === 0) {
452
+ const out = [...found];
453
+ out.sort();
454
+ return out;
455
+ }
456
+ const submodulePaths = await findSubmodulePaths(rootPath);
457
+ const isDeclared = (repoPath: string) =>
458
+ submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
459
+ const verdicts = await Promise.all(
460
+ provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(rootPath, repoPath)))
461
+ );
462
+ const out = [...found];
463
+ provisional.forEach((repoPath, i) => {
464
+ if (verdicts[i]) out.push(repoPath);
465
+ });
466
+ out.sort();
467
+ return out;
468
+ }
469
+
470
+ /**
471
+ * The raw, uncached filesystem walk. Returns repos split into those reportable
472
+ * on structure alone and those still needing to prove local work — the split
473
+ * `findNestedRepoPaths` caches, because only the first half is stable.
474
+ */
475
+ async function walkNestedRepos(rootPath: string): Promise<{ found: string[]; provisional: string[] }> {
170
476
  const found: string[] = [];
171
477
  /** Repos found inside an ignored tree — reported only if they prove local work. */
172
478
  const provisional: string[] = [];
@@ -278,22 +584,7 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
278
584
  debug.warn('git', `Nested repo scan of ${rootPath} stopped at ${MAX_REPOS} repos`);
279
585
  }
280
586
 
281
- if (provisional.length > 0) {
282
- // A submodule is the user declaring the sub-repo themselves, which
283
- // outranks anything we could infer from its working tree.
284
- const submodulePaths = await findSubmodulePaths(rootPath);
285
- const isDeclared = (repoPath: string) =>
286
- submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
287
- const verdicts = await Promise.all(
288
- provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(repoPath)))
289
- );
290
- provisional.forEach((repoPath, i) => {
291
- if (verdicts[i]) found.push(repoPath);
292
- });
293
- }
294
-
295
- found.sort();
296
- return found;
587
+ return { found, provisional };
297
588
  }
298
589
 
299
590
  /**
@@ -347,6 +638,28 @@ export async function findSubmodulePaths(rootPath: string): Promise<Set<string>>
347
638
  return out;
348
639
  }
349
640
 
641
+ /**
642
+ * Drop every cached answer so the next call re-scans and re-probes. Exists for
643
+ * tests, which mutate a project's layout far faster than any TTL and would
644
+ * otherwise assert against the previous fixture. Production code should reach
645
+ * for the targeted `invalidateRepoSet` / `invalidateLocalWork` instead, so one
646
+ * repo's churn does not throw away every other repo's answer.
647
+ */
648
+ export function clearNestedRepoCache(rootPath?: string): void {
649
+ if (rootPath) {
650
+ nestedRepoWalkCache.delete(cacheKey(rootPath));
651
+ nestedRepoInflight.delete(cacheKey(rootPath));
652
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
653
+ if (isUnder(rootPath, cachedRepoKey)) localWorkCache.delete(cachedRepoKey);
654
+ }
655
+ } else {
656
+ nestedRepoWalkCache.clear();
657
+ nestedRepoInflight.clear();
658
+ localWorkCache.clear();
659
+ watchedRoots.clear();
660
+ }
661
+ }
662
+
350
663
  /**
351
664
  * Given a file path relative to the project root, find the deepest nested
352
665
  * git repo that contains it. Returns the repo's absolute path and the file
@@ -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}`);
@@ -339,6 +345,9 @@ async function gracefulShutdown() {
339
345
  uploadTempCleanup.dispose();
340
346
  // Stop port polling and release any SSH leases it holds
341
347
  portMonitor.stop();
348
+ // Same for the container list, and the log streams it may still be pumping
349
+ stopAllContainerLogStreams();
350
+ containerMonitor.stop();
342
351
  // Close MCP remote server (before engines, as they may still reference it)
343
352
  await closeMcpServer();
344
353
  // Cleanup browser preview sessions
@@ -22,7 +22,7 @@
22
22
  */
23
23
 
24
24
  import type { PortOrigin, PortProcess, PortSocket } from '$shared/types/ports';
25
- import type { ProbePlatform } from './runner';
25
+ import type { ProbePlatform } from '../host/runner';
26
26
  import { ptyKitManager } from '../terminal/ptykit';
27
27
  import { projectQueries } from '../database/queries';
28
28
  import { collectOwnedPorts, ownedPortKey, type OwnedPort } from './registry';
@@ -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 {
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
- import type { CommandRunner } from './runner';
2
+ import type { CommandRunner } from '../host/runner';
3
3
  import {
4
4
  parseLsof,
5
5
  parseNetstatUnix,