@myrialabs/clopen 0.4.32 → 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 (78) hide show
  1. package/backend/chat/stream-manager.ts +4 -1
  2. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  5. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  6. package/backend/database/queries/index.ts +3 -0
  7. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  8. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  9. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  10. package/backend/db-client/connection-manager.ts +8 -1
  11. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  12. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  13. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  14. package/backend/engine/adapters/codex/stream.ts +33 -4
  15. package/backend/engine/adapters/copilot/stream.ts +1 -1
  16. package/backend/engine/adapters/cursor/stream.ts +1 -1
  17. package/backend/engine/adapters/qwen/stream.ts +1 -1
  18. package/backend/engine/docs/adapter-contract.md +7 -0
  19. package/backend/files/file-watcher.ts +283 -51
  20. package/backend/files/git-events.test.ts +110 -0
  21. package/backend/git/git-dirs.test.ts +132 -0
  22. package/backend/git/git-dirs.ts +0 -0
  23. package/backend/git/nested-repos.test.ts +108 -5
  24. package/backend/git/nested-repos.ts +103 -18
  25. package/backend/http/audio.ts +5 -32
  26. package/backend/http/bearer-auth.ts +47 -0
  27. package/backend/http/files-download.test.ts +146 -0
  28. package/backend/http/files-download.ts +109 -0
  29. package/backend/http/files-upload.ts +3 -29
  30. package/backend/http/ssh-sftp.ts +133 -0
  31. package/backend/index.ts +16 -2
  32. package/backend/mcp/README.md +34 -6
  33. package/backend/mcp/index.ts +8 -8
  34. package/backend/mcp/internal/config.ts +69 -19
  35. package/backend/mcp/internal/project-context.test.ts +40 -0
  36. package/backend/mcp/internal/project-context.ts +80 -7
  37. package/backend/mcp/internal/remote-server.test.ts +17 -2
  38. package/backend/mcp/internal/remote-server.ts +36 -3
  39. package/backend/mcp/internal/servers/helper.ts +48 -18
  40. package/backend/preview/browser/browser-video-capture.ts +51 -4
  41. package/backend/ssh/client-pool.ts +196 -0
  42. package/backend/ssh/connect.ts +375 -0
  43. package/backend/ssh/disk-usage.test.ts +134 -0
  44. package/backend/ssh/disk-usage.ts +214 -0
  45. package/backend/ssh/forwards.ts +309 -0
  46. package/backend/ssh/health.ts +141 -0
  47. package/backend/ssh/known-hosts.ts +96 -0
  48. package/backend/ssh/pty-backend.ts +215 -0
  49. package/backend/ssh/ptykit.ts +66 -0
  50. package/backend/ssh/sftp.test.ts +242 -0
  51. package/backend/ssh/sftp.ts +967 -0
  52. package/backend/ssh/socks5.test.ts +167 -0
  53. package/backend/ssh/socks5.ts +164 -0
  54. package/backend/ssh/tunnel.ts +87 -0
  55. package/backend/ws/db-client/connections.ts +1 -0
  56. package/backend/ws/files/watch.ts +5 -1
  57. package/backend/ws/index.ts +4 -0
  58. package/backend/ws/ssh/access.ts +31 -0
  59. package/backend/ws/ssh/connections.ts +224 -0
  60. package/backend/ws/ssh/forwards.ts +109 -0
  61. package/backend/ws/ssh/index.ts +18 -0
  62. package/backend/ws/ssh/sftp.ts +259 -0
  63. package/backend/ws/ssh/tunnel.ts +93 -0
  64. package/dist/assets/{index-DSvGoxp2.js → index-BF4buYmI.js} +1 -1
  65. package/dist/assets/{index-hu17G6tX.js → index-BW0DA8NV.js} +1 -1
  66. package/dist/assets/{main-BccclZsC.js → main-BbwWLJRN.js} +499 -473
  67. package/dist/assets/main-CCvRMXlP.css +1 -0
  68. package/dist/index.html +2 -2
  69. package/package.json +1 -1
  70. package/shared/types/database/schema.ts +49 -0
  71. package/shared/types/db-client/connection.ts +6 -0
  72. package/shared/types/ssh/connection.ts +80 -0
  73. package/shared/types/ssh/forward.ts +46 -0
  74. package/shared/types/ssh/index.ts +8 -0
  75. package/shared/types/ssh/known-host.ts +19 -0
  76. package/shared/types/ssh/sftp.ts +141 -0
  77. package/shared/utils/logger.ts +1 -0
  78. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -33,6 +33,7 @@ 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 { resolveGitDirs, type GitDirTarget } from '$backend/git/git-dirs';
36
37
  import type { FileChange } from '$shared/types/filesystem';
37
38
 
