@myrialabs/clopen 0.4.44 → 0.4.46

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 (118) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +20 -3
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/models.test.ts +49 -0
  15. package/backend/engine/adapters/claude/models.ts +81 -562
  16. package/backend/engine/adapters/claude/stream.ts +32 -5
  17. package/backend/engine/adapters/cline/credential.ts +42 -18
  18. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  19. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  20. package/backend/engine/adapters/cline/models.test.ts +77 -0
  21. package/backend/engine/adapters/cline/models.ts +89 -3
  22. package/backend/engine/adapters/cline/presets.ts +5 -0
  23. package/backend/engine/adapters/cline/stream.ts +29 -8
  24. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  25. package/backend/engine/adapters/codex/models.ts +54 -31
  26. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  27. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  28. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  29. package/backend/engine/adapters/codex/stream.ts +29 -11
  30. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  31. package/backend/engine/adapters/copilot/models.ts +51 -24
  32. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  33. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  34. package/backend/engine/adapters/copilot/stream.ts +83 -70
  35. package/backend/engine/adapters/cursor/stream.ts +27 -12
  36. package/backend/engine/adapters/opencode/server.ts +14 -4
  37. package/backend/engine/adapters/opencode/stream.ts +18 -3
  38. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  39. package/backend/engine/adapters/pi/credential.ts +68 -12
  40. package/backend/engine/adapters/pi/environment.ts +9 -5
  41. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  42. package/backend/engine/adapters/pi/mcp.ts +88 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  44. package/backend/engine/adapters/pi/presets.ts +10 -5
  45. package/backend/engine/adapters/pi/stream.ts +77 -41
  46. package/backend/engine/adapters/qwen/environment.ts +39 -2
  47. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  49. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  50. package/backend/engine/adapters/qwen/models.ts +42 -5
  51. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  52. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  53. package/backend/engine/adapters/qwen/stream.ts +118 -87
  54. package/backend/engine/artifact-sync.ts +12 -5
  55. package/backend/engine/docs/adapter-contract.md +7 -4
  56. package/backend/engine/docs/lessons-learned.md +405 -62
  57. package/backend/engine/docs/quick-reference.md +2 -2
  58. package/backend/engine/docs/stack.md +17 -4
  59. package/backend/engine/docs/websocket-routes.md +5 -5
  60. package/backend/engine/install-recipes.test.ts +105 -5
  61. package/backend/engine/install-recipes.ts +102 -42
  62. package/backend/engine/install-runner.ts +56 -2
  63. package/backend/engine/stack-project.ts +71 -1
  64. package/backend/files/file-watcher.test.ts +77 -0
  65. package/backend/files/file-watcher.ts +92 -60
  66. package/backend/files/watch-ignore.test.ts +182 -0
  67. package/backend/files/watch-ignore.ts +244 -0
  68. package/backend/git/git-executor.ts +14 -4
  69. package/backend/index.ts +16 -1
  70. package/backend/instructions/service.ts +5 -3
  71. package/backend/instructions/sync.ts +10 -27
  72. package/backend/mcp/README.md +2 -2
  73. package/backend/mcp/external/config.ts +83 -23
  74. package/backend/mcp/external/project.ts +124 -0
  75. package/backend/mcp/external/proxy.ts +65 -11
  76. package/backend/mcp/index.ts +22 -9
  77. package/backend/mcp/internal/config.ts +42 -3
  78. package/backend/mcp/internal/remote-server.ts +11 -1
  79. package/backend/memory/embedding/install.ts +29 -1
  80. package/backend/skills/marketplace.ts +1 -1
  81. package/backend/snapshot/blob-store.ts +9 -5
  82. package/backend/snapshot/git-attribution.test.ts +42 -0
  83. package/backend/snapshot/git-attribution.ts +306 -0
  84. package/backend/snapshot/gitignore.test.ts +62 -0
  85. package/backend/snapshot/gitignore.ts +158 -78
  86. package/backend/snapshot/snapshot-service.test.ts +270 -0
  87. package/backend/snapshot/snapshot-service.ts +412 -136
  88. package/backend/snapshot/turn-activity.test.ts +52 -0
  89. package/backend/snapshot/turn-activity.ts +83 -0
  90. package/backend/snapshot/turn-changes.test.ts +58 -1
  91. package/backend/snapshot/turn-changes.ts +66 -0
  92. package/backend/utils/keyed-lock.test.ts +33 -0
  93. package/backend/utils/keyed-lock.ts +17 -0
  94. package/backend/utils/port-utils.test.ts +29 -0
  95. package/backend/utils/port-utils.ts +19 -0
  96. package/backend/worktrees/tree.ts +1 -1
  97. package/backend/ws/chat/composer.ts +504 -0
  98. package/backend/ws/chat/index.ts +3 -1
  99. package/backend/ws/chat/stream.ts +252 -440
  100. package/backend/ws/engine/cline/accounts.ts +26 -6
  101. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  102. package/backend/ws/engine/codex/accounts.ts +17 -13
  103. package/backend/ws/engine/pi/accounts.ts +61 -6
  104. package/backend/ws/index.ts +4 -0
  105. package/backend/ws/project-artifacts/index.ts +236 -0
  106. package/backend/ws/snapshot/changes.ts +66 -31
  107. package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
  108. package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
  109. package/dist/assets/main-BiDNMWb3.css +1 -0
  110. package/dist/assets/main-BlhKWz2B.js +1241 -0
  111. package/dist/index.html +2 -2
  112. package/package.json +19 -15
  113. package/shared/types/stores/settings.ts +5 -0
  114. package/shared/types/unified/message.ts +2 -0
  115. package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
  116. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
  117. package/dist/assets/main-DOkwqXRU.js +0 -1215
  118. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -10,7 +10,7 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { streamManager, type StreamEvent } from '../../chat/stream-manager';
