@andorra-labs/code 0.1.12 → 0.1.14

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 (617) hide show
  1. package/dist/src/account-presentation.d.ts +1 -37
  2. package/dist/src/account-presentation.js +6 -43
  3. package/dist/src/activity.d.ts +0 -25
  4. package/dist/src/activity.js +1 -23
  5. package/dist/src/agent-definitions.d.ts +0 -26
  6. package/dist/src/agent-definitions.js +0 -43
  7. package/dist/src/agent-execution.d.ts +0 -2
  8. package/dist/src/agent-execution.js +347 -554
  9. package/dist/src/agent-mcp-catalog.d.ts +0 -8
  10. package/dist/src/agent-mcp-catalog.js +0 -2
  11. package/dist/src/agent-mcp.d.ts +0 -56
  12. package/dist/src/agent-mcp.js +11 -155
  13. package/dist/src/agent-modifiers.d.ts +0 -1
  14. package/dist/src/agent-modifiers.js +25 -68
  15. package/dist/src/analytics.d.ts +0 -66
  16. package/dist/src/analytics.js +0 -45
  17. package/dist/src/andorra/endpoint.d.ts +7 -0
  18. package/dist/src/andorra/endpoint.js +46 -0
  19. package/dist/src/andorra/entry.d.ts +21 -0
  20. package/dist/src/andorra/entry.js +100 -0
  21. package/dist/src/andorra/errors.d.ts +2 -0
  22. package/dist/src/andorra/errors.js +39 -0
  23. package/dist/src/andorra/hosted.d.ts +52 -0
  24. package/dist/src/andorra/hosted.js +126 -0
  25. package/dist/src/andorra/monitor.d.ts +151 -0
  26. package/dist/src/andorra/monitor.js +393 -0
  27. package/dist/src/andorra/notices.d.ts +7 -0
  28. package/dist/src/andorra/notices.js +15 -0
  29. package/dist/src/andorra/opt-in.d.ts +58 -0
  30. package/dist/src/andorra/opt-in.js +112 -0
  31. package/dist/src/andorra/request-watch.d.ts +6 -0
  32. package/dist/src/andorra/request-watch.js +10 -0
  33. package/dist/src/andorra/state.d.ts +86 -0
  34. package/dist/src/andorra/state.js +238 -0
  35. package/dist/src/andorra/terminal.d.ts +68 -0
  36. package/dist/src/andorra/terminal.js +125 -0
  37. package/dist/src/andorra/usage-format.d.ts +9 -0
  38. package/dist/src/andorra/usage-format.js +19 -0
  39. package/dist/src/anthropic-console-auth.d.ts +0 -24
  40. package/dist/src/anthropic-console-auth.js +0 -37
  41. package/dist/src/anthropic-credentials.d.ts +0 -25
  42. package/dist/src/anthropic-credentials.js +9 -29
  43. package/dist/src/app-server/protocol.d.ts +18 -246
  44. package/dist/src/app-server/protocol.js +1 -132
  45. package/dist/src/app-server/reasoning.d.ts +0 -31
  46. package/dist/src/app-server/reasoning.js +0 -54
  47. package/dist/src/app-server/terminal.d.ts +0 -36
  48. package/dist/src/app-server/terminal.js +3 -39
  49. package/dist/src/app-server/workspace.d.ts +0 -167
  50. package/dist/src/app-server/workspace.js +4 -406
  51. package/dist/src/app-server.d.ts +52 -925
  52. package/dist/src/app-server.js +828 -3076
  53. package/dist/src/artifacts.d.ts +0 -10
  54. package/dist/src/artifacts.js +1 -11
  55. package/dist/src/attachments.d.ts +4 -98
  56. package/dist/src/attachments.js +10 -130
  57. package/dist/src/auth/AuthManager.d.ts +9 -93
  58. package/dist/src/auth/AuthManager.js +164 -186
  59. package/dist/src/auth/callback-page.d.ts +0 -1
  60. package/dist/src/auth/callback-page.js +0 -4
  61. package/dist/src/auth/callback.d.ts +0 -25
  62. package/dist/src/auth/callback.js +1 -29
  63. package/dist/src/auth/deployment.d.ts +1 -16
  64. package/dist/src/auth/deployment.js +1 -16
  65. package/dist/src/auth/index.d.ts +1 -12
  66. package/dist/src/auth/index.js +1 -12
  67. package/dist/src/auth/lock.d.ts +0 -1
  68. package/dist/src/auth/lock.js +0 -1
  69. package/dist/src/auth/store.d.ts +33 -108
  70. package/dist/src/auth/store.js +55 -130
  71. package/dist/src/auth/types.d.ts +0 -8
  72. package/dist/src/auth-commands.d.ts +0 -5
  73. package/dist/src/auth-commands.js +0 -1
  74. package/dist/src/automation-runner.d.ts +0 -9
  75. package/dist/src/automation-runner.js +0 -11
  76. package/dist/src/automation-service.d.ts +0 -10
  77. package/dist/src/automation-service.js +3 -17
  78. package/dist/src/automation-tool.js +0 -5
  79. package/dist/src/automation-worker-shutdown.d.ts +0 -1
  80. package/dist/src/automation-worker-shutdown.js +0 -3
  81. package/dist/src/automations.d.ts +23 -2
  82. package/dist/src/automations.js +91 -12
  83. package/dist/src/background-tasks.d.ts +0 -23
  84. package/dist/src/background-tasks.js +0 -11
  85. package/dist/src/boot-trace.d.ts +0 -13
  86. package/dist/src/boot-trace.js +1 -14
  87. package/dist/src/browser-activity.js +0 -2
  88. package/dist/src/browser-bridge.d.ts +0 -2
  89. package/dist/src/browser-bridge.js +0 -27
  90. package/dist/src/browser-captcha-tool.d.ts +0 -13
  91. package/dist/src/browser-captcha-tool.js +3 -35
  92. package/dist/src/browser-extensions-tool.d.ts +24 -0
  93. package/dist/src/browser-extensions-tool.js +137 -0
  94. package/dist/src/browser-extensions.d.ts +127 -0
  95. package/dist/src/browser-extensions.js +729 -0
  96. package/dist/src/browser-observation.d.ts +0 -15
  97. package/dist/src/browser-observation.js +1 -22
  98. package/dist/src/browser-panel-tool.d.ts +1 -37
  99. package/dist/src/browser-panel-tool.js +3 -73
  100. package/dist/src/browser-runner.d.ts +0 -1
  101. package/dist/src/browser-runner.js +5 -46
  102. package/dist/src/browser-server.d.ts +0 -6
  103. package/dist/src/browser-server.js +6 -229
  104. package/dist/src/browser-session.d.ts +0 -25
  105. package/dist/src/browser-session.js +1 -71
  106. package/dist/src/browser-stealth.d.ts +19 -13
  107. package/dist/src/browser-stealth.js +22 -38
  108. package/dist/src/browser-ui/app.js +7 -174
  109. package/dist/src/browser-ui/style.css +0 -68
  110. package/dist/src/browser-ui/tokens.css +15 -97
  111. package/dist/src/browser-view.d.ts +106 -295
  112. package/dist/src/browser-view.js +551 -587
  113. package/dist/src/capabilities.d.ts +0 -8
  114. package/dist/src/capabilities.js +0 -29
  115. package/dist/src/capsolver.d.ts +0 -13
  116. package/dist/src/capsolver.js +0 -15
  117. package/dist/src/clarification-ui.d.ts +0 -7
  118. package/dist/src/clarification-ui.js +0 -8
  119. package/dist/src/claude-executable.d.ts +0 -1
  120. package/dist/src/claude-executable.js +1 -2
  121. package/dist/src/claude-provider.d.ts +6 -19
  122. package/dist/src/claude-provider.js +155 -63
  123. package/dist/src/cli-executable.d.ts +0 -16
  124. package/dist/src/cli-executable.js +0 -7
  125. package/dist/src/cli-process.d.ts +0 -26
  126. package/dist/src/cli-process.js +0 -18
  127. package/dist/src/cli-sign-in.d.ts +0 -20
  128. package/dist/src/cli-sign-in.js +1 -17
  129. package/dist/src/cli.d.ts +1 -55
  130. package/dist/src/cli.js +118 -742
  131. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +4 -59
  132. package/dist/src/code-intelligence/CodeIntelligenceManager.js +26 -99
  133. package/dist/src/code-intelligence/ContextLedger.d.ts +0 -4
  134. package/dist/src/code-intelligence/ContextLedger.js +0 -10
  135. package/dist/src/code-intelligence/ContextRouter.d.ts +0 -6
  136. package/dist/src/code-intelligence/ContextRouter.js +0 -8
  137. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.d.ts +0 -2
  138. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.js +5 -12
  139. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.d.ts +0 -6
  140. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.js +0 -6
  141. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.d.ts +0 -5
  142. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.js +1 -17
  143. package/dist/src/code-intelligence/codegraph/repoExploreTool.d.ts +0 -5
  144. package/dist/src/code-intelligence/codegraph/repoExploreTool.js +0 -5
  145. package/dist/src/code-intelligence/repository.d.ts +0 -9
  146. package/dist/src/code-intelligence/repository.js +1 -11
  147. package/dist/src/code-intelligence/types.d.ts +0 -8
  148. package/dist/src/codex-auth.d.ts +0 -44
  149. package/dist/src/codex-auth.js +0 -45
  150. package/dist/src/codex-browser-auth.d.ts +0 -13
  151. package/dist/src/codex-browser-auth.js +3 -20
  152. package/dist/src/codex-errors.js +0 -2
  153. package/dist/src/codex-executable.d.ts +0 -2
  154. package/dist/src/codex-executable.js +1 -7
  155. package/dist/src/codex-provider.d.ts +0 -13
  156. package/dist/src/codex-provider.js +0 -28
  157. package/dist/src/codex-rpc.d.ts +0 -10
  158. package/dist/src/codex-rpc.js +0 -12
  159. package/dist/src/coding-tools.d.ts +4 -26
  160. package/dist/src/coding-tools.js +161 -181
  161. package/dist/src/command-metrics.d.ts +0 -4
  162. package/dist/src/command-output-tap.d.ts +0 -11
  163. package/dist/src/command-output-tap.js +0 -3
  164. package/dist/src/command-screens.d.ts +41 -1
  165. package/dist/src/command-screens.js +316 -113
  166. package/dist/src/commands.d.ts +12 -63
  167. package/dist/src/commands.js +98 -127
  168. package/dist/src/completion-gates.d.ts +0 -47
  169. package/dist/src/completion-gates.js +0 -14
  170. package/dist/src/completion.d.ts +0 -98
  171. package/dist/src/completion.js +2 -239
  172. package/dist/src/config.d.ts +15 -115
  173. package/dist/src/config.js +123 -172
  174. package/dist/src/context-budget.d.ts +0 -22
  175. package/dist/src/context-budget.js +0 -44
  176. package/dist/src/context-compaction.d.ts +29 -6
  177. package/dist/src/context-compaction.js +94 -25
  178. package/dist/src/context-selection.d.ts +0 -24
  179. package/dist/src/context-selection.js +0 -34
  180. package/dist/src/dashboard-view.d.ts +2 -2
  181. package/dist/src/dashboard-view.js +11 -37
  182. package/dist/src/dashboard.d.ts +0 -2
  183. package/dist/src/dashboard.js +0 -9
  184. package/dist/src/deadline.d.ts +0 -45
  185. package/dist/src/deadline.js +0 -54
  186. package/dist/src/decision/ContinuationAdapter.d.ts +0 -5
  187. package/dist/src/decision/ContinuationAdapter.js +0 -5
  188. package/dist/src/decision/DecisionEngine.d.ts +0 -4
  189. package/dist/src/decision/DecisionManager.d.ts +0 -1
  190. package/dist/src/decision/DecisionManager.js +2 -7
  191. package/dist/src/decision/DecisionPolicy.d.ts +0 -1
  192. package/dist/src/decision/DecisionPolicy.js +0 -1
  193. package/dist/src/decision/FactContinuations.d.ts +11 -43
  194. package/dist/src/decision/FactContinuations.js +126 -95
  195. package/dist/src/decision/FactServiceGate.d.ts +0 -1
  196. package/dist/src/decision/FactServiceGate.js +0 -4
  197. package/dist/src/decision/PreparedSteps.d.ts +0 -15
  198. package/dist/src/decision/PreparedSteps.js +1 -11
  199. package/dist/src/decision/applyToolMenu.d.ts +0 -1
  200. package/dist/src/decision/applyToolMenu.js +2 -6
  201. package/dist/src/decision/checks.d.ts +15 -28
  202. package/dist/src/decision/checks.js +118 -49
  203. package/dist/src/decision/facts.d.ts +0 -16
  204. package/dist/src/decision/facts.js +0 -30
  205. package/dist/src/decision/guidancePolicy.js +0 -1
  206. package/dist/src/decision/hostedPolicy.d.ts +0 -6
  207. package/dist/src/decision/hostedPolicy.js +0 -7
  208. package/dist/src/decision/hostedSkills.d.ts +0 -19
  209. package/dist/src/decision/hostedSkills.js +0 -19
  210. package/dist/src/decision/optimizationPolicy.d.ts +0 -3
  211. package/dist/src/decision/optimizationPolicy.js +1 -4
  212. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +0 -7
  213. package/dist/src/decision/providers/AndorraDecisionProvider.js +4 -27
  214. package/dist/src/decision/providers/HttpDecisionProvider.d.ts +0 -2
  215. package/dist/src/decision/providers/HttpDecisionProvider.js +0 -6
  216. package/dist/src/decision/routeTools.d.ts +0 -8
  217. package/dist/src/decision/routeTools.js +1 -8
  218. package/dist/src/decision/toolFamilies.d.ts +0 -1
  219. package/dist/src/decision/toolFamilies.js +1 -2
  220. package/dist/src/decision/toolMenu.d.ts +0 -3
  221. package/dist/src/decision/toolMenu.js +0 -4
  222. package/dist/src/decision/types.d.ts +1 -6
  223. package/dist/src/default-graph.d.ts +0 -9
  224. package/dist/src/default-graph.js +0 -9
  225. package/dist/src/delegation-changes.d.ts +0 -56
  226. package/dist/src/delegation-changes.js +4 -130
  227. package/dist/src/diff-preview.d.ts +0 -1
  228. package/dist/src/diff-preview.js +0 -17
  229. package/dist/src/duration.d.ts +0 -50
  230. package/dist/src/duration.js +0 -50
  231. package/dist/src/efficiency.d.ts +0 -39
  232. package/dist/src/efficiency.js +0 -16
  233. package/dist/src/engine/protocol.d.ts +0 -2
  234. package/dist/src/engine/protocol.js +0 -2
  235. package/dist/src/engine-streams.d.ts +0 -9
  236. package/dist/src/extensions.d.ts +3 -2
  237. package/dist/src/extensions.js +63 -35
  238. package/dist/src/favicons.d.ts +0 -26
  239. package/dist/src/favicons.js +0 -34
  240. package/dist/src/file-diff.d.ts +2 -58
  241. package/dist/src/file-diff.js +0 -32
  242. package/dist/src/file-read-key.d.ts +0 -7
  243. package/dist/src/file-read-key.js +0 -7
  244. package/dist/src/file-read-state.d.ts +0 -1
  245. package/dist/src/file-read-state.js +0 -4
  246. package/dist/src/firefox-cookies.d.ts +0 -34
  247. package/dist/src/firefox-cookies.js +1 -55
  248. package/dist/src/git-identity-audit.d.ts +27 -0
  249. package/dist/src/git-identity-audit.js +286 -0
  250. package/dist/src/git-identity-guard.d.ts +4 -0
  251. package/dist/src/git-identity-guard.js +998 -0
  252. package/dist/src/git-identity-hold.d.ts +12 -0
  253. package/dist/src/git-identity-hold.js +81 -0
  254. package/dist/src/git-summary.d.ts +0 -58
  255. package/dist/src/git-summary.js +2 -212
  256. package/dist/src/goal-completion-verification.d.ts +2 -2
  257. package/dist/src/goal-completion-verification.js +3 -6
  258. package/dist/src/graph-account.d.ts +0 -21
  259. package/dist/src/graph-account.js +0 -17
  260. package/dist/src/graph-editor-session.d.ts +0 -1
  261. package/dist/src/graph-editor-session.js +0 -3
  262. package/dist/src/graph-health.d.ts +9 -61
  263. package/dist/src/graph-health.js +34 -59
  264. package/dist/src/graph-manager-chat.d.ts +36 -153
  265. package/dist/src/graph-manager-chat.js +161 -182
  266. package/dist/src/graph-provider-portability.d.ts +1 -21
  267. package/dist/src/graph-provider-portability.js +6 -45
  268. package/dist/src/graph-quota.d.ts +0 -33
  269. package/dist/src/graph-quota.js +1 -44
  270. package/dist/src/graph-runner.d.ts +0 -1
  271. package/dist/src/graph-runner.js +58 -391
  272. package/dist/src/graph-selection.d.ts +0 -14
  273. package/dist/src/graph-selection.js +2 -15
  274. package/dist/src/graph-server.d.ts +2 -10
  275. package/dist/src/graph-server.js +39 -101
  276. package/dist/src/graph-studio-features.d.ts +0 -5
  277. package/dist/src/graph-studio-features.js +2 -42
  278. package/dist/src/graph-sync.d.ts +0 -78
  279. package/dist/src/graph-sync.js +5 -201
  280. package/dist/src/graph-tool.d.ts +0 -18
  281. package/dist/src/graph-tool.js +0 -27
  282. package/dist/src/graph-ui/app.js +176 -492
  283. package/dist/src/graph-ui/compat.js +0 -7
  284. package/dist/src/graph-ui/controls.css +0 -48
  285. package/dist/src/graph-ui/controls.js +0 -88
  286. package/dist/src/graph-ui/drafts.js +0 -12
  287. package/dist/src/graph-ui/edge-router.js +0 -62
  288. package/dist/src/graph-ui/embed.js +0 -59
  289. package/dist/src/graph-ui/icons.js +0 -8
  290. package/dist/src/graph-ui/library.css +0 -5
  291. package/dist/src/graph-ui/manager-markdown.js +0 -11
  292. package/dist/src/graph-ui/manager-state.js +1 -78
  293. package/dist/src/graph-ui/manager.css +0 -18
  294. package/dist/src/graph-ui/manager.js +43 -185
  295. package/dist/src/graph-ui/model-picker.js +0 -29
  296. package/dist/src/graph-ui/sidebar.js +2 -3
  297. package/dist/src/graph-ui/skill-picker.js +373 -39
  298. package/dist/src/graph-ui/studio-canvas.js +3 -38
  299. package/dist/src/graph-ui/studio.css +0 -18
  300. package/dist/src/graph-ui/studio.js +3 -71
  301. package/dist/src/graph-ui/style.css +16 -136
  302. package/dist/src/graph-ui/theme.js +1 -26
  303. package/dist/src/graph-ui/tokens.css +19 -118
  304. package/dist/src/graphs.d.ts +6 -157
  305. package/dist/src/graphs.js +66 -269
  306. package/dist/src/grep-regex-worker.js +0 -2
  307. package/dist/src/grep-regex.d.ts +1 -5
  308. package/dist/src/grep-regex.js +6 -8
  309. package/dist/src/grok-provider.d.ts +0 -17
  310. package/dist/src/grok-provider.js +1 -26
  311. package/dist/src/handoffs.d.ts +0 -11
  312. package/dist/src/handoffs.js +0 -13
  313. package/dist/src/hardened-runtime.d.ts +0 -10
  314. package/dist/src/hardened-runtime.js +9 -47
  315. package/dist/src/harness-home.d.ts +21 -0
  316. package/dist/src/harness-home.js +87 -0
  317. package/dist/src/host-process-guard.d.ts +0 -50
  318. package/dist/src/host-process-guard.js +0 -641
  319. package/dist/src/limits.d.ts +0 -64
  320. package/dist/src/limits.js +0 -62
  321. package/dist/src/managed-sign-in.d.ts +0 -12
  322. package/dist/src/managed-sign-in.js +0 -16
  323. package/dist/src/markdown.d.ts +0 -28
  324. package/dist/src/markdown.js +1 -175
  325. package/dist/src/mcp.d.ts +0 -99
  326. package/dist/src/mcp.js +4 -170
  327. package/dist/src/membership-errors.d.ts +0 -14
  328. package/dist/src/membership-errors.js +1 -14
  329. package/dist/src/membership.d.ts +9 -59
  330. package/dist/src/membership.js +20 -91
  331. package/dist/src/memory/LocalToolMemory.d.ts +0 -1
  332. package/dist/src/memory/LocalToolMemory.js +2 -7
  333. package/dist/src/memory/MemoryDistiller.js +0 -15
  334. package/dist/src/memory/MemoryManager.d.ts +0 -3
  335. package/dist/src/memory/MemoryManager.js +6 -18
  336. package/dist/src/memory/MemoryPolicy.d.ts +0 -2
  337. package/dist/src/memory/MemoryPolicy.js +0 -2
  338. package/dist/src/memory/MemoryProvider.d.ts +0 -6
  339. package/dist/src/memory/MemoryRetriever.js +0 -7
  340. package/dist/src/memory/PermissionMemoryProvider.d.ts +0 -1
  341. package/dist/src/memory/PermissionMemoryProvider.js +0 -1
  342. package/dist/src/memory/ProjectMemory.d.ts +5 -40
  343. package/dist/src/memory/ProjectMemory.js +22 -47
  344. package/dist/src/memory/ToolFailureLessons.d.ts +0 -3
  345. package/dist/src/memory/ToolFailureLessons.js +0 -6
  346. package/dist/src/memory/providers/NoOpMemoryProvider.d.ts +0 -1
  347. package/dist/src/memory/providers/NoOpMemoryProvider.js +0 -1
  348. package/dist/src/memory/redaction.d.ts +0 -5
  349. package/dist/src/memory/redaction.js +0 -11
  350. package/dist/src/memory/repository.d.ts +0 -6
  351. package/dist/src/memory/repository.js +2 -12
  352. package/dist/src/memory/types.d.ts +0 -1
  353. package/dist/src/model-context-windows.d.ts +2 -0
  354. package/dist/src/model-context-windows.js +24 -0
  355. package/dist/src/model-health-cache.d.ts +0 -38
  356. package/dist/src/model-health-cache.js +2 -50
  357. package/dist/src/model-metadata.d.ts +1 -18
  358. package/dist/src/model-metadata.js +42 -45
  359. package/dist/src/model-override.d.ts +0 -36
  360. package/dist/src/model-override.js +0 -43
  361. package/dist/src/model-tiers.d.ts +0 -13
  362. package/dist/src/model-tiers.js +0 -23
  363. package/dist/src/opencode-catalog.d.ts +0 -2
  364. package/dist/src/opencode-catalog.js +0 -11
  365. package/dist/src/opencode-cli-provider.d.ts +0 -35
  366. package/dist/src/opencode-cli-provider.js +1 -44
  367. package/dist/src/opencode-provider.d.ts +0 -2
  368. package/dist/src/opencode-provider.js +1 -16
  369. package/dist/src/package-name.d.ts +0 -2
  370. package/dist/src/package-name.js +0 -2
  371. package/dist/src/paged-transcript.d.ts +0 -11
  372. package/dist/src/paged-transcript.js +2 -20
  373. package/dist/src/palette.d.ts +1 -63
  374. package/dist/src/palette.js +1 -64
  375. package/dist/src/permissions.d.ts +0 -15
  376. package/dist/src/permissions.js +17 -21
  377. package/dist/src/powershell-pool.d.ts +0 -9
  378. package/dist/src/powershell-pool.js +3 -26
  379. package/dist/src/process-warnings.d.ts +4 -0
  380. package/dist/src/process-warnings.js +103 -0
  381. package/dist/src/profile.d.ts +0 -43
  382. package/dist/src/profile.js +0 -43
  383. package/dist/src/project-reservation.d.ts +11 -0
  384. package/dist/src/project-reservation.js +143 -0
  385. package/dist/src/provider-connection.d.ts +0 -18
  386. package/dist/src/provider-connection.js +15 -39
  387. package/dist/src/provider-engine.d.ts +0 -21
  388. package/dist/src/provider-engine.js +1 -96
  389. package/dist/src/provider-import.d.ts +0 -49
  390. package/dist/src/provider-import.js +0 -60
  391. package/dist/src/provider-keys.d.ts +1 -36
  392. package/dist/src/provider-keys.js +5 -48
  393. package/dist/src/provider-settings.d.ts +16 -3
  394. package/dist/src/provider-settings.js +36 -52
  395. package/dist/src/providers.d.ts +14 -219
  396. package/dist/src/providers.js +69 -326
  397. package/dist/src/pull-requests.d.ts +0 -173
  398. package/dist/src/pull-requests.js +5 -195
  399. package/dist/src/qa/browser/PlaywrightRunner.d.ts +0 -7
  400. package/dist/src/qa/browser/PlaywrightRunner.js +2 -16
  401. package/dist/src/qa/command-policy.d.ts +0 -23
  402. package/dist/src/qa/command-policy.js +0 -30
  403. package/dist/src/qa/guidance.d.ts +0 -21
  404. package/dist/src/qa/guidance.js +0 -20
  405. package/dist/src/qa/profile/ProjectInspector.d.ts +0 -4
  406. package/dist/src/qa/profile/ProjectInspector.js +0 -6
  407. package/dist/src/qa/profile/QaConfigLoader.d.ts +0 -7
  408. package/dist/src/qa/profile/QaConfigLoader.js +0 -6
  409. package/dist/src/qa/profile/QaProfile.d.ts +0 -7
  410. package/dist/src/qa/profile/QaProfile.js +0 -7
  411. package/dist/src/qa/profile/yaml.d.ts +0 -9
  412. package/dist/src/qa/profile/yaml.js +0 -13
  413. package/dist/src/qa/qa-authorize.d.ts +0 -19
  414. package/dist/src/qa/qa-authorize.js +4 -11
  415. package/dist/src/qa/runtime/ProcessManager.d.ts +0 -31
  416. package/dist/src/qa/runtime/ProcessManager.js +4 -41
  417. package/dist/src/qa/runtime/PtyManager.d.ts +0 -4
  418. package/dist/src/qa/runtime/PtyManager.js +1 -7
  419. package/dist/src/qa/runtime/changes.d.ts +0 -11
  420. package/dist/src/qa/runtime/changes.js +1 -3
  421. package/dist/src/qa/tools.d.ts +0 -10
  422. package/dist/src/qa/tools.js +0 -12
  423. package/dist/src/qa/types.d.ts +0 -13
  424. package/dist/src/react-runtime.d.ts +2 -21
  425. package/dist/src/react-runtime.js +107 -422
  426. package/dist/src/read-document-doc.d.ts +0 -6
  427. package/dist/src/read-document-doc.js +0 -55
  428. package/dist/src/read-document-docx.d.ts +0 -16
  429. package/dist/src/read-document-docx.js +2 -69
  430. package/dist/src/read-document-text.d.ts +0 -17
  431. package/dist/src/read-document-text.js +0 -22
  432. package/dist/src/read-document-tool.d.ts +0 -31
  433. package/dist/src/read-document-tool.js +0 -30
  434. package/dist/src/read-document.d.ts +0 -49
  435. package/dist/src/read-document.js +1 -67
  436. package/dist/src/read-image.d.ts +0 -32
  437. package/dist/src/read-image.js +0 -33
  438. package/dist/src/remote/cert.d.ts +0 -18
  439. package/dist/src/remote/cert.js +0 -44
  440. package/dist/src/remote/client.d.ts +0 -70
  441. package/dist/src/remote/client.js +1 -116
  442. package/dist/src/remote/command.js +0 -17
  443. package/dist/src/remote/engine-pool.d.ts +0 -152
  444. package/dist/src/remote/engine-pool.js +22 -339
  445. package/dist/src/remote/errors.d.ts +0 -15
  446. package/dist/src/remote/errors.js +0 -7
  447. package/dist/src/remote/network.d.ts +0 -26
  448. package/dist/src/remote/network.js +1 -34
  449. package/dist/src/remote/pairing.d.ts +16 -51
  450. package/dist/src/remote/pairing.js +50 -57
  451. package/dist/src/remote/pem.d.ts +0 -4
  452. package/dist/src/remote/pem.js +0 -4
  453. package/dist/src/remote/roots.d.ts +0 -20
  454. package/dist/src/remote/roots.js +0 -8
  455. package/dist/src/remote/serve.d.ts +0 -47
  456. package/dist/src/remote/serve.js +0 -30
  457. package/dist/src/remote/server.d.ts +0 -14
  458. package/dist/src/remote/server.js +1 -79
  459. package/dist/src/remote/types.d.ts +1 -32
  460. package/dist/src/remote/types.js +0 -10
  461. package/dist/src/run-control.d.ts +2 -9
  462. package/dist/src/run-control.js +9 -13
  463. package/dist/src/run-progress.d.ts +0 -170
  464. package/dist/src/run-progress.js +0 -285
  465. package/dist/src/run-records.d.ts +0 -443
  466. package/dist/src/run-records.js +14 -687
  467. package/dist/src/run-temp.d.ts +12 -0
  468. package/dist/src/run-temp.js +50 -0
  469. package/dist/src/runtime.d.ts +12 -228
  470. package/dist/src/runtime.js +2 -128
  471. package/dist/src/sandbox-child.js +0 -1
  472. package/dist/src/save-lock.d.ts +0 -12
  473. package/dist/src/save-lock.js +0 -28
  474. package/dist/src/screen-selection.d.ts +0 -23
  475. package/dist/src/screen-selection.js +0 -22
  476. package/dist/src/secret-redaction.d.ts +0 -12
  477. package/dist/src/secret-redaction.js +0 -45
  478. package/dist/src/session-changes.d.ts +4 -80
  479. package/dist/src/session-changes.js +25 -130
  480. package/dist/src/session-goal.d.ts +129 -0
  481. package/dist/src/session-goal.js +230 -0
  482. package/dist/src/session-monitor.d.ts +1 -10
  483. package/dist/src/session-monitor.js +2 -39
  484. package/dist/src/session-reaper.d.ts +0 -15
  485. package/dist/src/session-reaper.js +0 -14
  486. package/dist/src/session-skills.d.ts +15 -44
  487. package/dist/src/session-skills.js +75 -60
  488. package/dist/src/session-summary.d.ts +0 -26
  489. package/dist/src/session-summary.js +0 -32
  490. package/dist/src/session-title.d.ts +0 -1
  491. package/dist/src/session-title.js +0 -2
  492. package/dist/src/sessions.d.ts +3 -122
  493. package/dist/src/sessions.js +9 -178
  494. package/dist/src/shell.d.ts +3 -20
  495. package/dist/src/shell.js +8 -72
  496. package/dist/src/side-panel.d.ts +5 -99
  497. package/dist/src/side-panel.js +76 -133
  498. package/dist/src/sign-in-detection.d.ts +0 -39
  499. package/dist/src/sign-in-detection.js +0 -43
  500. package/dist/src/sign-in-offer.d.ts +1 -19
  501. package/dist/src/sign-in-offer.js +0 -13
  502. package/dist/src/skill-commands.d.ts +0 -1
  503. package/dist/src/skill-commands.js +1 -4
  504. package/dist/src/skills/bundled/control-browser/SKILL.md +1 -1
  505. package/dist/src/skills/bundled/graph-manager/errors.md +1 -1
  506. package/dist/src/skills/bundled/provenance.json +738 -738
  507. package/dist/src/skills/invocable-skills.d.ts +0 -18
  508. package/dist/src/skills/invocable-skills.js +0 -17
  509. package/dist/src/skills/project-skills.d.ts +0 -1
  510. package/dist/src/skills/project-skills.js +0 -3
  511. package/dist/src/skills/prompt-skills.js +0 -14
  512. package/dist/src/skills/runtime-skills.d.ts +0 -13
  513. package/dist/src/skills/runtime-skills.js +0 -37
  514. package/dist/src/stall-recovery.d.ts +0 -25
  515. package/dist/src/stall-recovery.js +0 -38
  516. package/dist/src/stray-files.d.ts +0 -9
  517. package/dist/src/stray-files.js +0 -16
  518. package/dist/src/structured-step.d.ts +0 -22
  519. package/dist/src/structured-step.js +0 -22
  520. package/dist/src/subagent-run.d.ts +2 -163
  521. package/dist/src/subagent-run.js +18 -376
  522. package/dist/src/subagent-tree.d.ts +32 -0
  523. package/dist/src/subagent-tree.js +128 -0
  524. package/dist/src/telemetry/aggregate.d.ts +0 -37
  525. package/dist/src/telemetry/aggregate.js +0 -40
  526. package/dist/src/telemetry/capture-core.d.ts +0 -87
  527. package/dist/src/telemetry/capture-core.js +0 -67
  528. package/dist/src/telemetry/capture.d.ts +0 -1
  529. package/dist/src/telemetry/capture.js +0 -3
  530. package/dist/src/telemetry/classify.d.ts +0 -58
  531. package/dist/src/telemetry/classify.js +0 -60
  532. package/dist/src/telemetry/decision-capture.d.ts +0 -1
  533. package/dist/src/telemetry/emitter.d.ts +0 -30
  534. package/dist/src/telemetry/emitter.js +1 -62
  535. package/dist/src/telemetry/gate.d.ts +0 -29
  536. package/dist/src/telemetry/gate.js +0 -22
  537. package/dist/src/telemetry/identity.d.ts +0 -13
  538. package/dist/src/telemetry/identity.js +0 -29
  539. package/dist/src/telemetry/outbox.d.ts +0 -64
  540. package/dist/src/telemetry/outbox.js +1 -108
  541. package/dist/src/telemetry/schema.d.ts +1 -49
  542. package/dist/src/telemetry/schema.js +3 -84
  543. package/dist/src/telemetry/state.d.ts +0 -53
  544. package/dist/src/telemetry/state.js +0 -64
  545. package/dist/src/telemetry/surface.d.ts +0 -31
  546. package/dist/src/telemetry/surface.js +1 -39
  547. package/dist/src/telemetry/uploader.d.ts +0 -11
  548. package/dist/src/telemetry/uploader.js +0 -46
  549. package/dist/src/telemetry/uploads.d.ts +0 -11
  550. package/dist/src/telemetry/uploads.js +0 -11
  551. package/dist/src/telemetry/version.d.ts +0 -4
  552. package/dist/src/telemetry/version.js +0 -14
  553. package/dist/src/telemetry/workspace.d.ts +0 -7
  554. package/dist/src/telemetry/workspace.js +1 -22
  555. package/dist/src/terminal-ui.d.ts +33 -521
  556. package/dist/src/terminal-ui.js +145 -884
  557. package/dist/src/test-edit-guard.d.ts +74 -0
  558. package/dist/src/test-edit-guard.js +269 -0
  559. package/dist/src/text.d.ts +0 -1
  560. package/dist/src/text.js +0 -1
  561. package/dist/src/time-limit.d.ts +0 -36
  562. package/dist/src/time-limit.js +0 -37
  563. package/dist/src/timers.d.ts +0 -161
  564. package/dist/src/timers.js +0 -126
  565. package/dist/src/todos.d.ts +0 -1
  566. package/dist/src/todos.js +0 -3
  567. package/dist/src/token-rate.d.ts +0 -94
  568. package/dist/src/token-rate.js +0 -154
  569. package/dist/src/tool-activity.d.ts +0 -6
  570. package/dist/src/tool-activity.js +0 -7
  571. package/dist/src/tool-availability.d.ts +0 -13
  572. package/dist/src/tool-availability.js +1 -14
  573. package/dist/src/tool-call-clock.d.ts +1 -4
  574. package/dist/src/tool-call-clock.js +0 -13
  575. package/dist/src/tool-catalog.d.ts +0 -11
  576. package/dist/src/tool-catalog.js +0 -23
  577. package/dist/src/tool-dependencies.d.ts +0 -5
  578. package/dist/src/tool-dependencies.js +0 -4
  579. package/dist/src/tool-diff-stats.d.ts +0 -23
  580. package/dist/src/tool-diff-stats.js +0 -49
  581. package/dist/src/tool-errors.d.ts +9 -7
  582. package/dist/src/tool-errors.js +13 -6
  583. package/dist/src/tool-failure-tracker.d.ts +3 -11
  584. package/dist/src/tool-failure-tracker.js +19 -27
  585. package/dist/src/tool-names.d.ts +0 -16
  586. package/dist/src/tool-names.js +0 -12
  587. package/dist/src/tool-profile.d.ts +6 -0
  588. package/dist/src/tool-profile.js +23 -0
  589. package/dist/src/tool-result-filter.d.ts +0 -19
  590. package/dist/src/tool-result-filter.js +1 -66
  591. package/dist/src/tool-schema-compatibility.d.ts +0 -6
  592. package/dist/src/tool-schema-compatibility.js +0 -9
  593. package/dist/src/tools.d.ts +0 -4
  594. package/dist/src/tools.js +11 -114
  595. package/dist/src/trajectory.d.ts +0 -13
  596. package/dist/src/trajectory.js +23 -79
  597. package/dist/src/transcript.d.ts +0 -41
  598. package/dist/src/transcript.js +5 -60
  599. package/dist/src/types.d.ts +4 -168
  600. package/dist/src/untracked-file-removal.js +0 -20
  601. package/dist/src/update-check.d.ts +0 -14
  602. package/dist/src/update-check.js +1 -15
  603. package/dist/src/update.d.ts +0 -35
  604. package/dist/src/update.js +0 -100
  605. package/dist/src/usage-analytics.d.ts +17 -17
  606. package/dist/src/usage-analytics.js +168 -209
  607. package/dist/src/web-search.d.ts +0 -23
  608. package/dist/src/web-search.js +1 -27
  609. package/dist/src/widgets.d.ts +0 -25
  610. package/dist/src/widgets.js +0 -24
  611. package/dist/src/workspace-facts.d.ts +0 -12
  612. package/dist/src/workspace-facts.js +1 -18
  613. package/dist/src/workspace-git-metadata.d.ts +0 -16
  614. package/dist/src/workspace-git-metadata.js +0 -21
  615. package/dist/src/workspace-instructions.d.ts +3 -15
  616. package/dist/src/workspace-instructions.js +6 -19
  617. package/package.json +13 -2
