aicodeman 1.34.0 → 1.40.0

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 (299) hide show
  1. package/README.md +11 -0
  2. package/README.zh-CN.md +8 -0
  3. package/dist/attachment-registry.d.ts +6 -0
  4. package/dist/attachment-registry.d.ts.map +1 -1
  5. package/dist/attachment-registry.js +9 -3
  6. package/dist/attachment-registry.js.map +1 -1
  7. package/dist/cli.d.ts.map +1 -1
  8. package/dist/cli.js +2 -2
  9. package/dist/cli.js.map +1 -1
  10. package/dist/config/cli-registry/patterns.d.ts +6 -0
  11. package/dist/config/cli-registry/patterns.d.ts.map +1 -1
  12. package/dist/config/cli-registry/patterns.js +13 -0
  13. package/dist/config/cli-registry/patterns.js.map +1 -1
  14. package/dist/config/cli-registry/schema.d.ts +13 -0
  15. package/dist/config/cli-registry/schema.d.ts.map +1 -1
  16. package/dist/config/cli-registry/schema.js +60 -2
  17. package/dist/config/cli-registry/schema.js.map +1 -1
  18. package/dist/config/cli-registry/stock.d.ts.map +1 -1
  19. package/dist/config/cli-registry/stock.js +175 -7
  20. package/dist/config/cli-registry/stock.js.map +1 -1
  21. package/dist/config/cli-registry/types.d.ts +93 -6
  22. package/dist/config/cli-registry/types.d.ts.map +1 -1
  23. package/dist/config/dependency-registry.d.ts +7 -0
  24. package/dist/config/dependency-registry.d.ts.map +1 -1
  25. package/dist/config/dependency-registry.js +15 -0
  26. package/dist/config/dependency-registry.js.map +1 -1
  27. package/dist/config/path-probe.d.ts +37 -0
  28. package/dist/config/path-probe.d.ts.map +1 -0
  29. package/dist/config/path-probe.js +43 -0
  30. package/dist/config/path-probe.js.map +1 -0
  31. package/dist/deepseek-route-config.d.ts +110 -0
  32. package/dist/deepseek-route-config.d.ts.map +1 -0
  33. package/dist/deepseek-route-config.js +477 -0
  34. package/dist/deepseek-route-config.js.map +1 -0
  35. package/dist/git-workspace-status.d.ts +246 -0
  36. package/dist/git-workspace-status.d.ts.map +1 -0
  37. package/dist/git-workspace-status.js +626 -0
  38. package/dist/git-workspace-status.js.map +1 -0
  39. package/dist/hooks-config.d.ts.map +1 -1
  40. package/dist/hooks-config.js +83 -13
  41. package/dist/hooks-config.js.map +1 -1
  42. package/dist/model-config-resolvers.d.ts +29 -0
  43. package/dist/model-config-resolvers.d.ts.map +1 -0
  44. package/dist/model-config-resolvers.js +34 -0
  45. package/dist/model-config-resolvers.js.map +1 -0
  46. package/dist/session-display-model.d.ts +110 -0
  47. package/dist/session-display-model.d.ts.map +1 -0
  48. package/dist/session-display-model.js +154 -0
  49. package/dist/session-display-model.js.map +1 -0
  50. package/dist/session.d.ts +145 -8
  51. package/dist/session.d.ts.map +1 -1
  52. package/dist/session.js +280 -35
  53. package/dist/session.js.map +1 -1
  54. package/dist/types/api.d.ts +7 -0
  55. package/dist/types/api.d.ts.map +1 -1
  56. package/dist/types/api.js.map +1 -1
  57. package/dist/types/session.d.ts +28 -1
  58. package/dist/types/session.d.ts.map +1 -1
  59. package/dist/types/session.js.map +1 -1
  60. package/dist/types/tools.d.ts +1 -1
  61. package/dist/types/tools.d.ts.map +1 -1
  62. package/dist/utils/bounded-path-probe.d.ts +99 -0
  63. package/dist/utils/bounded-path-probe.d.ts.map +1 -0
  64. package/dist/utils/bounded-path-probe.js +228 -0
  65. package/dist/utils/bounded-path-probe.js.map +1 -0
  66. package/dist/utils/cli-executable-resolver.d.ts +2 -0
  67. package/dist/utils/cli-executable-resolver.d.ts.map +1 -1
  68. package/dist/utils/cli-executable-resolver.js +2 -1
  69. package/dist/utils/cli-executable-resolver.js.map +1 -1
  70. package/dist/utils/deepseek-cli-resolver.d.ts +8 -0
  71. package/dist/utils/deepseek-cli-resolver.d.ts.map +1 -1
  72. package/dist/utils/deepseek-cli-resolver.js +18 -2
  73. package/dist/utils/deepseek-cli-resolver.js.map +1 -1
  74. package/dist/utils/dependency-checker.d.ts +2 -0
  75. package/dist/utils/dependency-checker.d.ts.map +1 -1
  76. package/dist/utils/dependency-checker.js +37 -9
  77. package/dist/utils/dependency-checker.js.map +1 -1
  78. package/dist/utils/index.d.ts +2 -0
  79. package/dist/utils/index.d.ts.map +1 -1
  80. package/dist/utils/index.js +1 -0
  81. package/dist/utils/index.js.map +1 -1
  82. package/dist/web/case-path.d.ts +58 -0
  83. package/dist/web/case-path.d.ts.map +1 -0
  84. package/dist/web/case-path.js +182 -0
  85. package/dist/web/case-path.js.map +1 -0
  86. package/dist/web/launch-defaults.d.ts +22 -0
  87. package/dist/web/launch-defaults.d.ts.map +1 -0
  88. package/dist/web/launch-defaults.js +46 -0
  89. package/dist/web/launch-defaults.js.map +1 -0
  90. package/dist/web/public/admin-ui.js.gz +0 -0
  91. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  92. package/dist/web/public/app.abadc970.js +43 -0
  93. package/dist/web/public/app.abadc970.js.br +0 -0
  94. package/dist/web/public/app.abadc970.js.gz +0 -0
  95. package/dist/web/public/approvals-ui.js.gz +0 -0
  96. package/dist/web/public/{constants.d95fade9.js → constants.c0f8f9de.js} +1009 -127
  97. package/dist/web/public/constants.c0f8f9de.js.br +0 -0
  98. package/dist/web/public/constants.c0f8f9de.js.gz +0 -0
  99. package/dist/web/public/cron-ui.js.gz +0 -0
  100. package/dist/web/public/entrance-animations.js +1 -0
  101. package/dist/web/public/entrance-animations.js.br +0 -0
  102. package/dist/web/public/entrance-animations.js.gz +0 -0
  103. package/dist/web/public/git-status-ui.js +719 -0
  104. package/dist/web/public/git-status-ui.js.br +0 -0
  105. package/dist/web/public/git-status-ui.js.gz +0 -0
  106. package/dist/web/public/home-sessions.js +12 -9
  107. package/dist/web/public/home-sessions.js.br +0 -0
  108. package/dist/web/public/home-sessions.js.gz +0 -0
  109. package/dist/web/public/host-wake-ui.js.gz +0 -0
  110. package/dist/web/public/i18n.a31747a9.js +2 -0
  111. package/dist/web/public/i18n.a31747a9.js.br +0 -0
  112. package/dist/web/public/i18n.a31747a9.js.gz +0 -0
  113. package/dist/web/public/{image-input.a216cf9e.js → image-input.898a538b.js} +18 -8
  114. package/dist/web/public/image-input.898a538b.js.br +0 -0
  115. package/dist/web/public/image-input.898a538b.js.gz +0 -0
  116. package/dist/web/public/index.html +205 -42
  117. package/dist/web/public/index.html.br +0 -0
  118. package/dist/web/public/index.html.gz +0 -0
  119. package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
  120. package/dist/web/public/keyboard-accessory.c1e7c7b7.js.gz +0 -0
  121. package/dist/web/public/{mobile-handlers.23a85db1.js → mobile-handlers.0ef9c311.js} +20 -0
  122. package/dist/web/public/mobile-handlers.0ef9c311.js.br +0 -0
  123. package/dist/web/public/mobile-handlers.0ef9c311.js.gz +0 -0
  124. package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
  125. package/dist/web/public/mobile-overview.js.gz +0 -0
  126. package/dist/web/public/mobile.111b187d.css +1 -0
  127. package/dist/web/public/mobile.111b187d.css.br +0 -0
  128. package/dist/web/public/mobile.111b187d.css.gz +0 -0
  129. package/dist/web/public/notification-manager.50bb87d8.js.gz +0 -0
  130. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  131. package/dist/web/public/{panels-ui.6a5898d9.js → panels-ui.4735dfc2.js} +4 -4
  132. package/dist/web/public/panels-ui.4735dfc2.js.br +0 -0
  133. package/dist/web/public/{panels-ui.6a5898d9.js.gz → panels-ui.4735dfc2.js.gz} +0 -0
  134. package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
  135. package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
  136. package/dist/web/public/readmymind-ui.js.gz +0 -0
  137. package/dist/web/public/reboot-restore-ui.js.gz +0 -0
  138. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  139. package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
  140. package/dist/web/public/session-lineage.js +229 -86
  141. package/dist/web/public/session-lineage.js.br +0 -0
  142. package/dist/web/public/session-lineage.js.gz +0 -0
  143. package/dist/web/public/session-ui.f731602c.js +100 -0
  144. package/dist/web/public/session-ui.f731602c.js.br +0 -0
  145. package/dist/web/public/session-ui.f731602c.js.gz +0 -0
  146. package/dist/web/public/settings-ui.a97ab16f.js +97 -0
  147. package/dist/web/public/settings-ui.a97ab16f.js.br +0 -0
  148. package/dist/web/public/settings-ui.a97ab16f.js.gz +0 -0
  149. package/dist/web/public/spreadsheet-preview-worker.js +290 -0
  150. package/dist/web/public/spreadsheet-preview-worker.js.br +0 -0
  151. package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
  152. package/dist/web/public/spreadsheet-preview.af82fa2f.js +555 -0
  153. package/dist/web/public/spreadsheet-preview.af82fa2f.js.br +0 -0
  154. package/dist/web/public/spreadsheet-preview.af82fa2f.js.gz +0 -0
  155. package/dist/web/public/spreadsheet-xlsx-core.js +1006 -0
  156. package/dist/web/public/spreadsheet-xlsx-core.js.br +0 -0
  157. package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
  158. package/dist/web/public/styles.8ee12666.css +1 -0
  159. package/dist/web/public/styles.8ee12666.css.br +0 -0
  160. package/dist/web/public/styles.8ee12666.css.gz +0 -0
  161. package/dist/web/public/subagent-windows.e6ca799f.js.gz +0 -0
  162. package/dist/web/public/sw.js +2 -2
  163. package/dist/web/public/sw.js.br +0 -0
  164. package/dist/web/public/sw.js.gz +0 -0
  165. package/dist/web/public/tab-layout-browser.065fcba4.js +1 -0
  166. package/dist/web/public/tab-layout-browser.065fcba4.js.br +0 -0
  167. package/dist/web/public/tab-layout-browser.065fcba4.js.gz +0 -0
  168. package/dist/web/public/{tab-rail-resize.dcdc5772.js → tab-rail-resize.a5867793.js} +1 -1
  169. package/dist/web/public/tab-rail-resize.a5867793.js.br +0 -0
  170. package/dist/web/public/tab-rail-resize.a5867793.js.gz +0 -0
  171. package/dist/web/public/terminal-keycode229-recovery.af09f99a.js +1 -0
  172. package/dist/web/public/terminal-keycode229-recovery.af09f99a.js.br +0 -0
  173. package/dist/web/public/terminal-keycode229-recovery.af09f99a.js.gz +0 -0
  174. package/dist/web/public/terminal-split.js +146 -649
  175. package/dist/web/public/terminal-split.js.br +0 -0
  176. package/dist/web/public/terminal-split.js.gz +0 -0
  177. package/dist/web/public/terminal-tile.js +1611 -0
  178. package/dist/web/public/terminal-tile.js.br +0 -0
  179. package/dist/web/public/terminal-tile.js.gz +0 -0
  180. package/dist/web/public/terminal-ui.5059b30e.js +2 -0
  181. package/dist/web/public/terminal-ui.5059b30e.js.br +0 -0
  182. package/dist/web/public/terminal-ui.5059b30e.js.gz +0 -0
  183. package/dist/web/public/tile-grid.js +2684 -0
  184. package/dist/web/public/tile-grid.js.br +0 -0
  185. package/dist/web/public/tile-grid.js.gz +0 -0
  186. package/dist/web/public/ultracode-panel.js.gz +0 -0
  187. package/dist/web/public/ultracode-windows.js.gz +0 -0
  188. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  189. package/dist/web/public/vendor/exceljs.min.js +44 -0
  190. package/dist/web/public/vendor/exceljs.min.js.br +0 -0
  191. package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
  192. package/dist/web/public/vendor/fflate.min.js +1 -0
  193. package/dist/web/public/vendor/fflate.min.js.br +0 -0
  194. package/dist/web/public/vendor/fflate.min.js.gz +0 -0
  195. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  196. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  197. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  198. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  199. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  200. package/dist/web/public/vendor/xterm-predictive-echo.ae5e3d5d.js.gz +0 -0
  201. package/dist/web/public/vendor/xterm-zerolag-input.bbb5f84c.js.gz +0 -0
  202. package/dist/web/public/vendor/xterm.css.gz +0 -0
  203. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  204. package/dist/web/public/{voice-input.c4b51eb6.js → voice-input.2342c37b.js} +64 -10
  205. package/dist/web/public/voice-input.2342c37b.js.br +0 -0
  206. package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
  207. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  208. package/dist/web/public/webview-tabs.js +9 -1
  209. package/dist/web/public/webview-tabs.js.br +0 -0
  210. package/dist/web/public/webview-tabs.js.gz +0 -0
  211. package/dist/web/routes/case-routes.d.ts.map +1 -1
  212. package/dist/web/routes/case-routes.js +136 -18
  213. package/dist/web/routes/case-routes.js.map +1 -1
  214. package/dist/web/routes/cli-registry-routes.d.ts.map +1 -1
  215. package/dist/web/routes/cli-registry-routes.js +3 -1
  216. package/dist/web/routes/cli-registry-routes.js.map +1 -1
  217. package/dist/web/routes/doctor-routes.d.ts +23 -0
  218. package/dist/web/routes/doctor-routes.d.ts.map +1 -0
  219. package/dist/web/routes/doctor-routes.js +83 -0
  220. package/dist/web/routes/doctor-routes.js.map +1 -0
  221. package/dist/web/routes/file-routes.d.ts +7 -0
  222. package/dist/web/routes/file-routes.d.ts.map +1 -1
  223. package/dist/web/routes/file-routes.js +34 -4
  224. package/dist/web/routes/file-routes.js.map +1 -1
  225. package/dist/web/routes/git-status-routes.d.ts +16 -0
  226. package/dist/web/routes/git-status-routes.d.ts.map +1 -0
  227. package/dist/web/routes/git-status-routes.js +98 -0
  228. package/dist/web/routes/git-status-routes.js.map +1 -0
  229. package/dist/web/routes/index.d.ts +2 -0
  230. package/dist/web/routes/index.d.ts.map +1 -1
  231. package/dist/web/routes/index.js +2 -0
  232. package/dist/web/routes/index.js.map +1 -1
  233. package/dist/web/routes/session-routes.d.ts +18 -0
  234. package/dist/web/routes/session-routes.d.ts.map +1 -1
  235. package/dist/web/routes/session-routes.js +106 -42
  236. package/dist/web/routes/session-routes.js.map +1 -1
  237. package/dist/web/routes/status-telemetry-routes.d.ts +3 -0
  238. package/dist/web/routes/status-telemetry-routes.d.ts.map +1 -1
  239. package/dist/web/routes/status-telemetry-routes.js +12 -0
  240. package/dist/web/routes/status-telemetry-routes.js.map +1 -1
  241. package/dist/web/routes/system-routes.d.ts.map +1 -1
  242. package/dist/web/routes/system-routes.js +13 -0
  243. package/dist/web/routes/system-routes.js.map +1 -1
  244. package/dist/web/schemas.d.ts +28 -0
  245. package/dist/web/schemas.d.ts.map +1 -1
  246. package/dist/web/schemas.js +41 -0
  247. package/dist/web/schemas.js.map +1 -1
  248. package/dist/web/server.d.ts +5 -0
  249. package/dist/web/server.d.ts.map +1 -1
  250. package/dist/web/server.js +35 -12
  251. package/dist/web/server.js.map +1 -1
  252. package/dist/web/session-listener-wiring.d.ts +1 -0
  253. package/dist/web/session-listener-wiring.d.ts.map +1 -1
  254. package/dist/web/session-listener-wiring.js +11 -0
  255. package/dist/web/session-listener-wiring.js.map +1 -1
  256. package/package.json +3 -1
  257. package/scripts/postinstall.js +16 -0
  258. package/skills/codeman/reference/verbs.md +3 -0
  259. package/dist/web/public/app.cf0db8ce.js +0 -43
  260. package/dist/web/public/app.cf0db8ce.js.br +0 -0
  261. package/dist/web/public/app.cf0db8ce.js.gz +0 -0
  262. package/dist/web/public/constants.d95fade9.js.br +0 -0
  263. package/dist/web/public/constants.d95fade9.js.gz +0 -0
  264. package/dist/web/public/i18n.398b8331.js +0 -1
  265. package/dist/web/public/i18n.398b8331.js.br +0 -0
  266. package/dist/web/public/i18n.398b8331.js.gz +0 -0
  267. package/dist/web/public/image-input.a216cf9e.js.br +0 -0
  268. package/dist/web/public/image-input.a216cf9e.js.gz +0 -0
  269. package/dist/web/public/mobile-handlers.23a85db1.js.br +0 -0
  270. package/dist/web/public/mobile-handlers.23a85db1.js.gz +0 -0
  271. package/dist/web/public/mobile.1aa4952d.css +0 -1
  272. package/dist/web/public/mobile.1aa4952d.css.br +0 -0
  273. package/dist/web/public/mobile.1aa4952d.css.gz +0 -0
  274. package/dist/web/public/panels-ui.6a5898d9.js.br +0 -0
  275. package/dist/web/public/session-ui.bf66c13b.js +0 -89
  276. package/dist/web/public/session-ui.bf66c13b.js.br +0 -0
  277. package/dist/web/public/session-ui.bf66c13b.js.gz +0 -0
  278. package/dist/web/public/settings-ui.331d3b1d.js +0 -97
  279. package/dist/web/public/settings-ui.331d3b1d.js.br +0 -0
  280. package/dist/web/public/settings-ui.331d3b1d.js.gz +0 -0
  281. package/dist/web/public/styles.8c485d26.css +0 -1
  282. package/dist/web/public/styles.8c485d26.css.br +0 -0
  283. package/dist/web/public/styles.8c485d26.css.gz +0 -0
  284. package/dist/web/public/tab-layout-browser.4e0ed50c.js +0 -1
  285. package/dist/web/public/tab-layout-browser.4e0ed50c.js.br +0 -0
  286. package/dist/web/public/tab-layout-browser.4e0ed50c.js.gz +0 -0
  287. package/dist/web/public/tab-rail-resize.dcdc5772.js.br +0 -0
  288. package/dist/web/public/tab-rail-resize.dcdc5772.js.gz +0 -0
  289. package/dist/web/public/terminal-keycode229-recovery.fb91b25b.js +0 -1
  290. package/dist/web/public/terminal-keycode229-recovery.fb91b25b.js.br +0 -0
  291. package/dist/web/public/terminal-keycode229-recovery.fb91b25b.js.gz +0 -0
  292. package/dist/web/public/terminal-ui.a4535311.js +0 -2
  293. package/dist/web/public/terminal-ui.a4535311.js.br +0 -0
  294. package/dist/web/public/terminal-ui.a4535311.js.gz +0 -0
  295. package/dist/web/public/upload.html +0 -155
  296. package/dist/web/public/upload.html.br +0 -0
  297. package/dist/web/public/upload.html.gz +0 -0
  298. package/dist/web/public/voice-input.c4b51eb6.js.br +0 -0
  299. package/dist/web/public/voice-input.c4b51eb6.js.gz +0 -0
