@myrialabs/clopen 0.3.13 → 0.3.14

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.
@@ -82,6 +82,19 @@ interface ProjectWatcher {
82
82
  class FileWatcherManager {
83
83
  private watchers = new Map<string, ProjectWatcher>();
84
84
 
85
+ /**
86
+ * Per-project set of connection ids currently viewing the project.
87
+ * The watcher is a shared singleton per project; it must stay alive while
88
+ * ANY connection is viewing (multi-tab / multi-device) and be torn down
89
+ * only when the last viewer leaves. Reference-counting here avoids the
90
+ * previous bug where one viewer's unwatch killed the watcher for everyone,
91
+ * and where switching projects leaked orphaned watchers.
92
+ */
93
+ private viewers = new Map<string, Set<string>>();
94
+
95
+ /** Projects with an in-flight auto-restart, to avoid overlapping restarts. */
96
+ private restarting = new Set<string>();
97
+
85
98
  /**
86
99
  * Per-project dirty file tracking for snapshot system.
87
100
  * Accumulates changed file relative paths between snapshot captures.
@@ -113,7 +126,51 @@ class FileWatcherManager {
113
126
  }
114
127
 
115
128
  /**
116
- * Start watching a project directory
129
+ * Register a connection as a viewer of a project and ensure a watcher is
130
+ * running. Returns true if the project is being watched after the call.
131
+ */
132
+ async addViewer(connId: string, projectId: string, projectPath: string): Promise<boolean> {
133
+ if (!this.viewers.has(projectId)) {
134
+ this.viewers.set(projectId, new Set());
135
+ }
136
+ this.viewers.get(projectId)!.add(connId);
137
+
138
+ if (this.watchers.has(projectId)) return true;
139
+ return this.startWatching(projectId, projectPath);
140
+ }
141
+
142
+ /**
143
+ * Remove a connection as a viewer of a project. Stops the watcher only when
144
+ * no viewers remain.
145
+ */
146
+ removeViewer(connId: string, projectId: string): void {
147
+ const set = this.viewers.get(projectId);
148
+ if (!set) return;
149
+ set.delete(connId);
150
+ if (set.size === 0) {
151
+ this.viewers.delete(projectId);
152
+ this.stopWatching(projectId);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Remove a connection from every project it was viewing. Called on hard
158
+ * disconnect (tab close, network drop) where no explicit unwatch arrives.
159
+ */
160
+ removeViewerFromAll(connId: string): void {
161
+ for (const projectId of Array.from(this.viewers.keys())) {
162
+ this.removeViewer(connId, projectId);
163
+ }
164
+ }
165
+
166
+ /** In-flight start promises, to coalesce concurrent start requests. */
167
+ private starting = new Map<string, Promise<boolean>>();
168
+
169
+ /**
170
+ * Start watching a project directory. Concurrent calls for the same project
171
+ * are coalesced: `fs.watch` setup awaits a `stat`, so without this guard two
172
+ * near-simultaneous viewers (e.g. two devices) could each build a watcher and
173
+ * leak one.
117
174
  */
118
175
  async startWatching(projectId: string, projectPath: string): Promise<boolean> {
119
176
  // Already watching this project
@@ -122,6 +179,19 @@ class FileWatcherManager {
122
179
  return true;
123
180
  }
124
181
 
182
+ const inflight = this.starting.get(projectId);
183
+ if (inflight) return inflight;
184
+
185
+ const startPromise = this.doStartWatching(projectId, projectPath);
186
+ this.starting.set(projectId, startPromise);
187
+ try {
188
+ return await startPromise;
189
+ } finally {
190
+ this.starting.delete(projectId);
191
+ }
192
+ }
193
+
194
+ private async doStartWatching(projectId: string, projectPath: string): Promise<boolean> {
125
195
  try {
126
196
  // Normalize path
127
197
  const normalizedPath = normalize(projectPath);
@@ -140,14 +210,16 @@ class FileWatcherManager {
140
210
  }
141
211
  });
142
212
 
143
- // Handle watcher errors
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.
144
216
  watcher.on('error', (error) => {
145
217
  debug.error('file', `Watcher error for project ${projectId}:`, error);
146
- // Try to emit error to clients
147
218
  ws.emit.project(projectId, 'files:watch-error', {
148
219
  projectId,
149
220
  error: error.message || 'File watcher error'
150
221
  });
222
+ this.scheduleRestart(projectId);
151
223
  });
152
224
 
153
225
  // Store watcher instance
@@ -217,6 +289,17 @@ class FileWatcherManager {
217
289
  }
218
290
  }
219
291
 
292
+ /**
293
+ * Fully release a project: drop all viewers and any pending restart, then
294
+ * stop the watcher. Used when a project is removed entirely (not just when a
295
+ * single viewer navigates away).
296
+ */
297
+ releaseProject(projectId: string): void {
298
+ this.viewers.delete(projectId);
299
+ this.restarting.delete(projectId);
300
+ this.stopWatching(projectId);
301
+ }
302
+
220
303
  /**
221
304
  * Check if a project is being watched
222
305
  */
@@ -402,6 +485,37 @@ class FileWatcherManager {
402
485
  }, GIT_DEBOUNCE_MS);
403
486
  }
404
487
 
488
+ /**
489
+ * Schedule a debounced rebuild of a project's watcher after a fault.
490
+ * Guarded so overlapping error events don't spawn multiple restarts.
491
+ */
492
+ private scheduleRestart(projectId: string): void {
493
+ if (this.restarting.has(projectId)) return;
494
+ // Only restart if someone is still viewing the project.
495
+ if (!this.viewers.get(projectId)?.size) return;
496
+ this.restarting.add(projectId);
497
+
498
+ setTimeout(async () => {
499
+ this.restarting.delete(projectId);
500
+ if (!this.viewers.get(projectId)?.size) return;
501
+
502
+ const projectPath = this.watchers.get(projectId)?.projectPath;
503
+ if (!projectPath) return;
504
+
505
+ debug.warn('file', `Restarting faulted watcher for project ${projectId}`);
506
+ 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', {
512
+ projectId,
513
+ changes: [],
514
+ timestamp: Date.now()
515
+ });
516
+ }, 1000);
517
+ }
518
+
405
519
  /**
406
520
  * Stop all watchers (cleanup)
407
521
  */