@@ -5,41 +5,19 @@ import { mkdir } from 'node:fs/promises';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { observePage, observationResult } from './browser-observation.js';
8
- import { desktopUaOverride, hardenContext, stealthContextOptions, stealthLaunchArgs } from './browser-stealth.js';
8
+ import { desktopUaOverride, hardenContext, stealthLaunchArgs, STEALTH_LOCALE, userAgentMetadata } from './browser-stealth.js';
9
9
  export const VIEW_TAB_LIMIT = 6;
10
10
  export const VIEW_SESSION_LIMIT = 4;
11
11
  export const VIEW_IDLE_CLOSE_MS = 10 * 60 * 1000;
12
- /** The longest single idle-reap lease a caller may take; a holder renews well inside it. */
13
12
  export const VIEW_HOLD_MAX_MS = 10 * 60 * 1000;
14
- /** The pacing window between emitted frames: one per display refresh, with the coalescer holding the newest. */
15
13
  export const VIEW_FRAME_MIN_INTERVAL_MS = 16;
16
14
  export const VIEW_GOTO_TIMEOUT_MS = 30_000;
17
- /** The viewport Mobile mode simulates, in CSS pixels: an iPhone-class layout. */
18
15
  export const VIEW_MOBILE_VIEWPORT = { width: 390, height: 844 };
