@myrialabs/clopen 0.4.20 → 0.4.22

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 (116) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/bootstrap.ts +39 -0
  5. package/backend/chat/stream-manager.ts +15 -0
  6. package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/session-queries.ts +10 -0
  9. package/backend/engine/README.md +11 -8
  10. package/backend/engine/adapters/claude/models.ts +46 -23
  11. package/backend/engine/adapters/claude/stream.ts +18 -4
  12. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  13. package/backend/engine/adapters/codex/models.ts +19 -2
  14. package/backend/engine/adapters/codex/stream.ts +10 -3
  15. package/backend/engine/adapters/copilot/models.ts +20 -1
  16. package/backend/engine/adapters/copilot/stream.ts +11 -1
  17. package/backend/engine/adapters/cursor/models.ts +27 -3
  18. package/backend/engine/adapters/cursor/stream.ts +23 -3
  19. package/backend/engine/adapters/pi/models.ts +20 -2
  20. package/backend/engine/adapters/pi/stream.ts +6 -3
  21. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  22. package/backend/engine/bootstrap-default-engine.ts +18 -5
  23. package/backend/engine/docs/adapter-contract.md +66 -2
  24. package/backend/engine/docs/adding-an-engine.md +46 -7
  25. package/backend/engine/docs/frontend-and-chat.md +80 -17
  26. package/backend/engine/docs/lessons-learned.md +126 -7
  27. package/backend/engine/docs/quick-reference.md +12 -3
  28. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  29. package/backend/engine/docs/websocket-routes.md +54 -15
  30. package/backend/engine/install-runner.ts +4 -4
  31. package/backend/engine/resolve-model.ts +87 -0
  32. package/backend/engine/structured-helpers.test.ts +64 -0
  33. package/backend/engine/structured-helpers.ts +105 -13
  34. package/backend/engine/types.ts +6 -0
  35. package/backend/index.ts +6 -9
  36. package/backend/mcp/README.md +32 -11
  37. package/backend/mcp/internal/config.ts +3 -20
  38. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  39. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  40. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  41. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  42. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  43. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  44. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  45. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  46. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  47. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  48. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  49. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  50. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  51. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  52. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  53. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  54. package/backend/preview/browser/browser-console-manager.ts +310 -156
  55. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  56. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  57. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  58. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  59. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  60. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  61. package/backend/preview/browser/browser-pool.ts +83 -9
  62. package/backend/preview/browser/browser-preview-service.ts +432 -53
  63. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  64. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  65. package/backend/preview/browser/capture-profile.ts +213 -0
  66. package/backend/preview/browser/element-locator.ts +357 -0
  67. package/backend/preview/browser/frame-targeting.ts +92 -0
  68. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  69. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  70. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  71. package/backend/preview/browser/types.ts +397 -37
  72. package/backend/utils/cli.ts +1 -1
  73. package/backend/utils/path-enrich.ts +2 -2
  74. package/backend/ws/README.md +1 -1
  75. package/backend/ws/artifacts/generate.ts +2 -1
  76. package/backend/ws/chat/stream.ts +38 -2
  77. package/backend/ws/engine/codex/accounts.ts +1 -1
  78. package/backend/ws/engine/codex/status.ts +1 -1
  79. package/backend/ws/git/branch-name.ts +11 -5
  80. package/backend/ws/git/commit-message.ts +11 -5
  81. package/backend/ws/index.ts +3 -3
  82. package/backend/ws/preview/browser/host.ts +95 -0
  83. package/backend/ws/preview/browser/interact.ts +204 -10
  84. package/backend/ws/preview/browser/native-ui.ts +31 -1
  85. package/backend/ws/preview/browser/tab-info.ts +10 -1
  86. package/backend/ws/preview/browser/tab.ts +43 -0
  87. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  88. package/backend/ws/preview/index.ts +58 -1
  89. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  90. package/backend/ws/stack/index.ts +16 -0
  91. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  92. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  93. package/backend/ws/system/device-info.ts +290 -0
  94. package/backend/ws/system/index.ts +2 -0
  95. package/backend/ws/system/operations.ts +7 -0
  96. package/backend/ws/user/crud.ts +6 -3
  97. package/dist/assets/{index-BqBxKeAv.js → index-DH_GO0Lf.js} +1 -1
  98. package/dist/assets/{index-DdrcY5TE.js → index-igSQ3JaM.js} +1 -1
  99. package/dist/assets/main-BD3-qPfT.css +1 -0
  100. package/dist/assets/main-D-d8SFfW.js +616 -0
  101. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +2 -1
  104. package/shared/constants/engines.ts +23 -0
  105. package/shared/types/database/schema.ts +1 -0
  106. package/shared/types/stores/settings.ts +12 -0
  107. package/shared/types/unified/engine.ts +33 -0
  108. package/shared/types/unified/index.ts +2 -0
  109. package/shared/types/unified/message.ts +6 -0
  110. package/shared/types/unified/stream.ts +6 -0
  111. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  112. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  113. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  114. package/backend/ws/system-tools/index.ts +0 -16
  115. package/dist/assets/main-BBxAj17T.js +0 -582
  116. package/dist/assets/main-Cry3pLcl.css +0 -1
