@myrialabs/clopen 0.4.27 → 0.4.29

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 (47) hide show
  1. package/backend/auth/auth-service.ts +45 -25
  2. package/backend/auth/onboarding.test.ts +106 -0
  3. package/backend/auth/permissions.ts +1 -1
  4. package/backend/database/utils/connection.ts +7 -31
  5. package/backend/engine/README.md +8 -3
  6. package/backend/engine/adapters/claude/message-converter.ts +55 -23
  7. package/backend/engine/adapters/codex/message-converter.ts +8 -2
  8. package/backend/engine/adapters/codex/models.ts +85 -98
  9. package/backend/engine/adapters/codex/stream.ts +5 -7
  10. package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
  11. package/backend/engine/adapters/copilot/stream.ts +24 -0
  12. package/backend/engine/docs/lessons-learned.md +78 -1
  13. package/backend/engine/docs/stack.md +8 -0
  14. package/backend/engine/install-recipes.ts +19 -2
  15. package/backend/files/file-size-limit.ts +5 -14
  16. package/backend/files/file-watcher.test.ts +160 -0
  17. package/backend/files/file-watcher.ts +276 -58
  18. package/backend/git/git-executor.ts +8 -0
  19. package/backend/git/git-service.test.ts +136 -0
  20. package/backend/git/git-service.ts +113 -17
  21. package/backend/index.ts +11 -4
  22. package/backend/mcp/internal/remote-server.test.ts +8 -3
  23. package/backend/mcp/internal/remote-server.ts +1 -1
  24. package/backend/settings/system-settings.ts +97 -0
  25. package/backend/tunnel/public-origin.ts +5 -13
  26. package/backend/utils/env.ts +29 -0
  27. package/backend/utils/paths.ts +9 -3
  28. package/backend/ws/auth/login.test.ts +8 -1
  29. package/backend/ws/auth/login.ts +22 -15
  30. package/backend/ws/auth/status.ts +24 -1
  31. package/backend/ws/chat/stream.ts +1 -0
  32. package/backend/ws/engine/claude/accounts.ts +4 -12
  33. package/backend/ws/engine/codex/accounts.ts +4 -13
  34. package/backend/ws/engine/pty-output.test.ts +37 -0
  35. package/backend/ws/engine/pty-output.ts +43 -0
  36. package/backend/ws/files/watch.ts +9 -0
  37. package/backend/ws/settings/crud.ts +14 -22
  38. package/dist/assets/{index-BTGcf_Vy.js → index-C7e5TWG3.js} +1 -1
  39. package/dist/assets/{index-BCv5HlPk.js → index-Derlqeyy.js} +1 -1
  40. package/dist/assets/{main-BrqMMMRX.css → main-CqzaPnux.css} +1 -1
  41. package/dist/assets/main-OGhsRKU1.js +1037 -0
  42. package/dist/index.html +2 -2
  43. package/package.json +14 -14
  44. package/shared/constants/engines.ts +1 -0
  45. package/shared/types/stores/settings.ts +11 -1
  46. package/shared/types/unified/stream.ts +10 -4
  47. package/dist/assets/main-CgmAFpU3.js +0 -1036
@@ -7,10 +7,29 @@
7
7
  * - Debounced events to prevent spam
8
8
  * - Automatic cleanup on unwatch
9
9
  * - Cross-platform support (Windows/Unix)
10
+ *
11
+ * Watching strategy, per platform:
12
+ *
13
+ * macOS and Windows get a single `{ recursive: true }` watch on the project
14
+ * root. Both back it with one OS-level handle (FSEvents / ReadDirectoryChangesW)
15
+ * that covers the whole subtree, so recursion is essentially free and pruning
16
+ * would buy nothing.
17
+ *
18
+ * Linux cannot do that. There, recursion is emulated with inotify and costs one
19
+ * kernel watch per directory, with no way to exclude any of them. A project
20
+ * containing `node_modules` blows past `fs.inotify.max_user_watches`; the
21
+ * watcher faults with ENOSPC, gets rebuilt, and faults again — an endless
22
+ * restart loop that pegged the CPU and, because each restart announced itself as
23
+ * a file change, made clients reload every few seconds with nothing actually
24
+ * changing. So on Linux we walk the tree ourselves and never watch an ignored
25
+ * directory, which removes the overwhelming majority of the watch descriptors.
10
26
  */