19
- /** The pixel density Mobile mode emulates: a current phone's. */
20
16
  const VIEW_MOBILE_SCALE = 3;
21
- /** The JPEG quality stream frames use; agent screenshots keep their own setting. */
22
17
  export const VIEW_STREAM_QUALITY = 90;
23
- /**
24
- * The largest display pixel ratio a desktop-mode page renders at. A 4K laptop
25
- * panel at 300% scaling is the densest display Windows ships with; past that
26
- * the frames only cost bandwidth the pane cannot show.
27
- */
28
18
  export const VIEW_MAX_SCALE = 3;
29
- /**
30
- * The largest frame the desktop accepts, in base64 characters (`parseFrameEvent`
31
- * in desktop/src/engine/browserView.ts drops anything bigger). A dropped frame
32
- * leaves the pane frozen, so a frame over this is never sent: the stream steps
33
- * its quality and then its size down until the page's frames fit.
34
- */
35
19
  export const VIEW_FRAME_LIMIT = 4 * 1024 * 1024;
36
- /** The lowest JPEG quality the frame budget steps down to before it shrinks frames instead. */
37
20
  const VIEW_BUDGET_QUALITY_FLOOR = 50;
38
- /**
39
- * The next, smaller frame budget after a frame came out over the limit: quality
40
- * first, in steps of 20 down to 50, then the frame size in steps of a quarter,
41
- * down to the page's CSS size. Undefined when there is nothing left to give up.
42
- */
43
21
  export function nextFrameBudget(budget, scale) {
44
22
  if (budget.quality > VIEW_BUDGET_QUALITY_FLOOR)
45
23
  return { quality: Math.max(VIEW_BUDGET_QUALITY_FLOOR, budget.quality - 20), size: budget.size };
@@ -48,27 +26,35 @@ export function nextFrameBudget(budget, scale) {
48
26
  return { quality: budget.quality, size: Math.max(floor, budget.size * 0.75) };
49
27
  return undefined;
50
28
  }
51
- /** The largest viewport `clampViewport` allows, in CSS pixels. */
52
29
  const VIEW_MAX_VIEWPORT = { width: 1600, height: 2200 };
53
- /**
54
- * The mobile Chrome UA Mobile mode presents. A Chromium engine claiming to be
55
- * iOS Safari confuses sites that branch on it, so the UA names the platform the
56
- * page actually renders with.
57
- */
58
30
  export const VIEW_MOBILE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36';
31
+ // Fallback for the mobile override when the running browser's version cannot be read.
59
32
  const VIEW_URL_LIMIT = 2048;
60
- // A copy is answered as one JSON string over the same pipe as everything else,
61
- // so the largest plausible selection is bounded rather than trusted.
62
33
  const VIEW_CLIPBOARD_LIMIT = 1_000_000;
63
34
  /**
64
- * The top document's selection, and whether focus is inside a child frame.
65
- *
66
- * `document.activeElement` is the iframe element itself, never the field inside
67
- * it, and the top document's own selection is empty while a frame holds focus —
68
- * so a selection made in a frame is invisible here and the caller has to ask the
69
- * frames. It is an expression rather than a function: this file compiles without
70
- * the DOM library, and Playwright evaluates a string inside the page as-is.
35
+ * The panel browses with a real headed window so sites score it as a browser and
36
+ * not a bot, but the window is parked far offscreen: the pane shows the page by
37
+ * screencasting it, so the window does not need to be on screen or in the way.
38
+ * -32000 is the standard spot that Windows, macOS and Linux all keep off the
39
+ * visible desktop without clamping back.
40
+ */
41
+ export const VIEW_OFFSCREEN_POSITION = { left: -32000, top: -32000 };
42
+ /** Where the window goes when the user asks to see it. */
43
+ export const VIEW_ONSCREEN_POSITION = { left: 80, top: 80 };
44
+ const VIEW_WINDOW_ARGS = [
45
+ `--window-position=${VIEW_OFFSCREEN_POSITION.left},${VIEW_OFFSCREEN_POSITION.top}`,
46
+ '--window-size=1600,1000',
47
+ ];
48
+ /**
49
+ * The mobile emulation override is built from the running browser's real version,
50
+ * so the page never sees a version the browser itself does not have. Without a
51
+ * readable version the old constant stays the fallback.
71
52
  */
53
+ export function mobileUserAgent(version) {
54
+ if (!version || !/^\d+(\.\d+)*$/.test(version))
55
+ return VIEW_MOBILE_USER_AGENT;
56
+ return `Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version} Mobile Safari/537.36`;
57
+ }
72
58
  const SELECTION_STATE = `(() => {
73
59
  const active = document.activeElement;
74
60
  const inFrame = !!active && (active.tagName === 'IFRAME' || active.tagName === 'FRAME');
@@ -82,13 +68,6 @@ const SELECTION_STATE = `(() => {
82
68
  }
83
69
  return { inFrame: false, focused, text: window.getSelection ? String(window.getSelection() || '') : '' };
84
70
  })()`;
85
- /**
86
- * The cursor style in effect at a point in the page.
87
- *
88
- * The pane shows a streamed image, so the page's pointer never appears on its
89
- * own: the panel asks for the style under the pointer and draws that shape
90
- * itself. Same-origin frames are entered by mapping the point into each one.
91
- */
92
71
  const CURSOR_AT = `((point) => {
93
72
  let doc = document;
94
73
  let x = point.x;
@@ -112,9 +91,13 @@ const CURSOR_AT = `((point) => {
112
91
  }
113
92
  return 'default';
114
93
  })`;
115
- /** The dependency panel browsing needs: an HTTP(S) page an isolated browser can open. */ export function browserViewUrl(value) {
94
+ export function browserViewUrl(value) {
116
95
  const url = new URL(value);
117
- if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
96
+ if (url.protocol === 'chrome-extension:') {
97
+ if (!/^[a-p]{32}$/.test(url.hostname) || url.username || url.password)
98
+ throw new Error('Use a chrome-extension://<32-letter id>/ page');
99
+ }
100
+ else if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
118
101
  throw new Error('Use an HTTP(S) URL without embedded credentials');
119
102
  if (url.href.length > VIEW_URL_LIMIT)
120
103
  throw new Error('URL exceeds the 2048-character limit');
@@ -124,25 +107,11 @@ export function clampViewport(width, height) {
124
107
  const value = (input, min, max, fallback) => Number.isSafeInteger(input) ? Math.max(min, Math.min(max, input)) : fallback;
125
108
  return { width: value(width, 280, VIEW_MAX_VIEWPORT.width, 900), height: value(height, 240, VIEW_MAX_VIEWPORT.height, 700) };
126
109
  }
127
- /**
128
- * The pane's display pixel ratio, which sizes its frames (and the factor a
129
- * browser launched for it runs at), so one frame pixel is one screen pixel and
130
- * the pane never stretches a frame rendered at CSS size. Anything that is not a finite number is the plain 1×
131
- * an old panel (which sends none) has always had; the value is rounded to
132
- * hundredths so a ratio like 1.2500000001 does not count as a change.
133
- */
134
110
  export function clampScale(value) {
135
111
  if (typeof value !== 'number' || !Number.isFinite(value))
136
112
  return 1;
137
113
  return Math.round(Math.max(1, Math.min(VIEW_MAX_SCALE, value)) * 100) / 100;
138
114
  }
139
- /**
140
- * JPEG dimensions straight from the SOF markers, without decoding pixels.
141
- *
142
- * Screencast frames carry no size fields; the panel sends input in image pixels
143
- * and the engine must translate to page CSS pixels, so the real image size is
144
- * load-bearing, not decorative.
145
- */
146
115
  export function jpegSize(bytes) {
147
116
  if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8)
148
117
  return undefined;
@@ -153,13 +122,11 @@ export function jpegSize(bytes) {
153
122
  continue;
154
123
  }
155
124
  const marker = bytes[offset + 1];
156
- // Fill bytes before a marker, and the stand-alone markers that carry no length.
157
125
  if (marker === 0xff || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) {
158
126
  offset += 2;
159
127
  continue;
160
128
  }
161
129
  const length = (bytes[offset + 2] << 8) | bytes[offset + 3];
162
- // Baseline and progressive DCT carry the frame size; every other segment is skipped whole.
163
130
  if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
164
131
  if (length < 7 || offset + 9 > bytes.length)
165
132
  return undefined;
@@ -171,7 +138,6 @@ export function jpegSize(bytes) {
171
138
  }
172
139
  return undefined;
173
140
  }
174
- /** Windows virtual-key codes for the named keys a panel keypress can produce. */
175
141
  const KEY_CODE = {
176
142
  Enter: 13, Backspace: 8, Tab: 9, Escape: 27, Delete: 46, Insert: 45,
177
143
  ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Home: 36, End: 35, PageUp: 33, PageDown: 34,
@@ -182,19 +148,6 @@ const CODE_KEY = {
182
148
  Backslash: 220, Minus: 189, Equal: 187, Backquote: 192, NumpadEnter: 13, NumpadAdd: 107, NumpadSubtract: 109,
183
149
  NumpadMultiply: 106, NumpadDivide: 111, NumpadDecimal: 110,
184
150
  };
185
- /**
186
- * One panel key event as the CDP input domain needs it.
187
- *
188
- * A key is always a keyboard event, with the character a key-down inserts in
189
- * `text`: an ordinary letter is inserted that way, and Enter carries Chromium's
190
- * carriage return so a textarea or a content-editable field gets its newline.
191
- * Keeping the gesture as a key event is what lets the page run its own keydown
192
- * handling — Space activating a focused button, a page's printable-key shortcut —
193
- * which text insertion alone would never trigger. A Ctrl, Alt or Meta held over a
194
- * key drops the text (Ctrl+C must be a key event, never the character "c"), with
195
- * one exception: AltGr is reported as Ctrl+Alt, and the character it produced —
196
- * "@" on a German layout, "€" on many others — must survive.
197
- */
198
151
  export function keyDescriptor(key, code, modifiers = 0) {
199
152
  const named = KEY_CODE[key]
200
153
  ?? (code?.startsWith('Key') && code.length === 4 ? code.charCodeAt(3) : undefined)
@@ -205,13 +158,7 @@ export function keyDescriptor(key, code, modifiers = 0) {
205
158
  throw new Error(`Unsupported key: ${key}`);
206
159
  const ctrl = (modifiers & MODIFIER_BITS.ctrl) !== 0;
207
160
  const alt = (modifiers & MODIFIER_BITS.alt) !== 0;
208
- // An Option gesture on macOS that produces a character changes the key itself to
209
- // that character (Option+2 is '™' on a US layout), while an Alt shortcut leaves
210
- // the letter or digit it names untouched: a non-ASCII single character with Alt
211
- // held is text to insert, not a shortcut, or the page would see the key and
212
- // insert nothing.
213
161
  const altCharacter = alt && !ctrl && printable && (key.codePointAt(0) ?? 0) > 0x7f;
214
- // AltGr arrives as Ctrl+Alt together; a shortcut has exactly one of them (or Meta).
215
162
  const shortcut = !altCharacter && ((modifiers & MODIFIER_BITS.meta) !== 0 || (ctrl !== alt && (ctrl || alt)));
216
163
  const keyCode = named ?? key.toUpperCase().charCodeAt(0);
217
164
  const text = shortcut ? undefined : printable ? key : key === 'Enter' ? '\r' : undefined;
@@ -231,16 +178,6 @@ export function modifierMask(modifiers) {
231
178
  throw new Error('modifiers must be a list of alt, ctrl, meta, shift');
232
179
  return modifiers.reduce((mask, name) => mask | MODIFIER_BITS[name], 0);
233
180
  }
234
- /**
235
- * The native editing commands a macOS page performs for a key-down.
236
- *
237
- * On macOS, gestures like Cmd+A, Cmd+Z, or Option+Arrow are not synthesized from
238
- * key events: Chromium runs the named command instead, and nothing happens when
239
- * none is sent — the panel suppresses the local default, so the page would be
240
- * left without either. These are the mappings Playwright itself derives for the
241
- * same CDP call (its macEditingCommands table), limited to the gestures a pane
242
- * can forward.
243
- */
244
181
  export function macEditingCommands(key, modifiers) {
245
182
  const meta = (modifiers & MODIFIER_BITS.meta) !== 0;
246
183
  const alt = (modifiers & MODIFIER_BITS.alt) !== 0;
@@ -269,36 +206,33 @@ export function macEditingCommands(key, modifiers) {
269
206
  }
270
207
  return [];
271
208
  }
272
- /**
273
- * The launch options for the panel browser. Playwright mutes Chromium by default
274
- * (`--mute-audio`), which silences every page the user browses in the panel; the
275
- * screencast carries pixels only, so the page's own audio output on the engine's
276
- * machine is the only sound the panel has.
277
- */
278
- export function viewLaunchOptions(channel, executablePath, scale = 1) {
209
+ export function viewLaunchOptions(channel, executablePath, scale = 1, extensionPaths = []) {
210
+ const extensions = channel === 'chromium' ? extensionPaths : [];
279
211
  return {
280
212
  headless: true,
281
213
  ...(channel === 'chromium' ? { executablePath } : { channel }),
282
- ignoreDefaultArgs: ['--mute-audio'],
283
- // The panel's automation markers (see browser-stealth) must not reach the page.
284
- // A screencast captures the browser's own surface, which is CSS size at the
285
- // browser's real device scale factor; an emulated ratio alone renders the
286
- // page at that ratio and then shrinks it into a 1× surface (verified live:
287
- // 800×600 frames with devicePixelRatio 2). The real factor is what puts
288
- // screen-resolution pixels into the frames.
289
- args: [...stealthLaunchArgs(), ...(scale !== 1 ? [`--force-device-scale-factor=${scale}`] : [])],
214
+ ignoreDefaultArgs: ['--mute-audio', ...(extensions.length ? ['--disable-extensions'] : [])],
215
+ args: [
216
+ ...stealthLaunchArgs(), ...(scale !== 1 ? [`--force-device-scale-factor=${scale}`] : []),
217
+ ...(extensions.length ? [`--disable-extensions-except=${extensions.join(',')}`, `--load-extension=${extensions.join(',')}`] : []),
218
+ ],
290
219
  timeout: 20_000,
291
220
  };
292
221
  }
293
- /** Whether a frame arriving at `now` may be emitted, given the last emitted frame time. */
222
+ /**
223
+ * The options the panel actually launches with: the stealth launch options above,
224
+ * but headed, with the real window parked offscreen. A real window is what bot
225
+ * checks (Cloudflare's managed challenge among them) look for; the pane shows the
226
+ * page by screencasting it, so the window does not have to be visible or in the
227
+ * way. parkWindow re-asserts the offscreen position after the launch.
228
+ */
229
+ export function headedViewLaunchOptions(channel, executablePath, scale = 1, extensionPaths = []) {
230
+ const base = viewLaunchOptions(channel, executablePath, scale, extensionPaths);
231
+ return { ...base, headless: false, args: [...base.args, ...VIEW_WINDOW_ARGS] };
232
+ }
294
233
  export function frameGate(now, lastEmittedAt, minIntervalMs) {
295
234
  return lastEmittedAt === undefined || now - lastEmittedAt >= minIntervalMs;
296
235
  }
297
- /**
298
- * The file whose existence proves a channel is installed. The bundled Chromium's
299
- * path comes from playwright-core itself; system channels have per-platform
300
- * locations. The probe reads the filesystem and never launches anything.
301
- */
302
236
  export function channelCandidate(channel, platform, chromiumExecutable) {
303
237
  if (channel === 'chromium') {
304
238
  try {
@@ -321,60 +255,33 @@ export function channelCandidate(channel, platform, chromiumExecutable) {
321
255
  ? ['/usr/bin/microsoft-edge', '/usr/bin/microsoft-edge-stable'].find(existsSync)
322
256
  : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable'].find(existsSync);
323
257
  }
324
- /** How long closing a profile may take: a graceful close is what flushes cookies to disk. */
258
+ const EXTENSION_RESTART_POLL_MS = 5_000;
259
+ const EXTENSION_PROBE_TIMEOUT_MS = 4_000;
325
260
  const PROFILE_CLOSE_TIMEOUT_MS = 5_000;
326
- /**
327
- * One engine's panel browsers: a browser per session, a page per tab, and a CDP
328
- * screencast relay per active tab. Everything is keyed by the saved session id —
329
- * exactly the identity the desktop's browser pane already owns.
330
- */
261
+ const EXTENSION_PAGE_CLAIM_MS = 300;
331
262
  export class BrowserViewManager {
332
263
  emit;
333
264
  launchBrowser;
334
265
  options;
335
266
  sessions = new Map();
336
- /**
337
- * The pane's standing stream request per session, kept before a browser exists.
338
- *
339
- * A panel mounts and asks for frames before its first tab is opened, so the
340
- * request has to outlive the absence of a session: the open that follows
341
- * adopts this along with its viewport, and a later re-open after an idle reap
342
- * resumes streaming without another round trip.
343
- */
344
267
  desired = new Map();
345
- /**
346
- * The display ratio a pane most recently reported, for any session. A browser
347
- * an agent opens while its pane is collapsed has no request of its own to read
348
- * a ratio from; the machine's display is the best answer there is.
349
- */
350
268
  displayScale = 1;
351
- /** Launches in flight per session, so concurrent opens share one browser. */
352
269
  launching = new Map();
353
270
  runtime = { state: 'checking' };
354
271
  runtimeProbe;
355
272
  installTask;
356
- /**
357
- * The running installer, held here rather than in the closure that started it:
358
- * shutdown has to terminate the download and settle the request waiting on it,
359
- * or the child outlives the engine that is being closed.
360
- */
361
273
  installer;
362
- /**
363
- * Sessions released while their first launch was still in flight. The launch
364
- * that arrives afterwards closes its browser instead of registering one the
365
- * deleted session can never reach, or else it would hold a slot for good.
366
- */
367
274
  released = new Set();
368
- /** Project profiles open now, by profile key. */
369
275
  profiles = new Map();
370
- /**
371
- * Sessions whose panel browser is (or is about to be) incognito. The mark
372
- * lives exactly as long as that browser: it is cleared when the browser
373
- * closes, so the next open returns to the project profile.
374
- */
375
276
  incognito = new Set();
376
- /** Idle-reap leases by session id: the time each session's browser is held until (see `hold`). */
377
277
  holds = new Map();
278
+ pendingRestart = new Set();
279
+ claimedPages = new WeakSet();
280
+ restartsInFlight = new Set();
281
+ /** The restart under way for each profile, through its tab restoration: one at a time per profile. */
282
+ restartingProfiles = new Map();
283
+ restoring = new Map();
284
+ restartPoll;
378
285
  closed = false;
379
286
  constructor(emit, launchBrowser, options = {}) {
380
287
  this.emit = emit;
@@ -385,10 +292,6 @@ export class BrowserViewManager {
385
292
  this.runtime = status;
386
293
  this.emit('browser.runtime', { ...status });
387
294
  }
388
- /**
389
- * Probe the same executables `launch` will use, without launching anything;
390
- * the answer is cached.
391
- */
392
295
  runtimeStatus(force = false) {
393
296
  if (!force && this.runtime.state !== 'checking')
394
297
  return Promise.resolve(this.runtime);
@@ -416,16 +319,9 @@ export class BrowserViewManager {
416
319
  })().finally(() => { this.runtimeProbe = undefined; });
417
320
  return this.runtimeProbe;
418
321
  }
419
- /**
420
- * Download the bundled Chromium through playwright-core's own installer.
421
- *
422
- * A machine with Edge or Chrome installed never reaches this: the probe is
423
- * satisfied by the system browser and the download is skipped.
424
- */
425
322
  install() {
426
323
  if (this.installTask)
427
324
  return this.installTask;
428
- // Nothing to install into a manager that is already gone.
429
325
  if (this.closed)
430
326
  return Promise.resolve({ state: 'failed', detail: 'Application is shutting down' });
431
327
  const run = async () => new Promise(resolve => {
@@ -440,8 +336,6 @@ export class BrowserViewManager {
440
336
  this.installer = undefined;
441
337
  resolve(value);
442
338
  };
443
- // A stalled download must not wedge the runtime in 'installing' forever:
444
- // the installer is stopped and the state reported as failed.
445
339
  const timer = setTimeout(() => {
446
340
  child?.kill();
447
341
  const failed = { state: 'failed', detail: detail || 'Browser runtime install timed out' };
@@ -490,16 +384,10 @@ export class BrowserViewManager {
490
384
  return this.installTask;
491
385
  }
492
386
  async launch(scale) {
493
- // Tests supply a fake browser; production launches the real one below.
494
387
  if (this.launchBrowser)
495
388
  return await this.launchBrowser(scale);
496
389
  const { chromium } = await import('playwright-core');
497
390
  const failures = [];
498
- // The probe's candidates in the probe's order. The bundled Chromium is launched
499
- // by the very executable the probe checked: a default headless launch selects
500
- // Playwright's separate headless shell, which an install made with `--no-shell`
501
- // does not have, so probing the full binary and launching the shell would report
502
- // a ready runtime for a browser that cannot start.
503
391
  for (const channel of ['chromium', 'msedge', 'chrome']) {
504
392
  if (this.closed)
505
393
  throw new Error('Application is shutting down');
@@ -507,7 +395,7 @@ export class BrowserViewManager {
507
395
  if (!candidate || !existsSync(candidate))
508
396
  continue;
509
397
  try {
510
- return await chromium.launch(viewLaunchOptions(channel, candidate, scale));
398
+ return await chromium.launch(headedViewLaunchOptions(channel, candidate, scale));
511
399
  }
512
400
  catch (error) {
513
401
  failures.push((error instanceof Error ? error.message : String(error)).split('\n')[0]);
@@ -515,10 +403,21 @@ export class BrowserViewManager {
515
403
  }
516
404
  throw new Error(`Browser runtime is not usable: ${failures.join('; ').slice(0, 1000)}`);
517
405
  }
518
- /** Launch Chromium on a project's profile folder, with the same candidates as `launch`. */
519
406
  async launchPersistent(directory, viewport, scale) {
520
- if (this.options.launchProfile)
521
- return await this.options.launchProfile(directory, viewport, scale);
407
+ const set = this.options.extensions
408
+ ? await this.options.extensions.launchSet().catch(() => ({ load: [], problems: {} }))
409
+ : { load: [], problems: {} };
410
+ const status = {};
411
+ for (const [id, detail] of Object.entries(set.problems))
412
+ status[id] = { state: 'failed', detail };
413
+ if (this.options.launchProfile) {
414
+ const context = await this.options.launchProfile(directory, viewport, scale, set);
415
+ if (set.load.length)
416
+ await this.reportLoaded(context, set, status);
417
+ else if (Object.keys(status).length)
418
+ this.options.extensions?.report(status);
419
+ return context;
420
+ }
522
421
  await mkdir(directory, { recursive: true });
523
422
  const { chromium } = await import('playwright-core');
524
423
  const failures = [];
@@ -528,10 +427,36 @@ export class BrowserViewManager {
528
427
  const candidate = channelCandidate(channel, process.platform, () => chromium.executablePath());
529
428
  if (!candidate || !existsSync(candidate))
530
429
  continue;
531
- try {
532
- const context = await chromium.launchPersistentContext(directory, { ...viewLaunchOptions(channel, candidate, scale), ...stealthContextOptions(), viewport: { ...viewport }, acceptDownloads: false });
430
+ const open = async (paths) => {
431
+ // Headed, so the browser's own identity goes through: no fake UA is set on
432
+ // the context. Only the locale stays as a stealth option.
433
+ const context = await chromium.launchPersistentContext(directory, { ...headedViewLaunchOptions(channel, candidate, scale, paths), locale: STEALTH_LOCALE, viewport: { ...viewport }, acceptDownloads: false });
533
434
  await hardenContext(context);
534
435
  return context;
436
+ };
437
+ try {
438
+ if (channel !== 'chromium' || set.load.length === 0) {
439
+ const context = await open([]);
440
+ for (const item of set.load)
441
+ status[item.id] = { state: 'not-loaded', detail: 'The panel is running on Edge or Chrome, which cannot load extensions this way; install the browser runtime to use them' };
442
+ if (Object.keys(status).length)
443
+ this.options.extensions?.report(status);
444
+ return context;
445
+ }
446
+ let context;
447
+ try {
448
+ context = await open(set.load.map(item => item.path));
449
+ }
450
+ catch (error) {
451
+ const detail = `The browser would not start with extensions: ${(error instanceof Error ? error.message : String(error)).split('\n')[0].slice(0, 300)}`;
452
+ context = await open([]);
453
+ for (const item of set.load)
454
+ status[item.id] = { state: 'failed', detail };
455
+ this.options.extensions?.report(status);
456
+ return context;
457
+ }
458
+ await this.reportLoaded(context, set, status);
459
+ return context;
535
460
  }
536
461
  catch (error) {
537
462
  failures.push((error instanceof Error ? error.message : String(error)).split('\n')[0]);
@@ -539,12 +464,308 @@ export class BrowserViewManager {
539
464
  }
540
465
  throw new Error(`Project browser profile is not usable: ${failures.join('; ').slice(0, 1000)}`);
541
466
  }
467
+ async reportLoaded(context, set, status) {
468
+ let page;
469
+ try {
470
+ page = await context.newPage();
471
+ for (const item of set.load) {
472
+ try {
473
+ await page.goto(`chrome-extension://${item.id}/manifest.json`, { timeout: EXTENSION_PROBE_TIMEOUT_MS });
474
+ status[item.id] = { state: 'loaded' };
475
+ }
476
+ catch {
477
+ status[item.id] = { state: 'failed', detail: 'Chromium did not load it: check the folder for manifest errors or missing files' };
478
+ }
479
+ }
480
+ }
481
+ catch { }
482
+ finally {
483
+ await Promise.resolve().then(() => page?.close()).catch(() => { });
484
+ }
485
+ this.options.extensions?.report(status);
486
+ }
487
+ /**
488
+ * Re-assert the offscreen position over the browser-level CDP connection after
489
+ * the launch. --window-position already asks for it at startup; this second
490
+ * pass catches window managers that clamp the window back on screen (macOS has
491
+ * done so with very large negative coordinates).
492
+ */
493
+ parkWindow(browser) {
494
+ try {
495
+ const session = browser?.newBrowserCDPSession?.();
496
+ if (!session)
497
+ return;
498
+ void Promise.resolve().then(() => session).then(async (cdp) => {
499
+ const windowId = await this.windowIdFor(cdp, undefined);
500
+ if (windowId === undefined)
501
+ return;
502
+ await cdp.send('Browser.setWindowBounds', { windowId, bounds: { windowState: 'normal', ...VIEW_OFFSCREEN_POSITION } });
503
+ }).catch(() => { });
504
+ }
505
+ catch { /* same: never let window parking break the launch */ }
506
+ }
542
507
  /**
543
- * Join the project's shared profile browser, launching it for the first session.
544
- *
545
- * A profile that is still closing is waited out rather than reopened beside it:
546
- * two processes on one profile folder is exactly what Chromium refuses.
508
+ * Finds the id of the window that should be moved. The precise way is the target
509
+ * id of the tab the user is looking at; without one the browser target itself has
510
+ * no web contents to look a window up with, so the newest page target is used.
547
511
  */
512
+ async windowIdFor(cdp, targetId) {
513
+ if (targetId !== undefined) {
514
+ const direct = await this.lookupWindowId(cdp, { targetId });
515
+ if (direct !== undefined)
516
+ return direct;
517
+ }
518
+ const fallback = await this.lookupWindowId(cdp, {});
519
+ if (fallback !== undefined)
520
+ return fallback;
521
+ try {
522
+ const targets = await cdp.send('Target.getTargets');
523
+ const page = (targets?.targetInfos ?? []).find((info) => info.type === 'page' && typeof info.targetId === 'string');
524
+ if (page)
525
+ return await this.lookupWindowId(cdp, { targetId: page.targetId });
526
+ }
527
+ catch { /* nothing more to try */ }
528
+ return undefined;
529
+ }
530
+ async lookupWindowId(cdp, params) {
531
+ try {
532
+ const window = await cdp.send('Browser.getWindowForTarget', params);
533
+ return typeof window?.windowId === 'number' ? window.windowId : undefined;
534
+ }
535
+ catch {
536
+ return undefined;
537
+ }
538
+ }
539
+ browserFor(session) {
540
+ if (session.profileKey !== undefined && session.profileOwner !== undefined) {
541
+ return this.profiles.get(session.profileKey)?.context?.browser?.() ?? session.browser;
542
+ }
543
+ return session.browser;
544
+ }
545
+ async browserCdpFor(session) {
546
+ if (session.profileKey !== undefined && session.profileOwner !== undefined) {
547
+ const host = this.profiles.get(session.profileKey);
548
+ if (!host)
549
+ throw new Error('The browser is closing; retry shortly');
550
+ host.browserCdp ??= Promise.resolve().then(() => {
551
+ const browser = this.browserFor(session);
552
+ if (!browser?.newBrowserCDPSession)
553
+ throw new Error('The panel browser cannot be moved on screen: it does not expose window control');
554
+ return browser.newBrowserCDPSession();
555
+ });
556
+ try {
557
+ return await host.browserCdp;
558
+ }
559
+ catch (error) {
560
+ if (this.profiles.get(session.profileKey)?.browserCdp === host.browserCdp)
561
+ host.browserCdp = undefined;
562
+ throw error;
563
+ }
564
+ }
565
+ session.browserCdp ??= Promise.resolve().then(() => {
566
+ const browser = this.browserFor(session);
567
+ if (!browser?.newBrowserCDPSession)
568
+ throw new Error('The panel browser cannot be moved on screen: it does not expose window control');
569
+ return browser.newBrowserCDPSession();
570
+ });
571
+ try {
572
+ return await session.browserCdp;
573
+ }
574
+ catch (error) {
575
+ session.browserCdp = undefined;
576
+ throw error;
577
+ }
578
+ }
579
+ async showWindow(sessionId) {
580
+ await this.moveWindow(sessionId, VIEW_ONSCREEN_POSITION, true);
581
+ }
582
+ async hideWindow(sessionId) {
583
+ await this.moveWindow(sessionId, VIEW_OFFSCREEN_POSITION, false);
584
+ }
585
+ async moveWindow(sessionId, position, activate) {
586
+ const session = this.sessions.get(sessionId);
587
+ if (!session || session.closing)
588
+ throw new Error('No browser tab is open for this session');
589
+ this.scheduleIdleClose(sessionId, session);
590
+ const cdp = await this.browserCdpFor(session);
591
+ const active = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
592
+ const windowId = await this.windowIdFor(cdp, active?.targetId);
593
+ if (windowId === undefined)
594
+ throw new Error('The browser window could not be found to move');
595
+ await cdp.send('Browser.setWindowBounds', { windowId, bounds: { windowState: 'normal', ...position } });
596
+ if (activate) {
597
+ // Showing the window also raises the tab the panel is showing: the manager's
598
+ // selection and the native browser's selected tab are separate, so without
599
+ // this the real window can come up on a different tab than the one the user
600
+ // is interacting with (including while solving a challenge).
601
+ await Promise.resolve().then(() => active?.page?.bringToFront?.()).catch(() => { });
602
+ }
603
+ }
604
+ async restartForExtensions(force = false) {
605
+ if (this.closed)
606
+ return { restarted: 0, pending: [] };
607
+ for (const key of this.profiles.keys())
608
+ this.pendingRestart.add(key);
609
+ return await this.retryPendingRestarts(force);
610
+ }
611
+ async restartWithSession(sessionId, everyProfile) {
612
+ if (this.closed)
613
+ return { open: false, restarted: false, waitingOn: [] };
614
+ const key = this.sessions.get(sessionId)?.profileKey;
615
+ if (key !== undefined)
616
+ while (this.restartingProfiles.has(key))
617
+ await this.restartingProfiles.get(key).catch(() => { });
618
+ if (everyProfile)
619
+ for (const profile of this.profiles.keys())
620
+ this.pendingRestart.add(profile);
621
+ if (key !== undefined && this.sessions.get(sessionId)?.profileKey === key)
622
+ this.pendingRestart.add(key);
623
+ await this.retryPendingRestarts(false, sessionId);
624
+ if (key === undefined || this.sessions.get(sessionId)?.profileKey !== key)
625
+ return { open: false, restarted: false, waitingOn: [] };
626
+ if (!this.pendingRestart.has(key))
627
+ return { open: true, restarted: true, waitingOn: [] };
628
+ const now = Date.now();
629
+ const waitingOn = [...this.sessions].filter(([id, session]) => id !== sessionId && session.profileKey === key && (this.holds.get(id) ?? 0) > now).map(([id]) => id);
630
+ return { open: true, restarted: false, waitingOn };
631
+ }
632
+ async retryPendingRestarts(force = false, ownHold) {
633
+ if (this.closed)
634
+ return { restarted: 0, pending: [] };
635
+ const now = Date.now();
636
+ let restarted = 0;
637
+ const work = [];
638
+ for (const key of [...this.pendingRestart]) {
639
+ const members = [...this.sessions].filter(([, session]) => session.profileKey === key);
640
+ const host = this.profiles.get(key);
641
+ if (!host && members.length === 0) {
642
+ this.pendingRestart.delete(key);
643
+ continue;
644
+ }
645
+ if (host && (!host.context || members.length === 0))
646
+ continue;
647
+ // A restart still restoring this profile's tabs finishes first; the change stays queued and runs
648
+ // once it is done, with a snapshot of every restored tab rather than a half-restored one.
649
+ if (this.restartingProfiles.has(key))
650
+ continue;
651
+ const held = members.some(([id]) => id !== ownHold && (this.holds.get(id) ?? 0) > now);
652
+ if (held && !force)
653
+ continue;
654
+ this.pendingRestart.delete(key);
655
+ restarted += 1;
656
+ const running = this.restartProfile(key, members.map(([id]) => id));
657
+ this.restartsInFlight.add(running);
658
+ this.restartingProfiles.set(key, running);
659
+ work.push(running.finally(() => {
660
+ this.restartsInFlight.delete(running);
661
+ if (this.restartingProfiles.get(key) === running)
662
+ this.restartingProfiles.delete(key);
663
+ if (this.pendingRestart.has(key) && !this.closed)
664
+ void this.retryPendingRestarts(force).catch(() => { });
665
+ }));
666
+ }
667
+ await Promise.all(work);
668
+ this.armRestartPoll();
669
+ if (this.pendingRestart.size === 0 && this.restartsInFlight.size === 0)
670
+ this.options.extensions?.settled?.();
671
+ const pending = this.pendingRestartSessions();
672
+ this.emit('browser.extensions', { kind: 'restart', pending });
673
+ return { restarted, pending };
674
+ }
675
+ pendingRestartSessions() {
676
+ return [...this.sessions].filter(([, session]) => session.profileKey !== undefined && this.pendingRestart.has(session.profileKey)).map(([id]) => id);
677
+ }
678
+ armRestartPoll() {
679
+ if (this.restartPoll || this.pendingRestart.size === 0 || this.closed)
680
+ return;
681
+ this.restartPoll = setTimeout(() => {
682
+ this.restartPoll = undefined;
683
+ if (this.pendingRestart.size)
684
+ void this.retryPendingRestarts(false).catch(() => { });
685
+ }, EXTENSION_RESTART_POLL_MS);
686
+ this.restartPoll.unref?.();
687
+ }
688
+ async restartProfile(key, sessionIds) {
689
+ const snapshots = sessionIds.flatMap(sessionId => {
690
+ const session = this.sessions.get(sessionId);
691
+ if (!session)
692
+ return [];
693
+ const tabs = [...session.tabs.values()];
694
+ const urls = tabs.map(tab => tab.url);
695
+ return [{ sessionId, urls, active: tabs.findIndex(tab => tab.id === session.activeTabId) }];
696
+ });
697
+ const tokens = new Map(snapshots.map(snapshot => [snapshot.sessionId, { cancelled: false, abandoned: false }]));
698
+ for (const [sessionId, token] of tokens)
699
+ this.restoring.set(sessionId, token);
700
+ const host = this.profiles.get(key);
701
+ let finishRestart;
702
+ if (host)
703
+ host.restarting = new Promise(resolve => { finishRestart = resolve; });
704
+ try {
705
+ try {
706
+ await Promise.all(sessionIds.map(sessionId => this.closeSession(sessionId, 'extensions')));
707
+ await host?.closing;
708
+ }
709
+ finally {
710
+ if (host) {
711
+ host.restarting = undefined;
712
+ finishRestart();
713
+ }
714
+ }
715
+ for (const snapshot of snapshots) {
716
+ const token = tokens.get(snapshot.sessionId);
717
+ const opened = [];
718
+ for (const url of snapshot.urls) {
719
+ if (token.cancelled || token.abandoned || this.closed)
720
+ break;
721
+ // The session may have moved to another browser meanwhile (incognito): its tabs are not
722
+ // this profile's to fill, and the switch's own blank tab stays the one shown.
723
+ const current = this.sessions.get(snapshot.sessionId);
724
+ if (this.incognito.has(snapshot.sessionId) || (current && current.profileKey !== key)) {
725
+ token.abandoned = true;
726
+ break;
727
+ }
728
+ let target;
729
+ try {
730
+ target = browserViewUrl(url);
731
+ }
732
+ catch {
733
+ target = undefined;
734
+ }
735
+ if (!target) {
736
+ opened.push(undefined);
737
+ continue;
738
+ }
739
+ try {
740
+ opened.push((await this.openPage(snapshot.sessionId, target)).tabId);
741
+ }
742
+ catch {
743
+ opened.push(undefined);
744
+ }
745
+ }
746
+ if (token.cancelled) {
747
+ await this.closeSession(snapshot.sessionId, 'released');
748
+ continue;
749
+ }
750
+ if (token.abandoned)
751
+ continue;
752
+ const active = snapshot.active >= 0 ? opened[snapshot.active] : undefined;
753
+ if (active)
754
+ await this.activateTab(snapshot.sessionId, active).catch(() => { });
755
+ // The saved tabs are back; extension pages the relaunch opened take what room is left.
756
+ if (this.restoring.get(snapshot.sessionId) === token)
757
+ this.restoring.delete(snapshot.sessionId);
758
+ const restored = this.sessions.get(snapshot.sessionId);
759
+ if (restored)
760
+ this.claimUnclaimed(snapshot.sessionId, restored);
761
+ }
762
+ }
763
+ finally {
764
+ for (const [sessionId, token] of tokens)
765
+ if (this.restoring.get(sessionId) === token)
766
+ this.restoring.delete(sessionId);
767
+ }
768
+ }
548
769
  async acquireProfile(owner, profile, viewport, scale) {
549
770
  for (;;) {
550
771
  const current = this.profiles.get(profile.key);
@@ -552,29 +773,41 @@ export class BrowserViewManager {
552
773
  await current.closing;
553
774
  continue;
554
775
  }
555
- const host = current ?? { users: new Set() };
776
+ if (current?.restarting) {
777
+ await current.restarting;
778
+ continue;
779
+ }
780
+ const host = current ?? { users: new Set(), pendingBlanks: [] };
556
781
  if (!current)
557
782
  this.profiles.set(profile.key, host);
558
783
  host.users.add(owner);
559
- // A profile already running keeps the factor it was launched with: one
560
- // process, one surface scale, shared by every session of the project.
561
784
  if (!host.starting)
562
785
  host.scale = scale;
563
786
  host.starting ??= this.launchPersistent(profile.directory, viewport, scale).then(async (context) => {
564
- // A persistent launch opens with a blank page of its own; every tab the
565
- // panel shows is one a session asked for.
566
- for (const page of context.pages?.() ?? [])
567
- await Promise.resolve().then(() => page.close()).catch(() => { });
787
+ const pages = context.pages?.() ?? [];
788
+ const isBlank = (page) => {
789
+ const url = String(page.url?.() ?? '');
790
+ return !url || url === 'about:blank';
791
+ };
792
+ (host.unclaimed ??= []).push(...pages.filter(page => !isBlank(page)));
793
+ // Hold the leftover about:blank pages instead of closing them: under a headed
794
+ // launch the initial about:blank is the only tab of the real window, and
795
+ // closing it destroys the window, so every later Target.createTarget fails
796
+ // with "Failed to open a new tab". Headless tolerated that; a real window does
797
+ // not. The blanks are drained (drainPendingBlanks) as soon as the profile has
798
+ // a real page keeping the window alive.
799
+ host.pendingBlanks.push(...pages.filter(page => isBlank(page)));
800
+ context.on?.('page', (page) => { void this.claimExtensionPage(profile.key, page); });
568
801
  context.on?.('close', () => { if (this.profiles.get(profile.key) === host)
569
802
  this.profiles.delete(profile.key); });
570
803
  host.context = context;
804
+ this.parkWindow(context?.browser?.());
571
805
  return context;
572
806
  });
573
807
  try {
574
808
  return { context: await host.starting, scale: host.scale ?? 1 };
575
809
  }
576
810
  catch (error) {
577
- // A failed launch is not cached: the next open tries the profile again.
578
811
  host.users.delete(owner);
579
812
  if (this.profiles.get(profile.key) === host)
580
813
  this.profiles.delete(profile.key);
@@ -582,7 +815,56 @@ export class BrowserViewManager {
582
815
  }
583
816
  }
584
817
  }
585
- /** Leave a project's profile; the last session out closes it, which flushes cookies to disk. */
818
+ /**
819
+ * Closes the blank pages a persistent launch was left holding, once the profile
820
+ * has at least one real page: under a headed launch the initial about:blank is
821
+ * the only tab of the real window, and closing it while it is alone destroys the
822
+ * window, so the blanks are held until a real page keeps the window alive.
823
+ */
824
+ async drainPendingBlanks(host) {
825
+ if (!host?.pendingBlanks?.length)
826
+ return;
827
+ const blanks = host.pendingBlanks.splice(0);
828
+ for (const blank of blanks)
829
+ await Promise.resolve().then(() => blank.close()).catch(() => { });
830
+ }
831
+ async claimExtensionPage(key, page) {
832
+ await new Promise(resolve => { const timer = setTimeout(resolve, EXTENSION_PAGE_CLAIM_MS); timer.unref?.(); });
833
+ if (this.claimedPages.has(page) || page.isClosed?.() === true || this.closed)
834
+ return;
835
+ for (const session of this.sessions.values())
836
+ for (const tab of session.tabs.values())
837
+ if (tab.page === page)
838
+ return;
839
+ // A session whose saved tabs are still being reopened takes extension pages only once they are all back.
840
+ const members = [...this.sessions].filter(([id, session]) => session.profileKey === key && !session.closing && !this.restoring.has(id));
841
+ const [owner] = members.filter(([, session]) => session.streaming).concat(members);
842
+ if (!owner) {
843
+ const host = this.profiles.get(key);
844
+ if (host)
845
+ (host.unclaimed ??= []).push(page);
846
+ else
847
+ await Promise.resolve().then(() => page.close()).catch(() => { });
848
+ return;
849
+ }
850
+ this.claimedPages.add(page);
851
+ await this.adoptPage(owner[0], owner[1], page);
852
+ }
853
+ claimUnclaimed(sessionId, session) {
854
+ // Saved tabs come first: a session being restored claims extension pages after its last tab is back.
855
+ if (this.restoring.has(sessionId))
856
+ return;
857
+ const host = session.profileKey === undefined ? undefined : this.profiles.get(session.profileKey);
858
+ const pages = host?.unclaimed?.splice(0) ?? [];
859
+ for (const page of pages) {
860
+ if (page.isClosed?.() === true)
861
+ continue;
862
+ this.claimedPages.add(page);
863
+ void this.adoptPage(sessionId, session, page);
864
+ }
865
+ if (pages.length)
866
+ void this.drainPendingBlanks(host);
867
+ }
586
868
  async releaseProfile(key, owner) {
587
869
  const host = this.profiles.get(key);
588
870
  if (!host)
@@ -601,10 +883,6 @@ export class BrowserViewManager {
601
883
  })();
602
884
  await host.closing;
603
885
  }
604
- /**
605
- * Open the browser a new session's pages will live in: its project's profile,
606
- * or a throwaway browser when the session is incognito or has no usable profile.
607
- */
608
886
  async openBrowserFor(sessionId, viewport, scale) {
609
887
  if (!this.incognito.has(sessionId)) {
610
888
  const profile = this.options.profileFor ? await this.options.profileFor(sessionId).catch(() => undefined) : undefined;
@@ -617,18 +895,15 @@ export class BrowserViewManager {
617
895
  catch (error) {
618
896
  if (this.closed)
619
897
  throw error;
620
- // Another process holds the folder, or the profile cannot be opened: the
621
- // panel still works, on a throwaway browser that says so.
622
898
  }
623
899
  }
624
900
  }
625
- return { browser: await this.launch(scale), profile: this.incognito.has(sessionId) ? 'incognito' : 'isolated', renderScale: scale };
901
+ const browser = await this.launch(scale);
902
+ this.parkWindow(browser);
903
+ return { browser, profile: this.incognito.has(sessionId) ? 'incognito' : 'isolated', renderScale: scale };
626
904
  }
627
- /** Close a session's browser, or only its pages when they live in a shared project profile. */
628
905
  async disposeBrowser(session) {
629
906
  if (session.profileKey === undefined || session.profileOwner === undefined) {
630
- // Playwright transport shutdown is not reliably awaitable; own the
631
- // rejection and let the browser close land whenever it lands.
632
907
  await Promise.resolve().then(() => session.browser?.close()).catch(() => { });
633
908
  return;
634
909
  }
@@ -643,26 +918,12 @@ export class BrowserViewManager {
643
918
  };
644
919
  }
645
920
  publishTabs(sessionId, session) {
646
- // A browser being torn down is no longer the session's: a replacement may
647
- // already hold the id, and the old generation's late events must not speak
648
- // for it.
649
921
  if (session.closing || this.sessions.get(sessionId) !== session)
650
922
  return;
651
923
  this.emit('browser.view', { kind: 'tabs', sessionId, ...this.summary(session) });
652
924
  }
653
- /**
654
- * Keep a session's panel browser from being idle-reaped for the next `ms`.
655
- *
656
- * A live run whose agent drove the panel renews this lease while it lasts, so
657
- * a page it opened for the user — a sign-in it asked them to complete, say —
658
- * is still there when they look, however long the run waits on their answer.
659
- * A lease, not a flag: a run engine that dies stops renewing, and the browser
660
- * falls back to the ordinary idle window instead of staying pinned forever.
661
- */
662
925
  hold(sessionId, ms) {
663
926
  const now = Date.now();
664
- // A lapsed lease still sets its session's idle deadline (lease end + the idle window), so it is
665
- // forgotten only once that deadline has passed too.
666
927
  for (const [id, until] of this.holds)
667
928
  if (until + VIEW_IDLE_CLOSE_MS <= now)
668
929
  this.holds.delete(id);
@@ -672,14 +933,8 @@ export class BrowserViewManager {
672
933
  scheduleIdleClose(sessionId, session, delay = VIEW_IDLE_CLOSE_MS) {
673
934
  if (session.idleTimer)
674
935
  clearTimeout(session.idleTimer);
675
- // A session someone is watching (streaming) is never idle-reaped; only an
676
- // abandoned open browser is, so a forgotten panel cannot pin memory forever.
677
936
  session.idleTimer = setTimeout(() => {
678
937
  session.idleTimer = undefined;
679
- // A browser a run held is not idle until a full idle window after its
680
- // latest lease ends. The lease is read now, not when this check was
681
- // scheduled: renewals since then move the deadline, and an earlier check
682
- // that fires on a stale deadline just looks again at the current one.
683
938
  const until = this.holds.get(sessionId);
684
939
  if (until !== undefined) {
685
940
  const remaining = until + VIEW_IDLE_CLOSE_MS - Date.now();
@@ -689,7 +944,6 @@ export class BrowserViewManager {
689
944
  }
690
945
  this.holds.delete(sessionId);
691
946
  }
692
- // A tab still being created is work in progress, not idleness.
693
947
  if (!session.streaming && session.pendingTabs === 0)
694
948
  void this.closeSession(sessionId, 'idle', session);
695
949
  }, delay);
@@ -705,56 +959,20 @@ export class BrowserViewManager {
705
959
  try {
706
960
  await tab.cdp?.send('Page.stopScreencast');
707
961
  }
708
- catch { /* The page is already gone. */ }
962
+ catch { }
709
963
  }
710
- /**
711
- * Show one tab: the pane's current size, then its stream.
712
- *
713
- * Every path that makes a tab the visible one goes through here — an explicit
714
- * activation, an open that completed while it still owned the selection, and
715
- * the fallback chosen when the active tab closes — because a pane resized
716
- * while the tab was inactive only sized the active page, and a page laid out
717
- * at a stale size puts every translated click in the wrong place.
718
- */
719
964
  async showTab(session, tab) {
720
965
  if (session.activeTabId !== tab.id)
721
966
  return;
722
967
  await this.queueViewportMode(session, tab);
723
- // Two activations can overlap: the later one owns the pane by the time this
724
- // page finishes resizing, and a stream started for the earlier tab would be
725
- // a stream nobody sees — while its `streaming` flag would keep the next
726
- // selection of that tab from ever starting one.
727
968
  if (session.activeTabId !== tab.id)
728
969
  return;
729
970
  await this.startScreencast(session, tab);
730
971
  }
731
- /**
732
- * Put one page into the session's viewport mode.
733
- *
734
- * Desktop sizes the page to the pane. Mobile is full emulation: the fixed
735
- * phone's device metrics — `mobile: true` is what makes the meta viewport
736
- * respected, with a phone's pixel density — a mobile Chrome user agent, and
737
- * touch events, so the sites the pane shows answer with their mobile layouts
738
- * and hover-dependent UIs behave like they do on a phone. Leaving Mobile
739
- * clears the metrics and applies the desktop spoof identity (see
740
- * browser-stealth), so the page presents as a normal desktop browser rather
741
- * than the headless automation UA a reset would expose. A switch changes the
742
- * page's size, so the caller restarts the screencast for the new capture
743
- * scale.
744
- *
745
- * Calls for one tab are serialized by `queueViewportMode`: each applies
746
- * whatever the session's mode is at its turn, so a rapid toggle cannot leave
747
- * a page emulated under a session that has already moved on.
748
- */
749
972
  async applyViewportMode(session, tab) {
750
973
  const mobile = session.mode === 'mobile';
751
974
  try {
752
975
  if (mobile) {
753
- // Full device metrics, not just dimensions. Playwright's own
754
- // setViewportSize would re-issue the override with `mobile: false`, so
755
- // while Mobile is on, this override is the page's only sizing
756
- // authority (verified live: the metrics override yields exactly
757
- // 390×844 screencast frames at a phone's pixel density).
758
976
  await tab.cdp.send('Emulation.setDeviceMetricsOverride', {
759
977
  width: VIEW_MOBILE_VIEWPORT.width, height: VIEW_MOBILE_VIEWPORT.height, deviceScaleFactor: VIEW_MOBILE_SCALE, mobile: true,
760
978
  });
@@ -763,13 +981,6 @@ export class BrowserViewManager {
763
981
  if (tab.emulated)
764
982
  await tab.cdp.send('Emulation.clearDeviceMetricsOverride');
765
983
  await tab.page.setViewportSize(session.viewport).catch(() => { });
766
- // Playwright sizes the page at 1×, which on a browser launched at a
767
- // higher factor renders at 1× and stretches into the surface — the blur
768
- // this exists to remove. The page renders at the browser's real factor
769
- // instead, as a native window on that display would, sharp text and
770
- // `srcset` images included. The override is sent every time and after
771
- // Playwright's: Playwright skips a size it believes it already applied,
772
- // so it cannot be relied on to put back a ratio this override replaced.
773
984
  await tab.cdp.send('Emulation.setDeviceMetricsOverride', {
774
985
  width: session.viewport.width, height: session.viewport.height, deviceScaleFactor: session.renderScale, mobile: false,
775
986
  });
@@ -777,23 +988,42 @@ export class BrowserViewManager {
777
988
  if (mobile === Boolean(tab.emulated))
778
989
  return;
779
990
  tab.emulated = mobile;
780
- await tab.cdp.send('Emulation.setUserAgentOverride', mobile
781
- ? { userAgent: VIEW_MOBILE_USER_AGENT }
782
- // Desktop presents the spoofed identity too: an empty override would
783
- // expose the headless browser's own UA to every site the panel shows.
784
- : desktopUaOverride());
785
- await tab.cdp.send('Emulation.setTouchEmulationEnabled', { enabled: mobile, ...(mobile ? { maxTouchPoints: 5 } : {}) });
991
+ if (mobile) {
992
+ const version = this.browserVersion(session);
993
+ await tab.cdp.send('Emulation.setUserAgentOverride', { userAgent: mobileUserAgent(version), userAgentMetadata: userAgentMetadata(version, true) });
994
+ await tab.cdp.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
995
+ }
996
+ else {
997
+ // Switching back to desktop re-applies the desktop identity: built from the
998
+ // real running version when it can be read, the stealth fallback otherwise.
999
+ await this.applyDesktopIdentity(session, tab);
1000
+ await tab.cdp.send('Emulation.setTouchEmulationEnabled', { enabled: false });
1001
+ }
786
1002
  }
787
- catch { /* The page is gone; the next activation retries. */ }
1003
+ catch { }
788
1004
  }
789
- /** The per-tab serialization `applyViewportMode` relies on; see its note. */
790
1005
  queueViewportMode(session, tab) {
791
1006
  const tail = (tab.modeTask ?? Promise.resolve()).catch(() => { });
792
1007
  tab.modeTask = tail.then(() => this.applyViewportMode(session, tab));
793
1008
  return tab.modeTask;
794
1009
  }
1010
+ browserVersion(session) {
1011
+ const context = session.context;
1012
+ const version = (context?.browser?.() ?? this.browserFor(session))?.version?.();
1013
+ return typeof version === 'string' && /^\d+(\.\d+)*$/.test(version) ? version : undefined;
1014
+ }
1015
+ /**
1016
+ * The desktop override after mobile emulation: built from the real running
1017
+ * browser version when it is readable, falling back to the stealth version when
1018
+ * it is not. A desktop UA carrying a version the running browser does not have
1019
+ * is exactly what fingerprinting checks catch, so the real one wins whenever it
1020
+ * is available.
1021
+ */
1022
+ async applyDesktopIdentity(session, tab) {
1023
+ const version = this.browserVersion(session);
1024
+ await tab.cdp.send('Emulation.setUserAgentOverride', { ...desktopUaOverride(process.platform, version), userAgentMetadata: userAgentMetadata(version) }).catch(() => { });
1025
+ }
795
1026
  emitFrame(sessionId, session, tab, payload) {
796
- // Frames still in flight from a replaced browser belong to nobody.
797
1027
  if (session.closing || this.sessions.get(sessionId) !== session)
798
1028
  return;
799
1029
  if (payload.data.length > VIEW_FRAME_LIMIT) {
@@ -822,11 +1052,6 @@ export class BrowserViewManager {
822
1052
  try {
823
1053
  await tab.cdp.send('Page.startScreencast', {
824
1054
  format: 'jpeg', quality: Math.min(session.quality, budget.quality),
825
- // The viewport at the pane's ratio: one frame pixel per screen pixel.
826
- // A browser launched at that ratio fills it exactly; one launched
827
- // denser (the window moved to a lower-density monitor) is scaled down
828
- // to it once, and the caps never scale a frame up. A page whose frames
829
- // outgrew the payload limit runs at a reduced size until it changes.
830
1055
  maxWidth: Math.ceil(session.viewport.width * session.scale * budget.size),
831
1056
  maxHeight: Math.ceil(session.viewport.height * session.scale * budget.size),
832
1057
  everyNthFrame: 1,
@@ -836,11 +1061,6 @@ export class BrowserViewManager {
836
1061
  tab.streaming = false;
837
1062
  }
838
1063
  }
839
- /**
840
- * Step one tab's frame budget down after a frame came out over the limit, and
841
- * restart its stream at it. The oversized frame itself is not sent; the pane
842
- * keeps its previous frame until the smaller stream delivers.
843
- */
844
1064
  async shrinkStream(session, tab) {
845
1065
  if (tab.shrinking || !tab.streaming)
846
1066
  return;
@@ -850,7 +1070,6 @@ export class BrowserViewManager {
850
1070
  tab.budget = next;
851
1071
  await this.restartStream(session, tab);
852
1072
  }
853
- /** Stop and start one tab's stream, keeping it only while it still owns the pane. */
854
1073
  async restartStream(session, tab) {
855
1074
  if (tab.shrinking)
856
1075
  return;
@@ -869,19 +1088,21 @@ export class BrowserViewManager {
869
1088
  id: randomUUID(), page, cdp, url: '', title: '', loading: false,
870
1089
  streaming: false, seq: 0, lastEmitAt: undefined, imageWidth: session.viewport.width, imageHeight: session.viewport.height,
871
1090
  };
1091
+ // The target id ties window moves (show/hide) to the window that holds this
1092
+ // tab, so an extension popup opening its own window does not move the wrong one.
1093
+ void Promise.resolve().then(() => cdp.send('Target.getTargetInfo')).then((info) => {
1094
+ const id = info?.targetInfo?.targetId;
1095
+ if (typeof id === 'string' && id)
1096
+ tab.targetId = id;
1097
+ }).catch(() => { });
872
1098
  const publish = () => this.publishTabs(sessionId, session);
873
- // A fragment link or a `pushState` route change commits without loading a
874
- // document: `framenavigated` fires, `domcontentloaded` does not. Tracking the
875
- // document request is what tells the two apart, so the commit of a new
876
- // document clears the previous one's title and marks the tab loading while a
877
- // same-document commit only moves the address.
878
1099
  let documentRequest;
879
1100
  page.on('request', (request) => {
880
1101
  try {
881
1102
  if (request?.isNavigationRequest?.() === true && request.frame?.() === page.mainFrame())
882
1103
  documentRequest = request;
883
1104
  }
884
- catch { /* A request with no frame is not the document's own. */ }
1105
+ catch { }
885
1106
  });
886
1107
  page.on('requestfailed', (request) => { if (request === documentRequest)
887
1108
  documentRequest = undefined; });
@@ -894,8 +1115,6 @@ export class BrowserViewManager {
894
1115
  if (newDocument) {
895
1116
  tab.loading = true;
896
1117
  tab.title = '';
897
- // The budget was earned by the previous document's content; the next
898
- // page gets full quality and size again.
899
1118
  if (tab.budget) {
900
1119
  tab.budget = undefined;
901
1120
  if (tab.streaming)
@@ -922,27 +1141,18 @@ export class BrowserViewManager {
922
1141
  if (next)
923
1142
  void this.showTab(session, next);
924
1143
  }
925
- // A tab whose page is still being created is a live session too: closing
926
- // the browser here would take it away from the open that is waiting on it.
927
1144
  if (session.tabs.size === 0 && session.pendingTabs === 0)
928
1145
  void this.closeSession(sessionId, undefined, session);
929
1146
  else
930
1147
  publish();
931
1148
  });
932
1149
  page.on('crash', () => { void page.close().catch(() => { }); });
933
- // A `target="_blank"` link or `window.open()` opens a page of its own; without
934
- // this the destination loads in a browser nobody can see. A popup becomes a
935
- // tab of the session (the cap applies to it like any other open), and it
936
- // takes the pane so the user follows the link they clicked.
937
- page.on('popup', (popup) => { void this.adoptPage(sessionId, session, popup); });
1150
+ page.on('popup', (popup) => { this.claimedPages.add(popup); void this.adoptPage(sessionId, session, popup); });
938
1151
  cdp.on('Page.screencastFrame', async (payload) => {
939
- // Acknowledge first, always: the stream has a small outstanding-frame
940
- // window, and an unacknowledged frame stalls it even when this frame is
941
- // held back by the pacing window or its tab is no longer active.
942
1152
  try {
943
1153
  await cdp.send('Page.screencastFrameAck', { sessionId: payload.sessionId });
944
1154
  }
945
- catch { /* Gone. */ }
1155
+ catch { }
946
1156
  if (!tab.streaming || session.activeTabId !== tab.id || session.closing)
947
1157
  return;
948
1158
  const now = Date.now();
@@ -955,9 +1165,6 @@ export class BrowserViewManager {
955
1165
  this.emitFrame(sessionId, session, tab, payload);
956
1166
  return;
957
1167
  }
958
- // Inside the pacing window: keep only the newest image and deliver it
959
- // when the window opens. Dropping it outright would leave the panel on an
960
- // older frame forever when the page's last update lands here.
961
1168
  tab.pendingFrame = payload;
962
1169
  if (tab.pendingTimer)
963
1170
  return;
@@ -975,14 +1182,6 @@ export class BrowserViewManager {
975
1182
  session.tabs.set(tab.id, tab);
976
1183
  return tab;
977
1184
  }
978
- /**
979
- * A frame straight from the page, for a stream that is already running.
980
- *
981
- * A pane that reattaches (a renderer reload) has no image of its own, and a
982
- * static page produces no new screencast frames, so the screencast's own
983
- * stream cannot supply one. A screenshot is bounded and always reflects the
984
- * page as it is now.
985
- */
986
1185
  async captureFrame(sessionId, session, tab) {
987
1186
  try {
988
1187
  const shot = await tab.cdp?.send('Page.captureScreenshot', { format: 'jpeg', quality: session.quality });
@@ -992,15 +1191,8 @@ export class BrowserViewManager {
992
1191
  return;
993
1192
  this.emitFrame(sessionId, session, tab, { data: shot.data, sessionId: 'capture' });
994
1193
  }
995
- catch { /* The page may be mid-navigation; the stream supplies the next frame. */ }
1194
+ catch { }
996
1195
  }
997
- /**
998
- * A page the browser opened on its own, adopted as a tab of the session.
999
- *
1000
- * The page is already live, so it only needs a CDP session and its pane
1001
- * geometry. Past the tab cap the popup is closed rather than left running as an
1002
- * invisible page: the cap states one bound for everything the browser holds.
1003
- */
1004
1196
  async adoptPage(sessionId, session, page) {
1005
1197
  if (session.closing) {
1006
1198
  await Promise.resolve().then(() => page.close()).catch(() => { });
@@ -1016,12 +1208,6 @@ export class BrowserViewManager {
1016
1208
  const previous = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1017
1209
  if (previous)
1018
1210
  await this.stopScreencast(previous);
1019
- // Adoption yields before it takes the pane, so a tab activated meanwhile is
1020
- // streaming by now; assigning the popup would discard its frames while its
1021
- // `streaming` flag stayed on, and reselecting it would request neither a new
1022
- // screencast nor a screenshot. Stop the tab that actually holds the pane, as
1023
- // an open does; the loop is bounded by a stream really running, because a
1024
- // stop with nothing to do cannot have yielded.
1025
1211
  let selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1026
1212
  while (selected && selected.streaming) {
1027
1213
  await this.stopScreencast(selected);
@@ -1033,9 +1219,6 @@ export class BrowserViewManager {
1033
1219
  }
1034
1220
  const tab = this.wireTab(sessionId, session, page, cdp);
1035
1221
  await this.queueViewportMode(session, tab);
1036
- // The mode application yields, so a tab the user activated meanwhile can
1037
- // be streaming: it stops before the popup takes the pane, or it would
1038
- // stream on with nobody watching — the same reason the loop above ran.
1039
1222
  selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1040
1223
  while (selected && selected.streaming) {
1041
1224
  await this.stopScreencast(selected);
@@ -1046,8 +1229,6 @@ export class BrowserViewManager {
1046
1229
  return;
1047
1230
  }
1048
1231
  session.activeTabId = tab.id;
1049
- // The popup has usually navigated before it reached us, so its landing URL
1050
- // is read from the page rather than waiting for an event that already fired.
1051
1232
  tab.url = String(page.url?.() ?? '').slice(0, VIEW_URL_LIMIT);
1052
1233
  void page.title?.().then((title) => {
1053
1234
  if (typeof title === 'string' && title) {
@@ -1071,9 +1252,6 @@ export class BrowserViewManager {
1071
1252
  this.scheduleIdleClose(sessionId, existing);
1072
1253
  return existing;
1073
1254
  }
1074
- // A second open can arrive while the first is still launching (Enter pressed
1075
- // twice). It joins that launch instead of starting a second browser whose
1076
- // session record would overwrite the first and leave it unreachable.
1077
1255
  const inflight = this.launching.get(sessionId);
1078
1256
  if (inflight)
1079
1257
  return await inflight;
@@ -1085,23 +1263,14 @@ export class BrowserViewManager {
1085
1263
  const desired = this.desired.get(sessionId);
1086
1264
  const viewport = desired?.viewport ?? clampViewport(undefined, undefined);
1087
1265
  const opened = await this.openBrowserFor(sessionId, viewport, desired?.scale ?? this.displayScale);
1088
- // Shutdown may have finished while the launch was in flight: the browser
1089
- // that arrived late belongs to nobody, so it is closed here rather than
1090
- // inserted into a manager that has already visited its sessions.
1091
1266
  if (this.closed) {
1092
1267
  await this.disposeBrowser({ ...opened, tabs: new Map() });
1093
1268
  throw new Error('Application is shutting down');
1094
1269
  }
1095
- // A release that landed while this launch was in flight has already closed
1096
- // whatever it found; the browser this launch just produced belongs to the
1097
- // session that no longer exists, so it goes the same way.
1098
1270
  if (this.released.delete(sessionId)) {
1099
1271
  await this.disposeBrowser({ ...opened, tabs: new Map() });
1100
1272
  throw new Error('That session was deleted.');
1101
1273
  }
1102
- // The pane can enable streaming, resize or switch mode while the launch is in
1103
- // flight; those requests found no session to update, so the session takes
1104
- // the request as it stands now, not as it stood when the launch began.
1105
1274
  const current = this.desired.get(sessionId);
1106
1275
  const session = {
1107
1276
  ...opened, tabs: new Map(), activeTabId: undefined, pendingTabs: 0,
@@ -1112,6 +1281,7 @@ export class BrowserViewManager {
1112
1281
  };
1113
1282
  this.sessions.set(sessionId, session);
1114
1283
  this.scheduleIdleClose(sessionId, session);
1284
+ this.claimUnclaimed(sessionId, session);
1115
1285
  return session;
1116
1286
  })();
1117
1287
  this.launching.set(sessionId, starting);
@@ -1122,43 +1292,26 @@ export class BrowserViewManager {
1122
1292
  this.launching.delete(sessionId);
1123
1293
  }
1124
1294
  }
1125
- /**
1126
- * The session's browser context, created once.
1127
- *
1128
- * One context is what makes the tabs one browser: cookies, local storage and
1129
- * cache are shared across the pages in it. A project session's context is its
1130
- * project's persistent profile, shared with that project's other sessions; an
1131
- * incognito or isolated session gets a fresh context of its own.
1132
- */
1133
1295
  async contextFor(session) {
1134
1296
  if (session.context)
1135
1297
  return session.context;
1136
1298
  session.contextTask ??= Promise.resolve()
1137
- .then(() => session.browser.newContext({ viewport: { ...session.viewport }, acceptDownloads: false, ...stealthContextOptions() }))
1299
+ // Headed: the browser's own identity goes through, only the locale stays as a stealth option.
1300
+ .then(() => session.browser.newContext({ viewport: { ...session.viewport }, acceptDownloads: false, locale: STEALTH_LOCALE }))
1138
1301
  .then(async (context) => { await hardenContext(context); session.context = context; return context; });
1139
1302
  return await session.contextTask;
1140
1303
  }
1141
1304
  async openTab(sessionId, url, signal) {
1142
1305
  return await this.openPage(sessionId, browserViewUrl(url), signal);
1143
1306
  }
1144
- /**
1145
- * Replace the session's panel browser with an incognito one showing a blank tab.
1146
- *
1147
- * The current browser closes first — its tabs go with it, and a project
1148
- * profile it used is left untouched on disk. Nothing the incognito browser
1149
- * does is saved, and it lasts until `endIncognito` or until it closes.
1150
- */
1151
1307
  async startIncognito(sessionId, signal) {
1152
- // Wait out every launch for this session, including one an open began while
1153
- // this call was waiting, so nothing registers a project browser behind it.
1154
1308
  while (this.launching.has(sessionId))
1155
1309
  await this.launching.get(sessionId).catch(() => undefined);
1156
- // A switch that was stopped or timed out while waiting must not tear down the
1157
- // browser the user is using: nothing has been closed yet.
1158
1310
  signal?.throwIfAborted();
1159
- // From here to the mark there is no await: the old browser leaves the session
1160
- // table synchronously, and the mark is set before anything can open another,
1161
- // so an open that arrives during the teardown launches incognito too.
1311
+ // An extension restart about to reopen this session's project tabs leaves the switch alone.
1312
+ const restoring = this.restoring.get(sessionId);
1313
+ if (restoring)
1314
+ restoring.abandoned = true;
1162
1315
  const closing = this.closeSession(sessionId, 'incognito');
1163
1316
  this.incognito.add(sessionId);
1164
1317
  await closing;
@@ -1167,10 +1320,6 @@ export class BrowserViewManager {
1167
1320
  return await this.openPage(sessionId, 'about:blank', signal, 'incognito');
1168
1321
  }
1169
1322
  catch (error) {
1170
- // A start that failed or was abandoned (stopped, or past its deadline) must
1171
- // not leave an incognito browser a later open would land in unannounced:
1172
- // one that launched but holds no tab is closed, which also clears the mark,
1173
- // and a browser that never started leaves no mark behind.
1174
1323
  const session = this.sessions.get(sessionId);
1175
1324
  if (!session)
1176
1325
  this.incognito.delete(sessionId);
@@ -1179,12 +1328,9 @@ export class BrowserViewManager {
1179
1328
  throw error;
1180
1329
  }
1181
1330
  }
1182
- /** Close the session's incognito browser, if it has one; the next open uses the project profile. */
1183
1331
  async endIncognito(sessionId, signal) {
1184
1332
  while (this.launching.has(sessionId))
1185
1333
  await this.launching.get(sessionId).catch(() => undefined);
1186
- // An end that was stopped or timed out while a launch finished must not close
1187
- // the browser afterwards: nothing has changed yet, and the agent was told it failed.
1188
1334
  signal?.throwIfAborted();
1189
1335
  const session = this.sessions.get(sessionId);
1190
1336
  const active = this.incognito.delete(sessionId) || session?.profile === 'incognito';
@@ -1192,14 +1338,6 @@ export class BrowserViewManager {
1192
1338
  await this.closeSession(sessionId, 'incognito ended');
1193
1339
  return active;
1194
1340
  }
1195
- /**
1196
- * Add cookies to the project profile the session's panel browser runs on, then
1197
- * reload its active tab so the page is requested again with them.
1198
- *
1199
- * Only the project profile takes an import: it is the one browser whose cookies
1200
- * are kept, and the one the pane's badge never marks as temporary. The cookies
1201
- * go to the profile's shared context, so every session of the project has them.
1202
- */
1203
1341
  async importCookies(sessionId, cookies) {
1204
1342
  const session = this.sessions.get(sessionId);
1205
1343
  if (!session || session.closing || session.tabs.size === 0)
@@ -1210,28 +1348,18 @@ export class BrowserViewManager {
1210
1348
  throw new Error('This browser is temporary, so imported cookies would not be kept');
1211
1349
  this.scheduleIdleClose(sessionId, session);
1212
1350
  await session.context.addCookies(cookies);
1213
- // The import has already happened; a page that fails to reload is the page's
1214
- // own failure and shows in the pane, not a reason to report the import failed.
1215
1351
  await this.go(sessionId, 'refresh').catch(() => { });
1216
1352
  }
1217
- /** The kind of browser the session's pages live in now, or would on the next open. */
1218
1353
  profileKind(sessionId) {
1219
1354
  return this.sessions.get(sessionId)?.profile ?? (this.incognito.has(sessionId) ? 'incognito' : undefined);
1220
1355
  }
1221
1356
  async openPage(sessionId, target, signal, requireProfile) {
1222
1357
  const session = await this.ensureSession(sessionId);
1223
- // The launch is the longest wait here, and the one a stop usually arrives
1224
- // during: a cancelled call returns before creating a page at all.
1225
1358
  signal?.throwIfAborted();
1226
- // A switch to incognito must never report success on the signed-in profile.
1227
1359
  if (requireProfile !== undefined && session.profile !== requireProfile)
1228
1360
  throw new Error(`The panel browser is not ${requireProfile}; retry the switch`);
1229
1361
  if (session.closing)
1230
1362
  throw new Error('Browser is closing; retry shortly');
1231
- // Capacity is reserved before the first await. Stopping the previous
1232
- // screencast and creating the page both yield, so a burst of overlapping
1233
- // opens would otherwise all pass a plain `tabs.size` check and exceed the
1234
- // cap with pages nobody intended to keep.
1235
1363
  if (session.tabs.size + session.pendingTabs >= VIEW_TAB_LIMIT)
1236
1364
  throw new Error('Close a tab before opening another (maximum 6)');
1237
1365
  session.pendingTabs += 1;
@@ -1248,84 +1376,46 @@ export class BrowserViewManager {
1248
1376
  await this.stopScreencast(previous);
1249
1377
  const context = await this.contextFor(session);
1250
1378
  const page = await context.newPage();
1379
+ this.claimedPages.add(page);
1251
1380
  const cdp = await Promise.resolve().then(() => page.context().newCDPSession(page)).catch(async (error) => {
1252
1381
  await Promise.resolve().then(() => page.close()).catch(() => { });
1253
1382
  throw error;
1254
1383
  });
1255
- // A shared project profile outlives this session: a page whose session
1256
- // started closing while it was created or attached would otherwise stay
1257
- // open in it, unowned, because teardown closes only registered tabs. The
1258
- // check sits directly before registration, with no await between them, so
1259
- // a teardown that starts afterwards always finds this tab.
1260
1384
  if (session.closing) {
1261
1385
  await Promise.resolve().then(() => cdp.detach?.()).catch(() => { });
1262
1386
  await Promise.resolve().then(() => page.close()).catch(() => { });
1263
1387
  throw new Error('Browser is closing; retry shortly');
1264
1388
  }
1265
1389
  const tab = this.wireTab(sessionId, session, page, cdp);
1266
- // The context was created at the viewport of the first open; a tab opened
1267
- // after the pane was resized has to match the pane it will be shown in, or
1268
- // its layout and every translated click would use the old size. The mode's
1269
- // emulation rides along on the same call.
1270
1390
  await this.queueViewportMode(session, tab);
1271
- // The reservation has become a real tab; the cap now counts it directly.
1272
1391
  release();
1273
- // The pane follows the newest open. The selection may have moved while this
1274
- // page was being created, so it is re-read and stopped until it is this
1275
- // tab's: a stream left running for a tab nobody sees discards its frames
1276
- // while keeping `streaming` true, and selecting that tab again would then
1277
- // start nothing. The loop is bounded by the tab actually streaming — a stop
1278
- // with nothing to do cannot have yielded to another activation, so the
1279
- // assignment that follows is atomic.
1280
1392
  let selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1281
1393
  while (selected && selected.id !== tab.id && selected.streaming) {
1282
1394
  await this.stopScreencast(selected);
1283
- // An activation can land during that await; stop whatever the selection
1284
- // has become before this tab takes it.
1285
1395
  selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1286
1396
  }
1287
- // Creating the page stops the previous screencast, and both yield: a run
1288
- // stopped while its tab was being made must not select it or load the URL
1289
- // afterwards, so only the unfinished tab is closed here — the rest of the
1290
- // shared browser the user is watching stays exactly as it is.
1291
1397
  if (signal?.aborted) {
1292
1398
  await this.discardTab(sessionId, session, tab, previous);
1293
- // The pane never left the tab it was on, but this open had already stopped that tab's
1294
- // stream: without restarting it the panel would sit frozen on a tab that still accepts
1295
- // input. `discardTab` restores the stream only for a tab that held the pane, which this
1296
- // one never did.
1297
1399
  const survivor = session.activeTabId === undefined ? undefined : session.tabs.get(session.activeTabId);
1298
1400
  if (survivor && !survivor.streaming)
1299
1401
  await this.showTab(session, survivor);
1300
1402
  signal.throwIfAborted();
1301
1403
  }
1302
1404
  session.activeTabId = tab.id;
1303
- // The pane's target changes here, before the navigation it waits for: an
1304
- // input request naming no tab of its own would otherwise land on a page the
1305
- // panel is not showing yet, and the strip would still name the old one.
1306
1405
  this.publishTabs(sessionId, session);
1406
+ // The profile now has a real page keeping the window alive: leftover launch
1407
+ // blanks can go. Awaited so the close is settled before the open reports.
1408
+ await this.drainPendingBlanks(session.profileKey === undefined ? undefined : this.profiles.get(session.profileKey));
1307
1409
  try {
1308
1410
  await page.goto(target, { waitUntil: 'domcontentloaded', timeout: VIEW_GOTO_TIMEOUT_MS });
1309
1411
  }
1310
1412
  catch (error) {
1311
- // A page that failed its first navigation is not a tab worth keeping: an
1312
- // address-bar retry would otherwise stack error pages behind it.
1313
1413
  await this.discardTab(sessionId, session, tab, previous);
1314
1414
  throw error;
1315
1415
  }
1316
- // The URL the tab shows is the one the page actually landed on
1317
- // (`framenavigated` records redirects); the requested target may differ.
1318
- // A slow open that finished after a later one took the selection must not
1319
- // start a stream for a tab nobody is looking at: its frames would be
1320
- // discarded while `streaming` stayed true, and activating it later would
1321
- // find the stream already "running" and never ask for a fresh frame.
1322
1416
  if (session.activeTabId === tab.id)
1323
1417
  await this.showTab(session, tab);
1324
1418
  this.publishTabs(sessionId, session);
1325
- // The pane follows an open, whoever drove it: an agent's first tab is the
1326
- // moment the panel should be on screen, and expanding an open pane is a
1327
- // no-op, so the user's own opens can simply ride the same event. A session
1328
- // being torn down is nobody's pane to open.
1329
1419
  if (!session.closing)
1330
1420
  this.emit('browser.panel.opened', { sessionId });
1331
1421
  return { tabId: tab.id };
@@ -1334,21 +1424,8 @@ export class BrowserViewManager {
1334
1424
  release();
1335
1425
  }
1336
1426
  }
1337
- /**
1338
- * Remove one tab an open created and did not finish.
1339
- *
1340
- * The page itself is closed too — a discarded page still runs and still counts
1341
- * against the browser, and the tab cap only counts pages it holds. Only the
1342
- * unfinished tab goes: the rest of the shared browser, which the user may be
1343
- * watching, is left as it is.
1344
- */
1345
1427
  async discardTab(sessionId, session, tab, previous) {
1346
1428
  session.tabs.delete(tab.id);
1347
- // Only the tab that is still selected may hand the pane back: an overlapping
1348
- // open that succeeded meanwhile owns it, and clearing its selection would
1349
- // leave a visible tab that input cannot address. The tab that owned the pane
1350
- // before this open may itself have been closed while the open was in flight,
1351
- // so a survivor is chosen instead.
1352
1429
  if (session.activeTabId === tab.id) {
1353
1430
  const fallback = previous && session.tabs.has(previous.id) ? previous : [...session.tabs.values()][0];
1354
1431
  session.activeTabId = fallback?.id;
@@ -1357,13 +1434,10 @@ export class BrowserViewManager {
1357
1434
  }
1358
1435
  await tab.cdp?.detach().catch(() => { });
1359
1436
  await tab.page.close().catch(() => { });
1360
- // Another open may still be creating its page: the session is not empty.
1361
1437
  if (session.tabs.size === 0 && session.pendingTabs === 0)
1362
1438
  void this.closeSession(sessionId, undefined, session);
1363
1439
  }
1364
1440
  activeOrNamed(session, tabId) {
1365
- // An explicit id names one tab: falling back to the selection would let a
1366
- // repeated close of a tab that is already gone destroy an unrelated one.
1367
1441
  if (tabId !== undefined) {
1368
1442
  const named = session.tabs.get(tabId);
1369
1443
  if (!named)
@@ -1383,10 +1457,7 @@ export class BrowserViewManager {
1383
1457
  const tab = this.activeOrNamed(session, tabId);
1384
1458
  this.scheduleIdleClose(sessionId, session);
1385
1459
  await tab.page.goto(target, { waitUntil: 'domcontentloaded', timeout: VIEW_GOTO_TIMEOUT_MS });
1386
- // `framenavigated` owns the tab's URL (it records where redirects landed);
1387
- // overwriting it here would describe an address the page is not showing.
1388
1460
  this.publishTabs(sessionId, session);
1389
- // A navigation is new content in the pane: the same pop-up an open gets.
1390
1461
  if (!session.closing)
1391
1462
  this.emit('browser.panel.opened', { sessionId });
1392
1463
  }
@@ -1397,18 +1468,11 @@ export class BrowserViewManager {
1397
1468
  const previous = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1398
1469
  if (previous && previous.id !== tabId)
1399
1470
  await this.stopScreencast(previous);
1400
- // Another activation can have taken the pane while this one waited for that
1401
- // stop: whatever holds the selection now gives up its stream too, or its flag
1402
- // would keep its next selection from ever starting one. Bounded by a stream
1403
- // really running, as everywhere else that waits on a stop.
1404
1471
  let holding = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1405
1472
  while (holding && holding.streaming && holding.id !== tabId) {
1406
1473
  await this.stopScreencast(holding);
1407
1474
  holding = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1408
1475
  }
1409
- // The stop yields, so the tab being activated can have closed in that window.
1410
- // Naming it anyway would strand the pane on an id nothing can address, with
1411
- // the survivor's stream stopped and every implicit request refused.
1412
1476
  if (!session.tabs.has(tabId)) {
1413
1477
  const survivor = previous && session.tabs.has(previous.id) ? previous : [...session.tabs.values()][0];
1414
1478
  session.activeTabId = survivor?.id;
@@ -1419,9 +1483,6 @@ export class BrowserViewManager {
1419
1483
  }
1420
1484
  session.activeTabId = tabId;
1421
1485
  const tab = session.tabs.get(tabId);
1422
- // A pane resized while this tab was inactive only sized the active page. The
1423
- // page is brought to the session's current viewport before it streams, so
1424
- // input translation and the displayed frame agree on the page's size.
1425
1486
  await this.showTab(session, tab);
1426
1487
  this.scheduleIdleClose(sessionId, session);
1427
1488
  this.publishTabs(sessionId, session);
@@ -1434,15 +1495,6 @@ export class BrowserViewManager {
1434
1495
  await this.stopScreencast(tab);
1435
1496
  await tab.page.close().catch(() => { });
1436
1497
  }
1437
- /**
1438
- * Panel geometry: the page viewport and the streamed frame target follow the
1439
- * pane, or Mobile mode's fixed phone viewport with its emulation.
1440
- *
1441
- * The request is remembered even when the session has no browser yet: a panel
1442
- * mounts and asks for frames before its first tab is opened, and the open
1443
- * adopts the remembered request. Disabling forgets it, so a collapsed panel
1444
- * that is later reopened makes a fresh, explicitly desired request.
1445
- */
1446
1498
  async configureStream(sessionId, options) {
1447
1499
  if (!options.enabled) {
1448
1500
  this.desired.delete(sessionId);
@@ -1451,8 +1503,6 @@ export class BrowserViewManager {
1451
1503
  return;
1452
1504
  session.streaming = false;
1453
1505
  for (const tab of session.tabs.values()) {
1454
- // A newer enable took the pane back while this disable was stopping tabs:
1455
- // its stream stands, and the stops still owed belong to it, not this one.
1456
1506
  if (session.streaming)
1457
1507
  return;
1458
1508
  await this.stopScreencast(tab);
@@ -1464,8 +1514,6 @@ export class BrowserViewManager {
1464
1514
  const viewport = mode === 'mobile' ? { ...VIEW_MOBILE_VIEWPORT } : clampViewport(options.viewportWidth, options.viewportHeight);
1465
1515
  const quality = Number.isSafeInteger(options.quality) ? Math.max(30, Math.min(90, options.quality)) : VIEW_STREAM_QUALITY;
1466
1516
  const scale = clampScale(options.scale);
1467
- // Only a panel that sends a ratio speaks for the display; an old one that
1468
- // sends none must not reset what a current one reported.
1469
1517
  if (options.scale !== undefined)
1470
1518
  this.displayScale = scale;
1471
1519
  this.desired.set(sessionId, { viewport, quality, mode, scale });
@@ -1474,9 +1522,6 @@ export class BrowserViewManager {
1474
1522
  return;
1475
1523
  session.streaming = true;
1476
1524
  const modeChanged = mode !== session.mode;
1477
- // A new display ratio (the window moved to another monitor, or the system
1478
- // scaling changed) sizes the frames differently, and the screencast bakes
1479
- // its frame size in at start, so it restarts like a resize does.
1480
1525
  const resized = viewport.width !== session.viewport.width || viewport.height !== session.viewport.height
1481
1526
  || scale !== session.scale;
1482
1527
  session.mode = mode;
@@ -1488,14 +1533,8 @@ export class BrowserViewManager {
1488
1533
  if (!active)
1489
1534
  return;
1490
1535
  if (resized || modeChanged) {
1491
- // A new geometry changes every frame's size; the reduced budget belonged to the old one.
1492
1536
  active.budget = undefined;
1493
- // A mode switch is more than a resize: the page is put into or taken out
1494
- // of the phone's emulation.
1495
1537
  await this.queueViewportMode(session, active);
1496
- // Applying yields, so the selection can have moved by the time it lands:
1497
- // the tab that lost the pane stops streaming, and the pane's new owner
1498
- // gets the fresh geometry through the guarded path.
1499
1538
  if (session.activeTabId !== active.id) {
1500
1539
  await this.stopScreencast(active);
1501
1540
  const selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
@@ -1503,15 +1542,7 @@ export class BrowserViewManager {
1503
1542
  await this.showTab(session, selected);
1504
1543
  return;
1505
1544
  }
1506
- // The screencast bakes its capture scale in at start: a page resized under
1507
- // a running stream delivers frames scaled to the old size (verified live —
1508
- // a 560×800 page after a 390-wide capture arrives 390×557), so the stream
1509
- // restarts to pick up the new geometry. The pane holds its last painted
1510
- // frame through the gap, so the UI never blanks while it happens.
1511
1545
  await this.stopScreencast(active);
1512
- // The stop yields, so the selection can have moved by the time it lands:
1513
- // restarting this tab would stream one nobody sees while leaving its flag
1514
- // on, and the pane's new owner would wait for frames that never come.
1515
1546
  if (session.activeTabId !== active.id) {
1516
1547
  const selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1517
1548
  if (selected)
@@ -1521,16 +1552,9 @@ export class BrowserViewManager {
1521
1552
  }
1522
1553
  const reattached = active.streaming;
1523
1554
  await this.startScreencast(session, active);
1524
- // A stream that was already running sends nothing more for a page that is
1525
- // not repainting, so a pane that returned (renderer reload) would have no
1526
- // image; asking for one now makes the resumed panel show the page as it is.
1527
1555
  if (reattached)
1528
1556
  await this.captureFrame(sessionId, session, active);
1529
1557
  }
1530
- /**
1531
- * Panel input, translated from image pixels to page CSS pixels and forwarded
1532
- * as CDP input events. The panel never holds a CDP connection of its own.
1533
- */
1534
1558
  async input(sessionId, payload) {
1535
1559
  const session = this.sessions.get(sessionId);
1536
1560
  if (!session)
@@ -1554,8 +1578,6 @@ export class BrowserViewManager {
1554
1578
  const type = payload.type;
1555
1579
  if (type === 'move') {
1556
1580
  const at = point();
1557
- // A held button during a drag: the mask is what makes the page treat the
1558
- // movement as dragging rather than hovering.
1559
1581
  const pressed = payload.pressed === true;
1560
1582
  const name = pressed ? button(payload.button) : 'none';
1561
1583
  const buttons = pressed ? (name === 'right' ? 2 : name === 'middle' ? 4 : 1) : 0;
@@ -1586,11 +1608,7 @@ export class BrowserViewManager {
1586
1608
  else if (type === 'key') {
1587
1609
  const down = payload.down === true;
1588
1610
  const descriptor = keyDescriptor(String(payload.key ?? ''), typeof payload.code === 'string' ? payload.code : undefined, modifiers);
1589
- // The character a key inserts belongs to the key-down; a key-up carries
1590
- // none, so the page does not see the text twice.
1591
1611
  const text = down ? descriptor.text : undefined;
1592
- // A macOS browser performs its editing gestures as named commands on the
1593
- // key-down, not from the key event itself; see `macEditingCommands`.
1594
1612
  const commands = process.platform === 'darwin' && down ? macEditingCommands(descriptor.key, modifiers) : [];
1595
1613
  await tab.cdp.send('Input.dispatchKeyEvent', {
1596
1614
  type: down ? (text === undefined ? 'rawKeyDown' : 'keyDown') : 'keyUp',
@@ -1610,13 +1628,6 @@ export class BrowserViewManager {
1610
1628
  throw new Error('Unsupported browser input type');
1611
1629
  }
1612
1630
  }
1613
- /**
1614
- * The cursor shape the page would show at a pane point, in image pixels.
1615
- *
1616
- * The pane draws frames and forwards input, so the page's own pointer is never
1617
- * visible: a link must still read as a link. The answer is the page's computed
1618
- * `cursor` at that point, bounded and lower-cased for the panel to draw.
1619
- */
1620
1631
  async cursorAt(sessionId, x, y, tabId) {
1621
1632
  const session = this.sessions.get(sessionId);
1622
1633
  if (!session)
@@ -1625,7 +1636,6 @@ export class BrowserViewManager {
1625
1636
  this.scheduleIdleClose(sessionId, session);
1626
1637
  const px = Number(x);
1627
1638
  const py = Number(y);
1628
- // A point outside the frame the pane is showing names nothing in the page.
1629
1639
  if (!Number.isSafeInteger(px) || !Number.isSafeInteger(py) || px < 0 || py < 0 || px > tab.imageWidth || py > tab.imageHeight)
1630
1640
  return 'default';
1631
1641
  const scaleX = tab.imageWidth / Math.max(1, session.viewport.width);
@@ -1634,15 +1644,6 @@ export class BrowserViewManager {
1634
1644
  .catch(() => 'default');
1635
1645
  return typeof cursor === 'string' && /^[a-z-]{1,40}$/.test(cursor) ? cursor : 'default';
1636
1646
  }
1637
- /**
1638
- * The text a copy or cut would take from the page, for the viewer's clipboard.
1639
- *
1640
- * Copy and cut travel to the page as key events, so the text they produce stays
1641
- * in the browser that owns the page. The viewer reads it back here and writes
1642
- * it to its own clipboard, which is what makes a copy on a paired machine land
1643
- * on the machine the user is sitting at. The viewer reads before it forwards
1644
- * the key: a cut collapses the selection it just removed.
1645
- */
1646
1647
  async selectionText(sessionId, tabId) {
1647
1648
  const session = this.sessions.get(sessionId);
1648
1649
  if (!session)
@@ -1650,29 +1651,16 @@ export class BrowserViewManager {
1650
1651
  const tab = this.activeOrNamed(session, tabId);
1651
1652
  this.scheduleIdleClose(sessionId, session);
1652
1653
  const text = await this.selectionInPage(tab.page);
1653
- // A selection past the bound is refused rather than truncated: the viewer
1654
- // writes what it read and then forwards the key, and a cut removes the whole
1655
- // selection from the page — a prefix on the clipboard would lose the rest.
1656
1654
  if (typeof text !== 'string')
1657
1655
  return '';
1658
1656
  if (text.length > VIEW_CLIPBOARD_LIMIT)
1659
1657
  throw new Error(`The selection is too large to copy (${text.length} characters)`);
1660
1658
  return text;
1661
1659
  }
1662
- /**
1663
- * The focused document's selection, including one made inside a frame.
1664
- *
1665
- * The top document is asked first, and it says when focus is inside a frame:
1666
- * there the iframe element is the active element and the top selection is
1667
- * empty, so each frame is asked in turn. Playwright evaluates inside a
1668
- * cross-origin frame as well, because the evaluation runs over CDP rather than
1669
- * through the page's own script context.
1670
- */
1671
1660
  async selectionInPage(page) {
1672
1661
  const top = await page.evaluate(SELECTION_STATE).catch(() => undefined);
1673
1662
  if (typeof top?.text === 'string' && top.text)
1674
1663
  return top.text;
1675
- // The top document answered "no selection and focus is mine": no frame holds it.
1676
1664
  if (top?.inFrame === false)
1677
1665
  return '';
1678
1666
  let frames = [];
@@ -1683,10 +1671,6 @@ export class BrowserViewManager {
1683
1671
  catch {
1684
1672
  return '';
1685
1673
  }
1686
- // A frame keeps its selection after focus moves elsewhere, so an unfocused
1687
- // frame's text is not the user's. Only the focused document's selection is
1688
- // the answer, even an empty one; a focused frame whose own active element is
1689
- // another iframe is a step on the way to a deeper frame, not the caret itself.
1690
1674
  let fallback = '';
1691
1675
  let focusedAnswered = false;
1692
1676
  for (const frame of frames) {
@@ -1701,16 +1685,8 @@ export class BrowserViewManager {
1701
1685
  if (!fallback && text)
1702
1686
  fallback = text;
1703
1687
  }
1704
- // The focus is deeper than the frames readable here: their stale text is not it.
1705
1688
  return focusedAnswered ? '' : fallback;
1706
1689
  }
1707
- /**
1708
- * Agent operations on the session's panel browser.
1709
- *
1710
- * The panel browser belongs to the user as much as to the agent: an operation
1711
- * that fails, stalls or is cancelled ends only that call — never the browser —
1712
- * and tab-affecting operations publish tabs so the pane follows along.
1713
- */
1714
1690
  async boundedAgentOperation(signal, pending, timeoutMessage) {
1715
1691
  return await new Promise((resolve, reject) => {
1716
1692
  let settled = false;
@@ -1736,11 +1712,9 @@ export class BrowserViewManager {
1736
1712
  this.scheduleIdleClose(sessionId, session);
1737
1713
  return { session, tab: this.activeOrNamed(session, tabId) };
1738
1714
  }
1739
- /** The session's tabs as the agent sees them; a panel with no browser yet is simply empty. */
1740
1715
  agentTabs(sessionId) {
1741
1716
  return this.sessionSummaries()[sessionId] ?? { tabs: [] };
1742
1717
  }
1743
- /** Step a tab through its history or reload it, for the agent and the panel's toolbar alike. */
1744
1718
  async go(sessionId, kind, tabId) {
1745
1719
  const { session, tab } = this.agentTarget(sessionId, tabId);
1746
1720
  if (kind === 'back')
@@ -1767,9 +1741,6 @@ export class BrowserViewManager {
1767
1741
  }
1768
1742
  async agentPress(sessionId, options, signal) {
1769
1743
  const { tab } = this.agentTarget(sessionId, options.tabId);
1770
- // The keypress belongs to this call alone: a focus that resolves after the call
1771
- // was cancelled or timed out must not dispatch into the shared browser, where it
1772
- // could submit a form nobody is driving anymore.
1773
1744
  let callerGone = false;
1774
1745
  const sequence = (async () => {
1775
1746
  if (options.selector)
@@ -1795,11 +1766,6 @@ export class BrowserViewManager {
1795
1766
  }
1796
1767
  async agentScreenshot(sessionId, tabId, signal) {
1797
1768
  const { session, tab } = this.agentTarget(sessionId, tabId);
1798
- // The agent reads this image against the CSS-pixel size returned with it, but
1799
- // the page renders at the browser's launch factor (or Mobile's 3×). That ratio
1800
- // is applied over this manager's own CDP session, so Playwright still believes
1801
- // the page is 1×, and its `scale: 'css'` would return device pixels; the
1802
- // capture is made here instead, scaled down by the ratio actually in effect.
1803
1769
  const ratio = tab.emulated ? VIEW_MOBILE_SCALE : session.renderScale;
1804
1770
  const capture = (async () => {
1805
1771
  const metrics = await tab.cdp.send('Page.getLayoutMetrics').catch(() => undefined);
@@ -1807,10 +1773,6 @@ export class BrowserViewManager {
1807
1773
  const clip = visual && Number.isFinite(visual.clientWidth) && visual.clientWidth > 0
1808
1774
  ? { x: visual.pageX, y: visual.pageY, width: visual.clientWidth, height: visual.clientHeight }
1809
1775
  : { x: 0, y: 0, width: session.viewport.width, height: session.viewport.height };
1810
- // A Mobile page without a meta viewport lays out at ~980 CSS px and the
1811
- // phone shows it zoomed out to its 390: the visual viewport's scale (0.398
1812
- // there, measured) is what brings that wider clip back to the size the
1813
- // agent is told.
1814
1776
  const zoom = visual && Number.isFinite(visual.scale) && visual.scale > 0 ? visual.scale : 1;
1815
1777
  const shot = await tab.cdp.send('Page.captureScreenshot', { format: 'jpeg', quality: 60, clip: { ...clip, scale: zoom / ratio } });
1816
1778
  if (typeof shot?.data !== 'string')
@@ -1824,12 +1786,8 @@ export class BrowserViewManager {
1824
1786
  const session = this.sessions.get(sessionId);
1825
1787
  if (!session || session.closing)
1826
1788
  return;
1827
- // A teardown that started for an older generation must not close the
1828
- // replacement that took its id in the meantime.
1829
1789
  if (expected !== undefined && session !== expected)
1830
1790
  return;
1831
- // Incognito lasts exactly as long as its browser: once it closes, the next
1832
- // open returns to the project profile.
1833
1791
  if (session.profile === 'incognito')
1834
1792
  this.incognito.delete(sessionId);
1835
1793
  session.closing = (async () => {
@@ -1837,11 +1795,7 @@ export class BrowserViewManager {
1837
1795
  if (session.idleTimer)
1838
1796
  clearTimeout(session.idleTimer);
1839
1797
  await Promise.all([...session.tabs.values()].map(tab => this.stopScreencast(tab)));
1840
- // A shared project profile loses only this session's pages; the profile
1841
- // itself closes when its last session leaves.
1842
1798
  await this.disposeBrowser(session);
1843
- // A new browser may already hold this session id; its pane has content of
1844
- // its own, so the old generation stays silent.
1845
1799
  if (this.sessions.has(sessionId))
1846
1800
  return;
1847
1801
  this.emit('browser.view', { kind: 'gone', sessionId, ...(reason ? { reason } : {}) });
@@ -1855,16 +1809,29 @@ export class BrowserViewManager {
1855
1809
  return result;
1856
1810
  }
1857
1811
  /**
1858
- * Release one session's panel browser now.
1859
- *
1860
- * A deleted session will never stream again, so waiting for its idle timeout
1861
- * would keep a whole browser, and one of the four session slots, alive for ten
1862
- * minutes for a pane nobody can open.
1812
+ * Close the panel browsers of sessions whose project identity just changed. A profile is chosen once, when the
1813
+ * browser is created, so a task merged into another project would keep browsing on the cookies and logins of the
1814
+ * folder it left. Closing it here costs the open tabs of that one task; the next use opens it on the surviving
1815
+ * project's profile.
1863
1816
  */
1817
+ async rekeyProfiles(sessionIds) {
1818
+ const ids = [...sessionIds];
1819
+ if (ids.length === 0)
1820
+ return;
1821
+ await Promise.all(ids.map(async (id) => await this.launching.get(id)?.catch(() => { })));
1822
+ for (const id of ids) {
1823
+ // An incognito panel browser carries no project state, so there is nothing stale about leaving it open.
1824
+ const session = this.sessions.get(id);
1825
+ if (session === undefined || session.profile === 'incognito')
1826
+ continue;
1827
+ await this.closeSession(id, 'project changed');
1828
+ }
1829
+ }
1864
1830
  async release(sessionId, reason) {
1865
- // Marked before the close, so a launch finishing in between still sees the
1866
- // release; the marker is dropped once no launch can still be holding it.
1867
1831
  this.released.add(sessionId);
1832
+ const restoring = this.restoring.get(sessionId);
1833
+ if (restoring)
1834
+ restoring.cancelled = true;
1868
1835
  this.incognito.delete(sessionId);
1869
1836
  try {
1870
1837
  await this.closeSession(sessionId, reason);
@@ -1874,27 +1841,25 @@ export class BrowserViewManager {
1874
1841
  this.released.delete(sessionId);
1875
1842
  }
1876
1843
  }
1877
- /** Engine shutdown: no panel browser outlives the process. */
1878
1844
  async close() {
1879
1845
  if (this.closed)
1880
1846
  return;
1881
1847
  this.closed = true;
1882
- // A download in progress belongs to this engine: its child is terminated and
1883
- // the request waiting on it is answered, rather than left to the process
1884
- // exit and its twenty-minute timer.
1848
+ if (this.restartPoll) {
1849
+ clearTimeout(this.restartPoll);
1850
+ this.restartPoll = undefined;
1851
+ }
1852
+ this.pendingRestart.clear();
1885
1853
  if (this.installer) {
1886
1854
  const { child, finish } = this.installer;
1887
1855
  try {
1888
1856
  child.kill();
1889
1857
  }
1890
- catch { /* Already gone. */ }
1858
+ catch { }
1891
1859
  const stopped = { state: 'failed', detail: 'Application is shutting down' };
1892
1860
  this.publishRuntime(stopped);
1893
1861
  finish(stopped);
1894
1862
  }
1895
- // A launch already in flight is awaited before the last sweep: it inserts its
1896
- // session while this loop is running, and a browser nobody then visits would
1897
- // outlive the engine. The wait is bounded because a launch may never settle.
1898
1863
  const pending = [...this.launching.values()];
1899
1864
  if (pending.length) {
1900
1865
  await Promise.race([
@@ -1903,6 +1868,5 @@ export class BrowserViewManager {
1903
1868
  ]);
1904
1869
  }
1905
1870
  await Promise.all([...this.sessions.keys()].map(sessionId => this.closeSession(sessionId)));
1906
- // A launch that landed after the bound closed itself in `ensureSession`.
1907
1871
  }
1908
1872
  }