@myrialabs/clopen 0.3.12 → 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.
Files changed (55) hide show
  1. package/backend/auth/session-invalidation.test.ts +45 -1
  2. package/backend/auth/session-invalidation.ts +35 -1
  3. package/backend/chat/stream-manager.ts +15 -0
  4. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/engine/README.md +16 -1597
  7. package/backend/engine/adapters/claude/message-converter.ts +34 -7
  8. package/backend/engine/adapters/claude/models.ts +174 -2
  9. package/backend/engine/adapters/codex/stream.ts +54 -1
  10. package/backend/engine/adapters/copilot/stream.ts +79 -19
  11. package/backend/engine/adapters/opencode/stream.ts +23 -23
  12. package/backend/engine/adapters/qwen/stream.ts +83 -1
  13. package/backend/engine/docs/adapter-contract.md +183 -0
  14. package/backend/engine/docs/adding-an-engine.md +150 -0
  15. package/backend/engine/docs/database.md +123 -0
  16. package/backend/engine/docs/frontend-and-chat.md +176 -0
  17. package/backend/engine/docs/lessons-learned.md +715 -0
  18. package/backend/engine/docs/quick-reference.md +36 -0
  19. package/backend/engine/docs/system-tools.md +82 -0
  20. package/backend/engine/docs/websocket-routes.md +240 -0
  21. package/backend/engine/structured-helpers.ts +59 -0
  22. package/backend/files/file-archive.test.ts +131 -0
  23. package/backend/files/file-archive.ts +252 -0
  24. package/backend/files/file-operations.ts +39 -66
  25. package/backend/files/file-size-limit.test.ts +71 -15
  26. package/backend/files/file-size-limit.ts +36 -8
  27. package/backend/files/file-watcher.ts +117 -3
  28. package/backend/http/files-upload.ts +168 -0
  29. package/backend/index.ts +8 -0
  30. package/backend/mcp/servers/helper.ts +5 -1
  31. package/backend/projects/project-cleanup.ts +1 -1
  32. package/backend/terminal/pty-session-manager.ts +3 -0
  33. package/backend/terminal/stream-manager.ts +1 -1
  34. package/backend/utils/ws.ts +9 -0
  35. package/backend/ws/auth/users.ts +1 -1
  36. package/backend/ws/chat/stream.ts +46 -38
  37. package/backend/ws/files/path-access.test.ts +166 -0
  38. package/backend/ws/files/path-access.ts +56 -22
  39. package/backend/ws/files/read.ts +5 -5
  40. package/backend/ws/files/watch.ts +48 -19
  41. package/backend/ws/files/write.ts +53 -27
  42. package/backend/ws/git/commit-message.ts +12 -5
  43. package/backend/ws/terminal/session.ts +1 -0
  44. package/dist/assets/main-BqiSLc8F.css +1 -0
  45. package/dist/assets/{main-HIDO3ugS.js → main-C37-Y8f-.js} +230 -229
  46. package/dist/index.html +2 -2
  47. package/package.json +8 -7
  48. package/shared/types/git.ts +4 -2
  49. package/shared/types/stores/settings.ts +2 -0
  50. package/shared/types/unified/index.ts +6 -0
  51. package/shared/types/unified/stream.ts +15 -1
  52. package/shared/types/unified/tool.ts +41 -1
  53. package/shared/utils/ws-server.ts +6 -0
  54. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  55. package/dist/assets/main-C2JiGYnx.css +0 -1
@@ -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
  */