38
39
  /**
@@ -89,11 +90,78 @@ const IGNORED_FILES = new Set([
89
90
  ]);
90
91
 
91
92
  /**
92
- * Git state files to watch for external git operations
93
+ * Entries inside a git directory that never change what the Git panel renders.
94
+ *
95
+ * This is a denylist on purpose, and the inversion matters. Git writes almost
96
+ * everything atomically — it creates `<name>.lock`, writes it, then renames it
97
+ * onto `<name>` — and macOS reports that rename under the OLD name. In practice
98
+ * `<name>.lock` is frequently the ONLY name that ever arrives: a commit reports
99
+ * `index.lock`, `HEAD.lock` and `refs/heads/<branch>.lock` and never once
100
+ * reports `index`, `HEAD` or the branch ref itself.
101
+ *
102
+ * The previous allowlist of final names (`index`, `HEAD`, `MERGE_HEAD`,
103
+ * `REBASE_HEAD`) therefore matched almost nothing, and the sibling `refs/`
104
+ * watcher discarded every `.lock` outright — so external commits, checkouts,
105
+ * branch creations, stashes and tag creations produced no event at all and the
106
+ * panel only ever refreshed when a working-tree write happened to coincide.
107
+ *
108
+ * Listing what to ignore fails safe in the other direction: an unrecognised
109
+ * entry costs one debounced refresh, not a silently stale panel.
110
+ *
111
+ * `logs/` is deliberately NOT listed. The reflog looks like noise but is the
112
+ * best signal we get: git appends to it whenever a ref actually moves, it is
113
+ * written in place rather than through a lock file, and measurement showed it
114
+ * is frequently the ONLY event the project's recursive root watch delivers for
115
+ * `git branch` — the ref's own `.lock` never surfaces there.
93
116
  */
94
- const GIT_STATE_FILES = ['index', 'HEAD', 'MERGE_HEAD', 'REBASE_HEAD'];
117
+ const GIT_INTERNAL_IGNORED = new Set([
118
+ // Pure content churn, with no state meaning of its own; the index or ref
119
+ // update that gives it meaning is reported separately.
120
+ 'objects',
121
+ 'lfs',
122
+ // Never read by the panel.
123
+ 'hooks',
124
+ 'info',
125
+ 'COMMIT_EDITMSG',
126
+ 'MERGE_MSG',
127
+ 'SQUASH_MSG',
128
+ 'TAG_EDITMSG',
129
+ 'index.stat',
130
+ 'gitk.cache'
131
+ ]);
132
+
95
133
  const GIT_DEBOUNCE_MS = 500;
96
134
 
135
+ /**
136
+ * Delay before re-resolving a project's git directories after an event arrived
137
+ * from one we do not know about yet. Debounced because the trigger is bursty:
138
+ * `git init` and `git clone` create dozens of files under a brand-new `.git`.
139
+ */
140
+ const GIT_TARGETS_REFRESH_MS = 1500;
141
+
142
+ /** Strip git's atomic-write suffix so `index.lock` is read as `index`. */
143
+ export function stripGitLockSuffix(entryPath: string): string {
144
+ return entryPath.endsWith('.lock') ? entryPath.slice(0, -'.lock'.length) : entryPath;
145
+ }
146
+
147
+ /**
148
+ * Whether a path inside a git directory represents state the Git panel shows.
149
+ * `entryPath` is relative to the git directory itself (`index`, `HEAD`,
150
+ * `refs/heads/main.lock`, `objects/ab/cd`, …).
151
+ */
152
+ export function isGitStateEvent(entryPath: string): boolean {
153
+ const normalized = stripGitLockSuffix(entryPath.replace(/\\/g, '/'));
154
+ if (!normalized || normalized === '.') return false;
155
+ const topLevelEntry = normalized.split('/')[0];
156
+ if (!topLevelEntry) return false;
157
+ return !GIT_INTERNAL_IGNORED.has(topLevelEntry);
158
+ }
159
+
160
+ /** Whether a project-relative path passes through a `.git` directory. */
161
+ export function hasGitSegment(relativePath: string): boolean {
162
+ return relativePath.split('/').includes('.git');
163
+ }
164
+
97
165
  /**
98
166
  * Watcher instance for a project
99
167
  */
