@andorra-labs/code 0.1.12 → 0.1.13

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 (592) hide show
  1. package/dist/src/account-presentation.d.ts +1 -37
  2. package/dist/src/account-presentation.js +2 -42
  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 +49 -416
  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 +9 -153
  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/anthropic-console-auth.d.ts +0 -24
  18. package/dist/src/anthropic-console-auth.js +0 -37
  19. package/dist/src/anthropic-credentials.d.ts +0 -25
  20. package/dist/src/anthropic-credentials.js +0 -28
  21. package/dist/src/app-server/protocol.d.ts +13 -245
  22. package/dist/src/app-server/protocol.js +1 -132
  23. package/dist/src/app-server/reasoning.d.ts +0 -31
  24. package/dist/src/app-server/reasoning.js +0 -54
  25. package/dist/src/app-server/terminal.d.ts +0 -36
  26. package/dist/src/app-server/terminal.js +3 -39
  27. package/dist/src/app-server/workspace.d.ts +0 -167
  28. package/dist/src/app-server/workspace.js +4 -406
  29. package/dist/src/app-server.d.ts +27 -927
  30. package/dist/src/app-server.js +537 -2992
  31. package/dist/src/artifacts.d.ts +0 -10
  32. package/dist/src/artifacts.js +1 -11
  33. package/dist/src/attachments.d.ts +4 -98
  34. package/dist/src/attachments.js +10 -130
  35. package/dist/src/auth/AuthManager.d.ts +0 -93
  36. package/dist/src/auth/AuthManager.js +3 -165
  37. package/dist/src/auth/callback-page.d.ts +0 -1
  38. package/dist/src/auth/callback-page.js +0 -4
  39. package/dist/src/auth/callback.d.ts +0 -25
  40. package/dist/src/auth/callback.js +1 -29
  41. package/dist/src/auth/deployment.d.ts +0 -16
  42. package/dist/src/auth/deployment.js +0 -16
  43. package/dist/src/auth/index.d.ts +0 -11
  44. package/dist/src/auth/index.js +0 -11
  45. package/dist/src/auth/lock.d.ts +0 -1
  46. package/dist/src/auth/lock.js +0 -1
  47. package/dist/src/auth/store.d.ts +7 -108
  48. package/dist/src/auth/store.js +21 -129
  49. package/dist/src/auth/types.d.ts +0 -8
  50. package/dist/src/auth-commands.d.ts +0 -5
  51. package/dist/src/auth-commands.js +0 -1
  52. package/dist/src/automation-runner.d.ts +0 -9
  53. package/dist/src/automation-runner.js +0 -11
  54. package/dist/src/automation-service.d.ts +0 -10
  55. package/dist/src/automation-service.js +3 -17
  56. package/dist/src/automation-tool.js +0 -5
  57. package/dist/src/automation-worker-shutdown.d.ts +0 -1
  58. package/dist/src/automation-worker-shutdown.js +0 -3
  59. package/dist/src/automations.d.ts +23 -2
  60. package/dist/src/automations.js +91 -12
  61. package/dist/src/background-tasks.d.ts +0 -23
  62. package/dist/src/background-tasks.js +0 -11
  63. package/dist/src/boot-trace.d.ts +0 -13
  64. package/dist/src/boot-trace.js +1 -14
  65. package/dist/src/browser-activity.js +0 -2
  66. package/dist/src/browser-bridge.d.ts +0 -2
  67. package/dist/src/browser-bridge.js +0 -27
  68. package/dist/src/browser-captcha-tool.d.ts +0 -13
  69. package/dist/src/browser-captcha-tool.js +3 -35
  70. package/dist/src/browser-extensions-tool.d.ts +24 -0
  71. package/dist/src/browser-extensions-tool.js +137 -0
  72. package/dist/src/browser-extensions.d.ts +127 -0
  73. package/dist/src/browser-extensions.js +729 -0
  74. package/dist/src/browser-observation.d.ts +0 -15
  75. package/dist/src/browser-observation.js +1 -22
  76. package/dist/src/browser-panel-tool.d.ts +1 -37
  77. package/dist/src/browser-panel-tool.js +3 -73
  78. package/dist/src/browser-runner.d.ts +0 -1
  79. package/dist/src/browser-runner.js +4 -45
  80. package/dist/src/browser-server.d.ts +0 -6
  81. package/dist/src/browser-server.js +6 -229
  82. package/dist/src/browser-session.d.ts +0 -25
  83. package/dist/src/browser-session.js +1 -71
  84. package/dist/src/browser-stealth.d.ts +0 -12
  85. package/dist/src/browser-stealth.js +0 -36
  86. package/dist/src/browser-ui/app.js +7 -174
  87. package/dist/src/browser-ui/style.css +0 -68
  88. package/dist/src/browser-ui/tokens.css +11 -93
  89. package/dist/src/browser-view.d.ts +47 -301
  90. package/dist/src/browser-view.js +333 -582
  91. package/dist/src/capabilities.d.ts +0 -8
  92. package/dist/src/capabilities.js +0 -29
  93. package/dist/src/capsolver.d.ts +0 -13
  94. package/dist/src/capsolver.js +0 -15
  95. package/dist/src/clarification-ui.d.ts +0 -7
  96. package/dist/src/clarification-ui.js +0 -8
  97. package/dist/src/claude-executable.d.ts +0 -1
  98. package/dist/src/claude-executable.js +1 -2
  99. package/dist/src/claude-provider.d.ts +6 -19
  100. package/dist/src/claude-provider.js +155 -63
  101. package/dist/src/cli-executable.d.ts +0 -16
  102. package/dist/src/cli-executable.js +0 -7
  103. package/dist/src/cli-process.d.ts +0 -26
  104. package/dist/src/cli-process.js +0 -18
  105. package/dist/src/cli-sign-in.d.ts +0 -20
  106. package/dist/src/cli-sign-in.js +1 -17
  107. package/dist/src/cli.d.ts +1 -55
  108. package/dist/src/cli.js +80 -721
  109. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +4 -59
  110. package/dist/src/code-intelligence/CodeIntelligenceManager.js +26 -99
  111. package/dist/src/code-intelligence/ContextLedger.d.ts +0 -4
  112. package/dist/src/code-intelligence/ContextLedger.js +0 -10
  113. package/dist/src/code-intelligence/ContextRouter.d.ts +0 -6
  114. package/dist/src/code-intelligence/ContextRouter.js +0 -8
  115. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.d.ts +0 -2
  116. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.js +5 -12
  117. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.d.ts +0 -6
  118. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.js +0 -6
  119. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.d.ts +0 -5
  120. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.js +1 -17
  121. package/dist/src/code-intelligence/codegraph/repoExploreTool.d.ts +0 -5
  122. package/dist/src/code-intelligence/codegraph/repoExploreTool.js +0 -5
  123. package/dist/src/code-intelligence/repository.d.ts +0 -9
  124. package/dist/src/code-intelligence/repository.js +1 -11
  125. package/dist/src/code-intelligence/types.d.ts +0 -8
  126. package/dist/src/codex-auth.d.ts +0 -44
  127. package/dist/src/codex-auth.js +0 -45
  128. package/dist/src/codex-browser-auth.d.ts +0 -13
  129. package/dist/src/codex-browser-auth.js +3 -20
  130. package/dist/src/codex-errors.js +0 -2
  131. package/dist/src/codex-executable.d.ts +0 -2
  132. package/dist/src/codex-executable.js +1 -7
  133. package/dist/src/codex-provider.d.ts +0 -13
  134. package/dist/src/codex-provider.js +0 -28
  135. package/dist/src/codex-rpc.d.ts +0 -10
  136. package/dist/src/codex-rpc.js +0 -12
  137. package/dist/src/coding-tools.d.ts +4 -26
  138. package/dist/src/coding-tools.js +161 -181
  139. package/dist/src/command-metrics.d.ts +0 -4
  140. package/dist/src/command-output-tap.d.ts +0 -11
  141. package/dist/src/command-output-tap.js +0 -3
  142. package/dist/src/command-screens.d.ts +24 -0
  143. package/dist/src/command-screens.js +132 -100
  144. package/dist/src/commands.d.ts +6 -63
  145. package/dist/src/commands.js +20 -100
  146. package/dist/src/completion-gates.d.ts +0 -47
  147. package/dist/src/completion-gates.js +0 -14
  148. package/dist/src/completion.d.ts +0 -98
  149. package/dist/src/completion.js +2 -239
  150. package/dist/src/config.d.ts +11 -116
  151. package/dist/src/config.js +39 -171
  152. package/dist/src/context-budget.d.ts +0 -22
  153. package/dist/src/context-budget.js +0 -44
  154. package/dist/src/context-compaction.d.ts +29 -6
  155. package/dist/src/context-compaction.js +94 -25
  156. package/dist/src/context-selection.d.ts +0 -24
  157. package/dist/src/context-selection.js +0 -34
  158. package/dist/src/dashboard-view.d.ts +0 -2
  159. package/dist/src/dashboard-view.js +0 -35
  160. package/dist/src/dashboard.d.ts +0 -2
  161. package/dist/src/dashboard.js +0 -9
  162. package/dist/src/deadline.d.ts +0 -45
  163. package/dist/src/deadline.js +0 -54
  164. package/dist/src/decision/ContinuationAdapter.d.ts +0 -5
  165. package/dist/src/decision/ContinuationAdapter.js +0 -5
  166. package/dist/src/decision/DecisionEngine.d.ts +0 -4
  167. package/dist/src/decision/DecisionManager.d.ts +0 -1
  168. package/dist/src/decision/DecisionManager.js +2 -7
  169. package/dist/src/decision/DecisionPolicy.d.ts +0 -1
  170. package/dist/src/decision/DecisionPolicy.js +0 -1
  171. package/dist/src/decision/FactContinuations.d.ts +11 -43
  172. package/dist/src/decision/FactContinuations.js +126 -95
  173. package/dist/src/decision/FactServiceGate.d.ts +0 -1
  174. package/dist/src/decision/FactServiceGate.js +0 -4
  175. package/dist/src/decision/PreparedSteps.d.ts +0 -15
  176. package/dist/src/decision/PreparedSteps.js +0 -10
  177. package/dist/src/decision/applyToolMenu.d.ts +0 -1
  178. package/dist/src/decision/applyToolMenu.js +1 -5
  179. package/dist/src/decision/checks.d.ts +15 -28
  180. package/dist/src/decision/checks.js +118 -49
  181. package/dist/src/decision/facts.d.ts +0 -16
  182. package/dist/src/decision/facts.js +0 -30
  183. package/dist/src/decision/guidancePolicy.js +0 -1
  184. package/dist/src/decision/hostedPolicy.d.ts +0 -6
  185. package/dist/src/decision/hostedPolicy.js +0 -7
  186. package/dist/src/decision/hostedSkills.d.ts +0 -19
  187. package/dist/src/decision/hostedSkills.js +0 -19
  188. package/dist/src/decision/optimizationPolicy.d.ts +0 -3
  189. package/dist/src/decision/optimizationPolicy.js +1 -4
  190. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +0 -7
  191. package/dist/src/decision/providers/AndorraDecisionProvider.js +4 -27
  192. package/dist/src/decision/providers/HttpDecisionProvider.d.ts +0 -2
  193. package/dist/src/decision/providers/HttpDecisionProvider.js +0 -6
  194. package/dist/src/decision/routeTools.d.ts +0 -8
  195. package/dist/src/decision/routeTools.js +1 -8
  196. package/dist/src/decision/toolFamilies.d.ts +0 -1
  197. package/dist/src/decision/toolFamilies.js +0 -1
  198. package/dist/src/decision/toolMenu.d.ts +0 -3
  199. package/dist/src/decision/toolMenu.js +0 -4
  200. package/dist/src/decision/types.d.ts +0 -6
  201. package/dist/src/default-graph.d.ts +0 -9
  202. package/dist/src/default-graph.js +0 -9
  203. package/dist/src/delegation-changes.d.ts +0 -56
  204. package/dist/src/delegation-changes.js +4 -130
  205. package/dist/src/diff-preview.d.ts +0 -1
  206. package/dist/src/diff-preview.js +0 -17
  207. package/dist/src/duration.d.ts +0 -50
  208. package/dist/src/duration.js +0 -50
  209. package/dist/src/efficiency.d.ts +0 -39
  210. package/dist/src/efficiency.js +0 -16
  211. package/dist/src/engine/protocol.d.ts +0 -2
  212. package/dist/src/engine/protocol.js +0 -2
  213. package/dist/src/engine-streams.d.ts +0 -9
  214. package/dist/src/extensions.d.ts +3 -2
  215. package/dist/src/extensions.js +63 -35
  216. package/dist/src/favicons.d.ts +0 -26
  217. package/dist/src/favicons.js +0 -34
  218. package/dist/src/file-diff.d.ts +2 -58
  219. package/dist/src/file-diff.js +0 -32
  220. package/dist/src/file-read-key.d.ts +0 -7
  221. package/dist/src/file-read-key.js +0 -7
  222. package/dist/src/file-read-state.d.ts +0 -1
  223. package/dist/src/file-read-state.js +0 -4
  224. package/dist/src/firefox-cookies.d.ts +0 -34
  225. package/dist/src/firefox-cookies.js +1 -55
  226. package/dist/src/git-identity-audit.d.ts +27 -0
  227. package/dist/src/git-identity-audit.js +286 -0
  228. package/dist/src/git-identity-guard.d.ts +4 -0
  229. package/dist/src/git-identity-guard.js +998 -0
  230. package/dist/src/git-identity-hold.d.ts +12 -0
  231. package/dist/src/git-identity-hold.js +81 -0
  232. package/dist/src/git-summary.d.ts +0 -58
  233. package/dist/src/git-summary.js +2 -212
  234. package/dist/src/goal-completion-verification.d.ts +2 -2
  235. package/dist/src/goal-completion-verification.js +3 -6
  236. package/dist/src/graph-account.d.ts +0 -21
  237. package/dist/src/graph-account.js +0 -17
  238. package/dist/src/graph-editor-session.d.ts +0 -1
  239. package/dist/src/graph-editor-session.js +0 -3
  240. package/dist/src/graph-health.d.ts +0 -63
  241. package/dist/src/graph-health.js +0 -57
  242. package/dist/src/graph-manager-chat.d.ts +5 -155
  243. package/dist/src/graph-manager-chat.js +2 -177
  244. package/dist/src/graph-provider-portability.d.ts +1 -21
  245. package/dist/src/graph-provider-portability.js +6 -45
  246. package/dist/src/graph-quota.d.ts +0 -33
  247. package/dist/src/graph-quota.js +1 -44
  248. package/dist/src/graph-runner.d.ts +0 -1
  249. package/dist/src/graph-runner.js +31 -391
  250. package/dist/src/graph-selection.d.ts +0 -14
  251. package/dist/src/graph-selection.js +0 -14
  252. package/dist/src/graph-server.d.ts +2 -10
  253. package/dist/src/graph-server.js +39 -101
  254. package/dist/src/graph-studio-features.d.ts +0 -5
  255. package/dist/src/graph-studio-features.js +2 -42
  256. package/dist/src/graph-sync.d.ts +0 -78
  257. package/dist/src/graph-sync.js +5 -201
  258. package/dist/src/graph-tool.d.ts +0 -18
  259. package/dist/src/graph-tool.js +0 -27
  260. package/dist/src/graph-ui/app.js +152 -491
  261. package/dist/src/graph-ui/compat.js +0 -7
  262. package/dist/src/graph-ui/controls.css +0 -48
  263. package/dist/src/graph-ui/controls.js +0 -88
  264. package/dist/src/graph-ui/drafts.js +0 -12
  265. package/dist/src/graph-ui/edge-router.js +0 -62
  266. package/dist/src/graph-ui/embed.js +0 -59
  267. package/dist/src/graph-ui/icons.js +0 -8
  268. package/dist/src/graph-ui/library.css +0 -5
  269. package/dist/src/graph-ui/manager-markdown.js +0 -11
  270. package/dist/src/graph-ui/manager-state.js +1 -78
  271. package/dist/src/graph-ui/manager.css +0 -18
  272. package/dist/src/graph-ui/manager.js +3 -180
  273. package/dist/src/graph-ui/model-picker.js +0 -29
  274. package/dist/src/graph-ui/sidebar.js +2 -3
  275. package/dist/src/graph-ui/skill-picker.js +373 -39
  276. package/dist/src/graph-ui/studio-canvas.js +3 -38
  277. package/dist/src/graph-ui/studio.css +0 -18
  278. package/dist/src/graph-ui/studio.js +3 -71
  279. package/dist/src/graph-ui/style.css +11 -134
  280. package/dist/src/graph-ui/theme.js +1 -26
  281. package/dist/src/graph-ui/tokens.css +15 -114
  282. package/dist/src/graphs.d.ts +6 -157
  283. package/dist/src/graphs.js +65 -266
  284. package/dist/src/grep-regex-worker.js +0 -2
  285. package/dist/src/grep-regex.d.ts +1 -5
  286. package/dist/src/grep-regex.js +6 -8
  287. package/dist/src/grok-provider.d.ts +0 -17
  288. package/dist/src/grok-provider.js +1 -26
  289. package/dist/src/handoffs.d.ts +0 -11
  290. package/dist/src/handoffs.js +0 -13
  291. package/dist/src/hardened-runtime.d.ts +0 -10
  292. package/dist/src/hardened-runtime.js +8 -46
  293. package/dist/src/harness-home.d.ts +21 -0
  294. package/dist/src/harness-home.js +87 -0
  295. package/dist/src/host-process-guard.d.ts +0 -50
  296. package/dist/src/host-process-guard.js +0 -641
  297. package/dist/src/limits.d.ts +0 -64
  298. package/dist/src/limits.js +0 -62
  299. package/dist/src/managed-sign-in.d.ts +0 -12
  300. package/dist/src/managed-sign-in.js +0 -16
  301. package/dist/src/markdown.d.ts +0 -28
  302. package/dist/src/markdown.js +1 -175
  303. package/dist/src/mcp.d.ts +0 -99
  304. package/dist/src/mcp.js +4 -170
  305. package/dist/src/membership-errors.d.ts +0 -14
  306. package/dist/src/membership-errors.js +0 -13
  307. package/dist/src/membership.d.ts +2 -60
  308. package/dist/src/membership.js +0 -85
  309. package/dist/src/memory/LocalToolMemory.d.ts +0 -1
  310. package/dist/src/memory/LocalToolMemory.js +2 -7
  311. package/dist/src/memory/MemoryDistiller.js +0 -15
  312. package/dist/src/memory/MemoryManager.d.ts +0 -3
  313. package/dist/src/memory/MemoryManager.js +6 -18
  314. package/dist/src/memory/MemoryPolicy.d.ts +0 -2
  315. package/dist/src/memory/MemoryPolicy.js +0 -2
  316. package/dist/src/memory/MemoryProvider.d.ts +0 -6
  317. package/dist/src/memory/MemoryRetriever.js +0 -7
  318. package/dist/src/memory/PermissionMemoryProvider.d.ts +0 -1
  319. package/dist/src/memory/PermissionMemoryProvider.js +0 -1
  320. package/dist/src/memory/ProjectMemory.d.ts +5 -40
  321. package/dist/src/memory/ProjectMemory.js +22 -47
  322. package/dist/src/memory/ToolFailureLessons.d.ts +0 -3
  323. package/dist/src/memory/ToolFailureLessons.js +0 -6
  324. package/dist/src/memory/providers/NoOpMemoryProvider.d.ts +0 -1
  325. package/dist/src/memory/providers/NoOpMemoryProvider.js +0 -1
  326. package/dist/src/memory/redaction.d.ts +0 -5
  327. package/dist/src/memory/redaction.js +0 -11
  328. package/dist/src/memory/repository.d.ts +0 -6
  329. package/dist/src/memory/repository.js +2 -12
  330. package/dist/src/memory/types.d.ts +0 -1
  331. package/dist/src/model-health-cache.d.ts +0 -38
  332. package/dist/src/model-health-cache.js +1 -49
  333. package/dist/src/model-metadata.d.ts +0 -18
  334. package/dist/src/model-metadata.js +2 -42
  335. package/dist/src/model-override.d.ts +0 -36
  336. package/dist/src/model-override.js +0 -43
  337. package/dist/src/model-tiers.d.ts +0 -13
  338. package/dist/src/model-tiers.js +0 -23
  339. package/dist/src/opencode-catalog.d.ts +0 -2
  340. package/dist/src/opencode-catalog.js +0 -11
  341. package/dist/src/opencode-cli-provider.d.ts +0 -35
  342. package/dist/src/opencode-cli-provider.js +1 -44
  343. package/dist/src/opencode-provider.d.ts +0 -2
  344. package/dist/src/opencode-provider.js +1 -16
  345. package/dist/src/package-name.d.ts +0 -2
  346. package/dist/src/package-name.js +0 -2
  347. package/dist/src/paged-transcript.d.ts +0 -11
  348. package/dist/src/paged-transcript.js +2 -20
  349. package/dist/src/palette.d.ts +0 -63
  350. package/dist/src/palette.js +0 -63
  351. package/dist/src/permissions.d.ts +0 -15
  352. package/dist/src/permissions.js +0 -17
  353. package/dist/src/powershell-pool.d.ts +0 -9
  354. package/dist/src/powershell-pool.js +3 -26
  355. package/dist/src/process-warnings.d.ts +4 -0
  356. package/dist/src/process-warnings.js +103 -0
  357. package/dist/src/profile.d.ts +0 -43
  358. package/dist/src/profile.js +0 -43
  359. package/dist/src/project-reservation.d.ts +11 -0
  360. package/dist/src/project-reservation.js +143 -0
  361. package/dist/src/provider-connection.d.ts +0 -18
  362. package/dist/src/provider-connection.js +0 -39
  363. package/dist/src/provider-engine.d.ts +0 -21
  364. package/dist/src/provider-engine.js +1 -96
  365. package/dist/src/provider-import.d.ts +0 -49
  366. package/dist/src/provider-import.js +0 -60
  367. package/dist/src/provider-keys.d.ts +1 -36
  368. package/dist/src/provider-keys.js +5 -48
  369. package/dist/src/provider-settings.d.ts +0 -2
  370. package/dist/src/provider-settings.js +0 -32
  371. package/dist/src/providers.d.ts +0 -217
  372. package/dist/src/providers.js +0 -315
  373. package/dist/src/pull-requests.d.ts +0 -173
  374. package/dist/src/pull-requests.js +5 -195
  375. package/dist/src/qa/browser/PlaywrightRunner.d.ts +0 -7
  376. package/dist/src/qa/browser/PlaywrightRunner.js +2 -16
  377. package/dist/src/qa/command-policy.d.ts +0 -23
  378. package/dist/src/qa/command-policy.js +0 -30
  379. package/dist/src/qa/guidance.d.ts +0 -21
  380. package/dist/src/qa/guidance.js +0 -20
  381. package/dist/src/qa/profile/ProjectInspector.d.ts +0 -4
  382. package/dist/src/qa/profile/ProjectInspector.js +0 -6
  383. package/dist/src/qa/profile/QaConfigLoader.d.ts +0 -7
  384. package/dist/src/qa/profile/QaConfigLoader.js +0 -6
  385. package/dist/src/qa/profile/QaProfile.d.ts +0 -7
  386. package/dist/src/qa/profile/QaProfile.js +0 -7
  387. package/dist/src/qa/profile/yaml.d.ts +0 -9
  388. package/dist/src/qa/profile/yaml.js +0 -13
  389. package/dist/src/qa/qa-authorize.d.ts +0 -19
  390. package/dist/src/qa/qa-authorize.js +4 -11
  391. package/dist/src/qa/runtime/ProcessManager.d.ts +0 -31
  392. package/dist/src/qa/runtime/ProcessManager.js +4 -41
  393. package/dist/src/qa/runtime/PtyManager.d.ts +0 -4
  394. package/dist/src/qa/runtime/PtyManager.js +1 -7
  395. package/dist/src/qa/runtime/changes.d.ts +0 -11
  396. package/dist/src/qa/runtime/changes.js +1 -3
  397. package/dist/src/qa/tools.d.ts +0 -10
  398. package/dist/src/qa/tools.js +0 -12
  399. package/dist/src/qa/types.d.ts +0 -13
  400. package/dist/src/react-runtime.d.ts +2 -21
  401. package/dist/src/react-runtime.js +95 -415
  402. package/dist/src/read-document-doc.d.ts +0 -6
  403. package/dist/src/read-document-doc.js +0 -55
  404. package/dist/src/read-document-docx.d.ts +0 -16
  405. package/dist/src/read-document-docx.js +2 -69
  406. package/dist/src/read-document-text.d.ts +0 -17
  407. package/dist/src/read-document-text.js +0 -22
  408. package/dist/src/read-document-tool.d.ts +0 -31
  409. package/dist/src/read-document-tool.js +0 -30
  410. package/dist/src/read-document.d.ts +0 -49
  411. package/dist/src/read-document.js +1 -67
  412. package/dist/src/read-image.d.ts +0 -32
  413. package/dist/src/read-image.js +0 -33
  414. package/dist/src/remote/cert.d.ts +0 -18
  415. package/dist/src/remote/cert.js +0 -44
  416. package/dist/src/remote/client.d.ts +0 -70
  417. package/dist/src/remote/client.js +1 -116
  418. package/dist/src/remote/command.js +0 -17
  419. package/dist/src/remote/engine-pool.d.ts +0 -152
  420. package/dist/src/remote/engine-pool.js +17 -335
  421. package/dist/src/remote/errors.d.ts +0 -15
  422. package/dist/src/remote/errors.js +0 -7
  423. package/dist/src/remote/network.d.ts +0 -26
  424. package/dist/src/remote/network.js +1 -34
  425. package/dist/src/remote/pairing.d.ts +16 -51
  426. package/dist/src/remote/pairing.js +50 -57
  427. package/dist/src/remote/pem.d.ts +0 -4
  428. package/dist/src/remote/pem.js +0 -4
  429. package/dist/src/remote/roots.d.ts +0 -20
  430. package/dist/src/remote/roots.js +0 -8
  431. package/dist/src/remote/serve.d.ts +0 -47
  432. package/dist/src/remote/serve.js +0 -30
  433. package/dist/src/remote/server.d.ts +0 -14
  434. package/dist/src/remote/server.js +1 -79
  435. package/dist/src/remote/types.d.ts +1 -32
  436. package/dist/src/remote/types.js +0 -10
  437. package/dist/src/run-control.d.ts +0 -7
  438. package/dist/src/run-control.js +0 -7
  439. package/dist/src/run-progress.d.ts +0 -170
  440. package/dist/src/run-progress.js +0 -285
  441. package/dist/src/run-records.d.ts +0 -443
  442. package/dist/src/run-records.js +14 -687
  443. package/dist/src/run-temp.d.ts +12 -0
  444. package/dist/src/run-temp.js +50 -0
  445. package/dist/src/runtime.d.ts +10 -228
  446. package/dist/src/runtime.js +0 -127
  447. package/dist/src/sandbox-child.js +0 -1
  448. package/dist/src/save-lock.d.ts +0 -12
  449. package/dist/src/save-lock.js +0 -28
  450. package/dist/src/screen-selection.d.ts +0 -23
  451. package/dist/src/screen-selection.js +0 -22
  452. package/dist/src/secret-redaction.d.ts +0 -12
  453. package/dist/src/secret-redaction.js +0 -45
  454. package/dist/src/session-changes.d.ts +4 -80
  455. package/dist/src/session-changes.js +25 -130
  456. package/dist/src/session-goal.d.ts +129 -0
  457. package/dist/src/session-goal.js +230 -0
  458. package/dist/src/session-monitor.d.ts +1 -10
  459. package/dist/src/session-monitor.js +2 -39
  460. package/dist/src/session-reaper.d.ts +0 -15
  461. package/dist/src/session-reaper.js +0 -14
  462. package/dist/src/session-skills.d.ts +15 -44
  463. package/dist/src/session-skills.js +75 -60
  464. package/dist/src/session-summary.d.ts +0 -26
  465. package/dist/src/session-summary.js +0 -32
  466. package/dist/src/session-title.d.ts +0 -1
  467. package/dist/src/session-title.js +0 -2
  468. package/dist/src/sessions.d.ts +2 -122
  469. package/dist/src/sessions.js +7 -178
  470. package/dist/src/shell.d.ts +3 -20
  471. package/dist/src/shell.js +8 -72
  472. package/dist/src/side-panel.d.ts +5 -99
  473. package/dist/src/side-panel.js +76 -133
  474. package/dist/src/sign-in-detection.d.ts +0 -39
  475. package/dist/src/sign-in-detection.js +0 -43
  476. package/dist/src/sign-in-offer.d.ts +1 -19
  477. package/dist/src/sign-in-offer.js +0 -13
  478. package/dist/src/skill-commands.d.ts +0 -1
  479. package/dist/src/skill-commands.js +1 -4
  480. package/dist/src/skills/bundled/control-browser/SKILL.md +1 -1
  481. package/dist/src/skills/bundled/provenance.json +1 -1
  482. package/dist/src/skills/invocable-skills.d.ts +0 -18
  483. package/dist/src/skills/invocable-skills.js +0 -17
  484. package/dist/src/skills/project-skills.d.ts +0 -1
  485. package/dist/src/skills/project-skills.js +0 -3
  486. package/dist/src/skills/prompt-skills.js +0 -14
  487. package/dist/src/skills/runtime-skills.d.ts +0 -13
  488. package/dist/src/skills/runtime-skills.js +0 -37
  489. package/dist/src/stall-recovery.d.ts +0 -25
  490. package/dist/src/stall-recovery.js +0 -38
  491. package/dist/src/stray-files.d.ts +0 -9
  492. package/dist/src/stray-files.js +0 -16
  493. package/dist/src/structured-step.d.ts +0 -22
  494. package/dist/src/structured-step.js +0 -22
  495. package/dist/src/subagent-run.d.ts +0 -163
  496. package/dist/src/subagent-run.js +4 -373
  497. package/dist/src/subagent-tree.d.ts +32 -0
  498. package/dist/src/subagent-tree.js +128 -0
  499. package/dist/src/telemetry/aggregate.d.ts +0 -37
  500. package/dist/src/telemetry/aggregate.js +0 -40
  501. package/dist/src/telemetry/capture-core.d.ts +0 -87
  502. package/dist/src/telemetry/capture-core.js +0 -67
  503. package/dist/src/telemetry/capture.d.ts +0 -1
  504. package/dist/src/telemetry/capture.js +0 -3
  505. package/dist/src/telemetry/classify.d.ts +0 -58
  506. package/dist/src/telemetry/classify.js +0 -60
  507. package/dist/src/telemetry/decision-capture.d.ts +0 -1
  508. package/dist/src/telemetry/emitter.d.ts +0 -30
  509. package/dist/src/telemetry/emitter.js +1 -62
  510. package/dist/src/telemetry/gate.d.ts +0 -29
  511. package/dist/src/telemetry/gate.js +0 -22
  512. package/dist/src/telemetry/identity.d.ts +0 -13
  513. package/dist/src/telemetry/identity.js +0 -29
  514. package/dist/src/telemetry/outbox.d.ts +0 -64
  515. package/dist/src/telemetry/outbox.js +1 -108
  516. package/dist/src/telemetry/schema.d.ts +1 -49
  517. package/dist/src/telemetry/schema.js +1 -82
  518. package/dist/src/telemetry/state.d.ts +0 -53
  519. package/dist/src/telemetry/state.js +0 -64
  520. package/dist/src/telemetry/surface.d.ts +0 -31
  521. package/dist/src/telemetry/surface.js +1 -39
  522. package/dist/src/telemetry/uploader.d.ts +0 -11
  523. package/dist/src/telemetry/uploader.js +0 -46
  524. package/dist/src/telemetry/uploads.d.ts +0 -11
  525. package/dist/src/telemetry/uploads.js +0 -11
  526. package/dist/src/telemetry/version.d.ts +0 -4
  527. package/dist/src/telemetry/version.js +0 -14
  528. package/dist/src/telemetry/workspace.d.ts +0 -7
  529. package/dist/src/telemetry/workspace.js +1 -22
  530. package/dist/src/terminal-ui.d.ts +14 -523
  531. package/dist/src/terminal-ui.js +74 -876
  532. package/dist/src/test-edit-guard.d.ts +74 -0
  533. package/dist/src/test-edit-guard.js +269 -0
  534. package/dist/src/text.d.ts +0 -1
  535. package/dist/src/text.js +0 -1
  536. package/dist/src/time-limit.d.ts +0 -36
  537. package/dist/src/time-limit.js +0 -37
  538. package/dist/src/timers.d.ts +0 -161
  539. package/dist/src/timers.js +0 -126
  540. package/dist/src/todos.d.ts +0 -1
  541. package/dist/src/todos.js +0 -3
  542. package/dist/src/token-rate.d.ts +0 -94
  543. package/dist/src/token-rate.js +0 -154
  544. package/dist/src/tool-activity.d.ts +0 -6
  545. package/dist/src/tool-activity.js +0 -7
  546. package/dist/src/tool-availability.d.ts +0 -13
  547. package/dist/src/tool-availability.js +1 -14
  548. package/dist/src/tool-call-clock.d.ts +1 -4
  549. package/dist/src/tool-call-clock.js +0 -13
  550. package/dist/src/tool-catalog.d.ts +0 -11
  551. package/dist/src/tool-catalog.js +0 -23
  552. package/dist/src/tool-dependencies.d.ts +0 -5
  553. package/dist/src/tool-dependencies.js +0 -4
  554. package/dist/src/tool-diff-stats.d.ts +0 -23
  555. package/dist/src/tool-diff-stats.js +0 -49
  556. package/dist/src/tool-errors.d.ts +9 -7
  557. package/dist/src/tool-errors.js +13 -6
  558. package/dist/src/tool-failure-tracker.d.ts +3 -11
  559. package/dist/src/tool-failure-tracker.js +19 -27
  560. package/dist/src/tool-names.d.ts +0 -16
  561. package/dist/src/tool-names.js +0 -12
  562. package/dist/src/tool-profile.d.ts +6 -0
  563. package/dist/src/tool-profile.js +23 -0
  564. package/dist/src/tool-result-filter.d.ts +0 -19
  565. package/dist/src/tool-result-filter.js +1 -66
  566. package/dist/src/tool-schema-compatibility.d.ts +0 -6
  567. package/dist/src/tool-schema-compatibility.js +0 -9
  568. package/dist/src/tools.d.ts +0 -4
  569. package/dist/src/tools.js +11 -114
  570. package/dist/src/trajectory.d.ts +0 -13
  571. package/dist/src/trajectory.js +23 -79
  572. package/dist/src/transcript.d.ts +0 -41
  573. package/dist/src/transcript.js +2 -60
  574. package/dist/src/types.d.ts +1 -168
  575. package/dist/src/untracked-file-removal.js +0 -20
  576. package/dist/src/update-check.d.ts +0 -14
  577. package/dist/src/update-check.js +1 -15
  578. package/dist/src/update.d.ts +0 -35
  579. package/dist/src/update.js +0 -100
  580. package/dist/src/usage-analytics.d.ts +17 -17
  581. package/dist/src/usage-analytics.js +168 -209
  582. package/dist/src/web-search.d.ts +0 -23
  583. package/dist/src/web-search.js +1 -27
  584. package/dist/src/widgets.d.ts +0 -25
  585. package/dist/src/widgets.js +0 -24
  586. package/dist/src/workspace-facts.d.ts +0 -12
  587. package/dist/src/workspace-facts.js +1 -18
  588. package/dist/src/workspace-git-metadata.d.ts +0 -16
  589. package/dist/src/workspace-git-metadata.js +0 -21
  590. package/dist/src/workspace-instructions.d.ts +3 -15
  591. package/dist/src/workspace-instructions.js +6 -19
  592. package/package.json +2 -2
