@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
@@ -1,7 +1,8 @@
1
1
  import type { Browser, BrowserContext, Page, Target } from 'puppeteer';
2
2
  import { EventEmitter } from 'events';
3
- import { getViewportDimensions } from '$shared/constants/preview.js';
4
- import type { BrowserTab, BrowserTabInfo, DeviceSize, Rotation } from './types';
3
+ import { planDevice, type DeviceRequest } from '$shared/constants/preview.js';
4
+ import type { BrowserTab, BrowserTabInfo, DeviceSize, Rotation, ViewportSize } from './types';
5
+ import { applyDevice, mergeEmulation, type EmulatedDevice, type EmulationPatch } from './viewport';
5
6
  import { DEFAULT_STREAMING_CONFIG } from './types';
6
7
  import { browserPool, type PooledSession } from './browser-pool';
7
8
  import { BrowserAudioCapture } from './browser-audio-capture';
@@ -194,8 +195,24 @@ export class BrowserTabManager extends EventEmitter {
194
195
  preNavigationSetup?: (page: Page, tabId: string) => Promise<void>;
195
196
  /** Client-minted name for this launch, so Stop can reach it. */
196
197
  launchId?: string;
198
+ /** An exact size; the model's own size when omitted. */
199
+ viewport?: ViewportSize | null;
200
+ /** The device model; the class default when omitted. */
201
+ deviceModel?: string | null;
202
+ /** Device settings on top of the model. */
203
+ emulation?: EmulationPatch | null;
197
204
  }
