@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
@@ -42,7 +42,7 @@ import {
42
42
  mapToolName,
43
43
  TOOL_NAME_MAP,
44
44
  } from './message-converter';
45
- import { ensureClient, acquireServer, releaseServer, getClient, getServerUrl, type ServerInstance } from './server';
45
+ import { ensureClient, acquireServer, releaseServer, getDefaultServer, type ServerInstance } from './server';
46
46
  import { syncSkills } from '$backend/skills';
47
47
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
48
48
  import { artifactFilter } from '$backend/profiles';
@@ -887,7 +887,7 @@ export class OpenCodeEngine implements AIEngine {
887
887
  // The pool hold is still held here on purpose — handing the server back
888
888
  // first could let it be reaped out from under this very call.
889
889
  for (const run of targets) {
890
- const client = run.server?.client ?? getClient();
890
+ const client = run.server?.client ?? getDefaultServer()?.client;
891
891
  const { sessionId, projectPath } = run;
892
892
  if (!client || !sessionId) continue;
893
893
  try {
@@ -948,8 +948,8 @@ export class OpenCodeEngine implements AIEngine {
948
948
  * POST /question/{requestID}/reply to send user answers back to the OpenCode server.
949
949
  */
950
950
  private replyToQuestion(run: OpenCodeRun | null, requestId: string, orderedAnswers: string[][]): void {
951
- const serverUrl = run?.server?.url ?? getServerUrl();
952
- if (!serverUrl) {
951
+ const server = run?.server ?? getDefaultServer();
952
+ if (!server) {
953
953
  debug.warn('engine', 'replyToQuestion: Server URL not available');
954
954
  return;
955
955
  }
@@ -959,12 +959,12 @@ export class OpenCodeEngine implements AIEngine {
959
959
  // a shared "current server" would post this reply into the wrong one and
960
960
  // leave the asking session waiting forever.
961
961
  const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
962
- const url = `${serverUrl}/question/${requestId}/reply${dirParam}`;
962
+ const url = `${server.url}/question/${requestId}/reply${dirParam}`;
963
963
  debug.log('engine', `Replying to question ${requestId}:`, orderedAnswers);
964
964
 
965
965
  fetch(url, {
966
966
  method: 'POST',
967
- headers: { 'Content-Type': 'application/json' },
967
+ headers: { 'Content-Type': 'application/json', ...server.authHeaders },
968
968
  body: JSON.stringify({ answers: orderedAnswers }),
969
969
  }).then(async res => {
970
970
  if (res.ok) {
@@ -986,15 +986,15 @@ export class OpenCodeEngine implements AIEngine {
986
986
  // still-running one when there is exactly one, else the shared client.
987
987
  const running = this.runs.all();
988
988
  const run = running.length === 1 ? running[0] : null;
989
- const serverUrl = run?.server?.url ?? getServerUrl();
990
- if (!serverUrl) {
989
+ const server = run?.server ?? getDefaultServer();
990
+ if (!server) {
991
991
  debug.warn('engine', 'fetchAndReplyToQuestion: Server URL not available');
992
992
  return;
993
993
  }
994
994
 
995
995
  try {
996
996
  const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
997
- const res = await fetch(`${serverUrl}/question${dirParam}`);
997
+ const res = await fetch(`${server.url}/question${dirParam}`, { headers: server.authHeaders });
998
998
  if (!res.ok) {
999
999
  debug.error('engine', `Failed to list pending questions: ${res.status}`);
1000
1000
  return;
@@ -1029,14 +1029,14 @@ export class OpenCodeEngine implements AIEngine {
1029
1029
  * the v2 permission.reply method.
1030
1030
  */
1031
1031
  private replyPermission(run: OpenCodeRun, permissionId: string, sessionId: string, response: 'once' | 'reject'): void {
1032
- const serverUrl = run.server?.url ?? getServerUrl();
1033
- if (!serverUrl) return;
1032
+ const server = run.server ?? getDefaultServer();
1033
+ if (!server) return;
1034
1034
  const verb = response === 'reject' ? 'rejected' : 'approved';
1035
1035
 
1036
1036
  // Try v2 endpoint first (/permission/{requestID}/reply), fall back to v1
1037
- fetch(`${serverUrl}/permission/${permissionId}/reply`, {
1037
+ fetch(`${server.url}/permission/${permissionId}/reply`, {
1038
1038
  method: 'POST',
1039
- headers: { 'Content-Type': 'application/json' },
1039
+ headers: { 'Content-Type': 'application/json', ...server.authHeaders },
1040
1040
  body: JSON.stringify({ reply: response }),
1041
1041
  }).then(res => {
1042
1042
  if (res.ok) {
@@ -1044,7 +1044,7 @@ export class OpenCodeEngine implements AIEngine {
1044
1044
  return;
1045
1045
  }
1046
1046
  // v2 endpoint not available — try v1
1047
- const client = run.server?.client ?? getClient();
1047
+ const client = run.server?.client ?? getDefaultServer()?.client;
1048
1048
  if (client) {
1049
1049
  client.postSessionIdPermissionsPermissionId({
1050
1050
  path: { id: sessionId, permissionID: permissionId },
@@ -34,6 +34,8 @@ import {
34
34
  acquireServer,
35
35
  pooledScopeKeys,
36
36
  reconcileServerHolders,
37
+ revalidatePool,
38
+ setLiveStreamSource,
37
39
  DEFAULT_SCOPE_KEY,
38
40
  } from './adapters/opencode/server';
39
41
  import { debug } from '$shared/utils/logger';
@@ -51,7 +53,6 @@ let started = false;
51
53
  * talk to a server anyway.
52
54
  */
53
55
  async function warmDefaultScope(): Promise<void> {
54
- if (!pooledScopeKeys().includes(DEFAULT_SCOPE_KEY)) return;
55
56
  try {
56
57
  await acquireServer({});
57
58
  debug.log('engine', 'Open Code default server re-warmed for the new config');
@@ -71,6 +72,10 @@ export function startEngineHotReload(): void {
71
72
  if (started) return;
72
73
  started = true;
73
74
 
75
+ // The pool sweeps itself on a timer; this is where it learns which holds are
76
+ // still backed by a running stream.
77
+ setLiveStreamSource(() => new Set(streamManager.getActiveStreams().map(s => s.streamId)));
78
+
74
79
  onEngineConfigChanged(revision => {
75
80
  // Holder bookkeeping is reconciled against the live stream set first, so
76
81
  // "is anything running" and "is this server still needed" are answered from
@@ -83,16 +88,26 @@ export function startEngineHotReload(): void {
83
88
  // that is mid-answer.
84
89
  retireAllEngines();
85
90
 
86
- if (liveStreams.length > 0) {
87
- debug.log(
88
- 'engine',
89
- `Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
90
- 'applying it to the next turn and draining the old server behind them'
91
- );
92
- return;
93
- }
91
+ // Read BEFORE revalidating: revalidation is what makes the outgoing default
92
+ // server reapable, so asking afterwards would report the scope as unused
93
+ // and skip the warm-up on exactly the change that needs it.
94
+ const defaultScopeInUse = pooledScopeKeys().includes(DEFAULT_SCOPE_KEY);
94
95
 
95
- void warmDefaultScope();
96
+ // Re-resolve every pooled scope's key, not just the default one. A Profile
97
+ // server is otherwise still its own scope's current key, so it is neither
98
+ // superseded nor idle and goes on serving the config — and the credentials —
99
+ // that were just replaced. Held servers are unaffected: they are pinned.
100
+ void revalidatePool().then(() => {
101
+ if (liveStreams.length > 0) {
102
+ debug.log(
103
+ 'engine',
104
+ `Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
105
+ 'applying it to the next turn and draining the old server behind them'
106
+ );
107
+ return;
108
+ }
109
+ if (defaultScopeInUse) return warmDefaultScope();
110
+ });
96
111
  });
97
112
 
98
113
  debug.log('engine', 'Engine hot-reload active');
@@ -10,6 +10,9 @@
10
10
 
11
11
  import { describe, expect, mock, test, beforeAll, afterEach } from 'bun:test';
12
12
  import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
13
+ import { execGit } from '../git/git-executor';
14
+ import { clearNestedRepoCache, findNestedRepoPaths } from '../git/nested-repos';
15
+ import { relative } from 'node:path';
13
16
  import { tmpdir } from 'node:os';
14
17
  import { join } from 'node:path';
15
18
 
@@ -48,6 +51,16 @@ async function makeProject(): Promise<string> {
48
51
  return dir;
49
52
  }
50
53
 
54
+ /** Wait until an async `predicate` holds, or fail after `timeout` ms. */
55
+ async function waitForAsync(predicate: () => Promise<boolean>, timeout = 8000): Promise<void> {
56
+ const deadline = Date.now() + timeout;
57
+ while (Date.now() < deadline) {
58
+ if (await predicate()) return;
59
+ await new Promise((resolve) => setTimeout(resolve, 50));
60
+ }
61
+ throw new Error('Timed out waiting for watcher-driven invalidation');
62
+ }
63
+
51
64
  /** Wait until `predicate` holds, or fail after `timeout` ms. */
52
65
  async function waitFor(predicate: () => boolean, timeout = 4000): Promise<void> {
53
66
  const deadline = Date.now() + timeout;
@@ -58,6 +71,19 @@ async function waitFor(predicate: () => boolean, timeout = 4000): Promise<void>
58
71
  throw new Error('Timed out waiting for watcher event');
59
72
  }
60
73
 
74
+ function gitRepoPathsFor(projectId: string): string[] {
75
+ return emitted
76
+ .filter((e) => e.projectId === projectId && e.event === 'git:changed')
77
+ .flatMap((e) => e.payload.repoPaths as string[]);
78
+ }
79
+
80
+ async function initRepo(dir: string): Promise<void> {
81
+ await mkdir(dir, { recursive: true });
82
+ await execGit(['init', '-b', 'main', '.'], dir);
83
+ await execGit(['config', 'user.email', 'test@example.com'], dir);
84
+ await execGit(['config', 'user.name', 'Test'], dir);
85
+ }
86
+
61
87
  function changesFor(projectId: string): string[] {
62
88
  return emitted
63
89
  .filter((e) => e.projectId === projectId && e.event === 'files:changed')
@@ -69,6 +95,7 @@ afterEach(async () => {
69
95
  fileWatcher.releaseProject(projectId);
70
96
  }
71
97
  emitted.length = 0;
98
+ clearNestedRepoCache();
72
99
  await Promise.all(tempRoots.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
73
100
  });
74
101
 
@@ -146,6 +173,84 @@ describe('FileWatcherManager', () => {
146
173
  expect(fileWatcher.getDirtyFiles('p5').size).toBe(0);
147
174
  });
148
175
 
176
+ test('watches a sub-repo created while the project is already open', async () => {
177
+ // `findNestedRepoPaths` caches its walk for a few seconds, and the panel
178
+ // warms that cache constantly — every `git:status` and `git:branches`
179
+ // goes through it. `scheduleGitTargetsRefresh` then re-resolves 1.5s
180
+ // after an unknown `.git` shows up, well inside the TTL, so it would be
181
+ // answered from a walk taken before the new repo existed. The git dir
182
+ // would stay unaccounted for, `syncGitWatchers` would file it under
183
+ // `rejectedGitDirs` — which is permanent — and `routeGitEvent` would
184
+ // then refuse to schedule another refresh for it. The sub-repo would go
185
+ // unwatched for as long as the project stayed open.
186
+ const root = await makeProject();
187
+ await initRepo(root);
188
+
189
+ // Warm the cache the way the panel does, before the sub-repo exists.
190
+ expect(await findNestedRepoPaths(root)).toEqual([]);
191
+
192
+ expect(await fileWatcher.startWatching('p7', root)).toBe(true);
193
+
194
+ const sub = join(root, 'packages', 'widget');
195
+ await initRepo(sub);
196
+
197
+ // The refresh announces itself by emitting for the project root once the
198
+ // repo set has been re-resolved.
199
+ await waitFor(() => gitRepoPathsFor('p7').includes(root), 10000);
200
+
201
+ emitted.length = 0;
202
+ // Space this out: the platform watchers coalesce bursts, and this write
203
+ // has to be seen on its own to mean anything.
204
+ await new Promise((resolve) => setTimeout(resolve, 400));
205
+ await writeFile(join(sub, '.git', 'index'), 'stand-in for a real index write');
206
+
207
+ await waitFor(() => gitRepoPathsFor('p7').includes(sub), 10000);
208
+ // 20s, not bun's 5s default: this test cannot finish faster than the
209
+ // watcher's own debounces (1.5s to re-resolve git targets, 0.5s to emit)
210
+ // plus two `git init`s and the spacing write.
211
+ }, 20000);
212
+
213
+ test('the watcher forwards path events to sub-repo discovery', async () => {
214
+ // Discovery leans on this watcher instead of a short clock, so raw paths
215
+ // have to reach it. There are two forwarding points — the working-tree
216
+ // handler and the git dir handles, which are a separate event source and
217
+ // the only one for `.git` on Linux — and this pins that AT LEAST ONE of
218
+ // them is live. It deliberately does not pin which: the two overlap on a
219
+ // real filesystem, and asserting on one would only pass by accident of
220
+ // which handle the platform happened to report an event through.
221
+ //
222
+ // Which path means what is pinned exactly, and without timing, by the
223
+ // `notifyPathChanged` tests in nested-repos.test.ts — `.gitignore`,
224
+ // `.git/info/exclude`, a `.git` appearing, and an ordinary write that
225
+ // must NOT invalidate anything.
226
+ //
227
+ // Direction matters. Going the other way — a repo that only becomes
228
+ // visible once an ignore rule is dropped — tests nothing: an unreported
229
+ // repo's `.git` is one the watcher does not know, so its first event
230
+ // triggers the unknown-git-dir refresh and the repo set is invalidated
231
+ // by that path whether or not anything is forwarded. Starting from a
232
+ // REPORTED repo keeps its git dir known.
233
+ const root = await makeProject();
234
+ await initRepo(root);
235
+ await initRepo(join(root, 'themes', 'mytheme'));
236
+
237
+ expect(await fileWatcher.startWatching('p8', root)).toBe(true);
238
+ expect((await findNestedRepoPaths(root)).map((repo) => relative(root, repo))).toEqual([
239
+ join('themes', 'mytheme')
240
+ ]);
241
+
242
+ // Space it out: the platform watchers coalesce bursts, and this write has
243
+ // to be seen on its own to mean anything.
244
+ await new Promise((resolve) => setTimeout(resolve, 400));
245
+ // `themes/` is now ignored, so the still-pristine repo inside it has to
246
+ // prove local work before it is listed — and it has none.
247
+ await writeFile(join(root, '.gitignore'), 'themes/\n');
248
+
249
+ await waitForAsync(async () => (await findNestedRepoPaths(root)).length === 0);
250
+ // Same reason as the test above — the debounces alone outlast bun's 5s
251
+ // default.
252
+ }, 20000);
253
+
149
254
  test('stops watching once the last viewer leaves', async () => {
150
255
  const root = await makeProject();
151
256
  expect(await fileWatcher.addViewer('conn-a', 'p6', root)).toBe(true);
@@ -33,7 +33,14 @@ import { stat, readdir } from 'node:fs/promises';
33
33
  import { join, relative, normalize, sep } from 'node:path';
34
34
  import { ws } from '$backend/utils/ws';
35
35
  import { debug } from '$shared/utils/logger';
36
+ import { isScopeOfProject, scopeProjectId } from '$shared/utils/workspace-scope';
36
37
  import { resolveGitDirs, type GitDirTarget } from '$backend/git/git-dirs';
38
+ import {
39
+ beginWatchedDiscovery,
40
+ endWatchedDiscovery,
41
+ invalidateRepoSet,
42
+ notifyPathChanged
43
+ } from '$backend/git/nested-repos';
37
44
  import type { FileChange } from '$shared/types/filesystem';
38
45
 
39
46
  /**
@@ -350,6 +357,12 @@ class FileWatcherManager {
350
357
  };
351
358
  this.watchers.set(projectId, projectWatcher);
352
359
 
360
+ // From here on this watcher is the authority on when the project's
361
+ // sub-repo set and their working states change, so discovery can stop
362
+ // re-deriving them on a short clock. Paired with `endWatchedDiscovery`
363
+ // in `stopWatching`, which puts discovery back on the clock.
364
+ beginWatchedDiscovery(normalizedPath);
365
+
353
366
  // Watch the root synchronously so events are never missed while the
354
367
  // (async) subtree walk is still in progress.
355
368
  if (!this.watchDir(projectWatcher, normalizedPath)) {
@@ -401,7 +414,7 @@ class FileWatcherManager {
401
414
  'file',
402
415
  `Watch ceiling (${MAX_WATCHED_DIRS} dirs) reached for project ${pw.projectId}; deeper directories will not report changes`
403
416
  );
404
- ws.emit.project(pw.projectId, 'files:watch-error', {
417
+ ws.emit.project(scopeProjectId(pw.projectId), 'files:watch-error', {
405
418
  projectId: pw.projectId,
406
419
  error: `Project is too large to watch entirely (${MAX_WATCHED_DIRS}+ directories). Changes in deeply nested folders may not appear automatically.`
407
420
  });
@@ -472,8 +485,15 @@ class FileWatcherManager {
472
485
  * Recursively attach watchers to every non-ignored directory under `dir`.
473
486
  * Ignored directories (node_modules, .git, build output, …) are never
474
487
  * descended into — that pruning is what keeps the watch count survivable.
488
+ *
489
+ * `announceGitDirs` reports each pruned `.git` to git discovery. Set it when
490
+ * walking a directory that just APPEARED: everything inside it was created
491
+ * before this watcher had a handle on it, so a `git clone` or `git init` into
492
+ * a fresh nested path emits no event we can ever see. Pruning `.git` without
493
+ * announcing it therefore lost the sub-repo for the whole session. The
494
+ * initial walk leaves it off — `syncGitWatchers` already resolves the tree.
475
495
  */
476
- private async watchSubtree(pw: ProjectWatcher, dir: string): Promise<void> {
496
+ private async watchSubtree(pw: ProjectWatcher, dir: string, announceGitDirs = false): Promise<void> {
477
497
  if (pw.closed) return;
478
498
 
479
499
  let entries;
@@ -489,7 +509,12 @@ class FileWatcherManager {
489
509
 
490
510
  const childPath = join(dir, entry.name);
491
511
  const relativePath = relative(pw.projectPath, childPath).replace(/\\/g, '/');
492
- if (this.shouldIgnore(relativePath)) continue;
512
+ if (this.shouldIgnore(relativePath)) {
513
+ if (announceGitDirs && entry.name === '.git') {
514
+ this.routeGitEvent(pw, relativePath, childPath);
515
+ }
516
+ continue;
517
+ }
493
518
 
494
519
  if (!this.watchDir(pw, childPath)) {
495
520
  // Ceiling reached — stop descending entirely rather than watching an
@@ -497,7 +522,7 @@ class FileWatcherManager {
497
522
  if (pw.truncated) return;
498
523
  continue;
499
524
  }
500
- await this.watchSubtree(pw, childPath);
525
+ await this.watchSubtree(pw, childPath, announceGitDirs);
501
526
  }
502
527
  }
503
528
 
@@ -531,6 +556,9 @@ class FileWatcherManager {
531
556
  }
532
557
  projectWatcher.gitDirOwners.clear();
533
558
 
559
+ // No more signals from here, so discovery must not keep trusting them.
560
+ endWatchedDiscovery(projectWatcher.projectPath);
561
+
534
562
  // Clear debounce timers
535
563
  if (projectWatcher.debounceTimer) {
536
564
  clearTimeout(projectWatcher.debounceTimer);
@@ -564,6 +592,17 @@ class FileWatcherManager {
564
592
  this.stopWatching(projectId);
565
593
  }
566
594
 
595
+ /**
596
+ * Release every workspace of a project — the main tree and each worktree.
597
+ * Watchers are keyed per workspace, so releasing the project id alone would
598
+ * leave a deleted project's worktree watchers running.
599
+ */
600
+ releaseProjectScopes(projectId: string): void {
601
+ for (const key of [...this.watchers.keys(), ...this.viewers.keys()]) {
602
+ if (isScopeOfProject(key, projectId)) this.releaseProject(key);
603
+ }
604
+ }
605
+
567
606
  /**
568
607
  * Check if a project is being watched
569
608
  */
@@ -606,6 +645,12 @@ class FileWatcherManager {
606
645
  // path: where the root watch is recursive it is the only thing that sees
607
646
  // a sub-repo's git dir, so dropping it here is what left a commit made
608
647
  // inside a nested repo completely unreported.
648
+ // Tell sub-repo discovery before anything below filters the path away.
649
+ // It decides for itself what a path means: `routeGitEvent` swallows every
650
+ // `.git` path and `shouldIgnore` every dotfile, so `.gitignore` — which
651
+ // moves the reported repo set — would otherwise never reach it.
652
+ notifyPathChanged(projectWatcher.projectPath, fullPath);
653
+
609
654
  if (this.routeGitEvent(projectWatcher, relativePath, fullPath)) return;
610
655
 
611
656
  if (this.shouldIgnore(relativePath)) return;
@@ -632,7 +677,9 @@ class FileWatcherManager {
632
677
  if (!USE_NATIVE_RECURSIVE_WATCH) {
633
678
  if (isDirectory && changeType === 'created') {
634
679
  if (this.watchDir(projectWatcher, fullPath)) {
635
- void this.watchSubtree(projectWatcher, fullPath);
680
+ // Announce pruned git dirs: this subtree existed before we could
681
+ // watch it, so anything already inside it emitted no event.
682
+ void this.watchSubtree(projectWatcher, fullPath, true);
636
683
  }
637
684
  } else if (changeType === 'deleted' && projectWatcher.dirWatchers.has(fullPath)) {
638
685
  this.unwatchDir(projectWatcher, fullPath);
@@ -698,7 +745,7 @@ class FileWatcherManager {
698
745
  projectWatcher.debounceTimer = null;
699
746
 
700
747
  // Emit changes to users currently viewing the project
701
- ws.emit.project(projectId, 'files:changed', {
748
+ ws.emit.project(scopeProjectId(projectId), 'files:changed', {
702
749
  projectId,
703
750
  changes,
704
751
  timestamp: Date.now()
@@ -790,7 +837,17 @@ class FileWatcherManager {
790
837
  try {
791
838
  const watcher = watch(dirToWatch, { recursive }, (_eventType, filename) => {
792
839
  if (!filename) return;
793
- const entryPath = relative(gitDirPath, join(dirToWatch, String(filename)));
840
+ const fullPath = join(dirToWatch, String(filename));
841
+
842
+ // These handles are their own event source: nothing here reaches
843
+ // `handleFileChange`, and on Linux — where `.git` is pruned from the
844
+ // recursive walk — they are the ONLY source for it. Discovery has to
845
+ // be told from here too, before `isGitStateEvent` filters, since that
846
+ // filter answers 'does the panel show this' and drops `info/exclude`,
847
+ // which discovery very much cares about.
848
+ notifyPathChanged(projectWatcher.projectPath, fullPath);
849
+
850
+ const entryPath = relative(gitDirPath, fullPath);
794
851
  if (!isGitStateEvent(entryPath)) return;
795
852
  this.emitGitChanged(projectWatcher.projectId, repoPath);
796
853
  });
@@ -832,6 +889,14 @@ class FileWatcherManager {
832
889
  * Queue a re-resolve of the project's git directories, for when an event
833
890
  * arrives from a `.git` we do not know about — `git init` or `git clone` run
834
891
  * inside the project while it is open.
892
+ *
893
+ * This is the one signal that the project's repo SET changed, so it drops
894
+ * the cached sub-repo walk first. Without that, `resolveGitDirs` answers
895
+ * from a walk taken before the new repo existed, the git dir stays
896
+ * unaccounted for, and `syncGitWatchers` files it under `rejectedGitDirs` —
897
+ * which is permanent, and which `routeGitEvent` then uses to stop
898
+ * scheduling refreshes for it. A repo created in an open project would
899
+ * never be watched again.
835
900
  */
836
901
  private scheduleGitTargetsRefresh(projectId: string, gitDirPath?: string): void {
837
902
  const projectWatcher = this.watchers.get(projectId);
@@ -843,6 +908,7 @@ class FileWatcherManager {
843
908
  projectWatcher.gitTargetsTimer = setTimeout(() => {
844
909
  projectWatcher.gitTargetsTimer = null;
845
910
  if (projectWatcher.closed) return;
911
+ invalidateRepoSet(projectWatcher.projectPath);
846
912
  void this.syncGitWatchers(projectId).then(() => {
847
913
  if (projectWatcher.closed) return;
848
914
  // The repo set itself changed, so tell clients: this is what flips a
@@ -894,7 +960,7 @@ class FileWatcherManager {
894
960
  projectWatcher.gitDebounceTimer = null;
895
961
  const repoPaths = Array.from(projectWatcher.pendingGitRepos);
896
962
  projectWatcher.pendingGitRepos.clear();
897
- ws.emit.project(projectId, 'git:changed', {
963
+ ws.emit.project(scopeProjectId(projectId), 'git:changed', {
898
964
  projectId,
899
965
  repoPaths,
900
966
  timestamp: Date.now()
@@ -931,10 +997,14 @@ class FileWatcherManager {
931
997
  'file',
932
998
  `Watcher for project ${projectId} faulted ${attempt} times; giving up on automatic restart`
933
999
  );
934
- ws.emit.project(projectId, 'files:watch-error', {
1000
+ ws.emit.project(scopeProjectId(projectId), 'files:watch-error', {
935
1001
  projectId,
936
1002
  error: 'File watching stopped after repeated failures. Refresh to retry.'
937
1003
  });
1004
+ // No more signals are coming, so sub-repo discovery must stop trusting
1005
+ // this watcher and go back to re-deriving on its own clock. Without
1006
+ // this the claim outlives the watcher that made it.
1007
+ this.stopWatching(projectId);
938
1008
  return;
939
1009
  }
940
1010
 
@@ -959,7 +1029,7 @@ class FileWatcherManager {
959
1029
  // reconcile — deliberately NOT via `files:changed`, which means "these
960
1030
  // specific paths changed" and made consumers tear down and rebuild live
961
1031
  // views (the open diff editor) on every restart.
962
- ws.emit.project(projectId, 'files:resync', {
1032
+ ws.emit.project(scopeProjectId(projectId), 'files:resync', {
963
1033
  projectId,
964
1034
  timestamp: Date.now()
965
1035
  });
@@ -107,6 +107,39 @@ describe('undoLastCommit — with a parent commit', () => {
107
107
  });
108
108
  });
109
109
 
110
+ describe('getLog branch scoping', () => {
111
+ beforeEach(async () => {
112
+ await writeFile(path.join(repo, 'a.txt'), 'one\n');
113
+ await commitAll('on main');
114
+ await git('checkout', '-b', 'side');
115
+ await writeFile(path.join(repo, 'b.txt'), 'two\n');
116
+ await commitAll('on side');
117
+ await git('checkout', 'main');
118
+ });
119
+
120
+ test('defaults to HEAD, so another branch\'s commits stay out', async () => {
121
+ const log = await gitService.getLog(repo);
122
+ expect(log.commits.map(c => c.message)).toEqual(['on main']);
123
+ expect(log.total).toBe(1);
124
+ });
125
+
126
+ test('a named branch reports that branch', async () => {
127
+ const log = await gitService.getLog(repo, 50, 0, 'side');
128
+ expect(log.commits.map(c => c.message)).toEqual(['on side', 'on main']);
129
+ expect(log.total).toBe(2);
130
+ });
131
+
132
+ test('allBranches walks every ref and counts across all of them', async () => {
133
+ const log = await gitService.getLog(repo, 50, 0, undefined, true);
134
+ expect(log.commits.map(c => c.message).sort()).toEqual(['on main', 'on side']);
135
+ expect(log.total).toBe(2);
136
+ });
137
+
138
+ test('the branch argument still rejects option-shaped values', async () => {
139
+ await expect(gitService.getLog(repo, 50, 0, '--all')).rejects.toThrow(/option injection/i);
140
+ });
141
+ });
142
+
110
143
  describe('other actions on a repo with no commits', () => {
111
144
  test('getLog reports an empty history rather than throwing', async () => {
112
145
  expect(await gitService.getLog(repo)).toEqual({ commits: [], total: 0, hasMore: false });
@@ -471,7 +471,7 @@ export class GitService {
471
471
  // Log
472
472
  // ============================================
473
473
 
474
- async getLog(cwd: string, limit = 50, skip = 0, branch?: string): Promise<GitLogResult> {
474
+ async getLog(cwd: string, limit = 50, skip = 0, branch?: string, allBranches = false): Promise<GitLogResult> {
475
475
  const SEPARATOR = '|||';
476
476
  const format = `%H${SEPARATOR}%h${SEPARATOR}%an${SEPARATOR}%ae${SEPARATOR}%aI${SEPARATOR}%P${SEPARATOR}%D%n%s%x00`;
477
477
 
@@ -483,7 +483,11 @@ export class GitService {
483
483
  `--skip=${skip}`
484
484
  ];
485
485
 
486
- if (branch) {
486
+ // `--all` is a flag, not a revision, so it stays out of the value slot that
487
+ // `assertSafeGitRevish` guards against option injection.
488
+ if (allBranches) {
489
+ args.push('--all');
490
+ } else if (branch) {
487
491
  assertSafeGitRevish(branch, 'log branch');
488
492
  args.push(branch);
489
493
  }
@@ -503,7 +507,7 @@ export class GitService {
503
507
  if (hasMore) commits.pop(); // Remove the extra one
504
508
 
505
509
  // Get total count
506
- const countRef = branch ?? 'HEAD';
510
+ const countRef = allBranches ? '--all' : (branch ?? 'HEAD');
507
511
  const countResult = await execGit(['rev-list', '--count', countRef], cwd);
508
512
  const total = parseInt(countResult.stdout.trim()) || commits.length;
509
513