@myrialabs/clopen 0.3.18 → 0.3.20

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 (44) hide show
  1. package/backend/chat/stream-manager.ts +11 -1
  2. package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
  5. package/backend/database/queries/file-audit-log-queries.ts +184 -0
  6. package/backend/database/queries/index.ts +2 -1
  7. package/backend/db-client/drivers/mongodb.ts +52 -0
  8. package/backend/db-client/drivers/mysql.ts +168 -11
  9. package/backend/db-client/drivers/postgres.ts +182 -19
  10. package/backend/db-client/drivers/redis.ts +27 -0
  11. package/backend/db-client/drivers/sqlite.ts +66 -0
  12. package/backend/db-client/drivers/types.ts +13 -0
  13. package/backend/engine/install-recipes.ts +1 -109
  14. package/backend/http/files-upload.ts +84 -3
  15. package/backend/preview/browser/browser-preview-service.ts +44 -11
  16. package/backend/snapshot/snapshot-service.ts +82 -52
  17. package/backend/tunnel/tunnel-config.ts +76 -209
  18. package/backend/utils/client-ip.test.ts +55 -0
  19. package/backend/utils/client-ip.ts +42 -0
  20. package/backend/utils/ws.ts +6 -3
  21. package/backend/ws/auth/login.test.ts +271 -0
  22. package/backend/ws/auth/login.ts +36 -3
  23. package/backend/ws/auth/users.ts +3 -2
  24. package/backend/ws/db-client/schema.ts +14 -0
  25. package/backend/ws/db-client/structure.ts +120 -0
  26. package/backend/ws/files/path-access.test.ts +60 -1
  27. package/backend/ws/files/path-access.ts +21 -0
  28. package/backend/ws/snapshot/restore.ts +34 -29
  29. package/backend/ws/system-tools/install.ts +0 -1
  30. package/backend/ws/system-tools/status.ts +3 -4
  31. package/backend/ws/tunnel/config.ts +17 -25
  32. package/backend/ws/tunnel/operations.ts +63 -68
  33. package/dist/assets/{main-CaqEjA6B.js → main-72Z_L-nD.js} +224 -223
  34. package/dist/assets/main-ClADBkFf.css +1 -0
  35. package/dist/index.html +2 -2
  36. package/package.json +2 -1
  37. package/shared/types/db-client/query.ts +9 -0
  38. package/shared/utils/ws-client.ts +188 -38
  39. package/backend/tunnel/cloudflared/binary.ts +0 -171
  40. package/backend/tunnel/cloudflared/index.ts +0 -24
  41. package/backend/tunnel/cloudflared/tunnel.ts +0 -444
  42. package/backend/tunnel/global-tunnel-manager.ts +0 -687
  43. package/backend/tunnel/project-tunnel-manager.ts +0 -264
  44. package/dist/assets/main-6cCq8H0w.css +0 -1