@@ -20,7 +20,7 @@ registerProjectCleanup({
20
20
  registerProjectCleanup({
21
21
  name: 'file-watcher',
22
22
  run: (projectId) => {
23
- fileWatcher.stopWatching(projectId);
23
+ fileWatcher.releaseProject(projectId);
24
24
  }
25
25
  });
26
26
 
@@ -526,6 +526,15 @@ class WSServer {
526
526
  return this.connectionState.get(id);
527
527
  }
528
528
 
529
+ /**
530
+ * Get the stable connection id for a connection, or null if not registered.
531
+ * Exposed so services (e.g. the file watcher) can reference-count viewers
532
+ * per connection without duplicating room bookkeeping.
533
+ */
534
+ getConnectionId(conn: WSConnection): string | null {
535
+ return this.resolveId(conn);
536
+ }
537
+
529
538
  /**
530
539
  * Set authentication state for a connection.
531
540
  * Called by auth handlers after successful login/setup/invite.
@@ -17,6 +17,48 @@ import { broadcastPresence } from '../projects/status';
17
17
  import { sessionQueries, messageQueries } from '../../database/queries';
18
18
  import { requireSessionAccess } from '../access';
19
19
 
20
+ /**
21
+ * Broadcast presence + notify project members when a chat message may flip the
22
+ * stream's waiting-for-input state (an AskUserQuestion tool_use arrives, or a
23
+ * tool_result answers it). `event.data.message` IS the UnifiedMessage, so its
24
+ * blocks live at `.content` — reading `.message.content` (one level too deep)
25
+ * silently yields `[]` and the status indicators never update until refresh.
26
+ *
27
+ * Shared by the initial-stream and reconnect message handlers so the two paths
28
+ * cannot drift apart again.
29
+ */
30
+ function handleWaitingInputChange(
31
+ event: StreamEvent,
32
+ chatSessionId: string,
33
+ projectId: string | undefined,
34
+ ): void {
35
+ const message = event.data?.message;
36
+ const msgContent = Array.isArray(message?.content) ? message.content : [];
37
+
38
+ const askToolUse = msgContent.find(
39
+ (item: any) => item.type === 'tool_use' && item.name === 'AskUserQuestion'
40
+ );
41
+ const hasToolResult = msgContent.some((item: any) => item.type === 'tool_result');
42
+
43
+ // Recompute presence whenever the waiting state may have changed in either
44
+ // direction (AskUserQuestion → amber, tool_result → green).
45
+ if (askToolUse || hasToolResult) {
46
+ broadcastPresence().catch((err) => {
47
+ debug.warn('chat', 'Presence broadcast error on waiting-input state change:', err);
48
+ });
49
+ }
50
+
51
+ // Notify all project members when AskUserQuestion arrives (sound + push)
52
+ if (askToolUse && projectId) {
53
+ ws.emit.projectMembers(projectId, 'chat:waiting-input', {
54
+ projectId,
55
+ chatSessionId,
56
+ toolUseId: askToolUse.id,
57
+ timestamp: event.data?.timestamp || new Date().toISOString()
58
+ });
59
+ }
60
+ }
61
+
20
62
  // ============================================================================
21
63
  // Global stream lifecycle handler (module-level, not per-connection)
22
64
  //
@@ -233,26 +275,8 @@ export const streamHandler = createRouter()
233
275
  engine: event.data.engine,
234
276
  seq: event.seq
235
277
  });
