@myrialabs/clopen 0.4.31 → 0.4.33

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 (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -13,6 +13,8 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
13
  import type { z } from "zod";
14
14
  import { projectContextService } from '../project-context';
15
15
  import { validateMcpOutput } from '../output-validator';
16
+ import type { McpExecutionContext } from '$backend/engine/types';
17
+ import type { EngineType } from '$shared/types/unified';
16
18
 
17
19
  /**
18
20
  * Infer argument types from Zod schema
@@ -143,6 +145,21 @@ export function buildServerRegistries<
143
145
  // Remote MCP Server for Open Code (HTTP transport, in-process execution)
144
146
  // ============================================================================
145
147
 
148
+ /**
149
+ * Who the bridge is talking to.
150
+ *
151
+ * `context` is the calling stream, named by the query string its engine's
152
+ * config builder put on the bridge URL — the HTTP equivalent of the
153
+ * `McpExecutionContext` the in-process engines bind directly. `engine` alone is
154
+ * the fallback for a config that cannot name the caller (Open Code's pooled
155
+ * server), and is resolved per call rather than pinned, because the stream it
156
+ * refers to changes while the MCP session stays open.
157
+ */
158
+ export interface RemoteMcpCaller {
159
+ context?: McpExecutionContext;
160
+ engine?: EngineType;
161
+ }
162
+
146
163
  /**
147
164
  * Create a McpServer instance (from @modelcontextprotocol/sdk) with tools registered
148
165
  * from the same RawToolDef definitions used by Claude Code.
@@ -152,10 +169,12 @@ export function buildServerRegistries<
152
169
  *
153
170
  * @param servers - Server definitions from defineServer()
154
171
  * @param enabledConfig - Which servers/tools are enabled (from mcpServersConfig)
172
+ * @param caller - Identity of the engine/stream on the other end of the bridge
155
173
  */
156
174
  export function createRemoteMcpServer(
157
175
  servers: readonly ServerWithMeta<string, readonly string[]>[],
158
- enabledConfig: Record<string, { enabled: boolean; tools: readonly string[] }>
176
+ enabledConfig: Record<string, { enabled: boolean; tools: readonly string[] }>,
177
+ caller?: RemoteMcpCaller
159
178
  ): McpServer {
160
179
  const mcpServer = new McpServer({
161
180
  name: 'clopen-mcp',
@@ -178,23 +197,34 @@ export function createRemoteMcpServer(
178
197
  // at runtime. Cast to bridge the mismatch.
179
198
  inputSchema: def.schema as Record<string, any>,
180
199
  }, async (args: Record<string, unknown>) => {
181
- // Fast-fail when the owning chat stream has already been
182
- // cancelled — the handler never runs. Without this, the
183
- // engine subprocess dies on cancel but in-flight HTTP-MCP
184
- // tool calls continue to drive puppeteer ops, surfacing as
185
- // "preview keeps moving by itself" after interrupt.
186
- const signal = projectContextService.getCurrentSignal();
187
- if (signal?.aborted) {
188
- return {
189
- content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
190
- isError: true,
191
- } as any;
192
- }
193
- const result = await def.handler(args) as any;
194
- if (result?.content) {
195
- result.content = validateMcpOutput(result.content, toolName as string);
196
- }
197
- return result;
200
+ const run = async () => {
201
+ // Fast-fail when the owning chat stream has already been
202
+ // cancelled — the handler never runs. Without this, the
203
+ // engine subprocess dies on cancel but in-flight HTTP-MCP
204
+ // tool calls continue to drive puppeteer ops, surfacing as
205
+ // "preview keeps moving by itself" after interrupt.
206
+ const signal = projectContextService.getCurrentSignal();
207
+ if (signal?.aborted) {
208
+ return {
209
+ content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
210
+ isError: true,
211
+ } as any;
212
+ }
213
+ const result = await def.handler(args) as any;
214
+ if (result?.content) {
215
+ result.content = validateMcpOutput(result.content, toolName as string);
216
+ }
217
+ return result;
218
+ };
219
+
220
+ // Bind the caller for the duration of the handler, exactly as the
221
+ // in-process path does. Without it every handler that asks "which
222
+ // project is this?" answers with the most recently started stream
223
+ // anywhere in the app.
224
+ const bound = caller?.context
225
+ ?? (caller?.engine ? projectContextService.getContextForEngine(caller.engine) : undefined);
226
+
227
+ return bound ? projectContextService.runWithContextAsync(bound, run) : run();
198
228
  });
199
229
  }
200
230
  }
@@ -169,6 +169,13 @@ interface VideoStreamSession {
169
169
  lastEncodedAt: number;
170
170
  /** Guards the watchdog against re-entering while a repair is in flight. */
171
171
  repairing: boolean;
172
+ /**
173
+ * Repairs attempted since the stream last produced anything. A repair that
174
+ * did not restore frames must escalate rather than be repeated: the cheap
175
+ * one asks the page what it thinks, and a page whose own answer is the
176
+ * wrong one will give the same answer every time.
177
+ */
178
+ stallRounds: number;
172
179
  /** Codecs every viewer can decode — one encoder serves them all. */
173
180
  codecSupport: ClientCodecSupport;
174
181
  /** Display metrics of the most demanding viewer. */
@@ -587,6 +594,12 @@ export class BrowserVideoCapture extends EventEmitter {
587
594
  */
588
595
  private static readonly STREAM_STALL_MS = 6_000;
589
596
 
597
+ /**
598
+ * Cheap stall repairs before the watchdog stops taking the page's word for
599
+ * its own health and rebuilds the peer from scratch.
600
+ */
601
+ private static readonly STALL_REPAIR_ROUNDS = 1;
602
+
590
603
  private sessions = new Map<string, VideoStreamSession>();
591
604
  private feeders = new Map<string, ScreencastFeeder>();
592
605
  private preInjectPromises = new Map<string, Promise<boolean>>();
@@ -729,6 +742,7 @@ export class BrowserVideoCapture extends EventEmitter {
729
742
  scriptsPreInjected: false,
730
743
  lastEncodedAt: 0,
731
744
  repairing: false,
745
+ stallRounds: 0,
732
746
  codecSupport: { ...DEFAULT_CODEC_SUPPORT },
733
747
  display: {},
734
748
  profile,
@@ -978,6 +992,20 @@ export class BrowserVideoCapture extends EventEmitter {
978
992
  const codecChanged = injection.codecSignature !== this.codecSignature(videoSession);
979
993
  const needsInjection = epochMismatch || codecChanged;
980
994
 
995
+ // In push mode the page is only the encoder — the frames come from a CDP
996
+ // screencast this process owns. `capturing: true` then means "willing",
997
+ // not "being fed", so a feeder that has gone away leaves a session both
998
+ // halves call healthy and which produces nothing at all. That state is
999
+ // self-sustaining: the page keeps answering, so this check keeps taking
1000
+ // the cheap branch, and the viewer keeps waiting for a first frame that
1001
+ // no longer has a source.
1002
+ const sourceMissing =
1003
+ !needsInjection &&
1004
+ !!health?.capturing &&
1005
+ health.captureMode === 'push' &&
1006
+ !videoSession.paused &&
1007
+ !this.feeders.has(sessionId);
1008
+
981
1009
  if (needsInjection) {
982
1010
  const reason = options.force
983
1011
  ? 'forced'
@@ -993,7 +1021,10 @@ export class BrowserVideoCapture extends EventEmitter {
993
1021
  this.feeders.get(sessionId)?.invalidatePeerHandle();
994
1022
  }
995
1023
 
996
- if (needsInjection || !health?.capturing) {
1024
+ if (needsInjection || !health?.capturing || sourceMissing) {
1025
+ if (sourceMissing) {
1026
+ debug.warn('webcodecs', `Page for ${sessionId} reports capturing with no frame source — rebuilding it`);
1027
+ }
997
1028
  const started = await this.startPageCapture(page);
998
1029
  if (!started) {
999
1030
  debug.error('webcodecs', `Page refused to start capturing for ${sessionId}`);
@@ -1593,10 +1624,23 @@ export class BrowserVideoCapture extends EventEmitter {
1593
1624
  if (videoSession.lastEncodedAt === 0 || silentFor < BrowserVideoCapture.STREAM_STALL_MS) return;
1594
1625
 
1595
1626
  const { sessionId, tab } = videoSession;
1596
- debug.warn('webcodecs', `Stream for ${sessionId} produced nothing for ${silentFor}ms — repairing`);
1627
+ videoSession.stallRounds++;
1628
+
1629
+ // The first round asks the page what state it is in and repairs from
1630
+ // that answer, which is cheap and keeps every viewer's peer intact. Once
1631
+ // that has been tried and the stream is still silent, the page's own
1632
+ // account is the thing that cannot be trusted — so rebuild the peer
1633
+ // outright. Viewers lose their connection and re-handshake, which is a
1634
+ // visible hiccup, but they are looking at a frozen picture either way.
1635
+ const force = videoSession.stallRounds > BrowserVideoCapture.STALL_REPAIR_ROUNDS;
1636
+ debug.warn(
1637
+ 'webcodecs',
1638
+ `Stream for ${sessionId} produced nothing for ${silentFor}ms — ` +
1639
+ `${force ? 'rebuilding the page peer' : 'repairing'} (round ${videoSession.stallRounds})`
1640
+ );
1597
1641
 
1598
1642
  videoSession.repairing = true;
1599
- void this.ensureLive(sessionId, tab, () => !tab.isDestroyed)
1643
+ void this.ensureLive(sessionId, tab, () => !tab.isDestroyed, { force })
1600
1644
  .then((live) => {
1601
1645
  if (live) return this.requestKeyframe(sessionId, tab);
1602
1646
  })
@@ -1620,7 +1664,10 @@ export class BrowserVideoCapture extends EventEmitter {
1620
1664
  // Frames reaching the encoder is the one signal that means the pipeline
1621
1665
  // is genuinely alive end to end. The counter is per-window, so any
1622
1666
  // non-zero report is proof of life for this window.
1623
- if (stats.framesAttempted > 0) videoSession.lastEncodedAt = Date.now();
1667
+ if (stats.framesAttempted > 0) {
1668
+ videoSession.lastEncodedAt = Date.now();
1669
+ videoSession.stallRounds = 0;
1670
+ }
1624
1671
 
1625
1672
  // In-page capture can end on its own — the captured surface goes away
1626
1673
  // on some navigations — and the page has no way to start a screencast.
@@ -12,6 +12,7 @@ import fs from 'fs/promises';
12
12
  import path from 'path';
13
13
  import { debug } from '$shared/utils/logger';
14
14
  import { execGit } from '../git/git-executor';
15
+ import { findNestedRepoPaths } from '../git/nested-repos';
15
16
 
16
17
  /**
17
18
  * Safety-net directories to always exclude regardless of .gitignore.
@@ -22,137 +23,6 @@ const ALWAYS_EXCLUDE_DIRS = new Set([
22
23
  'node_modules',
23
24
  ]);
24
25
 
25
- /**
26
- * Find paths of all nested git repos (directories with their own `.git`) at any
27
- * depth under `rootPath`. Walks into nested repos to find deeply nested ones.
28
- * Does NOT scan the repos — just returns their absolute paths.
29
- *
30
- * Used by callers that need to run git commands inside each nested repo
31
- * (e.g. `git:status` aggregating changes from nested repos into the Changes
32
- * tab of the Git panel).
33
- */
34
- export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
35
- const paths: string[] = [];
36
-
37
- const walk = async (currentPath: string): Promise<void> => {
38
- let entries;
39
- try {
40
- entries = await fs.readdir(currentPath, { withFileTypes: true });
41
- } catch {
42
- return;
43
- }
44
-
45
- for (const entry of entries) {
46
- if (!entry.isDirectory()) continue;
47
- if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
48
-
49
- const fullPath = path.join(currentPath, entry.name);
50
-
51
- // Check if this directory is itself a git repo
52
- try {
53
- await fs.access(path.join(fullPath, '.git'));
54
- paths.push(fullPath);
55
- // Fall through to also walk into it for deeper nested repos
56
- } catch {
57
- // Not a git repo
58
- }
59
-
60
- await walk(fullPath);
61
- }
62
- };
63
-
64
- await walk(rootPath);
65
- return paths;
66
- }
67
-
68
- /**
69
- * Read the outer repo's `.gitmodules` file and return the set of relative
70
- * submodule paths. Returns an empty set when the file is missing or unreadable
71
- * (e.g. the project isn't a git repo at all, or has no submodules).
72
- *
73
- * The format is INI-like:
74
- * [submodule "vendor/foo"]
75
- * path = vendor/foo
76
- * url = git@example.com:vendor/foo.git
77
- *
78
- * The `path =` value is what we return — the directory inside the project root
79
- * where the submodule is checked out. If a section omits `path =`, git falls
80
- * back to the section name; we mirror that.
81
- */
82
- export async function findSubmodulePaths(rootPath: string): Promise<Set<string>> {
83
- const out = new Set<string>();
84
- let raw: string;
85
- try {
86
- raw = await fs.readFile(path.join(rootPath, '.gitmodules'), 'utf8');
87
- } catch {
88
- return out; // file missing → no submodules
89
- }
90
-
91
- // Two-pass parse: collect per-section { name, path? } then resolve.
92
- // Single-pass is simpler but needs careful handling of the implicit
93
- // section-name fallback; the two-pass version reads more clearly.
94
- const sections: Array<{ name: string; path?: string }> = [];
95
- let current: { name: string; path?: string } | null = null;
96
- for (const line of raw.split(/\r?\n/)) {
97
- const trimmed = line.trim();
98
- if (!trimmed || trimmed.startsWith('#')) continue;
99
-
100
- const sectionMatch = trimmed.match(/^\[submodule\s+"([^"]+)"\]\s*$/);
101
- if (sectionMatch) {
102
- if (current) sections.push(current);
103
- current = { name: sectionMatch[1] };
104
- continue;
105
- }
106
- if (!current) continue;
107
-
108
- const pathMatch = trimmed.match(/^path\s*=\s*(.+?)\s*$/);
109
- if (pathMatch) current.path = pathMatch[1].replace(/\\/g, '/');
110
- }
111
- if (current) sections.push(current);
112
-
113
- for (const s of sections) {
114
- out.add(s.path ?? s.name);
115
- }
116
- return out;
117
- }
118
-
119
- /**
120
- * Given a file path relative to the project root, find the deepest nested
121
- * git repo that contains it. Returns the repo's absolute path and the file
122
- * path relative to that repo, or `null` if the file lives in the outer repo.
123
- *
124
- * Used by git staging/discard handlers so that `git add` / `git restore` /
125
- * `git rm` run inside the correct repo (the outer repo's `git` would skip
126
- * or fail on files that are tracked by a nested repo).
127
- */
128
- export async function findRepoForFile(
129
- projectPath: string,
130
- filePath: string
131
- ): Promise<{ repoPath: string; relativeFilePath: string } | null> {
132
- const normalizedFilePath = filePath.replace(/\\/g, '/');
133
- const nestedRepoPaths = await findNestedRepoPaths(projectPath);
134
-
135
- let bestMatch: { repoPath: string; relativeFilePath: string } | null = null;
136
- let bestRepoRelLen = -1;
137
-
138
- for (const repoPath of nestedRepoPaths) {
139
- const repoRel = path.relative(projectPath, repoPath).replace(/\\/g, '/');
140
- // File is inside this repo if its path starts with `repoRel/`
141
- if (normalizedFilePath === repoRel || normalizedFilePath.startsWith(repoRel + '/')) {
142
- if (repoRel.length > bestRepoRelLen) {
143
- bestMatch = {
144
- repoPath,
145
- relativeFilePath: normalizedFilePath === repoRel
146
- ? ''
147
- : normalizedFilePath.substring(repoRel.length + 1)
148
- };
149
- bestRepoRelLen = repoRel.length;
150
- }
151
- }
152
- }
153
-
154
- return bestMatch;
155
- }
156
26
 
157
27
  /**
158
28
  * Get list of snapshot-eligible files using git (preferred) or manual scan.
@@ -236,52 +106,18 @@ async function scanSingleGitRepo(dirPath: string): Promise<string[]> {
236
106
  }
237
107
 
238
108
  /**
239
- * Walk the project tree to find nested git repos (directories with their own
240
- * `.git`) and scan each one independently. This catches nested repos that are
241
- * gitignored by the parent — they'd otherwise be invisible to the outer repo's
242
- * `git ls-files --exclude-standard`.
243
- *
244
- * The walk respects ALWAYS_EXCLUDE_DIRS (skips `.git`, `node_modules`) but does
245
- * NOT respect .gitignore, because the nested repo we're looking for may itself
246
- * be gitignored by the parent. Once a nested repo is found, its own
247
- * `git ls-files --exclude-standard` handles its .gitignore rules.
109
+ * Scan every nested git repo inside the project and return their files.
110
+ * Discovery is delegated to `findNestedRepoPaths` — the same source of truth
111
+ * the Git panel uses — so a repo the panel shows is a repo the snapshot
112
+ * captures, and a package-manager checkout neither of them touches. Each repo
113
+ * is then scanned with its own `git ls-files --exclude-standard`, which applies
114
+ * that repo's .gitignore rules.
248
115
  */
249
116
  async function findAndScanNestedRepos(rootPath: string): Promise<string[]> {
250
117
  const files: string[] = [];
251
-
252
- const walk = async (currentPath: string): Promise<void> => {
253
- let entries;
254
- try {
255
- entries = await fs.readdir(currentPath, { withFileTypes: true });
256
- } catch {
257
- return;
258
- }
259
-
260
- for (const entry of entries) {
261
- if (!entry.isDirectory()) continue;
262
- if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
263
-
264
- const fullPath = path.join(currentPath, entry.name);
265
-
266
- // Check if this directory is itself a git repo (`.git` can be a
267
- // directory or a file — the latter for worktrees/submodules).
268
- try {
269
- await fs.access(path.join(fullPath, '.git'));
270
- // Nested repo found — scan it independently, then continue
271
- // walking into it to find even deeper nested repos.
272
- const nestedFiles = await scanSingleGitRepo(fullPath);
273
- files.push(...nestedFiles);
274
- await walk(fullPath);
275
- continue;
276
- } catch {
277
- // Not a git repo — recurse to find deeper nested repos
278
- }
279
-
280
- await walk(fullPath);
281
- }
282
- };
283
-
284
- await walk(rootPath);
118
+ for (const repoPath of await findNestedRepoPaths(rootPath)) {
119
+ files.push(...await scanSingleGitRepo(repoPath));
120
+ }
285
121
  return files;
286
122
  }
287
123
 
@@ -0,0 +1,196 @@
1
+ /**
2
+ * ssh-client — one live ssh2 client per saved connection, shared by everything.
3
+ *
4
+ * SSH multiplexes channels over a single transport, so a host's terminal tabs,
5
+ * its file browser and its port forwards all ride one authenticated connection
6
+ * — the user authenticates once, not once per feature.
7
+ *
8
+ * Leases decide when that connection may close. A terminal tab or a running
9
+ * forward holds a lease for as long as it lives; a one-shot SFTP call holds one
10
+ * for the length of the call. An entry with no leases is swept after IDLE_MS.
11
+ */
12
+
13
+ import type { Client as SshClient } from 'ssh2';
14
+ import { sshConnectionQueries } from '../database/queries';
15
+ import { closeChain, dial, type DialResult } from './connect';
16
+ import { debug } from '$shared/utils/logger';
17
+
18
+ /** How long a lease-free connection stays warm before being dropped. */
19
+ const IDLE_MS = 60 * 1000;
20
+ const SWEEP_INTERVAL_MS = 30 * 1000;
21
+
22
+ interface PoolEntry {
23
+ dialed: DialResult;
24
+ leases: number;
25
+ lastUsedAt: number;
26
+ alive: boolean;
27
+ }
28
+
29
+ export interface SshLease {
30
+ client: SshClient;
31
+ /** Release this lease. Idempotent — calling it twice does not double-count. */
32
+ release(): void;
33
+ }
34
+
35
+ class SshClientPool {
36
+ private entries = new Map<string, PoolEntry>();
37
+ private pending = new Map<string, Promise<PoolEntry>>();
38
+ /**
39
+ * Hosts the user explicitly disconnected. The pool dials on demand, so
40
+ * without this a "Disconnect" would be undone by the next keystroke in a
41
+ * terminal or click in the file browser — the button has to actually mean
42
+ * something. Runtime-only: a restart starts every host reconnectable.
43
+ */
44
+ private suspended = new Set<string>();
45
+ private sweeperHandle: ReturnType<typeof setInterval> | null = null;
46
+
47
+ private startSweeper(): void {
48
+ if (this.sweeperHandle) return;
49
+ this.sweeperHandle = setInterval(() => this.sweepIdle(), SWEEP_INTERVAL_MS);
50
+ // Don't keep the process alive just for this timer.
51
+ (this.sweeperHandle as unknown as { unref?: () => void }).unref?.();
52
+ }
53
+
54
+ private async openEntry(connectionId: string): Promise<PoolEntry> {
55
+ const connection = sshConnectionQueries.get(connectionId);
56
+ if (!connection) throw new Error('ssh connection not found');
57
+
58
+ const dialed = await dial(connection);
59
+ const entry: PoolEntry = { dialed, leases: 0, lastUsedAt: Date.now(), alive: true };
60
+
61
+ // A dropped transport must not be handed to the next caller. Mark the
62
+ // entry dead and drop it so the following acquire dials fresh.
63
+ const invalidate = (): void => {
64
+ if (!entry.alive) return;
65
+ entry.alive = false;
66
+ if (this.entries.get(connectionId) === entry) {
67
+ this.entries.delete(connectionId);
68
+ }
69
+ debug.log('ssh', `connection ${connectionId} closed`);
70
+ };
71
+ dialed.client.on('close', invalidate);
72
+ dialed.client.on('end', invalidate);
73
+ dialed.client.on('error', (error: Error) => {
74
+ debug.warn('ssh', `connection ${connectionId} error: ${error.message}`);
75
+ invalidate();
76
+ });
77
+
78
+ sshConnectionQueries.markUsed(connectionId);
79
+ return entry;
80
+ }
81
+
82
+ /**
83
+ * Take a lease on the connection, dialing it if needed. Concurrent callers
84
+ * for the same host share one dial rather than racing two handshakes.
85
+ */
86
+ async acquire(connectionId: string): Promise<SshLease> {
87
+ if (this.suspended.has(connectionId)) {
88
+ throw new Error('This host is disconnected — use Connect to open it again');
89
+ }
90
+ this.startSweeper();
91
+
92
+ const existing = this.entries.get(connectionId);
93
+ if (existing?.alive) {
94
+ return this.leaseOf(connectionId, existing);
95
+ }
96
+
97
+ let inFlight = this.pending.get(connectionId);
98
+ if (!inFlight) {
99
+ inFlight = this.openEntry(connectionId).finally(() => this.pending.delete(connectionId));
100
+ this.pending.set(connectionId, inFlight);
101
+ }
102
+
103
+ const entry = await inFlight;
104
+ // Another caller's dial may already be registered; prefer whichever entry
105
+ // is live so both callers end up on the same transport.
106
+ const current = this.entries.get(connectionId);
107
+ if (current?.alive && current !== entry) {
108
+ closeChain(entry.dialed.chain);
109
+ return this.leaseOf(connectionId, current);
110
+ }
111
+ this.entries.set(connectionId, entry);
112
+ return this.leaseOf(connectionId, entry);
113
+ }
114
+
115
+ private leaseOf(connectionId: string, entry: PoolEntry): SshLease {
116
+ entry.leases++;
117
+ entry.lastUsedAt = Date.now();
118
+ let released = false;
119
+ return {
120
+ client: entry.dialed.client,
121
+ release: () => {
122
+ if (released) return;
123
+ released = true;
124
+ entry.leases = Math.max(0, entry.leases - 1);
125
+ entry.lastUsedAt = Date.now();
126
+ debug.log('ssh', `lease released for ${connectionId} (${entry.leases} remaining)`);
127
+ }
128
+ };
129
+ }
130
+
131
+ /** Run one operation under a lease, releasing it even if the operation throws. */
132
+ async use<T>(connectionId: string, operation: (client: SshClient) => Promise<T>): Promise<T> {
133
+ const lease = await this.acquire(connectionId);
134
+ try {
135
+ return await operation(lease.client);
136
+ } finally {
137
+ lease.release();
138
+ }
139
+ }
140
+
141
+ /** True when the host currently has a live, authenticated transport. */
142
+ isLive(connectionId: string): boolean {
143
+ return this.entries.get(connectionId)?.alive === true;
144
+ }
145
+
146
+ /** True when the user disconnected this host and has not reconnected it. */
147
+ isSuspended(connectionId: string): boolean {
148
+ return this.suspended.has(connectionId);
149
+ }
150
+
151
+ /** Close the host and refuse to redial it until `resume` is called. */
152
+ suspend(connectionId: string): void {
153
+ this.suspended.add(connectionId);
154
+ this.release(connectionId);
155
+ }
156
+
157
+ /** Allow the host to be dialed again. */
158
+ resume(connectionId: string): void {
159
+ this.suspended.delete(connectionId);
160
+ }
161
+
162
+ /** Close a host's transport now, whatever its leases. Used on edit and delete. */
163
+ release(connectionId: string): void {
164
+ const entry = this.entries.get(connectionId);
165
+ if (!entry) return;
166
+ this.entries.delete(connectionId);
167
+ entry.alive = false;
168
+ closeChain(entry.dialed.chain);
169
+ }
170
+
171
+ private sweepIdle(): void {
172
+ const now = Date.now();
173
+ for (const [connectionId, entry] of this.entries) {
174
+ if (entry.leases > 0) continue;
175
+ if (!entry.alive || now - entry.lastUsedAt > IDLE_MS) {
176
+ debug.log('ssh', `idle sweep: closing ${connectionId}`);
177
+ this.entries.delete(connectionId);
178
+ entry.alive = false;
179
+ closeChain(entry.dialed.chain);
180
+ }
181
+ }
182
+ }
183
+
184
+ closeAll(): void {
185
+ this.suspended.clear();
186
+ for (const connectionId of [...this.entries.keys()]) {
187
+ this.release(connectionId);
188
+ }
189
+ if (this.sweeperHandle) {
190
+ clearInterval(this.sweeperHandle);
191
+ this.sweeperHandle = null;
192
+ }
193
+ }
194
+ }
195
+
196
+ export const sshClientPool = new SshClientPool();