@@ -9,37 +9,15 @@ import { desktopUaOverride, hardenContext, stealthContextOptions, stealthLaunchA
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,10 @@ 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';
59
31
  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
32
  const VIEW_CLIPBOARD_LIMIT = 1_000_000;
63
- /**
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.
71
- */
72
33
  const SELECTION_STATE = `(() => {
73
34
  const active = document.activeElement;
74
35
  const inFrame = !!active && (active.tagName === 'IFRAME' || active.tagName === 'FRAME');
@@ -82,13 +43,6 @@ const SELECTION_STATE = `(() => {
82
43
  }
83
44
  return { inFrame: false, focused, text: window.getSelection ? String(window.getSelection() || '') : '' };
84
45
  })()`;
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
46
  const CURSOR_AT = `((point) => {
93
47
  let doc = document;
94
48
  let x = point.x;
@@ -112,9 +66,13 @@ const CURSOR_AT = `((point) => {
112
66
  }
113
67
  return 'default';
114
68
  })`;
115
- /** The dependency panel browsing needs: an HTTP(S) page an isolated browser can open. */ export function browserViewUrl(value) {
69
+ export function browserViewUrl(value) {
116
70
  const url = new URL(value);
117
- if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
71
+ if (url.protocol === 'chrome-extension:') {
72
+ if (!/^[a-p]{32}$/.test(url.hostname) || url.username || url.password)
73
+ throw new Error('Use a chrome-extension://<32-letter id>/ page');
74
+ }
75
+ else if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
118
76
  throw new Error('Use an HTTP(S) URL without embedded credentials');
119
77
  if (url.href.length > VIEW_URL_LIMIT)
120
78
  throw new Error('URL exceeds the 2048-character limit');
@@ -124,25 +82,11 @@ export function clampViewport(width, height) {
124
82
  const value = (input, min, max, fallback) => Number.isSafeInteger(input) ? Math.max(min, Math.min(max, input)) : fallback;
125
83
  return { width: value(width, 280, VIEW_MAX_VIEWPORT.width, 900), height: value(height, 240, VIEW_MAX_VIEWPORT.height, 700) };
126
84
  }
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
85
  export function clampScale(value) {
135
86
  if (typeof value !== 'number' || !Number.isFinite(value))
136
87
  return 1;
137
88
  return Math.round(Math.max(1, Math.min(VIEW_MAX_SCALE, value)) * 100) / 100;
138
89
  }
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
90
  export function jpegSize(bytes) {
147
91
  if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8)
148
92
  return undefined;
@@ -153,13 +97,11 @@ export function jpegSize(bytes) {
153
97
  continue;
154
98
  }
155
99
  const marker = bytes[offset + 1];
156
- // Fill bytes before a marker, and the stand-alone markers that carry no length.
157
100
  if (marker === 0xff || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) {
158
101
  offset += 2;
159
102
  continue;
160
103
  }
161
104
  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
105
  if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
164
106
  if (length < 7 || offset + 9 > bytes.length)
165
107
  return undefined;
@@ -171,7 +113,6 @@ export function jpegSize(bytes) {
171
113
  }
172
114
  return undefined;
173
115
  }
174
- /** Windows virtual-key codes for the named keys a panel keypress can produce. */
175
116
  const KEY_CODE = {
176
117
  Enter: 13, Backspace: 8, Tab: 9, Escape: 27, Delete: 46, Insert: 45,
177
118
  ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Home: 36, End: 35, PageUp: 33, PageDown: 34,
@@ -182,19 +123,6 @@ const CODE_KEY = {
182
123
  Backslash: 220, Minus: 189, Equal: 187, Backquote: 192, NumpadEnter: 13, NumpadAdd: 107, NumpadSubtract: 109,
183
124
  NumpadMultiply: 106, NumpadDivide: 111, NumpadDecimal: 110,
184
125
  };
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
126
  export function keyDescriptor(key, code, modifiers = 0) {
199
127
  const named = KEY_CODE[key]
200
128
  ?? (code?.startsWith('Key') && code.length === 4 ? code.charCodeAt(3) : undefined)
@@ -205,13 +133,7 @@ export function keyDescriptor(key, code, modifiers = 0) {
205
133
  throw new Error(`Unsupported key: ${key}`);
206
134
  const ctrl = (modifiers & MODIFIER_BITS.ctrl) !== 0;
207
135
  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
136
  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
137
  const shortcut = !altCharacter && ((modifiers & MODIFIER_BITS.meta) !== 0 || (ctrl !== alt && (ctrl || alt)));
216
138
  const keyCode = named ?? key.toUpperCase().charCodeAt(0);
217
139
  const text = shortcut ? undefined : printable ? key : key === 'Enter' ? '\r' : undefined;
@@ -231,16 +153,6 @@ export function modifierMask(modifiers) {
231
153
  throw new Error('modifiers must be a list of alt, ctrl, meta, shift');
232
154
  return modifiers.reduce((mask, name) => mask | MODIFIER_BITS[name], 0);
233
155
  }
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
156
  export function macEditingCommands(key, modifiers) {
245
157
  const meta = (modifiers & MODIFIER_BITS.meta) !== 0;
246
158
  const alt = (modifiers & MODIFIER_BITS.alt) !== 0;
@@ -269,36 +181,22 @@ export function macEditingCommands(key, modifiers) {
269
181
  }
270
182
  return [];
271
183
  }
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) {
184
+ export function viewLaunchOptions(channel, executablePath, scale = 1, extensionPaths = []) {
185
+ const extensions = channel === 'chromium' ? extensionPaths : [];
279
186
  return {
280
187
  headless: true,
281
188
  ...(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}`] : [])],
189
+ ignoreDefaultArgs: ['--mute-audio', ...(extensions.length ? ['--disable-extensions'] : [])],
190
+ args: [
191
+ ...stealthLaunchArgs(), ...(scale !== 1 ? [`--force-device-scale-factor=${scale}`] : []),
192
+ ...(extensions.length ? [`--disable-extensions-except=${extensions.join(',')}`, `--load-extension=${extensions.join(',')}`] : []),
193
+ ],
290
194
  timeout: 20_000,
291
195
  };
292
196
  }
293
- /** Whether a frame arriving at `now` may be emitted, given the last emitted frame time. */
294
197
  export function frameGate(now, lastEmittedAt, minIntervalMs) {
295
198
  return lastEmittedAt === undefined || now - lastEmittedAt >= minIntervalMs;
296
199
  }
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
200
  export function channelCandidate(channel, platform, chromiumExecutable) {
303
201
  if (channel === 'chromium') {
304
202
  try {
@@ -321,60 +219,33 @@ export function channelCandidate(channel, platform, chromiumExecutable) {
321
219
  ? ['/usr/bin/microsoft-edge', '/usr/bin/microsoft-edge-stable'].find(existsSync)
322
220
  : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable'].find(existsSync);
323
221
  }
324
- /** How long closing a profile may take: a graceful close is what flushes cookies to disk. */
222
+ const EXTENSION_RESTART_POLL_MS = 5_000;
223
+ const EXTENSION_PROBE_TIMEOUT_MS = 4_000;
325
224
  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
- */
225
+ const EXTENSION_PAGE_CLAIM_MS = 300;
331
226
  export class BrowserViewManager {
332
227
  emit;
333
228
  launchBrowser;
334
229
  options;
335
230
  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
231
  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
232
  displayScale = 1;
351
- /** Launches in flight per session, so concurrent opens share one browser. */
352
233
  launching = new Map();
353
234
  runtime = { state: 'checking' };
354
235
  runtimeProbe;
355
236
  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
237
  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
238
  released = new Set();
368
- /** Project profiles open now, by profile key. */
369
239
  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
240
  incognito = new Set();
376
- /** Idle-reap leases by session id: the time each session's browser is held until (see `hold`). */
377
241
  holds = new Map();
242
+ pendingRestart = new Set();
243
+ claimedPages = new WeakSet();
244
+ restartsInFlight = new Set();
245
+ /** The restart under way for each profile, through its tab restoration: one at a time per profile. */
246
+ restartingProfiles = new Map();
247
+ restoring = new Map();
248
+ restartPoll;
378
249
  closed = false;
379
250
  constructor(emit, launchBrowser, options = {}) {
380
251
  this.emit = emit;
@@ -385,10 +256,6 @@ export class BrowserViewManager {
385
256
  this.runtime = status;
386
257
  this.emit('browser.runtime', { ...status });
387
258
  }
388
- /**
389
- * Probe the same executables `launch` will use, without launching anything;
390
- * the answer is cached.
391
- */
392
259
  runtimeStatus(force = false) {
393
260
  if (!force && this.runtime.state !== 'checking')
394
261
  return Promise.resolve(this.runtime);
@@ -416,16 +283,9 @@ export class BrowserViewManager {
416
283
  })().finally(() => { this.runtimeProbe = undefined; });
417
284
  return this.runtimeProbe;
418
285
  }
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
286
  install() {
426
287
  if (this.installTask)
427
288
  return this.installTask;
428
- // Nothing to install into a manager that is already gone.
429
289
  if (this.closed)
430
290
  return Promise.resolve({ state: 'failed', detail: 'Application is shutting down' });
431
291
  const run = async () => new Promise(resolve => {
@@ -440,8 +300,6 @@ export class BrowserViewManager {
440
300
  this.installer = undefined;
441
301
  resolve(value);
442
302
  };
443
- // A stalled download must not wedge the runtime in 'installing' forever:
444
- // the installer is stopped and the state reported as failed.
445
303
  const timer = setTimeout(() => {
446
304
  child?.kill();
447
305
  const failed = { state: 'failed', detail: detail || 'Browser runtime install timed out' };
@@ -490,16 +348,10 @@ export class BrowserViewManager {
490
348
  return this.installTask;
491
349
  }
492
350
  async launch(scale) {
493
- // Tests supply a fake browser; production launches the real one below.
494
351
  if (this.launchBrowser)
495
352
  return await this.launchBrowser(scale);
496
353
  const { chromium } = await import('playwright-core');
497
354
  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
355
  for (const channel of ['chromium', 'msedge', 'chrome']) {
504
356
  if (this.closed)
505
357
  throw new Error('Application is shutting down');
@@ -515,10 +367,21 @@ export class BrowserViewManager {
515
367
  }
516
368
  throw new Error(`Browser runtime is not usable: ${failures.join('; ').slice(0, 1000)}`);
517
369
  }
518
- /** Launch Chromium on a project's profile folder, with the same candidates as `launch`. */
519
370
  async launchPersistent(directory, viewport, scale) {
520
- if (this.options.launchProfile)
521
- return await this.options.launchProfile(directory, viewport, scale);
371
+ const set = this.options.extensions
372
+ ? await this.options.extensions.launchSet().catch(() => ({ load: [], problems: {} }))
373
+ : { load: [], problems: {} };
374
+ const status = {};
375
+ for (const [id, detail] of Object.entries(set.problems))
376
+ status[id] = { state: 'failed', detail };
377
+ if (this.options.launchProfile) {
378
+ const context = await this.options.launchProfile(directory, viewport, scale, set);
379
+ if (set.load.length)
380
+ await this.reportLoaded(context, set, status);
381
+ else if (Object.keys(status).length)
382
+ this.options.extensions?.report(status);
383
+ return context;
384
+ }
522
385
  await mkdir(directory, { recursive: true });
523
386
  const { chromium } = await import('playwright-core');
524
387
  const failures = [];
@@ -528,10 +391,34 @@ export class BrowserViewManager {
528
391
  const candidate = channelCandidate(channel, process.platform, () => chromium.executablePath());
529
392
  if (!candidate || !existsSync(candidate))
530
393
  continue;
531
- try {
532
- const context = await chromium.launchPersistentContext(directory, { ...viewLaunchOptions(channel, candidate, scale), ...stealthContextOptions(), viewport: { ...viewport }, acceptDownloads: false });
394
+ const open = async (paths) => {
395
+ const context = await chromium.launchPersistentContext(directory, { ...viewLaunchOptions(channel, candidate, scale, paths), ...stealthContextOptions(), viewport: { ...viewport }, acceptDownloads: false });
533
396
  await hardenContext(context);
534
397
  return context;
398
+ };
399
+ try {
400
+ if (channel !== 'chromium' || set.load.length === 0) {
401
+ const context = await open([]);
402
+ for (const item of set.load)
403
+ 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' };
404
+ if (Object.keys(status).length)
405
+ this.options.extensions?.report(status);
406
+ return context;
407
+ }
408
+ let context;
409
+ try {
410
+ context = await open(set.load.map(item => item.path));
411
+ }
412
+ catch (error) {
413
+ const detail = `The browser would not start with extensions: ${(error instanceof Error ? error.message : String(error)).split('\n')[0].slice(0, 300)}`;
414
+ context = await open([]);
415
+ for (const item of set.load)
416
+ status[item.id] = { state: 'failed', detail };
417
+ this.options.extensions?.report(status);
418
+ return context;
419
+ }
420
+ await this.reportLoaded(context, set, status);
421
+ return context;
535
422
  }
536
423
  catch (error) {
537
424
  failures.push((error instanceof Error ? error.message : String(error)).split('\n')[0]);
@@ -539,12 +426,191 @@ export class BrowserViewManager {
539
426
  }
540
427
  throw new Error(`Project browser profile is not usable: ${failures.join('; ').slice(0, 1000)}`);
541
428
  }
542
- /**
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.
547
- */
429
+ async reportLoaded(context, set, status) {
430
+ let page;
431
+ try {
432
+ page = await context.newPage();
433
+ for (const item of set.load) {
434
+ try {
435
+ await page.goto(`chrome-extension://${item.id}/manifest.json`, { timeout: EXTENSION_PROBE_TIMEOUT_MS });
436
+ status[item.id] = { state: 'loaded' };
437
+ }
438
+ catch {
439
+ status[item.id] = { state: 'failed', detail: 'Chromium did not load it: check the folder for manifest errors or missing files' };
440
+ }
441
+ }
442
+ }
443
+ catch { }
444
+ finally {
445
+ await Promise.resolve().then(() => page?.close()).catch(() => { });
446
+ }
447
+ this.options.extensions?.report(status);
448
+ }
449
+ async restartForExtensions(force = false) {
450
+ if (this.closed)
451
+ return { restarted: 0, pending: [] };
452
+ for (const key of this.profiles.keys())
453
+ this.pendingRestart.add(key);
454
+ return await this.retryPendingRestarts(force);
455
+ }
456
+ async restartWithSession(sessionId, everyProfile) {
457
+ if (this.closed)
458
+ return { open: false, restarted: false, waitingOn: [] };
459
+ const key = this.sessions.get(sessionId)?.profileKey;
460
+ if (key !== undefined)
461
+ while (this.restartingProfiles.has(key))
462
+ await this.restartingProfiles.get(key).catch(() => { });
463
+ if (everyProfile)
464
+ for (const profile of this.profiles.keys())
465
+ this.pendingRestart.add(profile);
466
+ if (key !== undefined && this.sessions.get(sessionId)?.profileKey === key)
467
+ this.pendingRestart.add(key);
468
+ await this.retryPendingRestarts(false, sessionId);
469
+ if (key === undefined || this.sessions.get(sessionId)?.profileKey !== key)
470
+ return { open: false, restarted: false, waitingOn: [] };
471
+ if (!this.pendingRestart.has(key))
472
+ return { open: true, restarted: true, waitingOn: [] };
473
+ const now = Date.now();
474
+ const waitingOn = [...this.sessions].filter(([id, session]) => id !== sessionId && session.profileKey === key && (this.holds.get(id) ?? 0) > now).map(([id]) => id);
475
+ return { open: true, restarted: false, waitingOn };
476
+ }
477
+ async retryPendingRestarts(force = false, ownHold) {
478
+ if (this.closed)
479
+ return { restarted: 0, pending: [] };
480
+ const now = Date.now();
481
+ let restarted = 0;
482
+ const work = [];
483
+ for (const key of [...this.pendingRestart]) {
484
+ const members = [...this.sessions].filter(([, session]) => session.profileKey === key);
485
+ const host = this.profiles.get(key);
486
+ if (!host && members.length === 0) {
487
+ this.pendingRestart.delete(key);
488
+ continue;
489
+ }
490
+ if (host && (!host.context || members.length === 0))
491
+ continue;
492
+ // A restart still restoring this profile's tabs finishes first; the change stays queued and runs
493
+ // once it is done, with a snapshot of every restored tab rather than a half-restored one.
494
+ if (this.restartingProfiles.has(key))
495
+ continue;
496
+ const held = members.some(([id]) => id !== ownHold && (this.holds.get(id) ?? 0) > now);
497
+ if (held && !force)
498
+ continue;
499
+ this.pendingRestart.delete(key);
500
+ restarted += 1;
501
+ const running = this.restartProfile(key, members.map(([id]) => id));
502
+ this.restartsInFlight.add(running);
503
+ this.restartingProfiles.set(key, running);
504
+ work.push(running.finally(() => {
505
+ this.restartsInFlight.delete(running);
506
+ if (this.restartingProfiles.get(key) === running)
507
+ this.restartingProfiles.delete(key);
508
+ if (this.pendingRestart.has(key) && !this.closed)
509
+ void this.retryPendingRestarts(force).catch(() => { });
510
+ }));
511
+ }
512
+ await Promise.all(work);
513
+ this.armRestartPoll();
514
+ if (this.pendingRestart.size === 0 && this.restartsInFlight.size === 0)
515
+ this.options.extensions?.settled?.();
516
+ const pending = this.pendingRestartSessions();
517
+ this.emit('browser.extensions', { kind: 'restart', pending });
518
+ return { restarted, pending };
519
+ }
520
+ pendingRestartSessions() {
521
+ return [...this.sessions].filter(([, session]) => session.profileKey !== undefined && this.pendingRestart.has(session.profileKey)).map(([id]) => id);
522
+ }
523
+ armRestartPoll() {
524
+ if (this.restartPoll || this.pendingRestart.size === 0 || this.closed)
525
+ return;
526
+ this.restartPoll = setTimeout(() => {
527
+ this.restartPoll = undefined;
528
+ if (this.pendingRestart.size)
529
+ void this.retryPendingRestarts(false).catch(() => { });
530
+ }, EXTENSION_RESTART_POLL_MS);
531
+ this.restartPoll.unref?.();
532
+ }
533
+ async restartProfile(key, sessionIds) {
534
+ const snapshots = sessionIds.flatMap(sessionId => {
535
+ const session = this.sessions.get(sessionId);
536
+ if (!session)
537
+ return [];
538
+ const tabs = [...session.tabs.values()];
539
+ const urls = tabs.map(tab => tab.url);
540
+ return [{ sessionId, urls, active: tabs.findIndex(tab => tab.id === session.activeTabId) }];
541
+ });
542
+ const tokens = new Map(snapshots.map(snapshot => [snapshot.sessionId, { cancelled: false, abandoned: false }]));
543
+ for (const [sessionId, token] of tokens)
544
+ this.restoring.set(sessionId, token);
545
+ const host = this.profiles.get(key);
546
+ let finishRestart;
547
+ if (host)
548
+ host.restarting = new Promise(resolve => { finishRestart = resolve; });
549
+ try {
550
+ try {
551
+ await Promise.all(sessionIds.map(sessionId => this.closeSession(sessionId, 'extensions')));
552
+ await host?.closing;
553
+ }
554
+ finally {
555
+ if (host) {
556
+ host.restarting = undefined;
557
+ finishRestart();
558
+ }
559
+ }
560
+ for (const snapshot of snapshots) {
561
+ const token = tokens.get(snapshot.sessionId);
562
+ const opened = [];
563
+ for (const url of snapshot.urls) {
564
+ if (token.cancelled || token.abandoned || this.closed)
565
+ break;
566
+ // The session may have moved to another browser meanwhile (incognito): its tabs are not
567
+ // this profile's to fill, and the switch's own blank tab stays the one shown.
568
+ const current = this.sessions.get(snapshot.sessionId);
569
+ if (this.incognito.has(snapshot.sessionId) || (current && current.profileKey !== key)) {
570
+ token.abandoned = true;
571
+ break;
572
+ }
573
+ let target;
574
+ try {
575
+ target = browserViewUrl(url);
576
+ }
577
+ catch {
578
+ target = undefined;
579
+ }
580
+ if (!target) {
581
+ opened.push(undefined);
582
+ continue;
583
+ }
584
+ try {
585
+ opened.push((await this.openPage(snapshot.sessionId, target)).tabId);
586
+ }
587
+ catch {
588
+ opened.push(undefined);
589
+ }
590
+ }
591
+ if (token.cancelled) {
592
+ await this.closeSession(snapshot.sessionId, 'released');
593
+ continue;
594
+ }
595
+ if (token.abandoned)
596
+ continue;
597
+ const active = snapshot.active >= 0 ? opened[snapshot.active] : undefined;
598
+ if (active)
599
+ await this.activateTab(snapshot.sessionId, active).catch(() => { });
600
+ // The saved tabs are back; extension pages the relaunch opened take what room is left.
601
+ if (this.restoring.get(snapshot.sessionId) === token)
602
+ this.restoring.delete(snapshot.sessionId);
603
+ const restored = this.sessions.get(snapshot.sessionId);
604
+ if (restored)
605
+ this.claimUnclaimed(snapshot.sessionId, restored);
606
+ }
607
+ }
608
+ finally {
609
+ for (const [sessionId, token] of tokens)
610
+ if (this.restoring.get(sessionId) === token)
611
+ this.restoring.delete(sessionId);
612
+ }
613
+ }
548
614
  async acquireProfile(owner, profile, viewport, scale) {
549
615
  for (;;) {
550
616
  const current = this.profiles.get(profile.key);
@@ -552,19 +618,25 @@ export class BrowserViewManager {
552
618
  await current.closing;
553
619
  continue;
554
620
  }
621
+ if (current?.restarting) {
622
+ await current.restarting;
623
+ continue;
624
+ }
555
625
  const host = current ?? { users: new Set() };
556
626
  if (!current)
557
627
  this.profiles.set(profile.key, host);
558
628
  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
629
  if (!host.starting)
562
630
  host.scale = scale;
563
631
  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(() => { });
632
+ for (const page of context.pages?.() ?? []) {
633
+ const url = String(page.url?.() ?? '');
634
+ if (url && url !== 'about:blank')
635
+ (host.unclaimed ??= []).push(page);
636
+ else
637
+ await Promise.resolve().then(() => page.close()).catch(() => { });
638
+ }
639
+ context.on?.('page', (page) => { void this.claimExtensionPage(profile.key, page); });
568
640
  context.on?.('close', () => { if (this.profiles.get(profile.key) === host)
569
641
  this.profiles.delete(profile.key); });
570
642
  host.context = context;
@@ -574,7 +646,6 @@ export class BrowserViewManager {
574
646
  return { context: await host.starting, scale: host.scale ?? 1 };
575
647
  }
576
648
  catch (error) {
577
- // A failed launch is not cached: the next open tries the profile again.
578
649
  host.users.delete(owner);
579
650
  if (this.profiles.get(profile.key) === host)
580
651
  this.profiles.delete(profile.key);
@@ -582,7 +653,41 @@ export class BrowserViewManager {
582
653
  }
583
654
  }
584
655
  }
585
- /** Leave a project's profile; the last session out closes it, which flushes cookies to disk. */
656
+ async claimExtensionPage(key, page) {
657
+ await new Promise(resolve => { const timer = setTimeout(resolve, EXTENSION_PAGE_CLAIM_MS); timer.unref?.(); });
658
+ if (this.claimedPages.has(page) || page.isClosed?.() === true || this.closed)
659
+ return;
660
+ for (const session of this.sessions.values())
661
+ for (const tab of session.tabs.values())
662
+ if (tab.page === page)
663
+ return;
664
+ // A session whose saved tabs are still being reopened takes extension pages only once they are all back.
665
+ const members = [...this.sessions].filter(([id, session]) => session.profileKey === key && !session.closing && !this.restoring.has(id));
666
+ const [owner] = members.filter(([, session]) => session.streaming).concat(members);
667
+ if (!owner) {
668
+ const host = this.profiles.get(key);
669
+ if (host)
670
+ (host.unclaimed ??= []).push(page);
671
+ else
672
+ await Promise.resolve().then(() => page.close()).catch(() => { });
673
+ return;
674
+ }
675
+ this.claimedPages.add(page);
676
+ await this.adoptPage(owner[0], owner[1], page);
677
+ }
678
+ claimUnclaimed(sessionId, session) {
679
+ // Saved tabs come first: a session being restored claims extension pages after its last tab is back.
680
+ if (this.restoring.has(sessionId))
681
+ return;
682
+ const host = session.profileKey === undefined ? undefined : this.profiles.get(session.profileKey);
683
+ const pages = host?.unclaimed?.splice(0) ?? [];
684
+ for (const page of pages) {
685
+ if (page.isClosed?.() === true)
686
+ continue;
687
+ this.claimedPages.add(page);
688
+ void this.adoptPage(sessionId, session, page);
689
+ }
690
+ }
586
691
  async releaseProfile(key, owner) {
587
692
  const host = this.profiles.get(key);
588
693
  if (!host)
@@ -601,10 +706,6 @@ export class BrowserViewManager {
601
706
  })();
602
707
  await host.closing;
603
708
  }
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
709
  async openBrowserFor(sessionId, viewport, scale) {
609
710
  if (!this.incognito.has(sessionId)) {
610
711
  const profile = this.options.profileFor ? await this.options.profileFor(sessionId).catch(() => undefined) : undefined;
@@ -617,18 +718,13 @@ export class BrowserViewManager {
617
718
  catch (error) {
618
719
  if (this.closed)
619
720
  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
721
  }
623
722
  }
624
723
  }
625
724
  return { browser: await this.launch(scale), profile: this.incognito.has(sessionId) ? 'incognito' : 'isolated', renderScale: scale };
626
725
  }
627
- /** Close a session's browser, or only its pages when they live in a shared project profile. */
628
726
  async disposeBrowser(session) {
629
727
  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
728
  await Promise.resolve().then(() => session.browser?.close()).catch(() => { });
633
729
  return;
634
730
  }
@@ -643,26 +739,12 @@ export class BrowserViewManager {
643
739
  };
644
740
  }
645
741
  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
742
  if (session.closing || this.sessions.get(sessionId) !== session)
650
743
  return;
651
744
  this.emit('browser.view', { kind: 'tabs', sessionId, ...this.summary(session) });
652
745
  }
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
746
  hold(sessionId, ms) {
663
747
  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
748
  for (const [id, until] of this.holds)
667
749
  if (until + VIEW_IDLE_CLOSE_MS <= now)
668
750
  this.holds.delete(id);
@@ -672,14 +754,8 @@ export class BrowserViewManager {
672
754
  scheduleIdleClose(sessionId, session, delay = VIEW_IDLE_CLOSE_MS) {
673
755
  if (session.idleTimer)
674
756
  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
757
  session.idleTimer = setTimeout(() => {
678
758
  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
759
  const until = this.holds.get(sessionId);
684
760
  if (until !== undefined) {
685
761
  const remaining = until + VIEW_IDLE_CLOSE_MS - Date.now();
@@ -689,7 +765,6 @@ export class BrowserViewManager {
689
765
  }
690
766
  this.holds.delete(sessionId);
691
767
  }
692
- // A tab still being created is work in progress, not idleness.
693
768
  if (!session.streaming && session.pendingTabs === 0)
694
769
  void this.closeSession(sessionId, 'idle', session);
695
770
  }, delay);
@@ -705,56 +780,20 @@ export class BrowserViewManager {
705
780
  try {
706
781
  await tab.cdp?.send('Page.stopScreencast');
707
782
  }
708
- catch { /* The page is already gone. */ }
783
+ catch { }
709
784
  }
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
785
  async showTab(session, tab) {
720
786
  if (session.activeTabId !== tab.id)
721
787
  return;
722
788
  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
789
  if (session.activeTabId !== tab.id)
728
790
  return;
729
791
  await this.startScreencast(session, tab);
730
792
  }
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
793
  async applyViewportMode(session, tab) {
750
794
  const mobile = session.mode === 'mobile';
751
795
  try {
752
796
  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
797
  await tab.cdp.send('Emulation.setDeviceMetricsOverride', {
759
798
  width: VIEW_MOBILE_VIEWPORT.width, height: VIEW_MOBILE_VIEWPORT.height, deviceScaleFactor: VIEW_MOBILE_SCALE, mobile: true,
760
799
  });
@@ -763,13 +802,6 @@ export class BrowserViewManager {
763
802
  if (tab.emulated)
764
803
  await tab.cdp.send('Emulation.clearDeviceMetricsOverride');
765
804
  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
805
  await tab.cdp.send('Emulation.setDeviceMetricsOverride', {
774
806
  width: session.viewport.width, height: session.viewport.height, deviceScaleFactor: session.renderScale, mobile: false,
775
807
  });
@@ -779,21 +811,17 @@ export class BrowserViewManager {
779
811
  tab.emulated = mobile;
780
812
  await tab.cdp.send('Emulation.setUserAgentOverride', mobile
781
813
  ? { 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
814
  : desktopUaOverride());
785
815
  await tab.cdp.send('Emulation.setTouchEmulationEnabled', { enabled: mobile, ...(mobile ? { maxTouchPoints: 5 } : {}) });
786
816
  }
787
- catch { /* The page is gone; the next activation retries. */ }
817
+ catch { }
788
818
  }
789
- /** The per-tab serialization `applyViewportMode` relies on; see its note. */
790
819
  queueViewportMode(session, tab) {
791
820
  const tail = (tab.modeTask ?? Promise.resolve()).catch(() => { });
792
821
  tab.modeTask = tail.then(() => this.applyViewportMode(session, tab));
793
822
  return tab.modeTask;
794
823
  }
795
824
  emitFrame(sessionId, session, tab, payload) {
796
- // Frames still in flight from a replaced browser belong to nobody.
797
825
  if (session.closing || this.sessions.get(sessionId) !== session)
798
826
  return;
799
827
  if (payload.data.length > VIEW_FRAME_LIMIT) {
@@ -822,11 +850,6 @@ export class BrowserViewManager {
822
850
  try {
823
851
  await tab.cdp.send('Page.startScreencast', {
824
852
  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
853
  maxWidth: Math.ceil(session.viewport.width * session.scale * budget.size),
831
854
  maxHeight: Math.ceil(session.viewport.height * session.scale * budget.size),
832
855
  everyNthFrame: 1,
@@ -836,11 +859,6 @@ export class BrowserViewManager {
836
859
  tab.streaming = false;
837
860
  }
838
861
  }
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
862
  async shrinkStream(session, tab) {
845
863
  if (tab.shrinking || !tab.streaming)
846
864
  return;
@@ -850,7 +868,6 @@ export class BrowserViewManager {
850
868
  tab.budget = next;
851
869
  await this.restartStream(session, tab);
852
870
  }
853
- /** Stop and start one tab's stream, keeping it only while it still owns the pane. */
854
871
  async restartStream(session, tab) {
855
872
  if (tab.shrinking)
856
873
  return;
@@ -870,18 +887,13 @@ export class BrowserViewManager {
870
887
  streaming: false, seq: 0, lastEmitAt: undefined, imageWidth: session.viewport.width, imageHeight: session.viewport.height,
871
888
  };
872
889
  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
890
  let documentRequest;
879
891
  page.on('request', (request) => {
880
892
  try {
881
893
  if (request?.isNavigationRequest?.() === true && request.frame?.() === page.mainFrame())
882
894
  documentRequest = request;
883
895
  }
884
- catch { /* A request with no frame is not the document's own. */ }
896
+ catch { }
885
897
  });
886
898
  page.on('requestfailed', (request) => { if (request === documentRequest)
887
899
  documentRequest = undefined; });
@@ -894,8 +906,6 @@ export class BrowserViewManager {
894
906
  if (newDocument) {
895
907
  tab.loading = true;
896
908
  tab.title = '';
897
- // The budget was earned by the previous document's content; the next
898
- // page gets full quality and size again.
899
909
  if (tab.budget) {
900
910
  tab.budget = undefined;
901
911
  if (tab.streaming)
@@ -922,27 +932,18 @@ export class BrowserViewManager {
922
932
  if (next)
923
933
  void this.showTab(session, next);
924
934
  }
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
935
  if (session.tabs.size === 0 && session.pendingTabs === 0)
928
936
  void this.closeSession(sessionId, undefined, session);
929
937
  else
930
938
  publish();
931
939
  });
932
940
  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); });
941
+ page.on('popup', (popup) => { this.claimedPages.add(popup); void this.adoptPage(sessionId, session, popup); });
938
942
  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
943
  try {
943
944
  await cdp.send('Page.screencastFrameAck', { sessionId: payload.sessionId });
944
945
  }
945
- catch { /* Gone. */ }
946
+ catch { }
946
947
  if (!tab.streaming || session.activeTabId !== tab.id || session.closing)
947
948
  return;
948
949
  const now = Date.now();
@@ -955,9 +956,6 @@ export class BrowserViewManager {
955
956
  this.emitFrame(sessionId, session, tab, payload);
956
957
  return;
957
958
  }
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
959
  tab.pendingFrame = payload;
962
960
  if (tab.pendingTimer)
963
961
  return;
@@ -975,14 +973,6 @@ export class BrowserViewManager {
975
973
  session.tabs.set(tab.id, tab);
976
974
  return tab;
977
975
  }
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
976
  async captureFrame(sessionId, session, tab) {
987
977
  try {
988
978
  const shot = await tab.cdp?.send('Page.captureScreenshot', { format: 'jpeg', quality: session.quality });
@@ -992,15 +982,8 @@ export class BrowserViewManager {
992
982
  return;
993
983
  this.emitFrame(sessionId, session, tab, { data: shot.data, sessionId: 'capture' });
994
984
  }
995
- catch { /* The page may be mid-navigation; the stream supplies the next frame. */ }
985
+ catch { }
996
986
  }
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
987
  async adoptPage(sessionId, session, page) {
1005
988
  if (session.closing) {
1006
989
  await Promise.resolve().then(() => page.close()).catch(() => { });
@@ -1016,12 +999,6 @@ export class BrowserViewManager {
1016
999
  const previous = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1017
1000
  if (previous)
1018
1001
  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
1002
  let selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1026
1003
  while (selected && selected.streaming) {
1027
1004
  await this.stopScreencast(selected);
@@ -1033,9 +1010,6 @@ export class BrowserViewManager {
1033
1010
  }
1034
1011
  const tab = this.wireTab(sessionId, session, page, cdp);
1035
1012
  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
1013
  selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1040
1014
  while (selected && selected.streaming) {
1041
1015
  await this.stopScreencast(selected);
@@ -1046,8 +1020,6 @@ export class BrowserViewManager {
1046
1020
  return;
1047
1021
  }
1048
1022
  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
1023
  tab.url = String(page.url?.() ?? '').slice(0, VIEW_URL_LIMIT);
1052
1024
  void page.title?.().then((title) => {
1053
1025
  if (typeof title === 'string' && title) {
@@ -1071,9 +1043,6 @@ export class BrowserViewManager {
1071
1043
  this.scheduleIdleClose(sessionId, existing);
1072
1044
  return existing;
1073
1045
  }
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
1046
  const inflight = this.launching.get(sessionId);
1078
1047
  if (inflight)
1079
1048
  return await inflight;
@@ -1085,23 +1054,14 @@ export class BrowserViewManager {
1085
1054
  const desired = this.desired.get(sessionId);
1086
1055
  const viewport = desired?.viewport ?? clampViewport(undefined, undefined);
1087
1056
  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
1057
  if (this.closed) {
1092
1058
  await this.disposeBrowser({ ...opened, tabs: new Map() });
1093
1059
  throw new Error('Application is shutting down');
1094
1060
  }
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
1061
  if (this.released.delete(sessionId)) {
1099
1062
  await this.disposeBrowser({ ...opened, tabs: new Map() });
1100
1063
  throw new Error('That session was deleted.');
1101
1064
  }
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
1065
  const current = this.desired.get(sessionId);
1106
1066
  const session = {
1107
1067
  ...opened, tabs: new Map(), activeTabId: undefined, pendingTabs: 0,
@@ -1112,6 +1072,7 @@ export class BrowserViewManager {
1112
1072
  };
1113
1073
  this.sessions.set(sessionId, session);
1114
1074
  this.scheduleIdleClose(sessionId, session);
1075
+ this.claimUnclaimed(sessionId, session);
1115
1076
  return session;
1116
1077
  })();
1117
1078
  this.launching.set(sessionId, starting);
@@ -1122,14 +1083,6 @@ export class BrowserViewManager {
1122
1083
  this.launching.delete(sessionId);
1123
1084
  }
1124
1085
  }
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
1086
  async contextFor(session) {
1134
1087
  if (session.context)
1135
1088
  return session.context;
@@ -1141,24 +1094,14 @@ export class BrowserViewManager {
1141
1094
  async openTab(sessionId, url, signal) {
1142
1095
  return await this.openPage(sessionId, browserViewUrl(url), signal);
1143
1096
  }
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
1097
  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
1098
  while (this.launching.has(sessionId))
1155
1099
  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
1100
  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.
1101
+ // An extension restart about to reopen this session's project tabs leaves the switch alone.
1102
+ const restoring = this.restoring.get(sessionId);
1103
+ if (restoring)
1104
+ restoring.abandoned = true;
1162
1105
  const closing = this.closeSession(sessionId, 'incognito');
1163
1106
  this.incognito.add(sessionId);
1164
1107
  await closing;
@@ -1167,10 +1110,6 @@ export class BrowserViewManager {
1167
1110
  return await this.openPage(sessionId, 'about:blank', signal, 'incognito');
1168
1111
  }
1169
1112
  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
1113
  const session = this.sessions.get(sessionId);
1175
1114
  if (!session)
1176
1115
  this.incognito.delete(sessionId);
@@ -1179,12 +1118,9 @@ export class BrowserViewManager {
1179
1118
  throw error;
1180
1119
  }
1181
1120
  }
1182
- /** Close the session's incognito browser, if it has one; the next open uses the project profile. */
1183
1121
  async endIncognito(sessionId, signal) {
1184
1122
  while (this.launching.has(sessionId))
1185
1123
  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
1124
  signal?.throwIfAborted();
1189
1125
  const session = this.sessions.get(sessionId);
1190
1126
  const active = this.incognito.delete(sessionId) || session?.profile === 'incognito';
@@ -1192,14 +1128,6 @@ export class BrowserViewManager {
1192
1128
  await this.closeSession(sessionId, 'incognito ended');
1193
1129
  return active;
1194
1130
  }
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
1131
  async importCookies(sessionId, cookies) {
1204
1132
  const session = this.sessions.get(sessionId);
1205
1133
  if (!session || session.closing || session.tabs.size === 0)
@@ -1210,28 +1138,18 @@ export class BrowserViewManager {
1210
1138
  throw new Error('This browser is temporary, so imported cookies would not be kept');
1211
1139
  this.scheduleIdleClose(sessionId, session);
1212
1140
  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
1141
  await this.go(sessionId, 'refresh').catch(() => { });
1216
1142
  }
1217
- /** The kind of browser the session's pages live in now, or would on the next open. */
1218
1143
  profileKind(sessionId) {
1219
1144
  return this.sessions.get(sessionId)?.profile ?? (this.incognito.has(sessionId) ? 'incognito' : undefined);
1220
1145
  }
1221
1146
  async openPage(sessionId, target, signal, requireProfile) {
1222
1147
  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
1148
  signal?.throwIfAborted();
1226
- // A switch to incognito must never report success on the signed-in profile.
1227
1149
  if (requireProfile !== undefined && session.profile !== requireProfile)
1228
1150
  throw new Error(`The panel browser is not ${requireProfile}; retry the switch`);
1229
1151
  if (session.closing)
1230
1152
  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
1153
  if (session.tabs.size + session.pendingTabs >= VIEW_TAB_LIMIT)
1236
1154
  throw new Error('Close a tab before opening another (maximum 6)');
1237
1155
  session.pendingTabs += 1;
@@ -1248,84 +1166,43 @@ export class BrowserViewManager {
1248
1166
  await this.stopScreencast(previous);
1249
1167
  const context = await this.contextFor(session);
1250
1168
  const page = await context.newPage();
1169
+ this.claimedPages.add(page);
1251
1170
  const cdp = await Promise.resolve().then(() => page.context().newCDPSession(page)).catch(async (error) => {
1252
1171
  await Promise.resolve().then(() => page.close()).catch(() => { });
1253
1172
  throw error;
1254
1173
  });
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
1174
  if (session.closing) {
1261
1175
  await Promise.resolve().then(() => cdp.detach?.()).catch(() => { });
1262
1176
  await Promise.resolve().then(() => page.close()).catch(() => { });
1263
1177
  throw new Error('Browser is closing; retry shortly');
1264
1178
  }
1265
1179
  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
1180
  await this.queueViewportMode(session, tab);
1271
- // The reservation has become a real tab; the cap now counts it directly.
1272
1181
  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
1182
  let selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1281
1183
  while (selected && selected.id !== tab.id && selected.streaming) {
1282
1184
  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
1185
  selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1286
1186
  }
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
1187
  if (signal?.aborted) {
1292
1188
  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
1189
  const survivor = session.activeTabId === undefined ? undefined : session.tabs.get(session.activeTabId);
1298
1190
  if (survivor && !survivor.streaming)
1299
1191
  await this.showTab(session, survivor);
1300
1192
  signal.throwIfAborted();
1301
1193
  }
1302
1194
  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
1195
  this.publishTabs(sessionId, session);
1307
1196
  try {
1308
1197
  await page.goto(target, { waitUntil: 'domcontentloaded', timeout: VIEW_GOTO_TIMEOUT_MS });
1309
1198
  }
1310
1199
  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
1200
  await this.discardTab(sessionId, session, tab, previous);
1314
1201
  throw error;
1315
1202
  }
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
1203
  if (session.activeTabId === tab.id)
1323
1204
  await this.showTab(session, tab);
1324
1205
  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
1206
  if (!session.closing)
1330
1207
  this.emit('browser.panel.opened', { sessionId });
1331
1208
  return { tabId: tab.id };
@@ -1334,21 +1211,8 @@ export class BrowserViewManager {
1334
1211
  release();
1335
1212
  }
1336
1213
  }
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
1214
  async discardTab(sessionId, session, tab, previous) {
1346
1215
  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
1216
  if (session.activeTabId === tab.id) {
1353
1217
  const fallback = previous && session.tabs.has(previous.id) ? previous : [...session.tabs.values()][0];
1354
1218
  session.activeTabId = fallback?.id;
@@ -1357,13 +1221,10 @@ export class BrowserViewManager {
1357
1221
  }
1358
1222
  await tab.cdp?.detach().catch(() => { });
1359
1223
  await tab.page.close().catch(() => { });
1360
- // Another open may still be creating its page: the session is not empty.
1361
1224
  if (session.tabs.size === 0 && session.pendingTabs === 0)
1362
1225
  void this.closeSession(sessionId, undefined, session);
1363
1226
  }
1364
1227
  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
1228
  if (tabId !== undefined) {
1368
1229
  const named = session.tabs.get(tabId);
1369
1230
  if (!named)
@@ -1383,10 +1244,7 @@ export class BrowserViewManager {
1383
1244
  const tab = this.activeOrNamed(session, tabId);
1384
1245
  this.scheduleIdleClose(sessionId, session);
1385
1246
  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
1247
  this.publishTabs(sessionId, session);
1389
- // A navigation is new content in the pane: the same pop-up an open gets.
1390
1248
  if (!session.closing)
1391
1249
  this.emit('browser.panel.opened', { sessionId });
1392
1250
  }
@@ -1397,18 +1255,11 @@ export class BrowserViewManager {
1397
1255
  const previous = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1398
1256
  if (previous && previous.id !== tabId)
1399
1257
  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
1258
  let holding = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1405
1259
  while (holding && holding.streaming && holding.id !== tabId) {
1406
1260
  await this.stopScreencast(holding);
1407
1261
  holding = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1408
1262
  }
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
1263
  if (!session.tabs.has(tabId)) {
1413
1264
  const survivor = previous && session.tabs.has(previous.id) ? previous : [...session.tabs.values()][0];
1414
1265
  session.activeTabId = survivor?.id;
@@ -1419,9 +1270,6 @@ export class BrowserViewManager {
1419
1270
  }
1420
1271
  session.activeTabId = tabId;
1421
1272
  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
1273
  await this.showTab(session, tab);
1426
1274
  this.scheduleIdleClose(sessionId, session);
1427
1275
  this.publishTabs(sessionId, session);
@@ -1434,15 +1282,6 @@ export class BrowserViewManager {
1434
1282
  await this.stopScreencast(tab);
1435
1283
  await tab.page.close().catch(() => { });
1436
1284
  }
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
1285
  async configureStream(sessionId, options) {
1447
1286
  if (!options.enabled) {
1448
1287
  this.desired.delete(sessionId);
@@ -1451,8 +1290,6 @@ export class BrowserViewManager {
1451
1290
  return;
1452
1291
  session.streaming = false;
1453
1292
  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
1293
  if (session.streaming)
1457
1294
  return;
1458
1295
  await this.stopScreencast(tab);
@@ -1464,8 +1301,6 @@ export class BrowserViewManager {
1464
1301
  const viewport = mode === 'mobile' ? { ...VIEW_MOBILE_VIEWPORT } : clampViewport(options.viewportWidth, options.viewportHeight);
1465
1302
  const quality = Number.isSafeInteger(options.quality) ? Math.max(30, Math.min(90, options.quality)) : VIEW_STREAM_QUALITY;
1466
1303
  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
1304
  if (options.scale !== undefined)
1470
1305
  this.displayScale = scale;
1471
1306
  this.desired.set(sessionId, { viewport, quality, mode, scale });
@@ -1474,9 +1309,6 @@ export class BrowserViewManager {
1474
1309
  return;
1475
1310
  session.streaming = true;
1476
1311
  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
1312
  const resized = viewport.width !== session.viewport.width || viewport.height !== session.viewport.height
1481
1313
  || scale !== session.scale;
1482
1314
  session.mode = mode;
@@ -1488,14 +1320,8 @@ export class BrowserViewManager {
1488
1320
  if (!active)
1489
1321
  return;
1490
1322
  if (resized || modeChanged) {
1491
- // A new geometry changes every frame's size; the reduced budget belonged to the old one.
1492
1323
  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
1324
  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
1325
  if (session.activeTabId !== active.id) {
1500
1326
  await this.stopScreencast(active);
1501
1327
  const selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
@@ -1503,15 +1329,7 @@ export class BrowserViewManager {
1503
1329
  await this.showTab(session, selected);
1504
1330
  return;
1505
1331
  }
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
1332
  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
1333
  if (session.activeTabId !== active.id) {
1516
1334
  const selected = session.activeTabId ? session.tabs.get(session.activeTabId) : undefined;
1517
1335
  if (selected)
@@ -1521,16 +1339,9 @@ export class BrowserViewManager {
1521
1339
  }
1522
1340
  const reattached = active.streaming;
1523
1341
  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
1342
  if (reattached)
1528
1343
  await this.captureFrame(sessionId, session, active);
1529
1344
  }
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
1345
  async input(sessionId, payload) {
1535
1346
  const session = this.sessions.get(sessionId);
1536
1347
  if (!session)
@@ -1554,8 +1365,6 @@ export class BrowserViewManager {
1554
1365
  const type = payload.type;
1555
1366
  if (type === 'move') {
1556
1367
  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
1368
  const pressed = payload.pressed === true;
1560
1369
  const name = pressed ? button(payload.button) : 'none';
1561
1370
  const buttons = pressed ? (name === 'right' ? 2 : name === 'middle' ? 4 : 1) : 0;
@@ -1586,11 +1395,7 @@ export class BrowserViewManager {
1586
1395
  else if (type === 'key') {
1587
1396
  const down = payload.down === true;
1588
1397
  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
1398
  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
1399
  const commands = process.platform === 'darwin' && down ? macEditingCommands(descriptor.key, modifiers) : [];
1595
1400
  await tab.cdp.send('Input.dispatchKeyEvent', {
1596
1401
  type: down ? (text === undefined ? 'rawKeyDown' : 'keyDown') : 'keyUp',
@@ -1610,13 +1415,6 @@ export class BrowserViewManager {
1610
1415
  throw new Error('Unsupported browser input type');
1611
1416
  }
1612
1417
  }
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
1418
  async cursorAt(sessionId, x, y, tabId) {
1621
1419
  const session = this.sessions.get(sessionId);
1622
1420
  if (!session)
@@ -1625,7 +1423,6 @@ export class BrowserViewManager {
1625
1423
  this.scheduleIdleClose(sessionId, session);
1626
1424
  const px = Number(x);
1627
1425
  const py = Number(y);
1628
- // A point outside the frame the pane is showing names nothing in the page.
1629
1426
  if (!Number.isSafeInteger(px) || !Number.isSafeInteger(py) || px < 0 || py < 0 || px > tab.imageWidth || py > tab.imageHeight)
1630
1427
  return 'default';
1631
1428
  const scaleX = tab.imageWidth / Math.max(1, session.viewport.width);
@@ -1634,15 +1431,6 @@ export class BrowserViewManager {
1634
1431
  .catch(() => 'default');
1635
1432
  return typeof cursor === 'string' && /^[a-z-]{1,40}$/.test(cursor) ? cursor : 'default';
1636
1433
  }
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
1434
  async selectionText(sessionId, tabId) {
1647
1435
  const session = this.sessions.get(sessionId);
1648
1436
  if (!session)
@@ -1650,29 +1438,16 @@ export class BrowserViewManager {
1650
1438
  const tab = this.activeOrNamed(session, tabId);
1651
1439
  this.scheduleIdleClose(sessionId, session);
1652
1440
  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
1441
  if (typeof text !== 'string')
1657
1442
  return '';
1658
1443
  if (text.length > VIEW_CLIPBOARD_LIMIT)
1659
1444
  throw new Error(`The selection is too large to copy (${text.length} characters)`);
1660
1445
  return text;
1661
1446
  }
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
1447
  async selectionInPage(page) {
1672
1448
  const top = await page.evaluate(SELECTION_STATE).catch(() => undefined);
1673
1449
  if (typeof top?.text === 'string' && top.text)
1674
1450
  return top.text;
1675
- // The top document answered "no selection and focus is mine": no frame holds it.
1676
1451
  if (top?.inFrame === false)
1677
1452
  return '';
1678
1453
  let frames = [];
@@ -1683,10 +1458,6 @@ export class BrowserViewManager {
1683
1458
  catch {
1684
1459
  return '';
1685
1460
  }
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
1461
  let fallback = '';
1691
1462
  let focusedAnswered = false;
1692
1463
  for (const frame of frames) {
@@ -1701,16 +1472,8 @@ export class BrowserViewManager {
1701
1472
  if (!fallback && text)
1702
1473
  fallback = text;
1703
1474
  }
1704
- // The focus is deeper than the frames readable here: their stale text is not it.
1705
1475
  return focusedAnswered ? '' : fallback;
1706
1476
  }
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
1477
  async boundedAgentOperation(signal, pending, timeoutMessage) {
1715
1478
  return await new Promise((resolve, reject) => {
1716
1479
  let settled = false;
@@ -1736,11 +1499,9 @@ export class BrowserViewManager {
1736
1499
  this.scheduleIdleClose(sessionId, session);
1737
1500
  return { session, tab: this.activeOrNamed(session, tabId) };
1738
1501
  }
1739
- /** The session's tabs as the agent sees them; a panel with no browser yet is simply empty. */
1740
1502
  agentTabs(sessionId) {
1741
1503
  return this.sessionSummaries()[sessionId] ?? { tabs: [] };
1742
1504
  }
1743
- /** Step a tab through its history or reload it, for the agent and the panel's toolbar alike. */
1744
1505
  async go(sessionId, kind, tabId) {
1745
1506
  const { session, tab } = this.agentTarget(sessionId, tabId);
1746
1507
  if (kind === 'back')
@@ -1767,9 +1528,6 @@ export class BrowserViewManager {
1767
1528
  }
1768
1529
  async agentPress(sessionId, options, signal) {
1769
1530
  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
1531
  let callerGone = false;
1774
1532
  const sequence = (async () => {
1775
1533
  if (options.selector)
@@ -1795,11 +1553,6 @@ export class BrowserViewManager {
1795
1553
  }
1796
1554
  async agentScreenshot(sessionId, tabId, signal) {
1797
1555
  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
1556
  const ratio = tab.emulated ? VIEW_MOBILE_SCALE : session.renderScale;
1804
1557
  const capture = (async () => {
1805
1558
  const metrics = await tab.cdp.send('Page.getLayoutMetrics').catch(() => undefined);
@@ -1807,10 +1560,6 @@ export class BrowserViewManager {
1807
1560
  const clip = visual && Number.isFinite(visual.clientWidth) && visual.clientWidth > 0
1808
1561
  ? { x: visual.pageX, y: visual.pageY, width: visual.clientWidth, height: visual.clientHeight }
1809
1562
  : { 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
1563
  const zoom = visual && Number.isFinite(visual.scale) && visual.scale > 0 ? visual.scale : 1;
1815
1564
  const shot = await tab.cdp.send('Page.captureScreenshot', { format: 'jpeg', quality: 60, clip: { ...clip, scale: zoom / ratio } });
1816
1565
  if (typeof shot?.data !== 'string')
@@ -1824,12 +1573,8 @@ export class BrowserViewManager {
1824
1573
  const session = this.sessions.get(sessionId);
1825
1574
  if (!session || session.closing)
1826
1575
  return;
1827
- // A teardown that started for an older generation must not close the
1828
- // replacement that took its id in the meantime.
1829
1576
  if (expected !== undefined && session !== expected)
1830
1577
  return;
1831
- // Incognito lasts exactly as long as its browser: once it closes, the next
1832
- // open returns to the project profile.
1833
1578
  if (session.profile === 'incognito')
1834
1579
  this.incognito.delete(sessionId);
1835
1580
  session.closing = (async () => {
@@ -1837,11 +1582,7 @@ export class BrowserViewManager {
1837
1582
  if (session.idleTimer)
1838
1583
  clearTimeout(session.idleTimer);
1839
1584
  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
1585
  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
1586
  if (this.sessions.has(sessionId))
1846
1587
  return;
1847
1588
  this.emit('browser.view', { kind: 'gone', sessionId, ...(reason ? { reason } : {}) });
@@ -1855,16 +1596,29 @@ export class BrowserViewManager {
1855
1596
  return result;
1856
1597
  }
1857
1598
  /**
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.
1599
+ * Close the panel browsers of sessions whose project identity just changed. A profile is chosen once, when the
1600
+ * browser is created, so a task merged into another project would keep browsing on the cookies and logins of the
1601
+ * folder it left. Closing it here costs the open tabs of that one task; the next use opens it on the surviving
1602
+ * project's profile.
1863
1603
  */
1604
+ async rekeyProfiles(sessionIds) {
1605
+ const ids = [...sessionIds];
1606
+ if (ids.length === 0)
1607
+ return;
1608
+ await Promise.all(ids.map(async (id) => await this.launching.get(id)?.catch(() => { })));
1609
+ for (const id of ids) {
1610
+ // An incognito panel browser carries no project state, so there is nothing stale about leaving it open.
1611
+ const session = this.sessions.get(id);
1612
+ if (session === undefined || session.profile === 'incognito')
1613
+ continue;
1614
+ await this.closeSession(id, 'project changed');
1615
+ }
1616
+ }
1864
1617
  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
1618
  this.released.add(sessionId);
1619
+ const restoring = this.restoring.get(sessionId);
1620
+ if (restoring)
1621
+ restoring.cancelled = true;
1868
1622
  this.incognito.delete(sessionId);
1869
1623
  try {
1870
1624
  await this.closeSession(sessionId, reason);
@@ -1874,27 +1628,25 @@ export class BrowserViewManager {
1874
1628
  this.released.delete(sessionId);
1875
1629
  }
1876
1630
  }
1877
- /** Engine shutdown: no panel browser outlives the process. */
1878
1631
  async close() {
1879
1632
  if (this.closed)
1880
1633
  return;
1881
1634
  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.
1635
+ if (this.restartPoll) {
1636
+ clearTimeout(this.restartPoll);
1637
+ this.restartPoll = undefined;
1638
+ }
1639
+ this.pendingRestart.clear();
1885
1640
  if (this.installer) {
1886
1641
  const { child, finish } = this.installer;
1887
1642
  try {
1888
1643
  child.kill();
1889
1644
  }
1890
- catch { /* Already gone. */ }
1645
+ catch { }
1891
1646
  const stopped = { state: 'failed', detail: 'Application is shutting down' };
1892
1647
  this.publishRuntime(stopped);
1893
1648
  finish(stopped);
1894
1649
  }
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
1650
  const pending = [...this.launching.values()];
1899
1651
  if (pending.length) {
1900
1652
  await Promise.race([
@@ -1903,6 +1655,5 @@ export class BrowserViewManager {
1903
1655
  ]);
1904
1656
  }
1905
1657
  await Promise.all([...this.sessions.keys()].map(sessionId => this.closeSession(sessionId)));
1906
- // A launch that landed after the bound closed itself in `ensureSession`.
1907
1658
  }
1908
1659
  }