13
- import type { EngineType, UnifiedMessage } from '$shared/types/unified';
13
+ import type { EngineType, StreamRequest, UnifiedMessage } from '$shared/types/unified';
14
14
  import { debug } from '$shared/utils/logger';
15
15
  import { trimSubAgentForWire } from '$shared/utils/subagent-wire-trim';
16
16
  import { ws } from '$backend/utils/ws';
@@ -178,18 +178,198 @@ streamManager.on('snapshot:captured', (event: { projectId: string; chatSessionId
178
178
  ws.emit.projectMembers(projectId, 'snapshot:captured', { projectId, chatSessionId });
179
179
  });
180
180
 
181
- // In-memory store for latest chat input state per chat session (keyed by chatSessionId)
182
- const chatSessionInputState = new Map<string, { text: string; senderId: string; attachments?: any[] }>();
183
-
184
- // In-memory store for edit mode state per chat session (keyed by chatSessionId)
185
- const chatSessionEditMode = new Map<string, { isEditing: boolean; messageId: string | null; messageTimestamp: string | null }>();
186
-
187
181
  // In-memory store for model state per chat session (keyed by chatSessionId)
188
- const chatSessionModelState = new Map<string, { engine: string; provider: string; modelId: string; modelName: string; senderId: string }>();
182
+ const chatSessionModelState = new Map<string, { engine: string; provider: string; modelId: string; modelName: string; reasoningEffort?: string | null; senderId: string }>();
189
183
 
190
184
  // In-memory store for account state per chat session (keyed by chatSessionId)
191
185
  const chatSessionAccountState = new Map<string, { accountId: number | null; senderId: string }>();
192
186
 
187
+ /**
188
+ * Forward one stream's events to its chat session room until the stream ends.
189
+ *
190
+ * Every path that attaches a stream to the room goes through here — the
191
+ * sender's own request, a client re-attaching after a refresh, and a queued
192
+ * message the server starts on its own — so the event wire format exists once.
193
+ * Returns the unsubscribe; a terminal event unsubscribes by itself.
194
+ */
195
+ export function bridgeStreamToRoom(
196
+ streamId: string,
197
+ chatSessionId: string,
198
+ projectId: string | undefined,
199
+ options: { presenceOnConnection?: boolean } = {}
200
+ ): () => void {
201
+ const { presenceOnConnection = true } = options;
202
+
203
+ const handleStreamEvent = (event: StreamEvent) => {
204
+ try {
205
+ switch (event.type) {
206
+ case 'connection':
207
+ ws.emit.chatSession(chatSessionId, 'chat:connection', {
208
+ chatSessionId,
209
+ processId: event.data.processId,
210
+ timestamp: event.data.timestamp,
211
+ seq: event.seq
212
+ });
213
+ if (presenceOnConnection) {
214
+ broadcastPresence().catch((err) => {
215
+ debug.warn('chat', 'Presence broadcast error on stream connection event:', err);
216
+ });
217
+ }
218
+ break;
219
+
220
+ case 'message': {
221
+ ws.emit.chatSession(chatSessionId, 'chat:message', {
222
+ chatSessionId,
223
+ processId: event.processId,
224
+ message: trimSubAgentForWire(event.data.message),
225
+ usage: event.data.usage,
226
+ timestamp: event.data.timestamp,
227
+ message_id: event.data.message_id,
228
+ parent_message_id: event.data.parent_message_id,
229
+ sender_id: event.data.sender_id,
230
+ sender_name: event.data.sender_name,
231
+ engine: event.data.engine,
232
+ seq: event.seq
233
+ });
234
+ // Broadcast presence + notify when waiting-input state may change
235
+ handleWaitingInputChange(event, chatSessionId, projectId);
236
+ break;
237
+ }
238
+
239
+ case 'partial':
240
+ ws.emit.chatSession(chatSessionId, 'chat:partial', {
241
+ chatSessionId,
242
+ processId: event.processId,
243
+ eventType: event.data.eventType as any,
244
+ partialText: event.data.partialText || '',
245
+ deltaText: event.data.deltaText || '',
246
+ ...(event.data.reasoning && { reasoning: true }),
247
+ timestamp: event.data.timestamp,
248
+ seq: event.seq
249
+ });
250
+ break;
251
+
252
+ case 'notification':
253
+ ws.emit.chatSession(chatSessionId, 'chat:notification', {
254
+ notification: event.data.notification,
255
+ timestamp: event.data.timestamp,
256
+ seq: event.seq
257
+ });
258
+ break;
259
+
260
+ case 'rate_limit':
261
+ ws.emit.chatSession(chatSessionId, 'chat:rate_limit', {
262
+ chatSessionId: event.data.chatSessionId,
263
+ engine: event.data.engine,
264
+ accountId: event.data.accountId,
265
+ status: event.data.status,
266
+ utilization: event.data.utilization,
267
+ resetsAt: event.data.resetsAt,
268
+ rateLimitType: event.data.rateLimitType ?? null,
269
+ timestamp: event.data.timestamp,
270
+ seq: event.seq
271
+ });
272
+ break;
273
+
274
+ case 'complete':
275
+ ws.emit.chatSession(chatSessionId, 'chat:complete', {
276
+ chatSessionId,
277
+ processId: event.processId,
278
+ timestamp: event.data.timestamp,
279
+ seq: event.seq
280
+ });
281
+ // Cross-project notifications (stream-finished, presence) are handled
282
+ // by the global stream:lifecycle listener at the module level.
283
+ unsubscribe();
284
+ break;
285
+
286
+ case 'error':
287
+ ws.emit.chatSession(chatSessionId, 'chat:error', {
288
+ chatSessionId,
289
+ processId: event.processId,
290
+ error: event.data.error,
291
+ timestamp: event.data.timestamp,
292
+ seq: event.seq
293
+ });
294
+ unsubscribe();
295
+ break;
296
+
297
+ case 'cancelled':
298
+ ws.emit.chatSession(chatSessionId, 'chat:error', {
299
+ chatSessionId,
300
+ processId: event.processId,
301
+ error: 'Stream cancelled',
302
+ timestamp: event.data.timestamp,
303
+ seq: event.seq
304
+ });
305
+ unsubscribe();
306
+ break;
307
+ }
308
+ } catch (err) {
309
+ // Log but do NOT unsubscribe — one bad event must not kill the
310
+ // entire stream subscription. The bridge between StreamManager
311
+ // and the WS room would be permanently broken, causing the UI
312
+ // to stop receiving stream output while the WS stays connected.
313
+ debug.error('chat', 'Error handling stream event:', err);
314
+ }
315
+ };
316
+
317
+ const unsubscribe = streamManager.subscribeToStream(streamId, handleStreamEvent);
318
+ return unsubscribe;
319
+ }
320
+
321
+ /**
322
+ * Start a chat turn and announce it to the session room. Shared by a client's
323
+ * `chat:stream` and the server-side message queue. Failures are reported to the
324
+ * room as `chat:error` and resolve to null — the caller has nothing to attach.
325
+ */
326
+ export async function startChatStream(request: StreamRequest): Promise<string | null> {
327
+ // The client's projectPath is a view preference; the session's worktree is
328
+ // the fact. Resolving server-side is what keeps an isolated session from
329
+ // writing into the main tree when the two disagree.
330
+ const workingRoot = resolveSessionPath(request.chatSessionId, request.projectPath);
331
+
332
+ try {
333
+ debug.log('chat', 'Starting chat stream:', {
334
+ chatSessionId: request.chatSessionId,
335
+ projectId: request.projectId,
336
+ workingRoot
337
+ });
338
+
339
+ const streamId = await streamManager.startStream({ ...request, projectPath: workingRoot });
340
+ debug.log('chat', 'Stream started with ID:', streamId);
341
+
342
+ // The connection event from startStream() fires before anyone subscribes,
343
+ // so it is announced here. The user message reaches the room through the
344
+ // bridge (it carries resume, sender info and the saved message id).
345
+ const stream = streamManager.getStream(streamId);
346
+ if (stream) {
347
+ ws.emit.chatSession(request.chatSessionId, 'chat:connection', {
348
+ chatSessionId: request.chatSessionId,
349
+ processId: stream.processId,
350
+ timestamp: stream.startedAt.toISOString(),
351
+ seq: 1
352
+ });
353
+ }
354
+ broadcastPresence().catch((err) => {
355
+ debug.warn('chat', 'Presence broadcast error on chat stream start:', err);
356
+ });
357
+
358
+ return streamId;
359
+ } catch (error) {
360
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
361
+ debug.error('chat', 'Chat stream start error:', errorMessage);
362
+
363
+ ws.emit.chatSession(request.chatSessionId, 'chat:error', {
364
+ chatSessionId: request.chatSessionId,
365
+ processId: crypto.randomUUID(),
366
+ error: errorMessage,
367
+ timestamp: new Date().toISOString()
368
+ });
369
+ return null;
370
+ }
371
+ }
372
+
193
373
  export const streamHandler = createRouter()
194
374
  // Join a chat session room (subscribe to chat events for this session)
195
375
  .on('chat:join-session', {
@@ -301,195 +481,32 @@ export const streamHandler = createRouter()
301
481
  requireSessionAccess(conn, data.chatSessionId);
302
482
  const projectId = ws.getProjectId(conn);
303
483
 
304
- // The client's projectPath is a view preference; the session's worktree is
305
- // the fact. Resolving server-side is what keeps an isolated session from
306
- // writing into the main tree when the two disagree.
307
- const workingRoot = resolveSessionPath(data.chatSessionId, data.projectPath);
308
-
484
+ // The WS user id is server-trusted (unlike the client-supplied sender)
485
+ // and routes background Web Push to the requester's devices. Missing
486
+ // context must not break the stream — push is best-effort.
487
+ let requestedByUserId: string | undefined;
309
488
  try {
310
- debug.log('chat', 'WS chat:stream received:', {
311
- chatSessionId: data.chatSessionId,
312
- projectId,
313
- workingRoot
314
- });
315
-
316
- // The WS user id is server-trusted (unlike the client-supplied sender)
317
- // and routes background Web Push to the requester's devices. Missing
318
- // context must not break the stream — push is best-effort.
319
- let requestedByUserId: string | undefined;
320
- try {
321
- requestedByUserId = ws.getUserId(conn);
322
- } catch {
323
- requestedByUserId = undefined;
324
- }
325
-
326
- // Start background stream
327
- const streamId = await streamManager.startStream({
328
- projectPath: workingRoot,
329
- projectId,
330
- prompt: data.prompt,
331
- chatSessionId: data.chatSessionId,
332
- engine: data.engine,
333
- sender: data.sender,
334
- profileId: data.profileId,
335
- reasoningEffort: data.reasoningEffort,
336
- requestedByUserId
337
- });
338
-
339
- debug.log('chat', 'Stream started with ID:', streamId);
340
-
341
- // Emit connection event to chat session room and broadcast presence immediately
342
- // (the connection event from startStream() fires before subscription, so we emit it manually)
343
- const stream = streamManager.getStream(streamId);
344
- if (stream) {
345
- ws.emit.chatSession(data.chatSessionId, 'chat:connection', {
346
- chatSessionId: data.chatSessionId,
347
- processId: stream.processId,
348
- timestamp: stream.startedAt.toISOString(),
349
- seq: 1
350
- });
351
- // User message is broadcast by stream-manager via event subscription below
352
- // (includes resume, sender info, and saved message ID)
353
- }
354
- broadcastPresence().catch((err) => {
355
- debug.warn('chat', 'Presence broadcast error on chat:stream start:', err);
356
- });
357
-
358
- // Subscribe to stream events (event-driven, no polling)
359
- // Use ws.emit.chatSession() for session-scoped chat events
360
- // Only users who joined this chat session room receive events
361
- const chatSessionId = data.chatSessionId;
362
- const handleStreamEvent = (event: StreamEvent) => {
363
- try {
364
- switch (event.type) {
365
- case 'connection':
366
- ws.emit.chatSession(chatSessionId, 'chat:connection', {
367
- chatSessionId,
368
- processId: event.data.processId,
369
- timestamp: event.data.timestamp,
370
- seq: event.seq
371
- });
372
- broadcastPresence().catch((err) => {
373
- debug.warn('chat', 'Presence broadcast error on stream connection event:', err);
374
- });
375
- break;
376
-
377
- case 'message': {
378
- ws.emit.chatSession(chatSessionId, 'chat:message', {
379
- chatSessionId,
380
- processId: event.processId,
381
- message: trimSubAgentForWire(event.data.message),
382
- usage: event.data.usage,
383
- timestamp: event.data.timestamp,
384
- message_id: event.data.message_id,
385
- parent_message_id: event.data.parent_message_id,
386
- sender_id: event.data.sender_id,
387
- sender_name: event.data.sender_name,
388
- engine: event.data.engine,
389
- seq: event.seq
390
- });
391
- // Broadcast presence + notify when waiting-input state may change
392
- handleWaitingInputChange(event, chatSessionId, projectId);
393
- break;
394
- }
395
-
396
- case 'partial':
397
- ws.emit.chatSession(chatSessionId, 'chat:partial', {
398
- chatSessionId,
399
- processId: event.processId,
400
- eventType: event.data.eventType as any,
401
- partialText: event.data.partialText || '',
402
- deltaText: event.data.deltaText || '',
403
- ...(event.data.reasoning && { reasoning: true }),
404
- timestamp: event.data.timestamp,
405
- seq: event.seq
406
- });
407
- break;
408
-
409
- case 'notification':
410
- ws.emit.chatSession(chatSessionId, 'chat:notification', {
411
- notification: event.data.notification,
412
- timestamp: event.data.timestamp,
413
- seq: event.seq
414
- });
415
- break;
416
-
417
- case 'rate_limit':
418
- ws.emit.chatSession(chatSessionId, 'chat:rate_limit', {
419
- chatSessionId: event.data.chatSessionId,
420
- engine: event.data.engine,
421
- accountId: event.data.accountId,
422
- status: event.data.status,
423
- utilization: event.data.utilization,
424
- resetsAt: event.data.resetsAt,
425
- rateLimitType: event.data.rateLimitType ?? null,
426
- timestamp: event.data.timestamp,
427
- seq: event.seq
428
- });
429
- break;
430
-
431
- case 'complete':
432
- ws.emit.chatSession(chatSessionId, 'chat:complete', {
433
- chatSessionId,
434
- processId: event.processId,
435
- timestamp: event.data.timestamp,
436
- seq: event.seq
437
- });
438
- // Cross-project notifications (stream-finished, presence) are handled
439
- // by the global stream:lifecycle listener at the module level.
440
- unsubscribe();
441
- break;
442
-
443
- case 'error':
444
- ws.emit.chatSession(chatSessionId, 'chat:error', {
445
- chatSessionId,
446
- processId: event.processId,
447
- error: event.data.error,
448
- timestamp: event.data.timestamp,
449
- seq: event.seq
450
- });
451
- // Cross-project notifications handled by stream:lifecycle listener
452
- unsubscribe();
453
- break;
454
-
455
- case 'cancelled':
456
- ws.emit.chatSession(chatSessionId, 'chat:error', {
457
- chatSessionId,
458
- processId: event.processId,
459
- error: 'Stream cancelled',
460
- timestamp: event.data.timestamp,
461
- seq: event.seq
462
- });
463
- // Cross-project notifications handled by stream:lifecycle listener
464
- unsubscribe();
465
- break;
466
- }
467
- } catch (err) {
468
- // Log but do NOT unsubscribe — one bad event must not kill the
469
- // entire stream subscription. The bridge between StreamManager
470
- // and the WS room would be permanently broken, causing the UI
471
- // to stop receiving stream output while the WS stays connected.
472
- debug.error('chat', 'Error handling stream event:', err);
473
- }
474
- };
475
-
476
- // Subscribe to stream events
477
- const unsubscribe = streamManager.subscribeToStream(streamId, handleStreamEvent);
478
-
479
- // Register cleanup with WSServer (called automatically on connection close)
480
- ws.addCleanup(conn, unsubscribe);
489
+ requestedByUserId = ws.getUserId(conn);
490
+ } catch {
491
+ requestedByUserId = undefined;
492
+ }
481
493
 
482
- } catch (error) {
483
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
484
- debug.error('chat', 'WS chat:stream error:', errorMessage);
494
+ const streamId = await startChatStream({
495
+ projectPath: data.projectPath,
496
+ projectId,
497
+ chatSessionId: data.chatSessionId,
498
+ prompt: data.prompt,
499
+ engine: data.engine,
500
+ sender: data.sender,
501
+ profileId: data.profileId,
502
+ reasoningEffort: data.reasoningEffort,
503
+ requestedByUserId
504
+ });
505
+ if (!streamId) return;
485
506
 
486
- ws.emit.chatSession(data.chatSessionId, 'chat:error', {
487
- chatSessionId: data.chatSessionId,
488
- processId: crypto.randomUUID(),
489
- error: errorMessage,
490
- timestamp: new Date().toISOString()
491
- });
492
- }
507
+ // Tied to this connection: it closes with the connection, and the
508
+ // client's reconnect builds a new one.
509
+ ws.addCleanup(conn, bridgeStreamToRoom(streamId, data.chatSessionId, projectId));
493
510
  })