@@ -110,9 +178,25 @@ interface ProjectWatcher {
110
178
  faults: number;
111
179
  /** Flipped by stopWatching so in-flight async tree walks bail out. */
112
180
  closed: boolean;
113
- gitWatcher: FSWatcher | null;
114
- gitRefsWatcher: FSWatcher | null;
181
+ /**
182
+ * Every known git directory -> the working tree it belongs to. Covers the
183
+ * project's own repo and each sub-repo, and is the attribution table for
184
+ * git events seen by the project's recursive root watch.
185
+ */
186
+ gitDirOwners: Map<string, string>;
187
+ /** Git directory -> the handles held on it (its root and its `refs/`). */
188
+ gitWatchers: Map<string, FSWatcher[]>;
189
+ /**
190
+ * Git directories that were re-resolved and still turned out not to belong to
191
+ * this project, so their churn never schedules another resolve.
192
+ */
193
+ rejectedGitDirs: Set<string>;
194
+ /** Git dirs awaiting the next resolve, to be judged once it completes. */
195
+ unresolvedGitDirs: Set<string>;
196
+ /** Working trees with git state changes awaiting the debounced emit. */
197
+ pendingGitRepos: Set<string>;
115
198
  gitDebounceTimer: ReturnType<typeof setTimeout> | null;
199
+ gitTargetsTimer: ReturnType<typeof setTimeout> | null;
116
200
  }
117
201
 
118
202
  /**
@@ -256,9 +340,13 @@ class FileWatcherManager {
256
340
  truncated: false,
257
341
  faults,
258
342
  closed: false,
259
- gitWatcher: null,
260
- gitRefsWatcher: null,
261
- gitDebounceTimer: null
343
+ gitDirOwners: new Map(),
344
+ gitWatchers: new Map(),
345
+ rejectedGitDirs: new Set(),
346
+ unresolvedGitDirs: new Set(),
347
+ pendingGitRepos: new Set(),
348
+ gitDebounceTimer: null,
349
+ gitTargetsTimer: null
262
350
  };
263
351
  this.watchers.set(projectId, projectWatcher);
264
352
 
@@ -269,8 +357,10 @@ class FileWatcherManager {
269
357
  return false;
270
358
  }
271
359
 
272
- // Start git state watcher (for external git operations)
273
- this.startGitWatcher(projectId, normalizedPath);
360
+ // Resolve and watch the project's git directories (for external git
361
+ // operations). Async, but nothing is missed while it runs: git dirs
362
+ // inside the project tree are already covered by the root watch above.
363
+ void this.syncGitWatchers(projectId);
274
364
 
275
365
  // On Linux the root watch only covers the root itself. Walk the tree in
276
366
  // the background so every non-ignored directory gets its own watch;
@@ -436,8 +526,10 @@ class FileWatcherManager {
436
526
  projectWatcher.dirWatchers.clear();
437
527
 
438
528
  // Close git watchers
439
- projectWatcher.gitWatcher?.close();
440
- projectWatcher.gitRefsWatcher?.close();
529
+ for (const gitDirPath of Array.from(projectWatcher.gitWatchers.keys())) {
530
+ this.closeGitDirWatchers(projectWatcher, gitDirPath);
531
+ }
532
+ projectWatcher.gitDirOwners.clear();
441
533
 
442
534
  // Clear debounce timers
443
535
  if (projectWatcher.debounceTimer) {
@@ -446,6 +538,9 @@ class FileWatcherManager {
446
538
  if (projectWatcher.gitDebounceTimer) {
447
539
  clearTimeout(projectWatcher.gitDebounceTimer);
448
540
  }
541
+ if (projectWatcher.gitTargetsTimer) {
542
+ clearTimeout(projectWatcher.gitTargetsTimer);
543
+ }
449
544
 
450
545
  // Remove from map
451
546
  this.watchers.delete(projectId);
@@ -503,10 +598,17 @@ class FileWatcherManager {
503
598
  const relativePath = relative(projectWatcher.projectPath, fullPath).replace(/\\/g, '/');
504
599
 
505
600
  // Paths outside the project (possible on some platforms for rename events)
506
- // and ignored paths never reach clients.
507
- if (relativePath.startsWith('..') || this.shouldIgnore(relativePath)) {
508
- return;
509
- }
601
+ // never reach clients.
602
+ if (relativePath.startsWith('..')) return;
603
+
604
+ // Git metadata is not a working-tree change — it drives the Git panel
605
+ // instead. This runs BEFORE `shouldIgnore`, which discards every `.git`
606
+ // path: where the root watch is recursive it is the only thing that sees
607
+ // a sub-repo's git dir, so dropping it here is what left a commit made
608
+ // inside a nested repo completely unreported.
609
+ if (this.routeGitEvent(projectWatcher, relativePath, fullPath)) return;
610
+
611
+ if (this.shouldIgnore(relativePath)) return;
510
612
 
511
613
  // Determine change type
512
614
  let changeType: 'created' | 'modified' | 'deleted';
@@ -609,56 +711,180 @@ class FileWatcherManager {
609
711
  }
610
712
 
611
713
  /**
612
- * Start watching .git directory for external git operations
613
- * Watches: .git/index (staging), .git/HEAD (branch switch), .git/refs/ (branches/tags)
714
+ * Resolve every git directory this project depends on and reconcile the
715
+ * watchers held for them.
716
+ *
717
+ * Every git dir gets its own handles, including the ones already inside the
718
+ * watched tree. That is deliberate redundancy, not an oversight: measurement
719
+ * showed the two paths see different events for the same operation — the
720
+ * project's recursive root watch reports `git branch` only as a reflog write,
721
+ * while a watch rooted at `refs/` reports the ref's own lock file. Neither is
722
+ * complete alone, both are debounced into one emit, and the cost is two
723
+ * handles per repo against a sub-repo count already capped at 50.
724
+ *
725
+ * Git dirs OUTSIDE the tree — a project opened at a repo subfolder, a linked
726
+ * worktree, a submodule whose git dir lives in the superproject — have no
727
+ * other source at all, which is why resolving them is what makes those
728
+ * layouts work rather than silently reporting nothing.
614
729
  */