236
- // Broadcast presence when waiting-input state may change
237
- // (AskUserQuestion tool_use arrives or tool_result clears it)
238
- const msgContent = Array.isArray(event.data.message?.message?.content) ? event.data.message.message.content : [];
239
- const askToolUse = msgContent.find((item: any) =>
240
- item.type === 'tool_use' && item.name === 'AskUserQuestion'
241
- );
242
- if (askToolUse || msgContent.some((item: any) => item.type === 'tool_result')) {
243
- broadcastPresence().catch((err) => {
244
- debug.warn('chat', 'Presence broadcast error on waiting-input state change:', err);
245
- });
246
- }
247
- // Notify all project members when AskUserQuestion arrives (sound + push)
248
- if (askToolUse && projectId) {
249
- ws.emit.projectMembers(projectId, 'chat:waiting-input', {
250
- projectId,
251
- chatSessionId,
252
- toolUseId: askToolUse.id,
253
- timestamp: event.data.timestamp || new Date().toISOString()
254
- });
255
- }
278
+ // Broadcast presence + notify when waiting-input state may change
279
+ handleWaitingInputChange(event, chatSessionId, projectId);
256
280
  break;
257
281
  }
258
282
 
@@ -395,24 +419,8 @@ export const streamHandler = createRouter()
395
419
  engine: event.data.engine,
396
420
  seq: event.seq
397
421
  });
398
- // Broadcast presence when waiting-input state may change
399
- const reconnMsgContent = Array.isArray(event.data.message?.message?.content) ? event.data.message.message.content : [];
400
- const reconnAskToolUse = reconnMsgContent.find((item: any) =>
401
- item.type === 'tool_use' && item.name === 'AskUserQuestion'
402
- );
403
- if (reconnAskToolUse || reconnMsgContent.some((item: any) => item.type === 'tool_result')) {
404
- broadcastPresence().catch((err) => {
405
- debug.warn('chat', 'Presence broadcast error on reconnect waiting-input state change:', err);
406
- });
407
- }
408
- if (reconnAskToolUse && projectId) {
409
- ws.emit.projectMembers(projectId, 'chat:waiting-input', {
410
- projectId,
411
- chatSessionId,
412
- toolUseId: reconnAskToolUse.id,
413
- timestamp: event.data.timestamp || new Date().toISOString()
414
- });
415
- }
422
+ // Broadcast presence + notify when waiting-input state may change
423
+ handleWaitingInputChange(event, chatSessionId, projectId);
416
424
  break;
417
425
  }
418
426
 
@@ -15,6 +15,10 @@ import { ws } from '$backend/utils/ws';
15
15
  import { projectQueries } from '../../database/queries/project-queries';
16
16
  import { requireProjectAccess } from '../access';
17
17
 
18
+ // Connection ids that already have a disconnect cleanup registered, so we
19
+ // don't stack duplicate cleanups when a connection re-watches across switches.
20
+ const cleanupRegistered = new Set<string>();
21
+
18
22
  export const watchHandler = createRouter()
19
23
  // Start watching a project directory