494
511
 
495
512
  // Reconnect to an active stream (after browser refresh / project switch)
@@ -512,118 +529,7 @@ export const streamHandler = createRouter()
512
529
 
513
530
  debug.log('chat', 'Reconnecting to active stream:', streamState.streamId);
514
531
 
515
- // Subscribe this connection to the stream's events (session-scoped)
516
- const handleStreamEvent = (event: StreamEvent) => {
517
- try {
518
- switch (event.type) {
519
- case 'connection':
520
- ws.emit.chatSession(chatSessionId, 'chat:connection', {
521
- chatSessionId,
522
- processId: event.data.processId,
523
- timestamp: event.data.timestamp,
524
- seq: event.seq
525
- });
526
- break;
527
-
528
- case 'message': {
529
- ws.emit.chatSession(chatSessionId, 'chat:message', {
530
- chatSessionId,
531
- processId: event.processId,
532
- message: trimSubAgentForWire(event.data.message),
533
- usage: event.data.usage,
534
- timestamp: event.data.timestamp,
535
- message_id: event.data.message_id,
536
- parent_message_id: event.data.parent_message_id,
537
- sender_id: event.data.sender_id,
538
- sender_name: event.data.sender_name,
539
- engine: event.data.engine,
540
- seq: event.seq
541
- });
542
- // Broadcast presence + notify when waiting-input state may change
543
- handleWaitingInputChange(event, chatSessionId, projectId);
544
- break;
545
- }
546
-
547
- case 'partial':
548
- ws.emit.chatSession(chatSessionId, 'chat:partial', {
549
- chatSessionId,
550
- processId: event.processId,
551
- eventType: event.data.eventType as any,
552
- partialText: event.data.partialText || '',
553
- deltaText: event.data.deltaText || '',
554
- ...(event.data.reasoning && { reasoning: true }),
555
- timestamp: event.data.timestamp,
556
- seq: event.seq
557
- });
558
- break;
559
-
560
- case 'notification':
561
- ws.emit.chatSession(chatSessionId, 'chat:notification', {
562
- notification: event.data.notification,
563
- timestamp: event.data.timestamp,
564
- seq: event.seq
565
- });
566
- break;
567
-
568
- case 'rate_limit':
569
- ws.emit.chatSession(chatSessionId, 'chat:rate_limit', {
570
- chatSessionId: event.data.chatSessionId,
571
- engine: event.data.engine,
572
- accountId: event.data.accountId,
573
- status: event.data.status,
574
- utilization: event.data.utilization,
575
- resetsAt: event.data.resetsAt,
576
- rateLimitType: event.data.rateLimitType ?? null,
577
- timestamp: event.data.timestamp,
578
- seq: event.seq
579
- });
580
- break;
581
-
582
- case 'complete':
583
- ws.emit.chatSession(chatSessionId, 'chat:complete', {
584
- chatSessionId,
585
- processId: event.processId,
586
- timestamp: event.data.timestamp,
587
- seq: event.seq
588
- });
589
- // Cross-project notifications handled by stream:lifecycle listener
590
- unsubscribe();
591
- break;
592
-
593
- case 'error':
594
- ws.emit.chatSession(chatSessionId, 'chat:error', {
595
- chatSessionId,
596
- processId: event.processId,
597
- error: event.data.error,
598
- timestamp: event.data.timestamp,
599
- seq: event.seq
600
- });
601
- // Cross-project notifications handled by stream:lifecycle listener
602
- unsubscribe();
603
- break;
604
-
605
- case 'cancelled':
606
- ws.emit.chatSession(chatSessionId, 'chat:error', {
607
- chatSessionId,
608
- processId: event.processId,
609
- error: 'Stream cancelled',
610
- timestamp: event.data.timestamp,
611
- seq: event.seq
612
- });
613
- // Cross-project notifications handled by stream:lifecycle listener
614
- unsubscribe();
615
- break;
616
- }
617
- } catch (err) {
618
- // Log but do NOT unsubscribe — same rationale as the initial
619
- // stream handler: a transient error must not permanently break
620
- // the EventEmitter → WS room bridge.
621
- debug.error('chat', 'Error handling reconnected stream event:', err);
622
- }
623
- };
624
-
625
- const unsubscribe = streamManager.subscribeToStream(streamState.streamId, handleStreamEvent);
626
- ws.addCleanup(conn, unsubscribe);
532
+ ws.addCleanup(conn, bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false }));
627
533
 