198
205
  ): Promise<BrowserTab> {
206
+ const device = planDevice(null, {
207
+ deviceSize,
208
+ rotation,
209
+ size: options?.viewport,
210
+ deviceModel: options?.deviceModel
211
+ });
212
+ const { viewport, deviceModel } = device;
213
+ rotation = device.rotation;
214
+ const emulation = mergeEmulation({}, options?.emulation);
215
+
199
216
  // The counter restarts per workspace, so the scope token is what stops a
200
217
  // worktree's `tab-1` from being matched as the main tree's on the client.
201
218
  const tabId = `tab-${scopeSlug(this.projectId)}-${this.nextTabNumber++}`;
@@ -244,7 +261,7 @@ export class BrowserTabManager extends EventEmitter {
244
261
 
245
262
  // Setup page (viewport, headers, etc.)
246
263
  debug.log('preview', `⚙️ Setting up page...`);
247
- await this.setupPage(page, deviceSize, rotation);
264
+ await this.setupPage(page, { deviceSize, viewport, emulation });
248
265
  debug.log('preview', `✅ Page setup complete`);
249
266
 
250
267
  // Run pre-navigation setup if provided (e.g., dialog handling)
@@ -295,6 +312,9 @@ export class BrowserTabManager extends EventEmitter {
295
312
  // Device
296
313
  deviceSize,
297
314
  rotation,
315
+ viewport,
316
+ deviceModel,
317
+ emulation,
298
318
 
299
319
  // Console
300
320
  consoleLogs: [],
@@ -342,6 +362,9 @@ export class BrowserTabManager extends EventEmitter {
342
362
  isActive: tab.isActive,
343
363
  deviceSize: tab.deviceSize,
344
364
  rotation: tab.rotation,
365
+ width: tab.viewport.width,
366
+ height: tab.viewport.height,
367
+ deviceModel: tab.deviceModel,
345
368
  // Echoed so the client can tie this tab to the launch it started,
346
369
  // rather than guessing from "some tab is launching" — which stopped
347
370
  // being true the moment the user pressed Stop.
@@ -632,25 +655,39 @@ export class BrowserTabManager extends EventEmitter {
632
655
  }
633
656
 
634
657
  /**
635
- * Change viewport settings (device size and rotation) for an existing tab
658
+ * Change the device a tab is shown on: its class, model, orientation, exact
659
+ * size, and the device settings on top. See `planDevice` for how a partial
660
+ * request is completed; `emulation` fields left out keep their value and
661
+ * `null` hands them back to the device.
636
662
  */
637
- async setViewport(tabId: string, deviceSize: DeviceSize, rotation: Rotation): Promise<boolean> {
663
+ async setViewport(
664
+ tabId: string,
665
+ request: DeviceRequest & { emulation?: EmulationPatch | null }
666
+ ): Promise<boolean> {
638
667
  const tab = this.tabs.get(tabId);
639
668
  if (!tab) {
640
669
  debug.warn('preview', `❌ Cannot set viewport: Tab ${tabId} not found`);
641
670
  return false;
642
671
  }
643
672
 
644
- // Get new viewport dimensions
645
- const { width: viewportWidth, height: viewportHeight } = getViewportDimensions(deviceSize, rotation);
673
+ const next = planDevice(
674
+ { deviceSize: tab.deviceSize, rotation: tab.rotation, viewport: tab.viewport, deviceModel: tab.deviceModel },
675
+ request
676
+ );
677
+ const emulation = mergeEmulation(tab.emulation, request.emulation);
678
+ const { width: viewportWidth, height: viewportHeight } = next.viewport;
646
679
 
647
680
  try {
648
- // Update viewport on the page
649
- await tab.page.setViewport({ width: viewportWidth, height: viewportHeight });
681
+ // Metadata first: a touch or mobile change reloads the page, and
682
+ // anything that asks the tab for its viewport while that runs must
683
+ // get the new one.
684
+ tab.deviceSize = next.deviceSize;
685
+ tab.rotation = next.rotation;
686
+ tab.viewport = next.viewport;
687
+ tab.deviceModel = next.deviceModel;
688
+ tab.emulation = emulation;
650
689
 
651
- // Update tab metadata
652
- tab.deviceSize = deviceSize;
653
- tab.rotation = rotation;
690
+ await applyDevice(tab.page, tab);
654
691
 
655
692
  // Mark tab activity
656
693
  this.markTabActivity(tabId);
@@ -658,14 +695,15 @@ export class BrowserTabManager extends EventEmitter {
658
695
  // Emit viewport changed event
659
696
  this.emit('preview:browser-viewport-changed', {
660
697
  tabId,
661
- deviceSize,
662
- rotation,
698
+ deviceSize: next.deviceSize,
699
+ rotation: next.rotation,
663
700
  width: viewportWidth,
664
701
  height: viewportHeight,
702
+ deviceModel: next.deviceModel,
665
703
  timestamp: Date.now()
666
704
  });
667
705
 
668
- debug.log('preview', `📱 Viewport changed for tab ${tabId}: ${deviceSize} (${rotation}) - ${viewportWidth}x${viewportHeight}`);
706
+ debug.log('preview', `📱 Viewport changed for tab ${tabId}: ${next.deviceModel ?? next.deviceSize} (${next.rotation}) - ${viewportWidth}x${viewportHeight}`);
669
707
 
670
708
  return true;
671
709
  } catch (error) {
@@ -718,6 +756,10 @@ export class BrowserTabManager extends EventEmitter {
718
756
  isStreaming: tab.isStreaming,
719
757
  deviceSize: tab.deviceSize,
720
758
  rotation: tab.rotation,
759
+ width: tab.viewport.width,
760
+ height: tab.viewport.height,
761
+ deviceModel: tab.deviceModel,
762
+ emulation: tab.emulation,
721
763
  isActive: tab.isActive,
722
764
  canGoBack: tab.canGoBack,
723
765
  canGoForward: tab.canGoForward
@@ -737,6 +779,10 @@ export class BrowserTabManager extends EventEmitter {
737
779
  isStreaming: tab.isStreaming,
738
780
  deviceSize: tab.deviceSize,
739
781
  rotation: tab.rotation,
782
+ width: tab.viewport.width,
783
+ height: tab.viewport.height,
784
+ deviceModel: tab.deviceModel,
785
+ emulation: tab.emulation,
740
786
  isActive: tab.isActive,
741
787
  canGoBack: tab.canGoBack,
742
788
  canGoForward: tab.canGoForward
@@ -917,7 +963,7 @@ export class BrowserTabManager extends EventEmitter {
917
963
  tab.canGoBack = false;
918
964
  tab.canGoForward = false;
919
965
 
920
- await this.setupPage(pooled.page, tab.deviceSize, tab.rotation);
966
+ await this.setupPage(pooled.page, tab);
921
967
 
922
968
  const setupHook = this.tabSetupHooks.get(tabId);
923
969
  if (setupHook) {
@@ -983,11 +1029,8 @@ export class BrowserTabManager extends EventEmitter {
983
1029
  /**
984
1030
  * Setup page (viewport, headers, injections)
985
1031
  */
986
- private async setupPage(page: Page, deviceSize: DeviceSize, rotation: Rotation) {
987
- // Get viewport dimensions from config
988
- const { width: viewportWidth, height: viewportHeight } = getViewportDimensions(deviceSize, rotation);
989
-
990
- await page.setViewport({ width: viewportWidth, height: viewportHeight });
1032
+ private async setupPage(page: Page, device: EmulatedDevice) {
1033
+ await applyDevice(page, device);
991
1034
 
992
1035
  // Set page timeouts - more generous for stability
993
1036
  page.setDefaultTimeout(30000);
@@ -1630,7 +1673,7 @@ export class BrowserTabManager extends EventEmitter {
1630
1673
  debug.log('preview', `🧹 Cleaning up ${this.tabs.size} tabs...`);
1631
1674
 
1632
1675
  // Every page below is about to be closed on purpose; none of them is a
1633
- // crash to rebuild from. Restored at the end: an admin "clean up all"
1676
+ // crash to rebuild from. Restored at the end: a "clean up all"
1634
1677
  // leaves the manager in service, and the tabs opened after it must be
1635
1678
  // able to recover like any other.
1636
1679
  const wasShuttingDown = this.shuttingDown;
@@ -1678,7 +1721,7 @@ export class BrowserTabManager extends EventEmitter {
1678
1721
 
1679
1722
  // Deliberately NOT browserPool.cleanup(): that reaches every workspace's
1680
1723
  // Chrome, and calling it from one workspace's teardown — deleting a
1681
- // worktree, an admin "clean up all" — took every other project's
1724
+ // worktree, a "clean up all" — took every other project's
1682
1725
  // preview tabs down with it. Our own sessions are already gone with the
1683
1726
  // tabs above; the pool closes this workspace's Chrome once its last
1684
1727
  // session goes, and every Chrome on process shutdown.
@@ -41,6 +41,7 @@ import type {
41
41
  import { DEFAULT_STREAMING_CONFIG, resolveCodecCandidates } from './types';
42
42
  import { videoEncoderScript } from './scripts/video-stream';
43
43
  import { audioCaptureScript } from './scripts/audio-stream';
44
+ import { applyViewport } from './viewport';
44
45
 
45
46
  /**
46
47
  * Install the audio tap in every frame.
@@ -237,6 +238,19 @@ const DEFAULT_CODEC_SUPPORT: ClientCodecSupport = {
237
238
  hardware: []
238
239
  };
239
240
 
241
+ /** Aspect disagreement between the captured surface and the page that counts as drift. */
242
+ const SURFACE_DRIFT_TOLERANCE = 0.03;
243
+
244
+ /** How long a mismatch must last before it counts as drift rather than a resize in flight. */
245
+ const SURFACE_DRIFT_GRACE_MS = 250;
246
+
247
+ /** Minimum gap between two viewport restores asked for by the same tab. */
248
+ const SURFACE_DRIFT_COOLDOWN_MS = 1500;
249
+
250
+ /** Restores a tab may ask for within SURFACE_DRIFT_WINDOW_MS before frames are let through. */
251
+ const SURFACE_DRIFT_MAX_RESTORES = 3;
252
+ const SURFACE_DRIFT_WINDOW_MS = 30_000;
253
+
240
254
  /**
241
255
  * CDP screencast feeder with ack-gated flow control.
242
256
  *
@@ -264,6 +278,8 @@ class ScreencastFeeder {
264
278
  private lastDispatchAt = 0;
265
279
  private lastAckAt = 0;
266
280
  private pendingAckId: number | null = null;
281
+ /** When the surface first stopped matching the page, or 0. */
282
+ private driftSince = 0;
267
283
 
268
284
  constructor(
269
285
  private readonly cdp: CDPSession,
@@ -271,7 +287,9 @@ class ScreencastFeeder {
271
287
  private readonly getSession: () => VideoStreamSession | undefined,
272
288
  private readonly getTab: () => BrowserTab | undefined,
273
289
  private readonly onInvalidSession: () => void,
274
- private readonly isValidSession: () => boolean
290
+ private readonly isValidSession: () => boolean,
291
+ /** Returns whether a restore is under way (and the frame should be held back). */
292
+ private readonly onSurfaceDrift: (width: number, height: number) => boolean
275
293
  ) {
276
294
  this.cdp.on('Page.screencastFrame', (event: any) => this.handleFrame(event));
277
295
  }
@@ -407,6 +425,31 @@ class ScreencastFeeder {
407
425
  return;
408
426
  }
409
427
 
428
+ // A surface stranded by Chrome's fullscreen produces frames of the wrong
429
+ // shape. They are not forwarded — the viewer keeps the last good one —
430
+ // and the host is told so it can put the viewport back.
431
+ const surfaceWidth = Number(event.metadata?.deviceWidth) || 0;
432
+ const surfaceHeight = Number(event.metadata?.deviceHeight) || 0;
433
+ const viewport = tab?.page.viewport();
434
+ if (viewport && surfaceWidth > 0 && surfaceHeight > 0) {
435
+ const expected = viewport.width / viewport.height;
436
+ const drifted = Math.abs(surfaceWidth / surfaceHeight - expected) / expected > SURFACE_DRIFT_TOLERANCE;
437
+ if (!drifted) {
438
+ this.driftSince = 0;
439
+ } else {
440
+ // A device-size change leaves a frame or two of the old shape in
441
+ // flight; those are held back but are not worth a restore.
442
+ const now = Date.now();
443
+ if (!this.driftSince) this.driftSince = now;
444
+ const restoring =
445
+ now - this.driftSince < SURFACE_DRIFT_GRACE_MS || this.onSurfaceDrift(surfaceWidth, surfaceHeight);
446
+ if (restoring) {
447
+ this.ack(event.sessionId);
448
+ return;
449
+ }
450
+ }
451
+ }
452
+
410
453
  const now = Date.now();
411
454
  const interval = this.frameIntervalMs;
412
455
 
@@ -621,6 +664,12 @@ export class BrowserVideoCapture extends EventEmitter {
621
664
  private epochCounter = 0;
622
665
  private watchdogTimer: ReturnType<typeof setInterval> | null = null;
623
666
 
667
+ /** Per tab: when a surface drift last asked for a restore. */
668
+ private lastDriftReportAt = new Map<string, number>();
669
+
670
+ /** Per tab: restores asked for within the current window. */
671
+ private driftRestores = new Map<string, number[]>();
672
+
624
673
  constructor() {
625
674
  super();
626
675
  }
@@ -897,6 +946,11 @@ export class BrowserVideoCapture extends EventEmitter {
897
946
  this.applyEncoderStats(sessionId, stats);
898
947
  });
899
948
 
949
+ // The captured surface stopped matching the page — see video-stream.ts.
950
+ await expose('__reportSurfaceDrift', (width: number, height: number) => {
951
+ this.reportSurfaceDrift(sessionId, width, height);
952
+ });
953
+
900
954
  state.bindingsExposed = true;
901
955
  }
902
956
 
@@ -1373,7 +1427,8 @@ export class BrowserVideoCapture extends EventEmitter {
1373
1427
  () => {
1374
1428
  void this.stopStreaming(sessionId);
1375
1429
  },
1376
- isValidSession
1430
+ isValidSession,
1431
+ (width, height) => this.reportSurfaceDrift(sessionId, width, height)
1377
1432
  );
1378
1433
 
1379
1434
  this.feeders.set(sessionId, feeder);
@@ -2042,9 +2097,10 @@ export class BrowserVideoCapture extends EventEmitter {
2042
2097
  // ------------------------------------------------------------------
2043
2098
 
2044
2099
  /**
2045
- * Update viewport without reconnection (hot-swap)
2100
+ * Re-apply the tab's viewport and recompute the capture around it, without
2101
+ * reconnecting (hot-swap). The size is the tab's own — see `BrowserTab.viewport`.
2046
2102
  */
2047
- async updateViewport(sessionId: string, session: BrowserTab, width: number, height: number): Promise<boolean> {
2103
+ async updateViewport(sessionId: string, session: BrowserTab): Promise<boolean> {
2048
2104
  const videoSession = this.sessions.get(sessionId);
2049
2105
  if (!videoSession?.isActive || !session.page || session.page.isClosed()) {
2050
2106
  debug.warn('webcodecs', `Cannot update viewport: session not active`);
@@ -2052,11 +2108,12 @@ export class BrowserVideoCapture extends EventEmitter {
2052
2108
  }
2053
2109
 
2054
2110
  try {
2111
+ const { width, height } = session.viewport;
2055
2112
  debug.log('webcodecs', `🔄 Hot-swapping viewport to ${width}x${height}`);
2056
2113
 
2057
2114
  // The emulated viewport is what the page lays out against; capture
2058
2115
  // resolution is derived from it and the viewer's display metrics.
2059
- await session.page.setViewport({ width, height });
2116
+ await applyViewport(session.page, session);
2060
2117
 
2061
2118
  // Force a recompute even if the derived size happens to land close
2062
2119
  // to the previous one — the page content changed shape.
@@ -2069,6 +2126,34 @@ export class BrowserVideoCapture extends EventEmitter {
2069
2126
  }
2070
2127
  }
2071
2128
 
2129
+ /**
2130
+ * The captured surface no longer has the page's shape.
2131
+ *
2132
+ * Raised by the in-page encoder and by the screencast feeder; whoever owns
2133
+ * the tab re-asserts the viewport. Rate-limited per tab: the frames keep
2134
+ * arriving drifted until the restore lands, and each would otherwise ask
2135
+ * again.
2136
+ */
2137
+ private reportSurfaceDrift(sessionId: string, width: number, height: number): boolean {
2138
+ const now = Date.now();
2139
+ const recent = (this.driftRestores.get(sessionId) ?? []).filter(
2140
+ (at) => now - at < SURFACE_DRIFT_WINDOW_MS
2141
+ );
2142
+ this.driftRestores.set(sessionId, recent);
2143
+
2144
+ // A drift that keeps coming back after several restores is not one this
2145
+ // can fix; the caller stops holding frames back rather than freezing.
2146
+ if (recent.length >= SURFACE_DRIFT_MAX_RESTORES) return false;
2147
+
2148
+ if (now - (this.lastDriftReportAt.get(sessionId) ?? 0) < SURFACE_DRIFT_COOLDOWN_MS) return true;
2149
+ this.lastDriftReportAt.set(sessionId, now);
2150
+ recent.push(now);
2151
+
2152
+ debug.warn('webcodecs', `📐 Captured surface drifted to ${width}x${height} on ${sessionId}; restoring the viewport`);
2153
+ this.emit('surface-drift', { sessionId, width, height });
2154
+ return true;
2155
+ }
2156
+
2072
2157
  /**
2073
2158
  * Restart capture at the current geometry.
2074
2159
  * Used as a refresh/recovery path when the frontend detects a stuck stream.
@@ -2178,6 +2263,8 @@ export class BrowserVideoCapture extends EventEmitter {
2178
2263
  * Stop video streaming
2179
2264
  */
2180
2265
  async stopStreaming(sessionId: string, session?: BrowserTab): Promise<void> {
2266
+ this.lastDriftReportAt.delete(sessionId);
2267
+ this.driftRestores.delete(sessionId);
2181
2268
  const videoSession = this.sessions.get(sessionId);
2182
2269
  if (!videoSession) return;
2183
2270
 
@@ -68,24 +68,191 @@ interface ElementMeta {
68
68
  }
69
69
 
70
70
  /**
71
- * XPath that matches the *innermost* elements containing the text.
71
+ * Rank the elements of one frame that a piece of visible text could mean.
72
72
  *
73
- * Without the `not(.//*[...])` guard every ancestor up to <body> matches too,
74
- * and the first hit would be the whole document rather than the button the
75
- * agent meant.
73
+ * Runs inside the page, in a single round trip. Text alone is ambiguous in
74
+ * exactly the place agents use it most: "Click **Continue** to verify" sits
75
+ * right above a Continue button in the same modal, and taking the first match
76
+ * in document order clicked the bold word in the sentence. So every match is
77
+ * scored, the way a person picks the thing they meant:
78
+ *
79
+ * - **Exact** text beats a match that merely contains the words.
80
+ * - **Clickable** beats inert. A match inside a button, link, labelled
81
+ * control or `cursor: pointer` element is aimed at that element, not at
82
+ * the span holding the text.
83
+ * - **On top** beats covered: the element actually under its own centre is
84
+ * reachable; one behind a modal's backdrop is not.
85
+ * - Inside an open **dialog** beats the page behind it.
86
+ *
87
+ * Also matches what has no text node — `<input type=submit value=…>`,
88
+ * icon buttons named by `aria-label` or `title` — which a text search used to
89
+ * miss entirely.
90
+ *
91
+ * Self-contained on purpose: it is serialised into the page.
76
92
  */
77
- function innermostTextXPath(text: string): string {
78
- const escaped = xpathLiteral(text.toLowerCase());
79
- const lower = `translate(normalize-space(.), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;
80
- return `xpath///*[contains(${lower}, ${escaped}) and not(.//*[contains(${lower}, ${escaped})])]`;
93
+ function rankTextMatches(query: string, includeHidden: boolean, limit: number) {
94
+ const needle = query.replace(/\s+/g, ' ').trim().toLowerCase();
95
+ if (!needle) return [];
96
+
97
+ const norm = (value: string | null | undefined) => (value ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
98
+
99
+ const CLICKABLE_ROLES = new Set([
100
+ 'button', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'option',
101
+ 'checkbox', 'radio', 'switch', 'treeitem', 'gridcell'
102
+ ]);
103
+
104
+ const isClickable = (el: Element): boolean => {
105
+ const tag = el.tagName;
106
+ if (tag === 'BUTTON' || tag === 'SUMMARY' || tag === 'SELECT' || tag === 'LABEL') return true;
107
+ if (tag === 'A' && (el as HTMLAnchorElement).hasAttribute('href')) return true;
108
+ if (tag === 'INPUT') {
109
+ const type = ((el as HTMLInputElement).type || '').toLowerCase();
110
+ return ['button', 'submit', 'reset', 'checkbox', 'radio', 'image'].includes(type);
111
+ }
112
+ const role = el.getAttribute('role');
113
+ if (role && CLICKABLE_ROLES.has(role)) return true;
114
+ if (el.hasAttribute('onclick')) return true;
115
+ return false;
116
+ };
117
+
118
+ const isVisible = (el: Element): boolean => {
119
+ const rect = el.getBoundingClientRect();
120
+ if (rect.width <= 0 || rect.height <= 0) return false;
121
+ const style = window.getComputedStyle(el);
122
+ return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) !== 0;
123
+ };
124
+
125
+ /** The control a click on this text would actually be aimed at. */
126
+ const actionableFor = (el: Element): { target: Element; clickable: boolean } => {
127
+ let node: Element | null = el;
128
+ for (let depth = 0; node && depth < 6; depth++) {
129
+ if (isClickable(node)) return { target: node, clickable: true };
130
+ node = node.parentElement ?? ((node.getRootNode() as ShadowRoot).host || null);
131
+ }
132
+ // No semantic control — a styled div with a click handler still shows a
133
+ // pointer cursor, which is the only hint the page gives.
134
+ node = el;
135
+ for (let depth = 0; node && depth < 4; depth++) {
136
+ if (window.getComputedStyle(node).cursor === 'pointer') return { target: node, clickable: true };
137
+ node = node.parentElement;
138
+ }
139
+ return { target: el, clickable: false };
140
+ };
141
+
142
+ /** Deepest element under a point, through open shadow roots. */
143
+ const hitAt = (x: number, y: number): Element | null => {
144
+ let hit = document.elementFromPoint(x, y);
145
+ while (hit && (hit as HTMLElement).shadowRoot) {
146
+ const inner = (hit as HTMLElement).shadowRoot!.elementFromPoint(x, y);
147
+ if (!inner || inner === hit) break;
148
+ hit = inner;
149
+ }
150
+ return hit;
151
+ };
152
+
153
+ const inDialog = (el: Element): boolean =>
154
+ !!el.closest('dialog[open], [role="dialog"], [role="alertdialog"], [aria-modal="true"]');
155
+
156
+ // Innermost elements whose text contains the query: descend only into
157
+ // branches that contain it, and stop where no child does.
158
+ const textMatches: Element[] = [];
159
+ const visit = (root: Element | ShadowRoot) => {
160
+ for (const child of Array.from(root.children)) {
161
+ const tag = child.tagName;
162
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT' || tag === 'TEMPLATE') continue;
163
+ const shadow = (child as HTMLElement).shadowRoot;
164
+ const contains = norm(child.textContent).includes(needle);
165
+ if (shadow) visit(shadow);
166
+ if (!contains) continue;
167
+ const deeper = Array.from(child.children).some((grand) => norm(grand.textContent).includes(needle));
168
+ if (deeper) visit(child);
169
+ else textMatches.push(child);
170
+ }
171
+ };
172
+ if (document.body) visit(document.body);
173
+
174
+ // Elements named by an attribute rather than by text.
175
+ const named: Element[] = [];
176
+ for (const el of Array.from(document.querySelectorAll('input[type=submit], input[type=button], input[type=reset], [aria-label], [title]'))) {
177
+ const label = norm(
178
+ el.tagName === 'INPUT' ? (el as HTMLInputElement).value || el.getAttribute('aria-label') : el.getAttribute('aria-label') || el.getAttribute('title')
179
+ );
180
+ if (label.includes(needle)) named.push(el);
181
+ }
182
+
183
+ const order = new Map<Element, number>();
184
+ const scored = new Map<Element, { el: Element; score: number }>();
185
+ let position = 0;
186
+
187
+ for (const candidate of [...textMatches, ...named]) {
188
+ const { target, clickable } = actionableFor(candidate);
189
+ if (!order.has(target)) order.set(target, position++);
190
+ if (!includeHidden && !isVisible(target)) continue;
191
+
192
+ const ownText = norm(candidate.textContent) || norm(candidate.getAttribute('aria-label')) || norm((candidate as HTMLInputElement).value) || norm(candidate.getAttribute('title'));
193
+ const targetText = norm((target as HTMLElement).innerText ?? target.textContent);
194
+
195
+ let score = 0;
196
+ if (ownText === needle || targetText === needle) score += 100;
197
+ else if (ownText.startsWith(needle) || targetText.startsWith(needle)) score += 40;
198
+ else score += 10;
199
+
200
+ if (clickable) score += 50;
201
+ if ((target as HTMLButtonElement).disabled) score -= 30;
202
+ if (inDialog(target)) score += 20;
203
+
204
+ const rect = target.getBoundingClientRect();
205
+ const cx = rect.left + rect.width / 2;
206
+ const cy = rect.top + rect.height / 2;
207
+ if (cx >= 0 && cy >= 0 && cx <= window.innerWidth && cy <= window.innerHeight) {
208
+ const hit = hitAt(cx, cy);
209
+ if (hit && (target === hit || target.contains(hit))) score += 60;
210
+ else if (hit && !hit.contains(target)) score -= 80;
211
+ }
212
+
213
+ const previous = scored.get(target);
214
+ if (!previous || score > previous.score) scored.set(target, { el: target, score });
215
+ }
216
+
217
+ return Array.from(scored.values())
218
+ .sort((a, b) => b.score - a.score || (order.get(a.el) ?? 0) - (order.get(b.el) ?? 0))
219
+ .slice(0, limit);
81
220
  }
82
221
 
83
- /** XPath has no escape character; a mixed-quote string must be built with concat(). */
84
- function xpathLiteral(value: string): string {
85
- if (!value.includes("'")) return `'${value}'`;
86
- if (!value.includes('"')) return `"${value}"`;
87
- const parts = value.split("'").map((part) => `'${part}'`);
88
- return `concat(${parts.join(`, "'", `)})`;
222
+ /** Ranked text matches from every frame, best first. Caller disposes the handles. */
223
+ async function rankedTextHandles(
224
+ page: Page,
225
+ text: string,
226
+ opts: { includeHidden?: boolean; limit?: number } = {}
227
+ ): Promise<Array<{ handle: ElementHandle<Element>; frame: Frame; score: number }>> {
228
+ const found: Array<{ handle: ElementHandle<Element>; frame: Frame; score: number; frameIndex: number }> = [];
229
+ const frames = page.frames();
230
+
231
+ for (let frameIndex = 0; frameIndex < frames.length; frameIndex++) {
232
+ const frame = frames[frameIndex];
233
+ if (frame.isDetached()) continue;
234
+
235
+ try {
236
+ const list = await frame.evaluateHandle(rankTextMatches, text, !!opts.includeHidden, opts.limit ?? 20);
237
+ try {
238
+ const entries = await list.getProperties();
239
+ for (const entry of entries.values()) {
240
+ const el = (await entry.getProperty('el')) as ElementHandle<Element>;
241
+ const score = Number(await (await entry.getProperty('score')).jsonValue());
242
+ found.push({ handle: el, frame, score, frameIndex });
243
+ await entry.dispose().catch(() => {});
244
+ }
245
+ } finally {
246
+ await list.dispose().catch(() => {});
247
+ }
248
+ } catch {
249
+ // A frame that navigated mid-sweep must not abort the others.
250
+ }
251
+ }
252
+
253
+ // Best score wins across frames; the main frame breaks ties, then page order.
254
+ found.sort((a, b) => b.score - a.score || a.frameIndex - b.frameIndex);
255
+ return found.map(({ handle, frame, score }) => ({ handle, frame, score }));
89
256
  }
90
257
 
91
258
  /** Read everything the caller might want to show, in one round trip per element. */
@@ -153,6 +320,14 @@ async function readMeta(handle: ElementHandle<Element>): Promise<ElementMeta> {
153
320
 
154
321
  /** Collect candidate handles for a query, main frame first. */
155
322
  async function collectHandles(page: Page, query: LocateQuery): Promise<Array<{ handle: ElementHandle<Element>; frame: Frame }>> {
323
+ // Text is ranked, not listed in document order — see rankTextMatches.
324
+ if (query.text && !query.selector) {
325
+ return rankedTextHandles(page, query.text, {
326
+ includeHidden: query.visibleOnly === false,
327
+ limit: Math.max(query.limit ?? 20, (query.nth ?? 0) + 1)
328
+ });
329
+ }
330
+
156
331
  const found: Array<{ handle: ElementHandle<Element>; frame: Frame }> = [];
157
332
 
158
333
  for (const frame of page.frames()) {
@@ -163,8 +338,6 @@ async function collectHandles(page: Page, query: LocateQuery): Promise<Array<{ h
163
338
 
164
339
  if (query.selector) {
165
340
  handles.push(...(await frame.$$(query.selector)));
166
- } else if (query.text) {
167
- handles.push(...(await frame.$$(innermostTextXPath(query.text))));
168
341
  } else if (query.role) {
169
342
  // A role is expressed either explicitly or by the element itself:
170
343
  // `<button>` carries the button role without saying so. Both are
@@ -259,7 +432,7 @@ export async function resolveHandle(
259
432
  target: BrowserActionTarget,
260
433
  opts: { scrollIntoView?: boolean } = {}
261
434
  ): Promise<ElementHandle<Element> | null> {
262
- const candidates = await collectHandles(page, { selector: target.selector, text: target.text });
435
+ const candidates = await collectHandles(page, { selector: target.selector, text: target.text, nth: target.nth });
263
436
  if (candidates.length === 0) return null;
264
437
 
265
438
  const wanted = target.nth ?? 0;