@myrialabs/clopen 0.3.18 → 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.
@@ -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);
@@ -755,10 +762,39 @@ class BrowserPreviewServiceManager {
755
762
  ws.emit.project(projectId, 'preview:browser-new-window', data);
756
763
  });
757
764
 
758
- // 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
+
759
795
  browserMcpControl.on('control-start', (data) => {
760
- debug.log('preview', `🚀 Forwarding mcp-control-start to project ${projectId}:`, data);
761
- 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', {
762
798
  browserTabId: data.browserTabId,
763
799
  chatSessionId: data.chatSessionId,
764
800
  timestamp: data.timestamp
@@ -766,16 +802,15 @@ class BrowserPreviewServiceManager {
766
802
  });
767
803
 
768
804
  browserMcpControl.on('control-end', (data) => {
769
- debug.log('preview', `🚀 Forwarding mcp-control-end to project ${projectId}:`, data);
770
- 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', {
771
807
  browserTabId: data.browserTabId,
772
808
  timestamp: data.timestamp
773
809
  });
774
810
  });
775
811
 
776
- // Forward MCP cursor events
777
812
  browserMcpControl.on('cursor-position', (data) => {
778
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-position', {
813
+ emitToActiveProjects('preview:browser-mcp-cursor-position', {
779
814
  sessionId: data.tabId,
780
815
  x: data.x,
781
816
  y: data.y,
@@ -785,7 +820,7 @@ class BrowserPreviewServiceManager {
785
820
  });
786
821
 
787
822
  browserMcpControl.on('cursor-click', (data) => {
788
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-click', {
823
+ emitToActiveProjects('preview:browser-mcp-cursor-click', {
789
824
  sessionId: data.tabId,
790
825
  x: data.x,
791
826
  y: data.y,
@@ -795,14 +830,12 @@ class BrowserPreviewServiceManager {
795
830
  });
796
831
 
797
832
  browserMcpControl.on('test-completed', (data) => {
798
- ws.emit.project(projectId, 'preview:browser-mcp-test-completed', {
833
+ emitToActiveProjects('preview:browser-mcp-test-completed', {
799
834
  sessionId: data.tabId,
800
835
  timestamp: data.timestamp,
801
836
  source: 'mcp'
802
837
  });
803
838
  });
804
-
805
- debug.log('preview', `🎉 All WebSocket event listeners registered for project: ${projectId}`);
806
839
  }
807
840
 
808
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) => {
@@ -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())
@@ -6,6 +6,7 @@ import { t } from 'elysia';
6
6
  import { createRouter } from '$shared/utils/ws-server';
7
7
  import { connectionManager } from '../../db-client/connection-manager';
8
8
  import type { AlterOperation, IndexDefinition, TableDefinition } from '../../db-client/drivers/types';
9
+ import type { DbClientSchemaNodeType } from '$shared/types/db-client';
9
10
  import { requireDbClientConnectionAccess } from './access';
10
11
 
11
12
  const columnDefinitionSchema = t.Object({
@@ -52,6 +53,63 @@ export const structureHandler = createRouter()
52
53
  return { ok: true, ddl };
53
54
  })
54
55
 
56
+ .http('db-client:structure:drop-database', {
57
+ data: t.Object({
58
+ connectionId: t.String({ minLength: 1 }),
59
+ name: t.String({ minLength: 1 })
60
+ }),
61
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
62
+ }, async ({ data, conn }) => {
63
+ requireDbClientConnectionAccess(conn, data.connectionId);
64
+ const adapter = await connectionManager.get(data.connectionId);
65
+ if (!adapter.dropDatabase) throw new Error('Driver does not support dropping databases');
66
+ const ddl = await adapter.dropDatabase(data.name);
67
+ return { ok: true, ddl };
68
+ })
69
+
70
+ .http('db-client:structure:rename-database', {
71
+ data: t.Object({
72
+ connectionId: t.String({ minLength: 1 }),
73
+ name: t.String({ minLength: 1 }),
74
+ newName: t.String({ minLength: 1 })
75
+ }),
76
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
77
+ }, async ({ data, conn }) => {
78
+ requireDbClientConnectionAccess(conn, data.connectionId);
79
+ const adapter = await connectionManager.get(data.connectionId);
80
+ if (!adapter.renameDatabase) throw new Error('Driver does not support renaming databases');
81
+ const ddl = await adapter.renameDatabase(data.name, data.newName);
82
+ return { ok: true, ddl };
83
+ })
84
+
85
+ .http('db-client:structure:reset-database', {
86
+ data: t.Object({
87
+ connectionId: t.String({ minLength: 1 }),
88
+ database: t.Optional(t.String()),
89
+ schema: t.Optional(t.String())
90
+ }),
91
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
92
+ }, async ({ data, conn }) => {
93
+ requireDbClientConnectionAccess(conn, data.connectionId);
94
+ const adapter = await connectionManager.get(data.connectionId);
95
+ if (!adapter.resetDatabase) throw new Error('Driver does not support emptying databases');
96
+ const ddl = await adapter.resetDatabase({ database: data.database, schema: data.schema });
97
+ return { ok: true, ddl };
98
+ })
99
+
100
+ .http('db-client:structure:flush-database', {
101
+ data: t.Object({
102
+ connectionId: t.String({ minLength: 1 })
103
+ }),
104
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
105
+ }, async ({ data, conn }) => {
106
+ requireDbClientConnectionAccess(conn, data.connectionId);
107
+ const adapter = await connectionManager.get(data.connectionId);
108
+ if (!adapter.flushDatabase) throw new Error('Driver does not support flushing the database');
109
+ const ddl = await adapter.flushDatabase();
110
+ return { ok: true, ddl };
111
+ })
112
+
55
113
  .http('db-client:structure:create-table', {
56
114
  data: t.Object({
57
115
  connectionId: t.String({ minLength: 1 }),
@@ -129,6 +187,68 @@ export const structureHandler = createRouter()
129
187
  return { ok: true, ddl };
130
188
  })
131
189
 
190
+ .http('db-client:structure:reset-table', {
191
+ data: t.Object({
192
+ connectionId: t.String({ minLength: 1 }),
193
+ database: t.Optional(t.String()),
194
+ schema: t.Optional(t.String()),
195
+ name: t.String({ minLength: 1 })
196
+ }),
197
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
198
+ }, async ({ data, conn }) => {
199
+ requireDbClientConnectionAccess(conn, data.connectionId);
200
+ const adapter = await connectionManager.get(data.connectionId);
201
+ if (!adapter.resetTable) throw new Error('Driver does not support resetTable');
202
+ const ddl = await adapter.resetTable(data.name, {
203
+ database: data.database,
204
+ schema: data.schema
205
+ });
206
+ return { ok: true, ddl };
207
+ })
208
+
209
+ .http('db-client:structure:duplicate-table', {
210
+ data: t.Object({
211
+ connectionId: t.String({ minLength: 1 }),
212
+ database: t.Optional(t.String()),
213
+ schema: t.Optional(t.String()),
214
+ name: t.String({ minLength: 1 }),
215
+ newName: t.String({ minLength: 1 }),
216
+ withData: t.Optional(t.Boolean())
217
+ }),
218
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
219
+ }, async ({ data, conn }) => {
220
+ requireDbClientConnectionAccess(conn, data.connectionId);
221
+ const adapter = await connectionManager.get(data.connectionId);
222
+ if (!adapter.duplicateTable) throw new Error('Driver does not support duplicateTable');
223
+ const ddl = await adapter.duplicateTable(data.name, data.newName, {
224
+ database: data.database,
225
+ schema: data.schema,
226
+ withData: data.withData
227
+ });
228
+ return { ok: true, ddl };
229
+ })
230
+
231
+ .http('db-client:structure:create-statement', {
232
+ data: t.Object({
233
+ connectionId: t.String({ minLength: 1 }),
234
+ database: t.Optional(t.String()),
235
+ schema: t.Optional(t.String()),
236
+ name: t.String({ minLength: 1 }),
237
+ type: t.Optional(t.String())
238
+ }),
239
+ response: t.Object({ ok: t.Boolean(), statement: t.String() })
240
+ }, async ({ data, conn }) => {
241
+ requireDbClientConnectionAccess(conn, data.connectionId);
242
+ const adapter = await connectionManager.get(data.connectionId);
243
+ if (!adapter.getCreateStatement) throw new Error('Driver does not support fetching the CREATE statement');
244
+ const statement = await adapter.getCreateStatement(
245
+ data.name,
246
+ (data.type as DbClientSchemaNodeType | undefined) ?? 'table',
247
+ { database: data.database, schema: data.schema }
248
+ );
249
+ return { ok: true, statement };
250
+ })
251
+
132
252
  .http('db-client:structure:rename-table', {
133
253
  data: t.Object({
134
254
  connectionId: t.String({ minLength: 1 }),
@@ -10,6 +10,7 @@ import { t } from 'elysia';
10
10
  import { createRouter } from '$shared/utils/ws-server';
11
11
  import { messageQueries, sessionQueries, projectQueries, checkpointQueries } from '../../database/queries';
12
12
  import { snapshotService } from '../../snapshot/snapshot-service';
13
+ import { streamManager } from '../../chat/stream-manager';
13
14
  import { debug } from '$shared/utils/logger';
14
15
  import type { UnifiedMessage } from '$shared/types/unified';
15
16
  import {
@@ -40,7 +41,8 @@ export const restoreHandler = createRouter()
40
41
  modifiedBySnapshotId: t.String(),
41
42
  modifiedAt: t.String(),
42
43
  restoreContent: t.Optional(t.String()),
43
- currentContent: t.Optional(t.String())
44
+ currentContent: t.Optional(t.String()),
45
+ reason: t.Optional(t.Union([t.Literal('cross-session'), t.Literal('local')]))
44
46
  })),
45
47
  checkpointsToUndo: t.Array(t.String())
46
48
  })
@@ -111,7 +113,16 @@ export const restoreHandler = createRouter()
111
113
  })
112
114
  }, async ({ data, conn }) => {
113
115
  const { messageId, sessionId, conflictResolutions } = data;
114
- requireSessionAccess(conn, sessionId);
116
+ const session = requireSessionAccess(conn, sessionId);
117
+
118
+ // Refuse to restore while this session is still generating. Restore rewrites
119
+ // the working tree and resets the in-memory baseline; doing that mid-stream
120
+ // would corrupt the end-of-turn snapshot and race the engine's own writes.
121
+ const activeStream = streamManager.getSessionStream(sessionId, session.project_id);
122
+ if (activeStream?.status === 'active') {
123
+ throw new Error('Cannot restore while the chat is still generating. Stop the stream first, then try again.');
124
+ }
125
+
115
126
  const isInitialRestore = messageId === INITIAL_NODE_ID;
116
127
 
117
128
  debug.log('snapshot', `RESTORE - ${isInitialRestore ? 'Restoring to initial state' : 'Moving HEAD to checkpoint'}`);
@@ -136,19 +147,16 @@ export const restoreHandler = createRouter()
136
147
  let filesRestored = 0;
137
148
  let filesSkipped = 0;
138
149
 
139
- const session = sessionQueries.getById(sessionId);
140
- if (session) {
141
- const project = projectQueries.getById(session.project_id);
142
- if (project) {
143
- const result = await snapshotService.restoreSessionScoped(
144
- project.path,
145
- sessionId,
146
- null, // null = restore to initial (before all snapshots)
147
- conflictResolutions
148
- );
149
- filesRestored = result.restoredFiles;
150
- filesSkipped = result.skippedFiles;
151
- }
150
+ const project = projectQueries.getById(session.project_id);
151
+ if (project) {
152
+ const result = await snapshotService.restoreSessionScoped(
153
+ project.path,
154
+ sessionId,
155
+ null, // null = restore to initial (before all snapshots)
156
+ conflictResolutions
157
+ );
158
+ filesRestored = result.restoredFiles;
159
+ filesSkipped = result.skippedFiles;
152
160
  }
153
161
 
154
162
  // Broadcast messages-changed
@@ -285,20 +293,17 @@ export const restoreHandler = createRouter()
285
293
  let filesRestored = 0;
286
294
  let filesSkipped = 0;
287
295
 
288
- const session = sessionQueries.getById(sessionId);
289
- if (session) {
290
- const project = projectQueries.getById(session.project_id);
291
- if (project) {
292
- const result = await snapshotService.restoreSessionScoped(
293
- project.path,
294
- sessionId,
295
- resolvedCheckpointId,
296
- conflictResolutions,
297
- checkpointPath.length > 0 ? checkpointPath : undefined
298
- );
299
- filesRestored = result.restoredFiles;
300
- filesSkipped = result.skippedFiles;
301
- }
296
+ const project = projectQueries.getById(session.project_id);
297
+ if (project) {
298
+ const result = await snapshotService.restoreSessionScoped(
299
+ project.path,
300
+ sessionId,
301
+ resolvedCheckpointId,
302
+ conflictResolutions,
303
+ checkpointPath.length > 0 ? checkpointPath : undefined
304
+ );
305
+ filesRestored = result.restoredFiles;
306
+ filesSkipped = result.skippedFiles;
302
307
  }
303
308
 
304
309
  // 8. Broadcast messages-changed