628
534
  // Send current state snapshot to chat session room so frontend can catch up
629
535
  ws.emit.chatSession(chatSessionId, 'chat:connection', {
@@ -797,114 +703,6 @@ export const streamHandler = createRouter()
797
703
  }
798
704
  })
799
705
 
800
- // Collaborative edit mode - broadcast and store edit mode state per chat session
801
- .on('chat:edit-mode', {
802
- data: t.Object({
803
- senderId: t.String(),
804
- chatSessionId: t.String(),
805
- isEditing: t.Boolean(),
806
- messageId: t.Union([t.String(), t.Null()]),
807
- messageTimestamp: t.Union([t.String(), t.Null()])
808
- })
809
- }, ({ data, conn }) => {
810
- requireSessionAccess(conn, data.chatSessionId);
811
- const chatSessionId = data.chatSessionId;
812
-
813
- // Store on server for late joiners / refresh (keyed by chatSessionId)
814
- if (data.isEditing && data.messageId) {
815
- chatSessionEditMode.set(chatSessionId, {
816
- isEditing: true,
817
- messageId: data.messageId,
818
- messageTimestamp: data.messageTimestamp
819
- });
820
- } else {
821
- chatSessionEditMode.delete(chatSessionId);
822
- }
823
-
824
- ws.emit.chatSession(chatSessionId, 'chat:edit-mode', {
825
- senderId: data.senderId,
826
- isEditing: data.isEditing,
827
- messageId: data.messageId,
828
- messageTimestamp: data.messageTimestamp
829
- });
830
- })
831
-
832
- // Get current edit mode state for a chat session (for refresh / late joiners)
833
- .http('chat:get-edit-mode', {
834
- data: t.Object({
835
- chatSessionId: t.Optional(t.String())
836
- }),
837
- response: t.Object({
838
- isEditing: t.Boolean(),
839
- messageId: t.Union([t.String(), t.Null()]),
840
- messageTimestamp: t.Union([t.String(), t.Null()])
841
- })
842
- }, ({ data, conn }) => {
843
- const chatSessionId = data.chatSessionId || '';
844
- if (chatSessionId) {
845
- requireSessionAccess(conn, chatSessionId);
846
- }
847
- const editState = chatSessionEditMode.get(chatSessionId);
848
- return editState || { isEditing: false, messageId: null, messageTimestamp: null };
849
- })
850
-
851
- // Collaborative input sync - broadcast typing/attachments to other users in the same chat session
852
- .on('chat:input-sync', {
853
- data: t.Object({
854
- text: t.String(),
855
- senderId: t.String(),
856
- chatSessionId: t.String(),
857
- attachments: t.Optional(t.Array(t.Object({
858
- id: t.String(),
859
- fileName: t.String(),
860
- type: t.String(),
861
- mediaType: t.String(),
862
- base64: t.String()
863
- })))
864
- })
865
- }, ({ data, conn }) => {
866
- requireSessionAccess(conn, data.chatSessionId);
867
- const chatSessionId = data.chatSessionId;
868
-
869
- // Store latest input state on server for late-joining users (keyed by chatSessionId)
870
- chatSessionInputState.set(chatSessionId, {
871
- text: data.text,
872
- senderId: data.senderId,
873
- attachments: data.attachments
874
- });
875
-
876
- ws.emit.chatSession(chatSessionId, 'chat:input-sync', {
877
- text: data.text,
878
- senderId: data.senderId,
879
- attachments: data.attachments
880
- });
881
- })
882
-
883
- // Get latest input state for a chat session (for users switching sessions)
884
- .http('chat:get-input-state', {
885
- data: t.Object({
886
- chatSessionId: t.Optional(t.String())
887
- }),
888
- response: t.Object({
889
- text: t.String(),
890
- senderId: t.String(),
891
- attachments: t.Optional(t.Array(t.Object({
892
- id: t.String(),
893
- fileName: t.String(),
894
- type: t.String(),
895
- mediaType: t.String(),
896
- base64: t.String()
897
- })))
898
- })
899
- }, ({ data, conn }) => {
900
- const chatSessionId = data.chatSessionId || '';
901
- if (chatSessionId) {
902
- requireSessionAccess(conn, chatSessionId);
903
- }
904
- const state = chatSessionInputState.get(chatSessionId);
905
- return state || { text: '', senderId: '' };
906
- })
907
-
908
706
  // Collaborative model sync - broadcast model changes to other users in the same chat session