20
24
  .on('files:watch', {
@@ -30,19 +34,23 @@ export const watchHandler = createRouter()
30
34
  const projectId = project.id;
31
35
 
32
36
  try {
33
- // Check if already watching
34
- if (fileWatcher.isWatching(projectId)) {
35
- // Already watching, broadcast confirmation (frontend filters by projectId)
36
- ws.emit.project(projectId, 'files:watching', {
37
- projectId,
38
- watching: true,
39
- timestamp: Date.now()
37
+ const connId = ws.getConnectionId(conn);
38
+
39
+ // Tear down the watcher automatically if the connection drops without
40
+ // sending an explicit unwatch (tab close, network loss).
41
+ if (connId && !cleanupRegistered.has(connId)) {
42
+ cleanupRegistered.add(connId);
43
+ ws.addCleanup(conn, () => {
44
+ cleanupRegistered.delete(connId);
45
+ fileWatcher.removeViewerFromAll(connId);
40
46
  });
41
- return;
42
47
  }
43
48
 
44
- // Start watching
45
- const success = await fileWatcher.startWatching(projectId, projectPath);
49
+ // Register this connection as a viewer; starts the watcher if it is
50
+ // the first viewer, otherwise reuses the existing one.
51
+ const success = connId
52
+ ? await fileWatcher.addViewer(connId, projectId, projectPath)
53
+ : await fileWatcher.startWatching(projectId, projectPath);
46
54
 
47
55
  if (success) {
48
56
  // Broadcast confirmation (frontend filters by projectId)
@@ -69,25 +77,46 @@ export const watchHandler = createRouter()
69
77
  }
70
78
  })
71
79
 
72
- // Stop watching a project directory
80
+ // Stop watching a project directory.
81
+ // Resolves the target project from the explicit `projectPath` (the project
82
+ // being left) rather than the connection's current project context — by the
83
+ // time this fires the context has usually already advanced to the new
84
+ // project, so relying on it would unwatch the wrong one.
73
85
  .on('files:unwatch', {
74
- data: t.Object({})
86
+ data: t.Object({
87
+ projectPath: t.Optional(t.String())
88
+ })
75
89
  }, async ({ data, conn }) => {
76
- const projectId = ws.getProjectId(conn);
90
+ let projectId: string;
91
+ if (data.projectPath) {
92
+ const project = projectQueries.getByPath(data.projectPath);
93
+ if (!project) return; // unknown path — nothing to unwatch
94
+ requireProjectAccess(conn, project.id);
95
+ projectId = project.id;
96
+ } else {
97
+ // Backwards-compatible fallback for callers that don't send a path.
98
+ projectId = ws.getProjectId(conn);
99
+ }
77
100
 
78
101
  try {
79
- const success = fileWatcher.stopWatching(projectId);
102
+ const connId = ws.getConnectionId(conn);
103
+ if (connId) {
104
+ // Drops this viewer; watcher is stopped only when none remain.
105
+ fileWatcher.removeViewer(connId, projectId);
106
+ } else {
107
+ fileWatcher.stopWatching(projectId);
108
+ }
80
109
 
81
- // Broadcast confirmation (frontend filters by projectId)
110
+ // Broadcast the ACTUAL resulting state — other devices may still be
111
+ // viewing this project, in which case the watcher is still alive and
112
+ // they must not be told it stopped.
82
113
  ws.emit.project(projectId, 'files:watching', {
83
114
  projectId,
84
- watching: false,
115
+ watching: fileWatcher.isWatching(projectId),
85
116
  timestamp: Date.now()
86
117
  });
87
118
 
88
- if (success) {
89
- debug.log('file', `Stopped watching project ${projectId}`);
90
- }
119
+ debug.log('file', `Viewer left project ${projectId}`);
91
120
  } catch (error) {
92
121
  debug.error('file', 'Error stopping file watch:', error);
93
122
  }
@@ -31,7 +31,11 @@ export const writeHandler = createRouter()
31
31
  .http('files:write-file', {
32
32
  data: t.Object({
33
33
  filePath: t.String(),
34
- content: t.String()
34
+ content: t.String(),
35
+ // Optimistic concurrency token: the disk mtime the client's buffer is
36
+ // based on. When present and it no longer matches disk, the write is
37
+ // rejected instead of overwriting newer content. Omit to force-write.
38
+ baseModified: t.Optional(t.String())
35
39
  }),
36
40
  response: t.Object({
37
41
  message: t.String(),
@@ -44,7 +48,7 @@ export const writeHandler = createRouter()
44
48
  filePath,
45
49
  contentLength: data.content.length
46
50
  });
47
- return await writeFileOperation(filePath, data.content);
51
+ return await writeFileOperation(filePath, data.content, data.baseModified);
48
52
  })
49
53
 
50
54
  // Create file operation