@myrialabs/clopen 0.4.47 → 0.4.48

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 (325) hide show
  1. package/README.md +11 -11
  2. package/backend/artifacts/project/sources.ts +1 -1
  3. package/backend/auth/auth-service.ts +52 -358
  4. package/backend/auth/onboarding.test.ts +2 -3
  5. package/backend/auth/permissions.test.ts +10 -20
  6. package/backend/auth/permissions.ts +4 -290
  7. package/backend/auth/rate-limiter.test.ts +8 -9
  8. package/backend/auth/rate-limiter.ts +0 -2
  9. package/backend/auth/tokens.ts +1 -8
  10. package/backend/bootstrap.ts +7 -0
  11. package/backend/chat/attachments.test.ts +88 -0
  12. package/backend/chat/attachments.ts +159 -0
  13. package/backend/chat/engine-handoff.test.ts +0 -2
  14. package/backend/chat/stream-manager.ts +62 -62
  15. package/backend/chat/turn-answer.test.ts +64 -0
  16. package/backend/chat/turn-answer.ts +125 -0
  17. package/backend/chat-apps/awaiting.test.ts +39 -0
  18. package/backend/chat-apps/awaiting.ts +49 -0
  19. package/backend/chat-apps/conversation.ts +746 -0
  20. package/backend/chat-apps/inbound.ts +324 -0
  21. package/backend/chat-apps/index.ts +309 -0
  22. package/backend/chat-apps/link-events.ts +20 -0
  23. package/backend/chat-apps/media.test.ts +62 -0
  24. package/backend/chat-apps/media.ts +208 -0
  25. package/backend/chat-apps/messages.test.ts +229 -0
  26. package/backend/chat-apps/messages.ts +365 -0
  27. package/backend/chat-apps/outbound.ts +243 -0
  28. package/backend/chat-apps/pairing.test.ts +45 -0
  29. package/backend/chat-apps/pairing.ts +74 -0
  30. package/backend/chat-apps/platforms/index.ts +20 -0
  31. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  32. package/backend/chat-apps/platforms/telegram.ts +191 -0
  33. package/backend/chat-apps/platforms/types.ts +114 -0
  34. package/backend/chat-apps/questions.ts +133 -0
  35. package/backend/chat-apps/runtime.ts +572 -0
  36. package/backend/chat-apps/storage.test.ts +201 -0
  37. package/backend/chat-apps/turns.test.ts +45 -0
  38. package/backend/chat-apps/turns.ts +208 -0
  39. package/backend/containers/pty.ts +3 -11
  40. package/backend/control/actions/accounts.ts +89 -0
  41. package/backend/control/actions/files.ts +116 -0
  42. package/backend/control/actions/models.ts +188 -0
  43. package/backend/control/actions/projects.ts +272 -0
  44. package/backend/control/actions/sessions.ts +280 -0
  45. package/backend/control/actions/skills.ts +111 -0
  46. package/backend/control/control.test.ts +169 -0
  47. package/backend/control/define.ts +20 -0
  48. package/backend/control/folders.test.ts +67 -0
  49. package/backend/control/index.ts +213 -0
  50. package/backend/control/invoke.ts +44 -0
  51. package/backend/control/links.ts +35 -0
  52. package/backend/control/paging.ts +26 -0
  53. package/backend/control/types.ts +117 -0
  54. package/backend/control/workspace.ts +127 -0
  55. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  56. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  57. package/backend/database/migrations/086_single_owner.test.ts +170 -0
  58. package/backend/database/migrations/086_single_owner.ts +418 -0
  59. package/backend/database/migrations/index.ts +21 -0
  60. package/backend/database/queries/auth-queries.ts +7 -85
  61. package/backend/database/queries/channel-queries.ts +270 -0
  62. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  63. package/backend/database/queries/file-share-queries.ts +5 -23
  64. package/backend/database/queries/git-identity-queries.ts +31 -42
  65. package/backend/database/queries/graph-queries.ts +1 -1
  66. package/backend/database/queries/index.ts +13 -1
  67. package/backend/database/queries/message-queries.test.ts +146 -0
  68. package/backend/database/queries/message-queries.ts +42 -1
  69. package/backend/database/queries/permission-set-queries.ts +1 -1
  70. package/backend/database/queries/profile-queries.ts +1 -1
  71. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  72. package/backend/database/queries/project-queries.ts +50 -63
  73. package/backend/database/queries/session-queries.ts +28 -56
  74. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  75. package/backend/db-client/integrations/projector.ts +0 -5
  76. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  77. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  78. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  79. package/backend/engine/adapters/cline/stream.ts +11 -15
  80. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  81. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  82. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  83. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  84. package/backend/engine/adapters/opencode/stream.ts +11 -0
  85. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  86. package/backend/engine/adapters/parent-scope.ts +44 -0
  87. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  88. package/backend/engine/adapters/pi/stream.ts +4 -5
  89. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  90. package/backend/engine/bootstrap-default-engine.ts +2 -2
  91. package/backend/engine/docs/adapter-contract.md +8 -1
  92. package/backend/engine/install-runner.ts +8 -17
  93. package/backend/files/file-shares.ts +20 -44
  94. package/backend/files/file-size-limit.ts +3 -3
  95. package/backend/files/image-processing.ts +1 -1
  96. package/backend/files/os-clipboard.ts +2 -2
  97. package/backend/git/git-executor.ts +25 -5
  98. package/backend/git/git-service.ts +420 -19
  99. package/backend/git/identity/credential-helper.test.ts +2 -7
  100. package/backend/git/identity/import-local.test.ts +11 -16
  101. package/backend/git/identity/import-local.ts +12 -12
  102. package/backend/git/identity/index.ts +10 -24
  103. package/backend/git/identity/resolve.ts +13 -14
  104. package/backend/git/identity/scope-config.ts +33 -28
  105. package/backend/git/identity/service.ts +44 -47
  106. package/backend/git/op-lock.test.ts +111 -0
  107. package/backend/git/op-lock.ts +180 -0
  108. package/backend/git/remote-sync.test.ts +249 -0
  109. package/backend/host/metrics.ts +1 -1
  110. package/backend/http/bearer-auth.ts +1 -2
  111. package/backend/http/files-download.test.ts +8 -9
  112. package/backend/http/files-download.ts +2 -2
  113. package/backend/http/files-shared.test.ts +62 -89
  114. package/backend/http/files-shared.ts +2 -2
  115. package/backend/http/files-upload.test.ts +3 -7
  116. package/backend/http/files-upload.ts +3 -3
  117. package/backend/http/notes-images.test.ts +15 -38
  118. package/backend/http/notes-images.ts +6 -8
  119. package/backend/http/ssh-sftp.ts +5 -10
  120. package/backend/index.ts +21 -7
  121. package/backend/integrations/accounts.ts +61 -3
  122. package/backend/integrations/index.ts +2 -2
  123. package/backend/integrations/registry/define.ts +15 -0
  124. package/backend/integrations/registry/index.ts +2 -0
  125. package/backend/integrations/registry/providers/telegram.ts +54 -0
  126. package/backend/integrations/registry/types.ts +21 -1
  127. package/backend/integrations/webhooks/gateway.ts +7 -6
  128. package/backend/integrations/webhooks/verify.test.ts +30 -0
  129. package/backend/integrations/webhooks/verify.ts +4 -0
  130. package/backend/mcp/external/project.ts +1 -1
  131. package/backend/mcp/internal/remote-server.test.ts +1 -3
  132. package/backend/mcp/internal/remote-server.ts +4 -4
  133. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  134. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  135. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  136. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  137. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  138. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  139. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  140. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  141. package/backend/memory/redact.ts +1 -1
  142. package/backend/notes/access.test.ts +28 -29
  143. package/backend/notes/access.ts +6 -11
  144. package/backend/permissions/service.ts +1 -1
  145. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  146. package/backend/preview/browser/browser-clipboard.ts +67 -0
  147. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  148. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  149. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  150. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  151. package/backend/preview/browser/browser-pool.ts +67 -6
  152. package/backend/preview/browser/browser-preview-service.ts +361 -25
  153. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  154. package/backend/preview/browser/browser-video-capture.ts +92 -5
  155. package/backend/preview/browser/element-locator.ts +190 -17
  156. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  157. package/backend/preview/browser/keyboard-chords.ts +132 -0
  158. package/backend/preview/browser/paste.ts +81 -0
  159. package/backend/preview/browser/process-usage.ts +142 -0
  160. package/backend/preview/browser/profile-lock.ts +209 -0
  161. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  162. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  163. package/backend/preview/browser/types.ts +40 -2
  164. package/backend/preview/browser/viewport.test.ts +45 -0
  165. package/backend/preview/browser/viewport.ts +96 -0
  166. package/backend/profiles/service.ts +2 -2
  167. package/backend/project/status-manager.ts +43 -172
  168. package/backend/projects/home.ts +61 -0
  169. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  170. package/backend/projects/project-cleanup.ts +0 -8
  171. package/backend/skills/service.ts +2 -3
  172. package/backend/snapshot/helpers.ts +0 -1
  173. package/backend/snapshot/restore.ts +252 -0
  174. package/backend/ssh/ptykit.ts +1 -2
  175. package/backend/terminal/ptykit.ts +5 -8
  176. package/backend/tunnel/public-origin.ts +31 -20
  177. package/backend/utils/user-helpers.ts +0 -55
  178. package/backend/utils/ws.ts +61 -154
  179. package/backend/worktrees/branching/engine.ts +3 -16
  180. package/backend/worktrees/branching/index.ts +1 -1
  181. package/backend/worktrees/branching/projector.ts +1 -1
  182. package/backend/worktrees/branching/service.ts +13 -25
  183. package/backend/ws/access.ts +12 -21
  184. package/backend/ws/artifacts/generate.ts +2 -2
  185. package/backend/ws/auth/device.ts +16 -71
  186. package/backend/ws/auth/index.ts +4 -22
  187. package/backend/ws/auth/login.test.ts +14 -60
  188. package/backend/ws/auth/login.ts +24 -124
  189. package/backend/ws/auth/status.ts +0 -1
  190. package/backend/ws/chat/composer.ts +118 -118
  191. package/backend/ws/chat/stream.ts +64 -47
  192. package/backend/ws/chat-apps/index.ts +117 -0
  193. package/backend/ws/containers/actions.ts +11 -25
  194. package/backend/ws/containers/index.ts +3 -4
  195. package/backend/ws/containers/list.ts +10 -36
  196. package/backend/ws/containers/logs.ts +2 -2
  197. package/backend/ws/containers/tunnel.ts +1 -2
  198. package/backend/ws/db-client/access.ts +2 -16
  199. package/backend/ws/db-client/accounts.ts +5 -15
  200. package/backend/ws/db-client/connections.ts +17 -25
  201. package/backend/ws/db-client/context.ts +1 -1
  202. package/backend/ws/db-client/env.ts +7 -10
  203. package/backend/ws/db-client/index.ts +2 -2
  204. package/backend/ws/db-client/io.ts +5 -5
  205. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  206. package/backend/ws/db-client/query.ts +18 -17
  207. package/backend/ws/db-client/schema.ts +13 -13
  208. package/backend/ws/db-client/structure.ts +35 -35
  209. package/backend/ws/db-client/supabase.ts +4 -21
  210. package/backend/ws/deployments/context.ts +1 -1
  211. package/backend/ws/deployments/crud.ts +0 -5
  212. package/backend/ws/engine/access.ts +7 -20
  213. package/backend/ws/engine/claude/accounts.ts +4 -4
  214. package/backend/ws/engine/cline/accounts.ts +5 -5
  215. package/backend/ws/engine/codex/accounts.ts +3 -3
  216. package/backend/ws/engine/pi/accounts.ts +5 -5
  217. package/backend/ws/files/clipboard.ts +8 -27
  218. package/backend/ws/files/image-edit.ts +6 -6
  219. package/backend/ws/files/index.ts +1 -1
  220. package/backend/ws/files/path-access.test.ts +32 -131
  221. package/backend/ws/files/path-access.ts +8 -87
  222. package/backend/ws/files/read.ts +15 -19
  223. package/backend/ws/files/reveal.ts +3 -3
  224. package/backend/ws/files/search.ts +7 -7
  225. package/backend/ws/files/share.ts +9 -13
  226. package/backend/ws/files/state.ts +9 -12
  227. package/backend/ws/files/watch.ts +3 -3
  228. package/backend/ws/files/write.ts +30 -31
  229. package/backend/ws/git/branch.ts +80 -59
  230. package/backend/ws/git/commit.ts +63 -44
  231. package/backend/ws/git/conflict.ts +16 -18
  232. package/backend/ws/git/identity-context.ts +8 -17
  233. package/backend/ws/git/identity.ts +17 -27
  234. package/backend/ws/git/index.ts +3 -1
  235. package/backend/ws/git/op-state.ts +139 -0
  236. package/backend/ws/git/remote.ts +241 -141
  237. package/backend/ws/git/repo-context.ts +67 -0
  238. package/backend/ws/git/staging.ts +18 -28
  239. package/backend/ws/git/status.ts +5 -2
  240. package/backend/ws/index.ts +5 -1
  241. package/backend/ws/instructions/crud.ts +1 -1
  242. package/backend/ws/integrations/crud.ts +1 -3
  243. package/backend/ws/mcp/crud.ts +3 -5
  244. package/backend/ws/mcp/tools.ts +1 -1
  245. package/backend/ws/memory/crud.ts +14 -46
  246. package/backend/ws/memory/index.ts +2 -2
  247. package/backend/ws/messages/crud.ts +29 -8
  248. package/backend/ws/notes/index.ts +33 -39
  249. package/backend/ws/permissions/crud.ts +3 -4
  250. package/backend/ws/ports/index.ts +1 -2
  251. package/backend/ws/ports/kill.ts +5 -10
  252. package/backend/ws/ports/list.ts +4 -10
  253. package/backend/ws/preview/access.ts +1 -1
  254. package/backend/ws/preview/browser/interact.ts +52 -79
  255. package/backend/ws/preview/browser/native-ui.ts +24 -0
  256. package/backend/ws/preview/browser/stats.ts +98 -1
  257. package/backend/ws/preview/browser/tab-info.ts +15 -0
  258. package/backend/ws/preview/browser/tab.ts +19 -4
  259. package/backend/ws/preview/index.ts +27 -0
  260. package/backend/ws/profiles/crud.ts +6 -8
  261. package/backend/ws/project-artifacts/index.ts +30 -31
  262. package/backend/ws/projects/crud.ts +33 -35
  263. package/backend/ws/projects/index.ts +3 -8
  264. package/backend/ws/projects/info.ts +3 -3
  265. package/backend/ws/projects/overview.ts +19 -30
  266. package/backend/ws/projects/status.ts +17 -57
  267. package/backend/ws/sessions/crud.ts +34 -45
  268. package/backend/ws/sessions/index.ts +1 -1
  269. package/backend/ws/settings/crud.ts +1 -1
  270. package/backend/ws/skills/crud.ts +3 -4
  271. package/backend/ws/skills/index.ts +1 -1
  272. package/backend/ws/snapshot/changes.ts +7 -7
  273. package/backend/ws/snapshot/restore.ts +11 -295
  274. package/backend/ws/snapshot/timeline.ts +2 -4
  275. package/backend/ws/ssh/access.ts +6 -21
  276. package/backend/ws/ssh/connections.ts +21 -31
  277. package/backend/ws/ssh/forwards.ts +12 -12
  278. package/backend/ws/ssh/sftp.ts +34 -34
  279. package/backend/ws/ssh/tunnel.ts +1 -2
  280. package/backend/ws/stack/install.ts +7 -17
  281. package/backend/ws/subagents/crud.ts +1 -1
  282. package/backend/ws/tunnel/share.ts +0 -2
  283. package/backend/ws/user/crud.ts +1 -59
  284. package/backend/ws/user/index.ts +1 -1
  285. package/backend/ws/work/context.ts +1 -1
  286. package/backend/ws/work/crud.ts +0 -5
  287. package/backend/ws/workspace/state.ts +10 -13
  288. package/backend/ws/worktrees/branching.ts +7 -36
  289. package/backend/ws/worktrees/crud.ts +2 -2
  290. package/bin/clopen.ts +10 -11
  291. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  292. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  293. package/dist/assets/main-BUiUL3eZ.css +1 -0
  294. package/dist/assets/main-nBOb9YOA.js +1240 -0
  295. package/dist/index.html +2 -2
  296. package/package.json +2 -1
  297. package/shared/constants/attachments.ts +14 -0
  298. package/shared/constants/engine-tools.ts +1 -1
  299. package/shared/constants/preview.test.ts +259 -0
  300. package/shared/constants/preview.ts +1018 -57
  301. package/shared/constants/tool-icons.ts +5 -0
  302. package/shared/types/containers/container.ts +1 -1
  303. package/shared/types/database/schema.ts +9 -6
  304. package/shared/types/git-identity.ts +1 -1
  305. package/shared/types/git.ts +116 -0
  306. package/shared/types/integrations.ts +7 -0
  307. package/shared/types/stores/settings.ts +1 -1
  308. package/shared/types/unified/index.ts +1 -1
  309. package/shared/types/unified/message.ts +0 -7
  310. package/shared/types/unified/stream.ts +2 -4
  311. package/shared/types/unified/tool.ts +15 -1
  312. package/shared/utils/ask-user-question.test.ts +319 -0
  313. package/shared/utils/ask-user-question.ts +154 -0
  314. package/shared/utils/home-project.ts +25 -0
  315. package/shared/utils/logger.ts +2 -0
  316. package/shared/utils/ws-server.ts +32 -7
  317. package/backend/auth/session-invalidation.test.ts +0 -112
  318. package/backend/auth/session-invalidation.ts +0 -77
  319. package/backend/project/status-manager.test.ts +0 -32
  320. package/backend/ws/auth/invites.ts +0 -94
  321. package/backend/ws/auth/users.ts +0 -112
  322. package/backend/ws/projects/presence.ts +0 -46
  323. package/backend/ws/stack/access.ts +0 -31
  324. package/dist/assets/main-BiDNMWb3.css +0 -1
  325. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -44,6 +44,7 @@ import { getChromeExecutablePath } from '$backend/engine/install-recipes';