909
707
  .on('chat:model-sync', {
910
708
  data: t.Object({
@@ -913,7 +711,13 @@ export const streamHandler = createRouter()
913
711
  engine: t.String(),
914
712
  provider: t.String(),
915
713
  modelId: t.String(),
916
- modelName: t.String()
714
+ modelName: t.String(),
715
+ // The reasoning level travels with the model pick (it is re-seeded per
716
+ // model), so collaborators never end up on a level the model lacks.
717
+ reasoningEffort: t.Optional(t.Union([t.String(), t.Null()])),
718
+ // Per-tab id of the sender; lets the sender drop its own echo without
719
+ // also dropping the same user's other tabs/devices.
720
+ clientId: t.Optional(t.String())
917
721
  })
918
722
  }, ({ data, conn }) => {
919
723
  requireSessionAccess(conn, data.chatSessionId);
@@ -925,6 +729,7 @@ export const streamHandler = createRouter()
925
729
  provider: data.provider,
926
730
  modelId: data.modelId,
927
731
  modelName: data.modelName,
732
+ reasoningEffort: data.reasoningEffort,
928
733
  senderId: data.senderId
929
734
  });
930
735
 
@@ -932,6 +737,9 @@ export const streamHandler = createRouter()
932
737
  // so refreshes and late joiners get the correct model