@@ -0,0 +1,168 @@
1
+ /**
2
+ * HTTP upload route for files.
3
+ *
4
+ * The WebSocket-based upload path was wedging on the Vite dev proxy for
5
+ * large transfers — the proxy reports `write EPIPE` and the client request
6
+ * times out. HTTP is purpose-built for streaming large request bodies and
7
+ * the same Vite proxy forwards it cleanly, so we route uploads here.
8
+ *
9
+ * Auth: `Authorization: Bearer <session-token>` (same token issued by
10
+ * `auth:login` and stored in `localStorage` on the frontend).
11
+ *
12
+ * Query: `targetPath`, `fileName`, `fileSize` (decimal bytes).
13
+ *
14
+ * Body: raw file bytes (no multipart wrapping).
15
+ */
16
+
17
+ import { Elysia } from 'elysia';
18
+ import { join } from 'node:path';
19
+ import { mkdir, rename, stat, unlink } from 'node:fs/promises';
20
+
21
+ import { debug } from '$shared/utils/logger';
22
+ import { hashToken } from '../auth/tokens';
23
+ import { authQueries } from '../database/queries';
24
+ import { requireFilePathAccessFor } from '../ws/files/path-access';
25
+ import { validateFileSize } from '../files/file-size-limit';
26
+
27
+ type AuthIdentity = { userId: string; role: string };
28
+
29
+ function authenticate(request: Request): AuthIdentity {
30
+ const header = request.headers.get('authorization') || request.headers.get('Authorization');
31
+ if (!header || !header.toLowerCase().startsWith('bearer ')) {
32
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
33
+ }
34
+ const token = header.slice(7).trim();
35
+ if (!token) {
36
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
37
+ }
38
+ const session = authQueries.getSessionByTokenHash(hashToken(token));
39
+ if (!session) {
40
+ throw Object.assign(new Error('Invalid session token'), { status: 401 });
41
+ }
42
+ if (new Date(session.expires_at) < new Date()) {
43
+ throw Object.assign(new Error('Session expired'), { status: 401 });
44
+ }
45
+ const user = authQueries.getUserById(session.user_id);
46
+ if (!user) {
47
+ throw Object.assign(new Error('User not found'), { status: 401 });
48
+ }
49
+ authQueries.updateLastActive(session.id);
50
+ return { userId: user.id, role: user.role };
51
+ }
52
+
53
+ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query }) => {
54
+ let identity: AuthIdentity;
55
+ try {
56
+ identity = authenticate(request);
57
+ } catch (error) {
58
+ const status = (error as { status?: number }).status ?? 401;
59
+ const message = error instanceof Error ? error.message : 'Unauthorized';
60
+ return new Response(message, { status });
61
+ }
62
+
63
+ const targetPathParam = typeof query.targetPath === 'string' ? query.targetPath : '';
64
+ const fileNameParam = typeof query.fileName === 'string' ? query.fileName : '';
65
+ const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
66
+
67
+ if (!targetPathParam || !fileNameParam) {
68
+ return new Response('Missing required query parameters: targetPath, fileName', { status: 400 });
69
+ }
70
+ if (!Number.isFinite(fileSizeParam) || fileSizeParam < 0) {
71
+ return new Response('Invalid fileSize query parameter', { status: 400 });
72
+ }
73
+
74
+ try {
75
+ validateFileSize(fileSizeParam);
76
+ } catch (error) {
77
+ return new Response(error instanceof Error ? error.message : 'Invalid file size', { status: 413 });
78
+ }
79
+
80
+ let resolvedTarget: string;
81
+ let resolvedFinal: string;
82
+ try {
83
+ resolvedTarget = await requireFilePathAccessFor(targetPathParam, identity.role, identity.userId);
84
+ const tentativeFinal = join(resolvedTarget, fileNameParam);
85
+ resolvedFinal = await requireFilePathAccessFor(tentativeFinal, identity.role, identity.userId);
86
+ } catch (error) {
87
+ const message = error instanceof Error ? error.message : 'Access denied';
88
+ return new Response(message, { status: 403 });
89
+ }
90
+
91
+ try {
92
+ const targetStat = await stat(resolvedTarget).catch(() => null);
93
+ if (!targetStat) {
94
+ await mkdir(resolvedTarget, { recursive: true });
95
+ }
96
+ } catch (error) {
97
+ const message = error instanceof Error ? error.message : 'Failed to prepare target directory';
98
+ return new Response(message, { status: 500 });
99
+ }
100
+
101
+ if (await Bun.file(resolvedFinal).exists()) {
102
+ return new Response('File already exists', { status: 409 });
103
+ }
104
+
105
+ if (!request.body) {
106
+ return new Response('Request body is empty', { status: 400 });
107
+ }
108
+
109
+ const tempPath = `${resolvedFinal}.${crypto.randomUUID()}.partial`;
110
+ const writer = Bun.file(tempPath).writer();
111
+ let written = 0;
112
+
113
+ const cleanupTemp = async () => {
114
+ try { await writer.end(); } catch { /* best-effort */ }
115
+ try { await unlink(tempPath); } catch { /* best-effort */ }
116
+ };
117
+
118
+ try {
119
+ const reader = request.body.getReader();
120
+ while (true) {
121
+ const { done, value } = await reader.read();
122
+ if (done) break;
123
+ if (!value) continue;
124
+ const incoming = value.byteLength;
125
+ if (written + incoming > fileSizeParam) {
126
+ await cleanupTemp();
127
+ return new Response('Received more bytes than declared file size', { status: 400 });
128
+ }
129
+ writer.write(value);
130
+ written += incoming;
131
+ }
132
+
133
+ await writer.end();
134
+
135
+ if (written !== fileSizeParam) {
136
+ await unlink(tempPath).catch(() => {});
137
+ return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
138
+ }
139
+
140
+ try {
141
+ validateFileSize(written);
142
+ } catch (error) {
143
+ await unlink(tempPath).catch(() => {});
144
+ return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
145
+ }
146
+
147
+ // Race-check: refuse to overwrite if the destination appeared mid-upload.
148
+ if (await Bun.file(resolvedFinal).exists()) {
149
+ await unlink(tempPath).catch(() => {});
150
+ return new Response('File already exists', { status: 409 });
151
+ }
152
+
153
+ await rename(tempPath, resolvedFinal);
154
+ const stats = await stat(resolvedFinal);
155
+
156
+ return Response.json({
157
+ message: 'File uploaded successfully',
158
+ path: resolvedFinal,
159
+ size: stats.size,
160
+ modified: stats.mtime.toISOString()
161
+ });
162
+ } catch (error) {
163
+ await cleanupTemp();
164
+ debug.error('file', 'HTTP upload error:', error);
165
+ const message = error instanceof Error ? error.message : 'Upload failed';
166
+ return new Response(message, { status: 500 });
167
+ }
168
+ });
package/backend/index.ts CHANGED
@@ -28,6 +28,10 @@ import { statSync } from 'node:fs';
28
28
  // Import WebSocket router
