aicodeman 1.49.0 → 1.50.1

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 (324) hide show
  1. package/README.md +30 -4
  2. package/dist/cli-install-runner.d.ts +112 -0
  3. package/dist/cli-install-runner.d.ts.map +1 -0
  4. package/dist/cli-install-runner.js +289 -0
  5. package/dist/cli-install-runner.js.map +1 -0
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +2 -2
  8. package/dist/cli.js.map +1 -1
  9. package/dist/config/attachment-guard.d.ts +11 -0
  10. package/dist/config/attachment-guard.d.ts.map +1 -1
  11. package/dist/config/attachment-guard.js +21 -1
  12. package/dist/config/attachment-guard.js.map +1 -1
  13. package/dist/config/local-model-catalog.d.ts +188 -0
  14. package/dist/config/local-model-catalog.d.ts.map +1 -0
  15. package/dist/config/local-model-catalog.js +556 -0
  16. package/dist/config/local-model-catalog.js.map +1 -0
  17. package/dist/config-backup.js +1 -1
  18. package/dist/config-backup.js.map +1 -1
  19. package/dist/custom-model-hosts-writer.d.ts +50 -0
  20. package/dist/custom-model-hosts-writer.d.ts.map +1 -0
  21. package/dist/custom-model-hosts-writer.js +110 -0
  22. package/dist/custom-model-hosts-writer.js.map +1 -0
  23. package/dist/git-clone.d.ts.map +1 -1
  24. package/dist/git-clone.js +21 -1
  25. package/dist/git-clone.js.map +1 -1
  26. package/dist/git-fetch.d.ts.map +1 -1
  27. package/dist/git-fetch.js +6 -0
  28. package/dist/git-fetch.js.map +1 -1
  29. package/dist/git-workspace-status.d.ts.map +1 -1
  30. package/dist/git-workspace-status.js +4 -0
  31. package/dist/git-workspace-status.js.map +1 -1
  32. package/dist/git-worktrees.d.ts.map +1 -1
  33. package/dist/git-worktrees.js +6 -0
  34. package/dist/git-worktrees.js.map +1 -1
  35. package/dist/hooks-config.d.ts +15 -3
  36. package/dist/hooks-config.d.ts.map +1 -1
  37. package/dist/hooks-config.js +108 -4
  38. package/dist/hooks-config.js.map +1 -1
  39. package/dist/live-worktree.d.ts +73 -15
  40. package/dist/live-worktree.d.ts.map +1 -1
  41. package/dist/live-worktree.js +200 -32
  42. package/dist/live-worktree.js.map +1 -1
  43. package/dist/local-model/connect.d.ts +155 -0
  44. package/dist/local-model/connect.d.ts.map +1 -0
  45. package/dist/local-model/connect.js +243 -0
  46. package/dist/local-model/connect.js.map +1 -0
  47. package/dist/local-model/developer-tools.d.ts +45 -0
  48. package/dist/local-model/developer-tools.d.ts.map +1 -0
  49. package/dist/local-model/developer-tools.js +105 -0
  50. package/dist/local-model/developer-tools.js.map +1 -0
  51. package/dist/local-model/format.d.ts +39 -0
  52. package/dist/local-model/format.d.ts.map +1 -0
  53. package/dist/local-model/format.js +48 -0
  54. package/dist/local-model/format.js.map +1 -0
  55. package/dist/local-model/hardware.d.ts +125 -0
  56. package/dist/local-model/hardware.d.ts.map +1 -0
  57. package/dist/local-model/hardware.js +336 -0
  58. package/dist/local-model/hardware.js.map +1 -0
  59. package/dist/local-model/harness-facts.d.ts +77 -0
  60. package/dist/local-model/harness-facts.d.ts.map +1 -0
  61. package/dist/local-model/harness-facts.js +145 -0
  62. package/dist/local-model/harness-facts.js.map +1 -0
  63. package/dist/local-model/install-job.d.ts +431 -0
  64. package/dist/local-model/install-job.d.ts.map +1 -0
  65. package/dist/local-model/install-job.js +1822 -0
  66. package/dist/local-model/install-job.js.map +1 -0
  67. package/dist/local-model/ollama-client.d.ts +216 -0
  68. package/dist/local-model/ollama-client.d.ts.map +1 -0
  69. package/dist/local-model/ollama-client.js +636 -0
  70. package/dist/local-model/ollama-client.js.map +1 -0
  71. package/dist/local-model/paths.d.ts +64 -0
  72. package/dist/local-model/paths.d.ts.map +1 -0
  73. package/dist/local-model/paths.js +75 -0
  74. package/dist/local-model/paths.js.map +1 -0
  75. package/dist/local-model/recommend.d.ts +118 -0
  76. package/dist/local-model/recommend.d.ts.map +1 -0
  77. package/dist/local-model/recommend.js +430 -0
  78. package/dist/local-model/recommend.js.map +1 -0
  79. package/dist/local-model/runtime.d.ts +339 -0
  80. package/dist/local-model/runtime.d.ts.map +1 -0
  81. package/dist/local-model/runtime.js +1240 -0
  82. package/dist/local-model/runtime.js.map +1 -0
  83. package/dist/local-model/state-store.d.ts +45 -0
  84. package/dist/local-model/state-store.d.ts.map +1 -0
  85. package/dist/local-model/state-store.js +261 -0
  86. package/dist/local-model/state-store.js.map +1 -0
  87. package/dist/readmymind-collectors.d.ts.map +1 -1
  88. package/dist/readmymind-collectors.js +4 -0
  89. package/dist/readmymind-collectors.js.map +1 -1
  90. package/dist/reboot-restore.d.ts +3 -1
  91. package/dist/reboot-restore.d.ts.map +1 -1
  92. package/dist/reboot-restore.js.map +1 -1
  93. package/dist/session.d.ts +29 -7
  94. package/dist/session.d.ts.map +1 -1
  95. package/dist/session.js +63 -10
  96. package/dist/session.js.map +1 -1
  97. package/dist/types/common.d.ts +5 -0
  98. package/dist/types/common.d.ts.map +1 -1
  99. package/dist/types/index.d.ts +4 -0
  100. package/dist/types/index.d.ts.map +1 -1
  101. package/dist/types/index.js +4 -0
  102. package/dist/types/index.js.map +1 -1
  103. package/dist/types/local-model-install.d.ts +533 -0
  104. package/dist/types/local-model-install.d.ts.map +1 -0
  105. package/dist/types/local-model-install.js +169 -0
  106. package/dist/types/local-model-install.js.map +1 -0
  107. package/dist/types/local-model.d.ts +551 -0
  108. package/dist/types/local-model.d.ts.map +1 -0
  109. package/dist/types/local-model.js +115 -0
  110. package/dist/types/local-model.js.map +1 -0
  111. package/dist/types/session.d.ts +17 -6
  112. package/dist/types/session.d.ts.map +1 -1
  113. package/dist/types/session.js.map +1 -1
  114. package/dist/utils/cli-executable-resolver.d.ts +18 -0
  115. package/dist/utils/cli-executable-resolver.d.ts.map +1 -1
  116. package/dist/utils/cli-executable-resolver.js +34 -2
  117. package/dist/utils/cli-executable-resolver.js.map +1 -1
  118. package/dist/utils/git-availability.d.ts +65 -0
  119. package/dist/utils/git-availability.d.ts.map +1 -0
  120. package/dist/utils/git-availability.js +134 -0
  121. package/dist/utils/git-availability.js.map +1 -0
  122. package/dist/web/agent-skill-default-migration.d.ts +60 -0
  123. package/dist/web/agent-skill-default-migration.d.ts.map +1 -0
  124. package/dist/web/agent-skill-default-migration.js +97 -0
  125. package/dist/web/agent-skill-default-migration.js.map +1 -0
  126. package/dist/web/approval-inbox.d.ts +10 -0
  127. package/dist/web/approval-inbox.d.ts.map +1 -1
  128. package/dist/web/approval-inbox.js +15 -0
  129. package/dist/web/approval-inbox.js.map +1 -1
  130. package/dist/web/case-state-sync.d.ts +28 -0
  131. package/dist/web/case-state-sync.d.ts.map +1 -0
  132. package/dist/web/case-state-sync.js +41 -0
  133. package/dist/web/case-state-sync.js.map +1 -0
  134. package/dist/web/ports/config-port.d.ts +1 -1
  135. package/dist/web/ports/config-port.d.ts.map +1 -1
  136. package/dist/web/public/admin-ui.js.gz +0 -0
  137. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  138. package/dist/web/public/{app.9ea37070.js → app.07398d90.js} +1 -1
  139. package/dist/web/public/app.07398d90.js.br +0 -0
  140. package/dist/web/public/app.07398d90.js.gz +0 -0
  141. package/dist/web/public/approvals-ui.js.gz +0 -0
  142. package/dist/web/public/constants.782170e1.js.gz +0 -0
  143. package/dist/web/public/cron-ui.js.gz +0 -0
  144. package/dist/web/public/edit-history-ui.js.gz +0 -0
  145. package/dist/web/public/entrance-animations.js.gz +0 -0
  146. package/dist/web/public/foreign-sessions.js.gz +0 -0
  147. package/dist/web/public/git-status-ui.js.gz +0 -0
  148. package/dist/web/public/header-divider.eb2d2463.js.gz +0 -0
  149. package/dist/web/public/home-sessions.js +38 -18
  150. package/dist/web/public/home-sessions.js.br +0 -0
  151. package/dist/web/public/home-sessions.js.gz +0 -0
  152. package/dist/web/public/host-wake-ui.js.gz +0 -0
  153. package/dist/web/public/{i18n.a5e82c95.js → i18n.519d025e.js} +2 -2
  154. package/dist/web/public/i18n.519d025e.js.br +0 -0
  155. package/dist/web/public/i18n.519d025e.js.gz +0 -0
  156. package/dist/web/public/image-input.a5d0f8f3.js.gz +0 -0
  157. package/dist/web/public/index.html +88 -13
  158. package/dist/web/public/index.html.br +0 -0
  159. package/dist/web/public/index.html.gz +0 -0
  160. package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
  161. package/dist/web/public/{keyboard-accessory.b941676c.js → keyboard-accessory.0800fc44.js} +160 -2
  162. package/dist/web/public/keyboard-accessory.0800fc44.js.br +0 -0
  163. package/dist/web/public/keyboard-accessory.0800fc44.js.gz +0 -0
  164. package/dist/web/public/local-model-ui.js +1735 -0
  165. package/dist/web/public/local-model-ui.js.br +0 -0
  166. package/dist/web/public/local-model-ui.js.gz +0 -0
  167. package/dist/web/public/mobile-handlers.f7c3f692.js.gz +0 -0
  168. package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
  169. package/dist/web/public/mobile-overview.js +30 -14
  170. package/dist/web/public/mobile-overview.js.br +0 -0
  171. package/dist/web/public/mobile-overview.js.gz +0 -0
  172. package/dist/web/public/mobile.4dfd5c55.css +1 -0
  173. package/dist/web/public/mobile.4dfd5c55.css.br +0 -0
  174. package/dist/web/public/mobile.4dfd5c55.css.gz +0 -0
  175. package/dist/web/public/notification-manager.feb82c04.js.gz +0 -0
  176. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  177. package/dist/web/public/{panels-ui.8bcd4473.js → panels-ui.9ba2683e.js} +100 -98
  178. package/dist/web/public/panels-ui.9ba2683e.js.br +0 -0
  179. package/dist/web/public/panels-ui.9ba2683e.js.gz +0 -0
  180. package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
  181. package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
  182. package/dist/web/public/readmymind-ui.js.gz +0 -0
  183. package/dist/web/public/reboot-restore-ui.js +2 -0
  184. package/dist/web/public/reboot-restore-ui.js.br +0 -0
  185. package/dist/web/public/reboot-restore-ui.js.gz +0 -0
  186. package/dist/web/public/respawn-ui.304ba0d4.js.gz +0 -0
  187. package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
  188. package/dist/web/public/session-lineage.js.gz +0 -0
  189. package/dist/web/public/{session-ui.a7c8c095.js → session-ui.8f300b14.js} +21 -21
  190. package/dist/web/public/session-ui.8f300b14.js.br +0 -0
  191. package/dist/web/public/session-ui.8f300b14.js.gz +0 -0
  192. package/dist/web/public/{settings-ui.18f92052.js → settings-ui.8b37cf07.js} +14 -14
  193. package/dist/web/public/settings-ui.8b37cf07.js.br +0 -0
  194. package/dist/web/public/settings-ui.8b37cf07.js.gz +0 -0
  195. package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
  196. package/dist/web/public/spreadsheet-preview.75c751de.js.gz +0 -0
  197. package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
  198. package/dist/web/public/styles.21b93520.css +1 -0
  199. package/dist/web/public/styles.21b93520.css.br +0 -0
  200. package/dist/web/public/styles.21b93520.css.gz +0 -0
  201. package/dist/web/public/subagent-windows.07277a58.js.gz +0 -0
  202. package/dist/web/public/sw.js +2 -2
  203. package/dist/web/public/sw.js.br +0 -0
  204. package/dist/web/public/sw.js.gz +0 -0
  205. package/dist/web/public/tab-layout-browser.2d6189f7.js.gz +0 -0
  206. package/dist/web/public/tab-rail-resize.b5cdceaf.js.gz +0 -0
  207. package/dist/web/public/terminal-keycode229-recovery.98843069.js.gz +0 -0
  208. package/dist/web/public/terminal-split.js.gz +0 -0
  209. package/dist/web/public/terminal-tile.js.gz +0 -0
  210. package/dist/web/public/{terminal-ui.a7883640.js → terminal-ui.f92eae28.js} +2 -2
  211. package/dist/web/public/terminal-ui.f92eae28.js.br +0 -0
  212. package/dist/web/public/terminal-ui.f92eae28.js.gz +0 -0
  213. package/dist/web/public/tile-grid.js.gz +0 -0
  214. package/dist/web/public/ultracode-panel.js.gz +0 -0
  215. package/dist/web/public/ultracode-windows.js.gz +0 -0
  216. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  217. package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
  218. package/dist/web/public/vendor/fflate.min.js.gz +0 -0
  219. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  220. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  221. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  222. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  223. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  224. package/dist/web/public/vendor/xterm-predictive-echo.276b11d9.js.gz +0 -0
  225. package/dist/web/public/vendor/xterm-zerolag-input.1be42307.js.gz +0 -0
  226. package/dist/web/public/vendor/xterm.css.gz +0 -0
  227. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  228. package/dist/web/public/{voice-input.2342c37b.js → voice-input.d0580528.js} +232 -137
  229. package/dist/web/public/voice-input.d0580528.js.br +0 -0
  230. package/dist/web/public/voice-input.d0580528.js.gz +0 -0
  231. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  232. package/dist/web/public/webview-tabs.js.gz +0 -0
  233. package/dist/web/public/whats-new.json +9 -9
  234. package/dist/web/repo-status.d.ts.map +1 -1
  235. package/dist/web/repo-status.js +4 -0
  236. package/dist/web/repo-status.js.map +1 -1
  237. package/dist/web/route-helpers.d.ts +29 -0
  238. package/dist/web/route-helpers.d.ts.map +1 -1
  239. package/dist/web/route-helpers.js +37 -0
  240. package/dist/web/route-helpers.js.map +1 -1
  241. package/dist/web/routes/approval-routes.d.ts.map +1 -1
  242. package/dist/web/routes/approval-routes.js +3 -2
  243. package/dist/web/routes/approval-routes.js.map +1 -1
  244. package/dist/web/routes/case-routes.d.ts.map +1 -1
  245. package/dist/web/routes/case-routes.js +31 -5
  246. package/dist/web/routes/case-routes.js.map +1 -1
  247. package/dist/web/routes/cli-registry-routes.d.ts +1 -27
  248. package/dist/web/routes/cli-registry-routes.d.ts.map +1 -1
  249. package/dist/web/routes/cli-registry-routes.js +11 -202
  250. package/dist/web/routes/cli-registry-routes.js.map +1 -1
  251. package/dist/web/routes/custom-model-routes.d.ts +15 -0
  252. package/dist/web/routes/custom-model-routes.d.ts.map +1 -1
  253. package/dist/web/routes/custom-model-routes.js +114 -33
  254. package/dist/web/routes/custom-model-routes.js.map +1 -1
  255. package/dist/web/routes/file-routes.d.ts +4 -2
  256. package/dist/web/routes/file-routes.d.ts.map +1 -1
  257. package/dist/web/routes/file-routes.js +160 -24
  258. package/dist/web/routes/file-routes.js.map +1 -1
  259. package/dist/web/routes/html-view-routes.d.ts.map +1 -1
  260. package/dist/web/routes/html-view-routes.js +12 -3
  261. package/dist/web/routes/html-view-routes.js.map +1 -1
  262. package/dist/web/routes/index.d.ts +1 -0
  263. package/dist/web/routes/index.d.ts.map +1 -1
  264. package/dist/web/routes/index.js +1 -0
  265. package/dist/web/routes/index.js.map +1 -1
  266. package/dist/web/routes/local-model-routes.d.ts +103 -0
  267. package/dist/web/routes/local-model-routes.d.ts.map +1 -0
  268. package/dist/web/routes/local-model-routes.js +210 -0
  269. package/dist/web/routes/local-model-routes.js.map +1 -0
  270. package/dist/web/routes/reboot-restore-routes.d.ts.map +1 -1
  271. package/dist/web/routes/reboot-restore-routes.js +16 -0
  272. package/dist/web/routes/reboot-restore-routes.js.map +1 -1
  273. package/dist/web/routes/session-routes.d.ts.map +1 -1
  274. package/dist/web/routes/session-routes.js +22 -27
  275. package/dist/web/routes/session-routes.js.map +1 -1
  276. package/dist/web/routes/system-routes.d.ts +2 -2
  277. package/dist/web/routes/system-routes.d.ts.map +1 -1
  278. package/dist/web/routes/system-routes.js +23 -4
  279. package/dist/web/routes/system-routes.js.map +1 -1
  280. package/dist/web/schemas.d.ts +30 -0
  281. package/dist/web/schemas.d.ts.map +1 -1
  282. package/dist/web/schemas.js +52 -5
  283. package/dist/web/schemas.js.map +1 -1
  284. package/dist/web/self-update.d.ts.map +1 -1
  285. package/dist/web/self-update.js +4 -0
  286. package/dist/web/self-update.js.map +1 -1
  287. package/dist/web/sensitive-path.d.ts.map +1 -1
  288. package/dist/web/sensitive-path.js +5 -0
  289. package/dist/web/sensitive-path.js.map +1 -1
  290. package/dist/web/server.d.ts +20 -0
  291. package/dist/web/server.d.ts.map +1 -1
  292. package/dist/web/server.js +83 -7
  293. package/dist/web/server.js.map +1 -1
  294. package/dist/web/voice-stream.d.ts +4 -3
  295. package/dist/web/voice-stream.d.ts.map +1 -1
  296. package/dist/web/voice-stream.js +5 -4
  297. package/dist/web/voice-stream.js.map +1 -1
  298. package/package.json +2 -1
  299. package/skills/codeman/SKILL.md +318 -24
  300. package/skills/codeman/preamble.sh +242 -16
  301. package/skills/codeman/reference/recipes.md +1 -1
  302. package/skills/codeman/reference/verbs.md +101 -1
  303. package/dist/web/public/app.9ea37070.js.br +0 -0
  304. package/dist/web/public/app.9ea37070.js.gz +0 -0
  305. package/dist/web/public/i18n.a5e82c95.js.br +0 -0
  306. package/dist/web/public/i18n.a5e82c95.js.gz +0 -0
  307. package/dist/web/public/keyboard-accessory.b941676c.js.br +0 -0
  308. package/dist/web/public/keyboard-accessory.b941676c.js.gz +0 -0
  309. package/dist/web/public/mobile.67c8eb5b.css +0 -1
  310. package/dist/web/public/mobile.67c8eb5b.css.br +0 -0
  311. package/dist/web/public/mobile.67c8eb5b.css.gz +0 -0
  312. package/dist/web/public/panels-ui.8bcd4473.js.br +0 -0
  313. package/dist/web/public/panels-ui.8bcd4473.js.gz +0 -0
  314. package/dist/web/public/session-ui.a7c8c095.js.br +0 -0
  315. package/dist/web/public/session-ui.a7c8c095.js.gz +0 -0
  316. package/dist/web/public/settings-ui.18f92052.js.br +0 -0
  317. package/dist/web/public/settings-ui.18f92052.js.gz +0 -0
  318. package/dist/web/public/styles.6a718331.css +0 -1
  319. package/dist/web/public/styles.6a718331.css.br +0 -0
  320. package/dist/web/public/styles.6a718331.css.gz +0 -0
  321. package/dist/web/public/terminal-ui.a7883640.js.br +0 -0
  322. package/dist/web/public/terminal-ui.a7883640.js.gz +0 -0
  323. package/dist/web/public/voice-input.2342c37b.js.br +0 -0
  324. package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