615
- private startGitWatcher(projectId: string, projectPath: string): void {
730
+ private async syncGitWatchers(projectId: string): Promise<void> {
616
731
  const projectWatcher = this.watchers.get(projectId);
617
- if (!projectWatcher) return;
618
-
619
- const gitDir = join(projectPath, '.git');
620
- if (!existsSync(gitDir)) return;
732
+ if (!projectWatcher || projectWatcher.closed) return;
621
733
 
734
+ let targets: GitDirTarget[];
622
735
  try {
623
- // Watch .git/ root for index, HEAD, MERGE_HEAD changes
624
- projectWatcher.gitWatcher = watch(gitDir, (eventType, filename) => {
625
- if (!filename) return;
626
- const normalized = filename.replace(/\\/g, '/');
627
- if (GIT_STATE_FILES.includes(normalized)) {
628
- this.emitGitChanged(projectId);
629
- }
630
- });
631
- projectWatcher.gitWatcher.on('error', () => {
632
- // Silently ignore git watcher errors
633
- });
736
+ targets = await resolveGitDirs(projectWatcher.projectPath);
737
+ } catch (error) {
738
+ debug.warn('file', `Failed to resolve git dirs for project ${projectId}:`, error);
739
+ return;
740
+ }
741
+
742
+ // The project may have been swapped or torn down while `git rev-parse` ran.
743
+ if (projectWatcher.closed || this.watchers.get(projectId) !== projectWatcher) return;
634
744
 
635
- // Watch .git/refs/ for branch/tag create/delete. Lock files are git's
636
- // own write-in-progress scratch space: every ref update produces a
637
- // `<ref>.lock` create AND delete, so forwarding them doubled the churn
638
- // and fired a refresh before the ref itself had landed.
639
- const refsDir = join(gitDir, 'refs');
640
- if (existsSync(refsDir)) {
641
- projectWatcher.gitRefsWatcher = watch(refsDir, { recursive: true }, (_eventType, filename) => {
642
- if (filename && filename.replace(/\\/g, '/').endsWith('.lock')) return;
643
- this.emitGitChanged(projectId);
745
+ // A git dir can appear twice (a worktree's own dir and its common dir);
746
+ // the first owner wins, which keeps shared refs attributed to the repo
747
+ // that actually owns them.
748
+ const ownerByGitDir = new Map<string, string>();
749
+ for (const target of targets) {
750
+ if (!ownerByGitDir.has(target.gitDir)) ownerByGitDir.set(target.gitDir, target.repoPath);
751
+ if (!ownerByGitDir.has(target.commonDir)) ownerByGitDir.set(target.commonDir, target.repoPath);
752
+ }
753
+ projectWatcher.gitDirOwners = ownerByGitDir;
754
+
755
+ // Release handles on git dirs that are gone (repo deleted, worktree pruned).
756
+ for (const gitDirPath of Array.from(projectWatcher.gitWatchers.keys())) {
757
+ if (ownerByGitDir.has(gitDirPath)) continue;
758
+ this.closeGitDirWatchers(projectWatcher, gitDirPath);
759
+ }
760
+
761
+ for (const [gitDirPath, repoPath] of ownerByGitDir) {
762
+ this.watchGitDir(projectWatcher, gitDirPath, repoPath);
763
+ }
764
+
765
+ // Anything that triggered this resolve and is still unaccounted for does
766
+ // not belong to the project (a package-manager checkout the sub-repo
767
+ // policy rejects); remember it so its churn cannot re-trigger forever.
768
+ for (const gitDirPath of projectWatcher.unresolvedGitDirs) {
769
+ if (!ownerByGitDir.has(gitDirPath)) projectWatcher.rejectedGitDirs.add(gitDirPath);
770
+ }
771
+ projectWatcher.unresolvedGitDirs.clear();
772
+
773
+ debug.log(
774
+ 'file',
775
+ `Watching ${projectWatcher.gitWatchers.size} git dir(s) for project ${projectId}`
776
+ );
777
+ }
778
+
779
+ /**
780
+ * Attach handles to one git directory: its root (where `index`, `HEAD` and
781
+ * the in-progress operation markers live) and `refs/` recursively.
782
+ */
783
+ private watchGitDir(projectWatcher: ProjectWatcher, gitDirPath: string, repoPath: string): void {
784
+ if (projectWatcher.closed || projectWatcher.gitWatchers.has(gitDirPath)) return;
785
+ if (!existsSync(gitDirPath)) return;
786
+
787
+ const attached: FSWatcher[] = [];
788
+ const attach = (dirToWatch: string, recursive: boolean): void => {
789
+ if (!existsSync(dirToWatch)) return;
790
+ try {
791
+ const watcher = watch(dirToWatch, { recursive }, (_eventType, filename) => {
792
+ if (!filename) return;
793
+ const entryPath = relative(gitDirPath, join(dirToWatch, String(filename)));
794
+ if (!isGitStateEvent(entryPath)) return;
795
+ this.emitGitChanged(projectWatcher.projectId, repoPath);
644
796
  });
645
- projectWatcher.gitRefsWatcher.on('error', () => {
646
- // Silently ignore refs watcher errors
797
+ // A faulted git watcher used to be swallowed in silence, leaving the
798
+ // panel with no event source and no way to notice. Re-resolving
799
+ // rebuilds the handles from scratch.
800
+ watcher.on('error', (error) => {
801
+ debug.warn('file', `Git watcher error for ${dirToWatch}:`, error);
802
+ this.closeGitDirWatchers(projectWatcher, gitDirPath);
803
+ this.scheduleGitTargetsRefresh(projectWatcher.projectId);
647
804
  });
805
+ attached.push(watcher);
806
+ } catch (error) {
807
+ debug.warn('file', `Failed to watch git dir ${dirToWatch}:`, error);
808
+ }
809
+ };
810
+
811
+ attach(gitDirPath, false);
812
+ attach(join(gitDirPath, 'refs'), true);
813
+
814
+ if (attached.length > 0) projectWatcher.gitWatchers.set(gitDirPath, attached);
815
+ }
816
+
817
+ /** Close and forget every handle held on one git directory. */
818
+ private closeGitDirWatchers(projectWatcher: ProjectWatcher, gitDirPath: string): void {
819
+ const attached = projectWatcher.gitWatchers.get(gitDirPath);
820
+ if (!attached) return;
821
+ for (const watcher of attached) {
822
+ try {
823
+ watcher.close();
824
+ } catch {
825
+ // Already closed — nothing to do.
648
826
  }
827
+ }
828
+ projectWatcher.gitWatchers.delete(gitDirPath);
829
+ }
830
+
831
+ /**
832
+ * Queue a re-resolve of the project's git directories, for when an event
833
+ * arrives from a `.git` we do not know about — `git init` or `git clone` run
834
+ * inside the project while it is open.
835
+ */
836
+ private scheduleGitTargetsRefresh(projectId: string, gitDirPath?: string): void {
837
+ const projectWatcher = this.watchers.get(projectId);
838
+ if (!projectWatcher || projectWatcher.closed) return;
839
+
840
+ if (gitDirPath) projectWatcher.unresolvedGitDirs.add(gitDirPath);
841
+ if (projectWatcher.gitTargetsTimer) return;
842
+
843
+ projectWatcher.gitTargetsTimer = setTimeout(() => {
844
+ projectWatcher.gitTargetsTimer = null;
845
+ if (projectWatcher.closed) return;
846
+ void this.syncGitWatchers(projectId).then(() => {
847
+ if (projectWatcher.closed) return;
848
+ // The repo set itself changed, so tell clients: this is what flips a
849
+ // panel out of "Not a git repository" after an external `git init`.
850
+ this.emitGitChanged(projectId, projectWatcher.projectPath);
851
+ });
852
+ }, GIT_TARGETS_REFRESH_MS);
853
+ }
649
854
 
650
- debug.log('file', `Started git watcher for project: ${projectId}`);
651
- } catch (err) {
652
- debug.warn('file', `Failed to start git watcher for project ${projectId}:`, err);
855
+ /**
856
+ * Handle a change under a `.git` directory reported by the project's own
857
+ * (recursive) root watch. Returns true when the event was git metadata and
858
+ * must not be forwarded as a working-tree change.
859
+ */
860
+ private routeGitEvent(projectWatcher: ProjectWatcher, relativePath: string, fullPath: string): boolean {
861
+ if (!hasGitSegment(relativePath)) return false;
862
+
863
+ const segments = relativePath.split('/');
864
+ const gitSegmentIndex = segments.indexOf('.git');
865
+ const gitDirPath = join(projectWatcher.projectPath, ...segments.slice(0, gitSegmentIndex + 1));
866
+
867
+ const repoPath = projectWatcher.gitDirOwners.get(gitDirPath);
868
+ if (repoPath) {
869
+ if (isGitStateEvent(relative(gitDirPath, fullPath))) {
870
+ this.emitGitChanged(projectWatcher.projectId, repoPath);
871
+ }
872
+ } else if (!projectWatcher.rejectedGitDirs.has(gitDirPath)) {
873
+ this.scheduleGitTargetsRefresh(projectWatcher.projectId, gitDirPath);
653
874
  }
875
+
876
+ return true;
654
877
  }
655
878
 
656
879
  /**
657
- * Debounced emit of git:changed event
880
+ * Debounced emit of git:changed, carrying every working tree that moved since
881
+ * the last flush so clients can refresh sub-repos selectively.
658
882
  */
659
- private emitGitChanged(projectId: string): void {
883
+ private emitGitChanged(projectId: string, repoPath: string): void {
660
884
  const projectWatcher = this.watchers.get(projectId);
661
- if (!projectWatcher) return;
885
+ if (!projectWatcher || projectWatcher.closed) return;
886
+
887
+ projectWatcher.pendingGitRepos.add(repoPath);
662
888
 
663
889
  if (projectWatcher.gitDebounceTimer) {
664
890
  clearTimeout(projectWatcher.gitDebounceTimer);
@@ -666,11 +892,17 @@ class FileWatcherManager {
666
892
 
667
893
  projectWatcher.gitDebounceTimer = setTimeout(() => {
668
894
  projectWatcher.gitDebounceTimer = null;
895
+ const repoPaths = Array.from(projectWatcher.pendingGitRepos);
896
+ projectWatcher.pendingGitRepos.clear();
669
897
  ws.emit.project(projectId, 'git:changed', {
670
898
  projectId,
899
+ repoPaths,
671
900
  timestamp: Date.now()
672
901
  });
673
- debug.log('file', `Emitted git:changed for project ${projectId}`);
902
+ debug.log(
903
+ 'file',
904
+ `Emitted git:changed for project ${projectId} (${repoPaths.length} repo(s))`
905
+ );
674
906
  }, GIT_DEBOUNCE_MS);
675
907
  }
676
908
 
@@ -0,0 +1,110 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { hasGitSegment, isGitStateEvent, stripGitLockSuffix } from './file-watcher';
3
+
4
+ /**
5
+ * These tests pin down the classification that decides whether a filesystem
6
+ * event under a `.git` directory becomes a `git:changed` for the Git panel.
7
+ *
8
+ * The bug they exist to prevent: git writes almost everything atomically, by
9
+ * creating `<name>.lock`, writing it, then renaming it onto `<name>`. macOS
10
+ * reports that rename under the OLD name, so `<name>.lock` is very often the
11
+ * only name that ever arrives. The watcher used to match an allowlist of final
12
+ * names (`index`, `HEAD`, `MERGE_HEAD`, `REBASE_HEAD`) and, in the sibling
13
+ * `refs/` watcher, to discard every `.lock` outright. Between them, an external
14
+ * commit, checkout, branch creation, stash or tag produced no event at all —
15
+ * the panel only refreshed when an unrelated working-tree write happened to
16
+ * coincide with it.
17
+ *
18
+ * The event names below are transcribed from what the watcher actually
19
+ * received while driving real git commands, not invented.
20
+ */
21
+ describe('isGitStateEvent', () => {
22
+ test('accepts the lock files git actually reports', () => {
23
+ // `git commit`
24
+ expect(isGitStateEvent('index.lock')).toBe(true);
25
+ expect(isGitStateEvent('HEAD.lock')).toBe(true);
26
+ expect(isGitStateEvent('refs/heads/main.lock')).toBe(true);
27
+ // `git tag` / `git stash`
28
+ expect(isGitStateEvent('refs/tags/v1.lock')).toBe(true);
29
+ expect(isGitStateEvent('refs/stash.lock')).toBe(true);
30
+ // `git branch -D` / `git tag -d` on a packed repo
31
+ expect(isGitStateEvent('packed-refs.lock')).toBe(true);
32
+ });
33
+
34
+ test('accepts the settled names too, so no platform is left out', () => {
35
+ // Linux reports both halves of the rename; Windows and network shares
36
+ // differ again. Accepting only one form would move the hole, not close it.
37
+ expect(isGitStateEvent('index')).toBe(true);
38
+ expect(isGitStateEvent('HEAD')).toBe(true);
39
+ expect(isGitStateEvent('refs/heads/main')).toBe(true);
40
+ expect(isGitStateEvent('packed-refs')).toBe(true);
41
+ });
42
+
43
+ test('accepts in-progress operation markers the panel reads', () => {
44
+ // `detectGitOperation` reads exactly these to render the merge/rebase
45
+ // banner, so the watcher has to report them.
46
+ expect(isGitStateEvent('MERGE_HEAD')).toBe(true);
47
+ expect(isGitStateEvent('CHERRY_PICK_HEAD')).toBe(true);
48
+ expect(isGitStateEvent('REVERT_HEAD')).toBe(true);
49
+ expect(isGitStateEvent('BISECT_LOG')).toBe(true);
50
+ expect(isGitStateEvent('rebase-merge/done')).toBe(true);
51
+ expect(isGitStateEvent('rebase-apply/next')).toBe(true);
52
+ });
53
+
54
+ test('accepts the reflog, which is sometimes the only event delivered', () => {
55
+ // A recursive watch on the project root reports `git branch` solely as a
56
+ // reflog write; the ref's own lock file never surfaces there.
57
+ expect(isGitStateEvent('logs/HEAD')).toBe(true);
58
+ expect(isGitStateEvent('logs/refs/heads/feature')).toBe(true);
59
+ });
60
+
61
+ test('accepts remote-tracking updates from a fetch', () => {
62
+ expect(isGitStateEvent('refs/remotes/origin/main.lock')).toBe(true);
63
+ expect(isGitStateEvent('FETCH_HEAD')).toBe(true);
64
+ });
65
+
66
+ test('rejects pure content churn and entries the panel never reads', () => {
67
+ expect(isGitStateEvent('objects/ea/b10512e0f8')).toBe(false);
68
+ expect(isGitStateEvent('objects/7a/tmp_obj_WG7qLP')).toBe(false);
69
+ expect(isGitStateEvent('lfs/tmp/abc')).toBe(false);
70
+ expect(isGitStateEvent('hooks/pre-commit.sample')).toBe(false);
71
+ expect(isGitStateEvent('info/exclude')).toBe(false);
72
+ expect(isGitStateEvent('COMMIT_EDITMSG')).toBe(false);
73
+ expect(isGitStateEvent('MERGE_MSG')).toBe(false);
74
+ });
75
+
76
+ test('rejects an empty or self-referential path', () => {
77
+ expect(isGitStateEvent('')).toBe(false);
78
+ expect(isGitStateEvent('.')).toBe(false);
79
+ });
80
+
81
+ test('reads Windows separators the same way', () => {
82
+ expect(isGitStateEvent('refs\\heads\\main.lock')).toBe(true);
83
+ expect(isGitStateEvent('objects\\ea\\b10512')).toBe(false);
84
+ });
85
+ });
86
+
87
+ describe('stripGitLockSuffix', () => {
88
+ test('removes the suffix only when it is one', () => {
89
+ expect(stripGitLockSuffix('index.lock')).toBe('index');
90
+ expect(stripGitLockSuffix('refs/heads/main.lock')).toBe('refs/heads/main');
91
+ expect(stripGitLockSuffix('index')).toBe('index');
92
+ // A branch legitimately named `…lock` must not lose characters.
93
+ expect(stripGitLockSuffix('refs/heads/deadlock')).toBe('refs/heads/deadlock');
94
+ });
95
+ });
96
+
97
+ describe('hasGitSegment', () => {
98
+ test('recognises a git directory anywhere in the path', () => {
99
+ expect(hasGitSegment('.git/index')).toBe(true);
100
+ // The sub-repo case: this is the path the project's own recursive watch
101
+ // reports when a commit is made inside a nested repo.
102
+ expect(hasGitSegment('sdks/php/.git/refs/heads/main.lock')).toBe(true);
103
+ });
104
+
105
+ test('does not match names that merely start with .git', () => {
106
+ expect(hasGitSegment('.gitignore')).toBe(false);
107
+ expect(hasGitSegment('.github/workflows/ci.yml')).toBe(false);
108
+ expect(hasGitSegment('src/app.ts')).toBe(false);
109
+ });
110
+ });
@@ -0,0 +1,132 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile, mkdir, realpath } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { execGit } from './git-executor';
6
+ import { resolveGitDirs } from './git-dirs';
7
+
8
+ /**
9
+ * The watcher used to look for a `.git` DIRECTORY at the project root and give
10
+ * up when it found none. That silently produced no event source at all for
11
+ * every layout below — the panel still rendered correct data (git walks up on
12
+ * its own) but never learnt that anything had changed.
13
+ */
14
+
15
+ let root: string;
16
+
17
+ async function git(cwd: string, ...args: string[]) {
18
+ const result = await execGit(args, cwd);
19
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
20
+ return result.stdout;
21
+ }
22
+
23
+ async function initRepo(dir: string) {
24
+ await mkdir(dir, { recursive: true });
25
+ await git(dir, 'init', '-b', 'main', '.');
26
+ await git(dir, 'config', 'user.email', 'test@example.com');
27
+ await git(dir, 'config', 'user.name', 'Test');
28
+ await git(dir, 'config', 'commit.gpgsign', 'false');
29
+ }
30
+
31
+ async function commitSomething(dir: string, name = 'file.txt') {
32
+ await writeFile(path.join(dir, name), 'content\n');
33
+ await git(dir, 'add', '-A');
34
+ await git(dir, 'commit', '-m', 'init');
35
+ }
36
+
37
+ beforeEach(async () => {
38
+ // The temp dir is a symlink on macOS (/var -> /private/var); resolve it so
39
+ // the paths git reports and the paths we assert on are the same strings.
40
+ root = await realpath(await mkdtemp(path.join(tmpdir(), 'clopen-git-dirs-')));
41
+ });
42
+
43
+ afterEach(async () => {
44
+ await rm(root, { recursive: true, force: true });
45
+ });
46
+
47
+ describe('resolveGitDirs', () => {
48
+ test('resolves a plain repo to its own .git', async () => {
49
+ await initRepo(root);
50
+ await commitSomething(root);
51
+
52
+ const targets = await resolveGitDirs(root);
53
+
54
+ expect(targets).toHaveLength(1);
55
+ expect(targets[0].repoPath).toBe(root);
56
+ expect(targets[0].gitDir).toBe(path.join(root, '.git'));
57
+ expect(targets[0].commonDir).toBe(path.join(root, '.git'));
58
+ });
59
+
60
+ test('returns nothing for a directory that is not a repo', async () => {
61
+ expect(await resolveGitDirs(root)).toEqual([]);
62
+ });
63
+
64
+ test('resolves a project opened at a SUBFOLDER of a repo', async () => {
65
+ // No `.git` exists at the opened path, so the old existsSync probe found
66
+ // nothing and the project got no git watcher whatsoever.
67
+ await initRepo(root);
68
+ await commitSomething(root);
69
+ const subfolder = path.join(root, 'packages', 'web');
70
+ await mkdir(subfolder, { recursive: true });
71
+
72
+ const targets = await resolveGitDirs(subfolder);
73
+
74
+ expect(targets).toHaveLength(1);
75
+ expect(targets[0].gitDir).toBe(path.join(root, '.git'));
76
+ });
77
+
78
+ test('resolves a linked worktree to its own dir AND the shared common dir', async () => {
79
+ // A worktree's `.git` is a FILE. Watching it caught nothing, and `refs/`
80
+ // does not exist beneath it — the branch list lives in the common dir.
81
+ await initRepo(root);
82
+ await commitSomething(root);
83
+ const worktree = path.join(root, '..', path.basename(root) + '-wt');
84
+ await git(root, 'worktree', 'add', '-b', 'side', worktree);
85
+
86
+ try {
87
+ const targets = await resolveGitDirs(await realpath(worktree));
88
+
89
+ expect(targets).toHaveLength(1);
90
+ expect(targets[0].gitDir).toBe(path.join(root, '.git', 'worktrees', path.basename(worktree)));
91
+ expect(targets[0].commonDir).toBe(path.join(root, '.git'));
92
+ // The two differ — which is exactly why both have to be watched.
93
+ expect(targets[0].gitDir).not.toBe(targets[0].commonDir);
94
+ } finally {
95
+ await rm(worktree, { recursive: true, force: true });
96
+ }
97
+ });
98
+
99
+ test('includes each nested sub-repo alongside the project repo', async () => {
100
+ await initRepo(root);
101
+ await commitSomething(root);
102
+ const nested = path.join(root, 'sdks', 'php');
103
+ await initRepo(nested);
104
+ await commitSomething(nested, 'README.md');
105
+
106
+ const targets = await resolveGitDirs(root);
107
+ const byRepoPath = new Map(targets.map((target) => [target.repoPath, target]));
108
+
109
+ expect(byRepoPath.has(root)).toBe(true);
110
+ expect(byRepoPath.has(nested)).toBe(true);
111
+ expect(byRepoPath.get(nested)!.gitDir).toBe(path.join(nested, '.git'));
112
+ });
113
+
114
+ test('resolves a submodule to its git dir inside the superproject', async () => {
115
+ // A submodule's `.git` is a FILE pointing at `<super>/.git/modules/<name>`.
116
+ const upstream = path.join(root, 'upstream');
117
+ await initRepo(upstream);
118
+ await commitSomething(upstream);
119
+
120
+ const superproject = path.join(root, 'super');
121
+ await initRepo(superproject);
122
+ await commitSomething(superproject);
123
+ await git(superproject, '-c', 'protocol.file.allow=always', 'submodule', 'add', upstream, 'vendor/lib');
124
+ await git(superproject, 'commit', '-m', 'add submodule');
125
+
126
+ const targets = await resolveGitDirs(superproject);
127
+ const submodule = targets.find((target) => target.repoPath === path.join(superproject, 'vendor', 'lib'));
128
+
129
+ expect(submodule).toBeDefined();
130
+ expect(submodule!.gitDir).toBe(path.join(superproject, '.git', 'modules', 'vendor', 'lib'));
131
+ });
132
+ });
Binary file