11
27
 
28
+ /** Whether the platform's recursive `fs.watch` is a single cheap OS handle. */
29
+ const USE_NATIVE_RECURSIVE_WATCH = process.platform !== 'linux';
30
+
12
31
  import { watch, type FSWatcher, existsSync } from 'node:fs';
13
- import { stat } from 'node:fs/promises';
32
+ import { stat, readdir } from 'node:fs/promises';
14
33
  import { join, relative, normalize, sep } from 'node:path';
15
34
  import { ws } from '$backend/utils/ws';
16
35
  import { debug } from '$shared/utils/logger';
@@ -21,6 +40,21 @@ import type { FileChange } from '$shared/types/filesystem';
21
40
  */
22
41
  const DEBOUNCE_MS = 300; // Debounce file change events
23
42
 
43
+ /**
44
+ * Hard ceiling on directory watches per project (Linux manual recursion only).
45
+ * Even with ignored directories pruned, a pathological tree (generated code, a
46
+ * huge monorepo) could still exhaust `max_user_watches`. Stop adding watches
47
+ * past this point and tell the client its view may go stale, rather than
48
+ * faulting into the restart loop this whole design exists to prevent.
49
+ */
50
+ const MAX_WATCHED_DIRS = 4000;
51
+
52
+ /** Restart backoff after a watcher fault: 1s, 2s, 4s, 8s, then give up. */
53
+ const RESTART_DELAYS_MS = [1000, 2000, 4000, 8000];
54
+
55
+ /** How long a rebuilt watcher must survive before its fault count is forgiven. */
56
+ const FAULT_FORGIVENESS_MS = 60_000;
57
+
24
58
  /**
25
59
  * Directories to ignore when watching
26
60
  */
@@ -64,12 +98,18 @@ const GIT_DEBOUNCE_MS = 500;
64
98
  * Watcher instance for a project
65
99
  */