933
738
  try {
934
739
  sessionQueries.updateEngineModel(chatSessionId, data.engine, data.provider, data.modelId, data.modelName);
740
+ if (data.reasoningEffort !== undefined) {
741
+ sessionQueries.updateReasoning(chatSessionId, data.reasoningEffort);
742
+ }
935
743
  } catch (err) {
936
744
  debug.error('chat', 'Failed to persist model sync to DB:', err);
937
745
  }
@@ -939,10 +747,13 @@ export const streamHandler = createRouter()
939
747
  // Broadcast to all users in the same chat session
940
748
  ws.emit.chatSession(chatSessionId, 'chat:model-sync', {
941
749
  senderId: data.senderId,
750
+ clientId: data.clientId,
751
+ chatSessionId,
942
752
  engine: data.engine,
943
753
  provider: data.provider,
944
754
  modelId: data.modelId,
945
- modelName: data.modelName
755
+ modelName: data.modelName,
756
+ reasoningEffort: data.reasoningEffort
946
757
  });
947
758
  })
948
759
 
@@ -952,7 +763,8 @@ export const streamHandler = createRouter()
952
763
  senderId: t.String(),
953
764
  chatSessionId: t.String(),
954
765
  accountId: t.Union([t.Number(), t.Null()]),
955
- accountName: t.Optional(t.Union([t.String(), t.Null()]))
766
+ accountName: t.Optional(t.Union([t.String(), t.Null()])),
767
+ clientId: t.Optional(t.String())
956
768
  })