@@ -12,6 +12,7 @@ import type {
12
12
  DbClientObjectDetails,
13
13
  DbClientObjectForeignKey,
14
14
  DbClientObjectIndex,
15
+ DbClientOverview,
15
16
  DbClientQueryResult,
16
17
  DbClientSchemaNode,
17
18
  DbClientSchemaNodeType
@@ -151,6 +152,27 @@ export class SqliteAdapter implements DbClientDriverAdapter {
151
152
  return this.executeRead(`EXPLAIN QUERY PLAN ${q}`);
152
153
  }
153
154
 
155
+ // ── Overview ──────────────────────────────────────────────────────────
156
+
157
+ async overview(): Promise<DbClientOverview> {
158
+ const db = this.requireDb();
159
+ const start = performance.now();
160
+ const pageCount = (db.query('PRAGMA page_count').get() as { page_count?: number } | null)?.page_count ?? 0;
161
+ const pageSize = (db.query('PRAGMA page_size').get() as { page_size?: number } | null)?.page_size ?? 0;
162
+ const latencyMs = Math.round(performance.now() - start);
163
+ const counts = db.query(
164
+ "SELECT SUM(type = 'table') AS tables, SUM(type = 'view') AS views FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
165
+ ).get() as { tables: number | null; views: number | null } | null;
166
+ return {
167
+ serverVersion: this.version,
168
+ latencyMs,
169
+ sizeBytes: pageCount * pageSize,
170
+ tableCount: counts?.tables ?? 0,
171
+ viewCount: counts?.views ?? 0,
172
+ extra: [{ label: 'File', value: db.filename || 'main' }]
173
+ };
174
+ }
175
+
154
176
  // ── Schema ────────────────────────────────────────────────────────────
155
177
 
156
178
  async listDatabases(): Promise<DbClientSchemaNode[]> {
@@ -268,6 +290,50 @@ export class SqliteAdapter implements DbClientDriverAdapter {
268
290
  return ddl;
269
291
  }
270
292
 
293
+ async resetTable(name: string): Promise<string> {
294
+ assertSafeIdentifier(name);
295
+ const db = this.requireDb();
296
+ const ddl = `DELETE FROM ${Q(name)}`;
297
+ db.run(ddl);
298
+ // AUTOINCREMENT counters live in sqlite_sequence (absent if unused).
299
+ db.prepare('DELETE FROM sqlite_sequence WHERE name = ?').run(name);
300
+ return `${ddl}; DELETE FROM sqlite_sequence WHERE name = '${name}'`;
301
+ }
302
+
303
+ async resetDatabase(): Promise<string> {
304
+ const db = this.requireDb();
305
+ const rows = db.query(
306
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
307
+ ).all() as Array<{ name: string }>;
308
+ if (rows.length === 0) return '-- no tables to empty';
309
+ rows.forEach((r) => assertSafeIdentifier(r.name));
310
+ const statements = rows.map((r) => `DELETE FROM ${Q(r.name)}`);
311
+ db.transaction(() => {
312
+ for (const stmt of statements) db.run(stmt);
313
+ db.run('DELETE FROM sqlite_sequence');
314
+ })();
315
+ return `${statements.join(';\n')};\nDELETE FROM sqlite_sequence`;
316
+ }
317
+
318
+ async duplicateTable(name: string, newName: string, opts?: { withData?: boolean }): Promise<string> {
319
+ assertSafeIdentifier(name);
320
+ assertSafeIdentifier(newName);
321
+ // SQLite cannot copy constraints via DDL; CREATE … AS SELECT preserves
322
+ // columns and (optionally) rows. Constraints/keys are not carried over.
323
+ const where = opts?.withData ? '' : ' WHERE 0';
324
+ const ddl = `CREATE TABLE ${Q(newName)} AS SELECT * FROM ${Q(name)}${where}`;
325
+ this.requireDb().run(ddl);
326
+ return ddl;
327
+ }
328
+
329
+ async getCreateStatement(name: string): Promise<string> {
330
+ assertSafeIdentifier(name);
331
+ const row = this.requireDb()
332
+ .prepare("SELECT sql FROM sqlite_master WHERE name = ? AND sql IS NOT NULL")
333
+ .get(name) as { sql: string } | null;
334
+ return row?.sql ? `${row.sql};` : '';
335
+ }
336
+
271
337
  async renameTable(name: string, newName: string): Promise<string> {
272
338
  assertSafeIdentifier(name);
273
339
  assertSafeIdentifier(newName);
@@ -11,6 +11,7 @@ import type {
11
11
  DbClientConnection,
12
12
  DbClientHealth,
13
13
  DbClientObjectDetails,
14
+ DbClientOverview,
14
15
  DbClientQueryResult,
15
16
  DbClientSchemaNode,
16
17
  DbClientSchemaNodeType,
@@ -58,6 +59,7 @@ export interface DbClientDriverAdapter {
58
59
  isAlive(): boolean;
59
60
  health(): Promise<DbClientHealth>;
60
61
 
62
+ overview?(opts?: SchemaOpts): Promise<DbClientOverview>;
61
63
  listDatabases?(): Promise<DbClientSchemaNode[]>;
62
64
  listSchemas?(database?: string): Promise<DbClientSchemaNode[]>;
63
65
  listObjects?(database?: string, schema?: string): Promise<DbClientSchemaNode[]>;
@@ -75,11 +77,22 @@ export interface DbClientDriverAdapter {
75
77
 
76
78
  // Structure
77
79
  createDatabase?(name: string): Promise<string>;
80
+ dropDatabase?(name: string): Promise<string>;
81
+ renameDatabase?(name: string, newName: string): Promise<string>;
82
+ /** Empty every table/collection in a database without dropping the schema. */
83
+ resetDatabase?(opts?: SchemaOpts): Promise<string>;
84
+ /** Redis FLUSHDB — wipe every key in the selected logical database. */
85
+ flushDatabase?(): Promise<string>;
78
86
  createTable?(definition: TableDefinition, opts?: SchemaOpts): Promise<string>;
79
87
  alterTable?(name: string, operations: AlterOperation[], opts?: SchemaOpts): Promise<string>;
80
88
  dropTable?(name: string, opts?: SchemaOpts): Promise<string>;
81
89
  truncateTable?(name: string, opts?: SchemaOpts): Promise<string>;
90
+ /** Truncate and reset the auto-increment / sequence / identity counter. */
91
+ resetTable?(name: string, opts?: SchemaOpts): Promise<string>;
82
92
  renameTable?(name: string, newName: string, opts?: SchemaOpts): Promise<string>;
93
+ duplicateTable?(name: string, newName: string, opts?: SchemaOpts & { withData?: boolean }): Promise<string>;
94
+ /** Best-effort CREATE statement for an object (DDL), for copy-to-clipboard. */
95
+ getCreateStatement?(name: string, type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string>;
83
96
  createIndex?(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string>;
84
97
  dropIndex?(tableName: string, indexName: string, opts?: SchemaOpts): Promise<string>;
85
98
  createView?(name: string, query: string, opts?: SchemaOpts): Promise<string>;
@@ -20,7 +20,7 @@ import { getClopenDir } from '$backend/utils/paths';
20
20
  import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
21
21
  import { resolveStaticCurlAsset } from '$backend/utils/static-curl';
22
22
 
23
- export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome' | 'cloudflared';
23
+ export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome';
24
24
 
25
25
  export interface ManualInstruction {
26
26
  label: string;
@@ -205,15 +205,6 @@ export async function getToolStatus(tool: ToolId): Promise<ToolStatus> {
205
205
  const version = await runVersion(resolved);
206
206
  if (!version) return { tool, installed: false, version: null, source: null };
207
207
 
208
- // Cloudflared: tag binaries under ~/.clopen/bin as "clopen"-managed so the
209
- // UI distinguishes System Tools installs from system-wide ones.
210
- if (tool === 'cloudflared') {
211
- const clopenBinDir = join(getClopenDir(), 'bin');
212
- if (resolved.startsWith(clopenBinDir)) {
213
- return { tool, installed: true, version, source: 'clopen' };
214
- }
215
- }
216
-
217
208
  return { tool, installed: true, version, source: resolved };
218
209
  }
219
210
 
@@ -628,104 +619,6 @@ function pickLinuxChromeStrategy(
628
619
  return null;
629
620
  }
630
621
 
631
- // ─────────────────────────────────────────────────────────────────────────────
632
- // Cloudflared recipe — downloads the Cloudflare-signed binary into ~/.clopen/bin
633
- // ─────────────────────────────────────────────────────────────────────────────
634
-
635
- const CLOUDFLARED_RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/latest/download';
636
- const CLOUDFLARED_DOCS = 'https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/';
637
-
638
- const CLOUDFLARED_LINUX_ARCH: Record<string, string> = {
639
- x64: 'amd64',
640
- arm64: 'arm64',
641
- arm: 'arm',
642
- ia32: '386'
643
- };
644
-
645
- async function resolveCloudflaredRecipe(): Promise<Recipe> {
646
- const base: Recipe = {
647
- tool: 'cloudflared',
648
- autoInstallable: false,
649
- missingPrereqs: [],
650
- manualInstructions: []
651
- };
652
-
653
- const binDir = join(getClopenDir(), 'bin');
654
-
655
- if (process.platform === 'darwin') {
656
- const archKey = process.arch === 'arm64' ? 'arm64' : 'amd64';
657
- const file = `cloudflared-darwin-${archKey}.tgz`;
658
- const url = `${CLOUDFLARED_RELEASE_BASE}/${file}`;
659
- const cmd =
660
- `mkdir -p "${binDir}" && ` +
661
- `curl -fsSL -o "${binDir}/${file}" "${url}" && ` +
662
- `tar -xzf "${binDir}/${file}" -C "${binDir}" && ` +
663
- `rm -f "${binDir}/${file}" && ` +
664
- `chmod +x "${binDir}/cloudflared"`;
665
-
666
- base.manualInstructions.push({
667
- label: 'curl + tar',
668
- command: cmd,
669
- docs: CLOUDFLARED_DOCS
670
- });
671
- if (!attachCurlRequirement(base, 'Cloudflared')) return base;
672
- base.autoInstallable = true;
673
- base.shell = { program: 'bash', args: ['-c'] };
674
- base.command = [cmd];
675
- base.displayCommand = cmd;
676
- return base;
677
- }
678
-
679
- if (process.platform === 'linux') {
680
- const archKey = CLOUDFLARED_LINUX_ARCH[process.arch];
681
- if (!archKey) {
682
- base.unavailableReason = `Cloudflared has no published Linux build for ${process.arch}.`;
683
- return base;
684
- }
685
- const file = `cloudflared-linux-${archKey}`;
686
- const url = `${CLOUDFLARED_RELEASE_BASE}/${file}`;
687
- const cmd =
688
- `mkdir -p "${binDir}" && ` +
689
- `curl -fsSL -o "${binDir}/cloudflared" "${url}" && ` +
690
- `chmod +x "${binDir}/cloudflared"`;
691
-
692
- base.manualInstructions.push({
693
- label: 'curl',
694
- command: cmd,
695
- docs: CLOUDFLARED_DOCS
696
- });
697
- if (!attachCurlRequirement(base, 'Cloudflared')) return base;
698
- base.autoInstallable = true;
699
- base.shell = { program: 'bash', args: ['-c'] };
700
- base.command = [cmd];
701
- base.displayCommand = cmd;
702
- return base;
703
- }
704
-
705
- if (process.platform === 'win32') {
706
- const archKey = process.arch === 'ia32' ? '386' : 'amd64';
707
- const file = `cloudflared-windows-${archKey}.exe`;
708
- const url = `${CLOUDFLARED_RELEASE_BASE}/${file}`;
709
- const psCmd =
710
- `New-Item -ItemType Directory -Path "${binDir}" -Force | Out-Null; ` +
711
- `Invoke-WebRequest -Uri "${url}" -OutFile "${binDir}\\cloudflared.exe"`;
712
-
713
- base.manualInstructions.push({
714
- label: 'PowerShell',
715
- command: psCmd,
716
- docs: CLOUDFLARED_DOCS
717
- });
718
- base.autoInstallable = true;
719
- base.shell = { program: 'powershell.exe', args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command'] };
720
- base.command = [psCmd];
721
- base.displayCommand = psCmd;
722
- return base;
723
- }
724
-
725
- base.unavailableReason = `Unsupported platform: ${process.platform}`;
726
- return base;
727
- }
728
-
729
622
  /**
730
623
  * Resolve the install recipe for a tool on the current platform.
731
624
  * Result is platform- and privilege-aware: recipes that would fail
@@ -740,6 +633,5 @@ export async function resolveRecipe(tool: ToolId): Promise<Recipe> {
740
633
  case 'codex': return resolveCodexRecipe();
741
634
  case 'qwen': return resolveQwenRecipe();
742
635
  case 'chrome': return resolveChromeRecipe();
743
- case 'cloudflared': return resolveCloudflaredRecipe();
744
636
  }
745
637
  }
@@ -20,8 +20,9 @@ import { mkdir, rename, stat, unlink } from 'node:fs/promises';
20
20
 
21
21
  import { debug } from '$shared/utils/logger';
22
22
  import { hashToken } from '../auth/tokens';
23
- import { authQueries } from '../database/queries';
24
- import { requireFilePathAccessFor } from '../ws/files/path-access';
23
+ import { authQueries, fileAuditLogQueries } from '../database/queries';
24
+ import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
25
+ import { clientIpFromRequest } from '../utils/client-ip';
25
26
  import { validateFileSize } from '../files/file-size-limit';
26
27
 
27
28
  type AuthIdentity = { userId: string; role: string };
@@ -50,7 +51,7 @@ function authenticate(request: Request): AuthIdentity {
50
51
  return { userId: user.id, role: user.role };
51
52
  }
52
53
 
53
- export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query }) => {
54
+ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query, server }) => {
54
55
  let identity: AuthIdentity;
55
56
  try {
56
57
  identity = authenticate(request);
@@ -71,9 +72,24 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
71
72
  return new Response('Invalid fileSize query parameter', { status: 400 });
72
73
  }
73
74
 
75
+ const ipAddress = clientIpFromRequest(request, server);
76
+ const userAgent = request.headers.get('user-agent') ?? undefined;
77
+ const projectId = await findContainingProjectId(`${targetPathParam}/${fileNameParam}`);
78
+
74
79
  try {
75
80
  validateFileSize(fileSizeParam);
76
81
  } catch (error) {
82
+ fileAuditLogQueries.logOperation({
83
+ userId: identity.userId,
84
+ projectId,
85
+ action: 'upload',
86
+ filePath: `${targetPathParam}/${fileNameParam}`,
87
+ fileSize: fileSizeParam,
88
+ ipAddress,
89
+ userAgent,
90
+ success: false,
91
+ errorMessage: 'File too large'
92
+ });
77
93
  return new Response(error instanceof Error ? error.message : 'Invalid file size', { status: 413 });
78
94
  }
79
95
 
@@ -85,6 +101,17 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
85
101
  resolvedFinal = await requireFilePathAccessFor(tentativeFinal, identity.role, identity.userId);
86
102
  } catch (error) {
87
103
  const message = error instanceof Error ? error.message : 'Access denied';
104
+ fileAuditLogQueries.logOperation({
105
+ userId: identity.userId,
106
+ projectId,
107
+ action: 'upload',
108
+ filePath: `${targetPathParam}/${fileNameParam}`,
109
+ fileSize: fileSizeParam,
110
+ ipAddress,
111
+ userAgent,
112
+ success: false,
113
+ errorMessage: 'Path access denied'
114
+ });
88
115
  return new Response(message, { status: 403 });
89
116
  }
90
117
 
@@ -99,6 +126,17 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
99
126
  }
100
127
 
101
128
  if (await Bun.file(resolvedFinal).exists()) {
129
+ fileAuditLogQueries.logOperation({
130
+ userId: identity.userId,
131
+ projectId,
132
+ action: 'upload',
133
+ filePath: resolvedFinal,
134
+ fileSize: fileSizeParam,
135
+ ipAddress,
136
+ userAgent,
137
+ success: false,
138
+ errorMessage: 'File already exists'
139
+ });
102
140
  return new Response('File already exists', { status: 409 });
103
141
  }
104
142
 
@@ -141,18 +179,50 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
141
179
  validateFileSize(written);
142
180
  } catch (error) {
143
181
  await unlink(tempPath).catch(() => {});
182
+ fileAuditLogQueries.logOperation({
183
+ userId: identity.userId,
184
+ projectId,
185
+ action: 'upload',
186
+ filePath: resolvedFinal,
187
+ fileSize: written,
188
+ ipAddress,
189
+ userAgent,
190
+ success: false,
191
+ errorMessage: 'File too large'
192
+ });
144
193
  return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
145
194
  }
146
195
 
147
196
  // Race-check: refuse to overwrite if the destination appeared mid-upload.
148
197
  if (await Bun.file(resolvedFinal).exists()) {
149
198
  await unlink(tempPath).catch(() => {});
199
+ fileAuditLogQueries.logOperation({
200
+ userId: identity.userId,
201
+ projectId,
202
+ action: 'upload',
203
+ filePath: resolvedFinal,
204
+ fileSize: written,
205
+ ipAddress,
206
+ userAgent,
207
+ success: false,
208
+ errorMessage: 'File already exists (race condition)'
209
+ });
150
210
  return new Response('File already exists', { status: 409 });
151
211
  }
152
212
 
153
213
  await rename(tempPath, resolvedFinal);
154
214
  const stats = await stat(resolvedFinal);
155
215
 
216
+ fileAuditLogQueries.logOperation({
217
+ userId: identity.userId,
218
+ projectId,
219
+ action: 'upload',
220
+ filePath: resolvedFinal,
221
+ fileSize: stats.size,
222
+ ipAddress,
223
+ userAgent
224
+ });
225
+
156
226
  return Response.json({
157
227
  message: 'File uploaded successfully',
158
228
  path: resolvedFinal,
@@ -163,6 +233,17 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
163
233
  await cleanupTemp();
164
234
  debug.error('file', 'HTTP upload error:', error);
165
235
  const message = error instanceof Error ? error.message : 'Upload failed';
236
+ fileAuditLogQueries.logOperation({
237
+ userId: identity.userId,
238
+ projectId,
239
+ action: 'upload',
240
+ filePath: resolvedFinal,
241
+ fileSize: written,
242
+ ipAddress,
243
+ userAgent,
244
+ success: false,
245
+ errorMessage: message
246
+ });
166
247
  return new Response(message, { status: 500 });
167
248
  }
168
249
  });
@@ -610,6 +610,10 @@ export class BrowserPreviewService extends EventEmitter {
610
610
  class BrowserPreviewServiceManager {
611
611
  private services = new Map<string, BrowserPreviewService>();
612
612
 
613
+ // Whether the singleton browserMcpControl listeners have been registered.
614
+ // Guards against re-registering (and leaking) listeners on the shared emitter.
615
+ private mcpForwardingSetup = false;
616
+
613
617
  /**
614
618
  * Get or create a BrowserPreviewService for a project
615
619
  */
@@ -618,6 +622,9 @@ class BrowserPreviewServiceManager {
618
622
  throw new Error('projectId is required and cannot be empty');
619
623
  }
620
624
 
625
+ // Register singleton MCP control forwarding once (idempotent).
626
+ this.setupMcpControlForwarding();
627
+
621
628
  if (!this.services.has(projectId)) {
622
629
  debug.log('preview', `🆕 Creating new BrowserPreviewService for project: ${projectId}`);
623
630
  const service = new BrowserPreviewService(projectId);
@@ -755,10 +762,39 @@ class BrowserPreviewServiceManager {
755
762
  ws.emit.project(projectId, 'preview:browser-new-window', data);
756
763
  });
757
764
 
758
- // Forward MCP control events (from singleton browserMcpControl)
765
+ // MCP control events come from the singleton browserMcpControl, so their
766
+ // listeners are registered once globally (see setupMcpControlForwarding) —
767
+ // NOT here, which runs per-project and would leak listeners onto the
768
+ // singleton as projects are opened.
769
+
770
+ debug.log('preview', `🎉 All WebSocket event listeners registered for project: ${projectId}`);
771
+ }
772
+
773
+ /**
774
+ * Setup WebSocket forwarding for the singleton browserMcpControl.
775
+ *
776
+ * Registered exactly once for the whole manager. The emitter is a singleton
777
+ * shared across all projects, so attaching these listeners per-project would
778
+ * accumulate them without bound (MaxListenersExceededWarning). MCP control
779
+ * events are not project-scoped at the source, so we broadcast them to every
780
+ * currently-active project; the frontend filters by tab/session.
781
+ */
782
+ private setupMcpControlForwarding(): void {
783
+ if (this.mcpForwardingSetup) return;
784
+ this.mcpForwardingSetup = true;
785
+
786
+ const emitToActiveProjects = <K extends Parameters<typeof ws.emit.project>[1]>(
787
+ event: K,
788
+ payload: Parameters<typeof ws.emit.project<K>>[2]
789
+ ) => {
790
+ for (const projectId of this.services.keys()) {
791
+ ws.emit.project(projectId, event, payload);
792
+ }
793
+ };
794
+
759
795
  browserMcpControl.on('control-start', (data) => {
760
- debug.log('preview', `🚀 Forwarding mcp-control-start to project ${projectId}:`, data);
761
- ws.emit.project(projectId, 'preview:browser-mcp-control-start', {
796
+ debug.log('preview', '🚀 Forwarding mcp-control-start:', data);
797
+ emitToActiveProjects('preview:browser-mcp-control-start', {
762
798
  browserTabId: data.browserTabId,
763
799
  chatSessionId: data.chatSessionId,
764
800
  timestamp: data.timestamp
@@ -766,16 +802,15 @@ class BrowserPreviewServiceManager {
766
802
  });
767
803
 
768
804
  browserMcpControl.on('control-end', (data) => {
769
- debug.log('preview', `🚀 Forwarding mcp-control-end to project ${projectId}:`, data);
770
- ws.emit.project(projectId, 'preview:browser-mcp-control-end', {
805
+ debug.log('preview', '🚀 Forwarding mcp-control-end:', data);
806
+ emitToActiveProjects('preview:browser-mcp-control-end', {
771
807
  browserTabId: data.browserTabId,
772
808
  timestamp: data.timestamp
773
809
  });
774
810
  });
775
811
 
776
- // Forward MCP cursor events
777
812
  browserMcpControl.on('cursor-position', (data) => {
778
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-position', {
813
+ emitToActiveProjects('preview:browser-mcp-cursor-position', {
779
814
  sessionId: data.tabId,
780
815
  x: data.x,
781
816
  y: data.y,
@@ -785,7 +820,7 @@ class BrowserPreviewServiceManager {
785
820
  });
786
821
 
787
822
  browserMcpControl.on('cursor-click', (data) => {
788
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-click', {
823
+ emitToActiveProjects('preview:browser-mcp-cursor-click', {
789
824
  sessionId: data.tabId,
790
825
  x: data.x,
791
826
  y: data.y,
@@ -795,14 +830,12 @@ class BrowserPreviewServiceManager {
795
830
  });
796
831
 
797
832
  browserMcpControl.on('test-completed', (data) => {
798
- ws.emit.project(projectId, 'preview:browser-mcp-test-completed', {
833
+ emitToActiveProjects('preview:browser-mcp-test-completed', {
799
834
  sessionId: data.tabId,
800
835
  timestamp: data.timestamp,
801
836
  source: 'mcp'
802
837
  });
803
838
  });
804
-
805
- debug.log('preview', `🎉 All WebSocket event listeners registered for project: ${projectId}`);
806
839
  }
807
840
 
808
841
  /**