44
44
  import { getClopenDir } from '$backend/utils/paths';
45
45
  import { scopeSlug } from '$shared/utils/workspace-scope';
46
46
  import { open as openSealed, seal } from '$backend/database/crypto/envelope';
47
+ import { isProfileInUseError, releaseProfile, sweepOrphanedProfiles } from './profile-lock';
47
48
 
48
49
  puppeteer.use(StealthPlugin());
49
50
 
@@ -218,10 +219,23 @@ function cookieFile(profileKey: string): string {
218
219
  return join(profilesRoot(), `${profileDirName(profileKey)}.cookies`);
219
220
  }
220
221
 
222
+ /** End a browser's process if it is still running. Safe to call on a dead one. */
223
+ function killBrowserProcess(browser: Browser): void {
224
+ const child = browser.process();
225
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
226
+ try {
227
+ child.kill('SIGKILL');
228
+ } catch {
229
+ // Already gone.
230
+ }
231
+ }
232
+
221
233
  class BrowserPool {
222
234
  private browsers = new Map<string, ProfileBrowser>();
223
235
  private sessions = new Map<string, PooledSession>();
224
236
  private launches = new Map<string, Promise<ProfileBrowser>>();
237
+ /** One sweep of orphaned Chromes per server, before its first launch. */
238
+ private orphanSweep: Promise<void> | null = null;
225
239
  private config: PoolConfig;
226
240
 
227
241
  constructor(config: Partial<PoolConfig> = {}) {
@@ -268,12 +282,38 @@ class BrowserPool {
268
282
  debug.log('preview', ` using Chrome at: ${executablePath}`);
269
283
  debug.log('preview', ` profile: ${userDataDir}`);
270
284
 
271
- const browser = (await puppeteer.launch({
272
- headless: true,
273
- executablePath,
274
- userDataDir,
275
- args: CHROME_ARGS
276
- })) as unknown as Browser;
285
+ // Orphans from a previous server are cleared before the first launch,
286
+ // and this profile is made launchable before every one.
287
+ this.orphanSweep ??= sweepOrphanedProfiles(profilesRoot());
288
+ await this.orphanSweep;
289
+ await releaseProfile(userDataDir);
290
+
291
+ const launch = () =>
292
+ puppeteer.launch({
293
+ headless: true,
294
+ executablePath,
295
+ userDataDir,
296
+ args: CHROME_ARGS,
297
+ // A pipe, not a WebSocket. Chrome exits the moment its end of the
298
+ // pipe closes, so it cannot outlive this server — a crash, a kill
299
+ // or a restart used to leave a headless Chrome running with the
300
+ // profile locked, and every later launch failed with "The browser
301
+ // is already running" until the machine was restarted. There is
302
+ // also no socket to drop when a laptop sleeps.
303
+ pipe: true
304
+ }) as unknown as Promise<Browser>;
305
+
306
+ let browser: Browser;
307
+ try {
308
+ browser = await launch();
309
+ } catch (error) {
310
+ if (!isProfileInUseError(error)) throw error;
311
+ // Something grabbed the profile between the check and the launch —
312
+ // most likely a Chrome still shutting down. One more pass, then give up.
313
+ debug.warn('preview', `⚠️ Profile ${userDataDir} still held at launch, recovering once`);
314
+ await releaseProfile(userDataDir);
315
+ browser = await launch();
316
+ }
277
317
 
278
318
  const entry: ProfileBrowser = {
279
319
  key: profileKey,
@@ -288,6 +328,10 @@ class BrowserPool {
288
328
  browser.on('disconnected', () => {
289
329
  debug.warn('preview', `⚠️ Chrome for ${profileKey} disconnected`);
290
330
  this.forgetBrowser(entry);
331
+ // Losing the connection does not end the process. Forgetting a Chrome
332
+ // that is still running leaves it holding the profile, and the
333
+ // recovery launch that follows is refused for it.
334
+ killBrowserProcess(browser);
291
335
  });
292
336
 
293
337
  // Chrome opens a page of its own at launch. Every tab we care about is
@@ -515,6 +559,8 @@ class BrowserPool {
515
559
  await entry.browser.close();
516
560
  } catch (error) {
517
561
  debug.warn('preview', `⚠️ Error closing Chrome for ${entry.key}: ${error}`);
562
+ } finally {
563
+ killBrowserProcess(entry.browser);
518
564
  }
519
565
  }
520
566
 
@@ -680,6 +726,7 @@ class BrowserPool {
680
726
  await entry.browser.close().catch((error) => {
681
727
  debug.warn('preview', `⚠️ Error closing Chrome for ${profileKey}: ${error}`);
682
728
  });
729
+ killBrowserProcess(entry.browser);
683
730
  }
684
731
 
685
732
  try {
@@ -795,6 +842,20 @@ class BrowserPool {
795
842
  };
796
843
  }
797
844
 
845
+ /**
846
+ * Every running workspace Chrome, with the pid of its browser process — the
847
+ * root of the process tree the diagnostics panel measures.
848
+ */
849
+ getRunningBrowsers(): Array<{ profileKey: string; pid: number | null; sessions: number }> {
850
+ return Array.from(this.browsers.values())
851
+ .filter((entry) => entry.browser.connected)
852
+ .map((entry) => ({
853
+ profileKey: entry.key,
854
+ pid: entry.browser.process()?.pid ?? null,
855
+ sessions: entry.sessions.size
856
+ }));
857
+ }
858
+
798
859
  /**
799
860
  * Clean up all resources
800
861
  */
@@ -5,15 +5,18 @@ import { BrowserConsoleManager } from './browser-console-manager.js';
5
5
  import { BrowserInteractionHandler, type AutonomousRunOutcome } from './browser-interaction-handler.js';
6
6
  import { BrowserNavigationTracker } from './browser-navigation-tracker.js';
7
7
  import { BrowserVideoCapture } from './browser-video-capture.js';
8
- import { BrowserDialogHandler } from './browser-dialog-handler.js';
8
+ import { BrowserDialogHandler, type PendingDialogInfo } from './browser-dialog-handler.js';
9
9
  import { BrowserNativeUIHandler } from './browser-native-ui-handler.js';
10
10
  import { BrowserHostBridge, type HostResponse } from './browser-host-bridge.js';
11
11
  import { BrowserTabLifecycle } from './browser-tab-lifecycle.js';
12
+ import { WorkspaceClipboard, type ClipboardSource } from './browser-clipboard.js';
12
13
  import { browserMcpControl } from './browser-mcp-control.js';
13
14
  import { browserPool } from './browser-pool.js';
14
15
  import { ws } from '$backend/utils/ws';
15
- import { getViewportDimensions } from '$shared/constants/preview.js';
16
+ import { defaultRotation, type DeviceRequest } from '$shared/constants/preview.js';
17
+ import { applyViewport, type EmulationPatch } from './viewport';
16
18
  import { debug } from '$shared/utils/logger';
19
+ import { sleep } from '$shared/utils/async';
17
20
  import { scopeProjectId } from '$shared/utils/workspace-scope';
18
21
  import type {
19
22
  BrowserSiteData,
@@ -23,6 +26,8 @@ import type {
23
26
  BrowserAutonomousAction,
24
27
  DeviceSize,
25
28
  Rotation,
29
+ ViewportSize,
30
+ PageColors,
26
31
  BrowserDialogResponse,
27
32
  BrowserSelectResponse,
28
33
  BrowserContextMenuResponse,
@@ -34,6 +39,17 @@ import type {
34
39
  ClientStreamFeedback
35
40
  } from './types';
36
41
 
42
+ /**
43
+ * How often a watched phone or tablet tab has its colours re-read. A page can
44
+ * change them without navigating — a theme toggle, an agent's colorScheme —
45
+ * and the bands around it would otherwise keep the old ones until the next
46
+ * load. One small evaluate per watched tab; most rounds emit nothing.
47
+ */
48
+ const PAGE_COLORS_POLL_MS = 1500;
49
+
50
+ /** Time a window needs after leaving fullscreen before an override sticks. */
51
+ const WINDOW_SETTLE_MS = 150;
52
+
37
53
  /**
38
54
  * Browser Preview Service
39
55
  *
@@ -57,6 +73,8 @@ export class BrowserPreviewService extends EventEmitter {
57
73
  private nativeUIHandler: BrowserNativeUIHandler;
58
74
  private hostBridge: BrowserHostBridge;
59
75
  private lifecycle: BrowserTabLifecycle;
76
+ /** What was copied last in this workspace — see browser-clipboard.ts. */
77
+ private clipboard = new WorkspaceClipboard();
60
78
 
61
79
  // Store context menu info for later action execution
62
80
  private contextMenus = new Map<string, BrowserContextMenuInfo>();
@@ -95,17 +113,28 @@ export class BrowserPreviewService extends EventEmitter {
95
113
  this.consoleManager = new BrowserConsoleManager({
96
114
  isWatched: (tabId) => this.lifecycle.hasViewers(tabId)
97
115
  });
98
- this.interactionHandler = new BrowserInteractionHandler();
116
+ this.interactionHandler = new BrowserInteractionHandler({
117
+ readClipboard: () => this.clipboard.read(),
118
+ getPendingDialog: (tabId) => this.dialogHandler.getPendingDialog(tabId),
119
+ waitForDialog: (tabId) => this.dialogHandler.waitForDialog(tabId)
120
+ });
99
121
  this.navigationTracker = new BrowserNavigationTracker();
100
122
  this.videoCapture = new BrowserVideoCapture();
101
- this.dialogHandler = new BrowserDialogHandler();
123
+ this.dialogHandler = new BrowserDialogHandler({
124
+ isAgentHeld: (tabId) => browserMcpControl.isTabControlled(tabId, this.projectId)
125
+ });
102
126
  this.nativeUIHandler = new BrowserNativeUIHandler();
103
127
  this.hostBridge = new BrowserHostBridge();
104
128
 
105
129
  // Forward events from handlers to main service
106
130
  this.setupEventForwarding();
131
+
132
+ this.pageColorsTimer = setInterval(() => void this.pollPageColors(), PAGE_COLORS_POLL_MS);
107
133
  }
108
134
 
135
+ /** Re-reads the page colours of streaming handheld tabs; see `pollPageColors`. */
136
+ private pageColorsTimer: ReturnType<typeof setInterval> | null = null;
137
+
109
138
  /**
110
139
  * Tabs that must keep running even though nobody is watching them.
111
140
  *
@@ -262,6 +291,12 @@ export class BrowserPreviewService extends EventEmitter {
262
291
  this.videoCapture.on('connection-state', (data) => {
263
292
  this.emit('preview:browser-webcodecs-connection-state', data);
264
293
  });
294
+ // The captured surface lost the page's shape (Chrome's own fullscreen
295
+ // stranded it). Detected from the frames themselves, so it is caught
296
+ // whatever caused it — not only when the page's shim saw the fullscreen.
297
+ this.videoCapture.on('surface-drift', (data: { sessionId: string }) => {
298
+ void this.restoreEmulatedViewport(data.sessionId, null);
299
+ });
265
300
  this.videoCapture.on('cursor-change', (data) => {
266
301
  this.emit('preview:browser-cursor-change', data);
267
302
  });
@@ -293,8 +328,18 @@ export class BrowserPreviewService extends EventEmitter {
293
328
  this.applyFullscreenState(data.tabId, data.requestId, data.payload);
294
329
  return;
295
330
  }
331
+ if (this.answerClipboardRequest(data.tabId, data.requestId, data.kind, data.payload)) return;
296
332
  this.emit('preview:browser-host-request', data);
297
333
  });
334
+ // A clipboard read the viewer answered tells us what their device holds.
335
+ this.hostBridge.on('clipboard-observed', (data: { text: string }) => {
336
+ this.clipboard.write(data.text, 'device');
337
+ });
338
+ // Everything copied anywhere but on the device goes down to the devices,
339
+ // which is what keeps the user's clipboard and the workspace's in step.
340
+ this.clipboard.on('changed', (data) => {
341
+ this.emit('preview:browser-clipboard-sync', data);
342
+ });
298
343
  this.hostBridge.on('download', (data) => {
299
344
  this.emit('preview:browser-download', data);
300
345
  });
@@ -304,6 +349,9 @@ export class BrowserPreviewService extends EventEmitter {
304
349
 
305
350
  // Forward native UI events
306
351
  this.nativeUIHandler.on('copy-to-clipboard', (data) => {
352
+ // Into the workspace clipboard, which mirrors it to the devices; the
353
+ // event itself is only the viewer's confirmation that it happened.
354
+ this.clipboard.write(data.text, 'menu');
307
355
  this.emit('preview:browser-copy-to-clipboard', data);
308
356
  });
309
357
  this.nativeUIHandler.on('open-url-new-tab', (data) => {
@@ -351,10 +399,12 @@ export class BrowserPreviewService extends EventEmitter {
351
399
  url?: string,
352
400
  deviceSize: DeviceSize = 'laptop',
353
401
  rotation?: Rotation,
354
- launchId?: string
402
+ launchId?: string,
403
+ viewport?: ViewportSize | null,
404
+ device?: { deviceModel?: string | null; emulation?: EmulationPatch | null }
355
405
  ): Promise<BrowserTab> {
356
406
  // Use device-appropriate default rotation if not specified
357
- const actualRotation = rotation || ((deviceSize === 'desktop' || deviceSize === 'laptop') ? 'landscape' : 'portrait');
407
+ const actualRotation = rotation || defaultRotation(deviceSize);
358
408
 
359
409
  // Dialog interception and the capability shims both have to be in place
360
410
  // before the first navigation: a page can call alert() or getUserMedia()
@@ -369,7 +419,10 @@ export class BrowserPreviewService extends EventEmitter {
369
419
  const tab = await this.tabManager.createTab(url, deviceSize, actualRotation, {
370
420
  setActive: true,
371
421
  preNavigationSetup,
372
- launchId
422
+ launchId,
423
+ viewport,
424
+ deviceModel: device?.deviceModel,
425
+ emulation: device?.emulation
373
426
  });
374
427
 
375
428
  // Setup console, navigation tracking, and pre-inject streaming scripts in parallel
@@ -610,11 +663,89 @@ export class BrowserPreviewService extends EventEmitter {
610
663
  };
611
664
 
612
665
  this.emit('preview:browser-tab-meta', meta);
666
+ await this.refreshPageColors(tabId);
613
667
  } catch (error) {
614
668
  debug.warn('preview', `⚠️ Failed to refresh tab meta for ${tabId}:`, error);
615
669
  }
616
670
  }
617
671
 
672
+ /**
673
+ * Read the colours a page asks to be framed in, as a mobile browser does:
674
+ * the status bar takes the page's `theme-color` (honouring its `media`),
675
+ * and everything else the root background, falling through to the body
676
+ * and then to the canvas default for the page's colour scheme.
677
+ *
678
+ * Read from the DOM, never sampled from pixels — a sampled edge picks up
679
+ * whatever header, image or button happens to touch it, which is how three
680
+ * sides of one page came out three different colours.
681
+ */
682
+ private async readPageColors(page: Page): Promise<PageColors | null> {
683
+ const read = page.evaluate(() => {
684
+ const probe = document.createElement('canvas').getContext('2d');
685
+ const normalise = (colour: string | null | undefined): string | null => {
686
+ if (!colour || !probe) return null;
687
+ probe.fillStyle = '#000001';
688
+ probe.fillStyle = colour;
689
+ const value = String(probe.fillStyle);
690
+ return value === '#000001' && colour.trim().toLowerCase() !== '#000001' ? null : value;
691
+ };
692
+ const opaque = (colour: string | null): string | null => {
693
+ if (!colour) return null;
694
+ const alpha = /rgba?\([^)]*,\s*([\d.]+)\s*\)/.exec(colour);
695
+ return alpha && Number(alpha[1]) === 0 ? null : colour;
696
+ };
697
+
698
+ let theme: string | null = null;
699
+ for (const meta of Array.from(document.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]'))) {
700
+ const media = meta.getAttribute('media');
701
+ if (!media || matchMedia(media).matches) {
702
+ theme = opaque(normalise(meta.content));
703
+ if (theme) break;
704
+ }
705
+ }
706
+
707
+ const root = opaque(normalise(getComputedStyle(document.documentElement).backgroundColor));
708
+ const body = document.body ? opaque(normalise(getComputedStyle(document.body).backgroundColor)) : null;
709
+ const darkCanvas =
710
+ getComputedStyle(document.documentElement).colorScheme.includes('dark') &&
711
+ matchMedia('(prefers-color-scheme: dark)').matches;
712
+ const background = root ?? body ?? (darkCanvas ? '#121212' : '#ffffff');
713
+
714
+ return { statusBar: theme ?? background, background };
715
+ });
716
+ // A page mid-navigation can reject after the timeout has already won;
717
+ // caught here so that late rejection is not left unhandled.
718
+ const settled = read.catch(() => null);
719
+ const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 1000));
720
+ return await Promise.race([settled, timeout]);
721
+ }
722
+
723
+ /** Re-read a tab's page colours and tell viewers when they changed. */
724
+ private async refreshPageColors(tabId: string): Promise<void> {
725
+ const tab = this.getTab(tabId);
726
+ if (!tab || tab.page.isClosed()) return;
727
+
728
+ const colors = await this.readPageColors(tab.page);
729
+ if (!colors) return;
730
+ if (tab.pageColors?.statusBar === colors.statusBar && tab.pageColors?.background === colors.background) return;
731
+
732
+ tab.pageColors = colors;
733
+ this.emit('preview:browser-page-colors', { tabId, ...colors, timestamp: Date.now() });
734
+ }
735
+
736
+ /**
737
+ * Only phones and tablets have bands to paint, and only a tab someone is
738
+ * watching needs them current. Sleeping tabs are left alone — running
739
+ * script in a frozen page would wake it.
740
+ */
741
+ private async pollPageColors(): Promise<void> {
742
+ for (const tab of this.tabManager.getAllTabs()) {
743
+ if (tab.deviceSize !== 'mobile' && tab.deviceSize !== 'tablet') continue;
744
+ if (!this.videoCapture.isStreaming(tab.id) || this.lifecycle.isFrozen(tab.id)) continue;
745
+ await this.refreshPageColors(tab.id);
746
+ }
747
+ }
748
+
618
749
  /**
619
750
  * Resolve the page's favicon to an absolute URL, falling back to the
620
751
  * origin's /favicon.ico the way a browser does.
@@ -727,11 +858,29 @@ export class BrowserPreviewService extends EventEmitter {
727
858
  }
728
859
 
729
860
  /**
730
- * Change viewport settings (device size and rotation) for an existing tab
861
+ * Change the device class, orientation or exact size of an existing tab,
862
+ * and rebuild the capture around it.
863
+ *
864
+ * One call for every caller — the viewer's device menu, a drag, an agent's
865
+ * `set_viewport`. The agent's path used to stop at the page's viewport,
866
+ * leaving the capture sized for the old shape until something else
867
+ * happened to restart it.
731
868
  */
732
- async setViewport(tabId: string, deviceSize: DeviceSize, rotation: Rotation): Promise<boolean> {
869
+ async setViewport(
870
+ tabId: string,
871
+ request: DeviceRequest & { emulation?: EmulationPatch | null }
872
+ ): Promise<boolean> {
733
873
  await this.ensureTabAwake(tabId);
734
- return await this.tabManager.setViewport(tabId, deviceSize, rotation);
874
+ const ok = await this.tabManager.setViewport(tabId, request);
875
+ if (!ok) return false;
876
+
877
+ const tab = this.getTab(tabId);
878
+ // False only means nothing is streaming yet; the stream that starts
879
+ // later is sized from the viewport just set.
880
+ if (tab) await this.videoCapture.updateViewport(tabId, tab);
881
+ // A colour-scheme change recolours the page without a navigation.
882
+ void this.refreshPageColors(tabId);
883
+ return true;
735
884
  }
736
885
 
737
886
  /**
@@ -956,17 +1105,22 @@ export class BrowserPreviewService extends EventEmitter {
956
1105
  * it only happens on a fullscreen the page did not ask for, which is rare
957
1106
  * enough that the restart it costs is not worth trying to avoid.
958
1107
  */
959
- private async restoreEmulatedViewport(tabId: string, requestId: string): Promise<void> {
1108
+ private async restoreEmulatedViewport(tabId: string, requestId: string | null): Promise<void> {
960
1109
  try {
961
1110
  const tab = this.getTab(tabId);
962
1111
  if (tab) {
963
- const { width, height } = getViewportDimensions(tab.deviceSize, tab.rotation);
1112
+ const { width, height } = tab.viewport;
1113
+
1114
+ // A fullscreen that never exited leaves the window itself in
1115
+ // `fullscreen` state, and no viewport override survives that — the
1116
+ // surface stays the window's shape. Put the window back first.
1117
+ await this.normalizeWindow(tab.page);
964
1118
 
965
1119
  // The capture path re-sends the override and recomputes the screencast
966
1120
  // geometry with it. With no stream running there is no geometry to
967
1121
  // recompute and the override is all that is needed.
968
- const restored = await this.videoCapture.updateViewport(tabId, tab, width, height);
969
- if (!restored) await tab.page.setViewport({ width, height });
1122
+ const restored = await this.videoCapture.updateViewport(tabId, tab);
1123
+ if (!restored) await applyViewport(tab.page, tab);
970
1124
 
971
1125
  debug.log('preview', `🖥️ Restored emulated viewport for tab ${tabId}: ${width}x${height}`);
972
1126
  }
@@ -975,7 +1129,40 @@ export class BrowserPreviewService extends EventEmitter {
975
1129
  } finally {
976
1130
  // The page holds a promise on this. Nothing awaits it, but an unsettled
977
1131
  // request sits in the pending map until it times out.
978
- this.hostBridge.respond(requestId, { ok: true });
1132
+ if (requestId) this.hostBridge.respond(requestId, { ok: true });
1133
+ }
1134
+ }
1135
+
1136
+ /** Take a tab's window out of fullscreen/maximized/minimized, if it is in one. */
1137
+ private async normalizeWindow(page: Page): Promise<void> {
1138
+ const cdp = await page.createCDPSession().catch(() => null);
1139
+ if (!cdp) return;
1140
+ try {
1141
+ const { windowId, bounds } = (await cdp.send('Browser.getWindowForTarget')) as {
1142
+ windowId: number;
1143
+ bounds: { windowState?: string };
1144
+ };
1145
+ if (bounds.windowState && bounds.windowState !== 'normal') {
1146
+ await cdp.send('Browser.setWindowBounds', { windowId, bounds: { windowState: 'normal' } });
1147
+
1148
+ // The window resizes asynchronously. A viewport override sent
1149
+ // before it has settled is applied to the old surface and then
1150
+ // stranded again by the resize — measured: back at 1366×681.
1151
+ for (let attempt = 0; attempt < 20; attempt++) {
1152
+ const current = (await cdp.send('Browser.getWindowBounds', { windowId })) as {
1153
+ bounds: { windowState?: string };
1154
+ };
1155
+ if (current.bounds.windowState === 'normal') break;
1156
+ await sleep(25);
1157
+ }
1158
+ await sleep(WINDOW_SETTLE_MS);
1159
+ debug.log('preview', `🪟 Window was left ${bounds.windowState}; set back to normal`);
1160
+ }
1161
+ } catch {
1162
+ // Not every build lets a page session ask about its window; the
1163
+ // viewport override below is the part that matters.
1164
+ } finally {
1165
+ await cdp.detach().catch(() => {});
979
1166
  }
980
1167
  }
981
1168
 
@@ -1033,21 +1220,13 @@ export class BrowserPreviewService extends EventEmitter {
1033
1220
  this.fullscreenTabs.delete(tabId);
1034
1221
  this.emit('preview:browser-fullscreen-state', { tabId, active: false });
1035
1222
 
1036
- const { width, height } = getViewportDimensions(tab.deviceSize, tab.rotation);
1037
- const restored = await this.videoCapture.updateViewport(tabId, tab, width, height);
1038
- if (!restored) await tab.page.setViewport({ width, height }).catch(() => {});
1223
+ const restored = await this.videoCapture.updateViewport(tabId, tab);
1224
+ if (!restored) await applyViewport(tab.page, tab).catch(() => {});
1039
1225
 
1040
1226
  debug.log('preview', `🖥️ Forced tab ${tabId} out of full screen`);
1041
1227
  return true;
1042
1228
  }
1043
1229
 
1044
- async updateWebCodecsViewport(tabId: string, width: number, height: number): Promise<boolean> {
1045
- const tab = this.getTab(tabId);
1046
- if (!tab) {
1047
- return false;
1048
- }
1049
- return await this.videoCapture.updateViewport(tabId, tab, width, height);
1050
- }
1051
1230
 
1052
1231
  async getWebCodecsOffer(tabId: string, viewerId: string): Promise<RTCSessionDescriptionInit | null> {
1053
1232
  const tab = this.getTab(tabId);
@@ -1178,6 +1357,21 @@ export class BrowserPreviewService extends EventEmitter {
1178
1357
  return await this.dialogHandler.respondToDialog(response);
1179
1358
  }
1180
1359
 
1360
+ /** The dialog a tab's page is blocked on, if any. */
1361
+ getPendingDialog(tabId: string): PendingDialogInfo | null {
1362
+ return this.dialogHandler.getPendingDialog(tabId);
1363
+ }
1364
+
1365
+ /** Resolve when a tab raises a dialog; `dispose` once the race is decided. */
1366
+ waitForDialog(tabId: string): { promise: Promise<PendingDialogInfo>; dispose: () => void } {
1367
+ return this.dialogHandler.waitForDialog(tabId);
1368
+ }
1369
+
1370
+ /** Answer the dialog a tab has open. Null when there was none to answer. */
1371
+ async respondToTabDialog(tabId: string, accept: boolean, promptText?: string): Promise<PendingDialogInfo | null> {
1372
+ return this.dialogHandler.respondForTab(tabId, accept, promptText);
1373
+ }
1374
+
1181
1375
  // ============================================================================
1182
1376
  // Native UI Methods (Select & Context Menu)
1183
1377
  // ============================================================================
@@ -1234,6 +1428,119 @@ export class BrowserPreviewService extends EventEmitter {
1234
1428
  return result;
1235
1429
  }
1236
1430
 
1431
+ // ============================================================================
1432
+ // Diagnostics
1433
+ // ============================================================================
1434
+
1435
+ /**
1436
+ * What every tab of this workspace is doing and costing, for the
1437
+ * diagnostics panel.
1438
+ *
1439
+ * Nothing here runs script in a page: a frozen tab must stay frozen for
1440
+ * being looked at, and a tab paused on a dialog would hang the read. Page
1441
+ * metrics come over the DevTools protocol, which answers either way, and
1442
+ * stream counters are only read from tabs that are actually streaming.
1443
+ */
1444
+ async getDiagnostics() {
1445
+ const tabs = await Promise.all(
1446
+ this.getAllTabs().map(async (tab) => {
1447
+ const frozen = this.lifecycle.isFrozen(tab.id);
1448
+ const dialog = this.dialogHandler.getPendingDialog(tab.id);
1449
+ const owner = browserMcpControl.getTabOwner(tab.id);
1450
+
1451
+ let jsHeapUsedBytes: number | null = null;
1452
+ let domNodes: number | null = null;
1453
+ if (!tab.page.isClosed()) {
1454
+ const metrics = await Promise.race([
1455
+ tab.page.metrics().catch(() => null),
1456
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), 1500))
1457
+ ]);
1458
+ jsHeapUsedBytes = metrics?.JSHeapUsedSize ?? null;
1459
+ domNodes = metrics?.Nodes ?? null;
1460
+ }
1461
+
1462
+ const streaming = this.isWebCodecsActive(tab.id);
1463
+ const stream =
1464
+ streaming && !frozen && !dialog
1465
+ ? await Promise.race([
1466
+ this.getWebCodecsStats(tab.id).catch(() => null),
1467
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), 1500))
1468
+ ])
1469
+ : null;
1470
+
1471
+ return {
1472
+ id: tab.id,
1473
+ title: tab.title,
1474
+ url: tab.page.isClosed() ? tab.url : tab.page.url(),
1475
+ state: frozen ? ('frozen' as const) : ('active' as const),
1476
+ watched: this.lifecycle.hasViewers(tab.id),
1477
+ isLoading: !!tab.isLoading,
1478
+ openedBy: tab.openedBy?.kind ?? 'user',
1479
+ agentHeld: !!owner,
1480
+ dialog: dialog ? { type: dialog.type, message: dialog.message } : null,
1481
+ createdAt: tab.createdAt,
1482
+ lastAccessedAt: tab.lastAccessedAt,
1483
+ jsHeapUsedBytes,
1484
+ domNodes,
1485
+ stream: stream
1486
+ ? {
1487
+ videoBytesSent: stream.videoBytesSent ?? 0,
1488
+ videoFramesEncoded: stream.videoFramesEncoded ?? 0,
1489
+ connectionState: stream.connectionState ?? 'unknown'
1490
+ }
1491
+ : null
1492
+ };
1493
+ })
1494
+ );
1495
+
1496
+ return { tabs, clipboard: this.clipboard.describe() };
1497
+ }
1498
+
1499
+ // ============================================================================
1500
+ // Clipboard
1501
+ // ============================================================================
1502
+
1503
+ /**
1504
+ * Clipboard traffic from a page, answered here rather than by a viewer.
1505
+ *
1506
+ * Writes (and copy events) go into the workspace clipboard straight away:
1507
+ * there is no decision in them, and waiting on a device meant a page's
1508
+ * "Copy" button failed whenever nobody was watching. Reads are answered from
1509
+ * the workspace clipboard while an agent holds the tab — the agent is the
1510
+ * user there, and a prompt on someone's screen would stall its run. A read
1511
+ * on a tab a person is driving still asks that person, as a browser would.
1512
+ */
1513
+ private answerClipboardRequest(tabId: string, requestId: string, kind: string, payload: unknown): boolean {
1514
+ if (kind === 'clipboard-write' || kind === 'clipboard-copied') {
1515
+ const text = (payload as { text?: unknown } | null)?.text;
1516
+ if (typeof text === 'string') this.clipboard.write(text, 'page');
1517
+ this.hostBridge.respond(requestId, { ok: true });
1518
+ return true;
1519
+ }
1520
+
1521
+ if (kind === 'clipboard-read' && browserMcpControl.isTabControlled(tabId, this.projectId)) {
1522
+ this.hostBridge.respond(requestId, { ok: true, result: this.clipboard.read() });
1523
+ return true;
1524
+ }
1525
+
1526
+ return false;
1527
+ }
1528
+
1529
+ /** The workspace clipboard's text. */
1530
+ getClipboardText(): string {
1531
+ return this.clipboard.read();
1532
+ }
1533
+
1534
+ /** Who last wrote the workspace clipboard, for diagnostics. */
1535
+ describeClipboard() {
1536
+ return this.clipboard.describe();
1537
+ }
1538
+
1539
+ /** Record a copy made somewhere other than a page (the user's device, the agent). */
1540
+ setClipboardText(text: string, source: ClipboardSource): void {
1541
+ this.clipboard.write(text, source);
1542
+ }
1543
+
1237
1544
  // ============================================================================
1238
1545
  // Host Bridge Methods
1239
1546
  // ============================================================================
@@ -1285,6 +1592,10 @@ export class BrowserPreviewService extends EventEmitter {
1285
1592
  // Cleanup Methods
1286
1593
  // ============================================================================
1287
1594
  async cleanup() {
1595
+ if (this.pageColorsTimer) {
1596
+ clearInterval(this.pageColorsTimer);
1597
+ this.pageColorsTimer = null;
1598
+ }
1288
1599
  // Clear all cursor tracking
1289
1600
  this.interactionHandler.clearAllSessionCursors();
1290
1601
  // Release host-bridge scratch dirs and unblock any parked page promises
@@ -1451,6 +1762,10 @@ class BrowserPreviewServiceManager {
1451
1762
  });
1452
1763
 
1453
1764
  // Forward live tab metadata (title, favicon, back/forward availability)
1765
+ service.on('preview:browser-page-colors', (data) => {
1766
+ ws.emit.project(roomId, 'preview:browser-page-colors', { ...data, projectId });
1767
+ });
1768
+
1454
1769
  service.on('preview:browser-tab-meta', (data) => {
1455
1770
  ws.emit.project(roomId, 'preview:browser-tab-meta', { ...data, projectId });
1456
1771
  });
@@ -1511,6 +1826,12 @@ class BrowserPreviewServiceManager {
1511
1826
  ws.emit.project(roomId, 'preview:browser-copy-to-clipboard', data);
1512
1827
  });
1513
1828
 
1829
+ // The workspace clipboard changed — every device of this project writes it
1830
+ // to its own clipboard (when focused; otherwise on its next focus).
1831
+ service.on('preview:browser-clipboard-sync', (data) => {
1832
+ ws.emit.project(roomId, 'preview:browser-clipboard-sync', { ...data, projectId });
1833
+ });
1834
+
1514
1835
  service.on('preview:browser-open-url-new-tab', (data) => {
1515
1836
  ws.emit.project(roomId, 'preview:browser-open-url-new-tab', data);
1516
1837
  });
@@ -1617,6 +1938,21 @@ class BrowserPreviewServiceManager {
1617
1938
  });
1618
1939
  });
1619
1940
 
1941
+ browserMcpControl.on('cursor-glide', (data) => {
1942
+ if (!data.projectId) return;
1943
+ ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-glide', {
1944
+ sessionId: data.tabId,
1945
+ from: data.from,
1946
+ control: data.control,
1947
+ to: data.to,
1948
+ durationMs: data.durationMs,
1949
+ pressed: data.pressed,
1950
+ easing: data.easing,
1951
+ timestamp: data.timestamp,
1952
+ source: 'mcp' as const
1953
+ });
1954
+ });
1955
+
1620
1956
  browserMcpControl.on('cursor-click', (data) => {
1621
1957
  if (!data.projectId) return;
1622
1958
  ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-click', {