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,1828 @@
1
+ /**
2
+ * TabController - Unified tab management for sessions, files, and widgets
3
+ *
4
+ * Handles:
5
+ * - View switching (session, editor, widget)
6
+ * - Tab cycling and navigation
7
+ * - Widget tabs (terminals, etc.)
8
+ * - Tab rendering
9
+ */
10
+
11
+ import { CONFIG, debug } from '../config.js';
12
+ import { Storage, escapeHtml, appConfirm } from '../utils.js';
13
+ import S from '../strings.js';
14
+ import { WidgetManager, WidgetBus, TerminalWidget, FilePreviewWidget } from '../widget-system/init.js';
15
+ import { ICONS } from '../widget-system/icons.js';
16
+ import { getFileName, detectLanguage, getLanguageIcon } from '../file-tabs.js';
17
+ import { isFavoriteSession } from '../welcome.js';
18
+ import { recordOpen as recordRecentOpen } from '../recent-opens.js';
19
+ import { projectColorStyle } from '../project-colors.js';
20
+ import { basename } from '../path-utils.js';
21
+
22
+ export class TabController {
23
+ constructor(ctx) {
24
+ this.ctx = ctx;
25
+
26
+ // Tab state (owned by this controller)
27
+ this.widgetTabs = []; // Array of {id, widgetId, title, icon, isTerminal?}
28
+ this.activeWidgetTabId = null;
29
+ this.activeMode = 'session'; // 'session' | 'widget' | 'welcome'
30
+
31
+ // Unified strip order — sessions and widget tabs interleaved.
32
+ // Entries: {kind:'session', id, storeId?} | {kind:'widget', id}
33
+ // Self-healing via _syncTabOrder(); persisted to localStorage and
34
+ // carried to the server inside the /api/app/tabs payload.
35
+ this.tabOrder = Storage.get(CONFIG.TAB_ORDER_KEY, []) || [];
36
+ this._lastSavedOrderJson = null;
37
+
38
+ // Boot guard: widget tabs are recreated by restoreWidgetTabs(), which
39
+ // runs LATER in app.initFromUrl than the first renderTabs() (a session
40
+ // switch renders the strip immediately). Until then a widget entry in
41
+ // tabOrder has no live tab behind it, and pruning it there would throw
42
+ // away its strip position — the tab would come back appended at the end
43
+ // on every reload, dragging the tabs behind it forward.
44
+ this._widgetTabsRestored = false;
45
+
46
+ // Stack of recently closed widget tabs (for Ctrl+Shift+T reopen).
47
+ // Sessions have their own stack on SessionManager; the app's
48
+ // reopenLastClosedTab() merges both by closedAt.
49
+ this.recentlyClosedTabs = [];
50
+ this._maxRecentlyClosedTabs = 10;
51
+ }
52
+
53
+ // ═══════════════════════════════════════════════════════════════
54
+ // GETTERS (for external access to state)
55
+ // ═══════════════════════════════════════════════════════════════
56
+
57
+ get sessionManager() {
58
+ return this.ctx._app.sessionManager;
59
+ }
60
+
61
+ get activeSession() {
62
+ return this.ctx.session;
63
+ }
64
+
65
+ get els() {
66
+ return this.ctx.els;
67
+ }
68
+
69
+ /**
70
+ * Have widget tabs been recreated yet this page load? Until they have,
71
+ * serializeWidgetTabs() is empty and the strip is only half-built, so
72
+ * persisting it would erase the server's widget-tab record.
73
+ */
74
+ get widgetTabsRestored() {
75
+ return this._widgetTabsRestored;
76
+ }
77
+
78
+ // ═══════════════════════════════════════════════════════════════
79
+ // UNIFIED TAB LIST
80
+ // ═══════════════════════════════════════════════════════════════
81
+
82
+ /**
83
+ * Get all tabs (sessions + files + widgets) in strip order
84
+ * @returns {Array<{type: string, id: string, data: object}>}
85
+ */
86
+ getAllTabs() {
87
+ this._syncTabOrder();
88
+ const sessionById = new Map(this.sessionManager.sessions.map(s => [s.id, s]));
89
+ const widgetById = new Map(this.widgetTabs.map(t => [t.id, t]));
90
+ return this.tabOrder
91
+ .map(e => e.kind === 'session'
92
+ ? { type: 'session', id: e.id, data: sessionById.get(e.id) }
93
+ : { type: 'widget', id: e.id, data: widgetById.get(e.id) })
94
+ // Entries with no live tab behind them (widget tabs still awaiting
95
+ // restoreWidgetTabs) are placeholders, not tabs: renderTabs skips
96
+ // them, so keeping them here would make this list longer than the
97
+ // strip and drift every index-based caller — cycleTab included.
98
+ .filter(t => t.data);
99
+ }
100
+
101
+ /**
102
+ * Reconcile tabOrder with the actual session/widget-tab lists.
103
+ * - Remaps session entries whose client id changed (rebuild-from-server)
104
+ * by matching storeId.
105
+ * - Drops entries whose tab no longer exists.
106
+ * - Inserts new sessions: mid-array creations (atIndex, e.g. welcome-tab
107
+ * replace) keep their position relative to session neighbors; sessions
108
+ * at the array end append to the END OF THE STRIP — this is what lets
109
+ * widget tabs sit between session tabs.
110
+ * - Appends new widget tabs at the end of the strip.
111
+ * - Finally hoists pinned entries to the front (stable), so tabOrder is
112
+ * ALWAYS normalized pinned-first and array indices match visual order.
113
+ */
114
+ _syncTabOrder() {
115
+ const sessions = this.sessionManager.sessions;
116
+ const sessionById = new Map(sessions.map(s => [s.id, s]));
117
+ const widgetIds = new Set(this.widgetTabs.map(t => t.id));
118
+
119
+ // Remap stale session ids via storeId (sessions rebuilt from server state)
120
+ for (const e of this.tabOrder) {
121
+ if (e.kind !== 'session' || sessionById.has(e.id) || !e.storeId) continue;
122
+ const match = sessions.find(s => s.storeId === e.storeId);
123
+ if (match && !this.tabOrder.some(o => o !== e && o.kind === 'session' && o.id === match.id)) {
124
+ e.id = match.id;
125
+ }
126
+ }
127
+
128
+ // Drop stale entries; keep session storeIds fresh. Widget entries are
129
+ // held onto until restoreWidgetTabs() has had its turn (see
130
+ // _widgetTabsRestored) so a reload can't lose their strip position;
131
+ // getAllTabs() filters the not-yet-live ones out of the visible list.
132
+ this.tabOrder = this.tabOrder.filter(e => e.kind === 'session'
133
+ ? sessionById.has(e.id)
134
+ : (widgetIds.has(e.id) || !this._widgetTabsRestored));
135
+ for (const e of this.tabOrder) {
136
+ if (e.kind === 'session' && sessionById.get(e.id).storeId) {
137
+ e.storeId = sessionById.get(e.id).storeId;
138
+ }
139
+ }
140
+
141
+ // Insert missing sessions
142
+ const hasSession = (id) => this.tabOrder.some(e => e.kind === 'session' && e.id === id);
143
+ sessions.forEach((s, i) => {
144
+ if (hasSession(s.id)) return;
145
+ const entry = { kind: 'session', id: s.id, ...(s.storeId ? { storeId: s.storeId } : {}) };
146
+ const next = sessions.slice(i + 1).find(n => hasSession(n.id));
147
+ if (next) {
148
+ const idx = this.tabOrder.findIndex(e => e.kind === 'session' && e.id === next.id);
149
+ this.tabOrder.splice(idx, 0, entry);
150
+ } else {
151
+ this.tabOrder.push(entry);
152
+ }
153
+ });
154
+
155
+ // Append missing widget tabs
156
+ for (const t of this.widgetTabs) {
157
+ if (!this.tabOrder.some(e => e.kind === 'widget' && e.id === t.id)) {
158
+ this.tabOrder.push({ kind: 'widget', id: t.id });
159
+ }
160
+ }
161
+
162
+ this._partitionPinned();
163
+ }
164
+
165
+ // ═══════════════════════════════════════════════════════════════
166
+ // PINNED TABS
167
+ // ═══════════════════════════════════════════════════════════════
168
+
169
+ /**
170
+ * Hoist pinned entries to the front of tabOrder, preserving relative order
171
+ * within each group (filter is stable). Keeping tabOrder itself normalized
172
+ * — rather than sorting at read time — means index-based callers (moveTab,
173
+ * getTabPosition, switchToTabByIndex, cycleTab) all agree with the strip,
174
+ * and applyDomOrder() can keep reading the DOM back 1:1.
175
+ *
176
+ * NOTE the field is `stripPinned`, not `pinned`: this file already uses
177
+ * "pinned" for the unrelated file-preview ephemeral→permanent promotion
178
+ * (see openFilePreviewTab), so the strip concept gets its own name.
179
+ * @private
180
+ */
181
+ _partitionPinned() {
182
+ const pinned = this.tabOrder.filter(e => e.stripPinned);
183
+ if (pinned.length === 0 || pinned.length === this.tabOrder.length) return;
184
+ this.tabOrder = [...pinned, ...this.tabOrder.filter(e => !e.stripPinned)];
185
+ }
186
+
187
+ /**
188
+ * Is this tab pinned to the front of the strip?
189
+ * @param {string} kind - 'session' | 'widget'
190
+ * @param {string} id
191
+ */
192
+ isTabPinned(kind, id) {
193
+ return !!this.tabOrder.find(e => e.kind === kind && e.id === id)?.stripPinned;
194
+ }
195
+
196
+ /**
197
+ * Toggle pinned state for a tab. Pinned tabs sort first in the strip and
198
+ * are skipped by Close All / Close Others.
199
+ * @param {string} kind - 'session' | 'widget'
200
+ * @param {string} id
201
+ * @param {boolean} [force] - explicit target state (default: flip)
202
+ * @returns {boolean} the resulting pinned state
203
+ */
204
+ toggleTabPin(kind, id, force) {
205
+ this._syncTabOrder();
206
+ const entry = this.tabOrder.find(e => e.kind === kind && e.id === id);
207
+ if (!entry) return false;
208
+
209
+ const next = force === undefined ? !entry.stripPinned : !!force;
210
+ if (next) entry.stripPinned = true;
211
+ else delete entry.stripPinned; // keep persisted entries lean
212
+
213
+ this._partitionPinned();
214
+ this.renderTabs();
215
+ this.sessionManager._postTabStateToServer();
216
+ return next;
217
+ }
218
+
219
+ /**
220
+ * Persist tabOrder to localStorage (only when it actually changed).
221
+ */
222
+ _saveTabOrder() {
223
+ const json = JSON.stringify(this.tabOrder);
224
+ if (json === this._lastSavedOrderJson) return;
225
+ this._lastSavedOrderJson = json;
226
+ Storage.set(CONFIG.TAB_ORDER_KEY, this.tabOrder);
227
+ }
228
+
229
+ /**
230
+ * Move a tab within the unified strip (context menu "Move left/right").
231
+ * @param {string} kind - 'session' | 'widget'
232
+ * @param {string} id - session client id or widget tab id
233
+ * @param {number} direction - -1 left, +1 right
234
+ */
235
+ moveTab(kind, id, direction) {
236
+ this._syncTabOrder();
237
+ const idx = this.tabOrder.findIndex(e => e.kind === kind && e.id === id);
238
+ const target = idx + direction;
239
+ if (idx === -1 || target < 0 || target >= this.tabOrder.length) return;
240
+ // Never let a move cross the pinned/unpinned boundary — _partitionPinned
241
+ // would just snap it back on the next render.
242
+ if (!!this.tabOrder[idx].stripPinned !== !!this.tabOrder[target].stripPinned) return;
243
+ const [entry] = this.tabOrder.splice(idx, 1);
244
+ this.tabOrder.splice(target, 0, entry);
245
+ this.renderTabs();
246
+ this.sessionManager._postTabStateToServer();
247
+ }
248
+
249
+ /**
250
+ * Move an existing tab to an absolute strip index.
251
+ *
252
+ * Used by the reopen-closed-tab path: every creation API appends to the end
253
+ * of the strip, so a reopened tab is created first and then slid back to the
254
+ * slot it was closed from (recorded by getTabPosition at close time).
255
+ *
256
+ * The index is clamped into the tab's own pinned segment — a reopened
257
+ * (unpinned) tab can't land inside the pinned block, which _partitionPinned
258
+ * would undo on the next render anyway.
259
+ *
260
+ * @param {string} kind - 'session' | 'widget'
261
+ * @param {string} id - session client id or widget tab id
262
+ * @param {number} index - target strip index (tabOrder index)
263
+ * @returns {boolean} false when the tab isn't in the strip or index is unusable
264
+ */
265
+ insertTabAt(kind, id, index) {
266
+ if (!Number.isInteger(index) || index < 0) return false;
267
+ this._syncTabOrder();
268
+ const from = this.tabOrder.findIndex(e => e.kind === kind && e.id === id);
269
+ if (from === -1) return false;
270
+
271
+ const [entry] = this.tabOrder.splice(from, 1);
272
+ const pinnedCount = this.tabOrder.filter(e => e.stripPinned).length;
273
+ const lo = entry.stripPinned ? 0 : pinnedCount;
274
+ const hi = entry.stripPinned ? pinnedCount : this.tabOrder.length;
275
+ this.tabOrder.splice(Math.max(lo, Math.min(index, hi)), 0, entry);
276
+
277
+ this._partitionPinned();
278
+ this.renderTabs();
279
+ this.sessionManager._postTabStateToServer();
280
+ return true;
281
+ }
282
+
283
+ /**
284
+ * Adopt the current DOM order of the strip into tabOrder (drag-and-drop
285
+ * commit). Entries are matched by kind+id so session storeIds survive.
286
+ */
287
+ applyDomOrder() {
288
+ const domOrder = [...this.els.tabs.querySelectorAll('.tab')]
289
+ .map(el => ({ kind: el.dataset.type, id: el.dataset.id }));
290
+ const byKey = new Map(this.tabOrder.map(e => [`${e.kind}:${e.id}`, e]));
291
+ const next = domOrder
292
+ .map(x => byKey.get(`${x.kind}:${x.id}`))
293
+ .filter(Boolean);
294
+ // Anything not visible in the DOM (shouldn't happen) keeps its entry at the end
295
+ for (const e of this.tabOrder) {
296
+ if (!next.includes(e)) next.push(e);
297
+ }
298
+ this.tabOrder = next;
299
+ this.renderTabs();
300
+ this.sessionManager._postTabStateToServer();
301
+ }
302
+
303
+ /**
304
+ * Live-reposition a dragged tab element within the strip based on the
305
+ * pointer's X coordinate. Shared by mouse and touch drag paths.
306
+ * @private
307
+ */
308
+ _dragReposition(tabsEl, draggedEl, clientX) {
309
+ // Auto-scroll when dragging near the strip edges
310
+ const stripRect = tabsEl.getBoundingClientRect();
311
+ if (clientX < stripRect.left + 36) tabsEl.scrollLeft -= 12;
312
+ else if (clientX > stripRect.right - 36) tabsEl.scrollLeft += 12;
313
+
314
+ // Insert before the first tab whose midpoint is right of the pointer.
315
+ // Candidates are restricted to the dragged tab's own pinned group, so a
316
+ // drag can't cross the pinned boundary (_partitionPinned would snap it
317
+ // back on the next render, which reads as the drag being ignored).
318
+ const dragPinned = draggedEl.classList.contains('is-pinned');
319
+ const tabs = [...tabsEl.querySelectorAll('.tab')]
320
+ .filter(el => el !== draggedEl
321
+ && el.classList.contains('is-pinned') === dragPinned);
322
+ let target = null;
323
+ for (const el of tabs) {
324
+ const r = el.getBoundingClientRect();
325
+ if (clientX < r.left + r.width / 2) { target = el; break; }
326
+ }
327
+ // Past the last candidate: a pinned tab parks after the last pinned tab
328
+ // (i.e. before the first unpinned one) rather than at the true end.
329
+ if (!target && dragPinned) {
330
+ target = [...tabsEl.querySelectorAll('.tab')]
331
+ .find(el => el !== draggedEl && !el.classList.contains('is-pinned')) || null;
332
+ }
333
+ if (target) {
334
+ if (target.previousElementSibling !== draggedEl) {
335
+ tabsEl.insertBefore(draggedEl, target);
336
+ }
337
+ } else {
338
+ // Past the last tab — the strip now holds only tabs (overflow
339
+ // indicators moved to the viewport overlay), so append to the end.
340
+ if (draggedEl.nextElementSibling !== null) {
341
+ tabsEl.appendChild(draggedEl);
342
+ }
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Strip position of a tab in the unified order (for menu disabled states).
348
+ * canMoveLeft/canMoveRight are group-aware: a tab can only move within its
349
+ * own pinned/unpinned segment, so they go false at the segment edge.
350
+ * @returns {{index: number, count: number, canMoveLeft: boolean, canMoveRight: boolean}}
351
+ */
352
+ getTabPosition(kind, id) {
353
+ this._syncTabOrder();
354
+ const index = this.tabOrder.findIndex(e => e.kind === kind && e.id === id);
355
+ const samePinnedGroup = (i) => index !== -1 && i >= 0 && i < this.tabOrder.length
356
+ && !!this.tabOrder[i].stripPinned === !!this.tabOrder[index].stripPinned;
357
+ return {
358
+ index,
359
+ count: this.tabOrder.length,
360
+ canMoveLeft: samePinnedGroup(index - 1),
361
+ canMoveRight: samePinnedGroup(index + 1),
362
+ };
363
+ }
364
+
365
+ /**
366
+ * Serialize tabOrder for the server payload. Sessions are keyed by
367
+ * storeId (entries without one are skipped — same rule as the session
368
+ * list itself); widget tabs by tab id.
369
+ */
370
+ getOrderForPersistence() {
371
+ this._syncTabOrder();
372
+ return this.tabOrder
373
+ .filter(e => e.kind === 'widget' || e.storeId)
374
+ .map(e => ({
375
+ ...(e.kind === 'widget'
376
+ ? { kind: 'widget', id: e.id }
377
+ : { kind: 'session', storeId: e.storeId }),
378
+ ...(e.stripPinned ? { stripPinned: true } : {}),
379
+ }));
380
+ }
381
+
382
+ /**
383
+ * Apply a server-provided order (v2 tab-state). Session entries carry
384
+ * storeId only — _syncTabOrder remaps them to live client ids.
385
+ *
386
+ * The server order is INCOMPLETE by construction: getOrderForPersistence()
387
+ * skips sessions that have no storeId yet (nothing sent in them, so they
388
+ * don't exist server-side and can't be keyed across a localStorage-loss
389
+ * rebuild). Those entries are spliced back at their local position here —
390
+ * left to _syncTabOrder they would be appended at the END of the strip, so
391
+ * a tab the user had dragged left silently jumped to the far right on the
392
+ * next reload, and Cmd+[ / Cmd+] then cycled through that reshuffled order
393
+ * (the shortcut always follows the strip — it was the strip that moved).
394
+ */
395
+ applyServerOrder(order) {
396
+ if (!Array.isArray(order) || order.length === 0) return;
397
+
398
+ const localOrder = this.tabOrder;
399
+
400
+ // Remember pins we already know about locally. The server order omits
401
+ // sessions that have no storeId yet (getOrderForPersistence skips
402
+ // them), so a freshly-created pinned tab would otherwise lose its pin
403
+ // the moment server state wins. These entries keep their client id
404
+ // across the reload, so kind:id is a valid key.
405
+ const localPins = new Set(localOrder
406
+ .filter(e => e.stripPinned)
407
+ .map(e => `${e.kind}:${e.id}`));
408
+
409
+ this.tabOrder = order
410
+ .filter(e => e && (e.kind === 'widget' ? e.id : e.storeId))
411
+ .map(e => ({
412
+ ...(e.kind === 'widget'
413
+ ? { kind: 'widget', id: e.id }
414
+ : { kind: 'session', id: e.storeId, storeId: e.storeId }),
415
+ ...(e.stripPinned ? { stripPinned: true } : {}),
416
+ }));
417
+
418
+ // Merge the local order back in: walk it once with a cursor into the
419
+ // server-derived array. Entries the server also knows just advance the
420
+ // cursor; entries it doesn't know are spliced AT the cursor, i.e. at
421
+ // their local slot relative to the neighbours that did survive.
422
+ //
423
+ // This deliberately covers widget entries too, not just storeId-less
424
+ // sessions: widget tabs the server order happens to omit would
425
+ // otherwise be appended at the end by _syncTabOrder, which drags any
426
+ // session sitting behind them to the front of the strip.
427
+ //
428
+ // Sessions are matched by storeId (the server's key); a session without
429
+ // one is identity-only, so two storeId-less tabs never collide.
430
+ const keyOf = (e) => e.kind === 'widget'
431
+ ? `w:${e.id}`
432
+ : (e.storeId ? `s:${e.storeId}` : null);
433
+ const locate = (e) => {
434
+ const direct = this.tabOrder.indexOf(e);
435
+ if (direct !== -1) return direct;
436
+ const k = keyOf(e);
437
+ return k ? this.tabOrder.findIndex(x => keyOf(x) === k) : -1;
438
+ };
439
+ const localKeys = new Set(localOrder.map(keyOf).filter(Boolean));
440
+ let cursor = 0;
441
+ for (const entry of localOrder) {
442
+ const idx = locate(entry);
443
+ if (idx !== -1) {
444
+ cursor = idx + 1;
445
+ continue;
446
+ }
447
+ // Never jump in front of a tab the local order has no opinion
448
+ // about (present on the server, absent locally): the server is the
449
+ // only one that knows where it goes, so keep it ahead of us.
450
+ while (cursor < this.tabOrder.length
451
+ && !localKeys.has(keyOf(this.tabOrder[cursor]))) {
452
+ cursor++;
453
+ }
454
+ this.tabOrder.splice(cursor, 0, entry);
455
+ cursor++;
456
+ }
457
+
458
+ this._syncTabOrder();
459
+
460
+ // Re-apply local-only pins to the entries _syncTabOrder just re-inserted.
461
+ if (localPins.size) {
462
+ let restored = false;
463
+ for (const e of this.tabOrder) {
464
+ if (!e.stripPinned && localPins.has(`${e.kind}:${e.id}`)) {
465
+ e.stripPinned = true;
466
+ restored = true;
467
+ }
468
+ }
469
+ if (restored) this._partitionPinned();
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Get current tab index in unified list
475
+ */
476
+ getCurrentTabIndex() {
477
+ const tabs = this.getAllTabs();
478
+ if (this.activeMode === 'widget' && this.activeWidgetTabId) {
479
+ return tabs.findIndex(t => t.type === 'widget' && t.id === this.activeWidgetTabId);
480
+ } else if (this.activeSession) {
481
+ // 'session' and 'welcome' both anchor to a session tab
482
+ return tabs.findIndex(t => t.type === 'session' && t.id === this.activeSession.id);
483
+ }
484
+ return -1;
485
+ }
486
+
487
+ /**
488
+ * Switch to tab by unified index
489
+ */
490
+ switchToTabByIndex(index) {
491
+ const tabs = this.getAllTabs();
492
+ if (index < 0 || index >= tabs.length) return;
493
+ this.activateTab(tabs[index]);
494
+ }
495
+
496
+ /**
497
+ * Activate a {type, id, data} tab descriptor (as returned by getAllTabs()
498
+ * or pickSuccessorTab()). Returns false when there was nothing to activate.
499
+ */
500
+ activateTab(tab) {
501
+ if (!tab?.data) return false;
502
+ if (tab.type === 'session') {
503
+ this.switchToSession(tab.data);
504
+ } else {
505
+ this.switchToWidgetTab(tab.id);
506
+ }
507
+ return true;
508
+ }
509
+
510
+ /**
511
+ * Which tab should take focus when the tab (kind, id) closes?
512
+ *
513
+ * Resolved against the UNIFIED STRIP ORDER (getAllTabs()) — deliberately
514
+ * NOT against sessionManager.sessions / this.widgetTabs. Those two arrays
515
+ * are creation-ordered, so the moment a tab is dragged or pinned their
516
+ * indices stop matching what the user sees, and picking "whatever slid into
517
+ * the closed slot" lands on an arbitrary tab: with any tab pinned, closing
518
+ * the LAST tab jumped to the pinned tab at the far LEFT of the strip. They
519
+ * also can't see each other, so closing a widget tab could never land on an
520
+ * adjacent session tab (and vice versa) even when that's the visual
521
+ * neighbour.
522
+ *
523
+ * Prefers the LEFT neighbour (browser/editor convention — closing the last
524
+ * tab lands on the new last tab), falling back to the right one only when
525
+ * closing the very first tab.
526
+ *
527
+ * MUST be called BEFORE the tab is removed from its backing array.
528
+ * @param {string} kind - 'session' | 'widget'
529
+ * @param {string} id
530
+ * @returns {{type: string, id: string, data: object}|null} null when nothing is left
531
+ */
532
+ pickSuccessorTab(kind, id) {
533
+ const tabs = this.getAllTabs();
534
+ const index = tabs.findIndex(t => t.type === kind && t.id === id);
535
+ if (index === -1) return null;
536
+ return tabs[index - 1] || tabs[index + 1] || null;
537
+ }
538
+
539
+ /**
540
+ * Cycle to next/previous tab
541
+ * @param {number} direction - 1 for next, -1 for previous
542
+ */
543
+ cycleTab(direction) {
544
+ const tabs = this.getAllTabs();
545
+ if (tabs.length === 0) return;
546
+
547
+ const currentIdx = this.getCurrentTabIndex();
548
+ let newIdx;
549
+
550
+ if (currentIdx === -1) {
551
+ newIdx = 0;
552
+ } else {
553
+ newIdx = (currentIdx + direction + tabs.length) % tabs.length;
554
+ }
555
+
556
+ this.switchToTabByIndex(newIdx);
557
+ }
558
+
559
+ // ═══════════════════════════════════════════════════════════════
560
+ // SESSION VIEW SWITCHING
561
+ // ═══════════════════════════════════════════════════════════════
562
+
563
+ /**
564
+ * Switch to session view (conversation)
565
+ */
566
+ switchToSession(session) {
567
+ // Route to welcome up front when the session has no chat content. Avoids
568
+ // a one-frame flash of #session-view before _doSessionSwitch reroutes.
569
+ if (this.ctx._app.shouldShowWelcomeFor(session)) {
570
+ this.switchToWelcome(session);
571
+ // Still enqueue the session switch so _doSessionSwitch runs and
572
+ // performs the rest of the state setup (activeSession, persistence,
573
+ // scroll retargeting, etc.).
574
+ this.ctx._app.switchSession(session);
575
+ return;
576
+ }
577
+
578
+ const wasSessionMode = this.activeMode === 'session';
579
+ const isSameSession = this.activeSession === session;
580
+
581
+ this.activeMode = 'session';
582
+ Storage.set(CONFIG.ACTIVE_MODE_KEY, 'session');
583
+
584
+ // Update view visibility FIRST (before scroll restore)
585
+ // This ensures the container is visible when we restore scroll position
586
+ // (scroll position is lost/ignored when container is display:none)
587
+ this.els.sessionView?.classList.add('active');
588
+ this.els.welcomeView?.classList.remove('active');
589
+ document.getElementById('widget-views')?.classList.remove('active');
590
+
591
+ // Restore session-specific UI
592
+ this.els.inputArea?.classList.remove('hidden');
593
+ this.els.connectionBar?.classList.remove('hidden-by-terminal');
594
+
595
+ // Restore session's floating widgets (hidden when entering widget tab mode)
596
+ WidgetManager.setSessionWidgetsVisible(true);
597
+
598
+ // Delegate session switching to app
599
+ // (handles scroll save for outgoing session, render, and restore for incoming)
600
+ this.ctx._app.switchSession(session);
601
+
602
+ // If returning to the same session from a different mode (welcome /
603
+ // file / widget), app.switchSession early-returns without doing the
604
+ // full switch dance — so renderMessages never runs and the container
605
+ // pool never activates the current session. Without these calls, the
606
+ // previously-visible session's container stays on screen even though
607
+ // activeSession is now this one (the "new session shows other tab's
608
+ // chat" bug from the Cmd+T → pick project flow).
609
+ if (!wasSessionMode && isSameSession) {
610
+ this.ctx._app.renderMessages();
611
+ this.ctx._app.restoreScrollPosition();
612
+ }
613
+
614
+ this.renderTabs();
615
+ }
616
+
617
+ /**
618
+ * View toggle helper for session mode — used by _doSessionSwitch to flip
619
+ * back from welcome without re-running the full switchToSession path
620
+ * (which would re-enqueue _doSessionSwitch).
621
+ */
622
+ _enterSessionView() {
623
+ this.activeMode = 'session';
624
+ Storage.set(CONFIG.ACTIVE_MODE_KEY, 'session');
625
+ this.els.sessionView?.classList.add('active');
626
+ this.els.welcomeView?.classList.remove('active');
627
+ document.getElementById('widget-views')?.classList.remove('active');
628
+ this.els.inputArea?.classList.remove('hidden');
629
+ WidgetManager.setSessionWidgetsVisible(true);
630
+ }
631
+
632
+ /**
633
+ * Switch to welcome view (project picker / session discovery).
634
+ * Symmetric with switchToSession — the session is the "owner" of the
635
+ * welcome state (per-tab welcome containers inside #welcome-view).
636
+ */
637
+ switchToWelcome(session) {
638
+ // Save isUserScrolledUp before leaving session mode (scroll position is
639
+ // natively preserved by the browser on display:none containers).
640
+ if (this.activeMode === 'session' && this.activeSession) {
641
+ this.activeSession.isUserScrolledUp = this.ctx.scrollManager?.isUserScrolledUp ?? false;
642
+ }
643
+
644
+ this.activeMode = 'welcome';
645
+ Storage.set(CONFIG.ACTIVE_MODE_KEY, 'welcome');
646
+
647
+ // Toggle views
648
+ this.els.sessionView?.classList.remove('active');
649
+ document.getElementById('widget-views')?.classList.remove('active');
650
+ this.els.welcomeView?.classList.add('active');
651
+
652
+ // Welcome doesn't need an input area
653
+ this.els.inputArea?.classList.add('hidden');
654
+ this.els.connectionBar?.classList.remove('hidden-by-terminal');
655
+
656
+ // Hide floating session widgets while in welcome
657
+ WidgetManager.setSessionWidgetsVisible(false);
658
+
659
+ // Render per-session welcome container
660
+ this.ctx._app.renderWelcome(session);
661
+
662
+ // Re-target scroll-aware components to the welcome container
663
+ const scrollEl = this.ctx._app.getActiveScrollContainer();
664
+ this.ctx._app.scrollManager?.setContainer(scrollEl);
665
+ this.ctx._app.chatNavigator?.setScrollContainer?.(scrollEl);
666
+
667
+ this.renderTabs();
668
+ }
669
+
670
+ // ═══════════════════════════════════════════════════════════════
671
+ // WIDGET TAB MANAGEMENT
672
+ // ═══════════════════════════════════════════════════════════════
673
+
674
+ /**
675
+ * Initialize widget tab event listeners
676
+ */
677
+ initWidgetTabEvents() {
678
+ // Re-render tabs when favorites change (to show/hide favorite indicator)
679
+ window.addEventListener('welcome:favorites-changed', () => this.renderTabs());
680
+
681
+ // Listen for 'open as tab' requests from widgets
682
+ WidgetBus.on('widget:open-as-tab', ({ widgetId, title, icon, filePath, background }) => {
683
+ if (widgetId === 'terminal') {
684
+ this.openTerminalWidgetTab({ transferFromFloating: true });
685
+ } else if (widgetId === 'file-preview' && filePath) {
686
+ this.openFilePreviewTab(filePath, title, { promoted: true, background });
687
+ } else {
688
+ this.openWidgetAsTab(widgetId, title, icon, { background });
689
+ }
690
+ });
691
+
692
+ // Listen for file-preview navigating to a new file (update tab title/badge)
693
+ WidgetBus.on('widget:file-changed', ({ widgetId, filePath, convertScratch }) => {
694
+ if (widgetId === 'file-preview' && filePath) {
695
+ // Convert scratch tab to file tab on Save As
696
+ if (convertScratch) {
697
+ const scratchTab = this.widgetTabs.find(t => t.isScratch && t.id === this.activeWidgetTabId);
698
+ if (scratchTab) {
699
+ // Clean up scratch localStorage
700
+ if (scratchTab.scratchId) {
701
+ try { localStorage.removeItem(`claude-scratch-${scratchTab.scratchId}`); } catch (e) { /* ignore */ }
702
+ }
703
+ scratchTab.isScratch = false;
704
+ scratchTab.scratchId = null;
705
+ scratchTab.filePath = filePath;
706
+ scratchTab.title = basename(filePath);
707
+ scratchTab.icon = 'file';
708
+ this.renderTabs();
709
+ this.saveWidgetTabs();
710
+ return;
711
+ }
712
+ }
713
+
714
+ // Only update ephemeral preview tabs, not promoted ones
715
+ const tab = this.widgetTabs.find(t => t.widgetId === 'file-preview' && !t.isScratch && t.isPreview);
716
+ if (tab) {
717
+ tab.filePath = filePath;
718
+ tab.title = basename(filePath);
719
+ this.renderTabs();
720
+ this.saveWidgetTabs();
721
+ }
722
+ }
723
+ });
724
+
725
+ // Listen for widget tab close requests
726
+ WidgetBus.on('widget:close-tab', ({ widgetId, keepScratch }) => {
727
+ // Only close ephemeral preview tabs, not promoted ones
728
+ const tab = this.widgetTabs.find(t => t.widgetId === widgetId && !(keepScratch && t.isScratch) && t.isPreview !== false);
729
+ if (tab) {
730
+ this.closeWidgetTab(tab.id);
731
+ }
732
+ });
733
+ }
734
+
735
+ /**
736
+ * Open a new terminal as a widget tab
737
+ * @param {Object} options
738
+ * @param {boolean} options.transferFromFloating - Transfer existing floating terminal
739
+ * @param {string} options.terminalSessionId - Existing terminal session ID (for reconnection)
740
+ * @param {string} options.cwd - Working directory override
741
+ * @param {string} options.title - Tab title override (e.g. "Login")
742
+ * @param {string} options.icon - Tab icon override
743
+ * @param {string} options.initialCommand - Command to type into the PTY once connected (include trailing \n)
744
+ */
745
+ openTerminalWidgetTab(options = {}) {
746
+ const {
747
+ transferFromFloating = false,
748
+ terminalSessionId = null,
749
+ cwd = null,
750
+ title: titleOverride = null,
751
+ icon: iconOverride = null,
752
+ initialCommand = null,
753
+ } = options;
754
+
755
+ const termNum = TerminalWidget.getNextTabNumber();
756
+ const title = titleOverride || `Terminal ${termNum}`;
757
+ const icon = iconOverride || '>_';
758
+ const tabId = `widget-terminal-${Date.now()}`;
759
+
760
+ const tab = {
761
+ id: tabId,
762
+ widgetId: 'terminal',
763
+ title: title,
764
+ icon: icon,
765
+ isTerminal: true,
766
+ terminalSessionId: terminalSessionId // Store for persistence
767
+ };
768
+ this.widgetTabs.push(tab);
769
+
770
+ // Close floating widget if transferring
771
+ if (transferFromFloating) {
772
+ const widget = WidgetManager.get('terminal');
773
+ if (widget) widget.close();
774
+ }
775
+
776
+ // Create container and render
777
+ this.ensureWidgetViewContainer(tabId, 'terminal');
778
+
779
+ const container = document.getElementById(`widget-view-${tabId}`);
780
+ if (container) {
781
+ const config = WidgetManager.configs.get('terminal');
782
+ if (config?.render) {
783
+ config.render(container, {
784
+ sessionId: this.activeSession?.storeId || null,
785
+ cwd: cwd || this.activeSession?.cwd || null,
786
+ isTab: true,
787
+ tabId: tabId,
788
+ transferFromFloating: transferFromFloating,
789
+ terminalSessionId: terminalSessionId, // Pass for PTY reconnection
790
+ initialCommand: initialCommand // One-shot command to type once PTY connects
791
+ });
792
+ }
793
+ }
794
+
795
+ this.switchToWidgetTab(tabId);
796
+ this.renderTabs();
797
+ this.saveWidgetTabs();
798
+
799
+ return tabId;
800
+ }
801
+
802
+ /**
803
+ * Open a scratch editor tab (Ctrl+N)
804
+ */
805
+ openScratchTab() {
806
+ // Auto-increment name based on existing scratch tabs
807
+ const scratchTabs = this.widgetTabs.filter(t => t.isScratch);
808
+ const usedNumbers = scratchTabs.map(t => {
809
+ const m = t.title?.match(/Untitled-(\d+)/);
810
+ return m ? parseInt(m[1], 10) : 0;
811
+ });
812
+ let num = 1;
813
+ while (usedNumbers.includes(num)) num++;
814
+
815
+ const scratchId = `scratch-${Date.now()}`;
816
+ const tabId = `widget-scratch-${Date.now()}`;
817
+ const tab = {
818
+ id: tabId,
819
+ widgetId: 'file-preview',
820
+ title: `Untitled-${num}`,
821
+ icon: 'edit',
822
+ isScratch: true,
823
+ scratchId: scratchId
824
+ };
825
+ this.widgetTabs.push(tab);
826
+
827
+ this.ensureWidgetViewContainer(tabId, 'file-preview');
828
+ this.renderWidgetTabContent(tabId, 'file-preview', {
829
+ isScratch: true,
830
+ scratchId: scratchId,
831
+ scratchName: tab.title
832
+ });
833
+ this.switchToWidgetTab(tabId);
834
+ this.renderTabs();
835
+ this.saveWidgetTabs();
836
+
837
+ return tabId;
838
+ }
839
+
840
+ /**
841
+ * Open file preview as a tab with specific file path
842
+ * @param {string} filePath - The file path to preview
843
+ * @param {string} title - Tab title (defaults to filename)
844
+ * @param {Object} options - Options
845
+ * @param {boolean} options.background - If true, don't switch to the tab
846
+ */
847
+ openFilePreviewTab(filePath, title, options = {}) {
848
+ const { background = false, promoted = false, newTab = false } = options;
849
+ const pinned = promoted || background || newTab;
850
+
851
+ recordRecentOpen(filePath);
852
+
853
+ // Close floating widget if open (always, whether creating or reusing tab)
854
+ const floatingWidget = WidgetManager.get('file-preview');
855
+ if (floatingWidget && floatingWidget.isVisible) floatingWidget.close();
856
+
857
+ // Dedup: if a tab for this exact file already exists, reuse it instead
858
+ // of creating a duplicate. Promote an ephemeral preview tab to pinned
859
+ // if the caller asked for a full tab.
860
+ const existingForPath = this.widgetTabs.find(t =>
861
+ t.widgetId === 'file-preview' && !t.isScratch && t.filePath === filePath
862
+ );
863
+ if (existingForPath) {
864
+ if (pinned && existingForPath.isPreview) existingForPath.isPreview = false;
865
+ if (!background) this.switchToWidgetTab(existingForPath.id);
866
+ this.renderTabs();
867
+ this.saveWidgetTabs();
868
+ return existingForPath.id;
869
+ }
870
+
871
+ // Only reuse the ephemeral preview tab for plain clicks (not promoted/background/newTab)
872
+ if (!pinned) {
873
+ const existing = this.widgetTabs.find(t => t.widgetId === 'file-preview' && !t.isScratch && t.isPreview);
874
+ if (existing) {
875
+ existing.filePath = filePath;
876
+ existing.title = title || basename(filePath);
877
+ this.switchToWidgetTab(existing.id);
878
+ this.renderWidgetTabContent(existing.id, 'file-preview', { filePath });
879
+ this.renderTabs();
880
+ this.saveWidgetTabs();
881
+ return existing.id;
882
+ }
883
+ }
884
+
885
+ const tabId = `widget-file-preview-${Date.now()}`;
886
+ const tab = {
887
+ id: tabId,
888
+ widgetId: 'file-preview',
889
+ title: title || basename(filePath),
890
+ icon: 'file',
891
+ filePath: filePath, // Store file path in tab data
892
+ isPreview: !pinned // Only plain-click tabs are ephemeral/reusable
893
+ };
894
+ this.widgetTabs.push(tab);
895
+
896
+ // Save to localStorage for persistence
897
+ try {
898
+ localStorage.setItem('file-preview-path', filePath);
899
+ } catch (e) { /* ignore */ }
900
+
901
+ this.ensureWidgetViewContainer(tabId, 'file-preview');
902
+ this.renderWidgetTabContent(tabId, 'file-preview', { filePath });
903
+ if (!background) {
904
+ this.switchToWidgetTab(tabId);
905
+ }
906
+ this.renderTabs();
907
+ this.saveWidgetTabs();
908
+
909
+ return tabId;
910
+ }
911
+
912
+ /**
913
+ * Open a widget as a tab
914
+ * @param {string} widgetId
915
+ * @param {string} [title]
916
+ * @param {string} [icon]
917
+ * @param {Object} [options]
918
+ * @param {boolean} [options.background] - If true, create the tab but don't switch to it
919
+ */
920
+ openWidgetAsTab(widgetId, title, icon, options = {}) {
921
+ const { background = false } = options;
922
+ // Check if already open
923
+ const existing = this.widgetTabs.find(t => t.widgetId === widgetId);
924
+ if (existing) {
925
+ if (!background) this.switchToWidgetTab(existing.id);
926
+ return;
927
+ }
928
+
929
+ // Close bottom-sheet widget if open
930
+ const widget = WidgetManager.get(widgetId);
931
+ if (widget) widget.close();
932
+
933
+ const tabId = `widget-${widgetId}-${Date.now()}`;
934
+ const tab = {
935
+ id: tabId,
936
+ widgetId: widgetId,
937
+ title: title || widgetId,
938
+ icon: icon || 'layers'
939
+ };
940
+ this.widgetTabs.push(tab);
941
+
942
+ this.ensureWidgetViewContainer(tabId, widgetId);
943
+ this.renderWidgetTabContent(tabId, widgetId);
944
+ if (!background) this.switchToWidgetTab(tabId);
945
+ this.renderTabs();
946
+ this.saveWidgetTabs();
947
+ }
948
+
949
+ /**
950
+ * Ensure widget view container exists
951
+ */
952
+ ensureWidgetViewContainer(tabId, widgetId) {
953
+ let widgetViews = document.getElementById('widget-views');
954
+ if (!widgetViews) {
955
+ widgetViews = document.createElement('div');
956
+ widgetViews.id = 'widget-views';
957
+ widgetViews.className = 'view';
958
+ document.getElementById('main-content').appendChild(widgetViews);
959
+ }
960
+
961
+ const container = document.createElement('div');
962
+ container.id = `widget-view-${tabId}`;
963
+ container.className = 'widget-tab-content';
964
+ container.dataset.widgetId = widgetId;
965
+ widgetViews.appendChild(container);
966
+
967
+ return container;
968
+ }
969
+
970
+ /**
971
+ * Render widget content into its tab container
972
+ * @param {string} tabId - Tab identifier
973
+ * @param {string} widgetId - Widget identifier
974
+ * @param {Object} options - Additional options to pass to render
975
+ * @param {string} options.filePath - File path (for file-preview)
976
+ */
977
+ renderWidgetTabContent(tabId, widgetId, options = {}) {
978
+ const container = document.getElementById(`widget-view-${tabId}`);
979
+ if (!container) return;
980
+
981
+ const config = WidgetManager.configs.get(widgetId);
982
+ if (config?.render) {
983
+ config.render(container, {
984
+ sessionId: this.activeSession?.storeId || null,
985
+ cwd: this.activeSession?.cwd || null,
986
+ isTab: true,
987
+ tabId: tabId,
988
+ ...options // Pass through additional options like filePath
989
+ });
990
+ }
991
+ }
992
+
993
+ /**
994
+ * Switch to a widget tab
995
+ */
996
+ switchToWidgetTab(tabId) {
997
+ const tab = this.widgetTabs.find(t => t.id === tabId);
998
+ if (!tab) return;
999
+
1000
+ // Save isUserScrolledUp BEFORE hiding session view.
1001
+ // Note: scrollPosition is natively preserved by the browser on display:none
1002
+ // elements (per-tab scroll architecture), so no manual save needed.
1003
+ if (this.activeMode === 'session' && this.activeSession) {
1004
+ this.activeSession.isUserScrolledUp = this.ctx.scrollManager?.isUserScrolledUp ?? false;
1005
+ }
1006
+
1007
+ this.activeWidgetTabId = tabId;
1008
+ this.activeMode = 'widget';
1009
+ Storage.set(CONFIG.ACTIVE_MODE_KEY, 'widget');
1010
+
1011
+ // Notify widget of tab activation (e.g. file-preview swaps per-instance state)
1012
+ WidgetBus.emit('widget:tab-activated', { widgetId: tab.widgetId, tabId });
1013
+
1014
+ // Hide session's floating widgets so they don't overlap the tab content
1015
+ WidgetManager.setSessionWidgetsVisible(false);
1016
+
1017
+ // Hide other views
1018
+ this.els.sessionView?.classList.remove('active');
1019
+ this.els.welcomeView?.classList.remove('active');
1020
+
1021
+ // Show widget views container
1022
+ const widgetViews = document.getElementById('widget-views');
1023
+ if (widgetViews) {
1024
+ widgetViews.classList.add('active');
1025
+ }
1026
+
1027
+ // Show active widget tab content
1028
+ document.querySelectorAll('.widget-tab-content').forEach(el => {
1029
+ el.classList.remove('active');
1030
+ });
1031
+ const container = document.getElementById(`widget-view-${tabId}`);
1032
+ if (container) {
1033
+ container.classList.add('active');
1034
+ }
1035
+
1036
+ // Hide input area and connection bar (!important override prevents async re-show)
1037
+ this.els.inputArea?.classList.add('hidden');
1038
+ this.els.connectionBar?.classList.add('hidden-by-terminal');
1039
+
1040
+ // Focus terminal if applicable
1041
+ if (tab.widgetId === 'terminal' || tab.isTerminal) {
1042
+ setTimeout(() => {
1043
+ const tabState = TerminalWidget.getTabState(tabId);
1044
+ if (tabState?.terminal) {
1045
+ tabState.terminal.focus();
1046
+ TerminalWidget.fit();
1047
+ }
1048
+ }, 50);
1049
+ }
1050
+
1051
+ this.renderTabs();
1052
+ this.saveWidgetTabs();
1053
+ // Flush the active-tab pointer now (saveWidgetTabs' post is 500ms
1054
+ // debounced) — the server's activeTab is the first-choice restore
1055
+ // source on load, same rationale as the session-switch flush.
1056
+ this.sessionManager._postTabStateToServer({ immediate: true });
1057
+ }
1058
+
1059
+ /**
1060
+ * Close a widget tab
1061
+ */
1062
+ async closeWidgetTab(tabId) {
1063
+ let index = this.widgetTabs.findIndex(t => t.id === tabId);
1064
+ if (index === -1) return;
1065
+
1066
+ let tab = this.widgetTabs[index];
1067
+
1068
+ // Warn before closing scratch with content — before any state cleanup,
1069
+ // so declining leaves the tab fully intact
1070
+ if (tab.isScratch && tab.scratchId) {
1071
+ let hasContent = false;
1072
+ try {
1073
+ const raw = localStorage.getItem(`claude-scratch-${tab.scratchId}`);
1074
+ if (raw) {
1075
+ const saved = JSON.parse(raw);
1076
+ hasContent = !!(saved.content && saved.content.trim());
1077
+ }
1078
+ } catch (e) { /* ignore */ }
1079
+ if (hasContent) {
1080
+ const ok = await appConfirm(S.widgets.file_preview.discard_scratch_confirm, { confirmLabel: 'Discard', danger: true });
1081
+ if (!ok) return;
1082
+ // Re-resolve after the async gap — the strip may have changed
1083
+ index = this.widgetTabs.findIndex(t => t.id === tabId);
1084
+ if (index === -1) return;
1085
+ tab = this.widgetTabs[index];
1086
+ }
1087
+ try {
1088
+ localStorage.removeItem(`claude-scratch-${tab.scratchId}`);
1089
+ } catch (e) { /* ignore */ }
1090
+ }
1091
+
1092
+ // Cleanup terminal state
1093
+ if (tab.widgetId === 'terminal' || tab.isTerminal) {
1094
+ TerminalWidget.removeTabState(tabId);
1095
+ }
1096
+
1097
+ // Cleanup file-preview state (editor, etc.)
1098
+ if (tab.widgetId === 'file-preview') {
1099
+ FilePreviewWidget.removeTabState(tabId);
1100
+ }
1101
+
1102
+ // Snapshot reopenable tabs (currently only file-preview — terminals carry
1103
+ // PTY state, scratch content was just confirmed-discarded above).
1104
+ if (tab.widgetId === 'file-preview' && tab.filePath && !tab.isScratch) {
1105
+ this.recentlyClosedTabs.push({
1106
+ type: 'widget',
1107
+ widgetId: tab.widgetId,
1108
+ filePath: tab.filePath,
1109
+ title: tab.title,
1110
+ isPreview: tab.isPreview ?? true,
1111
+ // Strip slot, so reopen lands where it was closed from instead of
1112
+ // appending at the end (creation APIs always append).
1113
+ stripIndex: this.getTabPosition('widget', tabId).index,
1114
+ closedAt: new Date().toISOString(),
1115
+ });
1116
+ if (this.recentlyClosedTabs.length > this._maxRecentlyClosedTabs) {
1117
+ this.recentlyClosedTabs.shift();
1118
+ }
1119
+ }
1120
+
1121
+ // Resolve the successor while the closing tab is still in the strip —
1122
+ // pickSuccessorTab() reads visual order, so it must run before the splice.
1123
+ const wasActive = this.activeWidgetTabId === tabId;
1124
+ const successor = wasActive ? this.pickSuccessorTab('widget', tabId) : null;
1125
+
1126
+ this.widgetTabs.splice(index, 1);
1127
+
1128
+ // Remove container
1129
+ document.getElementById(`widget-view-${tabId}`)?.remove();
1130
+
1131
+ // Hand focus to the strip's left neighbour (may be a session tab)
1132
+ if (wasActive) {
1133
+ if (successor) {
1134
+ // Drop the dead id first: if the successor is a session tab,
1135
+ // switchToSession leaves activeWidgetTabId alone and a stale one
1136
+ // would keep matching in renderTabs/getCurrentTabIndex.
1137
+ this.activeWidgetTabId = null;
1138
+ this.activateTab(successor);
1139
+ } else {
1140
+ this.activeWidgetTabId = null;
1141
+ this.activeMode = 'session';
1142
+ Storage.set(CONFIG.ACTIVE_MODE_KEY, 'session');
1143
+ this.els.sessionView?.classList.add('active');
1144
+ this.els.welcomeView?.classList.remove('active');
1145
+ document.getElementById('widget-views')?.classList.remove('active');
1146
+ this.els.inputArea?.classList.remove('hidden');
1147
+ this.els.connectionBar?.classList.remove('hidden-by-terminal');
1148
+ // Restore scroll position for active session
1149
+ this.ctx._app.restoreScrollPosition();
1150
+ }
1151
+ }
1152
+
1153
+ this.renderTabs();
1154
+ this.saveWidgetTabs();
1155
+ }
1156
+
1157
+ // ═══════════════════════════════════════════════════════════════
1158
+ // WIDGET TAB PERSISTENCE
1159
+ // ═══════════════════════════════════════════════════════════════
1160
+
1161
+ /**
1162
+ * Serialize widget tabs for persistence (localStorage + server payload).
1163
+ */
1164
+ serializeWidgetTabs() {
1165
+ return this.widgetTabs.map(t => {
1166
+ const tabData = {
1167
+ id: t.id,
1168
+ widgetId: t.widgetId,
1169
+ title: t.title,
1170
+ icon: t.icon,
1171
+ isTerminal: t.isTerminal || false
1172
+ };
1173
+ // For terminals, save the sessionId to enable reconnection to existing PTY
1174
+ if (t.isTerminal) {
1175
+ const termState = TerminalWidget.getTabState(t.id);
1176
+ if (termState?.sessionId) {
1177
+ tabData.terminalSessionId = termState.sessionId;
1178
+ }
1179
+ }
1180
+ // For scratch tabs, save scratch metadata
1181
+ if (t.isScratch) {
1182
+ tabData.isScratch = true;
1183
+ tabData.scratchId = t.scratchId;
1184
+ }
1185
+ // For file-preview tabs, save the current file path and preview state
1186
+ // Use tab's stored filePath first, then localStorage as fallback
1187
+ if (t.widgetId === 'file-preview' && !t.isScratch) {
1188
+ const savedPath = t.filePath || localStorage.getItem('file-preview-path');
1189
+ if (savedPath) {
1190
+ tabData.filePath = savedPath;
1191
+ }
1192
+ tabData.isPreview = t.isPreview ?? true;
1193
+ }
1194
+ return tabData;
1195
+ });
1196
+ }
1197
+
1198
+ /**
1199
+ * Save widget tabs to localStorage and mirror to the server
1200
+ * (same iPadOS write-loss protection as session tabs).
1201
+ */
1202
+ saveWidgetTabs() {
1203
+ debug.log('[TabController] saveWidgetTabs called, tabs:', this.widgetTabs.map(t => t.id));
1204
+ const data = {
1205
+ tabs: this.serializeWidgetTabs(),
1206
+ activeTabId: this.activeWidgetTabId
1207
+ };
1208
+ Storage.set(CONFIG.WIDGET_TABS_KEY, data);
1209
+ this._saveTabOrder();
1210
+ this.sessionManager._postTabStateToServer();
1211
+ }
1212
+
1213
+ /**
1214
+ * Restore widget tabs — from server state when available (server wins,
1215
+ * matching session reconciliation), else from localStorage.
1216
+ * @param {Object} [serverState] - v2 /api/app/tabs response
1217
+ * @returns {boolean} True if widget tabs were restored
1218
+ */
1219
+ restoreWidgetTabs(serverState = null) {
1220
+ let saved;
1221
+ if (serverState && Array.isArray(serverState.widgetTabs)) {
1222
+ // Server has a v2 record (key present) — it is the source of truth,
1223
+ // even when empty (widget tabs may have been closed on another device).
1224
+ saved = {
1225
+ tabs: serverState.widgetTabs,
1226
+ activeTabId: serverState.activeTab?.kind === 'widget' ? serverState.activeTab.id : null,
1227
+ };
1228
+ debug.log('[TabController] restoreWidgetTabs from server:', saved.tabs.length, 'tabs');
1229
+ } else {
1230
+ saved = Storage.get(CONFIG.WIDGET_TABS_KEY);
1231
+ debug.log('[TabController] restoreWidgetTabs from localStorage:', saved);
1232
+ }
1233
+ // From here on widget tabs are live (or there are none), so
1234
+ // _syncTabOrder may prune widget entries again — see the constructor.
1235
+ this._widgetTabsRestored = true;
1236
+ if (!saved?.tabs?.length) return false;
1237
+
1238
+ for (const tabData of saved.tabs) {
1239
+ // Skip removed widget types
1240
+ if (tabData.widgetId === 'file-editor') continue;
1241
+ // Skip file-browser tabs (mode removed 2026-04-19)
1242
+ if (tabData.widgetId === 'file-explorer' && tabData.isFileBrowser) continue;
1243
+
1244
+ // Recreate the tab
1245
+ const tab = {
1246
+ id: tabData.id,
1247
+ widgetId: tabData.widgetId,
1248
+ title: tabData.title,
1249
+ icon: tabData.icon,
1250
+ isTerminal: tabData.isTerminal,
1251
+ terminalSessionId: tabData.terminalSessionId || null,
1252
+ filePath: tabData.filePath || null,
1253
+ isPreview: tabData.isPreview ?? true,
1254
+ isScratch: tabData.isScratch || false,
1255
+ scratchId: tabData.scratchId || null
1256
+ };
1257
+ this.widgetTabs.push(tab);
1258
+
1259
+ // Create container
1260
+ this.ensureWidgetViewContainer(tab.id, tab.widgetId);
1261
+
1262
+ // For file-preview tabs, ensure the path is in localStorage before rendering
1263
+ if (tab.widgetId === 'file-preview' && tab.filePath) {
1264
+ try {
1265
+ localStorage.setItem('file-preview-path', tab.filePath);
1266
+ } catch (e) { /* ignore */ }
1267
+ }
1268
+
1269
+ // Render widget content
1270
+ const container = document.getElementById(`widget-view-${tab.id}`);
1271
+ if (container) {
1272
+ const config = WidgetManager.configs.get(tab.widgetId);
1273
+ if (config?.render) {
1274
+ const renderCtx = {
1275
+ sessionId: this.activeSession?.storeId || null,
1276
+ cwd: this.activeSession?.cwd || null,
1277
+ isTab: true,
1278
+ tabId: tab.id,
1279
+ // Pass terminal sessionId for PTY reconnection
1280
+ terminalSessionId: tab.terminalSessionId,
1281
+ // Pass file path for file-preview restoration
1282
+ filePath: tab.filePath
1283
+ };
1284
+ // Pass scratch context for scratch tab restoration
1285
+ if (tab.isScratch) {
1286
+ renderCtx.isScratch = true;
1287
+ renderCtx.scratchId = tab.scratchId;
1288
+ renderCtx.scratchName = tab.title;
1289
+ }
1290
+ config.render(container, renderCtx);
1291
+ }
1292
+ }
1293
+ }
1294
+
1295
+ // Restore active tab ID (don't switch yet - caller will handle that)
1296
+ if (saved.activeTabId && this.widgetTabs.find(t => t.id === saved.activeTabId)) {
1297
+ this.activeWidgetTabId = saved.activeTabId;
1298
+ } else if (this.widgetTabs.length > 0) {
1299
+ this.activeWidgetTabId = this.widgetTabs[0].id;
1300
+ }
1301
+
1302
+ // Save cleaned-up state (removes skipped/removed widget tabs)
1303
+ if (this.widgetTabs.length !== saved.tabs.length) {
1304
+ this.saveWidgetTabs();
1305
+ }
1306
+
1307
+ return this.widgetTabs.length > 0;
1308
+ }
1309
+
1310
+
1311
+ // ═══════════════════════════════════════════════════════════════
1312
+ // TAB RENDERING
1313
+ // ═══════════════════════════════════════════════════════════════
1314
+
1315
+ /**
1316
+ * Scroll the active tab into view (centered if possible)
1317
+ */
1318
+ scrollActiveTabIntoView() {
1319
+ const tabsContainer = this.els.tabs;
1320
+ const activeTab = tabsContainer?.querySelector('.tab.active');
1321
+ if (!activeTab || !tabsContainer) return;
1322
+
1323
+ // Get the tab's position relative to the scrollable container
1324
+ const containerRect = tabsContainer.getBoundingClientRect();
1325
+ const tabRect = activeTab.getBoundingClientRect();
1326
+
1327
+ // Calculate visible bounds (the tab's position relative to container's viewport)
1328
+ const tabLeftRelative = tabRect.left - containerRect.left + tabsContainer.scrollLeft;
1329
+ const tabRightRelative = tabLeftRelative + tabRect.width;
1330
+ const visibleLeft = tabsContainer.scrollLeft;
1331
+ const visibleRight = tabsContainer.scrollLeft + tabsContainer.clientWidth;
1332
+
1333
+ // Check if tab is fully visible
1334
+ if (tabLeftRelative >= visibleLeft && tabRightRelative <= visibleRight) {
1335
+ return; // Already visible
1336
+ }
1337
+
1338
+ // Calculate scroll position to center the tab
1339
+ const tabCenterRelative = tabLeftRelative + tabRect.width / 2;
1340
+ const targetScroll = tabCenterRelative - tabsContainer.clientWidth / 2;
1341
+
1342
+ // Clamp to valid scroll range
1343
+ const maxScroll = tabsContainer.scrollWidth - tabsContainer.clientWidth;
1344
+ const clampedScroll = Math.max(0, Math.min(targetScroll, maxScroll));
1345
+
1346
+ tabsContainer.scrollTo({
1347
+ left: clampedScroll,
1348
+ behavior: 'smooth'
1349
+ });
1350
+ }
1351
+
1352
+ /**
1353
+ * Open the all-sessions grid switcher (iPad-style card grid).
1354
+ * Triggered by the desktop header button, the mobile rail-drawer button,
1355
+ * or the Alt+Tab shortcut.
1356
+ */
1357
+ toggleTabsOverview() {
1358
+ this.ctx._app?.toggleGridSwitcher?.();
1359
+ }
1360
+
1361
+ /**
1362
+ * Pin affordance for a tab: the `is-pinned` root class plus a clickable
1363
+ * pin glyph that unpins. Rendered for both session and widget tabs so the
1364
+ * whole strip behaves the same.
1365
+ * @returns {{cls: string, btn: string}}
1366
+ * @private
1367
+ */
1368
+ _pinDecor(kind, id) {
1369
+ if (!this.isTabPinned(kind, id)) return { cls: '', btn: '' };
1370
+ return {
1371
+ cls: ' is-pinned',
1372
+ btn: `<span class="tab-pin-btn" data-unpin="${id}" data-unpin-kind="${kind}"`
1373
+ + ` data-tooltip="${escapeHtml(S.context_menus.tab.unpin_hint)}">`
1374
+ + `${ICONS.pin || ''}</span>`,
1375
+ };
1376
+ }
1377
+
1378
+ /**
1379
+ * Render a single session tab
1380
+ * @private
1381
+ */
1382
+ _renderSessionTab(session) {
1383
+ const isActive = (this.activeMode === 'session' || this.activeMode === 'welcome')
1384
+ && session === this.activeSession;
1385
+ // Show name (truncated if long)
1386
+ const displayName = session.name.length > 30
1387
+ ? session.name.slice(0, 30) + '...'
1388
+ : session.name;
1389
+ // Tooltip shows full name + cwd (relative with ~)
1390
+ const cwdShort = session.cwd?.replace(/^\/home\/[^/]+\//, '~/') || session.cwd;
1391
+ const tooltip = `${session.name} - ${cwdShort}`;
1392
+ // Process status: running-claude, running-shadowgit, or empty
1393
+ const processStatus = session.processStatusClass || '';
1394
+ // Pending question indicator
1395
+ const hasPendingQuestion = session.hasPendingQuestion;
1396
+ const pendingType = session.pendingQuestionType;
1397
+ const badgeClass = pendingType === 'plan_approval' ? 'plan-badge'
1398
+ : pendingType === 'permission' ? 'permission-badge' : '';
1399
+ const badgeTooltip = pendingType === 'plan_approval' ? S.tab_badges.plan
1400
+ : pendingType === 'permission' ? S.tab_badges.permission : S.tab_badges.question;
1401
+ const badgeGlyph = pendingType === 'permission' ? '!' : '?';
1402
+ const isFav = session.storeId && isFavoriteSession(session.storeId);
1403
+ const isWorktree = session.isWorktree;
1404
+ const wtSubtitle = isWorktree ? `<span class="wt-tab-subtitle">${escapeHtml(session.worktreeName || '')}</span>` : '';
1405
+ const pin = this._pinDecor('session', session.id);
1406
+ return `
1407
+ <div class="tab tab-session ${isActive ? 'active' : ''} ${session.unread ? 'unread' : ''} ${hasPendingQuestion ? 'has-question' : ''} ${isFav ? 'is-favorite' : ''} ${isWorktree ? 'is-worktree' : ''}${pin.cls}"
1408
+ data-type="session" data-id="${session.id}" data-tooltip="${escapeHtml(tooltip)}"${projectColorStyle(session.cwd)}>
1409
+ <span class="status-dot ${processStatus}"></span>
1410
+ <span class="tab-name">${escapeHtml(displayName)}${wtSubtitle}</span>
1411
+ ${hasPendingQuestion ? `<span class="question-badge ${badgeClass}" data-tooltip="${escapeHtml(badgeTooltip)}">${badgeGlyph}</span>` : ''}
1412
+ <span class="unread-dot"></span>
1413
+ ${pin.btn}
1414
+ <span class="close-btn" data-close="${session.id}">
1415
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1416
+ <path d="M18 6L6 18M6 6l12 12"/>
1417
+ </svg>
1418
+ </span>
1419
+ </div>
1420
+ `;
1421
+ }
1422
+
1423
+ /**
1424
+ * Render a single widget tab
1425
+ * @private
1426
+ */
1427
+ _renderWidgetTab(tab) {
1428
+ const isActive = this.activeMode === 'widget' && tab.id === this.activeWidgetTabId;
1429
+ const pin = this._pinDecor('widget', tab.id);
1430
+
1431
+ // Scratch tabs get pencil icon and italic name
1432
+ if (tab.isScratch) {
1433
+ const iconSvg = ICONS.edit || '';
1434
+ return `
1435
+ <div class="tab tab-widget tab-scratch ${isActive ? 'active' : ''}${pin.cls}"
1436
+ data-type="widget" data-id="${tab.id}" data-tooltip="Scratch editor">
1437
+ <span class="file-icon widget-icon">${iconSvg}</span>
1438
+ <span class="tab-name">${escapeHtml(tab.title)}</span>
1439
+ ${pin.btn}
1440
+ <span class="close-btn" data-close="${tab.id}">
1441
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1442
+ <path d="M18 6L6 18M6 6l12 12"/>
1443
+ </svg>
1444
+ </span>
1445
+ </div>
1446
+ `;
1447
+ }
1448
+
1449
+ // File-preview tabs get language badge like editor tabs
1450
+ if (tab.widgetId === 'file-preview' && tab.filePath) {
1451
+ const lang = detectLanguage(tab.filePath);
1452
+ const icon = getLanguageIcon(lang);
1453
+ const fileName = basename(tab.filePath);
1454
+ return `
1455
+ <div class="tab tab-file ${isActive ? 'active' : ''}${pin.cls}"
1456
+ data-type="widget" data-id="${tab.id}" data-tooltip="${escapeHtml(tab.filePath)}">
1457
+ <span class="file-icon">${escapeHtml(icon)}</span>
1458
+ <span class="tab-name">${escapeHtml(fileName)}</span>
1459
+ ${pin.btn}
1460
+ <span class="close-btn" data-close="${tab.id}">
1461
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1462
+ <path d="M18 6L6 18M6 6l12 12"/>
1463
+ </svg>
1464
+ </span>
1465
+ </div>
1466
+ `;
1467
+ }
1468
+
1469
+ const iconSvg = ICONS[tab.icon] || ICONS.layers || '';
1470
+ return `
1471
+ <div class="tab tab-widget ${isActive ? 'active' : ''}${pin.cls}"
1472
+ data-type="widget" data-id="${tab.id}" data-tooltip="${escapeHtml(tab.title)}">
1473
+ <span class="file-icon widget-icon">${iconSvg}</span>
1474
+ <span class="tab-name">${escapeHtml(tab.title)}</span>
1475
+ ${pin.btn}
1476
+ <span class="close-btn" data-close="${tab.id}">
1477
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1478
+ <path d="M18 6L6 18M6 6l12 12"/>
1479
+ </svg>
1480
+ </span>
1481
+ </div>
1482
+ `;
1483
+ }
1484
+
1485
+ /**
1486
+ * Render all tabs (sessions + files + widgets) in unified strip order
1487
+ */
1488
+ renderTabs() {
1489
+ const tabsHtml = this.getAllTabs().map(t => {
1490
+ if (!t.data) return '';
1491
+ return t.type === 'session'
1492
+ ? this._renderSessionTab(t.data)
1493
+ : this._renderWidgetTab(t.data);
1494
+ }).join('');
1495
+
1496
+ this._saveTabOrder();
1497
+
1498
+ // Only the tabs live inside the scroll strip. The overflow indicators
1499
+ // are static overlays in .tabs-viewport (a sibling of #tabs) — they are
1500
+ // NOT re-created here, so rebuilding #tabs never disturbs them and
1501
+ // toggling them never changes this strip's scrollWidth.
1502
+ this.els.tabs.innerHTML = tabsHtml;
1503
+
1504
+ // Install delegated event handlers ONCE on the tabs container
1505
+ // (survives innerHTML replacement — no per-element listeners needed)
1506
+ this._installTabDelegation();
1507
+
1508
+ // Scroll active tab into view (after DOM is updated and layout computed)
1509
+ // Double-rAF ensures layout is complete, especially on initial page load.
1510
+ // The overlays don't affect layout, so update order vs. scroll is moot.
1511
+ requestAnimationFrame(() => {
1512
+ requestAnimationFrame(() => {
1513
+ this.updateOverflowIndicator();
1514
+ this.scrollActiveTabIntoView();
1515
+ });
1516
+ });
1517
+ }
1518
+
1519
+ /**
1520
+ * Install delegated event handlers on the tabs container (once only).
1521
+ * All tab click, touch, and overflow events are handled via event delegation
1522
+ * so renderTabs() can safely replace innerHTML without leaking listeners.
1523
+ * @private
1524
+ */
1525
+ _installTabDelegation() {
1526
+ if (this._tabDelegationInstalled) return;
1527
+ this._tabDelegationInstalled = true;
1528
+
1529
+ const tabsEl = this.els.tabs;
1530
+
1531
+ // Header overview button (lives in <header>, not inside #tabs)
1532
+ const headerOverviewBtn = document.querySelector('.header-overview-btn');
1533
+ if (headerOverviewBtn) {
1534
+ headerOverviewBtn.addEventListener('click', (e) => {
1535
+ e.stopPropagation();
1536
+ this.toggleTabsOverview(headerOverviewBtn);
1537
+ });
1538
+ }
1539
+
1540
+ // Overflow indicators (overlay siblings in .tabs-viewport, not inside
1541
+ // #tabs — so their clicks are wired directly, not via #tabs delegation).
1542
+ const viewport = this.els.tabsViewport || tabsEl.parentElement;
1543
+ viewport?.querySelector('.tabs-overflow-left')?.addEventListener('click', (e) => {
1544
+ e.stopPropagation();
1545
+ tabsEl.scrollBy({ left: -tabsEl.clientWidth * 0.8, behavior: 'smooth' });
1546
+ });
1547
+ viewport?.querySelector('.tabs-overflow-right')?.addEventListener('click', (e) => {
1548
+ e.stopPropagation();
1549
+ tabsEl.scrollBy({ left: tabsEl.clientWidth * 0.8, behavior: 'smooth' });
1550
+ });
1551
+
1552
+ // ── Click delegation ──
1553
+ tabsEl.addEventListener('click', (e) => {
1554
+ // Swallow the click that trails a completed drag-reorder. The
1555
+ // browser dispatches it within a few ms of pointerup, so the
1556
+ // window is short — a deliberate follow-up click must not be eaten.
1557
+ if (this._suppressClickUntil) {
1558
+ const trailing = Date.now() < this._suppressClickUntil;
1559
+ this._suppressClickUntil = 0;
1560
+ if (trailing) {
1561
+ e.stopPropagation();
1562
+ return;
1563
+ }
1564
+ }
1565
+
1566
+ // Tab click
1567
+ const tabEl = e.target.closest('.tab');
1568
+ if (!tabEl) return;
1569
+
1570
+ const tabType = tabEl.dataset.type;
1571
+ const tabId = tabEl.dataset.id;
1572
+
1573
+ const unpinBtn = e.target.closest('.tab-pin-btn');
1574
+ if (unpinBtn) {
1575
+ // Clicking the pin glyph unpins, without activating the tab.
1576
+ e.stopPropagation();
1577
+ this.toggleTabPin(unpinBtn.dataset.unpinKind, unpinBtn.dataset.unpin, false);
1578
+ return;
1579
+ }
1580
+
1581
+ if (e.target.closest('.close-btn')) {
1582
+ const closeId = e.target.closest('.close-btn').dataset.close;
1583
+ if (tabType === 'session') {
1584
+ const session = this.sessionManager.get(closeId);
1585
+ if (session) this.ctx._app.closeSession(session);
1586
+ } else if (tabType === 'widget') {
1587
+ this.closeWidgetTab(closeId);
1588
+ }
1589
+ } else {
1590
+ if (tabType === 'session') {
1591
+ const session = this.sessionManager.get(tabId);
1592
+ if (session) this.switchToSession(session);
1593
+ } else if (tabType === 'widget') {
1594
+ this.switchToWidgetTab(tabId);
1595
+ }
1596
+ }
1597
+ });
1598
+
1599
+ // ── Drag-to-reorder (mouse / trackpad) ──
1600
+ this._installMouseDrag(tabsEl);
1601
+
1602
+ // ── Long-press delegation (touch devices) ──
1603
+ // Hold 400ms to "pick up" the tab. Then: drag horizontally to
1604
+ // reorder, or release without moving to open the context menu.
1605
+ let pressTimer = null;
1606
+ let clickBlocker = null;
1607
+ let touchTab = null;
1608
+ let touchArmed = false; // long-press fired — tab picked up
1609
+ let touchDragged = false; // armed + moved — reordering
1610
+ let touchStartX = 0;
1611
+
1612
+ const removeClickBlocker = () => {
1613
+ if (clickBlocker) {
1614
+ document.removeEventListener('click', clickBlocker, { capture: true });
1615
+ clickBlocker = null;
1616
+ }
1617
+ };
1618
+
1619
+ const installClickBlocker = () => {
1620
+ clickBlocker = (evt) => {
1621
+ evt.preventDefault();
1622
+ evt.stopPropagation();
1623
+ evt.stopImmediatePropagation();
1624
+ // Auto-remove after one use to prevent leaks
1625
+ removeClickBlocker();
1626
+ };
1627
+ document.addEventListener('click', clickBlocker, { capture: true, once: true });
1628
+ };
1629
+
1630
+ const resetTouchDrag = () => {
1631
+ if (pressTimer) {
1632
+ clearTimeout(pressTimer);
1633
+ pressTimer = null;
1634
+ }
1635
+ touchTab?.classList.remove('dragging');
1636
+ touchTab = null;
1637
+ touchArmed = false;
1638
+ touchDragged = false;
1639
+ };
1640
+
1641
+ tabsEl.addEventListener('touchstart', (e) => {
1642
+ const tabEl = e.target.closest('.tab');
1643
+ if (!tabEl) return;
1644
+
1645
+ // Clean up any existing blocker from previous interaction
1646
+ removeClickBlocker();
1647
+ touchTab = tabEl;
1648
+ touchArmed = false;
1649
+ touchDragged = false;
1650
+ touchStartX = e.touches[0].clientX;
1651
+
1652
+ pressTimer = setTimeout(() => {
1653
+ pressTimer = null;
1654
+ touchArmed = true;
1655
+ tabEl.classList.add('dragging');
1656
+ }, 400);
1657
+ }, { passive: true });
1658
+
1659
+ tabsEl.addEventListener('touchmove', (e) => {
1660
+ if (touchArmed && touchTab) {
1661
+ // Picked up — reorder instead of scrolling the strip
1662
+ e.preventDefault();
1663
+ touchDragged = true;
1664
+ this._dragReposition(tabsEl, touchTab, e.touches[0].clientX);
1665
+ return;
1666
+ }
1667
+ // Moving before the long-press fires = scroll; cancel the pick-up
1668
+ if (pressTimer) {
1669
+ clearTimeout(pressTimer);
1670
+ pressTimer = null;
1671
+ }
1672
+ }, { passive: false });
1673
+
1674
+ tabsEl.addEventListener('touchend', (e) => {
1675
+ const tabEl = touchTab;
1676
+ const wasArmed = touchArmed;
1677
+ const wasDragged = touchDragged;
1678
+ resetTouchDrag();
1679
+ if (!tabEl || !wasArmed) return;
1680
+
1681
+ // Swallow the synthetic click that follows the long-press
1682
+ e.preventDefault();
1683
+ e.stopPropagation();
1684
+ installClickBlocker();
1685
+ setTimeout(removeClickBlocker, 400);
1686
+
1687
+ if (wasDragged) {
1688
+ // Trailing synthetic click is covered by preventDefault + the
1689
+ // one-shot click blocker above
1690
+ this.applyDomOrder();
1691
+ } else {
1692
+ // Long-press without movement — context menu
1693
+ const rect = tabEl.getBoundingClientRect();
1694
+ const items = this.ctx._app.buildTabContextMenu(tabEl);
1695
+ if (items.length > 0) {
1696
+ this.ctx._app.contextMenu.show(touchStartX, rect.bottom + 4, items);
1697
+ }
1698
+ }
1699
+ }, { passive: false });
1700
+
1701
+ tabsEl.addEventListener('touchcancel', () => {
1702
+ resetTouchDrag();
1703
+ }, { passive: true });
1704
+
1705
+ // ── Scroll listener for overflow indicator ──
1706
+ tabsEl.addEventListener('scroll', () => {
1707
+ this.updateOverflowIndicator();
1708
+ });
1709
+ }
1710
+
1711
+ /**
1712
+ * Install pointer-based drag-to-reorder for mouse/trackpad (touch has its
1713
+ * own long-press path). A small threshold distinguishes drag from click;
1714
+ * the trailing click is suppressed via _suppressClickUntil.
1715
+ * @private
1716
+ */
1717
+ _installMouseDrag(tabsEl) {
1718
+ let candidate = null;
1719
+ let dragging = false;
1720
+ let startX = 0;
1721
+ let startY = 0;
1722
+
1723
+ const onMove = (e) => {
1724
+ if (!candidate) return;
1725
+ if (!dragging) {
1726
+ if (Math.abs(e.clientX - startX) < 6 && Math.abs(e.clientY - startY) < 6) return;
1727
+ dragging = true;
1728
+ candidate.classList.add('dragging');
1729
+ tabsEl.classList.add('tabs-drag-active');
1730
+ }
1731
+ this._dragReposition(tabsEl, candidate, e.clientX);
1732
+ };
1733
+
1734
+ const onUp = () => {
1735
+ document.removeEventListener('pointermove', onMove);
1736
+ document.removeEventListener('pointerup', onUp);
1737
+ document.removeEventListener('pointercancel', onUp);
1738
+ if (dragging && candidate) {
1739
+ candidate.classList.remove('dragging');
1740
+ tabsEl.classList.remove('tabs-drag-active');
1741
+ this._suppressClickUntil = Date.now() + 150;
1742
+ this.applyDomOrder();
1743
+ }
1744
+ candidate = null;
1745
+ dragging = false;
1746
+ };
1747
+
1748
+ tabsEl.addEventListener('pointerdown', (e) => {
1749
+ // Touch is handled by the long-press path; ignore non-primary buttons
1750
+ if (e.pointerType === 'touch' || e.button !== 0) return;
1751
+ const tabEl = e.target.closest('.tab');
1752
+ if (!tabEl || e.target.closest('.close-btn')) return;
1753
+ candidate = tabEl;
1754
+ dragging = false;
1755
+ startX = e.clientX;
1756
+ startY = e.clientY;
1757
+ document.addEventListener('pointermove', onMove);
1758
+ document.addEventListener('pointerup', onUp);
1759
+ document.addEventListener('pointercancel', onUp);
1760
+ });
1761
+ }
1762
+
1763
+ /**
1764
+ * Update the overflow indicators showing count of hidden tabs on each side
1765
+ */
1766
+ updateOverflowIndicator() {
1767
+ const tabsContainer = this.els.tabs;
1768
+ if (!tabsContainer) return;
1769
+ // Indicators are overlay siblings in .tabs-viewport, not children of #tabs.
1770
+ const viewport = this.els.tabsViewport || tabsContainer.parentElement;
1771
+ const leftInd = viewport?.querySelector('.tabs-overflow-left');
1772
+ const rightInd = viewport?.querySelector('.tabs-overflow-right');
1773
+ if (!leftInd && !rightInd) return;
1774
+
1775
+ // Get all tab elements (not the overview button or separators)
1776
+ const tabs = tabsContainer.querySelectorAll('.tab');
1777
+
1778
+ // Short-circuit: if there's no actual overflow (or no tabs), hide both
1779
+ // indicators. Required because #tabs is now `flex: 0 1 auto` and often
1780
+ // sizes exactly to content — otherwise the per-tab measurement below
1781
+ // can flag tabs as hidden purely from sub-pixel/coordinate drift.
1782
+ const hasOverflow = tabsContainer.scrollWidth - tabsContainer.clientWidth > 1;
1783
+ if (tabs.length === 0 || !hasOverflow) {
1784
+ if (leftInd) leftInd.style.display = 'none';
1785
+ if (rightInd) rightInd.style.display = 'none';
1786
+ return;
1787
+ }
1788
+
1789
+ // Count tabs hidden on each side (20px tolerance for partial visibility).
1790
+ // Use getBoundingClientRect() — viewport coords work regardless of which
1791
+ // ancestor is `offsetParent` (#tabs is position:static so offsetLeft is
1792
+ // measured from <body>, which broke the comparison previously).
1793
+ const containerRect = tabsContainer.getBoundingClientRect();
1794
+ let hiddenLeft = 0;
1795
+ let hiddenRight = 0;
1796
+ tabs.forEach(tab => {
1797
+ const r = tab.getBoundingClientRect();
1798
+ if (r.right < containerRect.left + 20) hiddenLeft++;
1799
+ if (r.left > containerRect.right - 20) hiddenRight++;
1800
+ });
1801
+
1802
+ if (leftInd) {
1803
+ if (hiddenLeft > 0) {
1804
+ leftInd.textContent = `+${hiddenLeft}`;
1805
+ leftInd.style.display = 'flex';
1806
+ } else {
1807
+ leftInd.style.display = 'none';
1808
+ }
1809
+ }
1810
+ if (rightInd) {
1811
+ if (hiddenRight > 0) {
1812
+ rightInd.textContent = `+${hiddenRight}`;
1813
+ rightInd.style.display = 'flex';
1814
+ } else {
1815
+ rightInd.style.display = 'none';
1816
+ }
1817
+ }
1818
+ }
1819
+
1820
+ /**
1821
+ * Close active tab (for keyboard shortcut)
1822
+ */
1823
+ closeActiveTab() {
1824
+ if (this.activeMode === 'widget' && this.activeWidgetTabId) {
1825
+ this.closeWidgetTab(this.activeWidgetTabId);
1826
+ }
1827
+ }
1828
+ }