@myrialabs/clopen 0.3.13 → 0.3.15

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 (50) hide show
  1. package/backend/chat/stream-manager.ts +15 -0
  2. package/backend/engine/README.md +16 -1669
  3. package/backend/engine/adapters/claude/message-converter.ts +36 -7
  4. package/backend/engine/adapters/claude/models.ts +219 -4
  5. package/backend/engine/docs/adapter-contract.md +183 -0
  6. package/backend/engine/docs/adding-an-engine.md +150 -0
  7. package/backend/engine/docs/database.md +123 -0
  8. package/backend/engine/docs/frontend-and-chat.md +176 -0
  9. package/backend/engine/docs/lessons-learned.md +715 -0
  10. package/backend/engine/docs/quick-reference.md +36 -0
  11. package/backend/engine/docs/system-tools.md +82 -0
  12. package/backend/engine/docs/websocket-routes.md +240 -0
  13. package/backend/files/file-archive.test.ts +131 -0
  14. package/backend/files/file-archive.ts +89 -28
  15. package/backend/files/file-operations.ts +21 -1
  16. package/backend/files/file-reading.ts +1 -13
  17. package/backend/files/file-watcher.ts +117 -3
  18. package/backend/http/audio.ts +236 -0
  19. package/backend/index.ts +6 -0
  20. package/backend/projects/project-cleanup.ts +1 -1
  21. package/backend/tunnel/cloudflared/index.ts +3 -1
  22. package/backend/tunnel/cloudflared/tunnel.ts +42 -0
  23. package/backend/tunnel/global-tunnel-manager.ts +52 -1
  24. package/backend/utils/ws.ts +9 -0
  25. package/backend/ws/chat/stream.ts +46 -38
  26. package/backend/ws/files/search.ts +5 -2
  27. package/backend/ws/files/watch.ts +48 -19
  28. package/backend/ws/files/write.ts +17 -6
  29. package/dist/assets/main-CYVFcz-a.js +358 -0
  30. package/dist/assets/{main-BqiSLc8F.css → main-DrFILAEB.css} +1 -1
  31. package/dist/audio/alert.ogg +0 -0
  32. package/dist/audio/bell.ogg +0 -0
  33. package/dist/audio/blip.ogg +0 -0
  34. package/dist/audio/chirp.ogg +0 -0
  35. package/dist/audio/cloud.ogg +0 -0
  36. package/dist/audio/glass.ogg +0 -0
  37. package/dist/audio/message.ogg +0 -0
  38. package/dist/audio/sparkle.ogg +0 -0
  39. package/dist/audio/subtle.ogg +0 -0
  40. package/dist/audio/tap.ogg +0 -0
  41. package/dist/audio/woodblock.ogg +0 -0
  42. package/dist/index.html +2 -2
  43. package/package.json +2 -2
  44. package/shared/constants/notification-sounds.ts +31 -0
  45. package/shared/types/stores/settings.ts +4 -0
  46. package/shared/types/unified/index.ts +6 -0
  47. package/shared/types/unified/stream.ts +15 -1
  48. package/shared/types/unified/tool.ts +41 -1
  49. package/dist/assets/main-DOVudc3_.js +0 -354
  50. /package/dist/audio/{notification.ogg → chime.ogg} +0 -0
@@ -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
 
@@ -149,6 +149,7 @@ interface CodeMatch {
149
149
  line: number;
150
150
  text: string;
151
151
  column: number;
152
+ length: number;
152
153
  }
153
154
 
154
155
  interface CodeSearchResult {
@@ -231,7 +232,8 @@ async function searchCodeContent(
231
232
  matches.push({
232
233
  line: i + 1,
233
234
  text: lines[i].trimEnd(),
234
- column: match.index + 1
235
+ column: match.index + 1,
236
+ length: match[0].length
235
237
  });
236
238
  // Prevent infinite loop for zero-length matches
237
239
  if (match[0].length === 0) {
@@ -378,7 +380,8 @@ export const fileSearchHandler = createRouter()
378
380
  matches: t.Array(t.Object({
379
381
  line: t.Number(),
380
382
  text: t.String(),
381
- column: t.Number()
383
+ column: t.Number(),
384
+ length: t.Number()
382
385
  })),
383
386
  totalMatches: t.Number()
384
387
  }))
@@ -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
  }
@@ -23,7 +23,7 @@ import {
23
23
  deleteOperation
24
24
  } from '../../files/file-operations';
25
25
  import { createZipOperation, extractZipOperation } from '../../files/file-archive';
26
- import { stat as fsStat, readdir as fsReaddir, rename as fsRename, access as fsAccess } from 'node:fs/promises';
26
+ import { stat as fsStat, readdir as fsReaddir, rename as fsRename } from 'node:fs/promises';
27
27
  import { requireFilePathAccess, requireSharedFilePathAccess } from './path-access';
28
28
 
29
29
  export const writeHandler = createRouter()
@@ -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
@@ -237,14 +241,21 @@ export const writeHandler = createRouter()
237
241
  throw new Error('Source path is not a directory');
238
242
  }
239
243
 
244
+ // Reject only when the destination is a genuinely different entry. On
245
+ // case-insensitive filesystems (default on macOS and Windows) a
246
+ // case-only rename like "Foo" -> "foo" makes the destination resolve to
247
+ // the same inode as the source, so allow that case through.
240
248
  try {
241
- await fsAccess(newPath);
242
- throw new Error('Destination path already exists');
249
+ const newStats = await fsStat(newPath);
250
+ const sameEntry = newStats.ino === oldStats.ino && newStats.dev === oldStats.dev;
251
+ if (!sameEntry) {
252
+ throw new Error('Destination path already exists');
253
+ }
243
254
  } catch (err) {
244
255
  if (err instanceof Error && err.message === 'Destination path already exists') {
245
256
  throw err;
246
257
  }
247
- // fsAccess threw because newPath does not exist — that is what we want.
258
+ // fsStat threw because newPath does not exist — that is what we want.
248
259
  }
249
260
 
250
261
  await fsRename(oldPath, newPath);