painapple-code 1.0.0__py3-none-any.whl

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 (436) hide show
  1. painapple_code/__init__.py +30 -0
  2. painapple_code/__main__.py +18 -0
  3. painapple_code/_version.py +24 -0
  4. painapple_code/auth_middleware.py +930 -0
  5. painapple_code/cli/__init__.py +204 -0
  6. painapple_code/cli/deploy/__init__.py +15 -0
  7. painapple_code/cli/deploy/claude_seed.py +41 -0
  8. painapple_code/cli/deploy/config.py +260 -0
  9. painapple_code/cli/deploy/container.py +715 -0
  10. painapple_code/cli/deploy/launch.py +163 -0
  11. painapple_code/cli/deploy/runtime.py +223 -0
  12. painapple_code/cli/lifecycle_cmd.py +443 -0
  13. painapple_code/cli/list_cmd.py +572 -0
  14. painapple_code/cli/manage_cmd.py +670 -0
  15. painapple_code/cli/netinfo.py +125 -0
  16. painapple_code/cli/profiles.py +390 -0
  17. painapple_code/cli/serve_args.py +163 -0
  18. painapple_code/cli/serve_config.py +256 -0
  19. painapple_code/cli/setup_cmd.py +664 -0
  20. painapple_code/cli/ui.py +438 -0
  21. painapple_code/cost_analytics.py +879 -0
  22. painapple_code/data/models.defaults.yaml +18 -0
  23. painapple_code/data/models.yaml +18 -0
  24. painapple_code/data/presets.defaults.json +32 -0
  25. painapple_code/data/strings.yaml +2269 -0
  26. painapple_code/helpers.py +406 -0
  27. painapple_code/paths.py +1514 -0
  28. painapple_code/prompt_explorer.py +984 -0
  29. painapple_code/providers/__init__.py +224 -0
  30. painapple_code/providers/base.py +710 -0
  31. painapple_code/providers/claude/__init__.py +74 -0
  32. painapple_code/providers/claude/capabilities.py +218 -0
  33. painapple_code/providers/claude/errors.py +79 -0
  34. painapple_code/providers/claude/launch.py +50 -0
  35. painapple_code/providers/claude/summary.py +89 -0
  36. painapple_code/providers/claude/translate.py +74 -0
  37. painapple_code/providers/claude_sdk/__init__.py +139 -0
  38. painapple_code/providers/claude_sdk/driver.py +412 -0
  39. painapple_code/providers/codex/__init__.py +87 -0
  40. painapple_code/providers/codex/capabilities.py +321 -0
  41. painapple_code/providers/codex/errors.py +70 -0
  42. painapple_code/providers/codex/launch.py +142 -0
  43. painapple_code/providers/codex/summary.py +196 -0
  44. painapple_code/providers/codex/translate.py +204 -0
  45. painapple_code/providers/codex_app_server/__init__.py +100 -0
  46. painapple_code/providers/codex_app_server/capabilities.py +41 -0
  47. painapple_code/providers/codex_app_server/launch.py +202 -0
  48. painapple_code/providers/codex_app_server/summary.py +291 -0
  49. painapple_code/providers/codex_app_server/translate.py +263 -0
  50. painapple_code/providers/codex_app_server/transport.py +238 -0
  51. painapple_code/routes/__init__.py +0 -0
  52. painapple_code/routes/api_agents.py +441 -0
  53. painapple_code/routes/api_app.py +368 -0
  54. painapple_code/routes/api_app_commit_sections.py +127 -0
  55. painapple_code/routes/api_app_config.py +997 -0
  56. painapple_code/routes/api_app_session_prefs.py +217 -0
  57. painapple_code/routes/api_browser.py +690 -0
  58. painapple_code/routes/api_commands.py +374 -0
  59. painapple_code/routes/api_costs.py +128 -0
  60. painapple_code/routes/api_drafts.py +139 -0
  61. painapple_code/routes/api_exec.py +149 -0
  62. painapple_code/routes/api_files.py +542 -0
  63. painapple_code/routes/api_git.py +657 -0
  64. painapple_code/routes/api_logs.py +649 -0
  65. painapple_code/routes/api_plugins.py +275 -0
  66. painapple_code/routes/api_project_config.py +418 -0
  67. painapple_code/routes/api_prompts.py +231 -0
  68. painapple_code/routes/api_providers.py +53 -0
  69. painapple_code/routes/api_search.py +411 -0
  70. painapple_code/routes/api_session_stash.py +234 -0
  71. painapple_code/routes/api_session_welcome.py +151 -0
  72. painapple_code/routes/api_sessions.py +742 -0
  73. painapple_code/routes/api_shadow.py +323 -0
  74. painapple_code/routes/api_shadow_db.py +512 -0
  75. painapple_code/routes/api_shadow_files.py +332 -0
  76. painapple_code/routes/api_shadow_search.py +476 -0
  77. painapple_code/routes/api_skills.py +610 -0
  78. painapple_code/routes/api_tasks.py +147 -0
  79. painapple_code/routes/api_terminal.py +540 -0
  80. painapple_code/routes/api_upload.py +293 -0
  81. painapple_code/routes/api_viewer.py +229 -0
  82. painapple_code/routes/dependencies.py +109 -0
  83. painapple_code/routes/ws_chat.py +837 -0
  84. painapple_code/server.py +2208 -0
  85. painapple_code/server_logging.py +263 -0
  86. painapple_code/services/__init__.py +0 -0
  87. painapple_code/services/agent_session.py +2738 -0
  88. painapple_code/session_store.py +253 -0
  89. painapple_code/session_store_core.py +879 -0
  90. painapple_code/shadow_db.py +830 -0
  91. painapple_code/shadow_db_plans.py +369 -0
  92. painapple_code/shadow_db_queries.py +595 -0
  93. painapple_code/shadow_db_schema.py +676 -0
  94. painapple_code/shadow_git.py +1296 -0
  95. painapple_code/shadow_git_frontmatter.py +314 -0
  96. painapple_code/shadow_git_sections.py +520 -0
  97. painapple_code/shadow_git_summary.py +462 -0
  98. painapple_code/shadow_parser.py +560 -0
  99. painapple_code/static/css/00-variables.css +276 -0
  100. painapple_code/static/css/01-base.css +245 -0
  101. painapple_code/static/css/02-tooltips.css +36 -0
  102. painapple_code/static/css/09-left-rail.css +448 -0
  103. painapple_code/static/css/10-header.css +777 -0
  104. painapple_code/static/css/11-connection-bar.css +120 -0
  105. painapple_code/static/css/20-messages.css +750 -0
  106. painapple_code/static/css/21-tool-blocks.css +2340 -0
  107. painapple_code/static/css/22-edit-diff.css +619 -0
  108. painapple_code/static/css/23-thinking.css +1584 -0
  109. painapple_code/static/css/24-background-tasks.css +359 -0
  110. painapple_code/static/css/25-context-block.css +252 -0
  111. painapple_code/static/css/26-session-setup.css +144 -0
  112. painapple_code/static/css/30-markdown.css +854 -0
  113. painapple_code/static/css/40-input.css +2418 -0
  114. painapple_code/static/css/41-autocomplete.css +127 -0
  115. painapple_code/static/css/42-activity-strip.css +97 -0
  116. painapple_code/static/css/43-file-autocomplete.css +121 -0
  117. painapple_code/static/css/44-snippets-autocomplete.css +224 -0
  118. painapple_code/static/css/45-selection-bar.css +433 -0
  119. painapple_code/static/css/46-keyboard-bar.css +119 -0
  120. painapple_code/static/css/47-keyboard-longpress.css +116 -0
  121. painapple_code/static/css/47-token-profile.css +106 -0
  122. painapple_code/static/css/50-welcome.css +3095 -0
  123. painapple_code/static/css/51-modals.css +301 -0
  124. painapple_code/static/css/52-utilities.css +77 -0
  125. painapple_code/static/css/53-image-upload.css +456 -0
  126. painapple_code/static/css/54-todo-list.css +102 -0
  127. painapple_code/static/css/55-file-upload.css +113 -0
  128. painapple_code/static/css/56-chat-navigator.css +218 -0
  129. painapple_code/static/css/56-permission-card.css +332 -0
  130. painapple_code/static/css/56-plan-approval.css +204 -0
  131. painapple_code/static/css/56-question-form.css +602 -0
  132. painapple_code/static/css/57-swipe-indicator.css +95 -0
  133. painapple_code/static/css/58-session-families.css +627 -0
  134. painapple_code/static/css/59-about.css +196 -0
  135. painapple_code/static/css/61-log-explorer.css +723 -0
  136. painapple_code/static/css/62-json-tree.css +489 -0
  137. painapple_code/static/css/62-skills-widget.css +650 -0
  138. painapple_code/static/css/63-commands-widget.css +30 -0
  139. painapple_code/static/css/63-plugins-widget.css +174 -0
  140. painapple_code/static/css/63-terminal.css +516 -0
  141. painapple_code/static/css/64-search-files-widget.css +448 -0
  142. painapple_code/static/css/65-snippets-widget.css +426 -0
  143. painapple_code/static/css/66-active-sessions.css +979 -0
  144. painapple_code/static/css/66-agents-widget.css +265 -0
  145. painapple_code/static/css/66-file-explorer-widget.css +855 -0
  146. painapple_code/static/css/66-git-panel.css +791 -0
  147. painapple_code/static/css/66-history-explorer.css +1496 -0
  148. painapple_code/static/css/67-diff-viewer.css +602 -0
  149. painapple_code/static/css/67-editor-view.css +748 -0
  150. painapple_code/static/css/67-file-preview-widget.css +1873 -0
  151. painapple_code/static/css/68-browser-widget.css +337 -0
  152. painapple_code/static/css/68-compare-wizard.css +355 -0
  153. painapple_code/static/css/68-csv-preview.css +106 -0
  154. painapple_code/static/css/68-diff-preview.css +103 -0
  155. painapple_code/static/css/68-helpers-install-widget.css +491 -0
  156. painapple_code/static/css/68-image-annotate.css +346 -0
  157. painapple_code/static/css/68-terminal-view.css +98 -0
  158. painapple_code/static/css/68-uploads-widget.css +229 -0
  159. painapple_code/static/css/69-cost-analytics.css +537 -0
  160. painapple_code/static/css/70-config-panel.css +3736 -0
  161. painapple_code/static/css/70-excalidraw.css +136 -0
  162. painapple_code/static/css/70-prompt-explorer.css +890 -0
  163. painapple_code/static/css/71-chart.css +111 -0
  164. painapple_code/static/css/72-discussion-sidebar.css +678 -0
  165. painapple_code/static/css/74-debug-logs.css +656 -0
  166. painapple_code/static/css/80-open-dialog.css +146 -0
  167. painapple_code/static/css/80-quick-switcher.css +383 -0
  168. painapple_code/static/css/80-widget-system.css +1763 -0
  169. painapple_code/static/css/81-quick-actions.css +1020 -0
  170. painapple_code/static/css/82-context-popover.css +1233 -0
  171. painapple_code/static/css/83-context-menu.css +339 -0
  172. painapple_code/static/css/85-lazy-loading.css +102 -0
  173. painapple_code/static/css/86-zen-mode.css +708 -0
  174. painapple_code/static/css/87-grid-switcher.css +346 -0
  175. painapple_code/static/css/login.css +198 -0
  176. painapple_code/static/dist/app.bundle.js +7177 -0
  177. painapple_code/static/feature-triage.html +446 -0
  178. painapple_code/static/icons/apple-touch-icon.png +0 -0
  179. painapple_code/static/icons/favicon-32.png +0 -0
  180. painapple_code/static/icons/favicon.ico +0 -0
  181. painapple_code/static/icons/icon-128.png +0 -0
  182. painapple_code/static/icons/icon-144.png +0 -0
  183. painapple_code/static/icons/icon-152.png +0 -0
  184. painapple_code/static/icons/icon-180.png +0 -0
  185. painapple_code/static/icons/icon-192.png +0 -0
  186. painapple_code/static/icons/icon-384.png +0 -0
  187. painapple_code/static/icons/icon-512.png +0 -0
  188. painapple_code/static/icons/icon-72.png +0 -0
  189. painapple_code/static/icons/icon-96.png +0 -0
  190. painapple_code/static/js/action-delegate.js +187 -0
  191. painapple_code/static/js/activity-strip.js +193 -0
  192. painapple_code/static/js/app/context-menus.js +619 -0
  193. painapple_code/static/js/app/file-preview.js +163 -0
  194. painapple_code/static/js/app/init-ui.js +574 -0
  195. painapple_code/static/js/app/input-events.js +561 -0
  196. painapple_code/static/js/app/input-resize.js +313 -0
  197. painapple_code/static/js/app/message-actions.js +419 -0
  198. painapple_code/static/js/app/panels.js +210 -0
  199. painapple_code/static/js/app/rendering-delegators.js +246 -0
  200. painapple_code/static/js/app/server-loading.js +365 -0
  201. painapple_code/static/js/app/session-ops.js +287 -0
  202. painapple_code/static/js/app/session-switch.js +443 -0
  203. painapple_code/static/js/app/settings-helpers.js +280 -0
  204. painapple_code/static/js/app/startup-welcome.js +290 -0
  205. painapple_code/static/js/app-context.js +157 -0
  206. painapple_code/static/js/app.js +2134 -0
  207. painapple_code/static/js/auth-fetch.js +46 -0
  208. painapple_code/static/js/background-tasks.js +274 -0
  209. painapple_code/static/js/boot.js +73 -0
  210. painapple_code/static/js/caret-position.js +171 -0
  211. painapple_code/static/js/chat-navigator.js +710 -0
  212. painapple_code/static/js/chat-search.js +323 -0
  213. painapple_code/static/js/command-executor.js +176 -0
  214. painapple_code/static/js/command-store.js +497 -0
  215. painapple_code/static/js/components.js +1414 -0
  216. painapple_code/static/js/config.js +218 -0
  217. painapple_code/static/js/context-menu.js +740 -0
  218. painapple_code/static/js/controllers/chat-controller.js +4252 -0
  219. painapple_code/static/js/controllers/dialog-controller.js +217 -0
  220. painapple_code/static/js/controllers/tab-controller.js +1828 -0
  221. painapple_code/static/js/controllers/thinking-controller.js +915 -0
  222. painapple_code/static/js/diff-utils.js +486 -0
  223. painapple_code/static/js/drafts-pill.js +95 -0
  224. painapple_code/static/js/editor-view.js +815 -0
  225. painapple_code/static/js/effort-settings.js +430 -0
  226. painapple_code/static/js/feature-triage.js +811 -0
  227. painapple_code/static/js/file-autocomplete.js +516 -0
  228. painapple_code/static/js/file-tabs.js +123 -0
  229. painapple_code/static/js/gestures.js +448 -0
  230. painapple_code/static/js/grid-switcher.js +334 -0
  231. painapple_code/static/js/input-handler.js +1472 -0
  232. painapple_code/static/js/keyboard-bar.js +495 -0
  233. painapple_code/static/js/layout-switcher.js +109 -0
  234. painapple_code/static/js/linkify-utils.js +200 -0
  235. painapple_code/static/js/login.js +141 -0
  236. painapple_code/static/js/open-dialog.js +879 -0
  237. painapple_code/static/js/orphan-terminals.js +373 -0
  238. painapple_code/static/js/path-utils.js +179 -0
  239. painapple_code/static/js/perf-marks.js +102 -0
  240. painapple_code/static/js/permission-settings.js +475 -0
  241. painapple_code/static/js/pointer-input.js +59 -0
  242. painapple_code/static/js/preview/json-tree-menu.js +226 -0
  243. painapple_code/static/js/preview/json-tree-toolbar.js +291 -0
  244. painapple_code/static/js/preview/json-tree.js +457 -0
  245. painapple_code/static/js/preview/preview-breadcrumb.js +387 -0
  246. painapple_code/static/js/preview/preview-edit.js +367 -0
  247. painapple_code/static/js/preview/preview-events.js +361 -0
  248. painapple_code/static/js/preview/preview-history.js +567 -0
  249. painapple_code/static/js/preview/preview-inline-edit.js +869 -0
  250. painapple_code/static/js/preview/preview-poll.js +108 -0
  251. painapple_code/static/js/preview/preview-render.js +572 -0
  252. painapple_code/static/js/preview/preview-search.js +421 -0
  253. painapple_code/static/js/preview/preview-state.js +256 -0
  254. painapple_code/static/js/preview/preview-utils.js +251 -0
  255. painapple_code/static/js/preview-plugins/chart-plugin.js +22 -0
  256. painapple_code/static/js/preview-plugins/csv-plugin.js +188 -0
  257. painapple_code/static/js/preview-plugins/diff-plugin.js +258 -0
  258. painapple_code/static/js/preview-plugins/excalidraw-plugin.js +25 -0
  259. painapple_code/static/js/preview-plugins/html-plugin.js +104 -0
  260. painapple_code/static/js/preview-plugins/image-plugin.js +20 -0
  261. painapple_code/static/js/preview-plugins/index.js +34 -0
  262. painapple_code/static/js/preview-plugins/json-plugin.js +99 -0
  263. painapple_code/static/js/preview-plugins/jsonl-plugin.js +152 -0
  264. painapple_code/static/js/preview-plugins/markdown-plugin.js +266 -0
  265. painapple_code/static/js/preview-plugins/panzoom-plugin.js +63 -0
  266. painapple_code/static/js/preview-plugins/plugin-helpers.js +282 -0
  267. painapple_code/static/js/project-color-picker.js +110 -0
  268. painapple_code/static/js/project-colors.js +163 -0
  269. painapple_code/static/js/prompt-favorites.js +187 -0
  270. painapple_code/static/js/quick-actions-menu.js +1736 -0
  271. painapple_code/static/js/quick-actions-registry.js +1239 -0
  272. painapple_code/static/js/quick-switcher/controller.js +294 -0
  273. painapple_code/static/js/quick-switcher/fuzzy-scorer.js +123 -0
  274. painapple_code/static/js/quick-switcher/index.js +30 -0
  275. painapple_code/static/js/quick-switcher/providers/base-provider.js +51 -0
  276. painapple_code/static/js/quick-switcher/providers/command-provider.js +56 -0
  277. painapple_code/static/js/quick-switcher/providers/file-provider.js +291 -0
  278. painapple_code/static/js/quick-switcher/providers/panel-provider.js +132 -0
  279. painapple_code/static/js/quick-switcher/providers/project-provider.js +361 -0
  280. painapple_code/static/js/quick-switcher/providers/read-files-provider.js +104 -0
  281. painapple_code/static/js/quick-switcher/providers/skills-provider.js +129 -0
  282. painapple_code/static/js/quick-switcher/registry.js +69 -0
  283. painapple_code/static/js/quick-switcher/ui/item.js +54 -0
  284. painapple_code/static/js/quick-switcher/ui/picker.js +464 -0
  285. painapple_code/static/js/recent-opens.js +40 -0
  286. painapple_code/static/js/scroll-manager.js +530 -0
  287. painapple_code/static/js/scroll-state-machine.js +359 -0
  288. painapple_code/static/js/selection/action-bar.js +793 -0
  289. painapple_code/static/js/selection/index.js +15 -0
  290. painapple_code/static/js/selection/selection-handler.js +877 -0
  291. painapple_code/static/js/selection/state.js +181 -0
  292. painapple_code/static/js/session/agent-progress.js +202 -0
  293. painapple_code/static/js/session/handle-agent-message.js +481 -0
  294. painapple_code/static/js/session/handle-message.js +550 -0
  295. painapple_code/static/js/session/interactive.js +587 -0
  296. painapple_code/static/js/session/message-store.js +271 -0
  297. painapple_code/static/js/session/messages.js +253 -0
  298. painapple_code/static/js/session/persistence.js +179 -0
  299. painapple_code/static/js/session/restore.js +136 -0
  300. painapple_code/static/js/session/sync.js +333 -0
  301. painapple_code/static/js/session-container-pool.js +371 -0
  302. painapple_code/static/js/session-setup-panel.js +274 -0
  303. painapple_code/static/js/session.js +1047 -0
  304. painapple_code/static/js/shortcut-hints.js +272 -0
  305. painapple_code/static/js/shortcuts.js +1146 -0
  306. painapple_code/static/js/skills-autocomplete.js +262 -0
  307. painapple_code/static/js/snippets-autocomplete.js +738 -0
  308. painapple_code/static/js/stash-refs-view.js +83 -0
  309. painapple_code/static/js/stash-ui.js +768 -0
  310. painapple_code/static/js/stash.js +785 -0
  311. painapple_code/static/js/status-bar.js +1184 -0
  312. painapple_code/static/js/token-profile.js +274 -0
  313. painapple_code/static/js/tool-renderer-blocks.js +1626 -0
  314. painapple_code/static/js/tool-renderer-thinking.js +813 -0
  315. painapple_code/static/js/tool-renderer.js +1500 -0
  316. painapple_code/static/js/tooltips.js +197 -0
  317. painapple_code/static/js/upload-manager.js +1019 -0
  318. painapple_code/static/js/utils.js +521 -0
  319. painapple_code/static/js/welcome/api.js +363 -0
  320. painapple_code/static/js/welcome/cards.js +626 -0
  321. painapple_code/static/js/welcome/context-menu.js +585 -0
  322. painapple_code/static/js/welcome/families.js +801 -0
  323. painapple_code/static/js/welcome/preview.js +234 -0
  324. painapple_code/static/js/welcome/state.js +129 -0
  325. painapple_code/static/js/welcome.js +1874 -0
  326. painapple_code/static/js/widget-system/base-widget.js +717 -0
  327. painapple_code/static/js/widget-system/device-manager.js +178 -0
  328. painapple_code/static/js/widget-system/event-bus.js +152 -0
  329. painapple_code/static/js/widget-system/icons.js +120 -0
  330. painapple_code/static/js/widget-system/index.js +49 -0
  331. painapple_code/static/js/widget-system/init.js +54 -0
  332. painapple_code/static/js/widget-system/types/bottom-sheet.js +307 -0
  333. painapple_code/static/js/widget-system/types/floating.js +915 -0
  334. painapple_code/static/js/widget-system/types/index.js +40 -0
  335. painapple_code/static/js/widget-system/types/modal.js +147 -0
  336. painapple_code/static/js/widget-system/types/sidebar.js +158 -0
  337. painapple_code/static/js/widget-system/types/tab.js +146 -0
  338. painapple_code/static/js/widget-system/types/top-sheet.js +203 -0
  339. painapple_code/static/js/widget-system/widget-manager.js +1187 -0
  340. painapple_code/static/js/widgets/about-widget.js +260 -0
  341. painapple_code/static/js/widgets/active-sessions-widget.js +760 -0
  342. painapple_code/static/js/widgets/agents-widget.js +897 -0
  343. painapple_code/static/js/widgets/browser-widget.js +579 -0
  344. painapple_code/static/js/widgets/commands-widget.js +694 -0
  345. painapple_code/static/js/widgets/config/commit-sections.js +449 -0
  346. painapple_code/static/js/widgets/config/dir-autocomplete.js +224 -0
  347. painapple_code/static/js/widgets/config/gestures.js +161 -0
  348. painapple_code/static/js/widgets/config/models-tab.js +988 -0
  349. painapple_code/static/js/widgets/config/quick-actions-tab.js +882 -0
  350. painapple_code/static/js/widgets/config/shortcut-editor.js +587 -0
  351. painapple_code/static/js/widgets/config/state.js +517 -0
  352. painapple_code/static/js/widgets/config/system-controls.js +90 -0
  353. painapple_code/static/js/widgets/config-widget.js +1535 -0
  354. painapple_code/static/js/widgets/cost-analytics-widget.js +621 -0
  355. painapple_code/static/js/widgets/debug-widget.js +693 -0
  356. painapple_code/static/js/widgets/diff-viewer-widget.js +1420 -0
  357. painapple_code/static/js/widgets/discussion-widget.js +1107 -0
  358. painapple_code/static/js/widgets/file-explorer-widget.js +2166 -0
  359. painapple_code/static/js/widgets/file-preview-widget.js +861 -0
  360. painapple_code/static/js/widgets/git-widget.js +794 -0
  361. painapple_code/static/js/widgets/helpers-install-widget.js +720 -0
  362. painapple_code/static/js/widgets/history-explorer-widget.js +1804 -0
  363. painapple_code/static/js/widgets/image-annotate-widget.js +951 -0
  364. painapple_code/static/js/widgets/image-preview-widget.js +692 -0
  365. painapple_code/static/js/widgets/index.js +176 -0
  366. painapple_code/static/js/widgets/log-explorer-widget.js +1057 -0
  367. painapple_code/static/js/widgets/plugins-widget.js +305 -0
  368. painapple_code/static/js/widgets/prompt-explorer-widget.js +1119 -0
  369. painapple_code/static/js/widgets/search-files-widget.js +529 -0
  370. painapple_code/static/js/widgets/skills-widget.js +843 -0
  371. painapple_code/static/js/widgets/snippets-widget.js +479 -0
  372. painapple_code/static/js/widgets/sub-agents-widget.js +333 -0
  373. painapple_code/static/js/widgets/tasks-widget.js +379 -0
  374. painapple_code/static/js/widgets/terminal/connection.js +283 -0
  375. painapple_code/static/js/widgets/terminal/gestures.js +357 -0
  376. painapple_code/static/js/widgets/terminal/init.js +642 -0
  377. painapple_code/static/js/widgets/terminal/link-providers.js +532 -0
  378. painapple_code/static/js/widgets/terminal/osc52.js +213 -0
  379. painapple_code/static/js/widgets/terminal/render.js +159 -0
  380. painapple_code/static/js/widgets/terminal/size.js +54 -0
  381. painapple_code/static/js/widgets/terminal/state.js +211 -0
  382. painapple_code/static/js/widgets/terminal/wrap-utils.js +101 -0
  383. painapple_code/static/js/widgets/terminal-widget.js +793 -0
  384. painapple_code/static/js/widgets/uploads-widget.js +461 -0
  385. painapple_code/static/js/widgets/zen-widget.js +1001 -0
  386. painapple_code/static/login.html +51 -0
  387. painapple_code/static/manifest.json +73 -0
  388. painapple_code/static/sw.js +293 -0
  389. painapple_code/static/vendor/LICENSES.txt +769 -0
  390. painapple_code/static/vendor/README.md +103 -0
  391. painapple_code/static/vendor/codemirror.js +35 -0
  392. painapple_code/static/vendor/codemirror.js.LEGAL.txt +304 -0
  393. painapple_code/static/vendor/github-markdown-dark.min.css +1124 -0
  394. painapple_code/static/vendor/highlight-github-dark.min.css +10 -0
  395. painapple_code/static/vendor/highlight-lang-dockerfile.min.js +8 -0
  396. painapple_code/static/vendor/highlight-lang-nginx.min.js +21 -0
  397. painapple_code/static/vendor/highlight-lang-properties.min.js +10 -0
  398. painapple_code/static/vendor/highlight-lang-scala.min.js +28 -0
  399. painapple_code/static/vendor/highlight.min.js +1213 -0
  400. painapple_code/static/vendor/marked.min.js +6 -0
  401. painapple_code/static/vendor/purify.min.js +3 -0
  402. painapple_code/static/vendor/xterm-addon-fit.js +2 -0
  403. painapple_code/static/vendor/xterm.css +209 -0
  404. painapple_code/static/vendor/xterm.js +2 -0
  405. painapple_code/static/web-client.html +635 -0
  406. painapple_code/subprocess_registry.py +535 -0
  407. painapple_code/tls_cert.py +79 -0
  408. painapple_code/tools/agents/shadow-git-helper.md +400 -0
  409. painapple_code/tools/excalidraw-to-svg.js +143 -0
  410. painapple_code/tools/install-helpers.sh +148 -0
  411. painapple_code/tools/shadow-git +320 -0
  412. painapple_code/tools/shadow-query +120 -0
  413. painapple_code/tools/vegalite-to-svg.js +79 -0
  414. painapple_code/turn_query.py +766 -0
  415. painapple_code/turn_tracker.py +221 -0
  416. painapple_code/utils/__init__.py +0 -0
  417. painapple_code/utils/agent_cli.py +306 -0
  418. painapple_code/utils/chart.py +103 -0
  419. painapple_code/utils/excalidraw.py +107 -0
  420. painapple_code/utils/file_lock.py +162 -0
  421. painapple_code/utils/file_paths.py +648 -0
  422. painapple_code/utils/generate_icons.py +251 -0
  423. painapple_code/utils/proc.py +205 -0
  424. painapple_code/utils/pty_backend.py +59 -0
  425. painapple_code/utils/pty_posix.py +160 -0
  426. painapple_code/utils/pty_windows.py +245 -0
  427. painapple_code/utils/token_profiles.py +91 -0
  428. painapple_code/viewer_templates.py +657 -0
  429. painapple_code/welcome_search.py +879 -0
  430. painapple_code-1.0.0.dist-info/METADATA +292 -0
  431. painapple_code-1.0.0.dist-info/RECORD +436 -0
  432. painapple_code-1.0.0.dist-info/WHEEL +5 -0
  433. painapple_code-1.0.0.dist-info/entry_points.txt +2 -0
  434. painapple_code-1.0.0.dist-info/licenses/LICENSE +661 -0
  435. painapple_code-1.0.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +261 -0
  436. painapple_code-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2134 @@