29
29
  import { wsRouter } from './ws';
30
30
 
31
+ // HTTP upload route — bypasses the Vite WS proxy, which corrupts sustained
32
+ // binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
33
+ import { filesUploadRoute } from './http/files-upload';
34
+
31
35
  // Import browser preview manager for graceful shutdown
32
36
  import { browserPreviewServiceManager } from './preview';
33
37
 
@@ -92,6 +96,10 @@ const app = new Elysia()
92
96
  // Handles GET (SSE stream), POST (JSON-RPC), DELETE (session close)
93
97
  .all('/mcp', async ({ request }) => handleMcpRequest(request))
94
98
 
99
+ // HTTP file upload — mounted before the WS plugin so /api/files/upload
100
+ // stays on the HTTP path through the Vite dev proxy.
101
+ .use(filesUploadRoute)
102
+
95
103
  // Mount WebSocket router (all functionality now via WebSocket)
96
104
  .use(wsRouter.asPlugin('/ws'));
97
105
 
@@ -191,7 +191,11 @@ export function createRemoteMcpServer(
191
191
 
192
192
  mcpServer.registerTool(toolName as string, {
193
193
  description: def.description,
194
- inputSchema: def.schema,
194
+ // MCP SDK 1.29 typed `inputSchema` as `ZodRawShapeCompat` (Record of
195
+ // z3 | z4-core schemas). Our shapes are zod v4 instances whose
196
+ // nominal type doesn't satisfy that union, but they are accepted
197
+ // at runtime. Cast to bridge the mismatch.
198
+ inputSchema: def.schema as Record<string, any>,
195
199
  }, async (args: Record<string, unknown>) => {
196
200
  // Fast-fail when the owning chat stream has already been
197
201
  // cancelled — the handler never runs. Without this, the
@@ -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
 
@@ -13,6 +13,7 @@ export interface PtySession {
13
13
  sessionId: string;
14
14
  pty: IPty;
15
15
  cwd: string;
16
+ userId: string;
16
17
  projectId?: string;
17
18
  createdAt: Date;
18
19
  lastActivityAt: Date;
@@ -39,6 +40,7 @@ class PtySessionManager {
39
40
  async createSession(
40
41
  sessionId: string,
41
42
  cwd: string,
43
+ userId: string,
42
44
  projectId?: string,
43
45
  terminalSize?: { cols: number; rows: number }
44
46
  ): Promise<PtySession> {
@@ -101,6 +103,7 @@ class PtySessionManager {
101
103
  sessionId,
102
104
  pty,
103
105
  cwd,
106
+ userId,
104
107
  projectId,
105
108
  createdAt: new Date(),
106
109
  lastActivityAt: new Date(),
@@ -32,7 +32,7 @@ class TerminalStreamManager {
32
32
  */
33
33
  private createHeadlessTerminal(cols: number, rows: number): { terminal: Terminal; serializeAddon: SerializeAddon } {
34
34
  const terminal = new Terminal({
35
- scrollback: 1000,
35
+ scrollback: 5000,
36
36
  cols,
37
37
  rows,
38
38
  allowProposedApi: true
@@ -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.
@@ -93,7 +93,7 @@ export const usersHandler = createRouter()
93
93
  const actorUserId = ws.getUserId(conn);
94
94
  const removed = unassignProjectFromUser(data.userId, data.projectId);
95
95
  if (removed) {
96
- invalidateUserSessions(data.userId);
96
+ invalidateUserSessions(data.userId, data.projectId);
97
97
  auditLogQueries.logEvent({
98
98
  userId: data.userId,
99
99
  actorUserId,
@@ -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