@myrialabs/clopen 0.3.17 → 0.3.19

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 (34) hide show
  1. package/backend/chat/stream-manager.ts +11 -1
  2. package/backend/database/migrations/038_add_workspace_state_to_user_projects.ts +23 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/project-queries.ts +18 -0
  5. package/backend/db-client/drivers/mongodb.ts +52 -0
  6. package/backend/db-client/drivers/mysql.ts +140 -1
  7. package/backend/db-client/drivers/postgres.ts +152 -5
  8. package/backend/db-client/drivers/redis.ts +27 -0
  9. package/backend/db-client/drivers/sqlite.ts +66 -0
  10. package/backend/db-client/drivers/types.ts +13 -0
  11. package/backend/git/git-service.ts +135 -2
  12. package/backend/preview/browser/browser-preview-service.ts +53 -17
  13. package/backend/snapshot/snapshot-service.ts +82 -52
  14. package/backend/utils/ws.ts +3 -1
  15. package/backend/ws/db-client/schema.ts +14 -0
  16. package/backend/ws/db-client/structure.ts +120 -0
  17. package/backend/ws/git/commit.ts +63 -0
  18. package/backend/ws/git/remote.ts +36 -1
  19. package/backend/ws/index.ts +2 -0
  20. package/backend/ws/preview/access.ts +20 -1
  21. package/backend/ws/preview/browser/tab-info.ts +15 -6
  22. package/backend/ws/preview/index.ts +7 -0
  23. package/backend/ws/snapshot/restore.ts +34 -29
  24. package/backend/ws/workspace/index.ts +14 -0
  25. package/backend/ws/workspace/state.ts +44 -0
  26. package/dist/assets/main-BOUXyIaW.js +362 -0
  27. package/dist/assets/main-ClADBkFf.css +1 -0
  28. package/dist/index.html +2 -2
  29. package/package.json +1 -1
  30. package/shared/constants/notification-sounds.ts +1 -1
  31. package/shared/types/db-client/query.ts +9 -0
  32. package/shared/utils/logger.ts +4 -6
  33. package/dist/assets/main-CHTThSzD.js +0 -358
  34. package/dist/assets/main-Dzb_5CtR.css +0 -1