@@ -4,7 +4,7 @@
4
4
  `),id:_crashDiag._pageId}))}catch{}}if(setInterval(()=>{try{localStorage.setItem("codeman-crash-heartbeat",String(Date.now()))}catch{}_crashDiagBeacon()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&_crashDiagBeacon()}),window.addEventListener("error",m=>{_crashDiag.log(`ERROR: ${m.message} at ${m.filename}:${m.lineno}`),console.error("[CRASH-DIAG] Uncaught error:",m.message,`
5
5
  File:`,m.filename,":",m.lineno,":",m.colno,`
6
6
  Stack:`,m.error?.stack)}),window.addEventListener("unhandledrejection",m=>{_crashDiag.log(`UNHANDLED: ${m.reason?.message||m.reason}`),console.error("[CRASH-DIAG] Unhandled promise rejection:",m.reason?.message||m.reason,`
7
- Stack:`,m.reason?.stack)}),typeof PerformanceObserver<"u")try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>200&&(_crashDiag.log(`LONG_TASK: ${t.duration.toFixed(0)}ms`),console.warn(`[CRASH-DIAG] Long task: ${t.duration.toFixed(0)}ms (type: ${t.entryType}, name: ${t.name})`))}).observe({type:"longtask",buffered:!0})}catch{}const _origGetContext=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(m,...e){const t=_origGetContext.call(this,m,...e);return(m==="webgl2"||m==="webgl")&&(this.addEventListener("webglcontextlost",s=>{_crashDiag.log(`WEBGL_LOST: ${this.width}x${this.height}`),console.error("[CRASH-DIAG] WebGL context LOST on canvas",this.width,"x",this.height,"\u2014 prevented:",s.defaultPrevented)}),this.addEventListener("webglcontextrestored",()=>{_crashDiag.log("WEBGL_RESTORED"),console.warn("[CRASH-DIAG] WebGL context restored")})),t};const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSSETerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSSENeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSSEClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_LIMIT_PAUSE_SCHEDULED,"_onSessionLimitPauseScheduled"],[SSE_EVENTS.SESSION_LIMIT_RESUME,"_onSessionLimitResume"],[SSE_EVENTS.SESSION_LIMIT_RESUME_CANCELLED,"_onSessionLimitResumeCancelled"],[SSE_EVENTS.SESSION_RESPAWN_BREAKER_TRIPPED,"_onSessionRespawnBreakerTripped"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SESSION_STATUS_TELEMETRY,"_onSessionStatusTelemetry"],[SSE_EVENTS.SESSION_PROMPT_CACHE,"_onSessionPromptCache"],[SSE_EVENTS.SESSION_KEEP_WARM,"_onSessionKeepWarm"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.CRON_JOBS_CHANGED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_JOB_DELETED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_RUN_CREATED,"_onCronRunChanged"],[SSE_EVENTS.CRON_RUN_UPDATED,"_onCronRunChanged"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.REMOTE_SESSION_RECONNECTED,"_onRemoteSessionReconnected"],[SSE_EVENTS.REMOTE_RECONNECT_EXHAUSTED,"_onRemoteReconnectExhausted"],[SSE_EVENTS.REMOTE_HOST_WAKING,"_onRemoteHostWaking"],[SSE_EVENTS.REMOTE_HOST_WAKE_FAILED,"_onRemoteHostWakeFailed"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_ELICITATION_COMPLETE,"_onHookElicitationComplete"],[SSE_EVENTS.HOOK_ELICITATION_RESPONSE,"_onHookElicitationResponse"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_AGENT_WORKING,"_onHookAgentWorking"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.APPROVAL_PENDING,"_onApprovalPending"],[SSE_EVENTS.APPROVAL_UPDATED,"_onApprovalUpdated"],[SSE_EVENTS.APPROVAL_RESOLVED,"_onApprovalResolved"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.WORKFLOW_RUN_DISCOVERED,"_onWorkflowRunDiscovered"],[SSE_EVENTS.WORKFLOW_RUN_UPDATED,"_onWorkflowRunUpdated"],[SSE_EVENTS.WORKFLOW_RUN_REMOVED,"_onWorkflowRunRemoved"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.ATTACHMENT_DETECTED,"_onAttachmentDetected"],[SSE_EVENTS.TRANSCRIPT_TOOL_END,"_onEditHistoryTranscriptEvent"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"],[SSE_EVENTS.ORCHESTRATOR_STATE_CHANGED,"_onOrchestratorStateChanged"],[SSE_EVENTS.ORCHESTRATOR_PLAN_PROGRESS,"_onOrchestratorPlanProgress"],[SSE_EVENTS.ORCHESTRATOR_PLAN_READY,"_onOrchestratorPlanReady"],[SSE_EVENTS.ORCHESTRATOR_PHASE_STARTED,"_onOrchestratorPhaseStarted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_COMPLETED,"_onOrchestratorPhaseCompleted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_FAILED,"_onOrchestratorPhaseFailed"],[SSE_EVENTS.ORCHESTRATOR_VERIFICATION,"_onOrchestratorVerification"],[SSE_EVENTS.ORCHESTRATOR_TASK_ASSIGNED,"_onOrchestratorTaskAssigned"],[SSE_EVENTS.ORCHESTRATOR_TASK_COMPLETED,"_onOrchestratorTaskCompleted"],[SSE_EVENTS.ORCHESTRATOR_TASK_FAILED,"_onOrchestratorTaskFailed"],[SSE_EVENTS.ORCHESTRATOR_COMPLETED,"_onOrchestratorCompleted"],[SSE_EVENTS.ORCHESTRATOR_ERROR,"_onOrchestratorError"],[SSE_EVENTS.CLIPBOARD_WRITE,"_onClipboardWrite"],[SSE_EVENTS.SESSION_ORDER_CHANGED,"_onSessionOrderChanged"],[SSE_EVENTS.TAB_LAYOUT_CHANGED,"_onTabLayoutChanged"],[SSE_EVENTS.WEBVIEW_CHANGED,"_onWebviewChanged"]];function parseSessionPrefix(m){if(!m)return null;const e=m.match(/^(w\d+-[a-zA-Z0-9_-]+|s\d+-[a-zA-Z0-9_-]+)/);if(!e)return null;const t=e[1],s=m.slice(t.length);return s===""?{prefix:t,suffix:""}:s.startsWith(": ")?{prefix:t,suffix:s.slice(2)}:null}function paneExitLabel(m){return!m||typeof m!="object"?"":typeof m.signal=="number"&&m.signal>0?`exited (signal ${m.signal})`:typeof m.status=="number"?`exited (${m.status})`:"exited"}function paneExitAriaLabel(m,e){return e?`${m} session, agent ${e}`:`${m} session`}function applyPaneExitBadge(m,e){const t=paneExitLabel(e),s=m.querySelector(".tab-exited-badge");m.classList.toggle("tab-agent-exited",!!t);const i=m.querySelector(".tab-name")?.dataset?.fullName;if(i){const n=paneExitAriaLabel(i,t);m.dataset.ariaSource!==n&&(m.dataset.ariaSource=n,m.setAttribute("aria-label",n))}if(!t){s?.remove();return}if(!s){const n=document.createElement("span");n.className="tab-exited-badge",n.setAttribute("aria-hidden","true"),n.dataset.label=t,n.textContent=t,m.querySelector(".tab-name")?.insertAdjacentElement("afterend",n);return}s.dataset.label!==t&&(s.dataset.label=t,s.textContent=t)}const DEFAULT_SHORTCUTS=[{id:"show-shortcuts",group:"Panels",label:"Show Shortcuts",bindings:[{modifiers:["ctrl"],key:"?",code:"Slash"},{modifiers:["ctrl","shift"],key:"?"},{modifiers:["alt"],key:"?",code:"Slash"}],action:"showShortcutOverlay"},{id:"close-session",group:"Session",label:"Close Session",bindings:[],action:"killActiveSession"},{id:"next-session",group:"Session",label:"Next Session",bindings:[{modifiers:["ctrl"],key:"Tab"}],action:"nextSession"},{id:"clear-terminal",group:"Terminal",label:"Clear Terminal",bindings:[{modifiers:["ctrl"],key:"l"}],action:"clearTerminal"},{id:"copy-selection",group:"Terminal",label:"Copy Selection",bindings:[{modifiers:["ctrl"],key:"c"},{modifiers:["ctrl","shift"],key:"C"}],action:"copyTerminalSelection"},{id:"increase-font",group:"Terminal",label:"Increase Font",bindings:[{modifiers:["ctrl"],key:"=",code:"Equal"},{modifiers:["ctrl"],key:"+",code:"Equal"}],action:"increaseFontSize"},{id:"decrease-font",group:"Terminal",label:"Decrease Font",bindings:[{modifiers:["ctrl"],key:"-",code:"Minus"}],action:"decreaseFontSize"},{id:"voice-input",group:"Terminal",label:"Voice Input",bindings:[{modifiers:["ctrl","shift"],key:"V"}],action:"toggleVoiceInput"},{id:"restore-terminal-size",group:"Terminal",label:"Restore Terminal Size",bindings:[{modifiers:["ctrl","shift"],key:"R"}],action:"restoreTerminalSize"},{id:"move-tab-left",group:"Tabs",label:"Move Active Tab Left",bindings:[{modifiers:["ctrl","shift"],key:"{",code:"BracketLeft"}],action:"moveActiveTabLeft"},{id:"move-tab-right",group:"Tabs",label:"Move Active Tab Right",bindings:[{modifiers:["ctrl","shift"],key:"}",code:"BracketRight"}],action:"moveActiveTabRight"},{id:"command-palette",group:"Session",label:"Find Open Session",bindings:[{modifiers:["ctrl"],key:"k",code:"KeyK"},{modifiers:["meta"],key:"k",code:"KeyK"},{modifiers:["alt"],key:"k",code:"KeyK"}],action:"openCommandPalette"},{id:"toggle-session-sidebar",group:"Session",label:"Toggle Session Sidebar",bindings:[{modifiers:["alt"],key:"b",code:"KeyB"}],action:"toggleSessionSidebar"},{id:"toggle-tile-grid",group:"Tiles",label:"Toggle Tile Grid",bindings:[{modifiers:["ctrl","shift"],key:"G",code:"KeyG"}],action:"toggleTileGrid"},{id:"focus-tile-left",group:"Tiles",label:"Focus Tile Left",bindings:[{modifiers:["alt","shift"],key:"ArrowLeft"}],action:"focusTileLeft"},{id:"focus-tile-right",group:"Tiles",label:"Focus Tile Right",bindings:[{modifiers:["alt","shift"],key:"ArrowRight"}],action:"focusTileRight"},{id:"focus-tile-up",group:"Tiles",label:"Focus Tile Up",bindings:[{modifiers:["alt","shift"],key:"ArrowUp"}],action:"focusTileUp"},{id:"focus-tile-down",group:"Tiles",label:"Focus Tile Down",bindings:[{modifiers:["alt","shift"],key:"ArrowDown"}],action:"focusTileDown"},{id:"move-tile-left",group:"Tiles",label:"Move Tile Left",bindings:[{modifiers:["ctrl","shift"],key:"ArrowLeft"}],action:"moveTileLeft"},{id:"move-tile-right",group:"Tiles",label:"Move Tile Right",bindings:[{modifiers:["ctrl","shift"],key:"ArrowRight"}],action:"moveTileRight"},{id:"move-tile-up",group:"Tiles",label:"Move Tile Up",bindings:[{modifiers:["ctrl","shift"],key:"ArrowUp"}],action:"moveTileUp"},{id:"move-tile-down",group:"Tiles",label:"Move Tile Down",bindings:[{modifiers:["ctrl","shift"],key:"ArrowDown"}],action:"moveTileDown"},{id:"zoom-tile",group:"Tiles",label:"Zoom Focused Tile",bindings:[{modifiers:["alt","shift"],key:"Enter"}],action:"zoomTile"},{id:"remove-tile",group:"Tiles",label:"Remove Focused Tile",bindings:[],action:"removeTile"},{id:"previous-session",group:"Session",label:"Previous Session",displayBindings:["Alt/Option+["],bindings:[{modifiers:["alt"],code:"BracketLeft"}],action:"previousSession"},{id:"next-session-alt",group:"Session",label:"Next Session (alternate)",displayBindings:["Alt/Option+]"],bindings:[{modifiers:["alt"],code:"BracketRight"}],action:"nextSession"},{id:"switch-tab-n",group:"Session",label:"Switch to Tab N",displayBindings:["Alt/Option+1-9"]},{id:"focus-tabs",group:"Tabs",label:"Focus Tabs",displayBindings:["ArrowLeft","ArrowRight","Home","End"]},{id:"activate-focused-tab",group:"Tabs",label:"Activate Focused Tab",displayBindings:["Enter","Space"]},{id:"insert-newline",group:"Terminal",label:"Insert Newline",displayBindings:["Shift+Enter","Ctrl+Enter"]},{id:"close-panels",group:"Panels",label:"Close Panels",displayBindings:["Escape"]},{id:"file-preview-history",group:"Panels",label:"File Viewer Back / Forward",displayBindings:["Alt/Option+ArrowLeft","Alt/Option+ArrowRight"]}],SIDEBAR_RICH_CLOCK_MS=2e4,CONNECTION_BACKLOG_HINT_BYTES=4,CONNECTION_BACKLOG_HOLD_MS=1200,URL_SESSION_WAIT_MS=3e4,TAB_LAYOUT_PENDING_MAX_AGE_MS=6e4,TAB_GROUP_ARRIVAL_MS=2e3;class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.tabLayout=null,this.collapsedTabGroupIds=new Set,this._hiddenTabGroupByRef=new Map,this._lastTabGroupStructureKey=null,this._tabRailSearch="",this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this._clientId=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"c-"+Math.random().toString(36).slice(2)+Date.now().toString(36),this._wsTabNonce=this._clientId,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this.soloSessionId=this._detectSoloSessionId(),this.isSoloWindow=!!this.soloSessionId,this._urlSessionId=this.isSoloWindow?null:this._takeUrlSession(),this._urlSessionWaitTimer=null,this.detachedSessions=new Set,this.detachedWindows=new Map,this._detachWatchTimers=new Map,this.windowChannel=null,this._redockGrace=new Map,this._detachPingPending=null,this._detachLivenessTimer=null,this._detachOrphanStrikes=new Map,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this._fullHistoryLoaded=new Set,this._paneHistoryLines=new Map,this._fullHistoryRepullAt=new Map,this._fullHistoryRepullInFlight=!1,this._fullHistoryRepullUseless=new Set,this._geometryRetryUseless=new Set,this.terminalLoadStates=new Map,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.workflowRuns=new Map,this.workflowRunDetails=new Map,this.activeWorkflowRunId=null,this.activeWorkflowPhaseIndex=null,this.ultracodeWindows=new Map,this.ultracodeWindowsClosed=new Set,this.ultracodeWindowCloseTimers=new Map,this.ultracodeWindowZIndex=1e3,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.orchestratorState=null,this.orchestratorPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.attachmentCards=new Map,this.attachmentCardStack=null,this.attachmentHistoryCounts=new Map,this.attachmentHistoryItems=[],this.attachmentHistoryDrawerOpen=!1,this.fileBrowserData=null,this.fileBrowserExpandedDirs=new Set,this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1,this.fileBrowserDragListeners=null,this.fileBrowserShowHidden=this._loadFileBrowserShowHidden?.()??!1,this.filePreviewContent="",this._toastContainer=null,this._tunnelUrl=null,this.tabAlerts=new Map,this.pendingHooks=new Map,this._closingSessions=new Set,this.approvals=new Map,this._ws=null,this._wsSessionId=null,this._wsReady=!1,this._wsState="disconnected",this._wsLastRecvAt=0,this._wsOutputGapSession=null,this.pendingWrites=[],this.writeFrameScheduled=!1,this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._terminalRefreshOwner=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this._debounceTimers=Object.create(null),this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._sseLastMessageAt=0,this._sseStaleTimeoutMs=window.CodemanSseStale?.TIMEOUT_MS??45e3,this._sseStaleWatchdog=null,this._sseConnectTimeout=null,this._sseConnectTimeoutMs=window.CodemanSseStale?.CONNECT_TIMEOUT_MS??15e3,this._connDownSince=null,this._nextSseRetryAt=null,this._offlineOverlayDismissed=!1,this._offlineRetryPending=!1,this._offlineUiTicker=null,this._lastOfflineUiKey="",this._connectionStatus="connected",this._clientId="",this._seqCounters=new Map,this._pendingDeliveries=new Map,this._lastIndicatorDescriptor=null,this._lastIndicatorLanguage=null,this._postDraining=new Set,this._extraInputSockets=new Map,this._persistReliableTimer=null,this._reliableAckTimeoutMs=4e3,this._reliableMaxBytes=256*1024,this._loadReliableState(),this._reliableSweepTimer=setInterval(()=>this._redeliverSweep(),2e3),window.addEventListener("pagehide",()=>this._persistReliableNow()),window.addEventListener("pagehide",()=>this._persistPendingTabLayoutEdits()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._persistReliableNow():this._checkSseStale()}),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._predictiveEcho=null,this._localEchoPolicy="off",this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}_clearTimer(e){this[e]&&(clearTimeout(this[e]),this[e]=null)}_isStaleSelect(e){return e!==this._selectGeneration?(this._isLoadingBuffer&&this._finishBufferLoad(e),this._restoringFlushedState=!1,!0):!1}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,i=t/1e6*75;return s+i}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}markIdleAlertSeen(e){this.pendingHooks?.get(e)?.has("idle_prompt")&&(this.clearPendingHooks(e,"idle_prompt"),this.acknowledgeIdleApprovalOnView?.(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),this._initWindowChannel(),this.isSoloWindow&&document.body.classList.add("solo-mode"),this.isSoloWindow||window.addEventListener("hashchange",()=>{const s=this._takeUrlSession();s&&(this._retireUrlSession(),this._urlSessionId=s,this._selectUrlSession())}),document.documentElement.classList.toggle("host-windows",this.hasHostWindows()),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init();const e=this.loadAppSettingsFromStorage();KeyboardAccessoryBar.setMode(e.extendedKeyboardBar?"extended":"simple"),this.applyHeaderVisibilitySettings(),this.restorePlanUsageChip(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation(),this.initTabRailResize?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),this._installLineageStripScrollListener?.(),this._setupTabMiddleClickClose(),this.initEntranceAnimations?.(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker(),this.loadTunnelStatus(),this.initRebootRestoreBanner?.();const t=fetch("/api/settings").then(s=>s.ok?s.json():null).then(s=>s?.data??null).catch(()=>null);if(this.loadQuickStartCases(null,t),this._initRunMode(),this.initWebviews?.(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const s=i=>{i&&i.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const o=n.target.closest("button");o&&(n.preventDefault(),o.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};s(document.querySelector(".toolbar")),s(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(t).then(()=>{this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows()}),document.body.classList.add("app-loaded")}_initWebGL(){if(!(typeof WebglAddon>"u"))try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{console.error("[CRASH-DIAG] WebGL context LOST \u2014 falling back to canvas renderer"),_crashDiag.log("WEBGL_LOST"),this._disableWebGLSticky("context-lost"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint()}),this.terminal.loadAddon(this._webglAddon),console.log("[CRASH-DIAG] WebGL renderer enabled"),this._installWebGLLongTaskGuard()}catch{}}_installWebGLLongTaskGuard(){if(typeof PerformanceObserver>"u"||this._webglLongTaskObserver)return;const e=performance.now(),t=[];try{this._webglLongTaskObserver=new PerformanceObserver(s=>{if(!this._webglAddon||this._tilesOwnTerminal?.())return;const i=performance.now();i-e<WEBGL_FALLBACK.GRACE_MS||evaluateWebGLLongTaskTrip(t,s.getEntries(),i)&&(console.warn(`[CRASH-DIAG] WebGL long-task threshold (${t.length} stalls/${WEBGL_FALLBACK.WINDOW_MS}ms) \u2014 falling back to canvas renderer`),_crashDiag.log(`WEBGL_FALLBACK: ${t.length}`),this._disableWebGLSticky("long-tasks"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint())}),this._webglLongTaskObserver.observe({type:"longtask",buffered:!1})}catch{}}_disposeWebGLObserver(){if(this._webglLongTaskObserver){try{this._webglLongTaskObserver.disconnect()}catch{}this._webglLongTaskObserver=null}}_scheduleTerminalRepaint(){if(this._terminalRepaintScheduled)return;this._terminalRepaintScheduled=!0,(typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,0))(()=>{this._terminalRepaintScheduled=!1;try{this.terminal?.refresh(0,this.terminal.rows-1)}catch{}})}_disableWebGLSticky(e){try{localStorage.setItem("codeman-webgl-disabled",JSON.stringify({reason:e,at:Date.now()}))}catch{}}setupEventListeners(){const e=this._shortcutActions();document.addEventListener("keydown",s=>{if(s.target?.closest?.("[data-raw-keys]")||s.isComposing||s.keyCode===229)return;if(this.shouldOpenCommandPaletteFromShortcut?.(s)){s.preventDefault(),this.openCommandPalette();return}if(s.key==="Escape"){if(this._tabGroupMenu&&this._tabGroupMenuKeydown){this._tabGroupMenuKeydown(s);return}if(this._tabLayoutDrag?.active&&this._tabLayoutDragKeydown){this._tabLayoutDragKeydown(s);return}if(this._tileCountMenu){this.closeTileCountMenu({refocus:!0});return}if(s.target?.id==="tabRailSearch"&&this._tabRailSearch){this.handleTabRailSearchKeydown(s);return}this.closeAllPanels(),this.closeHelp(),this.attachmentHistoryDrawerOpen&&this.closeAttachmentHistory(),this.closeWorktreeModal?.(),this.closeSessionManager(),this.closeCommandPalette?.(),this.closeShortcutOverlay?.(),this._isSessionSidebarOverlay()&&this.isSessionSidebarActive()&&!this.isSessionSidebarCollapsed()&&(this.toggleSessionSidebar(),document.getElementById("sidebarToggleBtn")?.focus())}if(s.altKey&&!s.ctrlKey&&!s.shiftKey){const o=(s.code||"").match(/^Digit([1-9])$/);if(o){const a=parseInt(o[1],10)-1,r=this.sessionOrder.filter(l=>this.sessions.has(l));if(a<r.length)s.preventDefault(),this.selectSession(r[a]);else{const l=a-r.length,c=(this.webviewOrder||[])[l];c&&(s.preventDefault(),this.openWebview(c))}return}}const i=this.tileShortcutFor?.(s);if(i){s.preventDefault(),this.runTileShortcut(i);return}if(!(!s.ctrlKey&&!s.metaKey&&!s.altKey))for(const n of this.getShortcutRegistry()){if(n.disabled||!n.action)continue;const o=e[n.action];if(o&&this.matchesShortcutEvent(s,n)){s.preventDefault(),o();return}}},!0);const t=this.$("headerTokens");t&&!t._statsHandlerAttached&&(t.classList.add("clickable"),t._statsHandlerAttached=!0,t.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}_sseFilterSessionId(e){return this._tilesOwnTerminal?.()&&window.CodemanTileGrid?.TILE_GRID_SSE_FILTER||e}_updateSseSubscription(e){try{const t=this._sseFilterSessionId(e),s=JSON.stringify({clientId:this._clientId,sessions:t?[t]:null});fetch("/api/events/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:s,keepalive:!0}).catch(()=>{})}catch{}}_detectSoloSessionId(){try{if(typeof window<"u"&&typeof window.__CODEMAN_SOLO__=="string"&&window.__CODEMAN_SOLO__)return window.__CODEMAN_SOLO__;const e=window.CodemanBase?.base||"";let t=location.pathname;e&&t.startsWith(e)&&(t=t.slice(e.length)||"/");const s=t.match(/^\/session\/([^/]+)\/?$/);return s?decodeURIComponent(s[1]):null}catch{return null}}_takeUrlSession(){const e=window.CodemanUrlSession?.sessionIdFromFragment(location.hash)??null;if(e)try{history.replaceState(history.state,"",location.pathname+location.search)}catch{}return e}_selectUrlSession(){const e=this._urlSessionId;return e?this.sessions.has(e)?(this._retireUrlSession(),this.selectSession(e,{auto:!0,leaveTiles:!0}),!0):(this._armUrlSessionWait(e),!1):!1}_armUrlSessionWait(e){this._urlSessionWaitTimer||(this._urlSessionWaitTimer=setTimeout(()=>{if(this._urlSessionWaitTimer=null,this._urlSessionId===e){if(this.sessions.has(e)){this._selectUrlSession();return}this._retireUrlSession(),this.showToast?.("Session not found","warning")}},URL_SESSION_WAIT_MS))}_retireUrlSession(){this._urlSessionId=null,this._urlSessionWaitTimer&&(clearTimeout(this._urlSessionWaitTimer),this._urlSessionWaitTimer=null)}detachSession(e,t=null){if(this.isSoloWindow||!this.sessions.has(e)||this.detachedSessions.has(e)&&this._raiseDetached(e))return;const s=this.hasHostWindows()&&!this.windowChannel?!1:this.openInHostWindow(CodemanBase.url("/session/"+encodeURIComponent(e)));if(s!==null){if(!s){this.showToast?.("Could not open a new window for this session","error");return}this._markDetached(e,!0),this._postWindowMessage({type:"detached",id:e});return}const i=this._detachWindowFeatures(t);let n=null;try{n=window.open(CodemanBase.url("/session/"+encodeURIComponent(e)),"codeman-session-"+e,i)}catch{}if(!n){this.showToast?.("Pop-out blocked \u2014 allow popups for this site to detach a session","error");return}this.detachedWindows.set(e,n),this._markDetached(e,!0),this._watchDetachedWindow(e,n),this._postWindowMessage({type:"detached",id:e});try{n.focus()}catch{}}_detachWindowFeatures(e){const t=r=>Number.isFinite(r)?Math.round(r):null,s=t(e?.width)??960,i=t(e?.height)??680,n=t(e?.left),o=t(e?.top),a=n!==null&&o!==null?`,left=${n},top=${o}`:"";return`width=${s},height=${i}${a},menubar=no,toolbar=no,location=no,status=no`}hasHostWindows(){try{return typeof window<"u"&&typeof window.CodemanHost?.openWindow=="function"}catch{return!1}}tabDetachButtonEnabled(e,t={}){return e?.showTabDetachButton??(this.hasHostWindows()||(t?.showTabDetachButton??!1))}openInHostWindow(e){if(!this.hasHostWindows())return null;try{return window.CodemanHost.openWindow(new URL(e,location.href).href)!==!1}catch{return!1}}_raiseDetached(e){const t=this.detachedWindows.get(e);if(t&&!t.closed){try{t.focus()}catch{}return!0}return t&&t.closed?(this._redock(e),!1):(this._postWindowMessage({type:"focus-request",id:e}),!0)}redockSession(e){const t=this.detachedWindows.get(e);if(t&&!t.closed)try{t.close()}catch{}this._postWindowMessage({type:"close-request",id:e}),this._redock(e)}_redock(e){const t=this._detachWatchTimers.get(e);t&&(clearInterval(t),this._detachWatchTimers.delete(e)),this._cancelPendingRedock(e),this._detachOrphanStrikes.delete(e),this.detachedWindows.delete(e),this._markDetached(e,!1),this._lastResizeDims=null,this.sessions.has(e)&&e===this.activeSessionId&&this.sendResize(e,{force:!0})?.catch?.(()=>{})}_scheduleRedock(e){if(this._redockGrace.has(e))return;const t=setTimeout(()=>{this._redockGrace.delete(e),this._redock(e)},1500);this._redockGrace.set(e,t)}_cancelPendingRedock(e){const t=this._redockGrace.get(e);t&&(clearTimeout(t),this._redockGrace.delete(e))}_markDetached(e,t){t?this.detachedSessions.add(e):this.detachedSessions.delete(e),t&&this._tileGrid?.has(e)&&this.removeTile(e,{gone:!0});const s=this.$("sessionTabs"),i=s&&s.querySelector(`.session-tab[data-id="${e}"]`);i&&i.classList.toggle("detached",t)}_watchDetachedWindow(e,t){const s=this._detachWatchTimers.get(e);s&&clearInterval(s);const i=setInterval(()=>{(!t||t.closed)&&(clearInterval(i),this._detachWatchTimers.delete(e),this._redock(e))},800);this._detachWatchTimers.set(e,i)}_initWindowChannel(){if(!(typeof BroadcastChannel>"u")){try{this.windowChannel=new BroadcastChannel("codeman-windows")}catch{this.windowChannel=null;return}if(this.windowChannel.onmessage=e=>this._onWindowMessage(e.data),this.isSoloWindow){this._postWindowMessage({type:"detached",id:this.soloSessionId});const e=()=>this._postWindowMessage({type:"redocked",id:this.soloSessionId});window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}else this._postWindowMessage({type:"roll-call"}),this._startDetachLiveness()}}_postWindowMessage(e){try{this.windowChannel&&this.windowChannel.postMessage(e)}catch{}}_onWindowMessage(e){if(!(!e||typeof e!="object")){if(this.isSoloWindow){if(e.type==="roll-call"){this._soloReleased||this._postWindowMessage({type:"detached",id:this.soloSessionId});return}if(e.id!==this.soloSessionId)return;if(e.type==="close-request")this._releaseSoloWindow();else if(e.type==="focus-request")try{typeof window.CodemanHost?.focusWindow=="function"?window.CodemanHost.focusWindow():window.focus()}catch{}return}if(e.type==="detached"&&e.id){if(this._tileDockedRecently?.(e.id))return;this._cancelPendingRedock(e.id),this._detachPingPending?.delete(e.id),this._detachOrphanStrikes.delete(e.id),this._markDetached(e.id,!0)}else e.type==="redocked"&&e.id?this._scheduleRedock(e.id):e.type==="detach-request"&&e.id?this.detachSession(e.id):e.type==="tile-adopted"&&e.id&&e.by!==this._wsTabNonce&&this._onTileAdoptedElsewhere?.(e.id)}}_startDetachLiveness(){this._detachLivenessTimer||(this._detachLivenessTimer=setInterval(()=>this._pingDetached(),5e3))}_pingDetached(){const e=[];for(const t of this.detachedSessions){const s=this.detachedWindows.get(t);s?s.closed&&this._redock(t):e.push(t)}e.length&&(this._detachPingPending=new Set(e),this._postWindowMessage({type:"roll-call"}),setTimeout(()=>{if(this._detachPingPending){for(const t of this._detachPingPending){const s=(this._detachOrphanStrikes.get(t)||0)+1;s>=2?(this._detachOrphanStrikes.delete(t),this._redock(t)):this._detachOrphanStrikes.set(t,s)}this._detachPingPending=null}},1200))}_closeSoloWindow(){try{typeof window.CodemanHost?.closeWindow=="function"?window.CodemanHost.closeWindow():window.close()}catch{}}_releaseSoloWindow(){this._soloReleased||(this._soloReleased=!0,this._postWindowMessage({type:"redocked",id:this.soloSessionId}),this._closeSoloWindow(),setTimeout(()=>{window.closed||this._showSoloReleased()},300))}_showSoloReleased(){if(document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay";const t=document.createElement("h2");t.textContent="Session moved";const s=document.createElement("p");s.textContent="This session is back in a Codeman window. This one can be closed.";const i=document.createElement("button");i.className="btn-primary",i.textContent="Close window",i.addEventListener("click",()=>this._closeSoloWindow()),e.append(t,s,i),document.body.appendChild(e)}_applySoloMode(){document.body.classList.add("solo-mode");const e=this.sessions.get(this.soloSessionId);if(!e){this._showSoloSessionGone();return}this.activeSessionId=null,this.selectSession(this.soloSessionId,{auto:!0});const t=this.getSessionName(e)||"Session",s=document.getElementById("soloSessionTitle");s&&(s.textContent=t,s.style.display="");const i=document.getElementById("soloRedockBtn");i&&(i.style.display=""),this._installSoloTileHandle?.(),document.title=t+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman"),this.notificationManager&&(this.notificationManager.originalTitle=document.title);const n=document.querySelector(".header-brand .logo");n&&(n.onclick=o=>{o.preventDefault()})}_showSoloSessionGone(){if(document.body.classList.add("solo-mode"),document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay",e.innerHTML='<h2>Session unavailable</h2><p>This session has ended or is no longer available.</p><button class="btn-primary" onclick="app._closeSoloWindow()">Close window</button>',document.body.appendChild(e),document.title=(window.codemanT?.("Session ended")||"Session ended")+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman")}connectSSE(){if(this._clearTimer("_sseConnectTimeout"),!navigator.onLine){this.setConnectionStatus("offline");return}this._clearTimer("sseReconnectTimeout"),this._sseStaleWatchdog&&(clearInterval(this._sseStaleWatchdog),this._sseStaleWatchdog=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting");const e=new URLSearchParams({clientId:this._clientId}),t=this._sseFilterSessionId(this.activeSessionId);t&&e.set("sessions",t);const s=new EventSource(CodemanBase.url(`/api/events?${e.toString()}`));this.eventSource=s;const i=setTimeout(()=>{this._sseConnectTimeout===i&&(this._sseConnectTimeout=null,!(this.eventSource!==s||s.readyState===EventSource.OPEN)&&(console.warn(`[SSE] connection did not open within ${this._sseConnectTimeoutMs}ms, retrying`),this._handleSseConnectionFailure(s)))},this._sseConnectTimeoutMs);this._sseConnectTimeout=i;const n=[],o=(a,r)=>{const l=c=>{this._sseLastMessageAt=Date.now(),r(c)};this.eventSource.addEventListener(a,l),n.push({event:a,handler:l})};if(this._sseListenerCleanup=()=>{for(const{event:a,handler:r}of n)this.eventSource&&this.eventSource.removeEventListener(a,r);n.length=0},this.eventSource.onopen=()=>{this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts=0,this._sseLastMessageAt=Date.now(),this.setConnectionStatus("connected")},this.eventSource.onerror=()=>this._handleSseConnectionFailure(s),!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[a,r]of _SSE_HANDLER_MAP){const l=this[r],c=r==="_onSSETerminal"||r==="_onSSENeedsRefresh"||r==="_onSSEClearTerminal";this._sseHandlerWrappers.set(a,h=>{if(!(c&&this._wsReady))try{l.call(this,h.data?JSON.parse(h.data):{})}catch(d){console.error(`[SSE] Error handling ${a}:`,d)}})}}for(const[a]of _SSE_HANDLER_MAP)o(a,this._sseHandlerWrappers.get(a));for(const a of[SSE_EVENTS.SESSION_CREATED,SSE_EVENTS.SESSION_DELETED])o(a,()=>this._onSessionListMaybeChanged());o(SSE_EVENTS.DOCKER_EXPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export ready: ${r.bundle} (${Math.round((r.sizeBytes||0)/1e6)} MB)`,"success"),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker export complete:",r)}}),o(SSE_EVENTS.DOCKER_EXPORT_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker export failed:",r)}}),o(SSE_EVENTS.DOCKER_IMPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker bundle imported as case "${r.name}"`,"success"),this.loadQuickStartCases?.(),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker import complete:",r)}}),o(SSE_EVENTS.DOCKER_CONTAINER_RECREATED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Container for "${r.name}" removed \u2014 next launch recreates it with the new config`,"info")}catch(r){console.error("[SSE] docker container recreated:",r)}}),o(SSE_EVENTS.CUSTOM_MODEL_SWAPPED_OUT,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`${r.sessionName||r.sessionId}'s model (${r.previousModel}) was swapped out on llama-swap by another session \u2014 currently loaded: ${r.currentlyLoadedModel}. Sending a message there will reload it.`,"warning",{duration:0})}catch(r){console.error("[SSE] custom model swapped out:",r)}}),o(SSE_EVENTS.ADMIN_USERS_CHANGED,()=>{window.codemanAdmin?.onUsersChanged?.()}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_STARTED,()=>{this.showToast("Building the Codeman agent image (first Docker case, a few minutes)...","info",{duration:8e3})}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};r.error?this.showToast(`Agent image build failed: ${r.error}`,"error"):this.showToast("Agent image ready. Starting the container...","success")}catch(r){console.error("[SSE] docker image build complete:",r)}}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Agent image build failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker image build failed:",r)}}),o(SSE_EVENTS.SESSION_PINNED,a=>{let r=null;try{r=JSON.parse(a.data)}catch{}if(r&&r.id){const l=this.sessions.get(r.id);l&&(l.pinned=r.pinned===!0,l.pinnedAt=r.pinned?r.pinnedAt:void 0)}this._onSessionListMaybeChanged()}),o(SSE_EVENTS.HEARTBEAT,()=>{}),this._sseStaleWatchdog=setInterval(()=>this._checkSseStale(),5e3)}_handleSseConnectionFailure(e){if(this.eventSource!==e)return;this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource=null,e.close(),this._clearTimer("sseReconnectTimeout");const t=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this._nextSseRetryAt=Date.now()+t,this._updateConnectionLossUi(),this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),t)}_checkSseStale(){const e=window.CodemanSseStale;if(!e)return;const t=Date.now();e.compute({lastMessageAt:this._sseLastMessageAt,now:t,status:this._connectionStatus,isOnline:this.isOnline,timeoutMs:this._sseStaleTimeoutMs})&&(console.log(`[SSE] stream stale: no frame for ${t-this._sseLastMessageAt}ms (threshold ${this._sseStaleTimeoutMs}ms), forcing reconnect`),this.connectSSE())}_onInit(e){_crashDiag.log(`INIT: ${e.sessions?.length||0} sessions`),this.handleInit(e),this._ensureHostWakePoller?.()}_onSessionCreated(e){this._closingSessions?.has(e.id)||(this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||this.syncSessionOrder(),this.markSessionTabEntering?.(e.id),this.markTerminalEntering?.(e.id),e.parentSessionId&&this.markConnectionLineEntering?.("lineage:"+e.id),this.renderSessionTabs(),this.updateCost(),this._urlSessionId===e.id&&this._selectUrlSession())}_onSessionUpdated(e){const t=e.session||e;if(this._closingSessions?.has(t.id))return;const s=this.sessions.get(t.id),i=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),t.id===this.activeSessionId&&this._reconcileKeyboardHold?.(),t.id===this.activeSessionId&&this._followFileBrowserWorktree?.(t),this.updateSubagentParentNames(t.id),this.editingSessionId===t.id&&this.updateGitFetchStatus(t.id),i&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._wsSessionId===e.id&&this._disconnectWs(),this.isSoloWindow&&e.id===this.soloSessionId&&this._showSoloSessionGone(),this.detachedSessions.has(e.id)&&this._redock(e.id),this._cleanupSessionData(e.id),this.activeSessionId===e.id&&!this._closingSessions.has(e.id)){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel()}_onSSETerminal(e){this._wsReady||this._onSessionTerminal(e)}_onSSENeedsRefresh(e){this._wsReady||this._onSessionNeedsRefresh(e)}_onSSEClearTerminal(e){this._wsReady||this._onSessionClearTerminal(e)}_bufferLoadFinishOpts(e,t){return{flushQueued:e?.source==="mux-visible"||e?.source==="mux-full-history",since:t}}_onSessionTerminal(e){if(!this._tilesOwnTerminal?.()&&e.id===this.activeSessionId){e.data.length>32768&&_crashDiag.log(`TERMINAL: ${(e.data.length/1024).toFixed(0)}KB`);const t=(this.pendingWrites?.reduce((s,i)=>s+i.length,0)||0)+(this.flickerFilterBuffer?.length||0)+(this._loadBufferQueue?.reduce((s,i)=>s+i.data.length,0)||0)+(this._terminalWriteInFlightBytes||0);if(t+e.data.length>131072){this._scheduleDroppedOutputRecovery(e.id,0,t);return}this.batchTerminalWrite(e.data)}}_scheduleDroppedOutputRecovery(e,t=0,s){!e||this._clientDropRecoveryTimer||this._tilesOwnTerminal?.()||(Number.isFinite(s)&&_crashDiag.log(`TERMINAL DROP: ${(s/1024).toFixed(0)}KB queued`),this._clientDropRecoveryTimer=setTimeout(async()=>{this._clientDropRecoveryTimer=null;let i=!1,n=!1;try{const a=await this._onSessionNeedsRefresh({id:e});i=a===!0,n=a==="deadline"}catch{}window.CodemanDroppedOutput.shouldRetryDroppedOutputRecovery({repainted:i,timedOut:n,attempt:t,stillActive:this.activeSessionId===e})&&(_crashDiag.log(`DROP RECOVERY: attempt ${t+1} did not repaint, retrying`),this._scheduleDroppedOutputRecovery(e,t+1))},window.CodemanDroppedOutput.DROP_RECOVERY_DELAY_MS))}_sanitizeHtml(e){return typeof window<"u"&&typeof window.sanitizeMarkdownHtml=="function"?window.sanitizeMarkdownHtml(e):String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}_cleanTerminalBuffer(e){const t=e.replace(/\x1b\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[PX^_][^\x1b]*\x1b\\/g,"").replace(/\x1b[NO()][A-Z0-9]?/g,"").replace(/\x1b[>=<78cDEHM]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").replace(/\r\n/g,`
7
+ Stack:`,m.reason?.stack)}),typeof PerformanceObserver<"u")try{new PerformanceObserver(e=>{for(const t of e.getEntries())t.duration>200&&(_crashDiag.log(`LONG_TASK: ${t.duration.toFixed(0)}ms`),console.warn(`[CRASH-DIAG] Long task: ${t.duration.toFixed(0)}ms (type: ${t.entryType}, name: ${t.name})`))}).observe({type:"longtask",buffered:!0})}catch{}const _origGetContext=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(m,...e){const t=_origGetContext.call(this,m,...e);return(m==="webgl2"||m==="webgl")&&(this.addEventListener("webglcontextlost",s=>{_crashDiag.log(`WEBGL_LOST: ${this.width}x${this.height}`),console.error("[CRASH-DIAG] WebGL context LOST on canvas",this.width,"x",this.height,"\u2014 prevented:",s.defaultPrevented)}),this.addEventListener("webglcontextrestored",()=>{_crashDiag.log("WEBGL_RESTORED"),console.warn("[CRASH-DIAG] WebGL context restored")})),t};const _SSE_HANDLER_MAP=[[SSE_EVENTS.INIT,"_onInit"],[SSE_EVENTS.SESSION_CREATED,"_onSessionCreated"],[SSE_EVENTS.SESSION_UPDATED,"_onSessionUpdated"],[SSE_EVENTS.SESSION_DELETED,"_onSessionDeleted"],[SSE_EVENTS.SESSION_TERMINAL,"_onSSETerminal"],[SSE_EVENTS.SESSION_NEEDS_REFRESH,"_onSSENeedsRefresh"],[SSE_EVENTS.SESSION_CLEAR_TERMINAL,"_onSSEClearTerminal"],[SSE_EVENTS.SESSION_COMPLETION,"_onSessionCompletion"],[SSE_EVENTS.SESSION_ERROR,"_onSessionError"],[SSE_EVENTS.SESSION_EXIT,"_onSessionExit"],[SSE_EVENTS.SESSION_IDLE,"_onSessionIdle"],[SSE_EVENTS.SESSION_WORKING,"_onSessionWorking"],[SSE_EVENTS.SESSION_AUTO_CLEAR,"_onSessionAutoClear"],[SSE_EVENTS.SESSION_LIMIT_PAUSE_SCHEDULED,"_onSessionLimitPauseScheduled"],[SSE_EVENTS.SESSION_LIMIT_RESUME,"_onSessionLimitResume"],[SSE_EVENTS.SESSION_LIMIT_RESUME_CANCELLED,"_onSessionLimitResumeCancelled"],[SSE_EVENTS.SESSION_RESPAWN_BREAKER_TRIPPED,"_onSessionRespawnBreakerTripped"],[SSE_EVENTS.SESSION_CLI_INFO,"_onSessionCliInfo"],[SSE_EVENTS.SESSION_STATUS_TELEMETRY,"_onSessionStatusTelemetry"],[SSE_EVENTS.SESSION_PROMPT_CACHE,"_onSessionPromptCache"],[SSE_EVENTS.SESSION_KEEP_WARM,"_onSessionKeepWarm"],[SSE_EVENTS.SCHEDULED_CREATED,"_onScheduledCreated"],[SSE_EVENTS.SCHEDULED_UPDATED,"_onScheduledUpdated"],[SSE_EVENTS.SCHEDULED_COMPLETED,"_onScheduledCompleted"],[SSE_EVENTS.SCHEDULED_STOPPED,"_onScheduledStopped"],[SSE_EVENTS.CRON_JOBS_CHANGED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_JOB_DELETED,"_onCronJobsChanged"],[SSE_EVENTS.CRON_RUN_CREATED,"_onCronRunChanged"],[SSE_EVENTS.CRON_RUN_UPDATED,"_onCronRunChanged"],[SSE_EVENTS.RESPAWN_STARTED,"_onRespawnStarted"],[SSE_EVENTS.RESPAWN_STOPPED,"_onRespawnStopped"],[SSE_EVENTS.RESPAWN_STATE_CHANGED,"_onRespawnStateChanged"],[SSE_EVENTS.RESPAWN_CYCLE_STARTED,"_onRespawnCycleStarted"],[SSE_EVENTS.RESPAWN_BLOCKED,"_onRespawnBlocked"],[SSE_EVENTS.RESPAWN_AUTO_ACCEPT_SENT,"_onRespawnAutoAcceptSent"],[SSE_EVENTS.RESPAWN_DETECTION_UPDATE,"_onRespawnDetectionUpdate"],[SSE_EVENTS.RESPAWN_TIMER_STARTED,"_onRespawnTimerStarted"],[SSE_EVENTS.RESPAWN_TIMER_CANCELLED,"_onRespawnTimerCancelled"],[SSE_EVENTS.RESPAWN_TIMER_COMPLETED,"_onRespawnTimerCompleted"],[SSE_EVENTS.RESPAWN_ERROR,"_onRespawnError"],[SSE_EVENTS.RESPAWN_ACTION_LOG,"_onRespawnActionLog"],[SSE_EVENTS.TASK_CREATED,"_onTaskCreated"],[SSE_EVENTS.TASK_COMPLETED,"_onTaskCompleted"],[SSE_EVENTS.TASK_FAILED,"_onTaskFailed"],[SSE_EVENTS.TASK_UPDATED,"_onTaskUpdated"],[SSE_EVENTS.MUX_CREATED,"_onMuxCreated"],[SSE_EVENTS.MUX_KILLED,"_onMuxKilled"],[SSE_EVENTS.MUX_DIED,"_onMuxDied"],[SSE_EVENTS.MUX_STATS_UPDATED,"_onMuxStatsUpdated"],[SSE_EVENTS.REMOTE_SESSION_RECONNECTED,"_onRemoteSessionReconnected"],[SSE_EVENTS.REMOTE_RECONNECT_EXHAUSTED,"_onRemoteReconnectExhausted"],[SSE_EVENTS.REMOTE_HOST_WAKING,"_onRemoteHostWaking"],[SSE_EVENTS.REMOTE_HOST_WAKE_FAILED,"_onRemoteHostWakeFailed"],[SSE_EVENTS.SESSION_RALPH_LOOP_UPDATE,"_onRalphLoopUpdate"],[SSE_EVENTS.SESSION_RALPH_TODO_UPDATE,"_onRalphTodoUpdate"],[SSE_EVENTS.SESSION_RALPH_COMPLETION_DETECTED,"_onRalphCompletionDetected"],[SSE_EVENTS.SESSION_RALPH_STATUS_UPDATE,"_onRalphStatusUpdate"],[SSE_EVENTS.SESSION_CIRCUIT_BREAKER_UPDATE,"_onCircuitBreakerUpdate"],[SSE_EVENTS.SESSION_EXIT_GATE_MET,"_onExitGateMet"],[SSE_EVENTS.SESSION_BASH_TOOL_START,"_onBashToolStart"],[SSE_EVENTS.SESSION_BASH_TOOL_END,"_onBashToolEnd"],[SSE_EVENTS.SESSION_BASH_TOOLS_UPDATE,"_onBashToolsUpdate"],[SSE_EVENTS.HOOK_IDLE_PROMPT,"_onHookIdlePrompt"],[SSE_EVENTS.HOOK_PERMISSION_PROMPT,"_onHookPermissionPrompt"],[SSE_EVENTS.HOOK_ELICITATION_DIALOG,"_onHookElicitationDialog"],[SSE_EVENTS.HOOK_ELICITATION_COMPLETE,"_onHookElicitationComplete"],[SSE_EVENTS.HOOK_ELICITATION_RESPONSE,"_onHookElicitationResponse"],[SSE_EVENTS.HOOK_STOP,"_onHookStop"],[SSE_EVENTS.HOOK_AGENT_WORKING,"_onHookAgentWorking"],[SSE_EVENTS.HOOK_TEAMMATE_IDLE,"_onHookTeammateIdle"],[SSE_EVENTS.HOOK_TASK_COMPLETED,"_onHookTaskCompleted"],[SSE_EVENTS.APPROVAL_PENDING,"_onApprovalPending"],[SSE_EVENTS.APPROVAL_UPDATED,"_onApprovalUpdated"],[SSE_EVENTS.APPROVAL_RESOLVED,"_onApprovalResolved"],[SSE_EVENTS.SUBAGENT_DISCOVERED,"_onSubagentDiscovered"],[SSE_EVENTS.SUBAGENT_UPDATED,"_onSubagentUpdated"],[SSE_EVENTS.SUBAGENT_TOOL_CALL,"_onSubagentToolCall"],[SSE_EVENTS.SUBAGENT_PROGRESS,"_onSubagentProgress"],[SSE_EVENTS.SUBAGENT_MESSAGE,"_onSubagentMessage"],[SSE_EVENTS.SUBAGENT_TOOL_RESULT,"_onSubagentToolResult"],[SSE_EVENTS.SUBAGENT_COMPLETED,"_onSubagentCompleted"],[SSE_EVENTS.WORKFLOW_RUN_DISCOVERED,"_onWorkflowRunDiscovered"],[SSE_EVENTS.WORKFLOW_RUN_UPDATED,"_onWorkflowRunUpdated"],[SSE_EVENTS.WORKFLOW_RUN_REMOVED,"_onWorkflowRunRemoved"],[SSE_EVENTS.IMAGE_DETECTED,"_onImageDetected"],[SSE_EVENTS.ATTACHMENT_DETECTED,"_onAttachmentDetected"],[SSE_EVENTS.TRANSCRIPT_TOOL_END,"_onEditHistoryTranscriptEvent"],[SSE_EVENTS.TUNNEL_STARTED,"_onTunnelStarted"],[SSE_EVENTS.TUNNEL_STOPPED,"_onTunnelStopped"],[SSE_EVENTS.TUNNEL_PROGRESS,"_onTunnelProgress"],[SSE_EVENTS.TUNNEL_ERROR,"_onTunnelError"],[SSE_EVENTS.TUNNEL_QR_ROTATED,"_onTunnelQrRotated"],[SSE_EVENTS.TUNNEL_QR_REGENERATED,"_onTunnelQrRegenerated"],[SSE_EVENTS.TUNNEL_QR_AUTH_USED,"_onTunnelQrAuthUsed"],[SSE_EVENTS.PLAN_SUBAGENT,"_onPlanSubagent"],[SSE_EVENTS.PLAN_PROGRESS,"_onPlanProgress"],[SSE_EVENTS.PLAN_STARTED,"_onPlanStarted"],[SSE_EVENTS.PLAN_CANCELLED,"_onPlanCancelled"],[SSE_EVENTS.PLAN_COMPLETED,"_onPlanCompleted"],[SSE_EVENTS.ORCHESTRATOR_STATE_CHANGED,"_onOrchestratorStateChanged"],[SSE_EVENTS.ORCHESTRATOR_PLAN_PROGRESS,"_onOrchestratorPlanProgress"],[SSE_EVENTS.ORCHESTRATOR_PLAN_READY,"_onOrchestratorPlanReady"],[SSE_EVENTS.ORCHESTRATOR_PHASE_STARTED,"_onOrchestratorPhaseStarted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_COMPLETED,"_onOrchestratorPhaseCompleted"],[SSE_EVENTS.ORCHESTRATOR_PHASE_FAILED,"_onOrchestratorPhaseFailed"],[SSE_EVENTS.ORCHESTRATOR_VERIFICATION,"_onOrchestratorVerification"],[SSE_EVENTS.ORCHESTRATOR_TASK_ASSIGNED,"_onOrchestratorTaskAssigned"],[SSE_EVENTS.ORCHESTRATOR_TASK_COMPLETED,"_onOrchestratorTaskCompleted"],[SSE_EVENTS.ORCHESTRATOR_TASK_FAILED,"_onOrchestratorTaskFailed"],[SSE_EVENTS.ORCHESTRATOR_COMPLETED,"_onOrchestratorCompleted"],[SSE_EVENTS.ORCHESTRATOR_ERROR,"_onOrchestratorError"],[SSE_EVENTS.CLIPBOARD_WRITE,"_onClipboardWrite"],[SSE_EVENTS.SESSION_ORDER_CHANGED,"_onSessionOrderChanged"],[SSE_EVENTS.TAB_LAYOUT_CHANGED,"_onTabLayoutChanged"],[SSE_EVENTS.WEBVIEW_CHANGED,"_onWebviewChanged"]];function parseSessionPrefix(m){if(!m)return null;const e=m.match(/^(w\d+-[a-zA-Z0-9_-]+|s\d+-[a-zA-Z0-9_-]+)/);if(!e)return null;const t=e[1],s=m.slice(t.length);return s===""?{prefix:t,suffix:""}:s.startsWith(": ")?{prefix:t,suffix:s.slice(2)}:null}function paneExitLabel(m){return!m||typeof m!="object"?"":typeof m.signal=="number"&&m.signal>0?`exited (signal ${m.signal})`:typeof m.status=="number"?`exited (${m.status})`:"exited"}function paneExitAriaLabel(m,e){return e?`${m} session, agent ${e}`:`${m} session`}function applyPaneExitBadge(m,e){const t=paneExitLabel(e),s=m.querySelector(".tab-exited-badge");m.classList.toggle("tab-agent-exited",!!t);const i=m.querySelector(".tab-name")?.dataset?.fullName;if(i){const n=paneExitAriaLabel(i,t);m.dataset.ariaSource!==n&&(m.dataset.ariaSource=n,m.setAttribute("aria-label",n))}if(!t){s?.remove();return}if(!s){const n=document.createElement("span");n.className="tab-exited-badge",n.setAttribute("aria-hidden","true"),n.dataset.label=t,n.textContent=t,m.querySelector(".tab-name")?.insertAdjacentElement("afterend",n);return}s.dataset.label!==t&&(s.dataset.label=t,s.textContent=t)}const DEFAULT_SHORTCUTS=[{id:"show-shortcuts",group:"Panels",label:"Show Shortcuts",bindings:[{modifiers:["ctrl"],key:"?",code:"Slash"},{modifiers:["ctrl","shift"],key:"?"},{modifiers:["alt"],key:"?",code:"Slash"}],action:"showShortcutOverlay"},{id:"close-session",group:"Session",label:"Close Session",bindings:[],action:"killActiveSession"},{id:"next-session",group:"Session",label:"Next Session",bindings:[{modifiers:["ctrl"],key:"Tab"}],action:"nextSession"},{id:"clear-terminal",group:"Terminal",label:"Clear Terminal",bindings:[{modifiers:["ctrl"],key:"l"}],action:"clearTerminal"},{id:"copy-selection",group:"Terminal",label:"Copy Selection",bindings:[{modifiers:["ctrl"],key:"c"},{modifiers:["ctrl","shift"],key:"C"}],action:"copyTerminalSelection"},{id:"increase-font",group:"Terminal",label:"Increase Font",bindings:[{modifiers:["ctrl"],key:"=",code:"Equal"},{modifiers:["ctrl"],key:"+",code:"Equal"}],action:"increaseFontSize"},{id:"decrease-font",group:"Terminal",label:"Decrease Font",bindings:[{modifiers:["ctrl"],key:"-",code:"Minus"}],action:"decreaseFontSize"},{id:"voice-input",group:"Terminal",label:"Voice Input",bindings:[{modifiers:["ctrl","shift"],key:"V"}],action:"toggleVoiceInput"},{id:"restore-terminal-size",group:"Terminal",label:"Restore Terminal Size",bindings:[{modifiers:["ctrl","shift"],key:"R"}],action:"restoreTerminalSize"},{id:"move-tab-left",group:"Tabs",label:"Move Active Tab Left",bindings:[{modifiers:["ctrl","shift"],key:"{",code:"BracketLeft"}],action:"moveActiveTabLeft"},{id:"move-tab-right",group:"Tabs",label:"Move Active Tab Right",bindings:[{modifiers:["ctrl","shift"],key:"}",code:"BracketRight"}],action:"moveActiveTabRight"},{id:"command-palette",group:"Session",label:"Find Open Session",bindings:[{modifiers:["ctrl"],key:"k",code:"KeyK"},{modifiers:["meta"],key:"k",code:"KeyK"},{modifiers:["alt"],key:"k",code:"KeyK"}],action:"openCommandPalette"},{id:"toggle-session-sidebar",group:"Session",label:"Toggle Session Sidebar",bindings:[{modifiers:["alt"],key:"b",code:"KeyB"}],action:"toggleSessionSidebar"},{id:"toggle-tile-grid",group:"Tiles",label:"Toggle Tile Grid",bindings:[{modifiers:["ctrl","shift"],key:"G",code:"KeyG"}],action:"toggleTileGrid"},{id:"focus-tile-left",group:"Tiles",label:"Focus Tile Left",bindings:[{modifiers:["alt","shift"],key:"ArrowLeft"}],action:"focusTileLeft"},{id:"focus-tile-right",group:"Tiles",label:"Focus Tile Right",bindings:[{modifiers:["alt","shift"],key:"ArrowRight"}],action:"focusTileRight"},{id:"focus-tile-up",group:"Tiles",label:"Focus Tile Up",bindings:[{modifiers:["alt","shift"],key:"ArrowUp"}],action:"focusTileUp"},{id:"focus-tile-down",group:"Tiles",label:"Focus Tile Down",bindings:[{modifiers:["alt","shift"],key:"ArrowDown"}],action:"focusTileDown"},{id:"move-tile-left",group:"Tiles",label:"Move Tile Left",bindings:[{modifiers:["ctrl","shift"],key:"ArrowLeft"}],action:"moveTileLeft"},{id:"move-tile-right",group:"Tiles",label:"Move Tile Right",bindings:[{modifiers:["ctrl","shift"],key:"ArrowRight"}],action:"moveTileRight"},{id:"move-tile-up",group:"Tiles",label:"Move Tile Up",bindings:[{modifiers:["ctrl","shift"],key:"ArrowUp"}],action:"moveTileUp"},{id:"move-tile-down",group:"Tiles",label:"Move Tile Down",bindings:[{modifiers:["ctrl","shift"],key:"ArrowDown"}],action:"moveTileDown"},{id:"zoom-tile",group:"Tiles",label:"Zoom Focused Tile",bindings:[{modifiers:["alt","shift"],key:"Enter"}],action:"zoomTile"},{id:"remove-tile",group:"Tiles",label:"Remove Focused Tile",bindings:[],action:"removeTile"},{id:"previous-session",group:"Session",label:"Previous Session",displayBindings:["Alt/Option+["],bindings:[{modifiers:["alt"],code:"BracketLeft"}],action:"previousSession"},{id:"next-session-alt",group:"Session",label:"Next Session (alternate)",displayBindings:["Alt/Option+]"],bindings:[{modifiers:["alt"],code:"BracketRight"}],action:"nextSession"},{id:"switch-tab-n",group:"Session",label:"Switch to Tab N",displayBindings:["Alt/Option+1-9"]},{id:"focus-tabs",group:"Tabs",label:"Focus Tabs",displayBindings:["ArrowLeft","ArrowRight","Home","End"]},{id:"activate-focused-tab",group:"Tabs",label:"Activate Focused Tab",displayBindings:["Enter","Space"]},{id:"insert-newline",group:"Terminal",label:"Insert Newline",displayBindings:["Shift+Enter","Ctrl+Enter"]},{id:"close-panels",group:"Panels",label:"Close Panels",displayBindings:["Escape"]},{id:"file-preview-history",group:"Panels",label:"File Viewer Back / Forward",displayBindings:["Alt/Option+ArrowLeft","Alt/Option+ArrowRight"]}],SIDEBAR_RICH_CLOCK_MS=2e4,CONNECTION_BACKLOG_HINT_BYTES=4,CONNECTION_BACKLOG_HOLD_MS=1200,URL_SESSION_WAIT_MS=3e4,TAB_LAYOUT_PENDING_MAX_AGE_MS=6e4,TAB_GROUP_ARRIVAL_MS=2e3;class CodemanApp{constructor(){this.sessions=new Map,this._shortIdCache=new Map,this.sessionOrder=[],this.draggedTabId=null,this.tabLayout=null,this.collapsedTabGroupIds=new Set,this._hiddenTabGroupByRef=new Map,this._lastTabGroupStructureKey=null,this._tabRailSearch="",this.cases=[],this.currentRun=null,this.totalTokens=0,this.globalStats=null,this.eventSource=null,this._clientId=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"c-"+Math.random().toString(36).slice(2)+Date.now().toString(36),this._wsTabNonce=this._clientId,this.terminal=null,this.fitAddon=null,this.activeSessionId=null,this.soloSessionId=this._detectSoloSessionId(),this.isSoloWindow=!!this.soloSessionId,this._urlSessionId=this.isSoloWindow?null:this._takeUrlSession(),this._urlSessionWaitTimer=null,this.detachedSessions=new Set,this.detachedWindows=new Map,this._detachWatchTimers=new Map,this.windowChannel=null,this._redockGrace=new Map,this._detachPingPending=null,this._detachLivenessTimer=null,this._detachOrphanStrikes=new Map,this._initGeneration=0,this._initFallbackTimer=null,this._selectGeneration=0,this._fullHistoryLoaded=new Set,this._paneHistoryLines=new Map,this._fullHistoryRepullAt=new Map,this._fullHistoryRepullInFlight=!1,this._fullHistoryRepullUseless=new Set,this._geometryRetryUseless=new Set,this.terminalLoadStates=new Map,this.respawnStatus={},this.respawnTimers={},this.respawnCountdownTimers={},this.respawnActionLogs={},this.timerCountdownInterval=null,this.terminalBuffers=new Map,this.editingSessionId=null,this.pendingCloseSessionId=null,this.muxSessions=[],this.ralphStates=new Map,this.subagents=new Map,this.subagentActivity=new Map,this.subagentToolResults=new Map,this.activeSubagentId=null,this.subagentPanelVisible=!1,this.workflowRuns=new Map,this.workflowRunDetails=new Map,this.activeWorkflowRunId=null,this.activeWorkflowPhaseIndex=null,this.ultracodeWindows=new Map,this.ultracodeWindowsClosed=new Set,this.ultracodeWindowCloseTimers=new Map,this.ultracodeWindowZIndex=1e3,this.subagentWindows=new Map,this.subagentWindowZIndex=ZINDEX_SUBAGENT_BASE,this.minimizedSubagents=new Map,this._subagentHideTimeout=null,this.subagentParentMap=new Map,this.teams=new Map,this.teamTasks=new Map,this.teammateMap=new Map,this.teammatePanesByName=new Map,this.teammateTerminals=new Map,this.terminalBufferCache=new Map,this.ralphStatePanelCollapsed=!0,this.ralphClosedSessions=new Set,this.planSubagents=new Map,this.planSubagentWindowZIndex=ZINDEX_PLAN_SUBAGENT_BASE,this.planGenerationStopped=!1,this.planAgentsMinimized=!1,this.wizardDragState=null,this.wizardDragListeners=null,this.wizardPosition=null,this.projectInsights=new Map,this.logViewerWindows=new Map,this.logViewerWindowZIndex=ZINDEX_LOG_VIEWER_BASE,this.projectInsightsPanelVisible=!1,this.orchestratorState=null,this.orchestratorPanelVisible=!1,this.currentSessionWorkingDir=null,this.imagePopups=new Map,this.imagePopupZIndex=ZINDEX_IMAGE_POPUP_BASE,this.attachmentCards=new Map,this.attachmentCardStack=null,this.attachmentHistoryCounts=new Map,this.attachmentHistoryItems=[],this.attachmentHistoryDrawerOpen=!1,this.fileBrowserData=null,this.fileBrowserExpandedDirs=new Set,this.fileBrowserFilter="",this.fileBrowserAllExpanded=!1,this.fileBrowserDragListeners=null,this.fileBrowserShowHidden=this._loadFileBrowserShowHidden?.()??!1,this.filePreviewContent="",this._toastContainer=null,this._tunnelUrl=null,this.tabAlerts=new Map,this.pendingHooks=new Map,this._closingSessions=new Set,this.approvals=new Map,this._ws=null,this._wsSessionId=null,this._wsReady=!1,this._wsState="disconnected",this._wsLastRecvAt=0,this._wsOutputGapSession=null,this.pendingWrites=[],this.writeFrameScheduled=!1,this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,this._wasAtBottomBeforeWrite=!0,this.syncWaitTimeout=null,this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._terminalRefreshOwner=null,this.flickerFilterBuffer="",this.flickerFilterActive=!1,this.flickerFilterTimeout=null,this._debounceTimers=Object.create(null),this.systemStatsInterval=null,this.sseReconnectTimeout=null,this._sseListenerCleanup=null,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.isOnline=navigator.onLine,this._sseLastMessageAt=0,this._sseStaleTimeoutMs=window.CodemanSseStale?.TIMEOUT_MS??45e3,this._sseStaleWatchdog=null,this._sseConnectTimeout=null,this._sseConnectTimeoutMs=window.CodemanSseStale?.CONNECT_TIMEOUT_MS??15e3,this._connDownSince=null,this._nextSseRetryAt=null,this._offlineOverlayDismissed=!1,this._offlineRetryPending=!1,this._offlineUiTicker=null,this._lastOfflineUiKey="",this._connectionStatus="connected",this._clientId="",this._seqCounters=new Map,this._pendingDeliveries=new Map,this._lastIndicatorDescriptor=null,this._lastIndicatorLanguage=null,this._postDraining=new Set,this._extraInputSockets=new Map,this._persistReliableTimer=null,this._reliableAckTimeoutMs=4e3,this._reliableMaxBytes=256*1024,this._loadReliableState(),this._reliableSweepTimer=setInterval(()=>this._redeliverSweep(),2e3),window.addEventListener("pagehide",()=>this._persistReliableNow()),window.addEventListener("pagehide",()=>this._persistPendingTabLayoutEdits()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._persistReliableNow():this._checkSseStale()}),this._localEchoOverlay=null,this._localEchoEnabled=!1,this._predictiveEcho=null,this._localEchoPolicy="off",this._restoringFlushedState=!1,this.activeFocusTrap=null,this.notificationManager=new NotificationManager(this),this.idleTimers=new Map,this._elemCache={},this.init()}$(e){return this._elemCache[e]||(this._elemCache[e]=document.getElementById(e)),this._elemCache[e]}_clearTimer(e){this[e]&&(clearTimeout(this[e]),this[e]=null)}_isStaleSelect(e){return e!==this._selectGeneration?(this._isLoadingBuffer&&this._finishBufferLoad(e),this._restoringFlushedState=!1,!0):!1}formatTokens(e){if(e>=1e6){const t=e/1e6;return t>=10?`${t.toFixed(1)}m`:`${t.toFixed(2)}m`}else if(e>=1e3){const t=e/1e3;return t>=100?`${t.toFixed(0)}k`:`${t.toFixed(1)}k`}return String(e)}estimateCost(e,t){const s=e/1e6*15,i=t/1e6*75;return s+i}setPendingHook(e,t){this.pendingHooks.has(e)||this.pendingHooks.set(e,new Set),this.pendingHooks.get(e).add(t),this.updateTabAlertFromHooks(e)}clearPendingHooks(e,t=null){const s=this.pendingHooks.get(e);s&&(t?s.delete(t):s.clear(),s.size===0&&this.pendingHooks.delete(e),this.updateTabAlertFromHooks(e))}markIdleAlertSeen(e){this.pendingHooks?.get(e)?.has("idle_prompt")&&(this.clearPendingHooks(e,"idle_prompt"),this.acknowledgeIdleApprovalOnView?.(e))}updateTabAlertFromHooks(e){const t=this.pendingHooks.get(e);!t||t.size===0?this.tabAlerts.delete(e):t.has("permission_prompt")||t.has("elicitation_dialog")?this.tabAlerts.set(e,"action"):t.has("idle_prompt")&&this.tabAlerts.set(e,"idle"),this.renderSessionTabs()}init(){MobileDetection.init(),this._initWindowChannel(),this.isSoloWindow&&document.body.classList.add("solo-mode"),this.isSoloWindow||window.addEventListener("hashchange",()=>{const s=this._takeUrlSession();s&&(this._retireUrlSession(),this._urlSessionId=s,this._selectUrlSession())}),document.documentElement.classList.toggle("host-windows",this.hasHostWindows()),KeyboardHandler.init(),SwipeHandler.init(),VoiceInput.init(),KeyboardAccessoryBar.init();const e=this.loadAppSettingsFromStorage();KeyboardAccessoryBar.setMode(e.extendedKeyboardBar?"extended":"simple"),this.applyHeaderVisibilitySettings(),this.restorePlanUsageChip(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation(),this._wireMobileOverviewBreakpoint?.(),this._wireHomeSessionsBreakpoint?.(),this.initTabRailResize?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),this._installLineageStripScrollListener?.(),this._setupTabMiddleClickClose(),this.initEntranceAnimations?.(),document.documentElement.classList.remove("mobile-init"),requestAnimationFrame(()=>{this.initTerminal(),this.loadFontSize(),this.connectSSE(),this._initFallbackTimer=setTimeout(()=>{this._initGeneration===0&&this.loadState()},3e3)}),this.registerServiceWorker(),this.loadTunnelStatus(),this.initRebootRestoreBanner?.();const t=fetch("/api/settings").then(s=>s.ok?s.json():null).then(s=>s?.data??null).catch(()=>null);if(this.loadQuickStartCases(null,t),this._initRunMode(),this.initWebviews?.(),this.setupEventListeners(),MobileDetection.isTouchDevice()){const s=i=>{i&&i.addEventListener("touchstart",n=>{if(!KeyboardHandler.keyboardVisible)return;const o=n.target.closest("button");o&&(n.preventDefault(),o.click(),typeof app<"u"&&app.terminal&&app.terminal.focus())},{passive:!1})};s(document.querySelector(".toolbar")),s(document.querySelector(".welcome-overlay"))}this.setupOnlineDetection(),this.loadAppSettingsFromServer(t).then(()=>{this.applyHeaderVisibilitySettings(),this.applySkin(),this.applyLocalization(),this.applySessionListLayout(),this.applyTabOrientation?.(),this.applyMonitorVisibility(),this.applyLineageLineSettings?.(),typeof this.syncAllUltracodeFloatingWindows=="function"&&this.syncAllUltracodeFloatingWindows()}),document.body.classList.add("app-loaded")}_initWebGL(){if(!(typeof WebglAddon>"u"))try{this._webglAddon=new WebglAddon.WebglAddon,this._webglAddon.onContextLoss(()=>{console.error("[CRASH-DIAG] WebGL context LOST \u2014 falling back to canvas renderer"),_crashDiag.log("WEBGL_LOST"),this._disableWebGLSticky("context-lost"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint()}),this.terminal.loadAddon(this._webglAddon),console.log("[CRASH-DIAG] WebGL renderer enabled"),this._installWebGLLongTaskGuard()}catch{}}_installWebGLLongTaskGuard(){if(typeof PerformanceObserver>"u"||this._webglLongTaskObserver)return;const e=performance.now(),t=[];try{this._webglLongTaskObserver=new PerformanceObserver(s=>{if(!this._webglAddon||this._tilesOwnTerminal?.())return;const i=performance.now();i-e<WEBGL_FALLBACK.GRACE_MS||evaluateWebGLLongTaskTrip(t,s.getEntries(),i)&&(console.warn(`[CRASH-DIAG] WebGL long-task threshold (${t.length} stalls/${WEBGL_FALLBACK.WINDOW_MS}ms) \u2014 falling back to canvas renderer`),_crashDiag.log(`WEBGL_FALLBACK: ${t.length}`),this._disableWebGLSticky("long-tasks"),this._disposeWebGLObserver(),this._webglAddon?.dispose(),this._webglAddon=null,this._scheduleTerminalRepaint())}),this._webglLongTaskObserver.observe({type:"longtask",buffered:!1})}catch{}}_disposeWebGLObserver(){if(this._webglLongTaskObserver){try{this._webglLongTaskObserver.disconnect()}catch{}this._webglLongTaskObserver=null}}_scheduleTerminalRepaint(){if(this._terminalRepaintScheduled)return;this._terminalRepaintScheduled=!0,(typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,0))(()=>{this._terminalRepaintScheduled=!1;try{this.terminal?.refresh(0,this.terminal.rows-1)}catch{}})}_disableWebGLSticky(e){try{localStorage.setItem("codeman-webgl-disabled",JSON.stringify({reason:e,at:Date.now()}))}catch{}}setupEventListeners(){const e=this._shortcutActions();document.addEventListener("keydown",s=>{if(s.target?.closest?.("[data-raw-keys]")||s.isComposing||s.keyCode===229)return;if(this.shouldOpenCommandPaletteFromShortcut?.(s)){s.preventDefault(),this.openCommandPalette();return}if(s.key==="Escape"){if(this._tabGroupMenu&&this._tabGroupMenuKeydown){this._tabGroupMenuKeydown(s);return}if(this._tabLayoutDrag?.active&&this._tabLayoutDragKeydown){this._tabLayoutDragKeydown(s);return}if(this._tileCountMenu){this.closeTileCountMenu({refocus:!0});return}if(s.target?.id==="tabRailSearch"&&this._tabRailSearch){this.handleTabRailSearchKeydown(s);return}if(this.isLocalModelWindowOpen?.()){this.closeLocalModelWindow();return}this.closeAllPanels(),this.closeHelp(),this.attachmentHistoryDrawerOpen&&this.closeAttachmentHistory(),this.closeWorktreeModal?.(),this.closeSessionManager(),this.closeCommandPalette?.(),this.closeShortcutOverlay?.(),this._isSessionSidebarOverlay()&&this.isSessionSidebarActive()&&!this.isSessionSidebarCollapsed()&&(this.toggleSessionSidebar(),document.getElementById("sidebarToggleBtn")?.focus())}if(s.altKey&&!s.ctrlKey&&!s.shiftKey){const o=(s.code||"").match(/^Digit([1-9])$/);if(o){const a=parseInt(o[1],10)-1,r=this.sessionOrder.filter(l=>this.sessions.has(l));if(a<r.length)s.preventDefault(),this.selectSession(r[a]);else{const l=a-r.length,c=(this.webviewOrder||[])[l];c&&(s.preventDefault(),this.openWebview(c))}return}}const i=this.tileShortcutFor?.(s);if(i){s.preventDefault(),this.runTileShortcut(i);return}if(!(!s.ctrlKey&&!s.metaKey&&!s.altKey))for(const n of this.getShortcutRegistry()){if(n.disabled||!n.action)continue;const o=e[n.action];if(o&&this.matchesShortcutEvent(s,n)){s.preventDefault(),o();return}}},!0);const t=this.$("headerTokens");t&&!t._statsHandlerAttached&&(t.classList.add("clickable"),t._statsHandlerAttached=!0,t.addEventListener("click",()=>this.openTokenStats())),this.setupColorPicker()}_sseFilterSessionId(e){return this._tilesOwnTerminal?.()&&window.CodemanTileGrid?.TILE_GRID_SSE_FILTER||e}_updateSseSubscription(e){try{const t=this._sseFilterSessionId(e),s=JSON.stringify({clientId:this._clientId,sessions:t?[t]:null});fetch("/api/events/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:s,keepalive:!0}).catch(()=>{})}catch{}}_detectSoloSessionId(){try{if(typeof window<"u"&&typeof window.__CODEMAN_SOLO__=="string"&&window.__CODEMAN_SOLO__)return window.__CODEMAN_SOLO__;const e=window.CodemanBase?.base||"";let t=location.pathname;e&&t.startsWith(e)&&(t=t.slice(e.length)||"/");const s=t.match(/^\/session\/([^/]+)\/?$/);return s?decodeURIComponent(s[1]):null}catch{return null}}_takeUrlSession(){const e=window.CodemanUrlSession?.sessionIdFromFragment(location.hash)??null;if(e)try{history.replaceState(history.state,"",location.pathname+location.search)}catch{}return e}_selectUrlSession(){const e=this._urlSessionId;return e?this.sessions.has(e)?(this._retireUrlSession(),this.selectSession(e,{auto:!0,leaveTiles:!0}),!0):(this._armUrlSessionWait(e),!1):!1}_armUrlSessionWait(e){this._urlSessionWaitTimer||(this._urlSessionWaitTimer=setTimeout(()=>{if(this._urlSessionWaitTimer=null,this._urlSessionId===e){if(this.sessions.has(e)){this._selectUrlSession();return}this._retireUrlSession(),this.showToast?.("Session not found","warning")}},URL_SESSION_WAIT_MS))}_retireUrlSession(){this._urlSessionId=null,this._urlSessionWaitTimer&&(clearTimeout(this._urlSessionWaitTimer),this._urlSessionWaitTimer=null)}detachSession(e,t=null){if(this.isSoloWindow||!this.sessions.has(e)||this.detachedSessions.has(e)&&this._raiseDetached(e))return;const s=this.hasHostWindows()&&!this.windowChannel?!1:this.openInHostWindow(CodemanBase.url("/session/"+encodeURIComponent(e)));if(s!==null){if(!s){this.showToast?.("Could not open a new window for this session","error");return}this._markDetached(e,!0),this._postWindowMessage({type:"detached",id:e});return}const i=this._detachWindowFeatures(t);let n=null;try{n=window.open(CodemanBase.url("/session/"+encodeURIComponent(e)),"codeman-session-"+e,i)}catch{}if(!n){this.showToast?.("Pop-out blocked \u2014 allow popups for this site to detach a session","error");return}this.detachedWindows.set(e,n),this._markDetached(e,!0),this._watchDetachedWindow(e,n),this._postWindowMessage({type:"detached",id:e});try{n.focus()}catch{}}_detachWindowFeatures(e){const t=r=>Number.isFinite(r)?Math.round(r):null,s=t(e?.width)??960,i=t(e?.height)??680,n=t(e?.left),o=t(e?.top),a=n!==null&&o!==null?`,left=${n},top=${o}`:"";return`width=${s},height=${i}${a},menubar=no,toolbar=no,location=no,status=no`}hasHostWindows(){try{return typeof window<"u"&&typeof window.CodemanHost?.openWindow=="function"}catch{return!1}}tabDetachButtonEnabled(e,t={}){return e?.showTabDetachButton??(this.hasHostWindows()||(t?.showTabDetachButton??!1))}openInHostWindow(e){if(!this.hasHostWindows())return null;try{return window.CodemanHost.openWindow(new URL(e,location.href).href)!==!1}catch{return!1}}_raiseDetached(e){const t=this.detachedWindows.get(e);if(t&&!t.closed){try{t.focus()}catch{}return!0}return t&&t.closed?(this._redock(e),!1):(this._postWindowMessage({type:"focus-request",id:e}),!0)}redockSession(e){const t=this.detachedWindows.get(e);if(t&&!t.closed)try{t.close()}catch{}this._postWindowMessage({type:"close-request",id:e}),this._redock(e)}_redock(e){const t=this._detachWatchTimers.get(e);t&&(clearInterval(t),this._detachWatchTimers.delete(e)),this._cancelPendingRedock(e),this._detachOrphanStrikes.delete(e),this.detachedWindows.delete(e),this._markDetached(e,!1),this._lastResizeDims=null,this.sessions.has(e)&&e===this.activeSessionId&&this.sendResize(e,{force:!0})?.catch?.(()=>{})}_scheduleRedock(e){if(this._redockGrace.has(e))return;const t=setTimeout(()=>{this._redockGrace.delete(e),this._redock(e)},1500);this._redockGrace.set(e,t)}_cancelPendingRedock(e){const t=this._redockGrace.get(e);t&&(clearTimeout(t),this._redockGrace.delete(e))}_markDetached(e,t){t?this.detachedSessions.add(e):this.detachedSessions.delete(e),t&&this._tileGrid?.has(e)&&this.removeTile(e,{gone:!0});const s=this.$("sessionTabs"),i=s&&s.querySelector(`.session-tab[data-id="${e}"]`);i&&i.classList.toggle("detached",t)}_watchDetachedWindow(e,t){const s=this._detachWatchTimers.get(e);s&&clearInterval(s);const i=setInterval(()=>{(!t||t.closed)&&(clearInterval(i),this._detachWatchTimers.delete(e),this._redock(e))},800);this._detachWatchTimers.set(e,i)}_initWindowChannel(){if(!(typeof BroadcastChannel>"u")){try{this.windowChannel=new BroadcastChannel("codeman-windows")}catch{this.windowChannel=null;return}if(this.windowChannel.onmessage=e=>this._onWindowMessage(e.data),this.isSoloWindow){this._postWindowMessage({type:"detached",id:this.soloSessionId});const e=()=>this._postWindowMessage({type:"redocked",id:this.soloSessionId});window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}else this._postWindowMessage({type:"roll-call"}),this._startDetachLiveness()}}_postWindowMessage(e){try{this.windowChannel&&this.windowChannel.postMessage(e)}catch{}}_onWindowMessage(e){if(!(!e||typeof e!="object")){if(this.isSoloWindow){if(e.type==="roll-call"){this._soloReleased||this._postWindowMessage({type:"detached",id:this.soloSessionId});return}if(e.id!==this.soloSessionId)return;if(e.type==="close-request")this._releaseSoloWindow();else if(e.type==="focus-request")try{typeof window.CodemanHost?.focusWindow=="function"?window.CodemanHost.focusWindow():window.focus()}catch{}return}if(e.type==="detached"&&e.id){if(this._tileDockedRecently?.(e.id))return;this._cancelPendingRedock(e.id),this._detachPingPending?.delete(e.id),this._detachOrphanStrikes.delete(e.id),this._markDetached(e.id,!0)}else e.type==="redocked"&&e.id?this._scheduleRedock(e.id):e.type==="detach-request"&&e.id?this.detachSession(e.id):e.type==="tile-adopted"&&e.id&&e.by!==this._wsTabNonce&&this._onTileAdoptedElsewhere?.(e.id)}}_startDetachLiveness(){this._detachLivenessTimer||(this._detachLivenessTimer=setInterval(()=>this._pingDetached(),5e3))}_pingDetached(){const e=[];for(const t of this.detachedSessions){const s=this.detachedWindows.get(t);s?s.closed&&this._redock(t):e.push(t)}e.length&&(this._detachPingPending=new Set(e),this._postWindowMessage({type:"roll-call"}),setTimeout(()=>{if(this._detachPingPending){for(const t of this._detachPingPending){const s=(this._detachOrphanStrikes.get(t)||0)+1;s>=2?(this._detachOrphanStrikes.delete(t),this._redock(t)):this._detachOrphanStrikes.set(t,s)}this._detachPingPending=null}},1200))}_closeSoloWindow(){try{typeof window.CodemanHost?.closeWindow=="function"?window.CodemanHost.closeWindow():window.close()}catch{}}_releaseSoloWindow(){this._soloReleased||(this._soloReleased=!0,this._postWindowMessage({type:"redocked",id:this.soloSessionId}),this._closeSoloWindow(),setTimeout(()=>{window.closed||this._showSoloReleased()},300))}_showSoloReleased(){if(document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay";const t=document.createElement("h2");t.textContent="Session moved";const s=document.createElement("p");s.textContent="This session is back in a Codeman window. This one can be closed.";const i=document.createElement("button");i.className="btn-primary",i.textContent="Close window",i.addEventListener("click",()=>this._closeSoloWindow()),e.append(t,s,i),document.body.appendChild(e)}_applySoloMode(){document.body.classList.add("solo-mode");const e=this.sessions.get(this.soloSessionId);if(!e){this._showSoloSessionGone();return}this.activeSessionId=null,this.selectSession(this.soloSessionId,{auto:!0});const t=this.getSessionName(e)||"Session",s=document.getElementById("soloSessionTitle");s&&(s.textContent=t,s.style.display="");const i=document.getElementById("soloRedockBtn");i&&(i.style.display=""),this._installSoloTileHandle?.(),document.title=t+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman"),this.notificationManager&&(this.notificationManager.originalTitle=document.title);const n=document.querySelector(".header-brand .logo");n&&(n.onclick=o=>{o.preventDefault()})}_showSoloSessionGone(){if(document.body.classList.add("solo-mode"),document.querySelector(".solo-gone-overlay"))return;const e=document.createElement("div");e.className="solo-gone-overlay",e.innerHTML='<h2>Session unavailable</h2><p>This session has ended or is no longer available.</p><button class="btn-primary" onclick="app._closeSoloWindow()">Close window</button>',document.body.appendChild(e),document.title=(window.codemanT?.("Session ended")||"Session ended")+" \u2014 "+(window.CodemanI18n?.displayName||"Codeman")}connectSSE(){if(this._clearTimer("_sseConnectTimeout"),!navigator.onLine){this.setConnectionStatus("offline");return}this._clearTimer("sseReconnectTimeout"),this._sseStaleWatchdog&&(clearInterval(this._sseStaleWatchdog),this._sseStaleWatchdog=null),this._sseListenerCleanup&&(this._sseListenerCleanup(),this._sseListenerCleanup=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.reconnectAttempts===0?this.setConnectionStatus("connecting"):this.setConnectionStatus("reconnecting");const e=new URLSearchParams({clientId:this._clientId}),t=this._sseFilterSessionId(this.activeSessionId);t&&e.set("sessions",t);const s=new EventSource(CodemanBase.url(`/api/events?${e.toString()}`));this.eventSource=s;const i=setTimeout(()=>{this._sseConnectTimeout===i&&(this._sseConnectTimeout=null,!(this.eventSource!==s||s.readyState===EventSource.OPEN)&&(console.warn(`[SSE] connection did not open within ${this._sseConnectTimeoutMs}ms, retrying`),this._handleSseConnectionFailure(s)))},this._sseConnectTimeoutMs);this._sseConnectTimeout=i;const n=[],o=(a,r)=>{const l=c=>{this._sseLastMessageAt=Date.now(),r(c)};this.eventSource.addEventListener(a,l),n.push({event:a,handler:l})};if(this._sseListenerCleanup=()=>{for(const{event:a,handler:r}of n)this.eventSource&&this.eventSource.removeEventListener(a,r);n.length=0},this.eventSource.onopen=()=>{this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts=0,this._sseLastMessageAt=Date.now(),this.setConnectionStatus("connected")},this.eventSource.onerror=()=>this._handleSseConnectionFailure(s),!this._sseHandlerWrappers){this._sseHandlerWrappers=new Map;for(const[a,r]of _SSE_HANDLER_MAP){const l=this[r],c=r==="_onSSETerminal"||r==="_onSSENeedsRefresh"||r==="_onSSEClearTerminal";this._sseHandlerWrappers.set(a,h=>{if(!(c&&this._wsReady))try{l.call(this,h.data?JSON.parse(h.data):{})}catch(d){console.error(`[SSE] Error handling ${a}:`,d)}})}}for(const[a]of _SSE_HANDLER_MAP)o(a,this._sseHandlerWrappers.get(a));for(const a of[SSE_EVENTS.SESSION_CREATED,SSE_EVENTS.SESSION_DELETED])o(a,()=>this._onSessionListMaybeChanged());o(SSE_EVENTS.DOCKER_EXPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export ready: ${r.bundle} (${Math.round((r.sizeBytes||0)/1e6)} MB)`,"success"),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker export complete:",r)}}),o(SSE_EVENTS.DOCKER_EXPORT_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker export failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker export failed:",r)}}),o(SSE_EVENTS.DOCKER_IMPORT_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Docker bundle imported as case "${r.name}"`,"success"),this.loadQuickStartCases?.(),this.refreshDockerExports?.()}catch(r){console.error("[SSE] docker import complete:",r)}}),o(SSE_EVENTS.DOCKER_CONTAINER_RECREATED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Container for "${r.name}" removed \u2014 next launch recreates it with the new config`,"info")}catch(r){console.error("[SSE] docker container recreated:",r)}}),o(SSE_EVENTS.CUSTOM_MODEL_SWAPPED_OUT,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`${r.sessionName||r.sessionId}'s model (${r.previousModel}) was swapped out on llama-swap by another session \u2014 currently loaded: ${r.currentlyLoadedModel}. Sending a message there will reload it.`,"warning",{duration:0})}catch(r){console.error("[SSE] custom model swapped out:",r)}}),o(SSE_EVENTS.ADMIN_USERS_CHANGED,()=>{window.codemanAdmin?.onUsersChanged?.()}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_STARTED,()=>{this.showToast("Building the Codeman agent image (first Docker case, a few minutes)...","info",{duration:8e3})}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_COMPLETE,a=>{try{const r=a.data?JSON.parse(a.data):{};r.error?this.showToast(`Agent image build failed: ${r.error}`,"error"):this.showToast("Agent image ready. Starting the container...","success")}catch(r){console.error("[SSE] docker image build complete:",r)}}),o(SSE_EVENTS.DOCKER_IMAGE_BUILD_FAILED,a=>{try{const r=a.data?JSON.parse(a.data):{};this.showToast(`Agent image build failed: ${r.error||"unknown error"}`,"error")}catch(r){console.error("[SSE] docker image build failed:",r)}}),o(SSE_EVENTS.SESSION_PINNED,a=>{let r=null;try{r=JSON.parse(a.data)}catch{}if(r&&r.id){const l=this.sessions.get(r.id);l&&(l.pinned=r.pinned===!0,l.pinnedAt=r.pinned?r.pinnedAt:void 0)}this._onSessionListMaybeChanged()}),o(SSE_EVENTS.HEARTBEAT,()=>{}),this._sseStaleWatchdog=setInterval(()=>this._checkSseStale(),5e3)}_handleSseConnectionFailure(e){if(this.eventSource!==e)return;this._clearTimer("_sseConnectTimeout"),this.reconnectAttempts++,this.reconnectAttempts>=this.maxReconnectAttempts?this.setConnectionStatus("disconnected"):this.setConnectionStatus("reconnecting"),this.eventSource=null,e.close(),this._clearTimer("sseReconnectTimeout");const t=this.reconnectAttempts<=1?200:Math.min(500*Math.pow(2,this.reconnectAttempts-2),3e4);this._nextSseRetryAt=Date.now()+t,this._updateConnectionLossUi(),this.sseReconnectTimeout=setTimeout(()=>this.connectSSE(),t)}_checkSseStale(){const e=window.CodemanSseStale;if(!e)return;const t=Date.now();e.compute({lastMessageAt:this._sseLastMessageAt,now:t,status:this._connectionStatus,isOnline:this.isOnline,timeoutMs:this._sseStaleTimeoutMs})&&(console.log(`[SSE] stream stale: no frame for ${t-this._sseLastMessageAt}ms (threshold ${this._sseStaleTimeoutMs}ms), forcing reconnect`),this.connectSSE())}_onInit(e){_crashDiag.log(`INIT: ${e.sessions?.length||0} sessions`),this.handleInit(e),this._ensureHostWakePoller?.()}_onSessionCreated(e){this._closingSessions?.has(e.id)||(this.sessions.set(e.id,e),this.sessionOrder.includes(e.id)||this.syncSessionOrder(),this.markSessionTabEntering?.(e.id),this.markTerminalEntering?.(e.id),e.parentSessionId&&this.markConnectionLineEntering?.("lineage:"+e.id),this.renderSessionTabs(),this.updateCost(),this._urlSessionId===e.id&&this._selectUrlSession())}_onSessionUpdated(e){const t=e.session||e;if(this._closingSessions?.has(t.id))return;const s=this.sessions.get(t.id),i=t.claudeSessionId&&(!s||!s.claudeSessionId);this.sessions.set(t.id,t),this.renderSessionTabs(),this.updateCost(),t.id===this.activeSessionId&&t.tokens&&this.updateRespawnTokens(t.tokens),t.id===this.activeSessionId&&this._reconcileKeyboardHold?.(),t.id===this.activeSessionId&&this._followFileBrowserWorktree?.(t),this.updateSubagentParentNames(t.id),this.editingSessionId===t.id&&this.updateGitFetchStatus(t.id),i&&(this.recheckOrphanSubagents(),requestAnimationFrame(()=>{this.updateConnectionLines()}))}_onSessionDeleted(e){if(this._wsSessionId===e.id&&this._disconnectWs(),this.isSoloWindow&&e.id===this.soloSessionId&&this._showSoloSessionGone(),this.detachedSessions.has(e.id)&&this._redock(e.id),this._cleanupSessionData(e.id),this.activeSessionId===e.id&&!this._closingSessions.has(e.id)){this.activeSessionId=null;try{localStorage.removeItem("codeman-active-session")}catch{}this.terminal.clear(),this.showWelcome()}this.renderSessionTabs(),this.renderRalphStatePanel(),this.renderProjectInsightsPanel()}_onSSETerminal(e){this._wsReady||this._onSessionTerminal(e)}_onSSENeedsRefresh(e){this._wsReady||this._onSessionNeedsRefresh(e)}_onSSEClearTerminal(e){this._wsReady||this._onSessionClearTerminal(e)}_bufferLoadFinishOpts(e,t){return{flushQueued:e?.source==="mux-visible"||e?.source==="mux-full-history",since:t}}_onSessionTerminal(e){if(!this._tilesOwnTerminal?.()&&e.id===this.activeSessionId){e.data.length>32768&&_crashDiag.log(`TERMINAL: ${(e.data.length/1024).toFixed(0)}KB`);const t=(this.pendingWrites?.reduce((s,i)=>s+i.length,0)||0)+(this.flickerFilterBuffer?.length||0)+(this._loadBufferQueue?.reduce((s,i)=>s+i.data.length,0)||0)+(this._terminalWriteInFlightBytes||0);if(t+e.data.length>131072){this._scheduleDroppedOutputRecovery(e.id,0,t);return}this.batchTerminalWrite(e.data)}}_scheduleDroppedOutputRecovery(e,t=0,s){!e||this._clientDropRecoveryTimer||this._tilesOwnTerminal?.()||(Number.isFinite(s)&&_crashDiag.log(`TERMINAL DROP: ${(s/1024).toFixed(0)}KB queued`),this._clientDropRecoveryTimer=setTimeout(async()=>{this._clientDropRecoveryTimer=null;let i=!1,n=!1;try{const a=await this._onSessionNeedsRefresh({id:e});i=a===!0,n=a==="deadline"}catch{}window.CodemanDroppedOutput.shouldRetryDroppedOutputRecovery({repainted:i,timedOut:n,attempt:t,stillActive:this.activeSessionId===e})&&(_crashDiag.log(`DROP RECOVERY: attempt ${t+1} did not repaint, retrying`),this._scheduleDroppedOutputRecovery(e,t+1))},window.CodemanDroppedOutput.DROP_RECOVERY_DELAY_MS))}_sanitizeHtml(e){return typeof window<"u"&&typeof window.sanitizeMarkdownHtml=="function"?window.sanitizeMarkdownHtml(e):String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}_cleanTerminalBuffer(e){const t=e.replace(/\x1b\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[PX^_][^\x1b]*\x1b\\/g,"").replace(/\x1b[NO()][A-Z0-9]?/g,"").replace(/\x1b[>=<78cDEHM]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"").replace(/\r\n/g,`
8
8
  `).replace(/\r/g,`
9
9
  `),s=[/^\s*❯\s*/,/^\s*[⏵⏺⏸⏹]+\s*/,/^\s*✻\s*(Crunching|Crunched|Thinking)/i,/bypass permissions/i,/\bshift\+tab to cycle\b/i,/^\s*focus\s*$/,/^\s*new task\?/i,/\/clear to save/i,/^\s*─{5,}\s*$/,/\[(Opus|Sonnet|Haiku|GPT|Claude)[\s\S]*(tokens?|\$|¥|%|↑|↓)/i,/^\s*\[\d+[km]?\/\d+[km]?\]/i,/[█░▓▒]{3,}/,/^\s*\(.*\s*(tokens?|context).*\)\s*$/i];return t.split(`
10
10
  `).filter(o=>o.trim()?!s.some(r=>r.test(o)):!0).join(`
Binary file
Binary file
Binary file
@@ -126,20 +126,31 @@ Object.assign(CodemanApp.prototype, {
126
126
  this._stopHomeSessionsClock();
127
127
  },
128
128
 
129
- /** Re-render only when showing (called from the tab renderer's tail). */
129
+ /**
130
+ * Re-render only when showing (called from the tab renderer's tail). Asked
131
+ * again when the debounce fires: `renderHomeSessions()` unhides the column,
132
+ * so a render queued just before a fold to phone width hid it (#702) would
133
+ * otherwise bring it back behind the phone overview.
134
+ */
130
135
  _refreshHomeSessionsIfVisible() {
131
136
  if (!this.isHomeSessionsVisible()) return;
132
- this._debouncedCall('homeSessions', () => this.renderHomeSessions(), 150);
137
+ this._debouncedCall(
138
+ 'homeSessions',
139
+ () => {
140
+ if (this.isHomeSessionsVisible() && this.shouldShowHomeSessions()) this.renderHomeSessions();
141
+ },
142
+ 150
143
+ );
133
144
  },
134
145
 
135
146
  /**
136
- * One delegated click listener for every row, plus a width listener so
137
- * resizing the window while on the home screen adds or drops the column
138
- * instead of leaving it overlapping the content it was sized to clear.
147
+ * One delegated click listener for every row. The width listener lives in
148
+ * `_wireHomeSessionsBreakpoint()`, installed at startup.
139
149
  */
140
150
  _wireHomeSessions(el) {
141
151
  if (this._homeSessionsWired) return;
142
152
  this._homeSessionsWired = true;
153
+ this._wireHomeSessionsBreakpoint();
143
154
 
144
155
  el.addEventListener('click', (event) => {
145
156
  const target = event.target?.closest?.('[data-hs-action]');
@@ -150,20 +161,29 @@ Object.assign(CodemanApp.prototype, {
150
161
  void this.openWebview?.(target.dataset.hsWebview);
151
162
  }
152
163
  });
164
+ },
153
165
 
154
- if (window.matchMedia) {
155
- const mq = window.matchMedia(`(min-width: ${HOME_SESSIONS_MIN_WIDTH}px)`);
156
- const onChange = () => {
157
- // Only relevant while the welcome screen is up; entering a session
158
- // re-decides through hideWelcome()/showWelcome() anyway.
159
- if (this.activeSessionId) return;
160
- const overlay = document.getElementById('welcomeOverlay');
161
- if (!overlay || !overlay.classList.contains('visible')) return;
162
- this.showHomeSessions();
163
- };
164
- if (mq.addEventListener) mq.addEventListener('change', onChange);
165
- else if (mq.addListener) mq.addListener(onChange);
166
- }
166
+ /**
167
+ * Add or drop the column when the window crosses its width gate, so it never
168
+ * overlaps the content it was sized to clear. Installed ONCE at startup
169
+ * (`init()` in app.js) like the phone overview's breakpoint listener, so a
170
+ * page that loads on a phone and is unfolded to desktop width gets it too
171
+ * (#702). Idempotent.
172
+ */
173
+ _wireHomeSessionsBreakpoint() {
174
+ if (this._homeSessionsBreakpointWired || !window.matchMedia) return;
175
+ this._homeSessionsBreakpointWired = true;
176
+ const mq = window.matchMedia(`(min-width: ${HOME_SESSIONS_MIN_WIDTH}px)`);
177
+ const onChange = () => {
178
+ // Only relevant while the welcome screen is up; entering a session
179
+ // re-decides through hideWelcome()/showWelcome() anyway.
180
+ if (this.activeSessionId) return;
181
+ const overlay = document.getElementById('welcomeOverlay');
182
+ if (!overlay || !overlay.classList.contains('visible')) return;
183
+ this.showHomeSessions();
184
+ };
185
+ if (mq.addEventListener) mq.addEventListener('change', onChange);
186
+ else if (mq.addListener) mq.addListener(onChange);
167
187
  },
168
188
 
169
189
  // ═══════════════════════════════════════════════════════════════
Binary file
Binary file
Binary file