@@ -0,0 +1,1611 @@
1
+ // src/web/public/terminal-tile.js
2
+
3
+ /**
4
+ * @fileoverview TerminalTile: one independent live terminal pane bound to one
5
+ * session, with its own xterm instance and its own
6
+ * `/ws/sessions/:id/terminal` WebSocket. The split pane (terminal-split.js)
7
+ * uses one as its second pane ("Pane B"); the tile grid (tile-grid.js,
8
+ * docs/tile-grid-plan.md) uses one per tile, and feeds every capture they
9
+ * fetch through ONE TileLoadQueue (below), because each capture is a
10
+ * synchronous tmux call that blocks the server's event loop.
11
+ *
12
+ * Deliberately plainer than the primary pane (this.terminal/this._ws in
13
+ * terminal-ui.js): no local-echo overlay, no CJK IME textarea, no touch/mobile
14
+ * handlers (a swipe on a touch screen pages nothing), no keyboard accessory
15
+ * bar, and no SGR wheel forwarding to Claude's fullscreen renderer
16
+ * (docs/tile-grid-plan.md follow-up 4). Built for wide screens; see
17
+ * docs/split-pane-sessions-plan.md and docs/tile-grid-plan.md.
18
+ *
19
+ * What it does carry over from the primary pane, through the primary pane's
20
+ * own code aimed at THIS pane (its terminal, its session, never the active
21
+ * one):
22
+ * - Hollow-buffer paging (#555): a CLI that draws in place (opencode on the
23
+ * alternate screen, Claude's repaint mode) leaves the xterm no scrollback,
24
+ * so the wheel pages the CLI's own transcript with PageUp/PageDown
25
+ * (_maybePageCliTranscript) through the primary pane's gates, plus an
26
+ * overflow-row discount for this pane's capture-before-resize load
27
+ * (_localRows), and only while the viewport is on the live screen (a
28
+ * wheel-down from those overflow rows is xterm's, and brings it home).
29
+ * - The desktop click report: a plain left-click hand-encoded as SGR while
30
+ * the session's CLI has mouse tracking on (cliMouseTracking), for the modes
31
+ * whose mouse DECSETs the server strips (_installClickListener), sent
32
+ * ephemeral, like every mouse report from this pane (_onTerminalData).
33
+ * - The soft-keyboard controller (terminal-keycode229-recovery.js), one per
34
+ * pane, on this pane's own textarea and composition helper and sending to
35
+ * this pane's session (_createKeyCode229Recovery): it forwards an
36
+ * `insertText` xterm refused, settles a pending textarea edit at the next
37
+ * keydown ahead of that key (#441: the last character an Android keyboard
38
+ * commits in the same task as Enter), and replaces xterm's append-only
39
+ * keyCode-229 diff with an edit-based one (#541: autocorrect on space
40
+ * duplicated the line). Not a desktop-only concern: the grid and the split
41
+ * are gated on width alone (SPLIT_PANE_MIN_WIDTH, 1180 CSS px), which a wide
42
+ * Android tablet, or a large foldable unfolded in landscape, reaches.
43
+ *
44
+ * @dependency vendor/xterm.js, vendor/xterm-addon-fit.js
45
+ * @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE)
46
+ * @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/pageKeysForTravel, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_handleDesktopTerminalClick)
47
+ * @dependency terminal-keycode229-recovery.js (window.CodemanKeyCode229Recovery, optional: absent, xterm's own textarea handling stands)
48
+ * @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js
49
+ */
50
+
51
+ (function (global) {
52
+ // How long a load may hold this pane's live output while it reads a bounded
53
+ // body: a scroll-to-top history pull, or a refresh of a bounded window.
54
+ const HISTORY_PULL_TIMEOUT_MS = 10000;
55
+
56
+ // How much of a replay is queued in xterm at once: a 1 MiB load goes in one
57
+ // window, and xterm's write queue throws past 50 MB, which an unbounded
58
+ // `full=1` capture (up to the server's 32 MB) would otherwise come near.
59
+ const REPLAY_WINDOW_BYTES = 1024 * 1024;
60
+
61
+ /**
62
+ * Replays a capture into a pane's own xterm: TERMINAL_CHUNK_SIZE slices, all
63
+ * of a window queued at once. xterm 6 parses its write queue in 12 ms slices
64
+ * and yields between them, so a long scrollback never becomes a long task,
65
+ * and it is not held to one slice per animation frame either (that pacing
66
+ * took about a second per 1 MiB, with the grid's load queue waiting behind
67
+ * it). Queued up front, the capture also stays in one piece: live output
68
+ * written during the parse lands after it, not between two of its slices.
69
+ * Deliberately NOT the primary pane's chunkedTerminalWrite (terminal-ui.js):
70
+ * that one is wired into session-switch generation counters and the
71
+ * live-output gate this simpler, independently created/destroyed pane has no
72
+ * equivalent of.
73
+ *
74
+ * Resolves once xterm has parsed the last slice (a write's callback runs once
75
+ * everything queued before it is parsed), so _loadBuffer() below holds its
76
+ * single-flight flag across the whole replay. A disposed xterm never runs its
77
+ * callbacks, so `setCancel` hands the owner a function that settles the
78
+ * replay at once: destroy() calls it, or the pane's flag and the grid's load
79
+ * queue would wait forever.
80
+ */
81
+ function writeChunked(terminal, buffer, isDestroyed, setCancel) {
82
+ if (!buffer || !terminal) return Promise.resolve();
83
+ return new Promise((resolve) => {
84
+ let offset = 0;
85
+ let settled = false;
86
+ const settle = () => {
87
+ if (settled) return;
88
+ settled = true;
89
+ setCancel?.(null);
90
+ resolve();
91
+ };
92
+ const writeWindow = () => {
93
+ if (settled) return;
94
+ if (isDestroyed()) {
95
+ settle();
96
+ return;
97
+ }
98
+ const end = Math.min(buffer.length, offset + REPLAY_WINDOW_BYTES);
99
+ while (offset < end) {
100
+ const chunk = buffer.slice(offset, Math.min(end, offset + TERMINAL_CHUNK_SIZE));
101
+ offset += chunk.length;
102
+ terminal.write(chunk);
103
+ }
104
+ terminal.write('', offset < buffer.length ? writeWindow : settle);
105
+ };
106
+ setCancel?.(settle);
107
+ writeWindow();
108
+ });
109
+ }
110
+
111
+ class TerminalTile {
112
+ constructor(sessionId, mountEl, opts = {}) {
113
+ this.sessionId = sessionId;
114
+ this.mountEl = mountEl;
115
+ this.sessionMode = opts.mode;
116
+ this.fontSettings = opts.fontSettings || {};
117
+ // Live reference (not a snapshot) to the app's detachedSessions Set:
118
+ // detaching this session AFTER the pane opened must still be seen by
119
+ // _sendResize() below, or this pane and the session's own window fight
120
+ // over the PTY's size (which the split picker refuses at pick time).
121
+ this.detachedSessions = opts.detachedSessions;
122
+ // Lines of scrollback this pane's xterm keeps (the grid passes its smaller
123
+ // TILE_SCROLLBACK) and its font size (the grid's own tile font); absent,
124
+ // the primary pane's values.
125
+ this.scrollback = Number.isFinite(opts.scrollback) ? opts.scrollback : null;
126
+ this.fontSize = Number.isFinite(opts.fontSize) ? opts.fontSize : null;
127
+ // `scheduleLoad(tile, kind, run)` runs every capture this pane fetches
128
+ // (`kind`: 'initial', 'refresh' or 'history') when its owner says so, and
129
+ // resolves once `run` has finished or was dropped. The grid passes its one
130
+ // queue so N tiles never fetch at once; absent, a load runs straight away.
131
+ this._scheduleLoad = typeof opts.scheduleLoad === 'function' ? opts.scheduleLoad : null;
132
+ // Loads a BOUNDED window (`full=1&tail=` for a TUI, `tail=` for a shell)
133
+ // instead of a TUI's whole history. Grid tiles do; full history is one
134
+ // "leave the grid" away in the primary pane.
135
+ this.boundedLoad = opts.boundedLoad === true;
136
+ this.terminal = null;
137
+ this.fitAddon = null;
138
+ this.ws = null;
139
+ this._wsReady = false;
140
+ this._wsClosed = false;
141
+ this._destroyed = false;
142
+ // Single-flight state for _loadBuffer()/_refreshBuffer() below.
143
+ this._bufferLoading = false;
144
+ this._bufferRefreshPending = false;
145
+ // True only while a load's work runs, not while it waits in the owner's
146
+ // queue (see _runLoad): a close during the wait writes its marker at once.
147
+ this._loadRunning = false;
148
+ // Aborts the running load's fetch; destroy() uses it so a removed tile
149
+ // does not hold the owner's queue for a whole deadline.
150
+ this._loadAbort = null;
151
+ // Settles a replay xterm is still parsing (writeChunked): destroy() calls
152
+ // it, because a disposed xterm never runs the callback the replay awaits.
153
+ this._cancelReplay = null;
154
+ // Scroll-to-top history pull (shell panes only), see _maybeLoadMoreHistory().
155
+ // `_liveQueue` is non-null from the pull's response until its finally
156
+ // block: live frames are held there with their arrival time instead of
157
+ // written under the replay. `_markerOwed` is the "disconnected" marker a
158
+ // load still has to write (see _onSocketClosed()/_stampMarkerIfOwed()).
159
+ this._historyPullAt = 0;
160
+ this._historyPullUseless = false;
161
+ this._liveQueue = null;
162
+ this._liveQueueBytes = 0;
163
+ this._markerOwed = false;
164
+ // Live-output flow control (_writeLive, TerminalTile.LIVE_BACKLOG_BUDGET):
165
+ // code units written into this xterm and not yet parsed (each write's
166
+ // callback counts its own back down, unless a reset bumped `_liveEpoch`
167
+ // since), whether output was dropped and not yet recovered, when the last
168
+ // frame was dropped, and the debounced, bounded recovery refresh.
169
+ this._liveInFlight = 0;
170
+ this._liveEpoch = 0;
171
+ this._liveDropped = false;
172
+ this._liveDropAt = 0;
173
+ this._dropRecoveryTimer = null;
174
+ this._dropRecoveryAttempt = 0;
175
+ this._onWheel = null;
176
+ // `{ ws, lastRecvAt }`, registered with the app's input-socket map while
177
+ // this pane's socket is open, so the exactly-once input queue delivers this
178
+ // session's keystrokes over it (app.js _inputSocketFor). Null otherwise.
179
+ this._inputHandle = null;
180
+ // Reconnect state. `_socketUrl` is set once connect() opens the first
181
+ // socket: a pane that never connected has nothing to reconnect to.
182
+ // `_reconnectAttempts` counts consecutive failed opens and is reset ONLY by
183
+ // a successful open (resetting it per attempt is the tight-loop bug the
184
+ // primary pane's _disconnectWs documents). `_stoppedCode` is the close code
185
+ // that ended the pane for good; `onExit(code)` tells the owner once.
186
+ this._socketUrl = null;
187
+ this._reconnectAttempts = 0;
188
+ this._reconnectTimer = null;
189
+ this._stoppedCode = null;
190
+ this._markerText = TerminalTile.MARKER_RECONNECTING;
191
+ this.onExit = typeof opts.onExit === 'function' ? opts.onExit : null;
192
+ // The `{ cols, rows }` last sent in a `{t:'z'}` frame, so an unchanged size
193
+ // is not resent (each one costs a `tmux resize-window` and a SIGWINCH).
194
+ // Cleared on every open: a fresh socket must announce its size, which is
195
+ // also what registers it as a desktop viewer server-side.
196
+ this._lastSentDims = null;
197
+ // Whether the pointer is over a link in THIS pane (the primary pane's own
198
+ // flag, app._linkHovered, belongs to its terminal alone).
199
+ this._linkHovered = false;
200
+ this._onFocusIn = null;
201
+ // Hollow-buffer paging (_maybePageCliTranscript): wheel travel short of a
202
+ // whole page, carried to the next wheel event.
203
+ this._pageKeyPending = 0;
204
+ // Page keys waiting for the 40 ms flush, and its timer (_queueScrollBytes).
205
+ this._scrollBytes = '';
206
+ this._scrollFlushTimer = null;
207
+ // Rows above the screen that this pane pushed there itself rather than
208
+ // received as history: a capture taken at the PTY's previous, taller size
209
+ // and row-shrinking fits (_overflowAfterLoad, _noteResizeRows). Not
210
+ // history, so the paging gate leaves them out (_localRows).
211
+ this._overflowRows = 0;
212
+ // The desktop click reporter (_installClickListener).
213
+ this._onClick = null;
214
+ // The soft-keyboard controller (terminal-keycode229-recovery.js): created
215
+ // in connect() once the xterm is open, torn down in destroy().
216
+ this._keyCode229Recovery = null;
217
+ }
218
+
219
+ async connect() {
220
+ const savedFontSize = this.fontSize ?? parseInt(localStorage.getItem('codeman-font-size'), 10);
221
+ this.terminal = new Terminal({
222
+ theme: { ...global.codemanCurrentXtermTheme() },
223
+ fontFamily: global.CodemanTerminalFont.resolve(this.fontSettings.terminalFontFamily),
224
+ ...global.CodemanTerminalFont.resolveWeights(this.fontSettings),
225
+ fontSize: Number.isFinite(savedFontSize) ? savedFontSize : 14,
226
+ lineHeight: 1.2,
227
+ cursorBlink: false,
228
+ cursorStyle: 'block',
229
+ minimumContrastRatio: global.codemanCurrentSkinIsLight() ? 4.5 : 1,
230
+ scrollback: this.scrollback ?? DEFAULT_SCROLLBACK,
231
+ allowTransparency: true,
232
+ allowProposedApi: true,
233
+ });
234
+
235
+ this.fitAddon = new FitAddon.FitAddon();
236
+ this.terminal.loadAddon(this.fitAddon);
237
+ this.terminal.open(this.mountEl);
238
+ this.fitAddon.fit();
239
+
240
+ // File paths and URLs printed here are clickable, through the SAME
241
+ // provider as the primary pane (registerFilePathLinkProvider,
242
+ // terminal-ui.js), and open against THIS pane's session.
243
+ global.app?.registerFilePathLinkProvider?.({
244
+ terminal: this.terminal,
245
+ getSessionId: () => this.sessionId,
246
+ setHovered: (hovered) => {
247
+ this._linkHovered = hovered;
248
+ },
249
+ });
250
+
251
+ this._installWheelListener();
252
+ this._installClickListener();
253
+
254
+ // Focusing this terminal makes it the pane the keyboard is in, so the
255
+ // app-level shortcuts, voice and paste act on it (app._focusedPane).
256
+ this._onFocusIn = () => global.app?._noteFocusedTile?.(this);
257
+ this.terminal.textarea?.addEventListener('focus', this._onFocusIn);
258
+
259
+ this._createKeyCode229Recovery();
260
+ // The twin of terminal-ui.js's onData gate (initTerminal; keep the two in
261
+ // step). Canonical xterm data tells the controller this keystroke was
262
+ // delivered, but not a query reply or a focus/mouse report, which xterm
263
+ // emits on its own and which would otherwise stand a pending recovery
264
+ // down. The notify lives HERE and not in _onTerminalData(): the
265
+ // controller's own recovered bytes go through _onTerminalData() too, and
266
+ // must never count as xterm's, or a second pending character from the
267
+ // same keystroke window would stand down and be lost.
268
+ this.terminal.onData((data) => {
269
+ try {
270
+ const input = global.CodemanTerminalInput;
271
+ if (!input?.shouldSuppressTerminalQueryResponse?.(data) && !input?.isTerminalFocusOrMouseReport?.(data)) {
272
+ this._keyCode229Recovery?.notifyCanonicalData?.();
273
+ }
274
+ } catch {
275
+ /* Bookkeeping must never block real input. */
276
+ }
277
+ this._onTerminalData(data);
278
+ });
279
+
280
+ // xterm has no gates of its own, so every app-level chord that the
281
+ // document capture-phase handler (app.js) only preventDefault()s (never
282
+ // stopPropagation()s) would reach this xterm too and write its raw byte
283
+ // or escape sequence into THIS session's PTY on top of whatever the app
284
+ // action did (COD-153). These are the primary pane's gates
285
+ // (terminal-ui.js attachCustomKeyEventHandler): command palette,
286
+ // Alt+1-9/[/] tab nav, Alt+B sidebar toggle, the tile grid's chords,
287
+ // Ctrl+Z suspend, Shift/Ctrl+Enter newline, and smart-copy
288
+ // Ctrl+C/Ctrl+Shift+C. Routed through the same registry-aware
289
+ // predicates so a rebind or a disable restores plain terminal behavior
290
+ // here too. Ctrl+V goes through the primary pane's paste trap
291
+ // (image-input.js), aimed at this pane (below).
292
+ this.terminal.attachCustomKeyEventHandler((ev) => {
293
+ // FIRST, above the IME early return below, as in terminal-ui.js: every
294
+ // keydown settles this pane's pending textarea edit and drains a
295
+ // pending recovery BEFORE xterm handles the key, so a character an
296
+ // Android keyboard committed in the same task as Enter is sent ahead
297
+ // of the \r. Below that return a keyCode-229 keydown would skip the
298
+ // settle, the drain and the snapshot, and the panes would differ.
299
+ // Read at call time, never captured, so the controller can be swapped
300
+ // (the tests count xterm's emissions through it).
301
+ try {
302
+ this._keyCode229Recovery?.handleKeyEvent?.(ev);
303
+ } catch {
304
+ /* The controller must never interfere with xterm's own handling. */
305
+ }
306
+ if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return true;
307
+ if (
308
+ ev.altKey &&
309
+ !ev.ctrlKey &&
310
+ !ev.shiftKey &&
311
+ /^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(ev.code || '')
312
+ ) {
313
+ return false;
314
+ }
315
+ if (ev.type === 'keydown' && global.app?.shouldOpenCommandPaletteFromShortcut?.(ev)) {
316
+ return false;
317
+ }
318
+ if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(ev)) {
319
+ return false;
320
+ }
321
+ // Tile grid chords (focus, toggle): acted on by the capture handler, so
322
+ // they must never reach this tile's PTY. Every event type, and before
323
+ // the Shift+Enter branch below.
324
+ if (global.app?.tileShortcutFor?.(ev)) return false;
325
+ // Ctrl+V / Cmd+V: the primary pane's paste trap, aimed at THIS pane, so
326
+ // a pasted image uploads to this pane's session and its path is typed
327
+ // here, and pasted text goes into this xterm with its bracketed-paste
328
+ // markers intact. Mirrors terminal-ui.js's own Ctrl+V gate; without it
329
+ // xterm's default only ever pasted text.
330
+ if ((ev.ctrlKey || ev.metaKey) && ev.key === 'v' && ev.type === 'keydown') {
331
+ global.app?._handleImagePaste?.({ terminal: this.terminal, sessionId: this.sessionId });
332
+ return false;
333
+ }
334
+ // Ctrl+Z (SIGTSTP/job-control suspend), as terminal-ui.js swallows it:
335
+ // in a plain shell session this is the user's own job-control tool and
336
+ // must reach the PTY, but in every other mode (claude/omp/pi/codex/...)
337
+ // it silently stops an unattended agent loop dead. This pane has its
338
+ // own session and applies the same rule to it.
339
+ if (
340
+ ev.type === 'keydown' &&
341
+ ev.key.toLowerCase() === 'z' &&
342
+ ev.ctrlKey &&
343
+ !ev.altKey &&
344
+ !ev.metaKey &&
345
+ !ev.shiftKey &&
346
+ this.sessionMode !== 'shell'
347
+ ) {
348
+ return false;
349
+ }
350
+ // Shift+Enter / Ctrl+Enter: insert a newline instead of submitting, as
351
+ // terminal-ui.js does. xterm sends plain \r for every Enter variant,
352
+ // so an Ink app (Claude Code) can't tell a newline from a submit, and
353
+ // without this gate this pane's onData would send that bare \r and
354
+ // submit an incomplete prompt instead of adding a line to it. Targets
355
+ // THIS pane's own session (this.sessionId), never the primary pane's
356
+ // activeSessionId, and has no local-echo overlay of its own to flush
357
+ // first (this pane is deliberately plainer, see the fileoverview).
358
+ // Swallow keypress/keyup too (xterm would send \r for a Shift-only keypress); only keydown sends.
359
+ if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)) {
360
+ if (ev.type === 'keydown') {
361
+ fetch(`/api/sessions/${this.sessionId}/send-key`, {
362
+ method: 'POST',
363
+ headers: { 'Content-Type': 'application/json' },
364
+ body: JSON.stringify({ key: ev.ctrlKey ? 'C-Enter' : 'S-Enter' }),
365
+ }).catch(() => {
366
+ /* Best-effort, matching this pane's tolerance elsewhere. */
367
+ });
368
+ }
369
+ return false;
370
+ }
371
+ // Smart copy, the primary pane's rule (terminal-ui.js's Ctrl+C gate,
372
+ // #211) through the SAME helpers, aimed at THIS pane: the gutter width
373
+ // comes from this session's run mode, the partial first line from this
374
+ // terminal's selection, and the clear and refocus after the copy land
375
+ // here. With a selection worth copying, Ctrl+C copies instead of
376
+ // sending ^C; with none, plain Ctrl+C falls through unchanged or the
377
+ // interrupt key is lost. Ctrl+Shift+C is the explicit copy chord and
378
+ // never falls through (ev.shiftKey, below): with nothing to copy it
379
+ // would otherwise reach the browser's own binding for that chord.
380
+ // As in the primary gate, the CLEANED selection decides and the copy is
381
+ // handed the RAW one, because the margin strip is not idempotent.
382
+ if (ev.type === 'keydown' && global.app?.shouldCopyTerminalSelectionFromShortcut?.(ev)) {
383
+ const app = global.app;
384
+ const target = { terminal: this.terminal, sessionId: this.sessionId };
385
+ const raw = this.terminal?.getSelection?.() || '';
386
+ if (app.cleanedTerminalSelection?.(raw, target)?.trim()) {
387
+ ev.preventDefault();
388
+ void app.copyTerminalSelection(raw, target);
389
+ return false;
390
+ }
391
+ // Nothing worth copying: cleared for feedback, and the press still
392
+ // reaches the PTY as 0x03, as in the primary pane.
393
+ if (this.terminal?.hasSelection?.()) {
394
+ this.terminal.clearSelection?.();
395
+ app.showToast?.('Nothing to copy', 'warning');
396
+ }
397
+ if (ev.shiftKey) {
398
+ ev.preventDefault();
399
+ return false;
400
+ }
401
+ }
402
+ return true;
403
+ });
404
+
405
+ // Load existing scrollback before going live. The WS below is
406
+ // subscribe-only (ws-routes.ts sends nothing on connect, only future
407
+ // 'terminal' events), so without this the pane stays blank until the
408
+ // session happens to produce new output. The resize _sendResize() sends
409
+ // on open is no substitute: tmux repaints on a resize, but
410
+ // Session.resize() (session.ts) skips one that matches the session's
411
+ // last size, and then nothing repaints at all. The await covers the
412
+ // whole chunked replay, not just the fetch, so a live frame from the
413
+ // socket below can never land in the middle of it.
414
+ await this._loadBuffer();
415
+ if (this._destroyed) return;
416
+
417
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
418
+ // The tab's own connection identity plus a `:tile` suffix. The server
419
+ // supersedes a socket that reuses a cid on the same session (4010), so a
420
+ // pane must never share the primary pane's exact cid: were both ever on
421
+ // one session they would evict each other in a loop. Input frames still
422
+ // carry the BARE clientId, which is what the server dedups on.
423
+ const app = global.app;
424
+ const cid = app?._clientId ? `${app._clientId}:${app._wsTabNonce}:tile` : '';
425
+ const cidQuery = cid ? `?cid=${encodeURIComponent(cid)}` : '';
426
+ this._socketUrl = `${proto}//${location.host}${window.CodemanBase.base}/ws/sessions/${this.sessionId}/terminal${cidQuery}`;
427
+ this._openSocket();
428
+ }
429
+
430
+ // Opens a socket and makes it THE socket. A previous one is detached first
431
+ // (handlers nulled, then closed), and every handler below checks it still
432
+ // belongs to the current socket: a replacement opened while the old socket
433
+ // still looked alive (a half-open connection whose close has not landed)
434
+ // makes the server supersede the old one with a 4010, and that late close
435
+ // must not stop a pane that is already running on its successor.
436
+ _openSocket() {
437
+ if (this._destroyed || !this._socketUrl) return;
438
+ this._detachSocket();
439
+ const ws = new WebSocket(this._socketUrl);
440
+ this.ws = ws;
441
+
442
+ ws.onopen = () => {
443
+ if (ws !== this.ws) return;
444
+ this._onSocketOpen();
445
+ };
446
+
447
+ ws.onmessage = (event) => {
448
+ if (ws !== this.ws) return;
449
+ if (this._inputHandle) this._inputHandle.lastRecvAt = Date.now();
450
+ try {
451
+ const msg = JSON.parse(event.data);
452
+ if (msg.t === 'o') {
453
+ this._onLiveOutput(msg.d);
454
+ } else if (msg.t === 'c') {
455
+ this._onLiveClear();
456
+ } else if (msg.t === 'r') {
457
+ // Server-triggered refresh (SSE backpressure cleared, terminal
458
+ // data was dropped). The primary pane routes this to
459
+ // _onSessionNeedsRefresh (app.js); this pane has its own buffer
460
+ // loader for the same reason connect() does.
461
+ this._refreshBuffer();
462
+ } else if (msg.t === 'ia') {
463
+ // Input ACK. The frame names no session, so it is this pane's.
464
+ global.app?._onWsInputAck?.(msg.seq, msg, this.sessionId);
465
+ } else if (msg.t === 'zc') {
466
+ this._onPtyGeometryReport(msg.c, msg.r);
467
+ }
468
+ } catch {
469
+ /* Malformed frame: ignored, as in the primary pane. */
470
+ }
471
+ };
472
+
473
+ // _wsReady must go false on a drop or fit()/_sendResize() silently
474
+ // no-op on a closed socket per the WebSocket spec (no exception, no log).
475
+ // Input is not lost meanwhile: it waits in the app's durable queue and
476
+ // goes out over HTTP or the next socket. The "disconnected" marker says
477
+ // so on screen, and a transient close reconnects (_onSocketClosed).
478
+ ws.onclose = (event) => {
479
+ if (ws !== this.ws) return;
480
+ this._onSocketClosed(event);
481
+ };
482
+
483
+ ws.onerror = () => {
484
+ // onclose fires after onerror: cleanup happens there.
485
+ };
486
+ }
487
+
488
+ // Lets go of the current socket without running its close handling.
489
+ _detachSocket() {
490
+ const ws = this.ws;
491
+ if (!ws) return;
492
+ ws.onopen = null;
493
+ ws.onmessage = null;
494
+ // onclose fires asynchronously AFTER close(); without this it would run
495
+ // its "disconnected" write against a pane already torn down or replaced.
496
+ ws.onclose = null;
497
+ ws.onerror = null;
498
+ try {
499
+ ws.close();
500
+ } catch {
501
+ /* Already closed. */
502
+ }
503
+ this.ws = null;
504
+ this._wsReady = false;
505
+ this._unregisterInputSocket();
506
+ }
507
+
508
+ // A socket came up. After a drop this is a reconnect: the gap left nothing
509
+ // to replay (output frames carry no sequence number), so the buffer is
510
+ // refreshed. The closed state is reset FIRST, or the refresh would re-owe
511
+ // the "disconnected" marker (_refreshBuffer does on a closed socket) and
512
+ // stamp it under a healthy pane.
513
+ _onSocketOpen() {
514
+ const reconnected = this._wsClosed;
515
+ this._wsReady = true;
516
+ this._wsClosed = false;
517
+ this._markerOwed = false;
518
+ this._reconnectAttempts = 0;
519
+ this._lastSentDims = null;
520
+ this._registerInputSocket();
521
+ this._sendResize();
522
+ if (reconnected) {
523
+ // The gap already cost output, and the refresh below replaces the
524
+ // screen, so live-output accounting starts over with it.
525
+ this._resetLiveFlow();
526
+ this._refreshBuffer();
527
+ }
528
+ }
529
+
530
+ // Opens a replacement socket now instead of waiting out the backoff (for an
531
+ // owner that just learned the server is back). No-op while the current
532
+ // socket is open, after a permanent stop, or once destroyed.
533
+ reconnectNow() {
534
+ if (this._destroyed || this._stoppedCode !== null || !this._socketUrl) return;
535
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
536
+ clearTimeout(this._reconnectTimer);
537
+ this._reconnectTimer = null;
538
+ this._openSocket();
539
+ }
540
+
541
+ // The socket's close, split out of connect() so the tests can drive it.
542
+ // While any load runs (a history pull or a `{t:'r'}` refresh) the marker is
543
+ // only owed, and that load's finally block settles it (_stampMarkerIfOwed()):
544
+ // written now, it would sit above the output a pull is still holding (flushed
545
+ // after it on a skip, a downgrade or a failed fetch), above a refresh's
546
+ // replay, or in the middle of a chunked replay. A pull still waiting for its
547
+ // response holds the marker too, for as long as the request takes (up to its
548
+ // budget, see _pullHistory()).
549
+ //
550
+ // Then decides what comes next. Codes that cannot get better stop the pane
551
+ // for good and report once through `onExit(code)`: 4004/4009 (the session
552
+ // is gone), 4003 (refused: Host/Origin/owner, a retry gets the same answer)
553
+ // and 4010 (another socket with this pane's cid took over; only ever
554
+ // reaches here for the CURRENT socket, see _openSocket). Everything else,
555
+ // including the redelivery sweep force-closing a silent socket (1005), is
556
+ // transient and reconnects on the primary pane's backoff ladder
557
+ // (CodemanWsReconnect, constants.js) plus jitter.
558
+ _onSocketClosed(event) {
559
+ this._wsReady = false;
560
+ this._wsClosed = true;
561
+ this._unregisterInputSocket();
562
+ const code = event?.code;
563
+ const permanent = TerminalTile.STOP_MARKERS[code];
564
+ this._markerText = permanent || TerminalTile.MARKER_RECONNECTING;
565
+ if (this._loadRunning) this._markerOwed = true;
566
+ else this._writeDisconnectedMarker();
567
+ if (this._destroyed) return;
568
+ if (permanent) {
569
+ this._stop(code);
570
+ return;
571
+ }
572
+ this._scheduleReconnect(code);
573
+ }
574
+
575
+ _scheduleReconnect(code) {
576
+ if (this._destroyed || !this._socketUrl || this._reconnectTimer) return;
577
+ const plan = global.CodemanWsReconnect?.plan?.(code ?? 1006, this._reconnectAttempts) || {
578
+ action: 'reconnect',
579
+ delayMs: 1000,
580
+ };
581
+ if (plan.action === 'give-up') {
582
+ this._stop(code);
583
+ return;
584
+ }
585
+ this._reconnectAttempts++;
586
+ const delay = plan.delayMs + Math.floor(Math.random() * 250); // jitter: tiles must not reconnect in lockstep
587
+ this._reconnectTimer = setTimeout(() => {
588
+ this._reconnectTimer = null;
589
+ this._openSocket();
590
+ }, delay);
591
+ }
592
+
593
+ _stop(code) {
594
+ if (this._stoppedCode !== null) return;
595
+ this._stoppedCode = code ?? null;
596
+ clearTimeout(this._reconnectTimer);
597
+ this._reconnectTimer = null;
598
+ if (!this._destroyed) this.onExit?.(code);
599
+ }
600
+
601
+ // Keystrokes and pastes go through the app's exactly-once input queue (seq,
602
+ // ACK, persisted until delivered, redelivered after a drop), over this
603
+ // pane's own socket while it is open and the HTTP fallback while it is not.
604
+ // What xterm GENERATES must not be queued: a query reply (DA/CPR/OSC) is
605
+ // dropped, as the primary pane drops it, because forwarding it types
606
+ // "0;276;0c" into the CLI, and replaying one after a reload would do so
607
+ // again into a later screen. A focus or mouse report is real input the
608
+ // program asked for, but nobody typed it: it goes out once, never
609
+ // persisted. Same predicates as the primary pane (terminal-ui.js onData).
610
+ _onTerminalData(data) {
611
+ const input = global.CodemanTerminalInput;
612
+ if (input?.shouldSuppressTerminalQueryResponse?.(data)) return;
613
+ const app = global.app;
614
+ if (input?.isTerminalFocusOrMouseReport?.(data)) {
615
+ app?._sendInputEphemeral?.(this.sessionId, data);
616
+ return;
617
+ }
618
+ app?._sendInputAsync?.(this.sessionId, data);
619
+ }
620
+
621
+ // The soft-keyboard controller, the twin of the primary pane's wiring in
622
+ // terminal-ui.js initTerminal() (keep the two in step); the behaviour lives
623
+ // once, in terminal-keycode229-recovery.js. Everything it is handed is THIS
624
+ // pane's: its textarea, its xterm's CompositionHelper (whose
625
+ // `_handleAnyTextareaChanges` it patches, per instance) and its send path.
626
+ // Recovered text goes straight to _onTerminalData(), never through xterm's
627
+ // onData, so it is not counted as xterm's own (see connect()'s onData).
628
+ // Created after terminal.open(): xterm's capture `input` listener on the
629
+ // textarea is registered there, and must run before the controller's. No
630
+ // device or mode gate, as in the primary pane: with a hardware keyboard it
631
+ // costs one assignment per keydown. A failure leaves xterm's own handling.
632
+ _createKeyCode229Recovery() {
633
+ this._destroyKeyCode229Recovery();
634
+ if (!this.terminal) return;
635
+ try {
636
+ this._keyCode229Recovery =
637
+ global.CodemanKeyCode229Recovery?.create?.({
638
+ textarea: this.terminal.textarea,
639
+ emitRecovered: (data) => this._onTerminalData(data),
640
+ getCompositionHelper: () => this.terminal?._core?._compositionHelper,
641
+ isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
642
+ }) ?? null;
643
+ } catch {
644
+ this._keyCode229Recovery = null;
645
+ }
646
+ }
647
+
648
+ // Restores xterm's own textarea diff and removes the controller's capture
649
+ // listeners from the live textarea, so it runs before terminal.dispose().
650
+ _destroyKeyCode229Recovery() {
651
+ try {
652
+ this._keyCode229Recovery?.destroy?.();
653
+ } catch {
654
+ /* Optional; teardown must continue. */
655
+ }
656
+ this._keyCode229Recovery = null;
657
+ }
658
+
659
+ // Joins the app's input-socket map for this session and flushes anything
660
+ // already queued for it (typed while the socket was down, or left over from
661
+ // a reload) over the fresh socket. Called from onopen.
662
+ _registerInputSocket() {
663
+ const app = global.app;
664
+ if (!this.ws || !app?._registerInputSocket) return;
665
+ this._unregisterInputSocket();
666
+ this._inputHandle = { ws: this.ws, lastRecvAt: 0 };
667
+ app._registerInputSocket(this.sessionId, this._inputHandle);
668
+ app._onWsReady?.(this.sessionId);
669
+ // The header's connection dot reads tile sockets while the grid is open.
670
+ app._updateConnectionIndicator?.();
671
+ }
672
+
673
+ // Leaves the map; only this pane's own handle is removed (a replacement
674
+ // socket's registration survives a late close of the old one).
675
+ _unregisterInputSocket() {
676
+ if (!this._inputHandle) return;
677
+ global.app?._unregisterInputSocket?.(this.sessionId, this._inputHandle);
678
+ this._inputHandle = null;
679
+ global.app?._updateConnectionIndicator?.();
680
+ }
681
+
682
+ // Settles a marker the pane owes: set when a close lands during a load (the
683
+ // replay would otherwise sit below it) or when a load wipes the terminal on
684
+ // a closed socket. Called from each load's own finally, just before
685
+ // _endBufferLoad() starts any trailing refresh.
686
+ _stampMarkerIfOwed() {
687
+ // A trailing refresh is about to run, and it settles the marker itself:
688
+ // a replay's queued `\x1bc` would wipe one written here (it re-owes the
689
+ // marker on a closed socket and stamps it below the replay), and a refresh
690
+ // that writes nothing stamps the one still owed. Stamped here as well,
691
+ // there would be two marker writes for one close.
692
+ if (this._bufferRefreshPending && !this._destroyed) return;
693
+ const owed = this._markerOwed;
694
+ this._markerOwed = false;
695
+ if (owed && this._wsClosed && !this._destroyed) this._writeDisconnectedMarker();
696
+ }
697
+
698
+ // Extracted so both _onSocketClosed() and a load that ends owing it on a
699
+ // closed socket can write it (see _stampMarkerIfOwed()).
700
+ _writeDisconnectedMarker() {
701
+ this.terminal?.write(`\r\n\x1b[2m${this._markerText}\x1b[0m\r\n`);
702
+ }
703
+
704
+ // Fetches and writes the session's current scrollback. Used both by
705
+ // connect() (initial load) and by the refresh frames (`{t:'r'}`, `{t:'c'}`)
706
+ // and a reconnect (_refreshBuffer). The primary pane's own
707
+ // _onSessionNeedsRefresh (app.js) is scoped to `this.activeSessionId` and
708
+ // rewrites the primary terminal, neither of which applies to this
709
+ // independent pane, so this is a standalone equivalent rather than a call
710
+ // into it, in the primary's order (below).
711
+ //
712
+ // Mirrors the primary pane's own mode check (app.js's selectSession /
713
+ // _onSessionNeedsRefresh): a shell session can retain hundreds of
714
+ // thousands of plain scrollback lines, so pulling `?full=1` there parses
715
+ // an unbounded, server-capped (up to terminalBufferMaxBytes, 32MB) body
716
+ // into this xterm on every load; a shell loads the `tail=` window. A
717
+ // non-shell (TUI) session gets one full replay, or the same bounded window
718
+ // with `boundedLoad` (grid tiles). `fetch` here goes through the global
719
+ // wrapper (constants.js), which already prefixes CodemanBase, unlike the
720
+ // raw WebSocket URL above, which does not.
721
+ //
722
+ // A refresh replaces what the pane shows, in the primary pane's order
723
+ // (_onSessionNeedsRefresh, _resetTerminalForReplay): fetch FIRST, so the
724
+ // pane keeps its last frame through the round trip (and through a grid
725
+ // tile's wait in the load queue); then the queued in-stream `\x1bc`, never
726
+ // xterm's clear(): clear() is synchronous while write() is parsed on a later
727
+ // tick, so live bytes still queued would land after it and fuse into the
728
+ // snapshot, and it keeps the cursor's row, column, SGR and margins, so the
729
+ // capture (raw rows, no home) started wherever the cursor sat. Live frames
730
+ // from the response onward are held (`_liveQueue`, the primary's
731
+ // _finishBufferLoad `since` rule, as _pullHistory() holds them) and only
732
+ // those that arrived after it are written behind the replay. A failed,
733
+ // aborted or empty fetch writes nothing and resets nothing: the pane keeps
734
+ // its last frame and every held frame. The initial load needs none of
735
+ // this: it runs before the pane has a socket, onto a fresh xterm.
736
+ //
737
+ // Single-flight: the flag is held across the fetch AND the chunked write
738
+ // (writeChunked resolves after its last chunk), so two replays can never
739
+ // interleave their chunks into one terminal. A second call while one is
740
+ // in flight is dropped here; _refreshBuffer() is the caller that queues
741
+ // a trailing re-run instead.
742
+ async _loadBuffer({ refresh = false } = {}) {
743
+ if (this._bufferLoading) return;
744
+ this._bufferLoading = true;
745
+ await this._runLoad(refresh ? 'refresh' : 'initial', async () => {
746
+ this._loadRunning = true;
747
+ let replayed = false;
748
+ let capturedAt = 0;
749
+ // A deadline covering the body as well as the headers (the primary
750
+ // pane's budgets, CodemanFetchDeadline): a capture that never answers
751
+ // would otherwise hold this pane's single-flight flag, and in the grid
752
+ // the one load queue every tile waits behind, forever. Re-armed once a
753
+ // refresh's headers land (below), so one signal carries both budgets.
754
+ const controller = global.AbortController ? new global.AbortController() : null;
755
+ let abortTimer = null;
756
+ const armDeadline = (ms) => {
757
+ if (!controller) return;
758
+ clearTimeout(abortTimer);
759
+ abortTimer = setTimeout(() => controller.abort(), ms);
760
+ };
761
+ try {
762
+ if (this._destroyed) return;
763
+ const shell = this.sessionMode === 'shell';
764
+ let query = shell ? `tail=${TERMINAL_TAIL_SIZE}` : 'full=1';
765
+ if (this.boundedLoad && !shell) query = `full=1&tail=${TERMINAL_TAIL_SIZE}${this._historyLinesQuery()}`;
766
+ this._loadAbort = controller;
767
+ armDeadline(global.CodemanFetchDeadline?.terminalFetchDeadlineMs?.({ full: !shell }) ?? 45000);
768
+ let payload;
769
+ try {
770
+ const res = await fetch(
771
+ `/api/sessions/${this.sessionId}/terminal?${query}`,
772
+ controller ? { signal: controller.signal } : undefined
773
+ );
774
+ if (refresh) {
775
+ // The response's arrival stands in for the instant tmux took the
776
+ // capture (see _pullHistory()). Frames from here on are news the
777
+ // capture cannot hold, so they wait for the replay. From now on
778
+ // live output IS held, so a bounded window's body (at most
779
+ // TERMINAL_TAIL_SIZE) gets the pull's short budget; an unbounded
780
+ // capture (the split's Pane B, up to 32 MB) keeps the request's.
781
+ capturedAt = performance.now();
782
+ this._openLiveQueue();
783
+ if (shell || this.boundedLoad) armDeadline(HISTORY_PULL_TIMEOUT_MS);
784
+ }
785
+ payload = (await res.json())?.data ?? {};
786
+ } finally {
787
+ clearTimeout(abortTimer);
788
+ this._loadAbort = null;
789
+ }
790
+ if (payload.terminalBuffer && this.terminal && !this._destroyed) {
791
+ if (refresh) {
792
+ this.terminal.write('\x1bc');
793
+ this._overflowRows = 0; // the reset leaves nothing above the screen
794
+ replayed = true;
795
+ // The reset wipes a "disconnected" marker (a `{t:'r'}` frame can
796
+ // queue a trailing refresh behind a pull that the socket's close
797
+ // then interrupts), so a refresh on a closed socket owes it back
798
+ // once its replay is written.
799
+ if (this._wsClosed) this._markerOwed = true;
800
+ }
801
+ await writeChunked(
802
+ this.terminal,
803
+ payload.terminalBuffer,
804
+ () => this._destroyed,
805
+ (cancel) => (this._cancelReplay = cancel)
806
+ );
807
+ if (!this._destroyed && this.terminal) this._overflowRows = this._overflowAfterLoad(payload);
808
+ }
809
+ } catch {
810
+ /* Best-effort: live output still arrives once the socket connects. */
811
+ } finally {
812
+ clearTimeout(abortTimer);
813
+ this._loadAbort = null;
814
+ this._loadRunning = false;
815
+ // Before the flush: a refresh that recovered dropped output lets its
816
+ // held frames through.
817
+ if (refresh) this._settleDropRecovery({ replayed, capturedAt, timedOut: !!controller?.signal?.aborted });
818
+ // Held frames before the marker, so the marker stays the last thing on
819
+ // screen (see _pullHistory()).
820
+ this._flushLiveQueue(replayed ? capturedAt : 0);
821
+ this._stampMarkerIfOwed();
822
+ this._endBufferLoad();
823
+ }
824
+ });
825
+ }
826
+
827
+ // Runs a load's work now, or when the owner's queue gives this pane its turn
828
+ // (`scheduleLoad`). The single-flight flag is already set by the caller, so a
829
+ // load waiting in the queue still coalesces refreshes and blocks a second
830
+ // pull; the work itself sets `_loadRunning`. A load the queue drops (this
831
+ // pane was destroyed while it waited) never runs, so its flags are released
832
+ // here.
833
+ async _runLoad(kind, work) {
834
+ let ran = false;
835
+ const run = () => {
836
+ ran = true;
837
+ return work();
838
+ };
839
+ if (!this._scheduleLoad) {
840
+ await run();
841
+ return;
842
+ }
843
+ try {
844
+ await this._scheduleLoad(this, kind, run);
845
+ } catch {
846
+ /* The queue never rejects; a load that failed already settled itself. */
847
+ }
848
+ if (!ran) {
849
+ this._bufferLoading = false;
850
+ this._bufferRefreshPending = false;
851
+ }
852
+ }
853
+
854
+ // Ends a single-flight load (initial, refresh or history pull): clears the
855
+ // flag, then runs the ONE trailing refresh that arrived while it was busy.
856
+ _endBufferLoad() {
857
+ this._bufferLoading = false;
858
+ if (this._bufferRefreshPending && !this._destroyed) {
859
+ this._bufferRefreshPending = false;
860
+ this._refreshBuffer();
861
+ }
862
+ }
863
+
864
+ // Live terminal output. Written straight through, except while a refresh or
865
+ // a history pull is replaying: a capture is current only up to the instant
866
+ // tmux took it, so a frame arriving mid-replay is held with its arrival time
867
+ // and written behind the snapshot by that load's _flushLiveQueue() (the
868
+ // primary pane's _finishBufferLoad `since` rule), never underneath it.
869
+ // Held frames count against the same budget as unparsed ones: a pull or a
870
+ // refresh holds output for up to its body budget, and a flood meanwhile
871
+ // must not grow the queue without bound either.
872
+ _onLiveOutput(data) {
873
+ if (!data) return;
874
+ if (this._liveQueue) {
875
+ if (this._liveQueueBytes + data.length > TerminalTile.LIVE_BACKLOG_BUDGET) {
876
+ this._noteLiveDrop();
877
+ return;
878
+ }
879
+ this._liveQueueBytes += data.length;
880
+ this._liveQueue.push({ at: performance.now(), data });
881
+ return;
882
+ }
883
+ this._writeLive(data);
884
+ }
885
+
886
+ _openLiveQueue() {
887
+ this._liveQueue = [];
888
+ this._liveQueueBytes = 0;
889
+ }
890
+
891
+ // Releases the frames a load held (_liveQueue) and closes the queue. After a
892
+ // replay only those that arrived after the capture are news (`cutoff`, the
893
+ // response's arrival; earlier ones are already in it); with no replay
894
+ // (`cutoff` 0) every one is. Through _writeLive(), so they are counted (and
895
+ // a write that throws cannot skip the load's marker and trailing refresh).
896
+ _flushLiveQueue(cutoff) {
897
+ const queued = this._liveQueue ?? [];
898
+ this._liveQueue = null;
899
+ this._liveQueueBytes = 0;
900
+ for (const entry of queued) {
901
+ if (entry.at < cutoff) continue;
902
+ this._writeLive(entry.data);
903
+ }
904
+ }
905
+
906
+ // Writes one live frame into this xterm, under flow control. The server
907
+ // applies no backpressure (16 KB / 8 ms batches, never a bufferedAmount
908
+ // check), so a flood a tile cannot parse as fast as it arrives (a shell
909
+ // tile running `cat` on a huge log, `yes`) used to pile up in xterm's own
910
+ // write queue without bound, on a main thread six tiles share, until
911
+ // xterm's WriteBuffer throws past 50M code units and the frames were
912
+ // silently lost in onmessage's catch. The primary pane caps its queues
913
+ // and drops then recaptures (_onSessionTerminal, app.js); this is the
914
+ // tile's equivalent. Past TerminalTile.LIVE_BACKLOG_BUDGET unparsed, a
915
+ // frame is dropped and the tile stops writing until a refresh recaptures
916
+ // the screen (_scheduleDropRecovery): every byte after a hole is written
917
+ // onto a screen out of step with the PTY, which that refresh replaces
918
+ // anyway. A write that throws is the same drop, never a malformed frame.
919
+ _writeLive(data) {
920
+ const terminal = this.terminal;
921
+ if (!terminal || this._destroyed || !data) return;
922
+ if (this._liveDropped) {
923
+ this._noteLiveDrop();
924
+ return;
925
+ }
926
+ const n = data.length;
927
+ if (this._liveInFlight + n > TerminalTile.LIVE_BACKLOG_BUDGET) {
928
+ this._noteLiveDrop();
929
+ return;
930
+ }
931
+ const epoch = this._liveEpoch;
932
+ this._liveInFlight += n;
933
+ try {
934
+ terminal.write(data, () => {
935
+ if (epoch === this._liveEpoch) this._liveInFlight -= n;
936
+ });
937
+ } catch {
938
+ if (epoch === this._liveEpoch) this._liveInFlight -= n;
939
+ this._noteLiveDrop();
940
+ }
941
+ }
942
+
943
+ // A live frame was dropped. Marks the tile out of step and arms ONE
944
+ // recovery; later drops only move the stamp the recovery has to beat.
945
+ _noteLiveDrop() {
946
+ this._liveDropAt = performance.now();
947
+ if (this._liveDropped) return;
948
+ this._liveDropped = true;
949
+ this._scheduleDropRecovery();
950
+ }
951
+
952
+ // The primary pane's dropped-output recovery (_scheduleDroppedOutputRecovery,
953
+ // app.js), aimed at this tile: debounced by DROP_RECOVERY_DELAY_MS so a
954
+ // sustained flood collapses into one attempt, and run as an ordinary
955
+ // refresh, which is single-flight, bounded (`lines=`/`tail=`) and waits its
956
+ // turn in the grid's load queue. _settleDropRecovery() decides what the
957
+ // refresh it starts achieved.
958
+ _scheduleDropRecovery() {
959
+ if (this._dropRecoveryTimer || this._destroyed) return;
960
+ const delay = global.CodemanDroppedOutput?.DROP_RECOVERY_DELAY_MS ?? 2000;
961
+ this._dropRecoveryTimer = setTimeout(() => {
962
+ this._dropRecoveryTimer = null;
963
+ if (this._destroyed || !this._liveDropped) return;
964
+ this._dropRecoveryAttempt++;
965
+ this._refreshBuffer();
966
+ }, delay);
967
+ }
968
+
969
+ // A refresh finished while output was marked dropped. Recovered when its
970
+ // replay's capture was taken after the last dropped frame (the response's
971
+ // arrival, the cutoff every load uses): output flows again. Otherwise one
972
+ // more attempt, bounded by the primary pane's rule
973
+ // (shouldRetryDroppedOutputRecovery: DROP_RECOVERY_MAX_ATTEMPTS, and never
974
+ // after a capture cut off at its deadline, a stalled link); past that the
975
+ // flag is released so the tile is never left frozen, and it writes on, out
976
+ // of step, as every tile did before this existed.
977
+ _settleDropRecovery({ replayed, capturedAt, timedOut }) {
978
+ if (!this._liveDropped || this._destroyed) return;
979
+ if (replayed && capturedAt >= this._liveDropAt) {
980
+ this._liveDropped = false;
981
+ this._dropRecoveryAttempt = 0;
982
+ return;
983
+ }
984
+ // Another try is already on its way: the debounce, or a trailing refresh.
985
+ if (this._dropRecoveryTimer || this._bufferRefreshPending) return;
986
+ const retry =
987
+ global.CodemanDroppedOutput?.shouldRetryDroppedOutputRecovery?.({
988
+ repainted: false,
989
+ timedOut,
990
+ attempt: Math.max(0, this._dropRecoveryAttempt - 1),
991
+ stillActive: true,
992
+ }) === true;
993
+ if (retry) {
994
+ this._scheduleDropRecovery();
995
+ return;
996
+ }
997
+ this._liveDropped = false;
998
+ this._dropRecoveryAttempt = 0;
999
+ }
1000
+
1001
+ // Starts live-output accounting over (a reconnect, destroy): write callbacks
1002
+ // still pending from before carry the old epoch and count nothing.
1003
+ _resetLiveFlow() {
1004
+ this._liveEpoch++;
1005
+ this._liveInFlight = 0;
1006
+ this._liveDropped = false;
1007
+ this._dropRecoveryAttempt = 0;
1008
+ clearTimeout(this._dropRecoveryTimer);
1009
+ this._dropRecoveryTimer = null;
1010
+ }
1011
+
1012
+ // The server's `{t:'c'}` frame, which is a refresh, not a wipe. Its one
1013
+ // emitter (Session.startInteractive, session.ts) sends it once a fresh Claude
1014
+ // pane first shows its prompt: the server has just trimmed its own buffer and
1015
+ // means "refresh after startup". The primary pane refetches the capture and
1016
+ // replays it (_onSessionClearTerminal, app.js), and while the grid is open
1017
+ // that handler stands aside for the tiles. A bare xterm clear() here kept
1018
+ // only the cursor's row and dropped the banner and every row above it, and an
1019
+ // idle Claude never repaints static rows, so a Claude session Run into the
1020
+ // grid (or Attached in a tile) sat there as a near-empty tile. So it takes
1021
+ // the `{t:'r'}` route: single-flight, coalesced into one trailing refresh
1022
+ // behind a load already running (a pull's held frames included), and paced
1023
+ // by the grid's load queue.
1024
+ _onLiveClear() {
1025
+ this._refreshBuffer();
1026
+ }
1027
+
1028
+ // Capture phase, because xterm's own wheel handler stopPropagation()s every
1029
+ // event it consumes, so a bubbling listener here would never see the wheel
1030
+ // while the pane still has scrollback to scroll. Not passive: the one route
1031
+ // this pane takes over, paging a hollow buffer's CLI transcript
1032
+ // (_maybePageCliTranscript), is consumed right here (preventDefault plus
1033
+ // stopPropagation in the capture phase, the primary pane's technique), so
1034
+ // xterm's viewport, a descendant, never sees it. Every other wheel is left
1035
+ // to xterm, which keeps doing the scrolling, and only observed for the
1036
+ // shell history pull.
1037
+ _installWheelListener() {
1038
+ this._onWheel = (ev) => {
1039
+ if (this._maybePageCliTranscript(ev)) {
1040
+ ev.preventDefault();
1041
+ ev.stopPropagation();
1042
+ return;
1043
+ }
1044
+ if (ev.deltaY < 0) this._maybeLoadMoreHistory();
1045
+ };
1046
+ this.mountEl.addEventListener('wheel', this._onWheel, { capture: true, passive: false });
1047
+ }
1048
+
1049
+ // A plain left-click reported to the CLI, the primary pane's desktop click
1050
+ // (terminal-ui.js _handleDesktopTerminalClick) aimed at this pane. The
1051
+ // server strips the mouse DECSETs of some modes (opencode's since #555, so a
1052
+ // drag selects text), which leaves this xterm's own mouse encoder idle for
1053
+ // them; without this a click in such a pane never reached the CLI. Only
1054
+ // while this pane's session has tracking on (cliMouseTracking), through the
1055
+ // same skips as the primary pane. Bubble phase, as there. The target is
1056
+ // built per click, so the terminal and the link hover are read live.
1057
+ _installClickListener() {
1058
+ this._onClick = (ev) => {
1059
+ if (this._destroyed || !this.terminal) return;
1060
+ global.app?._handleDesktopTerminalClick?.(ev, {
1061
+ terminal: this.terminal,
1062
+ sessionId: this.sessionId,
1063
+ linkHovered: this._linkHovered,
1064
+ // Like every mouse report from this pane (_onTerminalData): once,
1065
+ // never persisted, so a reload cannot replay it onto a later screen.
1066
+ ephemeral: true,
1067
+ });
1068
+ };
1069
+ this.mountEl.addEventListener('click', this._onClick);
1070
+ }
1071
+
1072
+ // Hollow-buffer paging, the twin of the primary pane's
1073
+ // _maybePageCliTranscript (terminal-ui.js; keep the two in step). A CLI that
1074
+ // draws in place (opencode, on the alternate screen; Claude's repaint mode)
1075
+ // leaves this xterm no scrollback, so a wheel scrolled nothing; instead the
1076
+ // travel pages the CLI's own transcript with PageUp/PageDown. Every gate is
1077
+ // the primary pane's own, asked for THIS pane (its terminal, its session,
1078
+ // never the active one), so the CLI rules stay in terminal-ui.js and this
1079
+ // file names no CLI. Returns true when the wheel was consumed here.
1080
+ _maybePageCliTranscript(ev) {
1081
+ if (this._destroyed || !this.terminal || !ev || ev.shiftKey) return false;
1082
+ const app = global.app;
1083
+ const input = global.CodemanTerminalInput;
1084
+ if (!app || !input?.pageKeysForTravel || !input.wheelDeltaLines) return false;
1085
+ // xterm's own encoder forwards the wheel while the CLI's tracking reaches
1086
+ // it (a shell running htop), as in the primary pane.
1087
+ const tracking = this.terminal.modes?.mouseTrackingMode;
1088
+ if (tracking && tracking !== 'none') return false;
1089
+ const target = { terminal: this.terminal, sessionId: this.sessionId };
1090
+ // The primary pane would forward this wheel to Claude's fullscreen
1091
+ // renderer as SGR reports. Tiles do not do that yet (docs/tile-grid-plan.md
1092
+ // follow-up 4), so the wheel stays with xterm, as before.
1093
+ if (app._shouldForwardWheelToApp?.(ev, target)) return false;
1094
+ if (!app._localScrollbackIsHollow?.({ ...target, localRows: this._localRows() })) return false;
1095
+ // Only from the live screen. The one gate the primary pane never needs: a
1096
+ // primary hollow buffer has baseY 0, so its viewport is always at the
1097
+ // bottom, while a tile's is hollow with its own overflow rows still above
1098
+ // the screen, and Shift+PageUp, a scrollbar drag or a wheel during the
1099
+ // first replay can leave the viewport up there. Paging from there would
1100
+ // swallow every wheel (wheel-down included) and keep the stale rows on
1101
+ // screen while the CLI pages out of view; left to xterm, a wheel-down
1102
+ // brings the viewport home and paging resumes from there. The click
1103
+ // report refuses an off-bottom viewport for the same reason
1104
+ // (_terminalViewportAtBottom).
1105
+ if (!app._terminalViewportAtBottom?.(this.terminal)) return false;
1106
+ const lines = input.wheelDeltaLines(ev, this.terminal.rows);
1107
+ if (!lines) return false;
1108
+ const step = input.pageKeysForTravel(this._pageKeyPending, lines, this.terminal.rows);
1109
+ this._pageKeyPending = step.pending;
1110
+ if (step.keys) this._queueScrollBytes(step.keys);
1111
+ return true;
1112
+ }
1113
+
1114
+ // Coalesces the page keys into one send per 40 ms, bounded at 512 bytes so a
1115
+ // fling cannot build a backlog that keeps paging after it stops. A narrow
1116
+ // twin of the primary pane's _queueScrollBytes / _flushWheelSgrQueue
1117
+ // (terminal-ui.js; keep the two in step), which flushes to the active
1118
+ // session only. Sent ephemeral (no seq, never persisted) to THIS pane's
1119
+ // session, over this pane's socket while it is open.
1120
+ _queueScrollBytes(data) {
1121
+ if (!data || this._destroyed) return;
1122
+ if (this._scrollBytes.length > 512) return;
1123
+ this._scrollBytes += data;
1124
+ if (this._scrollFlushTimer) return;
1125
+ this._scrollFlushTimer = setTimeout(() => {
1126
+ this._scrollFlushTimer = null;
1127
+ const bytes = this._scrollBytes;
1128
+ this._scrollBytes = '';
1129
+ if (bytes && !this._destroyed) global.app?._sendInputEphemeral?.(this.sessionId, bytes);
1130
+ }, 40);
1131
+ }
1132
+
1133
+ // History rows in this xterm, for the paging gate: baseY less the rows this
1134
+ // pane pushed up itself. Clamped, because a clear (Ctrl+L) or an ED3/RIS in
1135
+ // the stream drops rows behind this count's back.
1136
+ _localRows() {
1137
+ const baseY = this.terminal?.buffer?.active?.baseY || 0;
1138
+ this._overflowRows = Math.min(this._overflowRows, baseY);
1139
+ return baseY - this._overflowRows;
1140
+ }
1141
+
1142
+ // After a local resize: rows a shrinking fit pushed above the screen count
1143
+ // as overflow, and rows a growing one pulled back come off it. `before` is
1144
+ // baseY just before the resize (xterm resizes synchronously).
1145
+ _noteResizeRows(before) {
1146
+ const after = this.terminal?.buffer?.active?.baseY || 0;
1147
+ this._overflowRows = Math.max(0, Math.min(after, this._overflowRows + (after - before)));
1148
+ }
1149
+
1150
+ // The overflow a finished load leaves: everything above the screen when the
1151
+ // capture held a single screen (the server says how tall in `captureRows`;
1152
+ // the full-history path keeps every pane row and trims one newline), none
1153
+ // when it carried history. The counterpart of the primary pane resizing the
1154
+ // PTY before it captures (app.js selectSession's sendResize), which this
1155
+ // pane does not do: its first capture is taken at the PTY's previous size
1156
+ // (usually the primary pane's, taller) and written into a shorter xterm,
1157
+ // whose extra rows land above the screen with nothing after them to clear
1158
+ // them. Without a `captureRows` the raw baseY stands, as in the primary.
1159
+ _overflowAfterLoad(payload) {
1160
+ const captureRows = payload?.captureRows;
1161
+ if (!Number.isFinite(captureRows)) return 0;
1162
+ const text = payload.terminalBuffer || '';
1163
+ let lines = 1;
1164
+ for (let i = text.indexOf('\n'); i !== -1 && lines <= captureRows; i = text.indexOf('\n', i + 1)) lines++;
1165
+ if (lines > captureRows) return 0;
1166
+ return this.terminal?.buffer?.active?.baseY || 0;
1167
+ }
1168
+
1169
+ // Wheel-up at the top of a SHELL pane's scrollback. tmux repaints a burst of
1170
+ // output (`cat` of a file longer than the screen) instead of scrolling it,
1171
+ // so this pane's xterm ends up with about one screen of scrollback while
1172
+ // tmux holds every line, and without this pull the history is
1173
+ // unreachable. The primary pane has the same pull
1174
+ // (app.js _maybeRefetchFullHistory); a tile is a separate xterm and needs
1175
+ // its own. Shell only: a non-shell CLI's history is out of scope for this
1176
+ // pull (its load already takes `full=1`; codex and Claude's inline renderer
1177
+ // do grow tmux history, this just isn't how they recover it). The
1178
+ // alternate-screen skip (nano, vim, less) only matters for a direct-PTY
1179
+ // shell: under tmux the browser xterm never enters the alternate buffer.
1180
+ _maybeLoadMoreHistory() {
1181
+ if (this.sessionMode !== 'shell' || this._destroyed || !this.terminal) return;
1182
+ if (this._bufferLoading) return;
1183
+ // Mirrors app.js _maybeRefetchFullHistory and this pane's own
1184
+ // _sendResize(): a detached session's own window already owns its PTY
1185
+ // size and scrollback, so this pane has nothing of its own to reconcile.
1186
+ if (this.detachedSessions?.has(this.sessionId)) return;
1187
+ const active = this.terminal.buffer.active;
1188
+ if (active.type !== 'normal' || active.viewportY !== 0) return;
1189
+ // Momentum scrolling fires this dozens of times per flick, so cooldown
1190
+ // rather than latch; a pull that could only have downgraded the pane
1191
+ // waits far longer.
1192
+ const cooldown = this._historyPullUseless ? 60000 : 4000;
1193
+ const now = Date.now();
1194
+ if (now - this._historyPullAt < cooldown) return;
1195
+ this._historyPullAt = now;
1196
+ this._bufferLoading = true;
1197
+ void this._runLoad('history', () => this._pullHistory());
1198
+ }
1199
+
1200
+ // Pulls a BOUNDED window of tmux's full history (the same TERMINAL_TAIL_SIZE
1201
+ // a tab switch loads, so a multi-megabyte capture never lands on xterm's
1202
+ // main thread) and replays it under the reader's current place. Holds the
1203
+ // single-flight flag across the fetch AND the replay, like _loadBuffer().
1204
+ async _pullHistory() {
1205
+ this._bufferLoading = true;
1206
+ if (this._destroyed) {
1207
+ this._endBufferLoad();
1208
+ return;
1209
+ }
1210
+ this._loadRunning = true;
1211
+ let replayed = false;
1212
+ let capturedAt = 0;
1213
+ // Two budgets on one signal. The request itself gets the primary pane's
1214
+ // (CodemanFetchDeadline, constants.js): live output is not held while it
1215
+ // runs, but the single-flight flag is, so a coalesced `{t:'r'}` refresh and
1216
+ // the marker owed by a close (_onSocketClosed()) both wait for it, at worst
1217
+ // for that whole budget. Once the headers land live output IS held, so the
1218
+ // body read gets the short one instead: a body that hangs would otherwise
1219
+ // freeze the pane for the long budget. Aborting lands in the catch below,
1220
+ // which releases the flag and the queue. AbortSignal.timeout() alone cannot
1221
+ // be re-armed, hence the controller; without AbortController the pull
1222
+ // simply has no deadline.
1223
+ const controller = global.AbortController ? new global.AbortController() : null;
1224
+ this._loadAbort = controller;
1225
+ let abortTimer = null;
1226
+ const armDeadline = (ms) => {
1227
+ if (!controller) return;
1228
+ clearTimeout(abortTimer);
1229
+ abortTimer = setTimeout(() => controller.abort(), ms);
1230
+ };
1231
+ try {
1232
+ armDeadline(global.CodemanFetchDeadline?.terminalFetchDeadlineMs?.({ full: true }) ?? HISTORY_PULL_TIMEOUT_MS);
1233
+ const res = await fetch(
1234
+ `/api/sessions/${this.sessionId}/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}${this._historyLinesQuery()}`,
1235
+ { signal: controller?.signal }
1236
+ );
1237
+ armDeadline(HISTORY_PULL_TIMEOUT_MS);
1238
+ // The cutoff below is the response's arrival, the same `since` rule the
1239
+ // primary pane uses (_finishBufferLoad). It is a client clock standing in
1240
+ // for the instant tmux took the capture, which lies somewhere in the
1241
+ // round trip, so a frame in that window can be lost or doubled. Bounded
1242
+ // by one round trip and not closable without a server-side capture time.
1243
+ capturedAt = performance.now();
1244
+ // Opened only now: a frame from before the response is either replaced by
1245
+ // the capture or written unchanged, so holding it for the round trip
1246
+ // would buy nothing and freeze the pane for as long as the fetch took.
1247
+ this._openLiveQueue();
1248
+ const payload = (await res.json())?.data;
1249
+ clearTimeout(abortTimer);
1250
+ const buffer = payload?.terminalBuffer;
1251
+ const term = this.terminal;
1252
+ if (!buffer || !term || this._destroyed) return;
1253
+ const rowsBefore = term.buffer.active.length;
1254
+ const rowsIncoming = global.app?._estimateReplayRows?.(buffer, term.cols) ?? buffer.split('\n').length;
1255
+ // xterm keeps at most `scrollback + rows` rows while tmux keeps far more
1256
+ // lines, so a window of short lines can carry more rows than this pane
1257
+ // can ever hold, and `rowsIncoming <= rowsBefore` would never come true.
1258
+ const scrollbackCap = term.options?.scrollback || 0;
1259
+ const paneFull = scrollbackCap > 0 && rowsBefore >= scrollbackCap + term.rows;
1260
+ // Nothing to gain (this also covers a downgrade, which would delete
1261
+ // history mid-scroll), and a reset+rewrite would jump the viewport. An
1262
+ // untruncated window IS all of tmux's history and the next burst can add
1263
+ // more, so keep the 4 s cooldown. A truncated window can never reach past
1264
+ // what the pane shows, and every ask costs the server a capture-pane of
1265
+ // the whole history (`tail` is cut after it): back off to 60 s, as the
1266
+ // primary pane does (app.js _maybeRefetchFullHistory). A full pane backs
1267
+ // off too, since no window can ever fit in it.
1268
+ if (rowsIncoming <= rowsBefore || paneFull) {
1269
+ if (payload.truncated || paneFull) this._historyPullUseless = true;
1270
+ return;
1271
+ }
1272
+ this._historyPullUseless = false;
1273
+ term.write('\x1bc');
1274
+ this._overflowRows = 0; // the reset leaves nothing above the screen
1275
+ replayed = true;
1276
+ if (this._wsClosed) this._markerOwed = true;
1277
+ await writeChunked(
1278
+ term,
1279
+ buffer,
1280
+ () => this._destroyed,
1281
+ (cancel) => (this._cancelReplay = cancel)
1282
+ );
1283
+ if (this._destroyed || !this.terminal) return;
1284
+ // xterm parses asynchronously: an empty write's callback fires only
1285
+ // after everything before it, so the row count below is the settled one.
1286
+ await new Promise((resolve) => this.terminal.write('', resolve));
1287
+ if (this._destroyed || !this.terminal) return;
1288
+ // The replay grew the buffer UPWARD, so what was row 0 is now `delta`
1289
+ // rows down; land there and the recovered history sits above it.
1290
+ const delta = this.terminal.buffer.active.length - rowsBefore;
1291
+ if (delta > 0) this.terminal.scrollToLine(delta);
1292
+ else this.terminal.scrollToTop();
1293
+ } catch {
1294
+ /* Best-effort: live output keeps arriving whatever happens here. */
1295
+ } finally {
1296
+ clearTimeout(abortTimer);
1297
+ this._loadAbort = null;
1298
+ this._loadRunning = false;
1299
+ // After a replay, only frames that arrived after the capture are news;
1300
+ // earlier ones are already in it. With no replay, every held frame is.
1301
+ this._flushLiveQueue(replayed ? capturedAt : 0);
1302
+ // Settled after the queue flush so the marker is the last thing on
1303
+ // screen: a close during the pull wrote nothing (_onSocketClosed() defers
1304
+ // it while a load runs), and a replay's own `\x1bc` (flagged above) wipes
1305
+ // one written before it, which would paint a fresh, current-looking
1306
+ // history while onData keeps silently dropping every keystroke on the
1307
+ // dead socket. With a trailing refresh pending (_endBufferLoad) the marker
1308
+ // is left to that refresh, which writes it below its own replay.
1309
+ this._stampMarkerIfOwed();
1310
+ this._endBufferLoad();
1311
+ }
1312
+ }
1313
+
1314
+ // A bounded load's `lines=` (grid tiles): tmux history beyond what this
1315
+ // xterm keeps (its scrollback plus the screen) would only be captured to be
1316
+ // thrown away, and a full capture is synchronous work on the server, about
1317
+ // 0.7 s for a 30k-line history. Unbounded panes (the split's Pane B) ask
1318
+ // for everything, as before.
1319
+ _historyLinesQuery() {
1320
+ if (!this.boundedLoad || !Number.isFinite(this.scrollback)) return '';
1321
+ return `&lines=${this.scrollback + (this.terminal?.rows || 0)}`;
1322
+ }
1323
+
1324
+ // The refresh path (`{t:'r'}`, `{t:'c'}`, a reconnect): fetch, then reset
1325
+ // in-stream and replay (_loadBuffer). Two refresh frames in a row must not
1326
+ // start two concurrent replays, each resetting the terminal under the
1327
+ // other's chunked write. A refresh that arrives mid-replay is COALESCED
1328
+ // into one trailing re-run rather than ignored: the in-flight fetch may
1329
+ // predate the drop the new frame is reporting, and no further frame is
1330
+ // coming to correct stale content.
1331
+ _refreshBuffer() {
1332
+ if (this._bufferLoading) {
1333
+ this._bufferRefreshPending = true;
1334
+ return;
1335
+ }
1336
+ void this._loadBuffer({ refresh: true });
1337
+ }
1338
+
1339
+ // Local reflow only, no PTY resize frame. Split out so a divider drag
1340
+ // can reflow the panes at the browser's paint rate (rAF) while sending
1341
+ // the actual `{t:'z'}` resize once, at drag end, matching the primary
1342
+ // pane's own convention (throttledResize in terminal-ui.js).
1343
+ localFit() {
1344
+ if (!this.fitAddon) return;
1345
+ const before = this.terminal?.buffer?.active?.baseY || 0;
1346
+ this.fitAddon.fit();
1347
+ this._noteResizeRows(before);
1348
+ }
1349
+
1350
+ // Reflow to the container and tell the PTY, as one step: the xterm and the
1351
+ // PTY must never disagree about size (#464), and a font change is a size
1352
+ // change too, so the font setters call this rather than localFit().
1353
+ // `force` resends an unchanged size and asks the server to apply it anyway
1354
+ // (Redraw, restoreTerminalSize). Returns whether a resize went out.
1355
+ fit({ force = false } = {}) {
1356
+ this.localFit();
1357
+ return this._sendResize({ force });
1358
+ }
1359
+
1360
+ // Returns true only once a `{t:'z'}` frame was sent, false at every early
1361
+ // exit, so Redraw can say when nothing reached the PTY.
1362
+ _sendResize({ force = false } = {}) {
1363
+ if (!this._wsReady || !this.fitAddon || !this.terminal) return false;
1364
+ // One PTY cannot hold two sizes (mirrors sendResize's own
1365
+ // detachedElsewhere yield in terminal-ui.js): the session got detached
1366
+ // to its own window AFTER this pane was opened, so its own window now
1367
+ // owns the PTY's size and this pane must stand aside.
1368
+ if (this.detachedSessions?.has(this.sessionId)) return false;
1369
+ // A hidden pane (a web tab over it, a zoomed neighbour) measures NaN, and
1370
+ // fit() then leaves the xterm alone: there is no size worth reporting.
1371
+ const dims = this.fitAddon.proposeDimensions();
1372
+ if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) return false;
1373
+ // Report what the xterm actually holds, so the PTY gets exactly the size
1374
+ // the pane renders at. Unclamped, unlike the primary pane's 40x10 floor:
1375
+ // a floor would misreport the split's Pane B at its divider's reachable
1376
+ // 20% position (about 28 columns) and wrap output wrongly, and a floored
1377
+ // xterm would be wider than its container. The server enforces
1378
+ // its own valid range ([1,500]/[1,200] in ws-routes.ts).
1379
+ const cols = this.terminal.cols;
1380
+ const rows = this.terminal.rows;
1381
+ const last = this._lastSentDims;
1382
+ if (!force && last && last.cols === cols && last.rows === rows) return false;
1383
+ // `f` is the primary pane's forced resize (sendResize, terminal-ui.js):
1384
+ // Session.resize (session.ts) otherwise skips a size equal to the one it
1385
+ // last applied, so without it a forced resend reached the server and did
1386
+ // nothing there (no tmux resize-window, no PTY resize).
1387
+ const msg = { t: 'z', c: cols, r: rows, v: 'desktop' };
1388
+ if (force) msg.f = true;
1389
+ try {
1390
+ this.ws.send(JSON.stringify(msg));
1391
+ } catch {
1392
+ return false; // nothing went out, so nothing is recorded as sent
1393
+ }
1394
+ this._lastSentDims = { cols, rows };
1395
+ return true;
1396
+ }
1397
+
1398
+ // The session's PTY is new: a tile can connect before its session has a
1399
+ // pane (one Run started while the grid is open joins first), and the
1400
+ // server drops a resize that arrives with no PTY, then spawns at its own
1401
+ // default size. Forget what was sent, so the size goes out now, or with
1402
+ // the next fit() when this tile is hidden right now (a zoomed neighbour):
1403
+ // _sendResize() returns before recording anything it did not send.
1404
+ paneStarted() {
1405
+ this._lastSentDims = null;
1406
+ this._sendResize();
1407
+ }
1408
+
1409
+ // The geometry the PTY actually holds (`{t:'zc'}`, the server's answer to
1410
+ // every resize). A PTY and a terminal that disagree on WIDTH render
1411
+ // garbled, so a different column count is adopted; rows stay local, as in
1412
+ // the primary pane (_onPtyGeometryReport in terminal-ui.js, #464). The
1413
+ // pure verdict is the primary's too (reconcilePtyGeometry, constants.js).
1414
+ _onPtyGeometryReport(cols, rows) {
1415
+ const terminal = this.terminal;
1416
+ if (!terminal) return;
1417
+ const verdict = global.CodemanTerminalGeometry?.reconcilePtyGeometry?.(
1418
+ { cols: terminal.cols, rows: terminal.rows },
1419
+ { cols, rows }
1420
+ );
1421
+ if (!verdict?.adopt) return;
1422
+ const before = terminal.buffer?.active?.baseY || 0;
1423
+ terminal.resize(verdict.cols, terminal.rows);
1424
+ this._noteResizeRows(before); // a column change reflows rows above the screen
1425
+ this._lastSentDims = { cols: verdict.cols, rows: terminal.rows };
1426
+ }
1427
+
1428
+ destroy() {
1429
+ this._destroyed = true;
1430
+ // Anything still queued for this session stays in the app's queue and is
1431
+ // delivered over HTTP by the redelivery sweep, so closing the pane mid-
1432
+ // keystroke loses nothing.
1433
+ clearTimeout(this._reconnectTimer);
1434
+ this._reconnectTimer = null;
1435
+ // A load still fetching would otherwise hold the owner's queue (and the
1436
+ // server's attention) for a pane nobody can see any more.
1437
+ try {
1438
+ this._loadAbort?.abort();
1439
+ } catch {
1440
+ /* Already settled. */
1441
+ }
1442
+ this._loadAbort = null;
1443
+ // Likewise a replay still parsing: the xterm is disposed below, so the
1444
+ // write callback it waits for would never come.
1445
+ this._cancelReplay?.();
1446
+ this._cancelReplay = null;
1447
+ if (this._onWheel) {
1448
+ this.mountEl?.removeEventListener('wheel', this._onWheel, { capture: true });
1449
+ this._onWheel = null;
1450
+ }
1451
+ if (this._onClick) {
1452
+ this.mountEl?.removeEventListener('click', this._onClick);
1453
+ this._onClick = null;
1454
+ }
1455
+ // A disposed xterm never runs its write callbacks, and a pending
1456
+ // recovery would refresh a pane nobody can see.
1457
+ this._resetLiveFlow();
1458
+ // Page keys still waiting for their flush go nowhere: the pane is gone.
1459
+ clearTimeout(this._scrollFlushTimer);
1460
+ this._scrollFlushTimer = null;
1461
+ this._scrollBytes = '';
1462
+ this._pageKeyPending = 0;
1463
+ this._detachSocket();
1464
+ if (this._onFocusIn) {
1465
+ this.terminal?.textarea?.removeEventListener('focus', this._onFocusIn);
1466
+ this._onFocusIn = null;
1467
+ }
1468
+ // Before dispose(): puts xterm's own textarea diff back and takes the
1469
+ // controller's listeners off the textarea; its pending timers are inert
1470
+ // once it is destroyed.
1471
+ this._destroyKeyCode229Recovery();
1472
+ // A destroyed pane cannot hold the keyboard: shortcuts fall back to the
1473
+ // primary terminal (_focusedPane also skips a destroyed tile on its own).
1474
+ if (global.app?._focusedTile === this) global.app._noteFocusedTile?.(null);
1475
+ if (this.terminal) {
1476
+ this.terminal.dispose();
1477
+ this.terminal = null;
1478
+ }
1479
+ this.fitAddon = null;
1480
+ }
1481
+ }
1482
+
1483
+ // Code units of live output a pane lets sit unparsed in its xterm (or held
1484
+ // behind a replay) before it drops a frame and recaptures (_writeLive). Not
1485
+ // the primary pane's 128 KB: that caps its own rAF-paced queues, about two
1486
+ // frames of them, while here xterm itself is the pacer, a burst normally
1487
+ // parses within a frame or two, and a tight cap would trip on ordinary
1488
+ // bursts and blank-and-reload the tile over and over. A few MB keeps a flood
1489
+ // far below xterm's 50M code-unit throw and bounds each tile's memory.
1490
+ TerminalTile.LIVE_BACKLOG_BUDGET = 4 * 1024 * 1024;
1491
+
1492
+ // The marker a pane writes when its socket drops: a transient drop says it is
1493
+ // reconnecting; a permanent stop says why, keyed by close code. All start
1494
+ // with `[disconnected` so a reader (and a test) can tell any of them apart
1495
+ // from session output.
1496
+ TerminalTile.MARKER_RECONNECTING = '[disconnected, reconnecting…]';
1497
+ TerminalTile.STOP_MARKERS = {
1498
+ 4003: '[disconnected: the server refused this connection]',
1499
+ 4004: '[disconnected: the session ended]',
1500
+ 4009: '[disconnected: the session ended]',
1501
+ 4010: '[disconnected: another connection took over this pane]',
1502
+ };
1503
+
1504
+ /**
1505
+ * ONE queue for every capture a set of tiles fetches (`GET
1506
+ * /api/sessions/:id/terminal`): the initial load, the refresh after a
1507
+ * reconnect, a server `{t:'r'}` refresh and the shell history pull. Each
1508
+ * capture runs synchronous tmux calls on the server, so N of them at once do
1509
+ * not run in parallel, they stall every WebSocket and SSE stream on it back to
1510
+ * back. After a deploy restart all N tiles reopen within the same second; this
1511
+ * drains their refreshes one at a time.
1512
+ *
1513
+ * Concurrency 1. Next up is a history pull (the user is waiting on it), then
1514
+ * the lowest `rank(tile)` (the grid ranks the focused tile first, then reading
1515
+ * order), then arrival order. A destroyed tile's entries are dropped, never run.
1516
+ * DOM-free, so the grid owns the policy and tests drive it directly.
1517
+ */
1518
+ class TileLoadQueue {
1519
+ /**
1520
+ * @param {{rank?: (tile: object) => number, onChange?: (tile: object, state: 'queued'|'running'|'idle') => void}} [opts]
1521
+ */
1522
+ constructor(opts = {}) {
1523
+ this._rank = typeof opts.rank === 'function' ? opts.rank : () => 0;
1524
+ this._onChange = typeof opts.onChange === 'function' ? opts.onChange : null;
1525
+ this._pending = [];
1526
+ this._active = null;
1527
+ this._seq = 0;
1528
+ }
1529
+
1530
+ /** The `scheduleLoad` a TerminalTile takes. Resolves once `run` finished or was dropped; never rejects. */
1531
+ schedule(tile, kind, run) {
1532
+ return new Promise((resolve) => {
1533
+ this._pending.push({ tile, kind, run, resolve, seq: this._seq++ });
1534
+ this._notify(tile, 'queued');
1535
+ this._pump();
1536
+ });
1537
+ }
1538
+
1539
+ /** Drops every load still waiting for `tile` (the running one, if any, finishes on its own). */
1540
+ drop(tile) {
1541
+ const keep = [];
1542
+ for (const entry of this._pending) {
1543
+ if (entry.tile === tile) entry.resolve();
1544
+ else keep.push(entry);
1545
+ }
1546
+ this._pending = keep;
1547
+ if (this._active?.tile !== tile) this._notify(tile, 'idle');
1548
+ }
1549
+
1550
+ /** How many loads are waiting (not counting the running one). */
1551
+ get size() {
1552
+ return this._pending.length;
1553
+ }
1554
+
1555
+ /** The tile whose load is running, or null. */
1556
+ get activeTile() {
1557
+ return this._active?.tile ?? null;
1558
+ }
1559
+
1560
+ _notify(tile, state) {
1561
+ try {
1562
+ this._onChange?.(tile, state);
1563
+ } catch {
1564
+ /* A display callback never stops the queue. */
1565
+ }
1566
+ }
1567
+
1568
+ _takeNext() {
1569
+ let best = -1;
1570
+ let bestKey = null;
1571
+ for (let i = 0; i < this._pending.length; i++) {
1572
+ const entry = this._pending[i];
1573
+ if (entry.tile?._destroyed) continue;
1574
+ const key = [entry.kind === 'history' ? 0 : 1, this._rank(entry.tile), entry.seq];
1575
+ const order = bestKey ? key[0] - bestKey[0] || key[1] - bestKey[1] || key[2] - bestKey[2] : -1;
1576
+ if (order < 0) {
1577
+ best = i;
1578
+ bestKey = key;
1579
+ }
1580
+ }
1581
+ // Destroyed tiles' entries go now, resolved but never run.
1582
+ const dropped = this._pending.filter((entry) => entry.tile?._destroyed);
1583
+ const next = best === -1 ? null : this._pending[best];
1584
+ this._pending = this._pending.filter((entry) => entry !== next && !entry.tile?._destroyed);
1585
+ for (const entry of dropped) entry.resolve();
1586
+ return next;
1587
+ }
1588
+
1589
+ async _pump() {
1590
+ if (this._active) return;
1591
+ const entry = this._takeNext();
1592
+ if (!entry) return;
1593
+ this._active = entry;
1594
+ this._notify(entry.tile, 'running');
1595
+ try {
1596
+ await entry.run();
1597
+ } catch {
1598
+ /* A load settles its own failure; the queue only moves on. */
1599
+ } finally {
1600
+ this._active = null;
1601
+ const stillQueued = this._pending.some((e) => e.tile === entry.tile);
1602
+ this._notify(entry.tile, stillQueued ? 'queued' : 'idle');
1603
+ entry.resolve();
1604
+ void this._pump();
1605
+ }
1606
+ }
1607
+ }
1608
+
1609
+ global.TerminalTile = TerminalTile;
1610
+ global.TileLoadQueue = TileLoadQueue;
1611
+ })(window);