@@ -12,6 +12,7 @@ import type {
12
12
  DbClientObjectDetails,
13
13
  DbClientObjectForeignKey,
14
14
  DbClientObjectIndex,
15
+ DbClientOverview,
15
16
  DbClientQueryResult,
16
17
  DbClientSchemaNode,
17
18
  DbClientSchemaNodeType
@@ -151,6 +152,27 @@ export class SqliteAdapter implements DbClientDriverAdapter {
151
152
  return this.executeRead(`EXPLAIN QUERY PLAN ${q}`);
152
153
  }
153
154
 
155
+ // ── Overview ──────────────────────────────────────────────────────────
156
+
157
+ async overview(): Promise<DbClientOverview> {
158
+ const db = this.requireDb();
159
+ const start = performance.now();
160
+ const pageCount = (db.query('PRAGMA page_count').get() as { page_count?: number } | null)?.page_count ?? 0;
161
+ const pageSize = (db.query('PRAGMA page_size').get() as { page_size?: number } | null)?.page_size ?? 0;
162
+ const latencyMs = Math.round(performance.now() - start);
163
+ const counts = db.query(
164
+ "SELECT SUM(type = 'table') AS tables, SUM(type = 'view') AS views FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
165
+ ).get() as { tables: number | null; views: number | null } | null;
166
+ return {
167
+ serverVersion: this.version,
168
+ latencyMs,
169
+ sizeBytes: pageCount * pageSize,
170
+ tableCount: counts?.tables ?? 0,
171
+ viewCount: counts?.views ?? 0,
172
+ extra: [{ label: 'File', value: db.filename || 'main' }]
173
+ };
174
+ }
175
+
154
176
  // ── Schema ────────────────────────────────────────────────────────────
155
177
 
156
178
  async listDatabases(): Promise<DbClientSchemaNode[]> {
@@ -268,6 +290,50 @@ export class SqliteAdapter implements DbClientDriverAdapter {
268
290
  return ddl;
269
291
  }
270
292
 
293
+ async resetTable(name: string): Promise<string> {
294
+ assertSafeIdentifier(name);
295
+ const db = this.requireDb();
296
+ const ddl = `DELETE FROM ${Q(name)}`;
297
+ db.run(ddl);
298
+ // AUTOINCREMENT counters live in sqlite_sequence (absent if unused).
299
+ db.prepare('DELETE FROM sqlite_sequence WHERE name = ?').run(name);
300
+ return `${ddl}; DELETE FROM sqlite_sequence WHERE name = '${name}'`;
301
+ }
302
+
303
+ async resetDatabase(): Promise<string> {
304
+ const db = this.requireDb();
305
+ const rows = db.query(
306
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
307
+ ).all() as Array<{ name: string }>;
308
+ if (rows.length === 0) return '-- no tables to empty';
309
+ rows.forEach((r) => assertSafeIdentifier(r.name));
310
+ const statements = rows.map((r) => `DELETE FROM ${Q(r.name)}`);
311
+ db.transaction(() => {
312
+ for (const stmt of statements) db.run(stmt);
313
+ db.run('DELETE FROM sqlite_sequence');
314
+ })();
315
+ return `${statements.join(';\n')};\nDELETE FROM sqlite_sequence`;
316
+ }
317
+
318
+ async duplicateTable(name: string, newName: string, opts?: { withData?: boolean }): Promise<string> {
319
+ assertSafeIdentifier(name);
320
+ assertSafeIdentifier(newName);
321
+ // SQLite cannot copy constraints via DDL; CREATE … AS SELECT preserves
322
+ // columns and (optionally) rows. Constraints/keys are not carried over.
323
+ const where = opts?.withData ? '' : ' WHERE 0';
324
+ const ddl = `CREATE TABLE ${Q(newName)} AS SELECT * FROM ${Q(name)}${where}`;
325
+ this.requireDb().run(ddl);
326
+ return ddl;
327
+ }
328
+
329
+ async getCreateStatement(name: string): Promise<string> {
330
+ assertSafeIdentifier(name);
331
+ const row = this.requireDb()
332
+ .prepare("SELECT sql FROM sqlite_master WHERE name = ? AND sql IS NOT NULL")
333
+ .get(name) as { sql: string } | null;
334
+ return row?.sql ? `${row.sql};` : '';
335
+ }
336
+
271
337
  async renameTable(name: string, newName: string): Promise<string> {
272
338
  assertSafeIdentifier(name);
273
339
  assertSafeIdentifier(newName);
@@ -11,6 +11,7 @@ import type {
11
11
  DbClientConnection,
12
12
  DbClientHealth,
13
13
  DbClientObjectDetails,
14
+ DbClientOverview,
14
15
  DbClientQueryResult,
15
16
  DbClientSchemaNode,
16
17
  DbClientSchemaNodeType,
@@ -58,6 +59,7 @@ export interface DbClientDriverAdapter {
58
59
  isAlive(): boolean;
59
60
  health(): Promise<DbClientHealth>;
60
61
 
62
+ overview?(opts?: SchemaOpts): Promise<DbClientOverview>;
61
63
  listDatabases?(): Promise<DbClientSchemaNode[]>;
62
64
  listSchemas?(database?: string): Promise<DbClientSchemaNode[]>;
63
65
  listObjects?(database?: string, schema?: string): Promise<DbClientSchemaNode[]>;
@@ -75,11 +77,22 @@ export interface DbClientDriverAdapter {
75
77
 
76
78
  // Structure
77
79
  createDatabase?(name: string): Promise<string>;
80
+ dropDatabase?(name: string): Promise<string>;
81
+ renameDatabase?(name: string, newName: string): Promise<string>;
82
+ /** Empty every table/collection in a database without dropping the schema. */
83
+ resetDatabase?(opts?: SchemaOpts): Promise<string>;
84
+ /** Redis FLUSHDB — wipe every key in the selected logical database. */
85
+ flushDatabase?(): Promise<string>;
78
86
  createTable?(definition: TableDefinition, opts?: SchemaOpts): Promise<string>;
79
87
  alterTable?(name: string, operations: AlterOperation[], opts?: SchemaOpts): Promise<string>;
80
88
  dropTable?(name: string, opts?: SchemaOpts): Promise<string>;
81
89
  truncateTable?(name: string, opts?: SchemaOpts): Promise<string>;
90
+ /** Truncate and reset the auto-increment / sequence / identity counter. */
91
+ resetTable?(name: string, opts?: SchemaOpts): Promise<string>;
82
92
  renameTable?(name: string, newName: string, opts?: SchemaOpts): Promise<string>;
93
+ duplicateTable?(name: string, newName: string, opts?: SchemaOpts & { withData?: boolean }): Promise<string>;
94
+ /** Best-effort CREATE statement for an object (DDL), for copy-to-clipboard. */
95
+ getCreateStatement?(name: string, type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string>;
83
96
  createIndex?(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string>;
84
97
  dropIndex?(tableName: string, indexName: string, opts?: SchemaOpts): Promise<string>;
85
98
  createView?(name: string, query: string, opts?: SchemaOpts): Promise<string>;
@@ -4,6 +4,8 @@
4
4
  */
5
5
 
6
6
  import { execGit, isGitRepo, getGitRoot } from './git-executor';
7
+ import { resolveBinary } from '../utils/cli';
8
+ import { getCleanSpawnEnv } from '../utils/env';
7
9
  import {
8
10
  parseStatus,
9
11
  parseBranches,
@@ -378,9 +380,11 @@ export class GitService {
378
380
  return result.stderr || result.stdout; // git fetch outputs to stderr
379
381
  }
380
382
 
381
- async pull(cwd: string, remote = 'origin', branch?: string): Promise<{ success: boolean; message: string }> {
383
+ async pull(cwd: string, remote = 'origin', branch?: string, rebase = false): Promise<{ success: boolean; message: string }> {
382
384
  assertSafeGitRemoteName(remote);
383
- const args = ['pull', remote];
385
+ const args = ['pull'];
386
+ if (rebase) args.push('--rebase');
387
+ args.push(remote);
384
388
  if (branch) {
385
389
  assertSafeGitRevish(branch, 'pull branch');
386
390
  args.push(branch);
@@ -409,6 +413,49 @@ export class GitService {
409
413
  };
410
414
  }
411
415
 
416
+ /**
417
+ * Advanced push variants surfaced in the "More" menu:
418
+ * - `with-tags` → push branch + reachable annotated tags (--follow-tags)
419
+ * - `all-tags` → push all local tags (--tags), no branch
420
+ * - `force-lease` → safe force push (--force-with-lease)
421
+ * - `force` → unconditional force push (--force)
422
+ */
423
+ async pushAdvanced(
424
+ cwd: string,
425
+ mode: 'with-tags' | 'all-tags' | 'force-lease' | 'force',
426
+ remote = 'origin',
427
+ branch?: string
428
+ ): Promise<{ success: boolean; message: string }> {
429
+ assertSafeGitRemoteName(remote);
430
+ const args = ['push', remote];
431
+ if (mode === 'all-tags') {
432
+ args.push('--tags');
433
+ } else {
434
+ if (branch) {
435
+ assertSafeGitRevish(branch, 'push branch');
436
+ args.push(branch);
437
+ }
438
+ if (mode === 'with-tags') args.push('--follow-tags');
439
+ else if (mode === 'force-lease') args.push('--force-with-lease');
440
+ else if (mode === 'force') args.push('--force');
441
+ args.push('-u');
442
+ }
443
+ const result = await execGit(args, cwd, 60000);
444
+ return {
445
+ success: result.exitCode === 0,
446
+ message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
447
+ };
448
+ }
449
+
450
+ /** Fetch every configured remote and prune deleted remote-tracking refs. */
451
+ async fetchAll(cwd: string): Promise<string> {
452
+ const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, 60000);
453
+ if (result.exitCode !== 0) {
454
+ throw new Error(`git fetch --all failed: ${result.stderr}`);
455
+ }
456
+ return result.stderr || result.stdout;
457
+ }
458
+
412
459
  async addRemote(cwd: string, name: string, url: string): Promise<void> {
413
460
  assertSafeGitRemoteName(name);
414
461
  assertSafeGitRemoteUrl(url);
@@ -627,6 +674,92 @@ export class GitService {
627
674
  throw new Error(`git reset --merge failed: ${reset.stderr}`);
628
675
  }
629
676
  }
677
+
678
+ // ============================================
679
+ // History rewrite / undo
680
+ // ============================================
681
+
682
+ /**
683
+ * Undo the last commit by moving HEAD back one commit.
684
+ * - `soft` keeps the changes staged
685
+ * - `mixed` keeps the changes in the working tree (unstaged)
686
+ * - `hard` discards the changes entirely (destructive)
687
+ */
688
+ async undoLastCommit(cwd: string, mode: 'soft' | 'mixed' | 'hard'): Promise<void> {
689
+ const flag = mode === 'soft' ? '--soft' : mode === 'hard' ? '--hard' : '--mixed';
690
+ const result = await execGit(['reset', flag, 'HEAD~1'], cwd);
691
+ if (result.exitCode !== 0) {
692
+ throw new Error(`git reset ${flag} failed: ${result.stderr}`);
693
+ }
694
+ }
695
+
696
+ /** Create a new commit that reverses a previous one (default: HEAD). */
697
+ async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
698
+ assertSafeGitRevish(ref, 'revert ref');
699
+ const result = await execGit(['revert', '--no-edit', ref], cwd);
700
+ return {
701
+ success: result.exitCode === 0,
702
+ message: result.exitCode === 0 ? (result.stdout || result.stderr) : result.stderr
703
+ };
704
+ }
705
+
706
+ // ============================================
707
+ // Maintenance
708
+ // ============================================
709
+
710
+ /** Remove untracked files and directories (`git clean -fd`). */
711
+ async cleanUntracked(cwd: string): Promise<string> {
712
+ const result = await execGit(['clean', '-fd'], cwd);
713
+ if (result.exitCode !== 0) {
714
+ throw new Error(`git clean failed: ${result.stderr}`);
715
+ }
716
+ return result.stdout.trim();
717
+ }
718
+
719
+ /** Run garbage collection to optimize the repository. */
720
+ async optimize(cwd: string): Promise<string> {
721
+ const result = await execGit(['gc'], cwd, 180000);
722
+ if (result.exitCode !== 0) {
723
+ throw new Error(`git gc failed: ${result.stderr}`);
724
+ }
725
+ return (result.stderr || result.stdout).trim() || 'Repository optimized';
726
+ }
727
+
728
+ // ============================================
729
+ // npm version
730
+ // ============================================
731
+
732
+ /**
733
+ * Bump the package version with `npm version <patch|minor|major>`. In a git
734
+ * repo npm creates the version-bump commit and tag automatically. Requires a
735
+ * clean working tree (npm refuses otherwise) — that error is surfaced verbatim.
736
+ */
737
+ async npmVersion(
738
+ cwd: string,
739
+ bump: 'patch' | 'minor' | 'major'
740
+ ): Promise<{ success: boolean; version: string; message: string }> {
741
+ const npmPath = resolveBinary('npm');
742
+ if (!npmPath) {
743
+ throw new Error('npm binary not found on PATH');
744
+ }
745
+ const proc = Bun.spawn([npmPath, 'version', bump, '-m', 'chore(release): v%s'], {
746
+ cwd,
747
+ stdout: 'pipe',
748
+ stderr: 'pipe',
749
+ env: { ...getCleanSpawnEnv() }
750
+ });
751
+ const [stdout, stderr] = await Promise.all([
752
+ new Response(proc.stdout).text(),
753
+ new Response(proc.stderr).text()
754
+ ]);
755
+ const exitCode = await proc.exited;
756
+ if (exitCode !== 0) {
757
+ return { success: false, version: '', message: (stderr || stdout).trim() };
758
+ }
759
+ // npm prints the new version (e.g. "v1.2.3") on stdout.
760
+ const version = stdout.trim().split('\n').pop()?.trim() || '';
761
+ return { success: true, version, message: version };
762
+ }
630
763
  }
631
764
 
632
765
  // Singleton
@@ -610,6 +610,10 @@ export class BrowserPreviewService extends EventEmitter {
610
610
  class BrowserPreviewServiceManager {
611
611
  private services = new Map<string, BrowserPreviewService>();
612
612
 
613
+ // Whether the singleton browserMcpControl listeners have been registered.
614
+ // Guards against re-registering (and leaking) listeners on the shared emitter.
615
+ private mcpForwardingSetup = false;
616
+
613
617
  /**
614
618
  * Get or create a BrowserPreviewService for a project
615
619
  */
@@ -618,6 +622,9 @@ class BrowserPreviewServiceManager {
618
622
  throw new Error('projectId is required and cannot be empty');
619
623
  }
620
624
 
625
+ // Register singleton MCP control forwarding once (idempotent).
626
+ this.setupMcpControlForwarding();
627
+
621
628
  if (!this.services.has(projectId)) {
622
629
  debug.log('preview', `🆕 Creating new BrowserPreviewService for project: ${projectId}`);
623
630
  const service = new BrowserPreviewService(projectId);
@@ -669,26 +676,29 @@ class BrowserPreviewServiceManager {
669
676
  ws.emit.project(projectId, 'preview:browser-navigation-spa', data);
670
677
  });
671
678
 
672
- // Forward tab events
679
+ // Forward tab events. Each carries projectId so the frontend can drop
680
+ // events for a project it has since switched away from — without it, a
681
+ // background stream (or a late event) could create/mutate tabs in the
682
+ // project the user is now viewing.
673
683
  service.on('preview:browser-tab-opened', (data) => {
674
684
  debug.log('preview', `🚀 Forwarding preview:browser-tab-opened to project ${projectId}:`, data);
675
- ws.emit.project(projectId, 'preview:browser-tab-opened', data);
685
+ ws.emit.project(projectId, 'preview:browser-tab-opened', { ...data, projectId });
676
686
  });
677
687
 
678
688
  service.on('preview:browser-tab-closed', (data) => {
679
- ws.emit.project(projectId, 'preview:browser-tab-closed', data);
689
+ ws.emit.project(projectId, 'preview:browser-tab-closed', { ...data, projectId });
680
690
  });
681
691
 
682
692
  service.on('preview:browser-tab-switched', (data) => {
683
- ws.emit.project(projectId, 'preview:browser-tab-switched', data);
693
+ ws.emit.project(projectId, 'preview:browser-tab-switched', { ...data, projectId });
684
694
  });
685
695
 
686
696
  service.on('preview:browser-tab-navigated', (data) => {
687
- ws.emit.project(projectId, 'preview:browser-tab-navigated', data);
697
+ ws.emit.project(projectId, 'preview:browser-tab-navigated', { ...data, projectId });
688
698
  });
689
699
 
690
700
  service.on('preview:browser-viewport-changed', (data) => {
691
- ws.emit.project(projectId, 'preview:browser-viewport-changed', data);
701
+ ws.emit.project(projectId, 'preview:browser-viewport-changed', { ...data, projectId });
692
702
  });
693
703
 
694
704
  // Forward console events
@@ -752,10 +762,39 @@ class BrowserPreviewServiceManager {
752
762
  ws.emit.project(projectId, 'preview:browser-new-window', data);
753
763
  });
754
764
 
755
- // Forward MCP control events (from singleton browserMcpControl)
765
+ // MCP control events come from the singleton browserMcpControl, so their
766
+ // listeners are registered once globally (see setupMcpControlForwarding) —
767
+ // NOT here, which runs per-project and would leak listeners onto the
768
+ // singleton as projects are opened.
769
+
770
+ debug.log('preview', `🎉 All WebSocket event listeners registered for project: ${projectId}`);
771
+ }
772
+
773
+ /**
774
+ * Setup WebSocket forwarding for the singleton browserMcpControl.
775
+ *
776
+ * Registered exactly once for the whole manager. The emitter is a singleton
777
+ * shared across all projects, so attaching these listeners per-project would
778
+ * accumulate them without bound (MaxListenersExceededWarning). MCP control
779
+ * events are not project-scoped at the source, so we broadcast them to every
780
+ * currently-active project; the frontend filters by tab/session.
781
+ */
782
+ private setupMcpControlForwarding(): void {
783
+ if (this.mcpForwardingSetup) return;
784
+ this.mcpForwardingSetup = true;
785
+
786
+ const emitToActiveProjects = <K extends Parameters<typeof ws.emit.project>[1]>(
787
+ event: K,
788
+ payload: Parameters<typeof ws.emit.project<K>>[2]
789
+ ) => {
790
+ for (const projectId of this.services.keys()) {
791
+ ws.emit.project(projectId, event, payload);
792
+ }
793
+ };
794
+
756
795
  browserMcpControl.on('control-start', (data) => {
757
- debug.log('preview', `🚀 Forwarding mcp-control-start to project ${projectId}:`, data);
758
- ws.emit.project(projectId, 'preview:browser-mcp-control-start', {
796
+ debug.log('preview', '🚀 Forwarding mcp-control-start:', data);
797
+ emitToActiveProjects('preview:browser-mcp-control-start', {
759
798
  browserTabId: data.browserTabId,
760
799
  chatSessionId: data.chatSessionId,
761
800
  timestamp: data.timestamp
@@ -763,16 +802,15 @@ class BrowserPreviewServiceManager {
763
802
  });
764
803
 
765
804
  browserMcpControl.on('control-end', (data) => {
766
- debug.log('preview', `🚀 Forwarding mcp-control-end to project ${projectId}:`, data);
767
- ws.emit.project(projectId, 'preview:browser-mcp-control-end', {
805
+ debug.log('preview', '🚀 Forwarding mcp-control-end:', data);
806
+ emitToActiveProjects('preview:browser-mcp-control-end', {
768
807
  browserTabId: data.browserTabId,
769
808
  timestamp: data.timestamp
770
809
  });
771
810
  });
772
811
 
773
- // Forward MCP cursor events
774
812
  browserMcpControl.on('cursor-position', (data) => {
775
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-position', {
813
+ emitToActiveProjects('preview:browser-mcp-cursor-position', {
776
814
  sessionId: data.tabId,
777
815
  x: data.x,
778
816
  y: data.y,
@@ -782,7 +820,7 @@ class BrowserPreviewServiceManager {
782
820
  });
783
821
 
784
822
  browserMcpControl.on('cursor-click', (data) => {
785
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-click', {
823
+ emitToActiveProjects('preview:browser-mcp-cursor-click', {
786
824
  sessionId: data.tabId,
787
825
  x: data.x,
788
826
  y: data.y,
@@ -792,14 +830,12 @@ class BrowserPreviewServiceManager {
792
830
  });
793
831
 
794
832
  browserMcpControl.on('test-completed', (data) => {
795
- ws.emit.project(projectId, 'preview:browser-mcp-test-completed', {
833
+ emitToActiveProjects('preview:browser-mcp-test-completed', {
796
834
  sessionId: data.tabId,
797
835
  timestamp: data.timestamp,
798
836
  source: 'mcp'
799
837
  });
800
838
  });
801
-
802
- debug.log('preview', `🎉 All WebSocket event listeners registered for project: ${projectId}`);
803
839
  }
804
840
 
805
841
  /**
@@ -45,6 +45,13 @@ export interface RestoreConflict {
45
45
  modifiedAt: string;
46
46
  restoreContent?: string;
47
47
  currentContent?: string;
48
+ /**
49
+ * 'cross-session' (default): file was changed by a different session after the
50
+ * reference time. 'local': the current on-disk content was never captured by
51
+ * this session's snapshots, so restoring would overwrite an unrecoverable
52
+ * manual edit.
53
+ */
54
+ reason?: 'cross-session' | 'local';
48
55
  }
49
56
 
50
57
  /**
@@ -147,82 +154,76 @@ export class SnapshotService {
147
154
  messageId: string
148
155
  ): Promise<MessageSnapshot> {
149
156
  try {
150
- const dirtyFiles = fileWatcher.getDirtyFiles(projectId);
151
-
152
157
  const previousSnapshots = snapshotQueries.getBySessionId(sessionId);
153
158
  const previousSnapshot = previousSnapshots.length > 0
154
159
  ? previousSnapshots[previousSnapshots.length - 1]
155
160
  : null;
156
161
 
157
- // FAST PATH: no file changes detected → skip snapshot
158
- if (dirtyFiles.size === 0 && previousSnapshot) {
159
- debug.log('snapshot', 'No file changes detected, skipping snapshot');
160
- return previousSnapshot;
161
- }
162
-
163
- // Get previous tree (in-memory baseline)
162
+ // Previous tree (in-memory baseline = disk state at session start or the
163
+ // last capture/restore).
164
164
  const previousTree = await this.getSessionBaseline(projectPath, sessionId);
165
165
 
166
- // Build current tree incrementally
167
- let currentTree: TreeMap;
166
+ // The source of truth is the DISK, not the file watcher's dirty set. The
167
+ // watcher only runs while the Files/Git panel is mounted, so relying on it
168
+ // silently dropped snapshots whenever the user chatted with those panels
169
+ // closed (worsened once dock state became per-project). A gitignore-aware
170
+ // scan + hash diff against the baseline is always correct, and
171
+ // blobStore.hashFile's mtime+size cache keeps it cheap — only files that
172
+ // actually changed are re-read.
173
+ const files = await getSnapshotFiles(projectPath);
174
+ const currentTree: TreeMap = {};
168
175
  const sessionChanges: SessionScopedChanges = {};
169
176
  const readContents = new Map<string, Buffer>();
177
+ const seen = new Set<string>();
170
178
 
171
- if (dirtyFiles.size === 0 && !previousSnapshot) {
172
- // First snapshot ever, no dirty files → initial baseline
173
- currentTree = { ...previousTree };
174
- } else if (dirtyFiles.size > 0) {
175
- // Incremental: start from previous tree, update only dirty files
176
- currentTree = { ...previousTree };
179
+ for (const filepath of files) {
180
+ try {
181
+ const stat = await fs.stat(filepath);
182
+ const relativePath = path.relative(projectPath, filepath).replace(/\\/g, '/');
177
183
 
178
- for (const relativePath of dirtyFiles) {
179
- const fullPath = path.join(projectPath, relativePath);
184
+ // Files over the size cap are never tracked (mirrors the baseline
185
+ // scan). If one was tracked before, the deletion pass below records
186
+ // its removal from the tree.
187
+ if (stat.size > MAX_FILE_SIZE) continue;
180
188
 
181
- try {
182
- const stat = await fs.stat(fullPath);
183
- if (stat.size > MAX_FILE_SIZE) {
184
- if (currentTree[relativePath]) {
185
- const oldHash = currentTree[relativePath];
186
- sessionChanges[relativePath] = { oldHash, newHash: '' };
187
- delete currentTree[relativePath];
188
- }
189
- continue;
190
- }
189
+ seen.add(relativePath);
191
190
 
192
- const result = await blobStore.hashFile(relativePath, fullPath);
193
- const newHash = result.hash;
194
- const oldHash = previousTree[relativePath] || '';
191
+ const result = await blobStore.hashFile(relativePath, filepath);
192
+ const newHash = result.hash;
193
+ const oldHash = previousTree[relativePath] || '';
195
194
 
196
- if (oldHash !== newHash) {
197
- currentTree[relativePath] = newHash;
198
- sessionChanges[relativePath] = { oldHash, newHash };
195
+ currentTree[relativePath] = newHash;
199
196
 
200
- if (result.content !== null) {
201
- readContents.set(relativePath, result.content);
202
- }
197
+ if (oldHash !== newHash) {
198
+ sessionChanges[relativePath] = { oldHash, newHash };
203
199
 
204
- if (oldHash && !(await blobStore.hasBlob(oldHash))) {
205
- debug.warn('snapshot', `Old blob missing for ${relativePath} (${oldHash.slice(0, 8)}), restore may be limited`);
206
- }
200
+ if (result.content !== null) {
201
+ readContents.set(relativePath, result.content);
207
202
  }
208
- } catch {
209
- // File was deleted
210
- if (currentTree[relativePath]) {
211
- const oldHash = currentTree[relativePath];
212
- sessionChanges[relativePath] = { oldHash, newHash: '' };
213
- delete currentTree[relativePath];
203
+
204
+ if (oldHash && !(await blobStore.hasBlob(oldHash))) {
205
+ debug.warn('snapshot', `Old blob missing for ${relativePath} (${oldHash.slice(0, 8)}), restore may be limited`);
214
206
  }
215
207
  }
208
+ } catch {
209
+ // Unreadable file — skip it
210
+ }
211
+ }
212
+
213
+ // Deletions: anything in the baseline that is no longer on disk.
214
+ for (const relativePath of Object.keys(previousTree)) {
215
+ if (!seen.has(relativePath)) {
216
+ sessionChanges[relativePath] = { oldHash: previousTree[relativePath], newHash: '' };
216
217
  }
217
- } else {
218
- currentTree = { ...previousTree };
219
218
  }
220
219
 
220
+ // The dirty set is no longer the snapshot source, but clear it so it does
221
+ // not grow unbounded for the Files panel UI.
221
222
  fileWatcher.clearDirtyFiles(projectId);
222
223
 
223
- // If no actual changes after processing, skip
224
+ // No changes vs the baseline → reuse the existing head snapshot.
224
225
  if (Object.keys(sessionChanges).length === 0 && previousSnapshot) {
225
- debug.log('snapshot', 'No actual file changes after hash comparison, skipping snapshot');
226
+ debug.log('snapshot', 'No file changes detected (full scan), skipping snapshot');
226
227
  return previousSnapshot;
227
228
  }
228
229
 
@@ -301,7 +302,10 @@ export class SnapshotService {
301
302
  return { hasConflicts: false, conflicts: [], checkpointsToUndo: [] };
302
303
  }
303
304
 
304
- // Filter out files already in expected state on disk (no actual change needed)
305
+ // Filter out files already in expected state on disk (no actual change needed),
306
+ // and remember the current on-disk hash of the files that WOULD change so the
307
+ // local-drift pass below can run without re-reading them.
308
+ const currentHashByFile = new Map<string, string>();
305
309
  if (projectPath) {
306
310
  for (const [filepath, expectedHash] of expectedState) {
307
311
  const fullPath = path.join(projectPath, filepath);
@@ -315,6 +319,8 @@ export class SnapshotService {
315
319
  }
316
320
  if (currentHash === expectedHash) {
317
321
  expectedState.delete(filepath);
322
+ } else {
323
+ currentHashByFile.set(filepath, currentHash);
318
324
  }
319
325
  }
320
326
 
@@ -396,6 +402,30 @@ export class SnapshotService {
396
402
 
397
403
  const uniqueConflicts = Array.from(conflictMap.values());
398
404
 
405
+ // Local-drift detection: a file restore would overwrite/delete whose CURRENT
406
+ // on-disk content was never captured by this session's snapshots. Overwriting
407
+ // it would lose an unrecoverable manual edit, so surface it as a conflict and
408
+ // let the user decide. Normal undo/redo never trips this — the working tree's
409
+ // content there always maps to a captured oldHash/newHash.
410
+ if (projectPath) {
411
+ const sessionReferenced = snapshotQueries.collectBlobHashes(sessionSnapshots);
412
+ const alreadyFlagged = new Set(uniqueConflicts.map(c => c.filepath));
413
+ for (const [filepath] of expectedState) {
414
+ if (alreadyFlagged.has(filepath)) continue;
415
+ const currentHash = currentHashByFile.get(filepath) || '';
416
+ if (!currentHash) continue; // no file on disk → nothing to lose
417
+ if (!sessionReferenced.has(currentHash)) {
418
+ uniqueConflicts.push({
419
+ filepath,
420
+ modifiedBySessionId: sessionId,
421
+ modifiedBySnapshotId: '',
422
+ modifiedAt: '',
423
+ reason: 'local'
424
+ });
425
+ }
426
+ }
427
+ }
428
+
399
429
  // Populate file contents for diff display
400
430
  if (uniqueConflicts.length > 0 && projectPath) {
401
431
  await Promise.all(uniqueConflicts.map(async (conflict) => {
@@ -747,7 +747,9 @@ class WSServer {
747
747
 
748
748
  const room = this.projectRooms.get(projectId);
749
749
  if (!room || room.size === 0) {
750
- debug.warn('websocket', `No connections in project room: ${projectId} for event: ${String(event)}`);
750
+ // Expected/benign: e.g. a background terminal in a project the client
751
+ // has switched away from keeps emitting output to an empty room.
752
+ debug.log('websocket', `No connections in project room: ${projectId} for event: ${String(event)}`);
751
753
  return;
752
754
  }
753
755
 
@@ -20,6 +20,20 @@ const nodeTypeSchema = t.Union([
20
20
  ]);
21
21
 
22
22
  export const schemaHandler = createRouter()
23
+ .http('db-client:overview', {
24
+ data: t.Object({
25
+ connectionId: t.String({ minLength: 1 }),
26
+ database: t.Optional(t.String()),
27
+ schema: t.Optional(t.String())
28
+ }),
29
+ response: t.Any()
30
+ }, async ({ data, conn }) => {
31
+ requireDbClientConnectionAccess(conn, data.connectionId);
32
+ const adapter = await connectionManager.get(data.connectionId);
33
+ if (!adapter.overview) throw new Error('Driver does not support overview');
34
+ return adapter.overview({ database: data.database, schema: data.schema });
35
+ })
36
+
23
37
  .http('db-client:list-databases', {
24
38
  data: t.Object({ connectionId: t.String({ minLength: 1 }) }),
25
39
  response: t.Array(t.Any())