@myrialabs/clopen 0.4.47 → 0.4.49

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 (390) 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/message-pages.test.ts +163 -0
  15. package/backend/chat/message-pages.ts +233 -0
  16. package/backend/chat/stream-manager.ts +91 -67
  17. package/backend/chat/turn-answer.test.ts +64 -0
  18. package/backend/chat/turn-answer.ts +125 -0
  19. package/backend/chat-apps/awaiting.test.ts +39 -0
  20. package/backend/chat-apps/awaiting.ts +49 -0
  21. package/backend/chat-apps/conversation.ts +746 -0
  22. package/backend/chat-apps/inbound.ts +324 -0
  23. package/backend/chat-apps/index.ts +309 -0
  24. package/backend/chat-apps/link-events.ts +20 -0
  25. package/backend/chat-apps/media.test.ts +62 -0
  26. package/backend/chat-apps/media.ts +208 -0
  27. package/backend/chat-apps/messages.test.ts +229 -0
  28. package/backend/chat-apps/messages.ts +365 -0
  29. package/backend/chat-apps/outbound.ts +243 -0
  30. package/backend/chat-apps/pairing.test.ts +45 -0
  31. package/backend/chat-apps/pairing.ts +74 -0
  32. package/backend/chat-apps/platforms/index.ts +20 -0
  33. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  34. package/backend/chat-apps/platforms/telegram.ts +191 -0
  35. package/backend/chat-apps/platforms/types.ts +114 -0
  36. package/backend/chat-apps/questions.ts +133 -0
  37. package/backend/chat-apps/runtime.ts +572 -0
  38. package/backend/chat-apps/storage.test.ts +201 -0
  39. package/backend/chat-apps/turns.test.ts +45 -0
  40. package/backend/chat-apps/turns.ts +208 -0
  41. package/backend/containers/pty.ts +3 -11
  42. package/backend/control/actions/accounts.ts +89 -0
  43. package/backend/control/actions/files.ts +116 -0
  44. package/backend/control/actions/models.ts +188 -0
  45. package/backend/control/actions/projects.ts +272 -0
  46. package/backend/control/actions/sessions.ts +280 -0
  47. package/backend/control/actions/skills.ts +111 -0
  48. package/backend/control/control.test.ts +169 -0
  49. package/backend/control/define.ts +20 -0
  50. package/backend/control/folders.test.ts +67 -0
  51. package/backend/control/index.ts +213 -0
  52. package/backend/control/invoke.ts +44 -0
  53. package/backend/control/links.ts +35 -0
  54. package/backend/control/paging.ts +26 -0
  55. package/backend/control/types.ts +117 -0
  56. package/backend/control/workspace.ts +127 -0
  57. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  58. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  59. package/backend/database/migrations/086_single_owner.ts +418 -0
  60. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  61. package/backend/database/migrations/index.ts +28 -0
  62. package/backend/database/queries/auth-queries.ts +7 -85
  63. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  64. package/backend/database/queries/channel-queries.ts +270 -0
  65. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  66. package/backend/database/queries/file-share-queries.ts +5 -23
  67. package/backend/database/queries/git-identity-queries.ts +31 -42
  68. package/backend/database/queries/graph-queries.ts +1 -1
  69. package/backend/database/queries/index.ts +15 -1
  70. package/backend/database/queries/message-queries.test.ts +146 -0
  71. package/backend/database/queries/message-queries.ts +42 -1
  72. package/backend/database/queries/permission-set-queries.ts +1 -1
  73. package/backend/database/queries/profile-queries.ts +1 -1
  74. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  75. package/backend/database/queries/project-queries.ts +50 -63
  76. package/backend/database/queries/session-queries.ts +28 -56
  77. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  78. package/backend/db-client/env/diff.ts +9 -33
  79. package/backend/db-client/env/env.test.ts +8 -8
  80. package/backend/db-client/env/service.ts +1 -1
  81. package/backend/db-client/integrations/projector.ts +0 -5
  82. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  83. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  84. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  85. package/backend/engine/adapters/cline/stream.ts +11 -15
  86. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  87. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  88. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  89. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  90. package/backend/engine/adapters/opencode/stream.ts +11 -0
  91. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  92. package/backend/engine/adapters/parent-scope.ts +44 -0
  93. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  94. package/backend/engine/adapters/pi/stream.ts +4 -5
  95. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  96. package/backend/engine/bootstrap-default-engine.ts +2 -2
  97. package/backend/engine/docs/adapter-contract.md +8 -1
  98. package/backend/engine/install-runner.ts +8 -17
  99. package/backend/files/file-shares.ts +20 -44
  100. package/backend/files/file-size-limit.ts +3 -3
  101. package/backend/files/file-watcher.ts +19 -0
  102. package/backend/files/image-processing.ts +1 -1
  103. package/backend/files/os-clipboard.ts +2 -2
  104. package/backend/git/contributors.test.ts +35 -0
  105. package/backend/git/contributors.ts +46 -0
  106. package/backend/git/git-executor.ts +25 -5
  107. package/backend/git/git-service.ts +420 -19
  108. package/backend/git/identity/credential-helper.test.ts +2 -7
  109. package/backend/git/identity/import-local.test.ts +11 -16
  110. package/backend/git/identity/import-local.ts +12 -12
  111. package/backend/git/identity/index.ts +10 -24
  112. package/backend/git/identity/resolve.ts +13 -14
  113. package/backend/git/identity/scope-config.ts +33 -28
  114. package/backend/git/identity/service.ts +44 -47
  115. package/backend/git/op-lock.test.ts +111 -0
  116. package/backend/git/op-lock.ts +180 -0
  117. package/backend/git/remote-sync.test.ts +249 -0
  118. package/backend/host/metrics.ts +1 -1
  119. package/backend/http/bearer-auth.ts +1 -2
  120. package/backend/http/files-download.test.ts +8 -9
  121. package/backend/http/files-download.ts +2 -2
  122. package/backend/http/files-shared.test.ts +62 -89
  123. package/backend/http/files-shared.ts +2 -2
  124. package/backend/http/files-upload.test.ts +3 -7
  125. package/backend/http/files-upload.ts +3 -3
  126. package/backend/http/notes-images.test.ts +15 -38
  127. package/backend/http/notes-images.ts +6 -8
  128. package/backend/http/ssh-sftp.ts +5 -10
  129. package/backend/http/static-assets.test.ts +78 -0
  130. package/backend/http/static-assets.ts +104 -0
  131. package/backend/index.ts +32 -16
  132. package/backend/integrations/accounts.ts +61 -3
  133. package/backend/integrations/index.ts +2 -2
  134. package/backend/integrations/registry/define.ts +15 -0
  135. package/backend/integrations/registry/index.ts +2 -0
  136. package/backend/integrations/registry/providers/telegram.ts +54 -0
  137. package/backend/integrations/registry/types.ts +21 -1
  138. package/backend/integrations/webhooks/gateway.ts +7 -6
  139. package/backend/integrations/webhooks/verify.test.ts +30 -0
  140. package/backend/integrations/webhooks/verify.ts +4 -0
  141. package/backend/mcp/external/project.ts +1 -1
  142. package/backend/mcp/internal/remote-server.test.ts +1 -3
  143. package/backend/mcp/internal/remote-server.ts +4 -4
  144. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  145. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  146. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  147. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  148. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  149. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  150. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  151. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  152. package/backend/memory/redact.ts +1 -1
  153. package/backend/notes/access.test.ts +28 -29
  154. package/backend/notes/access.ts +6 -11
  155. package/backend/permissions/service.ts +1 -1
  156. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  157. package/backend/preview/browser/browser-clipboard.ts +67 -0
  158. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  159. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  160. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  161. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  162. package/backend/preview/browser/browser-pool.ts +67 -6
  163. package/backend/preview/browser/browser-preview-service.ts +383 -29
  164. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  165. package/backend/preview/browser/browser-video-capture.ts +92 -5
  166. package/backend/preview/browser/element-locator.ts +190 -17
  167. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  168. package/backend/preview/browser/keyboard-chords.ts +132 -0
  169. package/backend/preview/browser/paste.ts +81 -0
  170. package/backend/preview/browser/process-usage.ts +142 -0
  171. package/backend/preview/browser/profile-lock.ts +209 -0
  172. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  173. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  174. package/backend/preview/browser/types.ts +40 -2
  175. package/backend/preview/browser/viewport.test.ts +45 -0
  176. package/backend/preview/browser/viewport.ts +96 -0
  177. package/backend/profiles/service.ts +2 -2
  178. package/backend/project/status-manager.ts +43 -172
  179. package/backend/projects/home.ts +61 -0
  180. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  181. package/backend/projects/project-cleanup.ts +0 -8
  182. package/backend/skills/service.ts +2 -3
  183. package/backend/snapshot/blob-store.ts +9 -1
  184. package/backend/snapshot/helpers.ts +3 -11
  185. package/backend/snapshot/line-stats.test.ts +80 -0
  186. package/backend/snapshot/line-stats.ts +64 -0
  187. package/backend/snapshot/restore.ts +252 -0
  188. package/backend/snapshot/snapshot-service.ts +14 -27
  189. package/backend/snapshot/turn-changes.test.ts +10 -5
  190. package/backend/snapshot/turn-changes.ts +78 -40
  191. package/backend/ssh/ptykit.ts +1 -2
  192. package/backend/terminal/ptykit.ts +10 -8
  193. package/backend/tunnel/public-origin.ts +31 -20
  194. package/backend/utils/user-helpers.ts +0 -55
  195. package/backend/utils/ws-wire.test.ts +87 -0
  196. package/backend/utils/ws-wire.ts +189 -0
  197. package/backend/utils/ws.ts +101 -192
  198. package/backend/worktrees/branching/engine.ts +3 -16
  199. package/backend/worktrees/branching/index.ts +1 -1
  200. package/backend/worktrees/branching/projector.ts +1 -1
  201. package/backend/worktrees/branching/service.ts +13 -25
  202. package/backend/ws/access.ts +12 -21
  203. package/backend/ws/artifacts/generate.ts +2 -2
  204. package/backend/ws/auth/device.ts +16 -71
  205. package/backend/ws/auth/index.ts +4 -22
  206. package/backend/ws/auth/login.test.ts +14 -60
  207. package/backend/ws/auth/login.ts +24 -124
  208. package/backend/ws/auth/status.ts +0 -1
  209. package/backend/ws/chat/composer.ts +118 -118
  210. package/backend/ws/chat/stream.ts +105 -57
  211. package/backend/ws/chat-apps/index.ts +117 -0
  212. package/backend/ws/containers/actions.ts +11 -25
  213. package/backend/ws/containers/index.ts +3 -4
  214. package/backend/ws/containers/list.ts +10 -36
  215. package/backend/ws/containers/logs.ts +2 -2
  216. package/backend/ws/containers/tunnel.ts +1 -2
  217. package/backend/ws/db-client/access.ts +2 -16
  218. package/backend/ws/db-client/accounts.ts +5 -15
  219. package/backend/ws/db-client/connections.ts +17 -25
  220. package/backend/ws/db-client/context.ts +1 -1
  221. package/backend/ws/db-client/env.ts +7 -10
  222. package/backend/ws/db-client/index.ts +2 -2
  223. package/backend/ws/db-client/io.ts +5 -5
  224. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  225. package/backend/ws/db-client/query.ts +18 -17
  226. package/backend/ws/db-client/schema.ts +13 -13
  227. package/backend/ws/db-client/structure.ts +35 -35
  228. package/backend/ws/db-client/supabase.ts +4 -21
  229. package/backend/ws/deployments/context.ts +1 -1
  230. package/backend/ws/deployments/crud.ts +0 -5
  231. package/backend/ws/engine/access.ts +7 -20
  232. package/backend/ws/engine/claude/accounts.ts +4 -4
  233. package/backend/ws/engine/cline/accounts.ts +5 -5
  234. package/backend/ws/engine/codex/accounts.ts +3 -3
  235. package/backend/ws/engine/pi/accounts.ts +5 -5
  236. package/backend/ws/files/clipboard.ts +8 -27
  237. package/backend/ws/files/image-edit.ts +6 -6
  238. package/backend/ws/files/index.ts +1 -1
  239. package/backend/ws/files/path-access.test.ts +32 -131
  240. package/backend/ws/files/path-access.ts +8 -87
  241. package/backend/ws/files/read.ts +45 -19
  242. package/backend/ws/files/reveal.ts +3 -3
  243. package/backend/ws/files/search.ts +7 -7
  244. package/backend/ws/files/share.ts +9 -13
  245. package/backend/ws/files/state.ts +9 -12
  246. package/backend/ws/files/watch.ts +3 -3
  247. package/backend/ws/files/write.ts +30 -31
  248. package/backend/ws/git/branch.ts +80 -59
  249. package/backend/ws/git/commit.ts +63 -44
  250. package/backend/ws/git/conflict.ts +16 -18
  251. package/backend/ws/git/identity-context.ts +8 -17
  252. package/backend/ws/git/identity.ts +17 -27
  253. package/backend/ws/git/index.ts +3 -1
  254. package/backend/ws/git/log.ts +52 -0
  255. package/backend/ws/git/op-state.ts +139 -0
  256. package/backend/ws/git/remote.ts +241 -141
  257. package/backend/ws/git/repo-context.ts +67 -0
  258. package/backend/ws/git/staging.ts +18 -28
  259. package/backend/ws/git/status.ts +5 -2
  260. package/backend/ws/index.ts +5 -1
  261. package/backend/ws/instructions/crud.ts +1 -1
  262. package/backend/ws/integrations/crud.ts +1 -3
  263. package/backend/ws/mcp/crud.ts +3 -5
  264. package/backend/ws/mcp/tools.ts +1 -1
  265. package/backend/ws/memory/crud.ts +14 -46
  266. package/backend/ws/memory/index.ts +2 -2
  267. package/backend/ws/messages/crud.ts +78 -8
  268. package/backend/ws/notes/index.ts +33 -39
  269. package/backend/ws/permissions/crud.ts +3 -4
  270. package/backend/ws/ports/index.ts +1 -2
  271. package/backend/ws/ports/kill.ts +5 -10
  272. package/backend/ws/ports/list.ts +4 -10
  273. package/backend/ws/preview/access.ts +1 -1
  274. package/backend/ws/preview/browser/interact.ts +52 -79
  275. package/backend/ws/preview/browser/native-ui.ts +24 -0
  276. package/backend/ws/preview/browser/stats.ts +98 -1
  277. package/backend/ws/preview/browser/tab-info.ts +15 -0
  278. package/backend/ws/preview/browser/tab.ts +19 -4
  279. package/backend/ws/preview/index.ts +29 -0
  280. package/backend/ws/preview/watchers.ts +84 -0
  281. package/backend/ws/profiles/crud.ts +6 -8
  282. package/backend/ws/project-artifacts/index.ts +30 -31
  283. package/backend/ws/projects/crud.ts +33 -35
  284. package/backend/ws/projects/index.ts +3 -8
  285. package/backend/ws/projects/info.ts +3 -3
  286. package/backend/ws/projects/overview.ts +19 -30
  287. package/backend/ws/projects/status.ts +17 -57
  288. package/backend/ws/sessions/crud.ts +42 -57
  289. package/backend/ws/sessions/index.ts +1 -1
  290. package/backend/ws/settings/crud.ts +1 -1
  291. package/backend/ws/skills/crud.ts +3 -4
  292. package/backend/ws/skills/index.ts +1 -1
  293. package/backend/ws/snapshot/changes.ts +12 -13
  294. package/backend/ws/snapshot/restore.ts +11 -295
  295. package/backend/ws/snapshot/timeline.ts +2 -4
  296. package/backend/ws/ssh/access.ts +6 -21
  297. package/backend/ws/ssh/connections.ts +21 -31
  298. package/backend/ws/ssh/forwards.ts +12 -12
  299. package/backend/ws/ssh/sftp.ts +34 -34
  300. package/backend/ws/ssh/tunnel.ts +1 -2
  301. package/backend/ws/stack/install.ts +7 -17
  302. package/backend/ws/subagents/crud.ts +1 -1
  303. package/backend/ws/terminal/tunnel.ts +2 -2
  304. package/backend/ws/tunnel/share.ts +0 -2
  305. package/backend/ws/user/crud.ts +1 -59
  306. package/backend/ws/user/index.ts +1 -1
  307. package/backend/ws/work/context.ts +1 -1
  308. package/backend/ws/work/crud.ts +0 -5
  309. package/backend/ws/workspace/state.ts +10 -13
  310. package/backend/ws/worktrees/branching.ts +7 -36
  311. package/backend/ws/worktrees/crud.ts +2 -2
  312. package/bin/clopen.ts +46 -41
  313. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  314. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  315. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  316. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  317. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  318. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  319. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  320. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  321. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  322. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  323. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  324. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  325. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  326. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  327. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  328. package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
  329. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  330. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  331. package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
  332. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  333. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  334. package/dist/assets/main-D2_TmcwQ.js +1240 -0
  335. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  336. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  337. package/dist/assets/main-Yucigcmf.css +1 -0
  338. package/dist/assets/main-Yucigcmf.css.br +0 -0
  339. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  340. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  341. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  342. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  343. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  344. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  345. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  346. package/dist/fonts/dm-sans.css.br +0 -0
  347. package/dist/fonts/dm-sans.css.gz +0 -0
  348. package/dist/index.html +2 -2
  349. package/dist/index.html.br +0 -0
  350. package/dist/index.html.gz +0 -0
  351. package/dist/sw.js.br +0 -0
  352. package/dist/sw.js.gz +0 -0
  353. package/package.json +3 -3
  354. package/shared/constants/attachments.ts +14 -0
  355. package/shared/constants/engine-tools.ts +1 -1
  356. package/shared/constants/preview.test.ts +259 -0
  357. package/shared/constants/preview.ts +1018 -57
  358. package/shared/constants/tool-icons.ts +5 -0
  359. package/shared/types/containers/container.ts +1 -1
  360. package/shared/types/database/schema.ts +9 -6
  361. package/shared/types/git-identity.ts +1 -1
  362. package/shared/types/git.ts +116 -0
  363. package/shared/types/integrations.ts +7 -0
  364. package/shared/types/stores/settings.ts +1 -1
  365. package/shared/types/unified/index.ts +1 -1
  366. package/shared/types/unified/message.ts +0 -7
  367. package/shared/types/unified/stream.ts +13 -5
  368. package/shared/types/unified/tool.ts +15 -1
  369. package/shared/utils/ask-user-question.test.ts +319 -0
  370. package/shared/utils/ask-user-question.ts +154 -0
  371. package/shared/utils/diff-calculator.test.ts +178 -41
  372. package/shared/utils/diff-calculator.ts +383 -100
  373. package/shared/utils/home-project.ts +25 -0
  374. package/shared/utils/logger.ts +2 -0
  375. package/shared/utils/process-supervisor.test.ts +172 -0
  376. package/shared/utils/process-supervisor.ts +251 -0
  377. package/shared/utils/ws-chunk.test.ts +33 -0
  378. package/shared/utils/ws-chunk.ts +73 -0
  379. package/shared/utils/ws-client-chunks.test.ts +45 -0
  380. package/shared/utils/ws-client.ts +43 -0
  381. package/shared/utils/ws-server.ts +49 -21
  382. package/backend/auth/session-invalidation.test.ts +0 -112
  383. package/backend/auth/session-invalidation.ts +0 -77
  384. package/backend/project/status-manager.test.ts +0 -32
  385. package/backend/ws/auth/invites.ts +0 -94
  386. package/backend/ws/auth/users.ts +0 -112
  387. package/backend/ws/projects/presence.ts +0 -46
  388. package/backend/ws/stack/access.ts +0 -31
  389. package/dist/assets/main-BiDNMWb3.css +0 -1
  390. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -50,6 +50,10 @@ export function verifySignature(
50
50
  return { ok: false, reason: `missing ${spec.signatureHeader}` };
51
51
  }