@@ -1,88 +1,259 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import type { Page, ConsoleMessage as PuppeteerConsoleMessage, HTTPResponse } from 'puppeteer';
3
- import type { BrowserConsoleMessage, BrowserTab } from './types';
3
+ import type { BrowserConsoleMessage, BrowserConsoleValue, BrowserTab } from './types';
4
4
 
5
5
  import { debug } from '$shared/utils/logger';
6
+
7
+ /** Ring-buffer bounds for a tab's console history. */
8
+ const MAX_LOGS = 1000;
9
+ const TRIM_TO = 500;
10
+
11
+ /**
12
+ * Flatten a page value into something renderable.
13
+ *
14
+ * Runs inside the page (serialized by `JSHandle.evaluate`), so it has to be
15
+ * self-contained. Depth and breadth are capped because a single logged object
16
+ * graph can otherwise be unbounded, and the panel only ever shows two levels
17
+ * before the user expands further.
18
+ */
19
+ function serializeConsoleValue(value: unknown, maxDepth = 2, maxEntries = 100): BrowserConsoleValue {
20
+ const seen = new WeakSet<object>();
21
+
22
+ function shortString(text: string, limit = 200): string {
23
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
24
+ }
25
+
26
+ function walk(input: unknown, depth: number): BrowserConsoleValue {
27
+ if (input === null) return { type: 'null', preview: 'null' };
28
+
29
+ const raw = typeof input;
30
+
31
+ if (raw === 'undefined') return { type: 'undefined', preview: 'undefined' };
32
+ if (raw === 'string') return { type: 'string', preview: shortString(input as string, 1000) };
33
+ if (raw === 'number') return { type: 'number', preview: String(input) };
34
+ if (raw === 'boolean') return { type: 'boolean', preview: String(input) };
35
+ if (raw === 'bigint') return { type: 'bigint', preview: `${String(input)}n` };
36
+ if (raw === 'symbol') return { type: 'symbol', preview: String(input) };
37
+ if (raw === 'function') {
38
+ const fn = input as { name?: string };
39
+ return { type: 'function', preview: `ƒ ${fn.name || '(anonymous)'}()` };
40
+ }
41
+
42
+ const obj = input as object;
43
+ if (seen.has(obj)) return { type: 'object', preview: '[Circular]' };
44
+ seen.add(obj);
45
+
46
+ if (obj instanceof Error) {
47
+ return { type: 'error', preview: obj.stack || `${obj.name}: ${obj.message}` };
48
+ }
49
+ if (typeof Node !== 'undefined' && obj instanceof Node) {
50
+ const el = obj as Element;
51
+ if (el.tagName) {
52
+ const attrs = el.id ? `#${el.id}` : el.className ? `.${String(el.className).split(/\s+/)[0]}` : '';
53
+ return { type: 'node', preview: `<${el.tagName.toLowerCase()}${attrs}>` };
54
+ }
55
+ return { type: 'node', preview: obj.nodeName };
56
+ }
57
+ if (obj instanceof Date) return { type: 'date', preview: obj.toISOString() };
58
+ if (obj instanceof RegExp) return { type: 'regexp', preview: String(obj) };
59
+
60
+ if (obj instanceof Map || obj instanceof Set) {
61
+ const isMap = obj instanceof Map;
62
+ const size = obj.size;
63
+ const result: BrowserConsoleValue = {
64
+ type: isMap ? 'map' : 'set',
65
+ preview: `${isMap ? 'Map' : 'Set'}(${size})`
66
+ };
67
+ if (depth < maxDepth) {
68
+ const entries: BrowserConsoleValue['entries'] = [];
69
+ let index = 0;
70
+ for (const item of obj as Iterable<unknown>) {
71
+ if (index >= maxEntries) {
72
+ result.truncated = true;
73
+ break;
74
+ }
75
+ if (isMap) {
76
+ const [key, val] = item as [unknown, unknown];
77
+ entries.push({ key: String(key), value: walk(val, depth + 1) });
78
+ } else {
79
+ entries.push({ key: String(index), value: walk(item, depth + 1) });
80
+ }
81
+ index += 1;
82
+ }
83
+ result.entries = entries;
84
+ }
85
+ return result;
86
+ }
87
+
88
+ if (Array.isArray(obj)) {
89
+ const result: BrowserConsoleValue = { type: 'array', preview: `Array(${obj.length})` };
90
+ if (depth < maxDepth) {
91
+ const limit = Math.min(obj.length, maxEntries);
92
+ result.entries = [];
93
+ for (let i = 0; i < limit; i += 1) {
94
+ result.entries.push({ key: String(i), value: walk(obj[i], depth + 1) });
95
+ }
96
+ result.truncated = obj.length > limit;
97
+ }
98
+ return result;
99
+ }
100
+
101
+ const ctor = (obj as { constructor?: { name?: string } }).constructor?.name;
102
+ const label = ctor && ctor !== 'Object' ? ctor : 'Object';
103
+ const result: BrowserConsoleValue = { type: 'object', preview: label };
104
+
105
+ if (depth < maxDepth) {
106
+ let keys: string[] = [];
107
+ try {
108
+ keys = Object.keys(obj);
109
+ } catch {
110
+ keys = [];
111
+ }
112
+ const limit = Math.min(keys.length, maxEntries);
113
+ result.entries = [];
114
+ for (let i = 0; i < limit; i += 1) {
115
+ const key = keys[i];
116
+ try {
117
+ result.entries.push({ key, value: walk((obj as Record<string, unknown>)[key], depth + 1) });
118
+ } catch {
119
+ result.entries.push({ key, value: { type: 'object', preview: '[unreadable]' } });
120
+ }
121
+ }
122
+ result.truncated = keys.length > limit;
123
+ if (keys.length > 0 && label === 'Object') {
124
+ result.preview = `{${keys.slice(0, 3).join(', ')}${keys.length > 3 ? ', …' : ''}}`;
125
+ }
126
+ }
127
+
128
+ return result;
129
+ }
130
+
131
+ return walk(value, 0);
132
+ }
133
+
134
+ /**
135
+ * Collapse Chrome's console levels onto the four the panel filters by.
136
+ *
137
+ * Puppeteer reports every variant `console.*` can produce (`dir`, `table`,
138
+ * `assert`, `count`, `verbose`, group markers…); left unmapped these fall
139
+ * outside every filter and the message becomes invisible.
140
+ */
141
+ function normalizeConsoleType(type: string): BrowserConsoleMessage['type'] {
142
+ switch (type) {
143
+ case 'error':
144
+ case 'assert':
145
+ return 'error';
146
+ case 'warn':
147
+ return 'warn';
148
+ case 'info':
149
+ return 'info';
150
+ case 'debug':
151
+ case 'verbose':
152
+ return 'debug';
153
+ case 'trace':
154
+ return 'trace';
155
+ case 'clear':
156
+ return 'clear';
157
+ default:
158
+ return 'log';
159
+ }
160
+ }
161
+
6
162
  export class BrowserConsoleManager extends EventEmitter {
7
163
  constructor() {
8
164
  super();
9
165
  }
10
166
 
11
- async setupConsoleLogging(sessionId: string, page: Page, session: BrowserTab) {
167
+ /**
168
+ * Append a message to the tab's buffer, collapsing an identical repeat into
169
+ * a counter the way DevTools does — a page logging inside a rAF loop would
170
+ * otherwise flood the panel and evict everything useful.
171
+ */
172
+ private record(session: BrowserTab, message: BrowserConsoleMessage): void {
173
+ const previous = session.consoleLogs[session.consoleLogs.length - 1];
174
+
175
+ if (
176
+ previous &&
177
+ previous.type === message.type &&
178
+ previous.text === message.text &&
179
+ previous.location?.url === message.location?.url &&
180
+ previous.location?.lineNumber === message.location?.lineNumber
181
+ ) {
182
+ previous.count = (previous.count ?? 1) + 1;
183
+ previous.timestamp = message.timestamp;
184
+ this.emit('console-message', { sessionId: session.id, message: previous });
185
+ return;
186
+ }
187
+
188
+ session.consoleLogs.push(message);
189
+ if (session.consoleLogs.length > MAX_LOGS) {
190
+ session.consoleLogs = session.consoleLogs.slice(-TRIM_TO);
191
+ }
192
+
193
+ this.emit('console-message', { sessionId: session.id, message });
194
+ }
12
195
 
196
+ private static makeId(prefix: string): string {
197
+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
198
+ }
199
+
200
+ async setupConsoleLogging(sessionId: string, page: Page, session: BrowserTab) {
13
201
  // Clear any existing console logs for this session
14
202
  session.consoleLogs = [];
15
203
 
16
204
  // Listen to ALL console events from the page
17
205
  page.on('console', async (consoleMessage: PuppeteerConsoleMessage) => {
18
- // Always log to server console for debugging
19
206
  if (!session.consoleEnabled) {
20
207
  return;
21
208
  }
22
209
 
23
210
  try {
24
- const messageId = `console-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
25
211
  const text = consoleMessage.text();
26
- const type = consoleMessage.type() as BrowserConsoleMessage['type'];
212
+ const type = normalizeConsoleType(consoleMessage.type());
27
213
 
28
214
  // Get location information (Puppeteer uses location() method)
29
215
  const location = consoleMessage.location();
30
- const messageLocation = location ? {
31
- url: location.url || '',
32
- lineNumber: location.lineNumber || 0,
33
- columnNumber: location.columnNumber || 0
34
- } : undefined;
35
-
36
- // Extract arguments with improved error handling
37
- let args: any[] = [];
216
+ const messageLocation = location
217
+ ? {
218
+ url: location.url || '',
219
+ lineNumber: location.lineNumber || 0,
220
+ columnNumber: location.columnNumber || 0
221
+ }
222
+ : undefined;
223
+
224
+ // Structured argument previews. Serializing in the page keeps DOM
225
+ // nodes, class instances and circular graphs renderable — all of
226
+ // which make `jsonValue()` throw and used to be dropped entirely.
227
+ let values: BrowserConsoleValue[] = [];
38
228
  try {
39
- const messageArgs = consoleMessage.args();
40
- if (messageArgs && messageArgs.length > 0) {
41
- args = await Promise.all(
42
- messageArgs.map(async (arg) => {
43
- try {
44
- // Try to get JSON value first
45
- const jsonValue = await arg.jsonValue();
46
- return jsonValue;
47
- } catch {
48
- try {
49
- // Fallback to string representation
50
- return arg.toString();
51
- } catch {
52
- // Final fallback
53
- return '[Unable to serialize]';
54
- }
55
- }
56
- })
229
+ const args = consoleMessage.args();
230
+ if (args.length > 0) {
231
+ values = await Promise.all(
232
+ args.map((arg) =>
233
+ arg
234
+ .evaluate(serializeConsoleValue as never)
235
+ .catch(() => ({ type: 'object', preview: '[unserializable]' }) as BrowserConsoleValue)
236
+ )
57
237
  );
58
238
  }
59
239
  } catch (error) {
60
240
  debug.warn('preview', 'Could not extract console message args:', error);
61
- args = [];
62
241
  }
63
242
 
64
- const consoleLog: BrowserConsoleMessage = {
65
- id: messageId,
243
+ const stack = consoleMessage.stackTrace();
244
+
245
+ this.record(session, {
246
+ id: BrowserConsoleManager.makeId('console'),
66
247
  type,
67
248
  text,
68
- args,
249
+ values,
69
250
  location: messageLocation,
251
+ stackTrace:
252
+ stack.length > 0
253
+ ? stack.map((frame) => ` at ${frame.url}:${frame.lineNumber}:${frame.columnNumber}`).join('\n')
254
+ : undefined,
70
255
  timestamp: Date.now()
71
- };
72
-
73
- // Add to session logs (with limit to prevent memory issues)
74
- session.consoleLogs.push(consoleLog);
75
- if (session.consoleLogs.length > 1000) {
76
- session.consoleLogs = session.consoleLogs.slice(-500); // Keep last 500 logs
77
- }
78
-
79
- // Emit console message event for real-time streaming
80
- this.emit('console-message', {
81
- sessionId: session.id,
82
- message: consoleLog
83
256
  });
84
-
85
-
86
257
  } catch (error) {
87
258
  debug.error('preview', '❌ Error processing console message:', error);
88
259
  }
@@ -96,73 +267,60 @@ export class BrowserConsoleManager extends EventEmitter {
96
267
 
97
268
  try {
98
269
  const error = err as Error;
99
- const messageId = `error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
100
- const consoleLog: BrowserConsoleMessage = {
101
- id: messageId,
270
+ this.record(session, {
271
+ id: BrowserConsoleManager.makeId('error'),
102
272
  type: 'error',
103
273
  text: `Uncaught ${error.message || String(err)}`,
104
274
  stackTrace: error.stack,
105
275
  timestamp: Date.now()
106
- };
107
-
108
- session.consoleLogs.push(consoleLog);
109
- if (session.consoleLogs.length > 1000) {
110
- session.consoleLogs = session.consoleLogs.slice(-500);
111
- }
112
-
113
- this.emit('console-message', {
114
- sessionId: session.id,
115
- message: consoleLog
116
276
  });
117
-
118
-
119
- } catch (err) {
120
- debug.error('preview', '❌ Error processing page error:', err);
277
+ } catch (err2) {
278
+ debug.error('preview', '❌ Error processing page error:', err2);
121
279
  }
122
280
  });
123
281
 
124
282
  // Listen to response failures (network errors)
125
283
  page.on('response', (response: HTTPResponse) => {
126
284
  if (!session.consoleEnabled) return;
285
+ if (response.ok() || response.status() < 400) return;
127
286
 
128
- if (!response.ok() && response.status() >= 400) {
129
-
130
-
131
- try {
132
- const messageId = `network-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
133
- const consoleLog: BrowserConsoleMessage = {
134
- id: messageId,
135
- type: 'error',
136
- text: `Network error: ${response.status()} ${response.statusText()} - ${response.url()}`,
137
- location: {
138
- url: response.url(),
139
- lineNumber: 0,
140
- columnNumber: 0
141
- },
142
- timestamp: Date.now()
143
- };
144
-
145
- session.consoleLogs.push(consoleLog);
146
- if (session.consoleLogs.length > 1000) {
147
- session.consoleLogs = session.consoleLogs.slice(-500);
148
- }
149
-
150
- this.emit('console-message', {
151
- sessionId: session.id,
152
- message: consoleLog
153
- });
154
-
155
-
156
- } catch (err) {
157
- debug.error('preview', '❌ Error processing network error:', err);
158
- }
287
+ try {
288
+ this.record(session, {
289
+ id: BrowserConsoleManager.makeId('network'),
290
+ type: 'error',
291
+ text: `${response.status()} ${response.statusText()} — ${response.url()}`,
292
+ status: response.status(),
293
+ location: {
294
+ url: response.url(),
295
+ lineNumber: 0,
296
+ columnNumber: 0
297
+ },
298
+ timestamp: Date.now()
299
+ });
300
+ } catch (err) {
301
+ debug.error('preview', '❌ Error processing network error:', err);
159
302
  }
160
303
  });
161
304
 
162
- // Console monitoring is handled automatically by Puppeteer's console event listener
163
- // No additional injection needed
164
-
305
+ // Requests that never got a response at all (DNS failure, refused
306
+ // connection, blocked by an extension) never fire `response`, so they
307
+ // would otherwise be invisible in the panel.
308
+ page.on('requestfailed', (request) => {
309
+ if (!session.consoleEnabled) return;
165
310
 
311
+ try {
312
+ const failure = request.failure();
313
+ this.record(session, {
314
+ id: BrowserConsoleManager.makeId('network'),
315
+ type: 'error',
316
+ text: `${failure?.errorText || 'Request failed'} — ${request.url()}`,
317
+ location: { url: request.url(), lineNumber: 0, columnNumber: 0 },
318
+ timestamp: Date.now()
319
+ });
320
+ } catch (err) {
321
+ debug.error('preview', '❌ Error processing request failure:', err);
322
+ }
323
+ });
166
324
  }
167
325
 
168
326
  getConsoleLogs(session: BrowserTab): BrowserConsoleMessage[] {
@@ -173,16 +331,6 @@ export class BrowserConsoleManager extends EventEmitter {
173
331
  if (!session) return false;
174
332
 
175
333
  session.consoleLogs = [];
176
-
177
- // Add a clear message to console logs
178
- const clearMessage: BrowserConsoleMessage = {
179
- id: `clear-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
180
- type: 'clear',
181
- text: 'Console was cleared',
182
- timestamp: Date.now()
183
- };
184
-
185
- session.consoleLogs.push(clearMessage);
186
334
 
187
335
  // Emit clear event
188
336
  this.emit('console-clear', {
@@ -190,7 +338,6 @@ export class BrowserConsoleManager extends EventEmitter {
190
338
  timestamp: Date.now()
191
339
  });
192
340
 
193
-
194
341
  return true;
195
342
  }
196
343
 
@@ -202,62 +349,69 @@ export class BrowserConsoleManager extends EventEmitter {
202
349
  return true;
203
350
  }
204
351
 
205
- async executeConsoleCommand(session: BrowserTab, command: string): Promise<any> {
352
+ /**
353
+ * Evaluate a REPL entry in the page and record both the input and its result.
354
+ *
355
+ * Expressions and statements are both accepted: the expression form is tried
356
+ * first so `{a: 1}` reads as an object rather than a block, and the statement
357
+ * form catches everything the parser rejects (`let x = 1`, `for (…)`).
358
+ */
359
+ async executeConsoleCommand(session: BrowserTab, command: string): Promise<BrowserConsoleValue> {
206
360
  if (!session) throw new Error('Session not found');
207
361
 
208
- try {
362
+ this.record(session, {
363
+ id: BrowserConsoleManager.makeId('input'),
364
+ type: 'input',
365
+ text: command,
366
+ timestamp: Date.now()
367
+ });
209
368
 
210
-
211
- // Execute the command in the browser context
212
- const result = await session.page.evaluate((cmd: string) => {
213
- // Create a safe evaluation context
214
- try {
215
- // Use Function constructor for safer evaluation than eval
216
- const func = new Function('return ' + cmd);
217
- return func();
218
- } catch (error) {
219
- return { error: error instanceof Error ? error.message : String(error) };
220
- }
221
- }, command);
222
-
223
- // Log the command execution as a console message
224
- const commandMessage: BrowserConsoleMessage = {
225
- id: `command-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
226
- type: 'log',
227
- text: `> ${command}`,
228
- args: [result],
369
+ try {
370
+ const outcome = await session.page.evaluate(
371
+ async (source: string, serializerSource: string) => {
372
+ const serialize = new Function(`return (${serializerSource})`)() as (
373
+ value: unknown
374
+ ) => BrowserConsoleValue;
375
+
376
+ let value: unknown;
377
+ try {
378
+ value = await (0, eval)(`(${source})`);
379
+ } catch (expressionError) {
380
+ if (!(expressionError instanceof SyntaxError)) {
381
+ return { failed: true, value: serialize(expressionError) };
382
+ }
383
+ try {
384
+ value = await (0, eval)(source);
385
+ } catch (statementError) {
386
+ return { failed: true, value: serialize(statementError) };
387
+ }
388
+ }
389
+ return { failed: false, value: serialize(value) };
390
+ },
391
+ command,
392
+ serializeConsoleValue.toString()
393
+ );
394
+
395
+ this.record(session, {
396
+ id: BrowserConsoleManager.makeId('result'),
397
+ type: outcome.failed ? 'error' : 'result',
398
+ text: outcome.value.preview,
399
+ values: [outcome.value],
229
400
  timestamp: Date.now()
230
- };
231
-
232
- session.consoleLogs.push(commandMessage);
233
-
234
- // Emit the command result
235
- this.emit('console-message', {
236
- sessionId: session.id,
237
- message: commandMessage
238
401
  });
239
402
 
240
- return result;
403
+ return outcome.value;
241
404
  } catch (error) {
242
- debug.error('preview', 'Error executing console command:', error);
243
-
244
- // Log the error as a console message
245
- const errorMessage: BrowserConsoleMessage = {
246
- id: `command-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
405
+ const message = error instanceof Error ? error.message : String(error);
406
+
407
+ this.record(session, {
408
+ id: BrowserConsoleManager.makeId('result'),
247
409
  type: 'error',
248
- text: `Error executing command: ${command}`,
249
- args: [error instanceof Error ? error.message : String(error)],
410
+ text: message,
250
411
  timestamp: Date.now()
251
- };
252
-
253
- session.consoleLogs.push(errorMessage);
254
-
255
- this.emit('console-message', {
256
- sessionId: session.id,
257
- message: errorMessage
258
412
  });
259
413
 
260
414
  throw error;
261
415
  }
262
416
  }
263
- }
417
+ }
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import type { Page, Dialog } from 'puppeteer';
3
- import type { BrowserTab, BrowserDialogEvent, BrowserDialogResponse, BrowserPrintEvent } from './types';
3
+ import type { BrowserDialogResponse } from './types';
4
4
  import { debug } from '$shared/utils/logger';
5
5
  import { nanoid } from 'nanoid';
6
6
 
@@ -12,9 +12,20 @@ import { nanoid } from 'nanoid';
12
12
  *
13
13
  * Also intercepts window.print() calls and emits print events.
14
14
  */
15
+ /**
16
+ * How long a dialog waits for the viewer before it is dismissed on its own.
17
+ *
18
+ * A JS dialog blocks the renderer, so an unanswered one freezes the page —
19
+ * including the video stream. That is the correct behaviour while someone is
20
+ * looking at the prompt, and a hang once nobody is (panel closed, browser tab
21
+ * gone), which is what this bound exists for.
22
+ */
23
+ const DIALOG_RESPONSE_TIMEOUT_MS = 120_000;
24
+
15
25
  export class BrowserDialogHandler extends EventEmitter {
16
- // Store pending dialogs waiting for response
17
- private pendingDialogs = new Map<string, Dialog>();
26
+ // Store pending dialogs waiting for response, tagged with the tab that raised
27
+ // them so closing one tab cannot dismiss another tab's prompt.
28
+ private pendingDialogs = new Map<string, { sessionId: string; dialog: Dialog; timeout: NodeJS.Timeout }>();
18
29
 
19
30
  constructor() {
20
31
  super();
@@ -39,7 +50,7 @@ export class BrowserDialogHandler extends EventEmitter {
39
50
  /**
40
51
  * Setup dialog event listeners - can be called AFTER navigation
41
52
  */
42
- async setupDialogHandling(sessionId: string, page: Page, session: BrowserTab) {
53
+ async setupDialogHandling(sessionId: string, page: Page) {
43
54
  debug.log('preview', `🎭 Setting up dialog event listeners for session: ${sessionId}`);
44
55
 
45
56
  // Intercept Puppeteer dialog events
@@ -61,8 +72,18 @@ export class BrowserDialogHandler extends EventEmitter {
61
72
 
62
73
  debug.log('preview', `🎭 Dialog detected - Type: ${dialogType}, Session: ${sessionId}`);
63
74
 
64
- // Store pending dialog for later response
65
- this.pendingDialogs.set(dialogId, dialog);
75
+ // Store pending dialog for later response, with a deadline so an
76
+ // unattended page cannot stay blocked indefinitely.
77
+ const timeout = setTimeout(() => {
78
+ this.pendingDialogs.delete(dialogId);
79
+ debug.warn('preview', `⏱️ Dialog ${dialogId} unanswered, auto-dismissing`);
80
+ // beforeunload is the one dialog where dismissing is the safe default
81
+ // in both directions: it cancels the navigation rather than losing work.
82
+ dialog.dismiss().catch(() => {});
83
+ this.emit('dialog-closed', { sessionId, dialogId, timestamp: Date.now() });
84
+ }, DIALOG_RESPONSE_TIMEOUT_MS);
85
+
86
+ this.pendingDialogs.set(dialogId, { sessionId, dialog, timeout });
66
87
 
67
88
  // Emit dialog event to frontend (sessionId will be converted to tabId by previewService)
68
89
  const dialogEvent: any = {
@@ -87,13 +108,16 @@ export class BrowserDialogHandler extends EventEmitter {
87
108
 
88
109
  debug.log('preview', `🔍 Responding to dialog - dialogId: ${dialogId}, accept: ${accept}, pending dialogs: ${this.pendingDialogs.size}`);
89
110
 
90
- const dialog = this.pendingDialogs.get(dialogId);
91
- if (!dialog) {
111
+ const entry = this.pendingDialogs.get(dialogId);
112
+ if (!entry) {
92
113
  debug.warn('preview', `⚠️ Dialog not found in pendingDialogs: ${dialogId}`);
93
114
  debug.warn('preview', ` Available dialog IDs: ${Array.from(this.pendingDialogs.keys()).join(', ') || '(none)'}`);
94
115
  return false;
95
116
  }
96
117
 
118
+ const { dialog } = entry;
119
+ clearTimeout(entry.timeout);
120
+
97
121
  debug.log('preview', `✅ Dialog found in pendingDialogs - Type: ${dialog.type()}, Message: "${dialog.message()}"`);
98
122
 
99
123
  try {
@@ -118,10 +142,15 @@ export class BrowserDialogHandler extends EventEmitter {
118
142
  // Remove from pending dialogs
119
143
  this.pendingDialogs.delete(dialogId);
120
144
  debug.log('preview', `🗑️ Removed dialog from pendingDialogs - remaining: ${this.pendingDialogs.size}`);
145
+ // The page has one dialog and it is now answered, but every viewer of
146
+ // this tab was shown a copy of it. Telling them all it is settled is
147
+ // what stops the other devices holding a prompt that no longer exists.
148
+ this.emit('dialog-closed', { sessionId: entry.sessionId, dialogId, timestamp: Date.now() });
121
149
  return true;
122
150
  } catch (error) {
123
151
  debug.error('preview', `💥 Error responding to dialog ${dialogId}:`, error);
124
152
  this.pendingDialogs.delete(dialogId);
153
+ this.emit('dialog-closed', { sessionId: entry.sessionId, dialogId, timestamp: Date.now() });
125
154
  return false;
126
155
  }
127
156
  }
@@ -181,15 +210,14 @@ export class BrowserDialogHandler extends EventEmitter {
181
210
  * Clear pending dialogs for a session
182
211
  */
183
212
  clearSessionDialogs(sessionId: string) {
184
- // Find and dismiss all dialogs for this session
185
213
  const dialogsToRemove: string[] = [];
186
214
 
187
- for (const [dialogId, dialog] of this.pendingDialogs.entries()) {
188
- // Check if dialog belongs to this session (we store sessionId in the dialogId via Map)
189
- // Since we don't have direct sessionId mapping, we'll clear all pending dialogs
190
- // This is safe as each session has its own page instance
215
+ for (const [dialogId, entry] of this.pendingDialogs.entries()) {
216
+ if (entry.sessionId !== sessionId) continue;
217
+
218
+ clearTimeout(entry.timeout);
191
219
  try {
192
- dialog.dismiss().catch(() => {});
220
+ entry.dialog.dismiss().catch(() => {});
193
221
  } catch (error) {
194
222
  // Dialog might already be closed
195
223
  }
@@ -208,9 +236,10 @@ export class BrowserDialogHandler extends EventEmitter {
208
236
  clearAllDialogs() {
209
237
  const count = this.pendingDialogs.size;
210
238
 
211
- for (const [dialogId, dialog] of this.pendingDialogs.entries()) {
239
+ for (const entry of this.pendingDialogs.values()) {
240
+ clearTimeout(entry.timeout);
212
241
  try {
213
- dialog.dismiss().catch(() => {});
242
+ entry.dialog.dismiss().catch(() => {});
214
243
  } catch (error) {
215
244
  // Dialog might already be closed
216
245
  }