957
769
  }, ({ data, conn }) => {
958
770
  requireSessionAccess(conn, data.chatSessionId);
@@ -974,6 +786,8 @@ export const streamHandler = createRouter()
974
786
  // Broadcast to all users in the same chat session
975
787
  ws.emit.chatSession(chatSessionId, 'chat:account-sync', {
976
788
  senderId: data.senderId,
789
+ clientId: data.clientId,
790
+ chatSessionId,
977
791
  accountId: data.accountId,
978
792
  accountName: data.accountName ?? null
979
793
  });
@@ -986,7 +800,8 @@ export const streamHandler = createRouter()
986
800
  data: t.Object({
987
801
  senderId: t.String(),
988
802
  chatSessionId: t.String(),
989
- reasoningEffort: t.Union([t.String(), t.Null()])
803
+ reasoningEffort: t.Union([t.String(), t.Null()]),
804
+ clientId: t.Optional(t.String())
990
805
  })
991
806
  }, ({ data, conn }) => {
992
807
  requireSessionAccess(conn, data.chatSessionId);
@@ -1002,6 +817,8 @@ export const streamHandler = createRouter()
1002
817
  // Broadcast to all users in the same chat session
1003
818
  ws.emit.chatSession(chatSessionId, 'chat:reasoning-sync', {
1004
819
  senderId: data.senderId,
820
+ clientId: data.clientId,
821
+ chatSessionId,
1005
822
  reasoningEffort: data.reasoningEffort
1006
823
  });
1007
824
  })