52
52
 
53
+ if (spec.scheme === 'header-token') {
54
+ return safeEqual(presented, secret) ? { ok: true } : { ok: false, reason: 'token mismatch' };
55
+ }
56
+
53
57
  const prefix = spec.signaturePrefix ?? '';
54
58
  if (prefix && !presented.startsWith(prefix)) {
55
59
  return { ok: false, reason: 'signature prefix mismatch' };
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * - TRUST. The file lives in the repo, so anyone who can push to it could make
9
9
  * the server run a command. A server is emitted — and the bridge will only
10
- * connect it — while the file's current sha256 matches the hash an admin
10
+ * connect it — while the file's current sha256 matches the hash the owner
11
11
  * approved (`project_mcp_trust`). Any edit makes it inert until re-approved.
12
12
  * The check runs at config-build time AND again when the bridge connects, so
13
13
  * a file swapped between the two is still refused.
@@ -63,7 +63,6 @@ beforeAll(async () => {
63
63
  name: 'MCP Test User',
64
64
  color: '#000000',
65
65
  avatar: 'mcp',
66
- role: 'admin',
67
66
  personal_access_token_hash: hashToken(patToken),
68
67
  created_at: new Date().toISOString()
69
68
  });
@@ -83,8 +82,7 @@ beforeAll(async () => {
83
82
  });
84
83
 
85
84
  afterAll(() => {
86
- authQueries.deleteSessionsByUserId(testUserId);
87
- authQueries.deleteUser(testUserId);
85
+ getDatabase().prepare('DELETE FROM users WHERE id = ?').run(testUserId);
88
86
  setAuthMode('required');
89
87
  closeDatabase();
90
88
  });
@@ -79,7 +79,7 @@ function disposeSession(sessionId: string): void {
79
79
  * Pure validator - does NOT create new sessions.
80
80
  * Returns user info if valid, null otherwise.
81
81
  */
82
- function validateAuthToken(request: Request): { userId: string; role: string } | null {
82
+ function validateAuthToken(request: Request): { userId: string } | null {
83
83
  const authHeader = request.headers.get('authorization');
84
84
  if (!authHeader || !authHeader.toLowerCase().startsWith('bearer ')) {
85
85
  return null;
@@ -94,7 +94,7 @@ function validateAuthToken(request: Request): { userId: string; role: string } |
94
94
  // loopback endpoint with the process-scoped service token, not a user
95
95
  // session. Accept it regardless of auth mode — it never leaves the host.
96
96
  if (isMcpServiceToken(token)) {
97
- return { userId: 'mcp-service', role: 'admin' };
97
+ return { userId: 'mcp-service' };
98
98
  }
99
99
 
100
100
  const tokenHash = hashToken(token);
@@ -109,13 +109,13 @@ function validateAuthToken(request: Request): { userId: string; role: string } |
109
109
  if (!user) {
110
110
  return null;
111
111
  }
112
- return { userId: user.id, role: user.role };
112
+ return { userId: user.id };
113
113
  }
114
114
 
115
115
  // Try PAT (Personal Access Token)
116
116
  const user = authQueries.getUserByPatHash(tokenHash);
117
117
  if (user) {
118
- return { userId: user.id, role: user.role };
118
+ return { userId: user.id };
119
119
  }
120
120
 
121
121
  return null;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Dialogs and the clipboard — the two things a page hands to the user rather
3
+ * than handling itself.
4
+ *
5
+ * Both used to be out of the agent's reach. A page's alert() went to whoever
6
+ * was watching the panel, and until someone clicked OK every action against
7
+ * the tab hung. The clipboard was the viewer's device, which the agent cannot
8
+ * see. They are the agent's now, exactly as they would be a person's.
9
+ */
10
+
11
+ import { z } from 'zod';
12
+ import type { ActionDef, TablessActionContext } from './types';
13
+ import { commonFields } from './shared';
14
+
15
+ /** Long dialog text is quoted in full in the report; the summary only needs a gist. */
16
+ function gist(text: string, max = 80): string {
17
+ const flat = text.replace(/\s+/g, ' ').trim();
18
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat;
19
+ }
20
+
21
+ export const dialog: ActionDef = {
22
+ type: 'dialog',
23
+ kind: 'control',
24
+ activity: 'Answering a dialog',
25
+ doc: `dialog {response, text?} — answer the alert / confirm / prompt / beforeunload the page has open.
26
+ The report says when one opens and quotes it; the page runs nothing until it is answered, so decide as the user would.
27
+ response: accept (OK, Leave) | dismiss (Cancel, Stay). text: the answer to a prompt.`,
28
+ schema: z.object({
29
+ type: z.literal('dialog'),
30
+ response: z.enum(['accept', 'dismiss']).describe('accept = OK / Leave; dismiss = Cancel / Stay.'),
31
+ text: z.string().optional().describe('Text for a prompt() dialog.'),
32
+ ...commonFields
33
+ }),
34
+ run: async (args, ctx) => {
35
+ const answered = await ctx.service.respondToTabDialog(ctx.tab.id, args.response === 'accept', args.text);
36
+ if (!answered) throw new Error('No dialog is open on this tab');
37
+
38
+ const verb = args.response === 'accept' ? 'accepted' : 'dismissed';
39
+ return { summary: `${verb} ${answered.type} "${gist(answered.message)}"` };
40
+ }
41
+ };
42
+
43
+ export const clipboard: ActionDef = {
44
+ type: 'clipboard',
45
+ kind: 'control',
46
+ activity: 'Using the clipboard',
47
+ doc: `clipboard {text?} — read the clipboard, or set it with text.
48
+ One clipboard is shared by the page, you and the user's device: after clicking a page's "Copy" button, read the copied value here instead of pasting it somewhere to look at it.`,
49
+ schema: z.object({
50
+ type: z.literal('clipboard'),
51
+ text: z.string().optional().describe('Set the clipboard to this. Omit to read it.'),
52
+ ...commonFields
53
+ }),
54
+ needsTab: false,
55
+ run: async (args, ctx: TablessActionContext) => {
56
+ if (typeof args.text === 'string') {
57
+ ctx.service.setClipboardText(args.text, 'agent');
58
+ return { summary: `clipboard set (${args.text.length} char(s))` };
59
+ }
60
+
61
+ const text = ctx.service.getClipboardText();
62
+ if (!text) return { summary: 'clipboard is empty' };
63
+ return { summary: `clipboard holds ${text.length} char(s)`, detail: text };
64
+ }
65
+ };
66
+
67
+ export const dialogActions: ActionDef[] = [dialog, clipboard];
@@ -12,12 +12,14 @@ import { navigationActions } from './navigation';
12
12
  import { inputActions } from './input';
13
13
  import { inspectActions } from './inspect';
14
14
  import { consoleActions } from './console';
15
+ import { dialogActions } from './dialogs';
15
16
 
16
17
  /** Grouped for the documentation; order is the order an agent meets them. */
17
18
  export const ACTION_GROUPS: Array<{ title: string; actions: ActionDef[] }> = [
18
- { title: 'Tabs & viewport', actions: tabActions },
19
+ { title: 'Tabs & device', actions: tabActions },
19
20
  { title: 'Navigation & waiting', actions: navigationActions },
20
21
  { title: 'Input (mouse, keyboard, touch)', actions: inputActions },
22
+ { title: 'Dialogs & clipboard', actions: dialogActions },
21
23
  { title: 'Inspection', actions: inspectActions },
22
24
  { title: 'Console', actions: consoleActions }
23
25
  ];
@@ -32,7 +32,7 @@ export const type_: ActionDef = {
32
32
  kind: 'input',
33
33
  doc: `type {text, selector?|x,y?, clearFirst?, key?} — type into the focused field.
34
34
  Give a selector/coords to focus a field first, so one batch can fill a whole form without interleaving clicks.
35
- clearFirst defaults to true (selects all, then overwrites). Set false to append.
35
+ clearFirst defaults to true: the field is emptied first and read back afterwards, so leftover text is caught and fixed rather than typed beside. Set false to append.
36
36
  For a single key use \`key\` (Enter, Tab, Escape, ArrowDown…); for a chord use the \`press\` action.`,
37
37
  schema: z.object({
38
38
  type: z.literal('type'),
@@ -58,7 +58,7 @@ export const press: ActionDef = {
58
58
  type: 'press',
59
59
  kind: 'input',
60
60
  doc: `press {keys} — a key chord: "Control+A", "Meta+Shift+P", "Alt+ArrowLeft".
61
- Modifiers are held for the duration and released in reverse, which is what shortcuts and IDE-like pages expect.`,
61
+ Modifiers are held for the duration and released in reverse, which is what shortcuts and IDE-like pages expect. Editing chords (select all, copy, cut, undo, redo) work with Control or Meta on any host; Ctrl/⌘+V pastes the shared clipboard.`,
62
62
  schema: z.object({
63
63
  type: z.literal('press'),
64
64
  keys: z.string().describe('Chord, e.g. "Control+Shift+K". Aliases: Ctrl, Cmd, Command, Option, Meta.'),
@@ -70,11 +70,11 @@ export const press: ActionDef = {
70
70
  export const paste: ActionDef = {
71
71
  type: 'paste',
72
72
  kind: 'input',
73
- doc: `paste {text} — insert text into the focused field as a paste.
74
- Faster than \`type\` for long strings, and raises the same input events. Note this pastes the given text, not the user's clipboard.`,
73
+ doc: `paste {text?} — paste into the focused field: a real \`paste\` event (what spreadsheets and rich editors listen for), then the text at the caret unless the page handled it.
74
+ Omit text to paste the clipboard. The clipboard is shared with the page and the user's device: a page's "Copy" button, Ctrl/⌘+C and the user's own copies all land in it, and Ctrl/⌘+V via \`press\` pastes it too.`,
75
75
  schema: z.object({
76
76
  type: z.literal('paste'),
77
- text: z.string().describe('Text to insert at the caret.'),
77
+ text: z.string().optional().describe('Text to paste. Omit to paste the clipboard.'),
78
78
  ...commonFields
79
79
  }),
80
80
  toInput: (a) => ({ type: 'paste', text: a.text })
@@ -16,20 +16,111 @@ import { browserMcpControl } from '$backend/preview';
16
16
  import { debug } from '$shared/utils/logger';
17
17
  import type { ActionDef, TablessActionContext } from './types';
18
18
  import { commonFields } from './shared';
19
+ import {
20
+ DEVICE_MODEL_IDS,
21
+ DEVICE_PRESETS,
22
+ DEVICE_SIZES,
23
+ VIEWPORT_LIMITS,
24
+ canRotate,
25
+ defaultRotation,
26
+ getDeviceEmulation,
27
+ getDevicePreset,
28
+ type DeviceSize
29
+ } from '$shared/constants/preview';
30
+ import type { BrowserTab } from '$backend/preview/browser/types';
31
+ import type { EmulationPatch } from '$backend/preview/browser/viewport';
19
32
 
20
- const DEVICE_SIZES = ['desktop', 'laptop', 'tablet', 'mobile'] as const;
21
33
  const ROTATIONS = ['portrait', 'landscape'] as const;
22
34
 
23
- /** Devices that read as held rather than sat in front of. */
24
- function defaultRotation(deviceSize: string): 'portrait' | 'landscape' {
25
- return deviceSize === 'desktop' || deviceSize === 'laptop' ? 'landscape' : 'portrait';
35
+ const DEVICE_DOC = `device: a model — ${DEVICE_MODEL_IDS.join(' · ')} — sets its class, size, mockup and emulation (list_devices for sizes).
36
+ deviceSize: desktop · laptop (default) · tablet · mobile · responsive (no mockup, any size); picks the class's default model.
37
+ width+height (${VIEWPORT_LIMITS.min}–${VIEWPORT_LIMITS.max}) set an exact size on the current model and decide the orientation themselves.
38
+ touch, mobile (true/false/"auto"): touch events and the mobile viewport (<meta viewport>, overlay scrollbars) — on for tablet/mobile by default; changing either reloads the page.
39
+ colorScheme ("light"/"dark"/"auto"), reducedMotion ("reduce"/"no-preference"/"auto"): emulated media features.`;
40
+
41
+ const sizeField = (what: string) =>
42
+ z.number().int().min(VIEWPORT_LIMITS.min).max(VIEWPORT_LIMITS.max).optional().describe(`Exact viewport ${what} in CSS pixels. Give with the other dimension.`);
43
+
44
+ /** Device settings shared by open_tab and set_viewport. */
45
+ const deviceFields = {
46
+ device: z.enum(DEVICE_MODEL_IDS).optional().describe('Device model id.'),
47
+ deviceSize: z.enum(DEVICE_SIZES).optional().describe('Device class; its default model.'),
48
+ rotation: z.enum(ROTATIONS).optional().describe('Orientation.'),
49
+ width: sizeField('width'),
50
+ height: sizeField('height'),
51
+ touch: z.union([z.boolean(), z.literal('auto')]).optional().describe('Touch input; "auto" = device default.'),
52
+ mobile: z.union([z.boolean(), z.literal('auto')]).optional().describe('Mobile viewport; "auto" = device default.'),
53
+ colorScheme: z.enum(['light', 'dark', 'auto']).optional().describe('prefers-color-scheme.'),
54
+ reducedMotion: z.enum(['reduce', 'no-preference', 'auto']).optional().describe('prefers-reduced-motion.')
55
+ };
56
+
57
+ interface DeviceArgs {
58
+ device?: string;
59
+ deviceSize?: DeviceSize;
60
+ rotation?: 'portrait' | 'landscape';
61
+ width?: number;
62
+ height?: number;
63
+ touch?: boolean | 'auto';
64
+ mobile?: boolean | 'auto';
65
+ colorScheme?: 'light' | 'dark' | 'auto';
66
+ reducedMotion?: 'reduce' | 'no-preference' | 'auto';
67
+ }
68
+
69
+ /** An exact size only counts when both halves of it were given. */
70
+ function exactSize(args: DeviceArgs) {
71
+ if ((args.width === undefined) !== (args.height === undefined)) {
72
+ throw new Error('width and height go together — give both, or neither');
73
+ }
74
+ return args.width && args.height ? { width: args.width, height: args.height } : null;
75
+ }
76
+
77
+ /** The class a request names, checking a model and a class do not disagree. */
78
+ function requestedClass(args: DeviceArgs): DeviceSize | undefined {
79
+ const preset = getDevicePreset(args.device);
80
+ if (args.device && !preset) throw new Error(`Unknown device '${args.device}' — see list_devices`);
81
+ if (preset && args.deviceSize && args.deviceSize !== preset.deviceSize) {
82
+ throw new Error(`'${args.device}' is a ${preset.deviceSize}, not a ${args.deviceSize}`);
83
+ }
84
+ return preset?.deviceSize ?? args.deviceSize;
85
+ }
86
+
87
+ /** A laptop's screen is hinged to its keyboard; it cannot stand up. */
88
+ function checkRotation(deviceSize: DeviceSize, args: DeviceArgs) {
89
+ const portraitSize = args.width && args.height && args.height > args.width;
90
+ if (!canRotate(deviceSize) && (args.rotation === 'portrait' || portraitSize)) {
91
+ throw new Error(`a ${deviceSize} cannot be portrait — use a monitor (desktop), a tablet, or responsive for a tall viewport`);
92
+ }
93
+ }
94
+
95
+ /** "auto" hands a setting back to the device; absent leaves it alone. */
96
+ function emulationPatch(args: DeviceArgs): EmulationPatch {
97
+ const auto = <T>(value: T | 'auto' | undefined): T | null | undefined => (value === 'auto' ? null : value);
98
+ return {
99
+ touch: auto(args.touch),
100
+ mobile: auto(args.mobile),
101
+ colorScheme: auto(args.colorScheme),
102
+ reducedMotion: auto(args.reducedMotion)
103
+ };
104
+ }
105
+
106
+ /** One line describing everything about a tab's device. */
107
+ function describeDevice(tab: BrowserTab): string {
108
+ const model = getDevicePreset(tab.deviceModel)?.label ?? tab.deviceSize;
109
+ const { isMobile, hasTouch } = getDeviceEmulation(tab.deviceSize, tab.emulation);
110
+ const settings = [
111
+ hasTouch ? 'touch' : 'no touch',
112
+ isMobile ? 'mobile viewport' : 'desktop viewport',
113
+ tab.emulation.colorScheme && `color-scheme ${tab.emulation.colorScheme}`,
114
+ tab.emulation.reducedMotion && `reduced-motion ${tab.emulation.reducedMotion}`
115
+ ].filter(Boolean);
116
+ return `${model} ${tab.rotation} ${tab.viewport.width}×${tab.viewport.height} · ${settings.join(', ')}`;
26
117
  }
27
118
 
28
119
  export const listTabs: ActionDef = {
29
120
  type: 'list_tabs',
30
121
  kind: 'control',
31
122
  activity: 'Checking tabs',
32
- doc: `list_tabs {} — every open tab with its id, URL, viewport and who controls it.
123
+ doc: `list_tabs {} — every open tab with its id, URL, device and who controls it.
33
124
  Use the id, not the position, with switch_tab/close_tab.`,
34
125
  schema: z.object({ type: z.literal('list_tabs'), ...commonFields }),
35
126
  needsTab: false,
@@ -40,10 +131,16 @@ export const listTabs: ActionDef = {
40
131
  const lines = tabs.map((tab, index) => {
41
132
  const owner = browserMcpControl.getTabOwner(tab.id);
42
133
  const control = owner ? (owner === ctx.chatSessionId ? ' [yours]' : ' [another session]') : '';
134
+ const opener =
135
+ tab.openedBy?.kind === 'agent'
136
+ ? tab.openedBy.chatSessionId === ctx.chatSessionId
137
+ ? ' [opened by you]'
138
+ : ' [opened by another chat]'
139
+ : ' [opened by the user]';
43
140
  return [
44
- `${index + 1}. ${tab.isActive ? '*' : ' '} ${tab.id}${control} — ${tab.title || 'Untitled'}`,
141
+ `${index + 1}. ${tab.isActive ? '*' : ' '} ${tab.id}${control}${opener} — ${tab.title || 'Untitled'}`,
45
142
  ` ${tab.url || '(empty)'}`,
46
- ` ${tab.deviceSize}/${tab.rotation}${tab.isLoading ? ' · loading' : ''}`
143
+ ` ${describeDevice(tab)}${tab.isLoading ? ' · loading' : ''}`
47
144
  ].join('\n');
48
145
  });
49
146
 
@@ -55,27 +152,31 @@ export const openTab: ActionDef = {
55
152
  type: 'open_tab',
56
153
  kind: 'control',
57
154
  activity: 'Opening a tab',
58
- doc: `open_tab {url?, deviceSize?, rotation?} — open a tab and make it the target.
59
- deviceSize: desktop 1920×1080 · laptop 1440×900 (default) · tablet 834×1194 · mobile 402×874.
60
- rotation defaults to landscape for desktop/laptop, portrait for tablet/mobile.`,
155
+ doc: `open_tab {url?, device?, deviceSize?, rotation?, width?, height?, touch?, mobile?, colorScheme?, reducedMotion?} — open a tab and make it the target.
156
+ Device settings as for set_viewport. rotation defaults to the device's natural one.`,
61
157
  schema: z.object({
62
158
  type: z.literal('open_tab'),
63
159
  url: z.string().url().optional().describe('URL to load, including protocol. Omit for a blank tab.'),
64
- deviceSize: z.enum(DEVICE_SIZES).optional().describe('Viewport preset (default: laptop).'),
65
- rotation: z.enum(ROTATIONS).optional().describe('Orientation. Omit for the device default.'),
160
+ ...deviceFields,
66
161
  ...commonFields
67
162
  }),
68
163
  needsTab: false,
69
164
  run: async (args, ctx: TablessActionContext) => {
70
- const deviceSize = args.deviceSize || 'laptop';
165
+ const deviceSize = requestedClass(args) ?? 'laptop';
166
+ checkRotation(deviceSize, args);
71
167
  const rotation = args.rotation || defaultRotation(deviceSize);
72
168
 
73
- const tab = await ctx.service.createTab(args.url || undefined, deviceSize, rotation);
169
+ const tab = await ctx.service.createTab(args.url || undefined, deviceSize, rotation, undefined, exactSize(args), {
170
+ deviceModel: args.device,
171
+ emulation: emulationPatch(args)
172
+ });
173
+ tab.openedBy = { kind: 'agent', chatSessionId: ctx.chatSessionId };
74
174
  browserMcpControl.acquireControl(tab.id, ctx.chatSessionId, ctx.projectId);
75
175
  ctx.invalidateTab();
76
176
 
77
- debug.log('mcp', `📑 Opened tab ${tab.id} (${deviceSize}/${rotation})`);
78
- return { summary: `${tab.id} · ${tab.url || '(blank)'} · ${deviceSize}/${rotation}` };
177
+ const device = describeDevice(tab);
178
+ debug.log('mcp', `📑 Opened tab ${tab.id} (${device})`);
179
+ return { summary: `${tab.id} · ${tab.url || '(blank)'} · ${device}` };
79
180
  }
80
181
  };
81
182
 
@@ -116,7 +217,8 @@ export const closeTab: ActionDef = {
116
217
  type: 'close_tab',
117
218
  kind: 'control',
118
219
  activity: 'Closing a tab',
119
- doc: `close_tab {tabId?} — close a tab (default: the current one).`,
220
+ doc: `close_tab {tabId?} — close a tab (default: the current one).
221
+ Close every tab you opened once you are done with it. Keep one open only if this chat will use it again, it is waiting on the user (a login, an OTP, a captcha), or the user asked for it. Never close a tab the user opened unless asked.`,
120
222
  schema: z.object({
121
223
  type: z.literal('close_tab'),
122
224
  tabId: z.string().optional().describe('Tab id from list_tabs. Omit to close the current tab.'),
@@ -139,27 +241,54 @@ export const closeTab: ActionDef = {
139
241
  }
140
242
  };
141
243
 
244
+ export const listDevices: ActionDef = {
245
+ type: 'list_devices',
246
+ kind: 'control',
247
+ activity: 'Checking devices',
248
+ doc: `list_devices {} — every device model with its class, system and size, and the current tab's device settings.`,
249
+ schema: z.object({ type: z.literal('list_devices'), ...commonFields }),
250
+ needsTab: false,
251
+ run: async (_args, ctx: TablessActionContext) => {
252
+ const lines = DEVICE_PRESETS.map(
253
+ (preset) => `${preset.id} — ${preset.label} · ${preset.deviceSize} · ${preset.os} · ${preset.width}×${preset.height}`
254
+ );
255
+ lines.push('responsive — no mockup, any size (width/height)');
256
+
257
+ const active = ctx.service.getActiveTab();
258
+ if (active) lines.push('', `current tab ${active.id}: ${describeDevice(active)}`);
259
+
260
+ return { summary: `${DEVICE_PRESETS.length} device models`, detail: lines.join('\n') };
261
+ }
262
+ };
263
+
142
264
  export const setViewport: ActionDef = {
143
265
  type: 'set_viewport',
144
266
  kind: 'control',
145
- activity: 'Changing the viewport',
146
- doc: `set_viewport {deviceSize?, rotation?} — resize the current tab.
147
- Changing this re-runs the page's media queries, so it is how responsive layouts get tested.`,
267
+ activity: 'Changing the device',
268
+ doc: `set_viewport {device?, deviceSize?, rotation?, width?, height?, touch?, mobile?, colorScheme?, reducedMotion?} — change the current tab's device; anything left out stays as it is.
269
+ ${DEVICE_DOC}
270
+ rotation alone turns the current size around; laptops stay landscape. Any of this re-runs the page's media queries, so it is how responsive layouts get tested.`,
148
271
  schema: z.object({
149
272
  type: z.literal('set_viewport'),
150
- deviceSize: z.enum(DEVICE_SIZES).optional().describe('Omit to keep the current size.'),
151
- rotation: z.enum(ROTATIONS).optional().describe('Omit to keep the current orientation.'),
273
+ ...deviceFields,
152
274
  ...commonFields
153
275
  }),
154
276
  run: async (args, ctx) => {
155
- const deviceSize = args.deviceSize || ctx.tab.deviceSize;
156
- const rotation = args.rotation || ctx.tab.rotation;
277
+ const deviceSize = requestedClass(args) ?? ctx.tab.deviceSize;
278
+ checkRotation(deviceSize, args);
157
279
 
158
- const ok = await ctx.service.setViewport(ctx.tab.id, deviceSize, rotation);
159
- if (!ok) throw new Error(`Could not resize tab '${ctx.tab.id}'`);
280
+ const ok = await ctx.service.setViewport(ctx.tab.id, {
281
+ deviceSize,
282
+ rotation: args.rotation,
283
+ size: exactSize(args),
284
+ deviceModel: args.device,
285
+ emulation: emulationPatch(args)
286
+ });
287
+ if (!ok) throw new Error(`Could not change the device of tab '${ctx.tab.id}'`);
160
288
 
161
- return { summary: `${deviceSize}/${rotation}` };
289
+ const tab = ctx.service.getTab(ctx.tab.id) ?? ctx.tab;
290
+ return { summary: describeDevice(tab) };
162
291
  }
163
292
  };
164
293
 
165
- export const tabActions: ActionDef[] = [listTabs, openTab, switchTab, closeTab, setViewport];
294
+ export const tabActions: ActionDef[] = [listTabs, openTab, switchTab, closeTab, listDevices, setViewport];
@@ -114,6 +114,7 @@ export async function getActiveTabSession(
114
114
 
115
115
  debug.log('mcp', `📑 No tab open for project ${resolvedProjectId} — opening a blank one`);
116
116
  const tab = await service.createTab(undefined, 'laptop', 'landscape');
117
+ tab.openedBy = { kind: 'agent', chatSessionId };
117
118
  browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
118
119
 
119
120
  return { tab, service, opened: true };
@@ -16,13 +16,15 @@ Everything is one call. Pass an array of actions and they run in order, which is
16
16
  HOW TO USE IT WELL
17
17
 
18
18
  1. Batch. Put every step you can predict into one call: open_tab → wait_for → click → type → click → screenshot is a single call, not six. Split only where the next step depends on something you must read first.
19
- 2. Target by selector or text, not coordinates. Elements are resolved in every frame, scrolled into view, and aimed at their centre — coordinates go stale the moment the page reflows. Use \`find\` when you are unsure what to name; use x/y only for canvases and images.
19
+ 2. Target by selector or text, not coordinates. Elements are resolved in every frame, scrolled into view, and aimed at their centre — coordinates go stale the moment the page reflows. Text targeting prefers an exact match on something clickable that is actually on top (a modal's button over the paragraph that mentions it); use \`find\` when you are unsure what to name; use x/y only for canvases and images.
20
20
  3. Read with analyze_dom, not screenshots. Text, links and structure come back as text, for the whole document, at a fraction of the cost. Screenshot when the answer is visual: canvas, charts, layout, iframes, captchas.
21
21
  4. Navigate by URL. If analyze_dom gave you an href, \`navigate\` to it. Clicking a link to move around is slower and fails more.
22
22
  5. Synchronise with wait_for, not wait. wait_for returns the instant the condition holds; a fixed delay is either too short (the batch fails) or too long (every run pays for it).
23
23
  6. Failure stops the batch. Anything after a failed action is skipped and reported as skipped. Mark a step \`optional: true\` when it may legitimately not apply — dismissing a cookie banner that might not be there — or set onError:"continue" for genuinely independent steps.
24
24
  7. Obstacles are yours to clear. Captcha, modal, cookie wall: solve or dismiss it and carry on. Do not stop to ask.
25
25
  8. Check the report. Every action reports its own outcome, and the report ends with the tab and URL you left behind. If a result contradicts your plan, say so and re-plan rather than continuing on the assumption it worked.
26
+ 9. Native dialogs are yours. When a page opens alert / confirm / prompt, the report says DIALOG OPEN and quotes it; nothing else runs until you answer with the dialog action. Decide as the user would — nobody else will.
27
+ 10. Clean up your tabs. Close every tab you opened once you are done with it; the report lists the ones still open. Keep one only if this chat will use it again, it is waiting on the user (a login, an OTP, a captcha), or the user asked for it. Never close a tab the user opened unless asked.
26
28
 
27
29
  WORKFLOWS
28
30
 
@@ -35,7 +37,8 @@ Fill a form
35
37
  [{type, selector:"#email", text:"…"}, {type, selector:"#password", text:"…"}, {click, selector:"button[type=submit]"}, {wait_for, urlContains:"/dashboard"}]
36
38
 
37
39
  Check a layout on mobile
38
- [{set_viewport, deviceSize:"mobile"}, {wait_for, state:"networkIdle"}, {screenshot}]
40
+ [{set_viewport, device:"iphone-16"}, {wait_for, state:"networkIdle"}, {screenshot}]
41
+ Same page on Android in dark mode: [{set_viewport, device:"galaxy-s24", colorScheme:"dark"}, {screenshot}]
39
42
 
40
43
  Debug a page that misbehaves
41
44
  [{clear_console}, {click, selector:"#save"}, {wait, ms:500}, {console_logs, level:"error"}]`;
@@ -38,7 +38,30 @@ export function formatReport(report: RunReport): {
38
38
  if (report.aborted) {
39
39
  lines.push('', 'Interrupted: the chat stream was cancelled, so the remaining actions did not run.');
40
40
  } else if (report.skipped > 0) {
41
- lines.push('', `${report.skipped} action(s) skipped after the failure above (onError defaults to "stop").`);
41
+ lines.push(
42
+ '',
43
+ report.dialog
44
+ ? `${report.skipped} action(s) skipped: the page is paused on the dialog below.`
45
+ : `${report.skipped} action(s) skipped after the failure above (onError defaults to "stop").`
46
+ );
47
+ }
48
+
49
+ if (report.dialog) {
50
+ const { tabId, type, message, defaultValue } = report.dialog;
51
+ const prompt = type === 'prompt' ? `, text:"…"` : '';
52
+ lines.push(
53
+ '',
54
+ `DIALOG OPEN on ${tabId} — ${type}: ${JSON.stringify(message)}${type === 'prompt' && defaultValue ? ` (default ${JSON.stringify(defaultValue)})` : ''}`,
55
+ `The page runs nothing until it is answered. Decide as the user would and reply with {type:"dialog", response:"accept"|"dismiss"${prompt}}.`
56
+ );
57
+ }
58
+
59
+ if (report.agentTabs?.length) {
60
+ const listed = report.agentTabs.map((tab) => `${tab.id} (${tab.url || 'blank'})`).join(', ');
61
+ lines.push(
62
+ '',
63
+ `Tabs you opened that are still open: ${listed}. Close each with close_tab once you are done — keep one only if this chat will use it again, it is waiting on the user, or the user asked to keep it.`
64
+ );
42
65
  }
43
66
 
44
67
  const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [
@@ -18,6 +18,7 @@
18
18
  */
19
19
 
20
20
  import type { BrowserAutonomousAction, BrowserTab } from '$backend/preview/browser/types';
21
+ import type { PendingDialogInfo } from '$backend/preview/browser/browser-dialog-handler';
21
22
  import { projectContextService } from '$backend/mcp/internal/project-context';
22
23
  import { debug } from '$shared/utils/logger';
23
24
  import { ACTIONS_BY_TYPE } from './actions/index';
@@ -57,6 +58,10 @@ export interface RunReport {
57
58
  url?: string;
58
59
  /** Set when the batch had to open a tab because the browser had none. */
59
60
  openedTabId?: string;
61
+ /** A dialog the page is blocked on — the agent has to answer it next. */
62
+ dialog?: PendingDialogInfo & { tabId: string };
63
+ /** Tabs this chat session opened that are still open, for the close-when-done nudge. */
64
+ agentTabs?: Array<{ id: string; url: string }>;
60
65
  }
61
66
 
62
67
  /** Consecutive input gestures form one native run; control actions stand alone. */
@@ -139,7 +144,9 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
139
144
 
140
145
  // Check every step this group produced, not just the last: one native
141
146
  // run can fail in the middle and still finish with a successful action.
142
- stopped = report.steps.slice(before).some((step) => !step.ok && !tolerates(step));
147
+ // A dialog stops the batch whatever `optional` says: the page runs
148
+ // nothing until it is answered, so every later step would only hang.
149
+ stopped = !!report.dialog || report.steps.slice(before).some((step) => !step.ok && !tolerates(step));
143
150
  }
144
151
 
145
152
  report.failed = report.steps.some((step) => !step.ok && !tolerates(step));
@@ -155,11 +162,22 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
155
162
  if (current) {
156
163
  report.tabId = current.id;
157
164
  report.url = current.page.url();
165
+
166
+ // A dialog can open after the last action returned (an alert on a
167
+ // timer, a response handler). The next call would find the page
168
+ // paused with no idea why, so it is reported now.
169
+ const open = report.dialog ? null : service.getPendingDialog(current.id);
170
+ if (open) report.dialog = { ...open, tabId: current.id };
158
171
  }
159
172
  } catch {
160
173
  // No tab left (closed by the batch, or none was ever open).
161
174
  }
162
175
 
176
+ report.agentTabs = service
177
+ .getAllTabs()
178
+ .filter((candidate) => candidate.openedBy?.kind === 'agent' && candidate.openedBy.chatSessionId === chatSessionId)
179
+ .map((candidate) => ({ id: candidate.id, url: candidate.page.isClosed() ? candidate.url : candidate.page.url() }));
180
+
163
181
  return report;
164
182
  }
165
183
 
@@ -194,12 +212,54 @@ async function runControl(item: { index: number; args: ActionArgs }, deps: RunDe
194
212
  // themselves from inside the engine (see ActionDef.activity); a control
195
213
  // action has no gesture, and is often the longest step in a batch — a
196
214
  // 30-second `wait_for` with a silent cursor on it reads as a hang.
215
+ // A page with a dialog open evaluates nothing and paints nothing, so a
216
+ // read or a screenshot would hang until someone answered. Only the
217
+ // tab-level actions and `dialog` itself still make sense.
218
+ const guarded = tab && def.needsTab !== false && def.type !== 'dialog';
219
+ const open = guarded ? deps.service.getPendingDialog(tab.id) : null;
220
+ if (tab && open) {
221
+ report.dialog = { ...open, tabId: tab.id };
222
+ report.steps.push({
223
+ index: item.index,
224
+ type: def.type,
225
+ ok: false,
226
+ error: `a ${open.type} dialog is open — answer it with the dialog action first`
227
+ });
228
+ return 1;
229
+ }
230
+
197
231
  if (tab && def.activity) {
198
232
  labelled = tab.id;
199
233
  browserMcpControl.emitActivity(tab.id, def.activity);
200
234
  }
201
235
 
202
- const output = await def.run(item.args, deps.makeContext(tab));
236
+ const running = def.run(item.args, deps.makeContext(tab));
237
+ const watch = guarded && tab ? deps.service.waitForDialog(tab.id) : null;
238
+ let winner: { kind: 'done'; output: Awaited<typeof running> } | { kind: 'dialog'; info: PendingDialogInfo };
239
+ try {
240
+ winner = await Promise.race([
241
+ running.then((output) => ({ kind: 'done' as const, output })),
242
+ ...(watch ? [watch.promise.then((info) => ({ kind: 'dialog' as const, info }))] : [])
243
+ ]);
244
+ } finally {
245
+ watch?.dispose();
246
+ }
247
+
248
+ if (winner.kind === 'dialog') {
249
+ // The action is parked behind the dialog and finishes on its own once
250
+ // it is answered; nothing here waits for that.
251
+ running.catch(() => {});
252
+ report.dialog = { ...winner.info, tabId: tab!.id };
253
+ report.steps.push({
254
+ index: item.index,
255
+ type: def.type,
256
+ ok: false,
257
+ error: `interrupted: a ${winner.info.type} dialog opened`
258
+ });
259
+ return 1;
260
+ }
261
+
262
+ const output = winner.output;
203
263
  report.steps.push({ index: item.index, type: def.type, ok: true, summary: output.summary, detail: output.detail });
204
264
  if (output.images?.length) report.images.push(...output.images);
205
265
  } catch (error) {
@@ -264,12 +324,17 @@ async function runInputGroup(items: Array<{ index: number; args: ActionArgs }>,
264
324
 
265
325
  const outcome = await deps.service.performAutonomousActions(tab.id, primitives, deps.signal);
266
326
 
327
+ if (outcome.blockedBy) report.dialog = { ...outcome.blockedBy, tabId: tab.id };
328
+
267
329
  // One engine result per primitive, in order.
268
330
  mapped.forEach((entry, position) => {
269
331
  const result = outcome.results[position];
270
332
  if (!result) {
271
333
  // The engine stopped before reaching this one.
272
- report.steps.push({ index: entry.index, type: entry.type, ok: false, error: 'did not run (batch stopped earlier)' });
334
+ const reason = outcome.blockedBy
335
+ ? 'did not run — the page is paused on a dialog'
336
+ : 'did not run (batch stopped earlier)';
337
+ report.steps.push({ index: entry.index, type: entry.type, ok: false, error: reason });
273
338
  return;
274
339
  }
275
340