1
+ /**
2
+ * Main App class and initialization
3
+ */
4
+
5
+ // Import first so window.fetch is wrapped before any module's poll fires.
6
+ import './auth-fetch.js';
7
+ import './action-delegate.js';
8
+ import S from './strings.js';
9
+ import { CONFIG, COMMANDS, HAS_PHYSICAL_KEYBOARD, debug, setServerHome, setServerWorkspace, INSTANCE } from './config.js';
10
+ import { $, genId, escapeHtml, formatTime, formatRelativeTime, Storage, highlightThinkingKeywords, hasThinkingKeywords, terminalAvailable } from './utils.js';
11
+ import { isThinkingKeywordsHighlightingEnabled } from './widgets/config-widget.js';
12
+ import { basename, isAbsolutePath, joinPath } from './path-utils.js';
13
+ import { Session, SessionManager } from './session.js';
14
+ import { MarkdownRenderer, AutocompleteUI } from './components.js';
15
+ // FileExplorer and LogExplorer are now widgets, imported via widget-system
16
+ // Widget System (new modular architecture)
17
+ import { initWidgetSystem, WidgetManager, WidgetBus, GitWidget, TerminalWidget, LogExplorerWidget, FileExplorerWidget, FilePreviewWidget, HistoryExplorerWidget, DiffViewerWidget } from './widget-system/init.js';
18
+ // Selection system - text selection handler for stash and discussion
19
+ import { initSelectionHandler, registerSelectionContainer, exitSelectionMode, restoreSelectionState, isSelectionModeActive } from './selection/selection-handler.js';
20
+ // ICONS moved to TabController
21
+ import { getFileName, isImageFile } from './file-tabs.js';
22
+ import { ShortcutManager, reconcileShortcutsWithServer } from './shortcuts.js';
23
+ // getCommandStore, CommandType moved to CommandExecutor
24
+ import { GestureManager } from './gestures.js';
25
+ import { ContextMenu, copyToClipboard, showToast, fileDownloadAction, getDownloadLabel } from './context-menu.js';
26
+ import { generateSmartDiff, renderSmartDiff } from './diff-utils.js';
27
+ import { ChatSearch } from './chat-search.js';
28
+ import { ChatNavigator } from './chat-navigator.js';
29
+ import { ScrollManager } from './scroll-manager.js';
30
+ import { UploadManager } from './upload-manager.js';
31
+ import { StatusBar, ensureModelsLoaded } from './status-bar.js';
32
+ import { ActivityStrip } from './activity-strip.js';
33
+ import { InputHandler } from './input-handler.js';
34
+ import { ShortcutHints } from './shortcut-hints.js';
35
+ import { ToolRenderer } from './tool-renderer.js';
36
+ import { FileAutocomplete } from './file-autocomplete.js';
37
+ import { recordOpen as recordRecentOpen } from './recent-opens.js';
38
+ import { SnippetsAutocomplete, initSnippetsData, refreshAgentsForCwd } from './snippets-autocomplete.js';
39
+ import { SkillsAutocomplete, invalidateSkillsCache } from './skills-autocomplete.js';
40
+ // Stash system - context collector for chat prompts
41
+ import { Stash } from './stash.js';
42
+ import { initStashUI, loadStashForSession, closeStashPickerIfOpen } from './stash-ui.js';
43
+ // Prompt favorites - mark prompts as favorites before/after sending
44
+ import * as PromptFavorites from './prompt-favorites.js';
45
+ // Welcome screen state management (for "back to sessions" feature)
46
+ import { initWelcomeScreen, clearSavedWelcomeState, isFavoriteSession, toggleFavoriteSession, loadFavoritesFromServer, openQuickSearch, isQuickSearchActive, typeIntoQuickSearch, clearWelcomeSearch, closeSessionPreview, closeWelcomeContextMenu } from './welcome.js';
47
+ // Tooltip system - unified tooltips for desktop hover and touch long-press
48
+ import { TooltipManager, initTooltips } from './tooltips.js';
49
+ // Controller Architecture (V2 modularization)
50
+ import { AppContext } from './app-context.js';
51
+ import { ThinkingController } from './controllers/thinking-controller.js';
52
+ import { DialogController } from './controllers/dialog-controller.js';
53
+ import { ChatController } from './controllers/chat-controller.js';
54
+ import { TabController } from './controllers/tab-controller.js';
55
+ import { CommandExecutor } from './command-executor.js';
56
+ import { orphanTerminals } from './orphan-terminals.js';
57
+ // Effort settings - controls response thoroughness (replaces thinking tokens)
58
+ import { effortSettings } from './effort-settings.js';
59
+ // Permission settings - per-session permission level control
60
+ import { permissionSettings } from './permission-settings.js';
61
+ // Token profile - per-session OAuth token selector (account chip)
62
+ import { tokenProfile } from './token-profile.js';
63
+ // Session setup panel — engine/model/permissions/effort/account pills in
64
+ // the empty chat area of a fresh session (self-initializing singleton)
65
+ import { sessionSetupPanel } from './session-setup-panel.js';
66
+ // Layout density switcher — popup opened from the left-rail density button
67
+ import { layoutSwitcher } from './layout-switcher.js';
68
+ import { state as configState } from './widgets/config/state.js';
69
+ // Quick Actions Menu API + Worktrees
70
+ import { QuickActionsMenu, ImagePreviewWidget, DiscussionWidget, handleAnnotatorEscape } from './widgets/index.js';
71
+ import { QuickActionsRegistry } from './quick-actions-registry.js';
72
+ // Quick Switcher (VS Code-style command palette / file picker)
73
+ import { QuickSwitcher } from './quick-switcher/index.js';
74
+ // Open Dialog (fish-style path picker — files preview, folders start new sessions)
75
+ import { OpenDialog } from './open-dialog.js';
76
+ // Grid Switcher (iPad-style session card grid, Alt+Tab)
77
+ import { GridSwitcher } from './grid-switcher.js';
78
+ // Background task tracking for header badge
79
+ import { bgTaskTracker } from './background-tasks.js';
80
+
81
+ // Prototype mixins extracted from this file (see Object.assign near the bottom).
82
+ import { panelMethods } from './app/panels.js';
83
+ import { contextMenuMethods } from './app/context-menus.js';
84
+ import { renderingDelegatorMethods } from './app/rendering-delegators.js';
85
+ import { filePreviewMethods } from './app/file-preview.js';
86
+ import { sessionSwitchMethods } from './app/session-switch.js';
87
+ import { initUiMethods } from './app/init-ui.js';
88
+ import { inputEventMethods } from './app/input-events.js';
89
+ import { serverLoadingMethods } from './app/server-loading.js';
90
+ import { inputResizeMethods } from './app/input-resize.js';
91
+ import { startupWelcomeMethods } from './app/startup-welcome.js';
92
+ import { settingsHelperMethods } from './app/settings-helpers.js';
93
+ import { messageActionMethods } from './app/message-actions.js';
94
+ import { sessionOpsMethods } from './app/session-ops.js';
95
+ import { loadProjectColors } from './project-colors.js';
96
+ import { closeProjectColorPicker } from './project-color-picker.js';
97
+
98
+ /**
99
+ * Main application class
100
+ */
101
+ class App {
102
+ constructor() {
103
+ this.sessionManager = new SessionManager();
104
+ this.activeSession = null;
105
+ this.markdown = new MarkdownRenderer();
106
+ this.toolRenderer = new ToolRenderer();
107
+ this.autocomplete = null;
108
+ this.userCommandNames = new Set(); // User-defined command names for autocomplete labeling
109
+ this.fileAutocomplete = null; // Initialized in initAutocomplete()
110
+ this.isTyping = false;
111
+
112
+ // Controller Architecture - shared context and controllers
113
+ this.ctx = new AppContext(this);
114
+ this.thinkingCtrl = new ThinkingController(this.ctx);
115
+ this.dialogCtrl = new DialogController(this.ctx);
116
+ this.chatCtrl = null; // Initialized after thinkingCtrl
117
+ this.tabCtrl = null; // Initialized after widget system
118
+ this.commandExec = new CommandExecutor(this.ctx);
119
+
120
+ // Input handler (initialized in initAutocomplete after DOM refs are ready)
121
+ this.inputHandler = null;
122
+
123
+ // Upload manager (initialized in initImageUpload after DOM refs are ready)
124
+ this.uploadManager = null;
125
+
126
+ // Font scale (0.75 to 1.5, step 0.1)
127
+ this.fontScale = Storage.get('claude-font-scale', 1.0);
128
+
129
+ // Scroll manager (initialized in initAutocomplete after DOM refs are ready)
130
+ this.scrollManager = null;
131
+
132
+ // Session switch queue - prevents race conditions from rapid tab clicks
133
+ this._switchQueue = {
134
+ pending: null, // Pending switch operation {session, cancelled}
135
+ processing: false // Whether a switch is in progress
136
+ };
137
+
138
+ // Chat search (initialized in initAutocomplete after DOM refs are ready)
139
+ this.chatSearch = null;
140
+
141
+ // Chat navigator for jumping between user messages (initialized in initAutocomplete)
142
+ this.chatNavigator = null;
143
+
144
+ // File explorer (now managed by WidgetManager as 'file-explorer')
145
+ this.fileExplorer = FileExplorerWidget;
146
+
147
+ // Log explorer is now a widget (registered via initWidgetSystem)
148
+
149
+ // Keyboard bar is now embedded inside the terminal widget (see terminal-widget.js)
150
+ // Widget System initialization
151
+ initWidgetSystem();
152
+
153
+ // Initialize TabController after widget system
154
+ this.tabCtrl = new TabController(this.ctx);
155
+
156
+ // Grid switcher overlay (iPad-style session grid; Alt+Tab + header button)
157
+ this.gridSwitcher = new GridSwitcher(this);
158
+
159
+ // Git panel is now managed by WidgetManager (registered as 'git')
160
+
161
+ // Context menu (right-click / long-press)
162
+ this.contextMenu = new ContextMenu();
163
+
164
+ // Resolve the markup's data-tooltip-key attributes into real tooltip
165
+ // text BEFORE anything reads data-tooltip. initEventListeners() ->
166
+ // initLeftRailButtons() derives the expanded-rail labels from it, so
167
+ // running late here would leave the rail unlabelled.
168
+ this.applyStaticTooltips?.();
169
+ this.initElements();
170
+ this.initAutocomplete();
171
+ // Initialize ChatController after elements are ready
172
+ this.chatCtrl = new ChatController(this.ctx, this.thinkingCtrl);
173
+ this._initControllerEvents();
174
+ this.initEventListeners();
175
+ this.initContextMenu();
176
+ this.shortcutManager = new ShortcutManager(this);
177
+ // Rail tooltips were rendered before shortcutManager existed — refresh
178
+ // them now so they pick up registered shortcut keys.
179
+ this.refreshRailShortcutTooltips?.();
180
+ this.gestureManager = new GestureManager(this);
181
+ // Config panel is now a widget - registered in initWidgets()
182
+ this.initBeforeUnload();
183
+ this.initWelcomeEvents();
184
+ this.initInputResize();
185
+ this.updateInputAreaHeight(); // Set initial CSS variable for floating elements
186
+ this.initImageUpload();
187
+ this.initVisibilitySync();
188
+ this.tabCtrl.initWidgetTabEvents();
189
+ orphanTerminals.init();
190
+ // Note: initFromUrl() is called after construction to properly await async loading
191
+ }
192
+
193
+ async initFromUrl() {
194
+ const urlParams = new URLSearchParams(window.location.search);
195
+ const urlSessionId = urlParams.get('session');
196
+
197
+ // Enable expand mode for screenshots (?expand=true)
198
+ if (urlParams.get('expand') === 'true') {
199
+ document.body.classList.add('expand-mode');
200
+ }
201
+
202
+ // Load favorites for context menu and quick actions
203
+ loadFavoritesFromServer().catch(e => console.warn('Failed to load favorites:', e));
204
+
205
+ // ── Server-side shortcut reconciliation ───────────────────────
206
+ // Keyboard shortcut customizations sync through the server so they
207
+ // persist across devices and survive iPadOS PWA localStorage drift.
208
+ reconcileShortcutsWithServer().then(synced => {
209
+ if (synced && this.shortcutManager) {
210
+ this.shortcutManager.reloadShortcuts();
211
+ this.refreshRailShortcutTooltips?.();
212
+ }
213
+ });
214
+
215
+ // ── Server-side tab state reconciliation ──────────────────────
216
+ // iPadOS PWA localStorage writes can silently fail to persist to disk.
217
+ // The server keeps a reliable copy of which tabs are open.
218
+ // If server and localStorage disagree, server wins.
219
+ const rebuiltFromServer = await this.sessionManager.reconcileWithServer();
220
+ let loadedFromServer = rebuiltFromServer;
221
+
222
+ // Get active session — server's pointer first, UNCONDITIONALLY (not
223
+ // gated on rebuiltFromServer). The server re-persists activeStoreId on
224
+ // every tab save, so it's the freshest source and the only one that
225
+ // survives localStorage loss (iPadOS write-loss, app reinstall, and
226
+ // the Tauri proxy's per-launch origin). Local ACTIVE_SESSION_KEY is
227
+ // the fallback when the server pointer is absent or doesn't resolve.
228
+ const serverActiveStoreId =
229
+ this.sessionManager._serverTabState?.activeStoreId || null;
230
+ let savedActiveSessionId;
231
+ if (serverActiveStoreId) {
232
+ // Find the session that matches the server's active storeId
233
+ const serverActive = this.sessionManager.sessions.find(
234
+ s => s.storeId === serverActiveStoreId
235
+ );
236
+ savedActiveSessionId = serverActive?.id;
237
+ }
238
+ if (!savedActiveSessionId) {
239
+ savedActiveSessionId = Storage.get(CONFIG.ACTIVE_SESSION_KEY);
240
+ }
241
+ const savedActiveSession = savedActiveSessionId
242
+ ? this.sessionManager.get(savedActiveSessionId)
243
+ : null;
244
+
245
+ let sessionLoaded = false;
246
+
247
+ // An explicit ?session= in the URL OUTRANKS restored state. Nothing in
248
+ // the app ever writes that param (no pushState/replaceState carries it,
249
+ // and the PWA start_url is a bare /app), so its presence is always a
250
+ // deliberate deep-link/share — the user asked for THAT session. It used
251
+ // to be an `else if` after restored state, which meant a share link
252
+ // silently dropped you into whatever tab happened to be active.
253
+ if (urlSessionId) {
254
+ const localMatch = this.sessionManager.sessions.find(
255
+ s => s.id === urlSessionId || s.storeId === urlSessionId
256
+ );
257
+ if (localMatch) {
258
+ this.switchSession(localMatch);
259
+ sessionLoaded = true;
260
+ debug.log('[initFromUrl] Deep-link ?session= resolved locally:', urlSessionId);
261
+ } else {
262
+ debug.log('[initFromUrl] Deep-link ?session= loading from server:', urlSessionId);
263
+ sessionLoaded = await this.loadSessionFromServer(urlSessionId);
264
+ loadedFromServer = sessionLoaded;
265
+ }
266
+ }
267
+
268
+ // Otherwise localStorage (or server-reconciled state) decides.
269
+ if (!sessionLoaded && savedActiveSession) {
270
+ this.switchSession(savedActiveSession);
271
+ sessionLoaded = true;
272
+ debug.log('[initFromUrl] Using session:', savedActiveSession.id,
273
+ 'storeId:', savedActiveSession.storeId,
274
+ rebuiltFromServer ? '(rebuilt from server)' : '(from localStorage)');
275
+ }
276
+
277
+ if (!sessionLoaded) {
278
+ // Fallback: no valid session and URL load failed (or no URL)
279
+ if (this.sessionManager.sessions.length > 0) {
280
+ this.switchSession(this.sessionManager.sessions[0]);
281
+ } else {
282
+ this.createSession();
283
+ }
284
+ }
285
+
286
+ // Restore widget tabs (terminals, etc.) — server v2 state wins over
287
+ // localStorage (same iPadOS write-loss rationale as session tabs)
288
+ const serverTabState = this.sessionManager._serverTabState || null;
289
+ const hasWidgetTabs = this.tabCtrl.restoreWidgetTabs(serverTabState);
290
+
291
+ // Restore interleaved strip order (sessions ↔ widget tabs)
292
+ if (serverTabState?.order?.length) {
293
+ this.tabCtrl.applyServerOrder(serverTabState.order);
294
+ }
295
+
296
+ // Restore active mode (session/widget)
297
+ const savedMode = Storage.get(CONFIG.ACTIVE_MODE_KEY, 'session');
298
+ const serverActiveWidget = serverTabState?.activeTab?.kind === 'widget'
299
+ ? serverTabState.activeTab.id : null;
300
+ if (serverActiveWidget
301
+ && this.tabCtrl.widgetTabs.some(t => t.id === serverActiveWidget)) {
302
+ // Server's active pointer says a widget tab was in front — trust
303
+ // it unconditionally (same rationale as activeStoreId above: the
304
+ // server copy is the only one that survives localStorage loss).
305
+ this.tabCtrl.switchToWidgetTab(serverActiveWidget);
306
+ } else if (savedMode === 'widget' && hasWidgetTabs && this.tabCtrl.activeWidgetTabId) {
307
+ this.tabCtrl.switchToWidgetTab(this.tabCtrl.activeWidgetTabId);
308
+ } else {
309
+ this.renderTabs();
310
+ }
311
+
312
+ // Return whether we loaded fresh from server (to skip unnecessary fullSync)
313
+ return { loadedFromServer };
314
+ }
315
+
316
+ /**
317
+ * Initialize event handlers for controller communication
318
+ */
319
+ _initControllerEvents() {
320
+ // Handle events from DialogController
321
+ this.ctx.on('openFileInEditor', ({ path, cwd }) => {
322
+ this.openFileInEditor(path, cwd);
323
+ });
324
+
325
+ this.ctx.on('directoryCreated', ({ path }) => {
326
+ // Set cwd and connect
327
+ this.activeSession.cwd = path;
328
+ this.activeSession.connect();
329
+ this.els.connectionBar.classList.remove('visible');
330
+ // cwd is set — flip to chat view
331
+ this.tabCtrl.switchToSession(this.activeSession);
332
+ this.fetchProjectCommands(path);
333
+ this.sessionManager.saveSessions();
334
+ });
335
+
336
+ this.ctx.on('showSettings', () => {
337
+ if (this.configPanel) {
338
+ this.configPanel.show();
339
+ }
340
+ });
341
+
342
+ this.ctx.on('sessionItemClicked', async ({ sessionId, cwd, fromWelcome }) => {
343
+ const existingSession = this.sessionManager.sessions.find(s => s.storeId === sessionId);
344
+ if (existingSession) {
345
+ // Mark session if opened from welcome (for back button)
346
+ if (fromWelcome) {
347
+ existingSession.openedFromWelcome = true;
348
+ }
349
+ this.switchToSession(existingSession);
350
+ return;
351
+ }
352
+
353
+ const loaded = await this.loadSessionFromServer(sessionId, 50, fromWelcome);
354
+ if (!loaded && cwd) {
355
+ this.createSession();
356
+ this.connectActiveSession(cwd);
357
+ }
358
+ });
359
+
360
+ this.ctx.on('projectItemClicked', ({ path }) => {
361
+ this.connectActiveSession(path);
362
+ });
363
+ }
364
+
365
+
366
+
367
+ /**
368
+ * Send a message directly without welcome screen checks.
369
+ * Used when welcome has already determined this should be sent.
370
+ */
371
+ _sendMessageDirect(content) {
372
+ if (!this.activeSession) return;
373
+
374
+ // Save to persistent per-project history
375
+ this.addToInputHistory(content);
376
+
377
+ // Send with images if any
378
+ const images = [...this.pendingImages];
379
+ const files = [...this.pendingFiles];
380
+
381
+ // Appended, not prepended — see the same block in app/input-events.js:
382
+ // a prefix stops a leading slash command from being a command at all.
383
+ let messageToSend = content;
384
+ const sendOptions = {};
385
+ if (files.length > 0) {
386
+ const fileRefs = files.map(f => `Uploaded file: ${f.path}`).join('\n');
387
+ messageToSend = `${messageToSend}\n\n${fileRefs}`;
388
+ // Store the typed text, not the composition, so the server's
389
+ // `message_stored` broadcast is adopted by the bubble already on
390
+ // screen instead of landing as a duplicate.
391
+ sendOptions.displayContent = content;
392
+ sendOptions.files = files.map(f => f.path).filter(Boolean);
393
+ }
394
+
395
+ this.clearPendingImages();
396
+ this.clearPendingFiles();
397
+ if (this.activeSession) {
398
+ this.activeSession._savedUploadImages = [];
399
+ this.activeSession._savedUploadFiles = [];
400
+ }
401
+
402
+ // Add user message to UI immediately
403
+ // peekEffectiveLevel returns the one-shot override if armed, else
404
+ // the persistent level — the actual sent value is consumed by
405
+ // session.sendWithImages right before the WS message goes out.
406
+ const effortLevel = effortSettings.peekEffectiveLevel();
407
+ this.activeSession.addMessage({
408
+ role: 'user',
409
+ content: content,
410
+ timestamp: new Date().toISOString(),
411
+ images: images.length > 0 ? images : undefined,
412
+ hasFiles: files.length > 0,
413
+ fileCount: files.length,
414
+ effort_level: effortLevel !== 'high' ? effortLevel : undefined,
415
+ });
416
+
417
+ // Render immediately so user sees their message
418
+ this.renderMessages();
419
+
420
+ // Connect if not connected
421
+ if (this.activeSession.status !== 'connected') {
422
+ this.activeSession.connect();
423
+ // Queue the message to send after connection
424
+ const checkConnection = setInterval(() => {
425
+ if (this.activeSession.status === 'connected') {
426
+ clearInterval(checkConnection);
427
+ this.activeSession.sendWithImages(messageToSend, images, sendOptions);
428
+ }
429
+ }, 100);
430
+ setTimeout(() => clearInterval(checkConnection), 10000);
431
+ return;
432
+ }
433
+
434
+ // Send
435
+ this.activeSession.sendWithImages(messageToSend, images, {});
436
+ }
437
+
438
+ /**
439
+ * Handle storage quota exceeded - show warning to user
440
+ * @param {{key: string, usage: Object}} detail
441
+ */
442
+ handleStorageQuotaExceeded(detail) {
443
+ const { usage } = detail;
444
+ console.error('[Storage] Quota exceeded!', usage);
445
+
446
+ // Show a visible warning to the user via system log
447
+ if (this.activeSession) {
448
+ this.activeSession.addSystemLog(
449
+ `Storage full (${usage.usedMB}) - tab state may not persist. Use Storage Cleanup in quick actions menu.`,
450
+ 'error'
451
+ );
452
+ }
453
+
454
+ // Also show a toast
455
+ showToast(S.errors.storage_full);
456
+ }
457
+
458
+
459
+
460
+ /**
461
+ * Rename a session (set/update name)
462
+ */
463
+ async renameSession(session) {
464
+ const currentName = session.name || '';
465
+ const newName = await this.dialogCtrl.showPrompt({
466
+ title: S.ui.rename_dialog.title,
467
+ label: 'Session name',
468
+ value: currentName,
469
+ placeholder: 'Enter a name for this session',
470
+ confirmText: 'Rename',
471
+ cancelText: 'Cancel'
472
+ });
473
+
474
+ if (newName !== null && newName !== currentName) {
475
+ session.name = newName.trim() || 'Session';
476
+ // Persist to server
477
+ if (session.storeId) {
478
+ fetch(`/api/sessions/${session.storeId}/meta`, {
479
+ method: 'PATCH',
480
+ headers: { 'Content-Type': 'application/json' },
481
+ body: JSON.stringify({ name: session.name })
482
+ }).catch(err => console.error('Failed to save session name:', err));
483
+ }
484
+ // Save to localStorage so it persists across page refresh
485
+ this.sessionManager.saveSessions();
486
+ this.tabCtrl.renderTabs();
487
+ showToast(newName ? S.toast.renamed : S.toast.name_reset);
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Create a new session with a specific CWD.
493
+ * Used by Duplicate (default toast) and the project-picker (pass `toast: null`).
494
+ * @param {string} cwd - Working directory for the new session
495
+ * @param {object} [opts]
496
+ * @param {string|null} [opts.toast] - Completion toast; pass null to suppress.
497
+ */
498
+ createNewSession(cwd, opts = {}) {
499
+ const { toast = S.toast.session_cloned } = opts;
500
+
501
+ const session = this.sessionManager.create({ name: 'New Session' });
502
+ if (session) {
503
+ session.cwd = cwd;
504
+ this.switchSession(session);
505
+ this.renderTabs();
506
+ session.connect();
507
+ this.els.connectionBar.classList.remove('visible');
508
+ this.sessionManager.saveSessions();
509
+ this.addToHistory(cwd);
510
+ this.fileExplorer.setHomePath(cwd);
511
+ this.fetchProjectCommands(cwd);
512
+ if (toast) showToast(toast);
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Close all sessions except the given one.
518
+ * Pinned tabs are protected — only an explicit single Close touches them.
519
+ */
520
+ closeOtherSessions(keepSession) {
521
+ const toClose = this.sessionManager.sessions.filter(
522
+ s => s !== keepSession && !this.tabCtrl.isTabPinned('session', s.id));
523
+ toClose.forEach(s => this.closeSession(s));
524
+ }
525
+
526
+ /**
527
+ * Close all sessions (except pinned ones — see closeOtherSessions)
528
+ */
529
+ closeAllSessions() {
530
+ const toClose = this.sessionManager.sessions.filter(
531
+ s => !this.tabCtrl.isTabPinned('session', s.id));
532
+ toClose.forEach(s => this.closeSession(s));
533
+ }
534
+
535
+
536
+ initVisibilitySync() {
537
+ // Track when page was hidden (for debouncing)
538
+ this.hiddenSince = null;
539
+
540
+ document.addEventListener('visibilitychange', () => {
541
+ if (document.visibilityState === 'hidden') {
542
+ // Page is going to background - SAVE STATE IMMEDIATELY
543
+ // iOS PWA may not fire beforeunload reliably, so save here too
544
+ // Use immediate save to bypass debounce (page may close any moment)
545
+ debug.log('[App] visibilitychange:hidden - saving state');
546
+ this.hiddenSince = Date.now();
547
+ // Save current upload state to active session before serialization
548
+ if (this.activeSession && this.uploadManager) {
549
+ const uploadState = this.uploadManager.saveState();
550
+ this.activeSession.pendingImages = uploadState.pendingImages;
551
+ this.activeSession.pendingFiles = uploadState.pendingFiles;
552
+ }
553
+ this.sessionManager.saveSessionsImmediate();
554
+ this.tabCtrl?.saveWidgetTabs();
555
+ } else if (document.visibilityState === 'visible') {
556
+ // Page is coming back to foreground
557
+ const hiddenDuration = this.hiddenSince ? Date.now() - this.hiddenSince : 0;
558
+ this.hiddenSince = null;
559
+
560
+ // Only act if hidden for >1 second (avoid rapid tab switches)
561
+ if (hiddenDuration > 1000) {
562
+ // ALWAYS re-render when returning from background
563
+ // iOS Safari throttles/pauses DOM updates in background, so even if
564
+ // WebSocket messages arrived and were added to this.messages array,
565
+ // the DOM may be stale. Re-render ensures UI matches state.
566
+ if (this.activeSession) {
567
+ debug.log('[VisibilitySync] Re-rendering after background (hidden for', hiddenDuration, 'ms)');
568
+ // Capture the live scroll offset BEFORE the forced re-render
569
+ // nukes the container: an at-bottom reader lands back at the
570
+ // bottom, a scrolled-up reader keeps their place. scrollPosition
571
+ // is consumed one-shot by restoreScrollPosition().
572
+ const scrollEl = this.getActiveScrollContainer();
573
+ if (scrollEl && scrollEl.clientHeight > 0) {
574
+ const atBottom = (scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight) <= 100;
575
+ this.activeSession.scrollPosition = atBottom ? null : scrollEl.scrollTop;
576
+ this.activeSession.isUserScrolledUp = !atBottom;
577
+ }
578
+ // CRITICAL: Invalidate container pool to force full re-render
579
+ // Without this, the pool thinks container is already rendered and returns cached (stale) DOM
580
+ const sessionId = this.activeSession.id || this.activeSession.storeId || this.activeSession.sessionId;
581
+ this.chatCtrl?.invalidateSession(sessionId);
582
+ this.renderMessages();
583
+ this.scrollToBottom();
584
+ }
585
+
586
+ // Re-establish live sockets. iOS freezes the per-session
587
+ // keepalive interval while backgrounded, so the half-open
588
+ // detector can't be relied on after resume — kick a liveness
589
+ // check on every session (reconnects zombie/half-open sockets
590
+ // that still report readyState OPEN). Without this, the chat
591
+ // WebSocket can stay wedged forever after inactivity and even
592
+ // a reload won't recover (frozen network stack / stuck timers).
593
+ this.sessionManager.sessions.forEach(s => s.checkLiveness?.());
594
+
595
+ // Also sync to catch any messages we missed entirely
596
+ // (e.g., if WebSocket disconnected while in background)
597
+ this.syncAllSessions();
598
+ }
599
+ }
600
+ });
601
+ }
602
+
603
+ // fullSync=true fetches all messages (used on page load to update incomplete tool outputs)
604
+ async syncAllSessions(fullSync = false) {
605
+ debug.log(`[SyncAll DEBUG] syncAllSessions called, fullSync=${fullSync}`);
606
+ const sessionsToSync = this.sessionManager.sessions.filter(s => s.storeId);
607
+ debug.log(`[SyncAll DEBUG] Sessions to sync: ${sessionsToSync.length}`, sessionsToSync.map(s => s.storeId));
608
+ if (sessionsToSync.length === 0) return;
609
+
610
+ this.activeSession?.addSystemLog(S.status.syncing, 'info');
611
+
612
+ const results = await Promise.all(
613
+ sessionsToSync.map(s => s.syncMessages(fullSync))
614
+ );
615
+
616
+ const totalSynced = results.reduce((sum, r) => sum + r.synced, 0);
617
+ const errors = results.filter(r => r.error);
618
+
619
+ if (totalSynced > 0) {
620
+ this.activeSession?.addSystemLog(S.status.synced.replace('{count}', totalSynced), 'info');
621
+ } else if (errors.length === 0) {
622
+ this.activeSession?.addSystemLog(S.status.up_to_date, 'info');
623
+ }
624
+
625
+ if (errors.length > 0) {
626
+ this.activeSession?.addSystemLog(S.status.sync_failed.replace('{count}', errors.length), 'error');
627
+ }
628
+ }
629
+
630
+
631
+ /**
632
+ * Update autocomplete with slash commands from Claude's system init
633
+ * Called when session receives init message with slash_commands array
634
+ * @param {Array} commandNames - ["todo", "compact", "cost", ...] (names without /)
635
+ * @param {Object} [descriptions] - {name: "description"} from server
636
+ */
637
+ updateSlashCommands(commandNames, descriptions) {
638
+ this.commandDescriptions = descriptions || this.commandDescriptions || {};
639
+ this.autocomplete.setAgentCommands(commandNames, this.userCommandNames, this.commandDescriptions);
640
+ debug.log(`Loaded ${commandNames?.length || 0} slash commands from Claude`);
641
+ }
642
+
643
+ /**
644
+ * Fetch cached project commands from server
645
+ * Commands are cached per-project so new sessions can show them before Claude starts
646
+ * @param {string} cwd - Project directory path
647
+ */
648
+ async fetchProjectCommands(cwd) {
649
+ if (!cwd) return;
650
+ try {
651
+ const response = await fetch(`${CONFIG.API_BASE}/api/project/commands?cwd=${encodeURIComponent(cwd)}`);
652
+ if (response.ok) {
653
+ const data = await response.json();
654
+ if (data.user_commands?.length > 0) {
655
+ this.userCommandNames = new Set(data.user_commands);
656
+ }
657
+ if (data.commands?.length > 0) {
658
+ this.updateSlashCommands(data.commands, data.descriptions);
659
+ // Also update session's slashCommands for persistence
660
+ if (this.activeSession) {
661
+ this.activeSession.slashCommands = data.commands;
662
+ }
663
+ debug.log(`Loaded ${data.commands.length} cached project commands for ${cwd}`);
664
+ }
665
+ // Source paths for commands whose definition lives in a .md file
666
+ // (used by the commands gallery to offer "View source").
667
+ if (data.sources) {
668
+ this.commandSources = data.sources;
669
+ }
670
+ }
671
+ } catch (error) {
672
+ debug.warn('Failed to fetch project commands:', error);
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Fetch git branch for current project
678
+ * Updates status bar with branch name
679
+ * @param {string} cwd - Project directory path
680
+ */
681
+ async fetchGitBranch(cwd) {
682
+ if (!cwd) {
683
+ this.statusBar.updateBranch(null);
684
+ return;
685
+ }
686
+ try {
687
+ const response = await fetch(`${CONFIG.API_BASE}/api/git/status?cwd=${encodeURIComponent(cwd)}`);
688
+ if (response.ok) {
689
+ const data = await response.json();
690
+ this.statusBar.updateBranch(data.branch || null);
691
+ } else {
692
+ // Not a git repo or error - hide branch
693
+ this.statusBar.updateBranch(null);
694
+ }
695
+ } catch (error) {
696
+ debug.warn('Failed to fetch git branch:', error);
697
+ this.statusBar.updateBranch(null);
698
+ }
699
+ }
700
+
701
+
702
+
703
+ /**
704
+ * Initialize type-anywhere search: typing with input unfocused auto-focuses and searches.
705
+ * Only active on welcome screen with physical keyboard.
706
+ * Like macOS Finder or VS Code - just start typing to search.
707
+ */
708
+ _initTypeAnywhereSearch() {
709
+ // Only on devices with physical keyboard
710
+ debug.log('[TypeAnywhere] Init check - HAS_PHYSICAL_KEYBOARD:', HAS_PHYSICAL_KEYBOARD, 'UA:', navigator.userAgent.substring(0, 50));
711
+ if (!HAS_PHYSICAL_KEYBOARD) {
712
+ debug.log('[TypeAnywhere] DISABLED - no physical keyboard detected');
713
+ return;
714
+ }
715
+ debug.log('[TypeAnywhere] Handler registered');
716
+
717
+ // Click-to-blur: clicking welcome screen background blurs the input
718
+ this.els.welcomeView?.addEventListener('click', (e) => {
719
+ // Only if clicking on welcome background (not on cards, buttons, etc.)
720
+ const target = e.target;
721
+ if (target.closest('.welcome-recent-card, .session-family, button, a, input, .welcome-project-picker, .welcome-hint')) {
722
+ return;
723
+ }
724
+
725
+ // Blur the message input
726
+ if (document.activeElement === this.els.messageInput) {
727
+ this.els.messageInput.blur();
728
+ }
729
+ });
730
+
731
+ // Type-anywhere: typing on welcome screen with input unfocused triggers quick search
732
+ document.addEventListener('keydown', (e) => {
733
+ // Only single printable characters (check early to reduce noise).
734
+ // e.key can be undefined on iPadOS WKWebView synthetic events
735
+ // (autofill / QuickType / IME) — optional-chain so those fall out.
736
+ if (e.key?.length !== 1) return;
737
+
738
+ // Don't capture modifier combos (those are shortcuts)
739
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
740
+
741
+ // Only on welcome screen
742
+ if (!this.chatCtrl?.isWelcomeShowing()) {
743
+ return;
744
+ }
745
+
746
+ // Already focused on input - let normal typing work
747
+ if (document.activeElement === this.els.messageInput) {
748
+ return;
749
+ }
750
+
751
+ // Don't capture if focused on another input/textarea/editable (including quick search)
752
+ if (document.activeElement?.matches('input, textarea, [contenteditable="true"]')) {
753
+ return;
754
+ }
755
+
756
+ // Don't capture if widget/modal is open (use class-based detection)
757
+ const hasOpenOverlay = document.querySelector(
758
+ '#modal-overlay.visible, .quick-actions-overlay.visible, ' +
759
+ '.session-context-overlay, .session-preview-overlay, ' +
760
+ '.config-modal-overlay, .prompt-dialog-overlay'
761
+ );
762
+ if (hasOpenOverlay) {
763
+ return;
764
+ }
765
+
766
+ // Don't capture space alone (might be scrolling) - unless quick search is already active
767
+ if (e.key === ' ' && !isQuickSearchActive()) return;
768
+
769
+ // Capture the keystroke
770
+ e.preventDefault();
771
+ e.stopPropagation();
772
+
773
+ // Type into inline quick search
774
+ typeIntoQuickSearch(e.key);
775
+ });
776
+ }
777
+
778
+ // ═══════════════════════════════════════════════════════════════
779
+ // SESSION MANAGEMENT
780
+ // ═══════════════════════════════════════════════════════════════
781
+
782
+ /**
783
+ * Initialize long-press handler for new tab button
784
+ * Long press shows menu: New Session vs New Terminal
785
+ */
786
+ initNewTabLongPress() {
787
+ const btn = this.els.newTabBtn;
788
+ let pressTimer = null;
789
+ let clickBlocker = null;
790
+ let menuShown = false;
791
+
792
+ const removeClickBlocker = () => {
793
+ if (clickBlocker) {
794
+ document.removeEventListener('click', clickBlocker, { capture: true });
795
+ clickBlocker = null;
796
+ }
797
+ };
798
+
799
+ const showNewTabMenu = (x, y) => {
800
+ menuShown = true;
801
+ const menuItems = [
802
+ {
803
+ label: S.context_menus.project.new_session,
804
+ action: () => this.createSession()
805
+ },
806
+ {
807
+ label: S.context_menus.project.new_terminal,
808
+ action: () => this.tabCtrl.openTerminalWidgetTab()
809
+ },
810
+ {
811
+ label: S.context_menus.project.new_browser,
812
+ action: () => WidgetManager.open('browser')
813
+ },
814
+ {
815
+ label: S.context_menus.project.new_draft,
816
+ action: () => this.createScratchTab()
817
+ }
818
+ ];
819
+
820
+ // Add recently closed sessions if any
821
+ const recentlyClosed = this.sessionManager.recentlyClosed;
822
+ if (recentlyClosed.length > 0) {
823
+ menuItems.push({ separator: true });
824
+ menuItems.push({
825
+ label: S.context_menus.project.reopen,
826
+ submenu: recentlyClosed.slice().reverse().map(closed => ({
827
+ label: closed.name || basename(closed.cwd) || 'Session',
828
+ sublabel: closed.cwd,
829
+ action: () => this.reopenClosedSession(closed.storeId)
830
+ }))
831
+ });
832
+ }
833
+
834
+ this.contextMenu.show(x, y, menuItems);
835
+ };
836
+
837
+ // Long-press for touch devices (iOS)
838
+ // Non-passive to allow preventDefault() which suppresses iOS text selection
839
+ btn.addEventListener('touchstart', (e) => {
840
+ removeClickBlocker();
841
+ menuShown = false;
842
+
843
+ const touch = e.touches[0];
844
+ const startX = touch.clientX;
845
+ const startY = touch.clientY;
846
+
847
+ pressTimer = setTimeout(() => {
848
+ // Create click blocker BEFORE showing menu
849
+ clickBlocker = (evt) => {
850
+ evt.preventDefault();
851
+ evt.stopPropagation();
852
+ evt.stopImmediatePropagation();
853
+ };
854
+ document.addEventListener('click', clickBlocker, { capture: true });
855
+
856
+ // Clear any iOS text selection triggered during long-press
857
+ window.getSelection()?.removeAllRanges();
858
+
859
+ // Show menu below the button
860
+ const rect = btn.getBoundingClientRect();
861
+ showNewTabMenu(startX, rect.bottom + 4);
862
+ }, 400);
863
+ }, { passive: false });
864
+
865
+ btn.addEventListener('touchend', (e) => {
866
+ if (pressTimer) {
867
+ clearTimeout(pressTimer);
868
+ pressTimer = null;
869
+ }
870
+ if (menuShown) {
871
+ e.preventDefault();
872
+ e.stopPropagation();
873
+ setTimeout(removeClickBlocker, 400);
874
+ }
875
+ }, { passive: false });
876
+
877
+ btn.addEventListener('touchmove', () => {
878
+ if (pressTimer) {
879
+ clearTimeout(pressTimer);
880
+ pressTimer = null;
881
+ }
882
+ }, { passive: true });
883
+
884
+ // Right-click for desktop
885
+ btn.addEventListener('contextmenu', (e) => {
886
+ e.preventDefault();
887
+ showNewTabMenu(e.clientX, e.clientY);
888
+ });
889
+ }
890
+
891
+
892
+ // ═══════════════════════════════════════════════════════════════
893
+ // VIEW SWITCHING (delegated to TabController)
894
+ // ═══════════════════════════════════════════════════════════════
895
+
896
+ /** @delegate TabController */
897
+ getAllTabs() { return this.tabCtrl.getAllTabs(); }
898
+
899
+ /** @delegate TabController */
900
+ getCurrentTabIndex() { return this.tabCtrl.getCurrentTabIndex(); }
901
+
902
+ /** @delegate TabController */
903
+ switchToTabByIndex(index) { this.tabCtrl.switchToTabByIndex(index); }
904
+
905
+ /** @delegate TabController */
906
+ cycleTab(direction) { this.tabCtrl.cycleTab(direction); }
907
+
908
+ /** @delegate TabController */
909
+ switchToSession(session) { this.tabCtrl.switchToSession(session); }
910
+
911
+ // ═══════════════════════════════════════════════════════════════
912
+ // WIDGET TABS (delegated to TabController)
913
+ // ═══════════════════════════════════════════════════════════════
914
+
915
+ /** @delegate TabController */
916
+ createTerminal() {
917
+ if (!terminalAvailable()) {
918
+ showToast(S.toast.terminal_unavailable);
919
+ return;
920
+ }
921
+ try {
922
+ this.tabCtrl.openTerminalWidgetTab();
923
+ } catch (e) {
924
+ this.activeSession?.addSystemLog(e.message, 'error');
925
+ }
926
+ }
927
+
928
+ /**
929
+ * Open a terminal tab running the engine's interactive login flow.
930
+ * Used by the `/login` slash command and the auth-error card — the in-app
931
+ * `/login` is interactive-only, so we drop the user into a PTY where the
932
+ * OAuth/device flow works as designed. `command` (from the auth_error
933
+ * frame's `login_command`) wins; otherwise the active session's engine is
934
+ * resolved via the registry (`/api/app/engine-auth`), falling back to
935
+ * `claude auth login`.
936
+ */
937
+ async openLoginTerminal(command = null) {
938
+ if (!terminalAvailable()) {
939
+ // No PTY on this server (native Windows) — the user runs the
940
+ // login command in their own console instead.
941
+ showToast(S.toast.terminal_unavailable_login);
942
+ return;
943
+ }
944
+ try {
945
+ if (!command) {
946
+ const engine = this.activeSession?.provider || this.activeSession?.pendingProvider;
947
+ if (engine) {
948
+ try {
949
+ const resp = await fetch(`/api/app/engine-auth/${encodeURIComponent(engine)}`);
950
+ if (resp.ok) command = (await resp.json()).login_command || null;
951
+ } catch { /* fall through to the claude default */ }
952
+ }
953
+ }
954
+ this.tabCtrl.openTerminalWidgetTab({
955
+ title: 'Login',
956
+ icon: 'terminal',
957
+ initialCommand: `${command || 'claude auth login'}\n`,
958
+ });
959
+ } catch (e) {
960
+ this.activeSession?.addSystemLog(e.message, 'error');
961
+ }
962
+ }
963
+
964
+ /** Open a terminal tab running `claude auth logout`. Mirror of openLoginTerminal. */
965
+ openLogoutTerminal() {
966
+ try {
967
+ this.tabCtrl.openTerminalWidgetTab({
968
+ title: 'Logout',
969
+ icon: 'terminal',
970
+ initialCommand: 'claude auth logout\n',
971
+ });
972
+ } catch (e) {
973
+ this.activeSession?.addSystemLog(e.message, 'error');
974
+ }
975
+ }
976
+
977
+ /** @delegate TabController - called during init */
978
+ initWidgetTabEvents() { this.tabCtrl.initWidgetTabEvents(); }
979
+
980
+ /** @delegate TabController */
981
+ openTerminalWidgetTab(options) { return this.tabCtrl.openTerminalWidgetTab(options); }
982
+
983
+ /** @delegate TabController */
984
+ openWidgetAsTab(widgetId, title, icon) { this.tabCtrl.openWidgetAsTab(widgetId, title, icon); }
985
+
986
+ /** @delegate TabController */
987
+ switchToWidgetTab(tabId) { this.tabCtrl.switchToWidgetTab(tabId); }
988
+
989
+ /** @delegate TabController */
990
+ closeWidgetTab(tabId) { this.tabCtrl.closeWidgetTab(tabId); }
991
+
992
+
993
+ async connectActiveSession(cwd = this.activeSession?.cwd) {
994
+ if (!this.activeSession) return;
995
+ // Prevent connecting if already connected or connecting
996
+ if (this.activeSession.status !== 'disconnected') return;
997
+
998
+ cwd = (cwd || '').trim();
999
+ if (!cwd) {
1000
+ this.activeSession?.addSystemLog(S.errors.enter_directory);
1001
+ return;
1002
+ }
1003
+
1004
+ // Expand paths: ~ to home, relative paths to projects base
1005
+ let expandedCwd = cwd;
1006
+ if (cwd.startsWith('~')) {
1007
+ expandedCwd = cwd.replace('~', CONFIG.HOME);
1008
+ } else if (!isAbsolutePath(cwd, CONFIG.HOME)) {
1009
+ // Relative path - make it relative to projects base
1010
+ expandedCwd = joinPath(CONFIG.PROJECTS_BASE, cwd);
1011
+ }
1012
+
1013
+ // Check if directory exists
1014
+ try {
1015
+ const response = await fetch(`${CONFIG.API_BASE}/api/check-dir?path=${encodeURIComponent(expandedCwd)}`);
1016
+ const data = await response.json();
1017
+
1018
+ if (!data.exists) {
1019
+ // Show confirm dialog to create directory
1020
+ this.pendingCwd = data.path;
1021
+ this.showConfirmDialog(data.path);
1022
+ return;
1023
+ }
1024
+
1025
+ if (!data.is_dir) {
1026
+ // It's a file - open it in the appropriate viewer
1027
+ this.els.connectionBar.classList.remove('visible');
1028
+ this.previewFile(data.path);
1029
+ return;
1030
+ }
1031
+
1032
+ // Directory exists, connect (use resolved path from server)
1033
+ this.activeSession.cwd = data.path;
1034
+ this.activeSession.connect();
1035
+ this.els.connectionBar.classList.remove('visible');
1036
+ // cwd is now set → predicate is false → switchToSession lands in chat
1037
+ this.tabCtrl.switchToSession(this.activeSession);
1038
+ this.sessionManager.saveSessions();
1039
+ // Save to history
1040
+ this.addToHistory(data.path);
1041
+ // Update file explorer's home path
1042
+ this.fileExplorer.setHomePath(data.path);
1043
+ // Fetch cached project commands (so autocomplete works before Claude starts)
1044
+ this.fetchProjectCommands(data.path);
1045
+ } catch (error) {
1046
+ console.error('Error checking directory:', error);
1047
+ // If we can't check, just try to connect anyway
1048
+ this.activeSession.cwd = expandedCwd;
1049
+ this.activeSession.connect();
1050
+ this.els.connectionBar.classList.remove('visible');
1051
+ this.tabCtrl.switchToSession(this.activeSession);
1052
+ this.fetchProjectCommands(expandedCwd);
1053
+ this.sessionManager.saveSessions();
1054
+ this.addToHistory(expandedCwd);
1055
+ this.fileExplorer.setHomePath(expandedCwd);
1056
+ }
1057
+ }
1058
+
1059
+ addToHistory(cwd) {
1060
+ const history = Storage.get(CONFIG.HISTORY_KEY, []);
1061
+ const filtered = history.filter(h => h !== cwd);
1062
+ filtered.unshift(cwd);
1063
+ Storage.set(CONFIG.HISTORY_KEY, filtered.slice(0, CONFIG.MAX_HISTORY));
1064
+ }
1065
+
1066
+ getCwdHistory() {
1067
+ return Storage.get(CONFIG.HISTORY_KEY, []);
1068
+ }
1069
+
1070
+ // ═══════════════════════════════════════════════════════════════
1071
+ // RENDERING
1072
+ // ═══════════════════════════════════════════════════════════════
1073
+
1074
+ /** @delegate TabController */
1075
+ renderTabs() { this.tabCtrl.renderTabs(); }
1076
+
1077
+ /** @delegate ChatController */
1078
+ renderMessages() {
1079
+ this.chatCtrl.renderMessages();
1080
+ }
1081
+
1082
+ /**
1083
+ * Render the welcome screen for a session inside #welcome-view.
1084
+ * Per-session container preserves DOM (and therefore scroll position) when
1085
+ * switching tabs, mirroring SessionContainerPool's strategy for chat.
1086
+ */
1087
+ renderWelcome(session) {
1088
+ if (!session || !this.els.welcomeView) return;
1089
+
1090
+ const sessionId = session.id || session.storeId;
1091
+ const root = this.els.welcomeView;
1092
+
1093
+ // Hide / un-id all existing instances
1094
+ for (const child of root.children) {
1095
+ child.style.display = 'none';
1096
+ if (child.id === 'welcome-container') child.removeAttribute('id');
1097
+ }
1098
+
1099
+ // Find-or-create the per-session container
1100
+ let container = root.querySelector(`[data-session-id="${CSS.escape(String(sessionId))}"]`);
1101
+ const isNew = !container;
1102
+ if (isNew) {
1103
+ container = document.createElement('div');
1104
+ container.className = 'welcome-container-instance';
1105
+ container.dataset.sessionId = sessionId;
1106
+ root.appendChild(container);
1107
+ }
1108
+
1109
+ // Show + mark as the active welcome-container (welcome.js querySelectors hit this one)
1110
+ container.style.display = '';
1111
+ container.id = 'welcome-container';
1112
+
1113
+ if (isNew) {
1114
+ initWelcomeScreen(container, sessionId);
1115
+ }
1116
+
1117
+ // No back-to-sessions pill from welcome
1118
+ this.chatCtrl?._hideBackToSessionsPill?.();
1119
+ }
1120
+
1121
+ /** @delegate ChatController */
1122
+ restoreScrollPosition() {
1123
+ this.chatCtrl.restoreScrollPosition();
1124
+ this.isUserScrolledUp = !this.isNearBottom();
1125
+ }
1126
+
1127
+ /** @delegate ChatController */
1128
+ async renderRecentProjects(container) {
1129
+ this.chatCtrl.renderRecentProjects(container);
1130
+ }
1131
+
1132
+ /** @delegate ChatController */
1133
+ prependMessages(messages) {
1134
+ this.chatCtrl.prependMessages(messages);
1135
+ }
1136
+
1137
+ /** @delegate ChatController */
1138
+ createMessageElement(msg) {
1139
+ return this.chatCtrl.createMessageElement(msg);
1140
+ }
1141
+
1142
+ /** @delegate ThinkingController */
1143
+ createThinkingGroupElement(thinkingGroup) {
1144
+ return this.thinkingCtrl.createThinkingGroupElement(thinkingGroup);
1145
+ }
1146
+
1147
+ /** @delegate ChatController */
1148
+ async handleScrollTop() {
1149
+ this.chatCtrl.handleScrollTop();
1150
+ }
1151
+
1152
+ /** @delegate ChatController */
1153
+ updateHistoryNotice() {
1154
+ this.chatCtrl.updateHistoryNotice();
1155
+ }
1156
+
1157
+ /** @delegate ChatController */
1158
+ showLoadMoreIndicator(show) {
1159
+ this.chatCtrl.showLoadMoreIndicator(show);
1160
+ }
1161
+
1162
+ /** @delegate ChatController */
1163
+
1164
+ updateInputState() {
1165
+ const connected = this.activeSession?.status === 'connected';
1166
+ const welcomeShowing = this.chatCtrl?.isWelcomeShowing();
1167
+
1168
+ // Enable input when connected OR when welcome screen allows search
1169
+ const inputEnabled = connected || welcomeShowing;
1170
+ const wasDisabled = this.els.messageInput.disabled;
1171
+
1172
+ this.els.inputContainer.classList.toggle('disabled', !inputEnabled);
1173
+ this.els.messageInput.disabled = !inputEnabled;
1174
+
1175
+ // When disabling: blur the input to remove false focus state (Safari/iPad bug)
1176
+ // Without this, the input can show blue border but not accept typing
1177
+ if (!inputEnabled && document.activeElement === this.els.messageInput) {
1178
+ this.els.messageInput.blur();
1179
+ }
1180
+
1181
+ // When enabling: auto-focus on desktop (don't pop up keyboard on mobile)
1182
+ // But NOT on welcome screen - the input area is hidden there, use search bar instead
1183
+ if (inputEnabled && wasDisabled && HAS_PHYSICAL_KEYBOARD && !welcomeShowing) {
1184
+ // Use requestAnimationFrame to ensure DOM is ready after any renders
1185
+ requestAnimationFrame(() => this.focusInput());
1186
+ }
1187
+
1188
+ const hasContent = this.els.messageInput.value.trim() || Stash.hasEnabled();
1189
+ const welcomeSearchEnabled = welcomeShowing && this.els.messageInput.value.trim();
1190
+
1191
+ this.els.sendBtn.disabled = !hasContent || (!connected && !welcomeSearchEnabled);
1192
+ if (this.els.followupBtn) this.els.followupBtn.disabled = this.els.sendBtn.disabled;
1193
+
1194
+ // Update placeholder
1195
+ this.updateInputPlaceholder();
1196
+ }
1197
+
1198
+ /**
1199
+ * Update input placeholder. Plan mode is signalled by the permission
1200
+ * button alone — the input keeps its default placeholder and shortcut
1201
+ * hints so the empty-input cheat sheet still appears.
1202
+ */
1203
+ updateInputPlaceholder() {
1204
+ if (!this.els.messageInput) return;
1205
+
1206
+ const pendingCount = this.activeSession?.pendingBangOutputs?.length || 0;
1207
+
1208
+ if (pendingCount > 0) {
1209
+ this.els.messageInput.placeholder = `${pendingCount} command${pendingCount > 1 ? 's' : ''} buffered. Type message and press Enter...`;
1210
+ } else {
1211
+ this.els.messageInput.placeholder = S.ui.input.placeholder;
1212
+ }
1213
+ }
1214
+
1215
+ /**
1216
+ * Set activity state via ActivityStrip (replaces old typing dots).
1217
+ * @param {{ active: boolean, icon?: string, text?: string }} activity
1218
+ */
1219
+ setActivity(activity) {
1220
+ if (activity.active) {
1221
+ this.activityStrip?.show(activity);
1222
+ // Strip appearing adds height — scroll after CSS transition (250ms).
1223
+ // respectLinkHover: fires on every tool/status change during a
1224
+ // turn, and must not yank a link out from under the pointer.
1225
+ if (!this.isUserScrolledUp) {
1226
+ setTimeout(() => this.scrollManager?.scrollToBottomForce({ respectLinkHover: true }), 300);
1227
+ }
1228
+ } else {
1229
+ this.activityStrip?.hide();
1230
+ }
1231
+ // Toggle send/stop buttons
1232
+ this.statusBar?.toggleStopButton(activity.active);
1233
+ }
1234
+
1235
+ /**
1236
+ * Backward-compat wrapper: setTyping(bool, statusText) → setActivity()
1237
+ */
1238
+ setTyping(typing, statusText = null) {
1239
+ if (typing) {
1240
+ const label = statusText || 'Working...';
1241
+ const icon = statusText === 'Compacting...' ? 'compress' : 'sparkle';
1242
+ this.setActivity({ active: true, icon, label });
1243
+ } else {
1244
+ this.setActivity({ active: false });
1245
+ }
1246
+ }
1247
+
1248
+ /** Compatibility getter for isTyping */
1249
+ get isTyping() {
1250
+ return this.statusBar?.isTyping ?? false;
1251
+ }
1252
+
1253
+ /** Compatibility setter for isTyping */
1254
+ set isTyping(value) {
1255
+ if (this.statusBar) {
1256
+ this.statusBar.isTyping = value;
1257
+ }
1258
+ }
1259
+
1260
+ // ═══════════════════════════════════════════════════════════════
1261
+ // TAB STATE (delegated to TabController)
1262
+ // ═══════════════════════════════════════════════════════════════
1263
+
1264
+ /** Widget tabs array from TabController */
1265
+ get widgetTabs() {
1266
+ return this.tabCtrl?.widgetTabs || [];
1267
+ }
1268
+
1269
+ /** Active widget tab ID from TabController */
1270
+ get activeWidgetTabId() {
1271
+ return this.tabCtrl?.activeWidgetTabId;
1272
+ }
1273
+
1274
+ /** Active mode (session/editor/widget) from TabController */
1275
+ get activeMode() {
1276
+ return this.tabCtrl?.activeMode || 'session';
1277
+ }
1278
+
1279
+ /** @deprecated Use toolRenderer.formatThinkingToolInput() */
1280
+ formatThinkingToolInput(toolName, input) {
1281
+ return this.toolRenderer.formatThinkingToolInput(toolName, input);
1282
+ }
1283
+
1284
+ /** @delegate ThinkingController */
1285
+ renderToolOutput(content, isCompleted = false, threshold = 5) {
1286
+ return this.thinkingCtrl.renderToolOutput(content, isCompleted, threshold);
1287
+ }
1288
+
1289
+ /** @delegate ThinkingController */
1290
+ renderThinkingEdits(thinkingMsgs) {
1291
+ return this.thinkingCtrl.renderThinkingEdits(thinkingMsgs);
1292
+ }
1293
+
1294
+ // ═══════════════════════════════════════════════════════════════
1295
+ // STATUS (delegated to StatusBar)
1296
+ // ═══════════════════════════════════════════════════════════════
1297
+
1298
+ /** Update connection status display */
1299
+ updateStatus() {
1300
+ this.statusBar?.updateStatus();
1301
+ // Fresh-session setup pills ride the same funnel (cheap no-op once
1302
+ // the first message exists / on non-fresh tabs).
1303
+ sessionSetupPanel.refresh();
1304
+ }
1305
+
1306
+ // ═══════════════════════════════════════════════════════════════
1307
+ // SCROLL MANAGEMENT (delegated to ScrollManager)
1308
+ // ═══════════════════════════════════════════════════════════════
1309
+
1310
+ /** @deprecated Use scrollManager.isNearBottom() */
1311
+ isNearBottom() {
1312
+ return this.scrollManager?.isNearBottom() ?? true;
1313
+ }
1314
+
1315
+ /** @deprecated Use scrollManager.scrollToBottom() */
1316
+ scrollToBottom() {
1317
+ this.scrollManager?.scrollToBottom();
1318
+ }
1319
+
1320
+ /** @deprecated Use scrollManager.trackNewMessage() */
1321
+ trackNewMessage() {
1322
+ this.scrollManager?.trackNewMessage();
1323
+ }
1324
+
1325
+ /** @deprecated Use scrollManager.scrollToBottomForce() */
1326
+ scrollToBottomForce() {
1327
+ this.scrollManager?.scrollToBottomForce();
1328
+ }
1329
+
1330
+ /** @deprecated Use scrollManager.clearIndicator() */
1331
+ clearNewMessagesIndicator() {
1332
+ this.scrollManager?.clearIndicator();
1333
+ }
1334
+
1335
+ /** Compatibility getter for isUserScrolledUp */
1336
+ get isUserScrolledUp() {
1337
+ return this.scrollManager?.isUserScrolledUp ?? false;
1338
+ }
1339
+
1340
+ /** Compatibility setter for isUserScrolledUp */
1341
+ set isUserScrolledUp(value) {
1342
+ if (this.scrollManager) {
1343
+ this.scrollManager.isUserScrolledUp = value;
1344
+ }
1345
+ }
1346
+
1347
+ /**
1348
+ * Update the floating question indicator
1349
+ * Call when question state changes (added/answered)
1350
+ */
1351
+ updateQuestionIndicator() {
1352
+ if (!this.scrollManager || !this.activeSession) return;
1353
+ const questionMsg = this.activeSession.messages.find(m => (m.role === 'question' || m.role === 'permission') && !m.answered);
1354
+ this.scrollManager.updateQuestionIndicator(questionMsg || null);
1355
+ }
1356
+
1357
+ // ═══════════════════════════════════════════════════════════════
1358
+ // COMMANDS
1359
+ // ═══════════════════════════════════════════════════════════════
1360
+ // DIALOGS (delegated to DialogController)
1361
+ // ═══════════════════════════════════════════════════════════════
1362
+
1363
+ /** @delegate DialogController */
1364
+ showHelp() {
1365
+ this.dialogCtrl.showHelp();
1366
+ }
1367
+
1368
+ /** @delegate DialogController */
1369
+ hideModal() {
1370
+ this.dialogCtrl.hideModal();
1371
+ }
1372
+
1373
+ /**
1374
+ * Clear session: archive current session (keep for browsing), start fresh in same project.
1375
+ * Unlike the old behavior which destroyed messages, this preserves the session history.
1376
+ */
1377
+ clearMessages() {
1378
+ const session = this.activeSession;
1379
+ if (!session?.cwd) {
1380
+ showToast(S.errors.no_project_clear);
1381
+ return;
1382
+ }
1383
+
1384
+ const cwd = session.cwd;
1385
+
1386
+ // Remove current session from local list (disconnects WS, keeps server data intact)
1387
+ this.sessionManager.remove(session);
1388
+
1389
+ // Create new session with same CWD
1390
+ const newSession = this.sessionManager.create({ name: 'New Session' });
1391
+ if (newSession) {
1392
+ newSession.cwd = cwd;
1393
+ this.switchSession(newSession);
1394
+ this.renderTabs();
1395
+ newSession.connect();
1396
+ this.els.connectionBar.classList.remove('visible');
1397
+ this.sessionManager.saveSessions();
1398
+ this.addToHistory(cwd);
1399
+ this.fileExplorer.setHomePath(cwd);
1400
+ this.fetchProjectCommands(cwd);
1401
+ showToast(S.status.starting_fresh);
1402
+ }
1403
+ }
1404
+
1405
+
1406
+ /** @delegate DialogController */
1407
+ showConfirmDialog(path) {
1408
+ this.dialogCtrl.showConfirmDialog(path);
1409
+ this.pendingCwd = path; // Keep for backward compatibility
1410
+ }
1411
+
1412
+ /** @delegate DialogController */
1413
+ hideConfirmDialog() {
1414
+ this.dialogCtrl.hideConfirmDialog();
1415
+ this.pendingCwd = null;
1416
+ }
1417
+
1418
+ /** @delegate DialogController */
1419
+ async createDirectoryAndConnect() {
1420
+ this.dialogCtrl.createDirectoryAndConnect();
1421
+ }
1422
+
1423
+ // ═══════════════════════════════════════════════════════════════
1424
+ // FILE & IMAGE UPLOAD (delegated to UploadManager)
1425
+ // ═══════════════════════════════════════════════════════════════
1426
+
1427
+ initImageUpload() {
1428
+ // Initialize UploadManager (replaces old inline implementation)
1429
+ this.uploadManager = new UploadManager(
1430
+ {
1431
+ inputContainer: this.els.inputContainer,
1432
+ messageInput: this.els.messageInput,
1433
+ messagesContainer: this.els.messagesContainer,
1434
+ sendBtn: this.els.sendBtn
1435
+ },
1436
+ { apiBase: CONFIG.API_BASE },
1437
+ {
1438
+ getSessionId: () => this.activeSession?.storeId,
1439
+ isConnected: () => this.activeSession?.status === 'connected',
1440
+ onError: (msg) => this.activeSession?.addSystemLog(msg, 'error'),
1441
+ onStateChange: () => {
1442
+ this.updateSendButtonState();
1443
+ // Uploads settled — release a send that was parked mid-upload
1444
+ this.inputHandler?.flushDeferredSend();
1445
+ }
1446
+ }
1447
+ );
1448
+ }
1449
+
1450
+ /** @deprecated Use uploadManager.getPendingImages() */
1451
+ get pendingImages() {
1452
+ return this.uploadManager?.pendingImages || [];
1453
+ }
1454
+
1455
+ /** @deprecated Use uploadManager.getPendingFiles() */
1456
+ get pendingFiles() {
1457
+ return this.uploadManager?.pendingFiles || [];
1458
+ }
1459
+
1460
+ /** @deprecated Use uploadManager.clearImages() */
1461
+ clearPendingImages() {
1462
+ this.uploadManager?.clearImages();
1463
+ }
1464
+
1465
+ /** @deprecated Use uploadManager.clearFiles() */
1466
+ clearPendingFiles() {
1467
+ this.uploadManager?.clearFiles();
1468
+ }
1469
+
1470
+ updateSendButtonState() {
1471
+ // In-flight uploads count as content: the user should be able to hit
1472
+ // send mid-upload and have it queue (InputHandler defers it) rather
1473
+ // than face a dead button or send the message without the attachment.
1474
+ const hasContent = this.els.messageInput.value.trim() ||
1475
+ this.uploadManager?.hasPending ||
1476
+ this.uploadManager?.isUploading ||
1477
+ Stash.hasEnabled();
1478
+ const connected = this.activeSession?.status === 'connected';
1479
+
1480
+ // Enable send button for welcome search even when disconnected
1481
+ const welcomeSearchEnabled = this.chatCtrl?.isWelcomeShowing() &&
1482
+ this.els.messageInput.value.trim();
1483
+
1484
+ // A send parked on an in-flight upload keeps the button disabled. This
1485
+ // method runs on every upload progress tick, so without the check it
1486
+ // would re-enable the button underneath the parked send and invite a
1487
+ // second Enter that only re-arms the same deferral.
1488
+ const awaitingUpload = this.inputHandler?.isAwaitingUpload() || false;
1489
+
1490
+ this.els.sendBtn.disabled = awaitingUpload || !hasContent ||
1491
+ (!connected && !welcomeSearchEnabled);
1492
+ if (this.els.followupBtn) this.els.followupBtn.disabled = this.els.sendBtn.disabled;
1493
+ }
1494
+
1495
+ openImageUpload() {
1496
+ this.uploadManager?.openImagePicker();
1497
+ }
1498
+
1499
+ openFileUpload() {
1500
+ this.uploadManager?.openFilePicker();
1501
+ }
1502
+
1503
+ // ═══════════════════════════════════════════════════════════════
1504
+ // UTILITIES
1505
+ // ═══════════════════════════════════════════════════════════════
1506
+
1507
+ // ═══════════════════════════════════════════════════════════════
1508
+ // SHORTCUT ACTION METHODS
1509
+ // These methods are called by ShortcutManager
1510
+ // ═══════════════════════════════════════════════════════════════
1511
+
1512
+ goToPreviousUserMessage() {
1513
+ this.chatNavigator?.goToPrevious();
1514
+ }
1515
+
1516
+ goToNextUserMessage() {
1517
+ this.chatNavigator?.goToNext();
1518
+ }
1519
+
1520
+ toggleTerminalPanel() {
1521
+ if (!terminalAvailable()) {
1522
+ showToast(S.toast.terminal_unavailable);
1523
+ return;
1524
+ }
1525
+ WidgetManager.toggle('terminal');
1526
+ }
1527
+
1528
+ /**
1529
+ * Handle trim messages action (via FAB quick action).
1530
+ * Removes old messages from DOM for better scroll performance.
1531
+ * Keeps at least 100 messages, and always preserves the complete last turn.
1532
+ */
1533
+ handleTrimMessages() {
1534
+ const trimCount = this.chatCtrl?.getTrimCount(); // Uses default 100, preserves last turn
1535
+ if (!trimCount || trimCount === 0) {
1536
+ this.activeSession?.addSystemLog(S.errors.no_messages_trim, 'info');
1537
+ return;
1538
+ }
1539
+
1540
+ // Perform the trim (uses default 100, preserves last turn)
1541
+ const trimmed = this.chatCtrl.trimOldMessages();
1542
+ if (trimmed > 0) {
1543
+ this.activeSession?.addSystemLog(`Trimmed ${trimmed} old messages. Scroll up to reload.`, 'info');
1544
+ }
1545
+ }
1546
+
1547
+ /**
1548
+ * Send key to the active terminal (tab or floating panel)
1549
+ * Used by keyboard bar to inject special keys
1550
+ */
1551
+ sendKeyToActiveTerminal(key, modifiers = {}) {
1552
+ // Map special keys to escape sequences
1553
+ const keyMap = {
1554
+ 'Escape': '\x1b',
1555
+ 'Tab': '\t',
1556
+ 'ArrowUp': '\x1b[A',
1557
+ 'ArrowDown': '\x1b[B',
1558
+ 'ArrowRight': '\x1b[C',
1559
+ 'ArrowLeft': '\x1b[D',
1560
+ 'Home': '\x1b[H',
1561
+ 'End': '\x1b[F',
1562
+ 'PageUp': '\x1b[5~',
1563
+ 'PageDown': '\x1b[6~',
1564
+ 'Delete': '\x1b[3~',
1565
+ 'Backspace': '\x7f',
1566
+ };
1567
+
1568
+ let data = keyMap[key] || key;
1569
+
1570
+ // Apply Ctrl modifier for single characters
1571
+ if (modifiers.ctrl && data.length === 1) {
1572
+ const code = data.toLowerCase().charCodeAt(0);
1573
+ if (code >= 97 && code <= 122) {
1574
+ data = String.fromCharCode(code - 96);
1575
+ }
1576
+ }
1577
+
1578
+ // Send to terminal widget
1579
+ const ws = TerminalWidget.getWebSocket();
1580
+ if (ws?.readyState === WebSocket.OPEN) {
1581
+ ws.send(data);
1582
+ }
1583
+ }
1584
+
1585
+
1586
+ closeActiveTab() {
1587
+ // First: close topmost floating widget if any are visible
1588
+ // Unlike ESC, Ctrl+W should always close terminal (no passthrough to vim/nano)
1589
+ if (WidgetManager.closeTopmost({ allowTerminalPassthrough: false })) {
1590
+ return;
1591
+ }
1592
+
1593
+ // Then: close tabs (widget tab in tab bar, or session tab)
1594
+ if (this.activeMode === 'widget' && this.activeWidgetTabId) {
1595
+ this.closeWidgetTab(this.activeWidgetTabId);
1596
+ } else if (this.activeSession) {
1597
+ this.closeSession(this.activeSession);
1598
+ }
1599
+ }
1600
+
1601
+ /**
1602
+ * Reopen the most recently closed tab (Ctrl+Shift+T).
1603
+ * Merges session and widget-tab stacks — whichever was closed last wins.
1604
+ */
1605
+ async reopenLastClosedTab() {
1606
+ const sessionStack = this.sessionManager.recentlyClosed;
1607
+ const tabStack = this.tabCtrl?.recentlyClosedTabs || [];
1608
+ if (sessionStack.length === 0 && tabStack.length === 0) {
1609
+ return;
1610
+ }
1611
+
1612
+ const topSession = sessionStack[sessionStack.length - 1];
1613
+ const topTab = tabStack[tabStack.length - 1];
1614
+ const tabWins = topTab && (!topSession || topTab.closedAt > topSession.closedAt);
1615
+
1616
+ if (tabWins) {
1617
+ tabStack.pop();
1618
+ if (topTab.widgetId === 'file-preview' && topTab.filePath) {
1619
+ const tabId = this.tabCtrl.openFilePreviewTab(topTab.filePath, topTab.title, { newTab: true });
1620
+ // Creation appends to the strip end — slide it back to its old slot
1621
+ if (tabId) this.tabCtrl.insertTabAt('widget', tabId, topTab.stripIndex);
1622
+ }
1623
+ return;
1624
+ }
1625
+
1626
+ const closedData = sessionStack.pop();
1627
+
1628
+ // Check if this session is already open
1629
+ const existing = this.sessionManager.sessions.find(s => s.storeId === closedData.storeId);
1630
+ if (existing) {
1631
+ this.switchSession(existing);
1632
+ return;
1633
+ }
1634
+
1635
+ // Load session from server (fetches messages, metadata, then switches)
1636
+ const loaded = await this.loadSessionFromServer(closedData.storeId);
1637
+ // loadSessionFromServer resolves to a boolean — re-find the session it made
1638
+ const reopened = loaded && this.sessionManager.sessions.find(s => s.storeId === closedData.storeId);
1639
+ if (reopened) {
1640
+ this.tabCtrl?.insertTabAt('session', reopened.id, closedData.stripIndex);
1641
+ }
1642
+ if (loaded && this.activeSession) {
1643
+ // Auto-connect after loading
1644
+ if (this.activeSession.status === 'disconnected') {
1645
+ this.activeSession.connect();
1646
+ }
1647
+ }
1648
+ }
1649
+
1650
+ /**
1651
+ * Reopen a specific closed session by storeId (from + button menu)
1652
+ */
1653
+ async reopenClosedSession(storeId) {
1654
+ // Find and remove from recentlyClosed stack
1655
+ const idx = this.sessionManager.recentlyClosed.findIndex(c => c.storeId === storeId);
1656
+ if (idx === -1) return;
1657
+
1658
+ const [closedData] = this.sessionManager.recentlyClosed.splice(idx, 1);
1659
+
1660
+ // Check if already open
1661
+ const existing = this.sessionManager.sessions.find(s => s.storeId === storeId);
1662
+ if (existing) {
1663
+ this.switchSession(existing);
1664
+ return;
1665
+ }
1666
+
1667
+ // Load session from server (fetches messages, metadata, then switches)
1668
+ const loaded = await this.loadSessionFromServer(storeId);
1669
+ const reopened = loaded && this.sessionManager.sessions.find(s => s.storeId === storeId);
1670
+ if (reopened) {
1671
+ this.tabCtrl?.insertTabAt('session', reopened.id, closedData.stripIndex);
1672
+ }
1673
+ if (loaded && this.activeSession) {
1674
+ // Auto-connect after loading
1675
+ if (this.activeSession.status === 'disconnected') {
1676
+ this.activeSession.connect();
1677
+ }
1678
+ }
1679
+ }
1680
+
1681
+ handleEscape() {
1682
+ // Priority order: zen mode > selection mode > FAB menu > context menu > legacy dialogs > close widgets > CWD autocomplete > file autocomplete > command autocomplete > close search > file explorer > stop Claude
1683
+ // This ensures dialogs, widgets and autocompletes close before stopping Claude
1684
+
1685
+ // 0. Cancel input Tab-cycle (must run before autocomplete-hide branches —
1686
+ // those would dismiss the popup but leave the inserted trigger char and
1687
+ // active toolbar highlight stranded).
1688
+ if (this.inputHandler?.isTabCycleActive?.()) {
1689
+ this.inputHandler.cancelTabCycle();
1690
+ return;
1691
+ }
1692
+
1693
+ // 0. Close grid switcher overlay (highest priority — full-screen modal)
1694
+ if (this.gridSwitcher?.visible) {
1695
+ this.gridSwitcher.hide();
1696
+ return;
1697
+ }
1698
+
1699
+ // 0. Close mid-text autocomplete pickers if open (skills `$`, snippets `#`, files `@`)
1700
+ if (this.skillsAutocomplete?.visible) {
1701
+ this.skillsAutocomplete.hide();
1702
+ return;
1703
+ }
1704
+ if (this.snippetsAutocomplete?.visible) {
1705
+ this.snippetsAutocomplete.hide();
1706
+ return;
1707
+ }
1708
+ if (this.fileAutocomplete?.visible) {
1709
+ this.fileAutocomplete.hide();
1710
+ return;
1711
+ }
1712
+
1713
+ // 0. Close Zen Mode overlay (fullscreen, highest priority)
1714
+ if (window.isZenModeOpen?.()) {
1715
+ window.toggleZenMode();
1716
+ return;
1717
+ }
1718
+
1719
+ // 1. Exit selection mode (action bar or popup)
1720
+ if (isSelectionModeActive()) {
1721
+ exitSelectionMode();
1722
+ return;
1723
+ }
1724
+
1725
+ // 1.5. Close permission/thinking/effort/layout popups if open
1726
+ if (permissionSettings.isOpen) {
1727
+ permissionSettings.close();
1728
+ return;
1729
+ }
1730
+ if (effortSettings.isOpen) {
1731
+ effortSettings.close();
1732
+ return;
1733
+ }
1734
+ if (layoutSwitcher.isOpen) {
1735
+ layoutSwitcher.close();
1736
+ return;
1737
+ }
1738
+ // Status-bar model popup — its own document keydown listener can be
1739
+ // starved when an earlier branch here (e.g. closeTopmost) eats the
1740
+ // key, so close it deterministically in the chain too.
1741
+ if (this.statusBar?._modelPopupOpen) {
1742
+ this.statusBar._closeModelPopup();
1743
+ return;
1744
+ }
1745
+
1746
+ // 1.6. Abandon a send parked on an in-flight upload. Ranked below the
1747
+ // popups (those are what the user is looking at) but above panels and
1748
+ // Stop: Escape here means "don't send that", and every branch below
1749
+ // would leave the send armed to fire when the upload lands. Has to live
1750
+ // in this chain rather than the textarea's own keydown listener —
1751
+ // ShortcutManager claims Escape in the capture phase and calls
1752
+ // stopImmediatePropagation(), so the input never sees the key.
1753
+ if (this.inputHandler?.isAwaitingUpload?.()) {
1754
+ this.inputHandler.cancelDeferredSend();
1755
+ return;
1756
+ }
1757
+
1758
+ // 2. Close quick actions menu (FAB) if open
1759
+ if (QuickActionsMenu.isContextMenuOpen) {
1760
+ QuickActionsMenu.closeContextMenu();
1761
+ return;
1762
+ }
1763
+ if (QuickActionsMenu.isOpen) {
1764
+ QuickActionsMenu.close();
1765
+ return;
1766
+ }
1767
+
1768
+ // 2.45. Close the project color-picker swatch popup if open
1769
+ if (closeProjectColorPicker()) {
1770
+ return;
1771
+ }
1772
+
1773
+ // 2.5. Close context menu (right-click menu) if open
1774
+ if (this.contextMenu?.visible) {
1775
+ this.contextMenu.hide();
1776
+ return;
1777
+ }
1778
+
1779
+ // 2.6. Close welcome screen context menu if open
1780
+ if (closeWelcomeContextMenu()) {
1781
+ return;
1782
+ }
1783
+
1784
+ // 2.65. Close the Comments Stash picker if open
1785
+ if (closeStashPickerIfOpen()) {
1786
+ return;
1787
+ }
1788
+
1789
+ // 2.7. Close CodeMirror search panel if open (edit/scratch mode)
1790
+ if (FilePreviewWidget.isOpen() && FilePreviewWidget.closeEditorSearch()) {
1791
+ return;
1792
+ }
1793
+
1794
+ // 2.8. Close file preview search if active (read-only mode)
1795
+ if (FilePreviewWidget.isOpen() && FilePreviewWidget.isSearchActive()) {
1796
+ FilePreviewWidget.closeSearch();
1797
+ return;
1798
+ }
1799
+
1800
+ // 2.9. Deactivate inline edit mode in file preview instead of closing widget.
1801
+ // Match anywhere in DOM — works for both floating widgets and tab-hosted ones,
1802
+ // which WidgetManager.get() doesn't always return.
1803
+ if (FilePreviewWidget.isOpen()) {
1804
+ // Prefer a VISIBLE pane: hidden session/widget tabs keep their
1805
+ // .file-preview-widget in the DOM, and the first match could be one
1806
+ // of those — Esc would then report "edit mode off" while the pane
1807
+ // the user is looking at stays in edit mode.
1808
+ const candidates = document.querySelectorAll('.preview-rendered.inline-edit-mode');
1809
+ const rendered = Array.from(candidates).find(el => el.offsetParent !== null)
1810
+ || candidates[0];
1811
+ if (rendered) {
1812
+ const container = rendered.closest('.file-preview-widget');
1813
+ import('./preview/preview-inline-edit.js').then(({ toggleInlineEdit }) => {
1814
+ toggleInlineEdit(container);
1815
+ showToast(S.preview?.inline_edit_off || 'Edit mode off');
1816
+ });
1817
+ return;
1818
+ }
1819
+ }
1820
+
1821
+ // 2.95. Leave edit (CM) view in file preview. State-based — a stale .cm-editor
1822
+ // in a different widget instance must not flip the active widget's viewMode.
1823
+ if (FilePreviewWidget.isOpen() && FilePreviewWidget.isEditing) {
1824
+ import('./preview/preview-edit.js').then(({ leaveEditView }) => {
1825
+ leaveEditView('code');
1826
+ });
1827
+ return;
1828
+ }
1829
+
1830
+ // 2.99. Exit file explorer search view → list view (before closing the widget entirely)
1831
+ if (window.FileExplorerWidget?.handleEscape?.()) {
1832
+ return;
1833
+ }
1834
+
1835
+ // 2.99b. Close any open inline modal overlay (snippet editor, prompt dialog)
1836
+ // before falling through to closing the widget that hosts it.
1837
+ const openModalOverlay = document.querySelector('.config-modal-overlay, .prompt-dialog-overlay');
1838
+ if (openModalOverlay) {
1839
+ openModalOverlay.remove();
1840
+ return;
1841
+ }
1842
+
1843
+ // 2.99d. Image annotator owns ESC — dirty-aware discard confirm and
1844
+ // cancelling an open text/marker input. Must run before closeTopmost,
1845
+ // which would otherwise close the modal outright and skip the confirm.
1846
+ if (handleAnnotatorEscape()) {
1847
+ return;
1848
+ }
1849
+
1850
+ // 2.99e. Close the legacy full-screen dialogs (help page, mkdir confirm).
1851
+ // They live at --z-modal, above every widget, so Esc must dismiss them
1852
+ // first — and crucially before the Stop-Claude branch below, which used
1853
+ // to cancel the running turn while the help page just sat there open.
1854
+ // The confirm dialog needs handling here too: the global shortcut
1855
+ // listener is capture-phase, so it beats the dialog's own keydown.
1856
+ if (this.els?.modalOverlay?.classList.contains('visible')) {
1857
+ this.hideModal();
1858
+ return;
1859
+ }
1860
+ if (this.els?.confirmDialog?.classList.contains('visible')) {
1861
+ this.hideConfirmDialog();
1862
+ return;
1863
+ }
1864
+
1865
+ // 3. Close topmost widget (floating windows, modals, panels)
1866
+ if (WidgetManager.closeTopmost()) {
1867
+ return;
1868
+ }
1869
+
1870
+ // 5. Hide file autocomplete dropdown
1871
+ if (this.fileAutocomplete?.visible) {
1872
+ this.fileAutocomplete.hide();
1873
+ return;
1874
+ }
1875
+
1876
+ // 6. Hide command autocomplete dropdown
1877
+ if (this.autocomplete?.visible) {
1878
+ this.autocomplete.hide();
1879
+ return;
1880
+ }
1881
+
1882
+ // 7. Close chat search
1883
+ if (this.chatSearch?.active) {
1884
+ this.chatSearch.close();
1885
+ return;
1886
+ }
1887
+
1888
+ // 7.5. Close session preview on welcome screen
1889
+ if (this.chatCtrl?.isWelcomeShowing() && closeSessionPreview()) {
1890
+ return;
1891
+ }
1892
+
1893
+ // 7.6. Clear welcome screen search
1894
+ if (this.chatCtrl?.isWelcomeShowing() && clearWelcomeSearch()) {
1895
+ return;
1896
+ }
1897
+
1898
+ // 8. Close old-style file explorer (not yet migrated to widget system)
1899
+ if (this.fileExplorer?.state !== 'collapsed') {
1900
+ this.fileExplorer.close();
1901
+ return;
1902
+ }
1903
+
1904
+ // 8.5. Deny a pending interactive permission ask (Esc = Deny). More
1905
+ // specific than Stop Claude below, so it wins while a card is waiting —
1906
+ // but only after transient overlays/widgets above have had their turn.
1907
+ if (this.denyPendingPermission()) {
1908
+ return;
1909
+ }
1910
+
1911
+ // 9. Dismiss back-to-sessions pill (Esc = dismiss, not navigate)
1912
+ if (this.chatCtrl?.canGoBackToSessions()) {
1913
+ this.chatCtrl._dismissBackToSessionsPill();
1914
+ return;
1915
+ }
1916
+
1917
+ // 10. Stop Claude if running — only when focused on a session tab.
1918
+ // Preview / terminal / other widget tabs shouldn't hijack ESC to cancel
1919
+ // the chat in the background.
1920
+ if (this.isTyping && this.activeMode === 'session') {
1921
+ this.stopClaude();
1922
+ return;
1923
+ }
1924
+
1925
+ // Nothing left to dismiss — the legacy dialogs are handled at 2.99e,
1926
+ // above Stop Claude, so there's no trailing hideModal() here.
1927
+ }
1928
+
1929
+ /**
1930
+ * Handle Backspace key - navigates back to sessions if pill is visible
1931
+ * (Shortcut action for 'backToSessions')
1932
+ */
1933
+ handleBackToSessions() {
1934
+ if (this.chatCtrl?.canGoBackToSessions()) {
1935
+ this.chatCtrl._handleBackToSessions();
1936
+ }
1937
+ }
1938
+
1939
+ openSearch() {
1940
+ // Check if file preview is open - prioritize its search
1941
+ if (FilePreviewWidget.isOpen()) {
1942
+ FilePreviewWidget.openSearch();
1943
+ return;
1944
+ }
1945
+
1946
+ // File explorer: prioritize its search when it's focused
1947
+ if (window.FileExplorerWidget?.isFocused?.()) {
1948
+ window.FileExplorerWidget.openSearch();
1949
+ return;
1950
+ }
1951
+
1952
+ // On welcome screen, open inline quick search
1953
+ if (this.chatCtrl?.isWelcomeShowing()) {
1954
+ openQuickSearch();
1955
+ return;
1956
+ }
1957
+
1958
+ if (this.activeMode === 'session') {
1959
+ this.chatSearch?.toggle();
1960
+ }
1961
+ }
1962
+
1963
+ findNext() {
1964
+ // Check if file preview search is active
1965
+ if (FilePreviewWidget.isOpen() && FilePreviewWidget.isSearchActive()) {
1966
+ FilePreviewWidget.findNext();
1967
+ return;
1968
+ }
1969
+
1970
+ if (this.activeMode === 'session' && this.chatSearch?.active) {
1971
+ this.chatSearch.navigate(1);
1972
+ }
1973
+ }
1974
+
1975
+ findPrevious() {
1976
+ // Check if file preview search is active
1977
+ if (FilePreviewWidget.isOpen() && FilePreviewWidget.isSearchActive()) {
1978
+ FilePreviewWidget.findPrevious();
1979
+ return;
1980
+ }
1981
+
1982
+ if (this.activeMode === 'session' && this.chatSearch?.active) {
1983
+ this.chatSearch.navigate(-1);
1984
+ }
1985
+ }
1986
+
1987
+ focusInput() {
1988
+ // Don't steal focus from terminal — if user is typing in xterm, leave it alone
1989
+ const inTerminal = document.activeElement?.closest('.xterm') ||
1990
+ document.activeElement?.closest('.terminal-container') ||
1991
+ document.activeElement?.closest('.terminal-widget-xterm');
1992
+ if (inTerminal) {
1993
+ return;
1994
+ }
1995
+ // If terminal widget is open but not focused, focus it instead of input
1996
+ if (WidgetManager.isOpen('terminal')) {
1997
+ TerminalWidget.focus();
1998
+ return;
1999
+ }
2000
+ // If input is disabled, check if session state has changed (race condition
2001
+ // during reconnection: updateInputState ran before WebSocket connected)
2002
+ if (this.els.messageInput?.disabled) {
2003
+ const connected = this.activeSession?.status === 'connected';
2004
+ const welcomeShowing = this.chatCtrl?.isWelcomeShowing();
2005
+ if (connected || welcomeShowing) {
2006
+ // Session caught up - re-sync input state
2007
+ this.updateInputState();
2008
+ }
2009
+ // Still disabled after re-sync? Fall back to the open-folder button
2010
+ if (this.els.messageInput?.disabled) {
2011
+ this.els.openFolderBtn?.focus();
2012
+ return;
2013
+ }
2014
+ }
2015
+ // On welcome screen, the input area is hidden - don't try to focus it
2016
+ // Type-anywhere handler will capture keystrokes and focus the search bar
2017
+ if (this.chatCtrl?.isWelcomeShowing()) {
2018
+ return;
2019
+ }
2020
+ // Blur first to break any "ghost focus" state on iOS/iPadOS/macOS PWA
2021
+ // (where input appears focused but doesn't receive keystrokes)
2022
+ if (document.activeElement === this.els.messageInput) {
2023
+ this.els.messageInput.blur();
2024
+ }
2025
+ // Focus message input
2026
+ this.els.messageInput?.focus();
2027
+ }
2028
+
2029
+ }
2030
+
2031
+ // Mix in cohesive sub-concerns extracted from this file. Each module exports a
2032
+ // plain object of methods that use `this` (App instance state); assigning onto
2033
+ // the prototype keeps the class API identical to the pre-split implementation.
2034
+ Object.assign(
2035
+ App.prototype,
2036
+ panelMethods,
2037
+ contextMenuMethods,
2038
+ renderingDelegatorMethods,
2039
+ filePreviewMethods,
2040
+ sessionSwitchMethods,
2041
+ initUiMethods,
2042
+ inputEventMethods,
2043
+ serverLoadingMethods,
2044
+ inputResizeMethods,
2045
+ startupWelcomeMethods,
2046
+ settingsHelperMethods,
2047
+ messageActionMethods,
2048
+ sessionOpsMethods,
2049
+ );
2050
+
2051
+ // ═══════════════════════════════════════════════════════════════════
2052
+ // INITIALIZE
2053
+ // ═══════════════════════════════════════════════════════════════════
2054
+ window.app = new App();
2055
+
2056
+ // Load user-assigned project colors early so tabs/cards paint the custom
2057
+ // accent on first render (falls back to deterministic hash colors on error).
2058
+ loadProjectColors();
2059
+
2060
+ // Render an optimistic Auto-journal pill immediately so users see it
2061
+ // instead of empty space; the real status check below will refine
2062
+ // (e.g. flip to red/yellow if helpers turn out missing/outdated).
2063
+ window.app?._updateHelpersPill?.({ all_installed: true, all_current: true, any_outdated: false, files: [] });
2064
+
2065
+ // Preload CodeMirror in background so editor opens instantly
2066
+ setTimeout(() => import('./editor-view.js').then(m => m.preloadCodeMirror()).catch(() => {}), 2000);
2067
+ // Check helper install state once the app has settled — silently updates the
2068
+ // status-bar pill, and pops the install modal when state warrants it.
2069
+ setTimeout(() => window.app?._checkHelpersInstall?.(), 800);
2070
+ window.WidgetManager = WidgetManager;
2071
+ window.DiffViewerWidget = DiffViewerWidget;
2072
+ // Expose DeviceManager and FileExplorerWidget for console probing
2073
+ import('./widget-system/device-manager.js').then(m => { window.DeviceManager = m.DeviceManager; });
2074
+ import('./widgets/file-explorer-widget.js').then(m => { window.FileExplorerWidget = m.FileExplorerWidget; });
2075
+ // Initialize text selection handler (for stash and discussion)
2076
+ initSelectionHandler();
2077
+ initTooltips();
2078
+ // Initialize stash UI (context collector)
2079
+ initStashUI();
2080
+ // Initialize prompt favorites (mark prompts as favorites before/after sending)
2081
+ PromptFavorites.init();
2082
+ // Expose for session.js to call when storeId is set
2083
+ window.loadStashForSession = loadStashForSession;
2084
+ // Update send button when stash changes
2085
+ Stash.subscribe(() => window.app?.updateSendButtonState());
2086
+
2087
+ // Register chat messages container for text selection (stash and discussion)
2088
+ const messagesContainer = document.getElementById('messages');
2089
+ if (messagesContainer) {
2090
+ registerSelectionContainer('chat-messages', messagesContainer, {
2091
+ buildAnchor: (range, text) => {
2092
+ // Find the closest message element
2093
+ const messageEl = range.commonAncestorContainer.nodeType === 1
2094
+ ? range.commonAncestorContainer.closest('.message')
2095
+ : range.commonAncestorContainer.parentElement?.closest('.message');
2096
+
2097
+ return {
2098
+ type: 'message',
2099
+ messageId: messageEl?.dataset?.msgId || null,
2100
+ messageIndex: messageEl ? Array.from(messagesContainer.children).indexOf(messageEl) + 1 : null,
2101
+ selectedText: text
2102
+ };
2103
+ }
2104
+ });
2105
+ debug.log('[App] Registered chat-messages container for selection');
2106
+ }
2107
+
2108
+ // Load performance instrumentation if ?perf=true
2109
+ if (new URLSearchParams(location.search).has('perf')) {
2110
+ import('./perf-marks.js');
2111
+ }
2112
+
2113
+ // Wait for URL-based session loading to complete before auto-reconnecting
2114
+ // This ensures server messages are loaded before connecting
2115
+ window.app.initFromUrl().then(async (result) => {
2116
+ // Initialize snippets data from server (async, non-blocking)
2117
+ // Pass initial cwd if available for project-local agents
2118
+ const initialCwd = window.app.activeSession?.cwd || null;
2119
+ initSnippetsData(initialCwd).catch(e => console.warn('Failed to init snippets:', e));
2120
+
2121
+ // Start WebSocket reconnection IMMEDIATELY — don't wait for message sync.
2122
+ // This is the critical path for input focus: input stays disabled until
2123
+ // ws.onopen fires, so every ms of delay here = slower time-to-interactive.
2124
+ window.app.autoReconnectSessions();
2125
+
2126
+ // Full sync on page load to update incomplete tool outputs in localStorage
2127
+ // (visibilitychange doesn't fire on page reload, only on tab switch/background)
2128
+ // BUT: skip if we just loaded fresh from server (already have latest data)
2129
+ // This runs in parallel with WebSocket connection — no longer blocks input focus.
2130
+ if (!result?.loadedFromServer) {
2131
+ window.app.syncAllSessions(true).catch(e => console.warn('Background sync failed:', e));
2132
+ }
2133
+ });
2134
+