66
100
  interface ProjectWatcher {
67
- watcher: FSWatcher;
68
101
  projectPath: string;
69
102
  projectId: string;
70
103
  debounceTimer: ReturnType<typeof setTimeout> | null;
71
104
  pendingChanges: Map<string, FileChange>;
72
- subWatchers: Map<string, FSWatcher>;
105
+ /** Absolute directory path -> its (non-recursive) watcher. Includes the root. */
106
+ dirWatchers: Map<string, FSWatcher>;
107
+ /** Set once MAX_WATCHED_DIRS was hit, so the warning is emitted only once. */
108
+ truncated: boolean;
109
+ /** Consecutive watcher faults; reset after a clean restart. */
110
+ faults: number;
111
+ /** Flipped by stopWatching so in-flight async tree walks bail out. */
112
+ closed: boolean;
73
113
  gitWatcher: FSWatcher | null;
74
114
  gitRefsWatcher: FSWatcher | null;
75
115
  gitDebounceTimer: ReturnType<typeof setTimeout> | null;
@@ -172,7 +212,7 @@ class FileWatcherManager {
172
212
  * near-simultaneous viewers (e.g. two devices) could each build a watcher and
173
213
  * leak one.
174
214
  */
175
- async startWatching(projectId: string, projectPath: string): Promise<boolean> {
215
+ async startWatching(projectId: string, projectPath: string, faults = 0): Promise<boolean> {
176
216
  // Already watching this project
177
217
  if (this.watchers.has(projectId)) {
178
218
  debug.log('file', `Already watching project: ${projectId}`);
@@ -182,7 +222,7 @@ class FileWatcherManager {
182
222
  const inflight = this.starting.get(projectId);
183
223
  if (inflight) return inflight;
184
224
 
185
- const startPromise = this.doStartWatching(projectId, projectPath);
225
+ const startPromise = this.doStartWatching(projectId, projectPath, faults);
186
226
  this.starting.set(projectId, startPromise);
187
227
  try {
188
228
  return await startPromise;
@@ -191,7 +231,11 @@ class FileWatcherManager {
191
231
  }
192
232
  }
193
233
 
194
- private async doStartWatching(projectId: string, projectPath: string): Promise<boolean> {
234
+ private async doStartWatching(
235
+ projectId: string,
236
+ projectPath: string,
237
+ faults = 0
238
+ ): Promise<boolean> {
195
239
  try {
196
240
  // Normalize path
197
241
  const normalizedPath = normalize(projectPath);
@@ -203,42 +247,47 @@ class FileWatcherManager {
203
247
  return false;
204
248
  }
205
249
 
206
- // Create main watcher for project root
207
- const watcher = watch(normalizedPath, { recursive: true }, (eventType, filename) => {
208
- if (filename) {
209
- this.handleFileChange(projectId, normalizedPath, filename, eventType);
210
- }
211
- });
212
-
213
- // Handle watcher errors. fs.watch can fault (and on some platforms go
214
- // silently deaf) under heavy churn or after sleep/wake — recover by
215
- // rebuilding the watcher instead of leaving the project stuck stale.
216
- watcher.on('error', (error) => {
217
- debug.error('file', `Watcher error for project ${projectId}:`, error);
218
- ws.emit.project(projectId, 'files:watch-error', {
219
- projectId,
220
- error: error.message || 'File watcher error'
221
- });
222
- this.scheduleRestart(projectId);
223
- });
224
-
225
- // Store watcher instance
226
250
  const projectWatcher: ProjectWatcher = {
227
- watcher,
228
251
  projectPath: normalizedPath,
229
252
  projectId,
230
253
  debounceTimer: null,
231
254
  pendingChanges: new Map(),
232
- subWatchers: new Map(),
255
+ dirWatchers: new Map(),
256
+ truncated: false,
257
+ faults,
258
+ closed: false,
233
259
  gitWatcher: null,
234
260
  gitRefsWatcher: null,
235
261
  gitDebounceTimer: null
236
262
  };
237
263
  this.watchers.set(projectId, projectWatcher);
238
264
 
265
+ // Watch the root synchronously so events are never missed while the
266
+ // (async) subtree walk is still in progress.
267
+ if (!this.watchDir(projectWatcher, normalizedPath)) {
268
+ this.watchers.delete(projectId);
269
+ return false;
270
+ }
271
+
239
272
  // Start git state watcher (for external git operations)
240
273
  this.startGitWatcher(projectId, normalizedPath);
241
274
 
275
+ // On Linux the root watch only covers the root itself. Walk the tree in
276
+ // the background so every non-ignored directory gets its own watch;
277
+ // elsewhere the root's recursive handle already covers everything.
278
+ if (!USE_NATIVE_RECURSIVE_WATCH) {
279
+ void this.watchSubtree(projectWatcher, normalizedPath);
280
+ }
281
+
282
+ // Forgive earlier faults once a rebuild has held steady, so an isolated
283
+ // hiccup much later still gets the full retry budget instead of
284
+ // inheriting an exhausted one.
285
+ if (faults > 0) {
286
+ setTimeout(() => {
287
+ if (this.watchers.get(projectId) === projectWatcher) projectWatcher.faults = 0;
288
+ }, FAULT_FORGIVENESS_MS);
289
+ }
290
+
242
291
  debug.log('file', `Started watching project: ${projectId} at ${normalizedPath}`);
243
292
  return true;
244
293
  } catch (error) {
@@ -247,6 +296,121 @@ class FileWatcherManager {
247
296
  }
248
297
  }
249
298
 
299
+ /**
300
+ * Attach a non-recursive watcher to a single directory.
301
+ * Returns false when the directory could not be watched (gone, permission
302
+ * denied, or the per-project ceiling was reached).
303
+ */
304
+ private watchDir(pw: ProjectWatcher, dir: string): boolean {
305
+ if (pw.closed || pw.dirWatchers.has(dir)) return true;
306
+
307
+ if (pw.dirWatchers.size >= MAX_WATCHED_DIRS) {
308
+ if (!pw.truncated) {
309
+ pw.truncated = true;
310
+ debug.warn(
311
+ 'file',
312
+ `Watch ceiling (${MAX_WATCHED_DIRS} dirs) reached for project ${pw.projectId}; deeper directories will not report changes`
313
+ );
314
+ ws.emit.project(pw.projectId, 'files:watch-error', {
315
+ projectId: pw.projectId,
316
+ error: `Project is too large to watch entirely (${MAX_WATCHED_DIRS}+ directories). Changes in deeply nested folders may not appear automatically.`
317
+ });
318
+ }
319
+ return false;
320
+ }
321
+
322
+ try {
323
+ // The root watch is recursive where that's a single OS handle; every
324
+ // other watch (and every Linux watch) covers exactly one directory.
325
+ // Either way `filename` arrives relative to `dir`, so the change handler
326
+ // resolves it the same way.
327
+ const recursive = USE_NATIVE_RECURSIVE_WATCH && dir === pw.projectPath;
328
+ const watcher = watch(dir, { recursive }, (eventType, filename) => {
329
+ if (filename) this.handleFileChange(pw.projectId, dir, filename, eventType);
330
+ });
331
+
332
+ // fs.watch can fault (and on some platforms go silently deaf) under heavy
333
+ // churn or after sleep/wake. A fault on a nested directory only costs us
334
+ // that subtree, so drop it quietly; a fault on the root means the project
335
+ // is unwatched and warrants a full rebuild.
336
+ watcher.on('error', (error) => {
337
+ if (dir === pw.projectPath) {
338
+ debug.error('file', `Watcher error for project ${pw.projectId}:`, error);
339
+ ws.emit.project(pw.projectId, 'files:watch-error', {
340
+ projectId: pw.projectId,
341
+ error: error.message || 'File watcher error'
342
+ });
343
+ this.scheduleRestart(pw.projectId);
344
+ } else {
345
+ debug.warn('file', `Dropping faulted watcher for ${dir}:`, error);
346
+ this.unwatchDir(pw, dir);
347
+ }
348
+ });
349
+
350
+ pw.dirWatchers.set(dir, watcher);
351
+ return true;
352
+ } catch (error) {
353
+ // ENOENT/EACCES on a nested directory is normal (it may have vanished
354
+ // between readdir and watch); only the root failing is fatal.
355
+ if (dir === pw.projectPath) {
356
+ debug.error('file', `Failed to watch project root ${dir}:`, error);
357
+ return false;
358
+ }
359
+ debug.log('file', `Skipped unwatchable directory ${dir}`);
360
+ return false;
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Close the watcher for `dir` and every directory beneath it.
366
+ * Called when a directory is deleted or renamed away.
367
+ */
368
+ private unwatchDir(pw: ProjectWatcher, dir: string): void {
369
+ const prefix = dir.endsWith(sep) ? dir : dir + sep;
370
+ for (const [watched, watcher] of pw.dirWatchers) {
371
+ if (watched !== dir && !watched.startsWith(prefix)) continue;
372
+ try {
373
+ watcher.close();
374
+ } catch {
375
+ // Already closed — nothing to do.
376
+ }
377
+ pw.dirWatchers.delete(watched);
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Recursively attach watchers to every non-ignored directory under `dir`.
383
+ * Ignored directories (node_modules, .git, build output, …) are never
384
+ * descended into — that pruning is what keeps the watch count survivable.
385
+ */
386
+ private async watchSubtree(pw: ProjectWatcher, dir: string): Promise<void> {
387
+ if (pw.closed) return;
388
+
389
+ let entries;
390
+ try {
391
+ entries = await readdir(dir, { withFileTypes: true });
392
+ } catch {
393
+ return; // Directory vanished or is unreadable — nothing to watch.
394
+ }
395
+
396
+ for (const entry of entries) {
397
+ if (pw.closed) return;
398
+ if (!entry.isDirectory()) continue;
399
+
400
+ const childPath = join(dir, entry.name);
401
+ const relativePath = relative(pw.projectPath, childPath).replace(/\\/g, '/');
402
+ if (this.shouldIgnore(relativePath)) continue;
403
+
404
+ if (!this.watchDir(pw, childPath)) {
405
+ // Ceiling reached — stop descending entirely rather than watching an
406
+ // arbitrary subset that depends on directory ordering.
407
+ if (pw.truncated) return;
408
+ continue;
409
+ }
410
+ await this.watchSubtree(pw, childPath);
411
+ }
412
+ }
413
+
250
414
  /**
251
415
  * Stop watching a project directory
252
416
  */
@@ -258,13 +422,18 @@ class FileWatcherManager {
258
422
  }
259
423
 
260
424
  try {
261
- // Close main watcher
262
- projectWatcher.watcher.close();
263
-
264
- // Close all sub-watchers
265
- for (const subWatcher of projectWatcher.subWatchers.values()) {
266
- subWatcher.close();
425
+ // Stop any in-flight subtree walk from re-adding watchers behind us.
426
+ projectWatcher.closed = true;
427
+
428
+ // Close every directory watcher (the root included)
429
+ for (const dirWatcher of projectWatcher.dirWatchers.values()) {
430
+ try {
431
+ dirWatcher.close();
432
+ } catch {
433
+ // Already closed — nothing to do.
434
+ }
267
435
  }
436
+ projectWatcher.dirWatchers.clear();
268
437
 
269
438
  // Close git watchers
270
439
  projectWatcher.gitWatcher?.close();
@@ -315,44 +484,60 @@ class FileWatcherManager {
315
484
  }
316
485
 
317
486
  /**
318
- * Handle file change event
487
+ * Handle a change reported by the watcher on `dir`.
488
+ * `filename` is relative to `dir`, not to the project root.
319
489
  */
320
490
  private async handleFileChange(
321
491
  projectId: string,
322
- projectPath: string,
492
+ dir: string,
323
493
  filename: string,
324
494
  eventType: string
325
495
  ): Promise<void> {
326
496
  const projectWatcher = this.watchers.get(projectId);
327
- if (!projectWatcher) return;
497
+ if (!projectWatcher || projectWatcher.closed) return;
328
498
 
329
- // Normalize filename to use forward slashes for consistency
330
- const normalizedFilename = filename.replace(/\\/g, '/');
499
+ // Build full path, then derive the project-relative path — the ignore rules
500
+ // are defined against the project root, and `filename` is only relative to
501
+ // the directory that reported it.
502
+ const fullPath = join(dir, filename);
503
+ const relativePath = relative(projectWatcher.projectPath, fullPath).replace(/\\/g, '/');
331
504
 
332
- // Check if should be ignored
333
- if (this.shouldIgnore(normalizedFilename)) {
505
+ // 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)) {
334
508
  return;
335
509
  }
336
510
 
337
- // Build full path
338
- const fullPath = join(projectPath, filename);
339
-
340
511
  // Determine change type
341
512
  let changeType: 'created' | 'modified' | 'deleted';
513
+ let isDirectory = false;
342
514
  if (eventType === 'change') {
343
515
  changeType = 'modified';
344
516
  } else {
345
517
  // 'rename' event — check if file exists to distinguish create from delete
346
518
  try {
347
- await stat(fullPath);
519
+ const entryStat = await stat(fullPath);
520
+ isDirectory = entryStat.isDirectory();
348
521
  changeType = 'created';
349
522
  } catch {
350
523
  changeType = 'deleted';
351
524
  }
352
525
  }
353
526
 
527
+ // Where recursion is emulated, keep the watch set in step with the tree: a
528
+ // new directory needs its own watcher, and a removed one must release its
529
+ // descendants' watchers so they can't leak.
530
+ if (!USE_NATIVE_RECURSIVE_WATCH) {
531
+ if (isDirectory && changeType === 'created') {
532
+ if (this.watchDir(projectWatcher, fullPath)) {
533
+ void this.watchSubtree(projectWatcher, fullPath);
534
+ }
535
+ } else if (changeType === 'deleted' && projectWatcher.dirWatchers.has(fullPath)) {
536
+ this.unwatchDir(projectWatcher, fullPath);
537
+ }
538
+ }
539
+
354
540
  // Track dirty file for snapshot system
355
- const relativePath = relative(projectPath, fullPath).replace(/\\/g, '/');
356
541
  this.trackDirtyFile(projectId, relativePath);
357
542
 
358
543
  // Create file change object
@@ -447,10 +632,14 @@ class FileWatcherManager {
447
632
  // Silently ignore git watcher errors
448
633
  });
449
634
 
450
- // Watch .git/refs/ for branch/tag create/delete
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.
451
639
  const refsDir = join(gitDir, 'refs');
452
640
  if (existsSync(refsDir)) {
453
- projectWatcher.gitRefsWatcher = watch(refsDir, { recursive: true }, (_eventType, _filename) => {
641
+ projectWatcher.gitRefsWatcher = watch(refsDir, { recursive: true }, (_eventType, filename) => {
642
+ if (filename && filename.replace(/\\/g, '/').endsWith('.lock')) return;
454
643
  this.emitGitChanged(projectId);
455
644
  });
456
645
  projectWatcher.gitRefsWatcher.on('error', () => {
@@ -486,13 +675,37 @@ class FileWatcherManager {
486
675
  }
487
676
 
488
677
  /**
489
- * Schedule a debounced rebuild of a project's watcher after a fault.
490
- * Guarded so overlapping error events don't spawn multiple restarts.
678
+ * Schedule a rebuild of a project's watcher after a fault, backing off on
679
+ * each consecutive failure and giving up once the backoff is exhausted.
680
+ *
681
+ * The backoff matters: a fault whose cause is structural (the platform watch
682
+ * limit, a permission change) reproduces immediately on restart. A fixed 1s
683
+ * retry turned that into an endless rebuild loop that pegged the CPU and,
684
+ * because each restart announced itself as a file change, made every client
685
+ * reload its editor every second.
491
686
  */
492
687
  private scheduleRestart(projectId: string): void {
493
688
  if (this.restarting.has(projectId)) return;
494
689
  // Only restart if someone is still viewing the project.
495
690
  if (!this.viewers.get(projectId)?.size) return;
691
+
692
+ const current = this.watchers.get(projectId);
693
+ if (!current) return;
694
+
695
+ const attempt = current.faults;
696
+ const delay = RESTART_DELAYS_MS[attempt];
697
+ if (delay === undefined) {
698
+ debug.error(
699
+ 'file',
700
+ `Watcher for project ${projectId} faulted ${attempt} times; giving up on automatic restart`
701
+ );
702
+ ws.emit.project(projectId, 'files:watch-error', {
703
+ projectId,
704
+ error: 'File watching stopped after repeated failures. Refresh to retry.'
705
+ });
706
+ return;
707
+ }
708
+
496
709
  this.restarting.add(projectId);
497
710
 
498
711
  setTimeout(async () => {
@@ -502,18 +715,23 @@ class FileWatcherManager {
502
715
  const projectPath = this.watchers.get(projectId)?.projectPath;
503
716
  if (!projectPath) return;
504
717
 
505
- debug.warn('file', `Restarting faulted watcher for project ${projectId}`);
718
+ debug.warn(
719
+ 'file',
720
+ `Restarting faulted watcher for project ${projectId} (attempt ${attempt + 1})`
721
+ );
506
722
  this.stopWatching(projectId);
507
- await this.startWatching(projectId, projectPath);
508
-
509
- // A faulted watcher may have dropped events while down — nudge clients
510
- // to reconcile so nothing stays stale.
511
- ws.emit.project(projectId, 'files:changed', {
723
+ const ok = await this.startWatching(projectId, projectPath, attempt + 1);
724
+ if (!ok) return;
725
+
726
+ // A faulted watcher may have dropped events while down. Ask clients to
727
+ // reconcile — deliberately NOT via `files:changed`, which means "these
728
+ // specific paths changed" and made consumers tear down and rebuild live
729
+ // views (the open diff editor) on every restart.
730
+ ws.emit.project(projectId, 'files:resync', {
512
731
  projectId,
513
- changes: [],
514
732
  timestamp: Date.now()
515
733
  });
516
- }, 1000);
734
+ }, delay);
517
735
  }
518
736
 
519
737
  /**
@@ -35,6 +35,14 @@ export async function execGit(
35
35
  ...getCleanSpawnEnv(),
36
36
  // Prevent git from prompting for credentials
37
37
  GIT_TERMINAL_PROMPT: '0',
38
+ // Read-only commands must stay read-only. Without this, `git status`
39
+ // opportunistically rewrites `.git/index` to refresh cached stat data —
40
+ // which trips our own `.git` watcher, which emits `git:changed`, which
41
+ // makes the client re-run `git status`. That feedback loop refreshed the
42
+ // Git panel (and reloaded the open diff) every few seconds with nothing
43
+ // actually changing. Commands that genuinely need the index lock (commit,
44
+ // add, checkout) still take it; only the optional refresh is suppressed.
45
+ GIT_OPTIONAL_LOCKS: '0',
38
46
  // Use English output for consistent parsing
39
47
  LANG: 'en_US.UTF-8',
40
48
  LC_ALL: 'en_US.UTF-8'
@@ -0,0 +1,136 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+ import { execGit } from './git-executor';
7
+ import { gitService } from './git-service';
8
+
9
+ /**
10
+ * These cover the two states where HEAD-relative revisions don't resolve:
11
+ * an unborn HEAD (fresh `git init`) and a lone root commit (no `HEAD~1`).
12
+ * Both used to surface git's raw `fatal: ambiguous argument` in the UI.
13
+ */
14
+
15
+ let repo: string;
16
+
17
+ async function git(...args: string[]) {
18
+ const result = await execGit(args, repo);
19
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
20
+ return result.stdout;
21
+ }
22
+
23
+ async function commitAll(message: string) {
24
+ await git('add', '-A');
25
+ await git('commit', '-m', message);
26
+ }
27
+
28
+ beforeEach(async () => {
29
+ repo = await mkdtemp(path.join(tmpdir(), 'clopen-git-'));
30
+ await git('init', '-b', 'main', '.');
31
+ await git('config', 'user.email', 'test@example.com');
32
+ await git('config', 'user.name', 'Test');
33
+ await git('config', 'commit.gpgsign', 'false');
34
+ });
35
+
36
+ afterEach(async () => {
37
+ await rm(repo, { recursive: true, force: true });
38
+ });
39
+
40
+ describe('undoLastCommit — no commits yet', () => {
41
+ test('reports an actionable message instead of git\'s fatal', async () => {
42
+ await expect(gitService.undoLastCommit(repo, 'soft')).rejects.toThrow(/no commits yet/i);
43
+ });
44
+ });
45
+
46
+ describe('undoLastCommit — root commit', () => {
47
+ beforeEach(async () => {
48
+ await writeFile(path.join(repo, 'a.txt'), 'hello\n');
49
+ await mkdir(path.join(repo, 'src'), { recursive: true });
50
+ await writeFile(path.join(repo, 'src', 'b.txt'), 'world\n');
51
+ await commitAll('init');
52
+ // An unrelated untracked file must survive every mode, including --hard.
53
+ await writeFile(path.join(repo, 'keep.txt'), 'untracked\n');
54
+ });
55
+
56
+ test('soft removes the commit and keeps its files staged', async () => {
57
+ await gitService.undoLastCommit(repo, 'soft');
58
+
59
+ const status = await gitService.getStatus(repo);
60
+ expect(status.staged.map(f => f.path).sort()).toEqual(['a.txt', 'src/b.txt']);
61
+ expect((await execGit(['rev-parse', '--verify', '--quiet', 'HEAD'], repo)).exitCode).not.toBe(0);
62
+ expect(existsSync(path.join(repo, 'keep.txt'))).toBe(true);
63
+ });
64
+
65
+ test('mixed removes the commit and leaves its files untracked', async () => {
66
+ await gitService.undoLastCommit(repo, 'mixed');
67
+
68
+ const status = await gitService.getStatus(repo);
69
+ expect(status.staged).toHaveLength(0);
70
+ expect(status.untracked.map(f => f.path).sort()).toEqual(['a.txt', 'keep.txt', 'src/b.txt']);
71
+ });
72
+
73
+ test('hard removes the commit and deletes only its files', async () => {
74
+ await gitService.undoLastCommit(repo, 'hard');
75
+
76
+ expect(existsSync(path.join(repo, 'a.txt'))).toBe(false);
77
+ expect(existsSync(path.join(repo, 'src', 'b.txt'))).toBe(false);
78
+ expect(existsSync(path.join(repo, 'keep.txt'))).toBe(true);
79
+ expect((await execGit(['rev-parse', '--verify', '--quiet', 'HEAD'], repo)).exitCode).not.toBe(0);
80
+ });
81
+
82
+ test('hard on an empty root commit leaves the repo unborn without erroring', async () => {
83
+ await rm(path.join(repo, 'keep.txt'));
84
+ await git('update-ref', '-d', 'HEAD');
85
+ await git('reset');
86
+ await git('commit', '--allow-empty', '-m', 'empty');
87
+
88
+ await gitService.undoLastCommit(repo, 'hard');
89
+
90
+ expect((await execGit(['rev-parse', '--verify', '--quiet', 'HEAD'], repo)).exitCode).not.toBe(0);
91
+ });
92
+ });
93
+
94
+ describe('undoLastCommit — with a parent commit', () => {
95
+ test('soft moves HEAD back one commit and restages the change', async () => {
96
+ await writeFile(path.join(repo, 'a.txt'), 'one\n');
97
+ await commitAll('first');
98
+ await writeFile(path.join(repo, 'a.txt'), 'two\n');
99
+ await commitAll('second');
100
+
101
+ await gitService.undoLastCommit(repo, 'soft');
102
+
103
+ const log = await gitService.getLog(repo);
104
+ expect(log.commits.map(c => c.message)).toEqual(['first']);
105
+ const status = await gitService.getStatus(repo);
106
+ expect(status.staged.map(f => f.path)).toEqual(['a.txt']);
107
+ });
108
+ });
109
+
110
+ describe('other actions on a repo with no commits', () => {
111
+ test('getLog reports an empty history rather than throwing', async () => {
112
+ expect(await gitService.getLog(repo)).toEqual({ commits: [], total: 0, hasMore: false });
113
+ });
114
+
115
+ test('revertCommit explains there is nothing to revert', async () => {
116
+ const result = await gitService.revertCommit(repo);
117
+ expect(result.success).toBe(false);
118
+ expect(result.message).toMatch(/no commits yet/i);
119
+ });
120
+
121
+ test('amendCommit points at creating the first commit', async () => {
122
+ await expect(gitService.amendCommit(repo)).rejects.toThrow(/no commit to amend/i);
123
+ });
124
+
125
+ test('stashSave explains a commit is required', async () => {
126
+ await writeFile(path.join(repo, 'a.txt'), 'hello\n');
127
+ await expect(gitService.stashSave(repo)).rejects.toThrow(/at least one commit/i);
128
+ });
129
+
130
+ test('push explains there is nothing to push', async () => {
131
+ await git('remote', 'add', 'origin', path.join(repo, 'nonexistent.git'));
132
+ const result = await gitService.push(repo, 'origin', 'main');
133
+ expect(result.success).toBe(false);
134
+ expect(result.message).toMatch(/nothing to push/i);
135
+ });
136
+ });