@@ -1013,7 +830,8 @@ export const streamHandler = createRouter()
1013
830
  data: t.Object({
1014
831
  senderId: t.String(),
1015
832
  chatSessionId: t.String(),
1016
- profileId: t.Union([t.Number(), t.Null()])
833
+ profileId: t.Union([t.Number(), t.Null()]),
834
+ clientId: t.Optional(t.String())
1017
835
  })
1018
836
  }, ({ data, conn }) => {
1019
837
  requireSessionAccess(conn, data.chatSessionId);
@@ -1024,52 +842,46 @@ export const streamHandler = createRouter()
1024
842
  }
1025
843
  ws.emit.chatSession(data.chatSessionId, 'chat:profile-sync', {
1026
844
  senderId: data.senderId,
845
+ clientId: data.clientId,
846
+ chatSessionId: data.chatSessionId,
1027
847
  profileId: data.profileId
1028
848
  });
1029
849
  })
1030
850
 
1031
851
  // Event declarations
1032
- .emit('chat:edit-mode', t.Object({
1033
- senderId: t.String(),
1034
- isEditing: t.Boolean(),
1035
- messageId: t.Union([t.String(), t.Null()]),
1036
- messageTimestamp: t.Union([t.String(), t.Null()])
1037
- }))
1038
-
1039
- .emit('chat:input-sync', t.Object({
1040
- text: t.String(),
1041
- senderId: t.String(),
1042
- attachments: t.Optional(t.Array(t.Object({
1043
- id: t.String(),
1044
- fileName: t.String(),
1045
- type: t.String(),
1046
- mediaType: t.String(),
1047
- base64: t.String()
1048
- }))),
1049
- chatSessionId: t.Optional(t.String())
1050
- }))
1051
-
852
+ // The *-sync broadcasts carry chatSessionId so a listener can drop events
853
+ // for a session it has just switched away from, and the sender's per-tab
854
+ // clientId so only the sending tab ignores its own echo.
1052
855
  .emit('chat:model-sync', t.Object({
1053
856
  senderId: t.String(),
857
+ clientId: t.Optional(t.String()),
858
+ chatSessionId: t.String(),
1054
859
  engine: t.String(),
1055
860
  provider: t.String(),
1056
861
  modelId: t.String(),
1057
- modelName: t.String()
862
+ modelName: t.String(),
863
+ reasoningEffort: t.Optional(t.Union([t.String(), t.Null()]))
1058
864
  }))
1059
865
 
1060
866
  .emit('chat:account-sync', t.Object({
1061
867
  senderId: t.String(),
868
+ clientId: t.Optional(t.String()),
869
+ chatSessionId: t.String(),
1062
870
  accountId: t.Union([t.Number(), t.Null()]),
1063
871
  accountName: t.Union([t.String(), t.Null()])
1064
872
  }))
1065
873
 
1066
874
  .emit('chat:profile-sync', t.Object({
1067
875
  senderId: t.String(),
876
+ clientId: t.Optional(t.String()),
877
+ chatSessionId: t.String(),
1068
878
  profileId: t.Union([t.Number(), t.Null()])
1069
879
  }))
1070
880
 
1071
881
  .emit('chat:reasoning-sync', t.Object({
1072
882
  senderId: t.String(),
883
+ clientId: t.Optional(t.String()),
884
+ chatSessionId: t.String(),
1073
885
  reasoningEffort: t.Union([t.String(), t.Null()])
1074
886
  }))
1075
887