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,1184 @@
1
+ /**
2
+ * Status Bar Module
3
+ * Manages connection status, token display, and typing indicator
4
+ */
5
+
6
+ import { CONFIG } from './config.js';
7
+ import S from './strings.js';
8
+ import { showToast } from './context-menu.js';
9
+
10
+ // Models loaded from server (GET /api/app/models)
11
+ let MODELS = [];
12
+ let SUMMARY_MODEL_ID = '';
13
+ let _modelsLoaded = false;
14
+
15
+ // Engine registry loaded from server (GET /api/providers):
16
+ // { providers: [describe()...], default: name, default_pinned_by_flag: bool }
17
+ let PROVIDERS_INFO = null;
18
+ let _providersLoaded = false;
19
+
20
+ async function ensureProvidersLoaded() {
21
+ if (_providersLoaded) return;
22
+ try {
23
+ const resp = await fetch(`${CONFIG.API_BASE}/api/providers`);
24
+ if (resp.ok) {
25
+ PROVIDERS_INFO = await resp.json();
26
+ _providersLoaded = true;
27
+ }
28
+ } catch (e) { /* silent — chip stays hidden */ }
29
+ }
30
+
31
+ /** Call when the default engine changes so the next popup re-fetches. */
32
+ function invalidateProvidersCache() {
33
+ _providersLoaded = false;
34
+ PROVIDERS_INFO = null;
35
+ }
36
+
37
+ /** Look up one engine's registry entry by name. */
38
+ function engineInfo(name) {
39
+ return PROVIDERS_INFO?.providers?.find(p => p.name === name) || null;
40
+ }
41
+
42
+ /** Compact chip label: "Claude Code (SDK)" → "Claude", "Codex CLI" → "Codex". */
43
+ function shortEngineLabel(displayName) {
44
+ return (displayName || '').split(/[\s(]/)[0] || displayName || '';
45
+ }
46
+
47
+ /**
48
+ * Author label for a session's assistant messages — the engine's OWN short
49
+ * name, lowercased ("claude", "codex"), never a hardcoded vendor. A session's
50
+ * engine locks on its first turn, so one label holds for the whole transcript.
51
+ *
52
+ * The provider id's first segment is the fallback (`codex-app-server` →
53
+ * "codex"), so history rendered before the registry fetch lands still paints
54
+ * the right author instead of flashing "claude" — same first-paint rule the
55
+ * status-bar managers follow.
56
+ */
57
+ function engineAuthorLabel(session) {
58
+ const name = session?.provider || session?.pendingProvider
59
+ || PROVIDERS_INFO?.default || '';
60
+ const label = shortEngineLabel(engineInfo(name)?.display_name)
61
+ || name.split(/[-_]/)[0];
62
+ return (label || S.engine.assistant_fallback).toLowerCase();
63
+ }
64
+
65
+ /** Engines the picker offers (Settings → Engines toggles; default always on). */
66
+ function enabledEngines() {
67
+ return (PROVIDERS_INFO?.providers || []).filter(p => p.enabled !== false);
68
+ }
69
+
70
+ /** The model list `engine` draws from: its self-described catalog (registry
71
+ * `models` — Claude mirrors models.yaml, Codex reads the CLI's own cache),
72
+ * falling back to the app-managed list while the registry hasn't loaded. */
73
+ function engineCatalog(engine) {
74
+ return (engine?.models?.length ? engine.models : MODELS) || [];
75
+ }
76
+
77
+ async function ensureModelsLoaded() {
78
+ if (_modelsLoaded) return;
79
+ try {
80
+ const resp = await fetch(`${CONFIG.API_BASE}/api/app/models`);
81
+ if (resp.ok) {
82
+ const data = await resp.json();
83
+ MODELS = data.selectable || [];
84
+ SUMMARY_MODEL_ID = data.summary_model || '';
85
+ _modelsLoaded = true;
86
+ }
87
+ } catch (e) { /* silent — popup will show raw IDs */ }
88
+ }
89
+
90
+ /** Call this when models.yaml changes so next popup re-fetches. */
91
+ function invalidateModelsCache() {
92
+ _modelsLoaded = false;
93
+ MODELS = [];
94
+ SUMMARY_MODEL_ID = '';
95
+ }
96
+
97
+ /**
98
+ * Friendly label for a model ID. Looks it up in MODELS first, then falls
99
+ * back to deriving from the ID pattern. "claude-haiku-4-5" → "Haiku 4.5".
100
+ */
101
+ function formatModelLabel(id) {
102
+ if (!id) return '';
103
+ const found = MODELS.find(m => m.id === id);
104
+ if (found?.label) return found.label;
105
+ const m = id.match(/claude-([a-z]+)-(\d+)-(\d+)(?:\[(\w+)\])?/i);
106
+ if (m) {
107
+ const [, family, major, minor, variant] = m;
108
+ const cap = family[0].toUpperCase() + family.slice(1);
109
+ return variant ? `${cap} ${major}.${minor} (${variant.toUpperCase()})` : `${cap} ${major}.${minor}`;
110
+ }
111
+ return id;
112
+ }
113
+
114
+ /** Display label for the configured background/auto-journal model. */
115
+ function getSummaryModelLabel() {
116
+ return SUMMARY_MODEL_ID ? formatModelLabel(SUMMARY_MODEL_ID) : 'Haiku';
117
+ }
118
+
119
+ /** Exported for config-widget and other consumers */
120
+ export { MODELS, ensureModelsLoaded, invalidateModelsCache, formatModelLabel, getSummaryModelLabel };
121
+ export { PROVIDERS_INFO, ensureProvidersLoaded, invalidateProvidersCache, engineInfo, shortEngineLabel, engineAuthorLabel, enabledEngines, engineCatalog };
122
+
123
+ /**
124
+ * StatusBar - Manage status display
125
+ */
126
+ export class StatusBar {
127
+ /**
128
+ * @param {Object} elements - DOM elements
129
+ * @param {HTMLElement} elements.statusConnection - Connection dot (tooltip-driven)
130
+ * @param {HTMLElement} elements.statusModel - Model name
131
+ * @param {HTMLElement} elements.statusBranch - Git branch name
132
+ * @param {HTMLElement} elements.statusProject - Project name display
133
+ * @param {HTMLElement} elements.statusCost - Cost display
134
+ * @param {HTMLElement} elements.statusTokens - Token bar container
135
+ * @param {HTMLElement} elements.sendBtn - Send button
136
+ * @param {HTMLElement} elements.followupBtn - Follow-up button (visible while working)
137
+ * @param {HTMLElement} elements.stopBtn - Stop button
138
+ * @param {Object} callbacks - Callback functions
139
+ * @param {Function} callbacks.getSession - Returns active session
140
+ */
141
+ constructor(elements, callbacks = {}) {
142
+ this.els = elements;
143
+ this.getSession = callbacks.getSession || (() => null);
144
+
145
+ // State
146
+ this.isTyping = false;
147
+ this.currentModel = null; // preferred_model for active session
148
+ this.globalDefaultModel = null; // active ENGINE's default model
149
+ this.currentSessionId = null;
150
+ // Per-engine default-model cache (keyed by models_key) — lets a tab
151
+ // switch seed the right engine's default synchronously instead of
152
+ // leaving the previous engine's value up until the confirm fetch.
153
+ this._defaultModelByEngine = {};
154
+ this._modelPopup = null;
155
+ this._modelPopupOpen = false;
156
+ }
157
+
158
+ // ─────────────────────────────────────────────────────────────────
159
+ // Connection Status
160
+ // ─────────────────────────────────────────────────────────────────
161
+
162
+ /**
163
+ * Update status display based on session state
164
+ */
165
+ updateStatus() {
166
+ const session = this.getSession();
167
+ if (!session) return;
168
+
169
+ // Connection status — three states (connected | connecting | disconnected).
170
+ // Rendered as a coloured WORD, not a dot: the dot used to sit flush
171
+ // against the "Auto-journal" pill and was read as that pill's status
172
+ // light. The colour still carries the state at a glance; the word says
173
+ // which state it is without a hover.
174
+ const dot = this.els.statusConnection;
175
+ if (dot) {
176
+ const state = session.status === 'connected' || session.status === 'connecting'
177
+ ? session.status
178
+ : 'disconnected';
179
+ dot.classList.remove('connected', 'connecting', 'disconnected');
180
+ dot.classList.add(state);
181
+ dot.textContent = S.connection?.[state] || state;
182
+ // When clickable (disconnected/connecting), advertise the action in
183
+ // the tooltip. When connected the label already says "Connected",
184
+ // so a tooltip repeating it is pure noise — drop it.
185
+ const clickable = state !== 'connected';
186
+ const tooltipKey = state === 'disconnected'
187
+ ? 'disconnected_click'
188
+ : 'connecting_click';
189
+ if (clickable) {
190
+ dot.setAttribute('data-tooltip',
191
+ S.connection?.[tooltipKey] || S.connection?.[state] || state);
192
+ } else {
193
+ dot.removeAttribute('data-tooltip');
194
+ }
195
+ dot.classList.toggle('clickable', clickable);
196
+ // role/tabindex so trackpad-/keyboard-only users get the affordance too.
197
+ if (clickable) {
198
+ dot.setAttribute('role', 'button');
199
+ dot.setAttribute('tabindex', '0');
200
+ } else {
201
+ dot.removeAttribute('role');
202
+ dot.removeAttribute('tabindex');
203
+ }
204
+ }
205
+
206
+ // Engine chip — which AI engine this session runs on (bound) or will
207
+ // run on (pendingProvider / box default for a not-yet-created tab).
208
+ // Hidden until the registry loads or when only one engine exists.
209
+ const engineName = (session.storeId ? session.provider : session.pendingProvider)
210
+ || PROVIDERS_INFO?.default || null;
211
+ const engine = engineInfo(engineName);
212
+ // Chip is pointless with a single choosable engine — unless this
213
+ // session happens to run on something else (e.g. an engine since
214
+ // disabled in Settings), where it's exactly the information needed.
215
+ const multiEngine = enabledEngines().length > 1
216
+ || (!!engineName && !!PROVIDERS_INFO && engineName !== PROVIDERS_INFO.default);
217
+ if (this.els.statusEngine) {
218
+ if (engine && multiEngine) {
219
+ this.els.statusEngine.textContent = shortEngineLabel(engine.display_name);
220
+ this.els.statusEngine.classList.add('clickable');
221
+ this.els.statusEngine.classList.toggle('pending', !session.storeId);
222
+ this.els.statusEngine.setAttribute('data-tooltip', session.storeId
223
+ ? `${engine.display_name} — ${S.engine.chip_tooltip}`
224
+ : S.engine.chip_tooltip_pending);
225
+ } else {
226
+ this.els.statusEngine.textContent = '';
227
+ this.els.statusEngine.classList.remove('clickable', 'pending');
228
+ this.els.statusEngine.removeAttribute('data-tooltip');
229
+ }
230
+ }
231
+
232
+ // Engines that declare NO catalog (the app doesn't manage their
233
+ // models at all) hide the model chip entirely.
234
+ const engineHidesModel = !!engine && (engine.models || []).length === 0;
235
+
236
+ // Model name (shortened) — the effective pick on this engine's own
237
+ // catalog, the engine-reported actual, or "Default" when the engine
238
+ // runs its own configured model (e.g. a fresh Codex session).
239
+ if (this.els.statusModel) {
240
+ const catalog = engineCatalog(engine);
241
+ const displayId = this.effectiveModelId(engine, session);
242
+ if (!engineHidesModel && (displayId || (engine?.models || []).length)) {
243
+ let label;
244
+ const known = displayId ? catalog.find(m => displayId.startsWith(m.id)) : null;
245
+ if (known) {
246
+ label = known.label;
247
+ } else if (displayId) {
248
+ const parts = displayId.replace('claude-', '').split('-');
249
+ label = parts.length >= 3 && !isNaN(parts[1]) && !isNaN(parts[2])
250
+ ? `${parts[0]}-${parts[1]}.${parts[2]}`
251
+ : parts.slice(0, 3).join('-');
252
+ } else {
253
+ label = S.models.engine_default_label;
254
+ }
255
+ this.els.statusModel.textContent = label;
256
+ this.els.statusModel.classList.add('clickable');
257
+ } else {
258
+ this.els.statusModel.textContent = '';
259
+ this.els.statusModel.classList.remove('clickable');
260
+ }
261
+ }
262
+
263
+ // Cost — hidden for tokens-only engines (no USD accounting); the
264
+ // token meter still shows usage for them.
265
+ if (this.els.statusCost) {
266
+ const tokensOnly = session.providerCaps?.cumulative_cost === false;
267
+ if (session.totalCost > 0 && !tokensOnly) {
268
+ this.els.statusCost.textContent = `$${session.totalCost.toFixed(4)}`;
269
+ } else {
270
+ this.els.statusCost.textContent = '';
271
+ }
272
+ }
273
+
274
+ // Token usage
275
+ this._updateTokenDisplay(session);
276
+
277
+ // Fresh-session setup panel mirrors this chip state in the empty
278
+ // chat area — same funnel, cheap when hidden. window-global lookup
279
+ // (not an import): the panel imports from this module.
280
+ window.sessionSetupPanel?.refresh();
281
+ }
282
+
283
+ /**
284
+ * Update git branch display
285
+ * @param {string|null} branch - Branch name or null to hide
286
+ */
287
+ updateBranch(branch) {
288
+ if (!this.els.statusBranch) return;
289
+
290
+ if (branch) {
291
+ this.els.statusBranch.innerHTML = `
292
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
293
+ <line x1="6" y1="3" x2="6" y2="15"></line>
294
+ <circle cx="18" cy="6" r="3"></circle>
295
+ <circle cx="6" cy="18" r="3"></circle>
296
+ <path d="M18 9a9 9 0 0 1-9 9"></path>
297
+ </svg>
298
+ <span>${branch}</span>
299
+ `;
300
+ this.els.statusBranch.classList.add('visible');
301
+ } else {
302
+ this.els.statusBranch.innerHTML = '';
303
+ this.els.statusBranch.classList.remove('visible');
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Update project name display
309
+ * Shows folder icon with project name, full path on hover
310
+ * @param {string|null} cwd - Full project path or null to hide
311
+ */
312
+ updateProject(cwd) {
313
+ const el = this.els.statusProject;
314
+ if (!el) return;
315
+
316
+ if (cwd) {
317
+ // Extract project name and parent folder for context
318
+ const parts = cwd.split('/').filter(Boolean);
319
+ const projectName = parts[parts.length - 1] || cwd;
320
+ const parentName = parts.length > 1 ? parts[parts.length - 2] : '';
321
+
322
+ // Folder icon (filled style)
323
+ el.innerHTML = `
324
+ <svg viewBox="0 0 24 24" fill="currentColor">
325
+ <path d="M10 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2z"/>
326
+ </svg>
327
+ ${parentName ? `<span class="project-sep">/</span>` : ''}
328
+ <span>${projectName}</span>
329
+ `;
330
+ el.setAttribute('data-tooltip', cwd);
331
+ el.classList.add('visible');
332
+
333
+ // Click to copy path
334
+ el.onclick = (e) => {
335
+ e.stopPropagation();
336
+ navigator.clipboard.writeText(cwd).then(() => {
337
+ // Brief visual feedback
338
+ const originalTooltip = el.getAttribute('data-tooltip');
339
+ el.setAttribute('data-tooltip', 'Copied!');
340
+ el.style.color = 'var(--success)';
341
+ setTimeout(() => {
342
+ el.setAttribute('data-tooltip', originalTooltip);
343
+ el.style.color = '';
344
+ }, 1000);
345
+ }).catch(() => {
346
+ // Silent fail - clipboard may not be available
347
+ });
348
+ };
349
+ } else {
350
+ el.innerHTML = '';
351
+ el.classList.remove('visible');
352
+ el.onclick = null;
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Update token usage bar
358
+ * Shows EFFECTIVE percentage (tokens / usable window) to match inline indicator
359
+ */
360
+ _updateTokenDisplay(session) {
361
+ const tokensEl = this.els.statusTokens;
362
+ if (!tokensEl) return;
363
+
364
+ const fill = tokensEl.querySelector('.token-fill');
365
+ const text = tokensEl.querySelector('.token-text');
366
+
367
+ // Error state
368
+ if (session.contextTokens === -1) {
369
+ tokensEl.classList.add('visible');
370
+ if (fill) {
371
+ fill.style.width = '100%';
372
+ fill.classList.remove('warning');
373
+ fill.classList.add('danger');
374
+ }
375
+ if (text) {
376
+ text.textContent = 'token error';
377
+ text.classList.remove('warning');
378
+ text.classList.add('danger');
379
+ }
380
+ return;
381
+ }
382
+
383
+ if (session.contextTokens > 0) {
384
+ tokensEl.classList.add('visible');
385
+
386
+ // Calculate reserved buffer and usable window (same logic as inline indicator)
387
+ const reservedBuffer = session.contextBreakdown?.autocompact_buffer?.tokens || 0;
388
+ const usableWindow = session.contextWindow - reservedBuffer;
389
+
390
+ // Effective percentage - what actually matters for auto-compaction
391
+ const effectivePct = reservedBuffer > 0
392
+ ? Math.min(100, (session.contextTokens / usableWindow) * 100)
393
+ : Math.min(100, (session.contextTokens / session.contextWindow) * 100);
394
+
395
+ if (fill) {
396
+ fill.style.width = `${effectivePct}%`;
397
+ fill.classList.remove('warning', 'danger');
398
+ // Thresholds aligned with inline indicator: 70% warning, 85% danger
399
+ if (effectivePct >= 85) {
400
+ fill.classList.add('danger');
401
+ } else if (effectivePct >= 70) {
402
+ fill.classList.add('warning');
403
+ }
404
+ }
405
+
406
+ if (text) {
407
+ const formatK = (n) => n >= 1000 ? `${Math.round(n / 1000)}K` : n;
408
+ // Show tokens / usable window (not total window)
409
+ text.textContent = `${formatK(session.contextTokens)} / ${formatK(usableWindow)}`;
410
+ text.classList.remove('warning', 'danger');
411
+ if (effectivePct >= 85) {
412
+ text.classList.add('danger');
413
+ } else if (effectivePct >= 70) {
414
+ text.classList.add('warning');
415
+ }
416
+ }
417
+ } else {
418
+ tokensEl.classList.remove('visible');
419
+ }
420
+ }
421
+
422
+ // ─────────────────────────────────────────────────────────────────
423
+ // Send/Stop Button Toggle
424
+ // ─────────────────────────────────────────────────────────────────
425
+
426
+ /**
427
+ * Toggle send/stop button visibility.
428
+ * Activity strip is managed by ActivityStrip module directly.
429
+ * @param {boolean} working - Whether Claude is working
430
+ */
431
+ toggleStopButton(working) {
432
+ this.isTyping = working;
433
+ this.els.sendBtn?.classList.toggle('hidden', working);
434
+ this.els.followupBtn?.classList.toggle('visible', working);
435
+ this.els.stopBtn?.classList.toggle('visible', working);
436
+ }
437
+
438
+ /**
439
+ * Get current working state
440
+ */
441
+ get typing() {
442
+ return this.isTyping;
443
+ }
444
+
445
+ // ─────────────────────────────────────────────────────────────────
446
+ // Context Popover
447
+ // ─────────────────────────────────────────────────────────────────
448
+
449
+ /**
450
+ * Load preferred model for a session (called on tab switch)
451
+ */
452
+ async setSession(sessionId) {
453
+ this.currentSessionId = sessionId;
454
+
455
+ // Synchronous seed — a tab switch must paint THIS session's engine
456
+ // state immediately (session pref cache + per-engine default cache);
457
+ // the fetches below only confirm. Never leave the previous session's
458
+ // values up while awaiting, or the chip/setup-panel flash the old
459
+ // engine's model until the network round-trip lands.
460
+ const sess = this.getSession();
461
+ const seedEngineName = (sess ? (sess.provider || sess.pendingProvider) : null)
462
+ || PROVIDERS_INFO?.default || null;
463
+ const seedKey = engineInfo(seedEngineName)?.models_key || seedEngineName;
464
+ this.globalDefaultModel = (seedKey && this._defaultModelByEngine[seedKey]) || null;
465
+ this.currentModel = sess?.preferredModel || this.globalDefaultModel;
466
+ this.updateStatus();
467
+
468
+ // Ensure models list is loaded from server
469
+ await ensureModelsLoaded();
470
+ // Bail if a newer setSession() superseded us during the await — otherwise a
471
+ // slow response for an old session clobbers the current session's model.
472
+ if (this.currentSessionId !== sessionId) return;
473
+
474
+ if (!sessionId) {
475
+ // Unbound tab — confirm the engine's configured default (scoped
476
+ // endpoint when the tab's engine is known, legacy default-engine
477
+ // endpoint otherwise).
478
+ try {
479
+ const url = seedEngineName
480
+ ? `${CONFIG.API_BASE}/api/app/engine-defaults/${encodeURIComponent(seedEngineName)}`
481
+ : `${CONFIG.API_BASE}/api/app/default-model`;
482
+ const gr = await fetch(url);
483
+ if (this.currentSessionId !== sessionId) return;
484
+ if (gr.ok) {
485
+ const gd = await gr.json();
486
+ this.globalDefaultModel = gd.default_model || null;
487
+ if (seedKey) this._defaultModelByEngine[seedKey] = this.globalDefaultModel;
488
+ }
489
+ } catch (e) { /* silent */ }
490
+ this.currentModel = this.globalDefaultModel;
491
+ this.updateStatus();
492
+ return;
493
+ }
494
+ try {
495
+ const resp = await fetch(`${CONFIG.API_BASE}/api/session/${sessionId}/model`);
496
+ if (this.currentSessionId !== sessionId) return;
497
+ if (resp.ok) {
498
+ const data = await resp.json();
499
+ // global_default is the SESSION ENGINE's configured default
500
+ // (null when that engine has none — e.g. codex running its
501
+ // own config.toml model, rendered as the "Default" row).
502
+ this.globalDefaultModel = data.global_default || null;
503
+ if (seedKey) this._defaultModelByEngine[seedKey] = this.globalDefaultModel;
504
+ this.currentModel = data.preferred_model || null;
505
+ if (sess) sess.preferredModel = data.preferred_model || null;
506
+ } else {
507
+ // Session not yet registered server-side (common right after a page
508
+ // load / reconcile). Fall back to the engine default rather
509
+ // than leaving currentModel null — a null lets the status chip show the
510
+ // stale last-run model (session.model) instead of the real default.
511
+ this.currentModel = this.globalDefaultModel;
512
+ }
513
+ } catch (e) {
514
+ if (this.currentSessionId !== sessionId) return;
515
+ this.currentModel = this.globalDefaultModel;
516
+ }
517
+ this.updateStatus();
518
+ }
519
+
520
+ /**
521
+ * Initialize hover handlers for interactive elements
522
+ */
523
+ init() {
524
+ // Connection dot — click to force-reconnect when not connected.
525
+ // Auto-reconnect with backoff already runs in Session; this handler
526
+ // just lets the user skip the wait and resets the attempt counter so
527
+ // the next try is immediate.
528
+ if (this.els.statusConnection) {
529
+ const triggerReconnect = (e) => {
530
+ const session = this.getSession();
531
+ if (!session) return;
532
+ // Always allow a user-initiated reconnect. Don't gate on
533
+ // status: a half-open socket (iPad PWA resume) still reports
534
+ // status 'connected' while being dead, and gating here made the
535
+ // dot a silent no-op — the user's only manual recovery. Skip
536
+ // only a genuinely healthy socket that saw a recent frame.
537
+ const healthy = session.status === 'connected' &&
538
+ session.ws && session.ws.readyState === WebSocket.OPEN &&
539
+ session._lastServerFrame &&
540
+ (Date.now() - session._lastServerFrame) < 75_000;
541
+ if (!healthy) {
542
+ e.stopPropagation();
543
+ if (typeof window !== 'undefined' && window.app?.connectIfDisconnected) {
544
+ window.app.connectIfDisconnected();
545
+ } else if (typeof session.forceReconnect === 'function') {
546
+ session.forceReconnect();
547
+ }
548
+ }
549
+ };
550
+ this.els.statusConnection.addEventListener('click', triggerReconnect);
551
+ this.els.statusConnection.addEventListener('keydown', (e) => {
552
+ if (e.key === 'Enter' || e.key === ' ') triggerReconnect(e);
553
+ });
554
+ }
555
+
556
+ // Model selector — click on status-model to open popup
557
+ if (this.els.statusModel) {
558
+ this.els.statusModel.addEventListener('click', (e) => {
559
+ e.stopPropagation();
560
+ this._toggleModelPopup();
561
+ });
562
+ }
563
+
564
+ // Engine selector — click on status-engine to open the picker
565
+ if (this.els.statusEngine) {
566
+ this.els.statusEngine.addEventListener('click', (e) => {
567
+ e.stopPropagation();
568
+ this._toggleEnginePopup();
569
+ });
570
+ }
571
+
572
+ // Close model/engine popups on outside click / Escape
573
+ document.addEventListener('click', (e) => {
574
+ if (this._modelPopupOpen && this._modelPopup && !this._modelPopup.contains(e.target)) {
575
+ this._closeModelPopup();
576
+ }
577
+ if (this._enginePopupOpen && this._enginePopup && !this._enginePopup.contains(e.target)) {
578
+ this._closeEnginePopup();
579
+ }
580
+ });
581
+
582
+ // Warm the engine registry so the chip appears on first paint.
583
+ ensureProvidersLoaded().then(() => this.updateStatus());
584
+
585
+ // Token display hover handler - show popover on mouseenter
586
+ if (this.els.statusTokens) {
587
+ this.els.statusTokens.style.cursor = 'default';
588
+ this._hoverTimeout = null;
589
+ this._hideTimeout = null;
590
+
591
+ this.els.statusTokens.addEventListener('mouseenter', () => {
592
+ clearTimeout(this._hideTimeout);
593
+ // Small delay before showing to avoid flicker on quick mouse passes
594
+ this._hoverTimeout = setTimeout(() => {
595
+ this.showContextPopover();
596
+ }, 150);
597
+ });
598
+
599
+ this.els.statusTokens.addEventListener('mouseleave', (e) => {
600
+ clearTimeout(this._hoverTimeout);
601
+ // Delay to allow mouse to reach popover
602
+ this._hideTimeout = setTimeout(() => {
603
+ const popover = document.getElementById('context-popover');
604
+ if (popover && popover.matches(':hover')) return;
605
+ this.hideContextPopover();
606
+ }, 300);
607
+ });
608
+ }
609
+
610
+ // Close popover on escape (only if visible, don't block other handlers)
611
+ document.addEventListener('keydown', (e) => {
612
+ if (e.key === 'Escape' && this._modelPopupOpen) {
613
+ this._closeModelPopup();
614
+ e.stopPropagation();
615
+ return;
616
+ }
617
+ if (e.key === 'Escape') {
618
+ // Close status bar popover
619
+ const statusPopover = document.getElementById('context-popover');
620
+ if (statusPopover) {
621
+ this.hideContextPopover();
622
+ e.stopPropagation();
623
+ return;
624
+ }
625
+ // Close inline breakdown popover
626
+ const inlinePopover = document.querySelector('.context-breakdown-popover');
627
+ if (inlinePopover) {
628
+ inlinePopover.remove();
629
+ e.stopPropagation();
630
+ return;
631
+ }
632
+ }
633
+ });
634
+ }
635
+
636
+ /**
637
+ * Toggle context popover visibility
638
+ */
639
+ toggleContextPopover() {
640
+ const existing = document.getElementById('context-popover');
641
+ if (existing) {
642
+ this.hideContextPopover();
643
+ } else {
644
+ this.showContextPopover();
645
+ }
646
+ }
647
+
648
+ /**
649
+ * Show context usage popover with detailed breakdown
650
+ */
651
+ showContextPopover() {
652
+ const session = this.getSession();
653
+ if (!session) return;
654
+
655
+ // Remove existing popover
656
+ this.hideContextPopover();
657
+
658
+ const popover = document.createElement('div');
659
+ popover.id = 'context-popover';
660
+ popover.className = 'context-popover';
661
+
662
+ // Calculate relative time
663
+ const updatedAgo = session.contextUpdatedAt
664
+ ? this._formatTimeAgo(Date.now() - session.contextUpdatedAt)
665
+ : 'unknown';
666
+
667
+ // Calculate effective percentage (same as inline indicator)
668
+ const reservedBuffer = session.contextBreakdown?.autocompact_buffer?.tokens || 0;
669
+ const usableWindow = session.contextWindow - reservedBuffer;
670
+ const effectivePct = session.contextWindow > 0
671
+ ? (reservedBuffer > 0
672
+ ? Math.round((session.contextTokens / usableWindow) * 100)
673
+ : Math.round((session.contextTokens / session.contextWindow) * 100))
674
+ : 0;
675
+
676
+ // Determine status class (thresholds aligned with inline: 70% warning, 85% danger)
677
+ let statusClass = '';
678
+ if (effectivePct >= 85) statusClass = 'danger';
679
+ else if (effectivePct >= 70) statusClass = 'warning';
680
+
681
+ // Format token numbers
682
+ const formatK = (n) => {
683
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
684
+ return String(n);
685
+ };
686
+
687
+ // Build breakdown HTML
688
+ let breakdownHtml = '';
689
+ if (session.contextBreakdown) {
690
+ const breakdown = session.contextBreakdown;
691
+ // Order categories logically
692
+ const order = ['system_prompt', 'system_tools', 'custom_agents', 'memory_files', 'skills', 'messages', 'free_space', 'autocompact_buffer'];
693
+ const labels = {
694
+ system_prompt: 'System prompt',
695
+ system_tools: 'Tool definitions',
696
+ custom_agents: 'Custom agents',
697
+ memory_files: 'Memory files',
698
+ skills: 'Skills',
699
+ messages: 'Conversation',
700
+ free_space: 'Free space',
701
+ autocompact_buffer: 'Reserved buffer'
702
+ };
703
+
704
+ breakdownHtml = '<div class="context-breakdown">';
705
+ for (const key of order) {
706
+ if (breakdown[key]) {
707
+ const { tokens, pct } = breakdown[key];
708
+ const isFree = key === 'free_space' || key === 'autocompact_buffer';
709
+ breakdownHtml += `
710
+ <div class="breakdown-row ${isFree ? 'muted' : ''}">
711
+ <span class="breakdown-label">${labels[key] || key}</span>
712
+ <span class="breakdown-tokens">${formatK(tokens)}</span>
713
+ <span class="breakdown-pct">${pct.toFixed(1)}%</span>
714
+ </div>`;
715
+ if (key === 'messages') {
716
+ breakdownHtml += '<div class="breakdown-divider"></div>';
717
+ }
718
+ }
719
+ }
720
+ breakdownHtml += '</div>';
721
+ }
722
+
723
+ // Memory files detail
724
+ let memoryHtml = '';
725
+ if (session.contextMemoryFiles && session.contextMemoryFiles.length > 0) {
726
+ memoryHtml = '<div class="context-memory"><div class="memory-title">Memory Files</div>';
727
+ for (const file of session.contextMemoryFiles) {
728
+ const shortPath = file.path.split('/').slice(-2).join('/');
729
+ memoryHtml += `
730
+ <div class="memory-row">
731
+ <span class="memory-path" data-tooltip="${file.path}">${shortPath}</span>
732
+ <span class="memory-tokens">${formatK(file.tokens)}</span>
733
+ </div>`;
734
+ }
735
+ memoryHtml += '</div>';
736
+ }
737
+
738
+ // Session stats
739
+ const turns = session.messages?.filter(m => m.role === 'user').length || 0;
740
+ const cost = session.totalCost?.toFixed(4) || '0.0000';
741
+
742
+ // Reserved buffer label (only if present)
743
+ const reservedLabel = reservedBuffer > 0
744
+ ? `<span class="popover-reserved">${Math.round((reservedBuffer / session.contextWindow) * 100)}% reserved</span>`
745
+ : '';
746
+
747
+ popover.innerHTML = `
748
+ <div class="popover-header">
749
+ <span class="popover-title">Context Usage</span>
750
+ <span class="popover-updated">Updated ${updatedAgo}</span>
751
+ </div>
752
+ <div class="popover-progress">
753
+ <div class="progress-bar">
754
+ <div class="progress-fill ${statusClass}" style="width: ${effectivePct}%"></div>
755
+ </div>
756
+ <div class="progress-text ${statusClass}">
757
+ ${effectivePct}% (${formatK(session.contextTokens)} / ${formatK(usableWindow)})
758
+ ${reservedLabel}
759
+ </div>
760
+ </div>
761
+ ${breakdownHtml}
762
+ ${memoryHtml}
763
+ <div class="popover-footer">
764
+ <span>Session: $${cost}</span>
765
+ <span>${turns} turn${turns !== 1 ? 's' : ''}</span>
766
+ </div>
767
+ `;
768
+
769
+ // Position below the token display
770
+ const rect = this.els.statusTokens.getBoundingClientRect();
771
+ popover.style.position = 'fixed';
772
+ popover.style.bottom = `${window.innerHeight - rect.top + 8}px`;
773
+ popover.style.right = `${window.innerWidth - rect.right}px`;
774
+
775
+ // Cancel hide timeout when mouse enters popover
776
+ popover.addEventListener('mouseenter', () => {
777
+ clearTimeout(this._hideTimeout);
778
+ });
779
+
780
+ // Close when mouse leaves popover
781
+ popover.addEventListener('mouseleave', (e) => {
782
+ if (e.relatedTarget && this.els.statusTokens?.contains(e.relatedTarget)) {
783
+ return; // Don't close - mouse moved back to token display
784
+ }
785
+ setTimeout(() => this.hideContextPopover(), 200);
786
+ });
787
+
788
+ document.body.appendChild(popover);
789
+
790
+ // Animate in
791
+ requestAnimationFrame(() => popover.classList.add('visible'));
792
+ }
793
+
794
+ // ─────────────────────────────────────────────────────────────────
795
+ // Model Selector Popup
796
+ // ─────────────────────────────────────────────────────────────────
797
+
798
+ /** Effective model id for the active session on `engine`, or null when
799
+ * the engine's own configured default applies (which the app can't name).
800
+ * The user-pick chain (per-session pick → global default) is filtered to
801
+ * ids the engine actually offers — a pick made under another engine must
802
+ * not label this one — while the engine-REPORTED actual (`session.model`)
803
+ * is always trusted. Prefix match: reported ids carry date suffixes. */
804
+ effectiveModelId(engine, session) {
805
+ const catalog = engineCatalog(engine);
806
+ const inCat = id => !!id && catalog.some(m => id.startsWith(m.id));
807
+ if (inCat(this.currentModel)) return this.currentModel;
808
+ if (session?.model) return session.model;
809
+ if (inCat(this.globalDefaultModel)) return this.globalDefaultModel;
810
+ // The app always presents a concrete default — fall back to the
811
+ // engine's top catalog model rather than the ambiguous "Default".
812
+ // The server resolves the same top-of-enabled default; this just
813
+ // covers the pre-fetch transient (globalDefaultModel not loaded yet).
814
+ return catalog[0]?.id || null;
815
+ }
816
+
817
+ /** The active session's engine registry entry (bound, pending, or the
818
+ * box default) — what the model chip/popup should describe. */
819
+ _activeEngine() {
820
+ const session = this.getSession();
821
+ // provider wins once known; a bound tab whose provider hasn't been
822
+ // echoed yet still resolves to the user's pick (pendingProvider).
823
+ const name = session
824
+ ? ((session.provider || session.pendingProvider)
825
+ || PROVIDERS_INFO?.default)
826
+ : PROVIDERS_INFO?.default;
827
+ return engineInfo(name);
828
+ }
829
+
830
+ _toggleModelPopup() {
831
+ if (this._modelPopupOpen) {
832
+ this._closeModelPopup();
833
+ } else {
834
+ this._openModelPopup();
835
+ }
836
+ }
837
+
838
+ async _openModelPopup() {
839
+ await Promise.all([ensureModelsLoaded(), ensureProvidersLoaded()]);
840
+ this._closeModelPopup();
841
+
842
+ // The popup lists the ACTIVE ENGINE's own catalog — Claude sessions
843
+ // get the models.yaml list, Codex sessions get the Codex CLI's.
844
+ const engine = this._activeEngine();
845
+ const catalog = engineCatalog(engine);
846
+ if (!catalog.length) return;
847
+
848
+ const popup = document.createElement('div');
849
+ popup.className = 'model-popup';
850
+ this._modelPopup = popup;
851
+ this._modelPopupOpen = true;
852
+
853
+ // The row in effect: the per-session pick if this engine offers it,
854
+ // else the engine's default. (No engine-reported actual here — the
855
+ // popup is about the USER's pick.) The default always resolves to a
856
+ // concrete catalog model — the server falls back to the top model, and
857
+ // catalog[0] covers the pre-fetch transient — so there is no "Default"
858
+ // pseudo-row; the default model is marked inline with a badge.
859
+ const inCat = id => !!id && catalog.some(m => id.startsWith(m.id));
860
+ const pick = inCat(this.currentModel) ? this.currentModel : null;
861
+ const resolvedDefault =
862
+ (inCat(this.globalDefaultModel) ? this.globalDefaultModel : null)
863
+ || catalog[0]?.id || null;
864
+ const effectiveModel = pick || resolvedDefault;
865
+
866
+ const rows = catalog.map(m => {
867
+ const isSelected = effectiveModel === m.id;
868
+ const isDefault = resolvedDefault === m.id;
869
+ return `<div class="model-option${isSelected ? ' selected' : ''}" data-model-id="${m.id}">
870
+ <span class="model-option-label">${m.label}</span>
871
+ <span class="model-option-desc">${isDefault ? S.models.global_default_badge : m.desc}</span>
872
+ </div>`;
873
+ });
874
+
875
+ // "Set as default" writes THIS ENGINE's new-session default model
876
+ // (defaults are per-engine) — offered on every engine's popup.
877
+ popup.innerHTML = rows.join('') + `<div class="model-popup-footer">
878
+ <button class="model-set-default" data-model-id="${effectiveModel || ''}">${S.models.set_default_button}</button>
879
+ </div>`;
880
+
881
+ popup.addEventListener('click', (e) => {
882
+ const opt = e.target.closest('.model-option');
883
+ if (opt) { this._selectModel(opt.dataset.modelId); return; }
884
+ const def = e.target.closest('.model-set-default');
885
+ if (def) this._saveToGlobal(def.dataset.modelId, engine?.name);
886
+ });
887
+
888
+ // Position above the status-model element
889
+ document.body.appendChild(popup);
890
+ const rect = this.els.statusModel.getBoundingClientRect();
891
+ popup.style.left = `${rect.left}px`;
892
+ popup.style.bottom = `${window.innerHeight - rect.top + 6}px`;
893
+
894
+ requestAnimationFrame(() => popup.classList.add('open'));
895
+ }
896
+
897
+ _closeModelPopup() {
898
+ if (this._modelPopup) {
899
+ this._modelPopup.remove();
900
+ this._modelPopup = null;
901
+ }
902
+ this._modelPopupOpen = false;
903
+ }
904
+
905
+ // ─────────────────────────────────────────────────────────────────
906
+ // Engine (provider) Picker Popup
907
+ // ─────────────────────────────────────────────────────────────────
908
+
909
+ _toggleEnginePopup(anchorEl) {
910
+ if (this._enginePopupOpen) {
911
+ this._closeEnginePopup();
912
+ } else {
913
+ this._openEnginePopup(anchorEl);
914
+ }
915
+ }
916
+
917
+ /** Engine locked = the session has run a turn on it (server-reported at
918
+ * connect; a providerSessionId appearing mid-session is the live signal). */
919
+ _engineLocked(session) {
920
+ return !!session?.storeId && (session.providerLocked || !!session.providerSessionId);
921
+ }
922
+
923
+ async _openEnginePopup(anchorEl) {
924
+ await ensureProvidersLoaded();
925
+ if (!PROVIDERS_INFO?.providers?.length) return;
926
+ this._closeModelPopup();
927
+ this._closeEnginePopup();
928
+
929
+ const session = this.getSession();
930
+ const bound = session?.storeId ? (session.provider || PROVIDERS_INFO.default) : null;
931
+ const locked = this._engineLocked(session);
932
+ const effective = bound || session?.pendingProvider || PROVIDERS_INFO.default;
933
+
934
+ const popup = document.createElement('div');
935
+ popup.className = 'model-popup engine-popup';
936
+ this._enginePopup = popup;
937
+ this._enginePopupOpen = true;
938
+
939
+ // Three states: pre-connect tab (choice rides the create connect),
940
+ // bound-but-empty (switchable in place until the first turn), locked
941
+ // (picking another engine opens a fresh tab on it).
942
+ const note = locked ? `<div class="engine-popup-note">${S.engine.fixed_note}</div>`
943
+ : bound ? `<div class="engine-popup-note">${S.engine.switchable_note}</div>`
944
+ : '';
945
+
946
+ // Offer only Settings-enabled engines, plus this session's own engine
947
+ // if it has since been disabled (the selected row must always exist).
948
+ const offered = PROVIDERS_INFO.providers.filter(
949
+ p => p.enabled !== false || p.name === effective);
950
+
951
+ popup.innerHTML = note + offered.map(p => {
952
+ const isSelected = p.name === effective;
953
+ const isDefault = p.name === PROVIDERS_INFO.default;
954
+ const cls = ['model-option', 'engine-option'];
955
+ if (isSelected) cls.push('selected');
956
+ if (!p.available) cls.push('unavailable');
957
+ const desc = !p.available
958
+ ? (p.unavailable_reason || '')
959
+ : (isSelected && bound) ? S.engine.this_session
960
+ : isDefault ? S.engine.default_badge
961
+ : (p.description || '');
962
+ return `<div class="${cls.join(' ')}" data-engine="${p.name}">
963
+ <span class="model-option-label">${p.display_name}</span>
964
+ <span class="model-option-desc">${desc}</span>
965
+ </div>`;
966
+ }).join('') + `<div class="model-popup-footer">
967
+ <button class="engine-set-default" data-engine="${effective}"${PROVIDERS_INFO.default_pinned_by_flag ? ` disabled data-tooltip="${S.engine.pinned_by_flag}"` : ''}>${S.engine.set_default}</button>
968
+ </div>`;
969
+
970
+ popup.addEventListener('click', (e) => {
971
+ const opt = e.target.closest('.engine-option');
972
+ if (opt) { this._selectEngine(opt.dataset.engine); return; }
973
+ const def = e.target.closest('.engine-set-default');
974
+ if (def && !def.disabled) this._saveEngineDefault(def.dataset.engine);
975
+ });
976
+
977
+ document.body.appendChild(popup);
978
+ // Anchor to whichever chip opened it: above a bottom chip (status
979
+ // bar), below a top chip (connection bar).
980
+ const anchor = anchorEl || this.els.statusEngine;
981
+ const rect = anchor.getBoundingClientRect();
982
+ popup.style.left = `${rect.left}px`;
983
+ if (rect.top < window.innerHeight / 2) {
984
+ popup.style.top = `${rect.bottom + 6}px`;
985
+ } else {
986
+ popup.style.bottom = `${window.innerHeight - rect.top + 6}px`;
987
+ }
988
+
989
+ requestAnimationFrame(() => popup.classList.add('open'));
990
+ }
991
+
992
+ _closeEnginePopup() {
993
+ if (this._enginePopup) {
994
+ this._enginePopup.remove();
995
+ this._enginePopup = null;
996
+ }
997
+ this._enginePopupOpen = false;
998
+ }
999
+
1000
+ async _selectEngine(name) {
1001
+ const p = engineInfo(name);
1002
+ const session = this.getSession();
1003
+ if (!p || !session) { this._closeEnginePopup(); return; }
1004
+
1005
+ if (!p.available) {
1006
+ showToast(S.engine.unavailable_toast
1007
+ .replace('{engine}', p.display_name)
1008
+ .replace('{reason}', p.unavailable_reason || ''));
1009
+ return; // keep the popup open — the row is informational
1010
+ }
1011
+
1012
+ this._closeEnginePopup();
1013
+
1014
+ if (!session.storeId) {
1015
+ // Tab not created server-side yet — the choice rides the create
1016
+ // connect (?provider=) once a project is picked.
1017
+ session.pendingProvider = name;
1018
+ this._afterEngineChange(session);
1019
+ showToast(S.engine.pending_toast.replace('{engine}', p.display_name));
1020
+ return;
1021
+ }
1022
+
1023
+ const bound = session.provider || PROVIDERS_INFO.default;
1024
+ if (name === bound) return; // already on it
1025
+
1026
+ if (!this._engineLocked(session)) {
1027
+ // Empty bound session — switch it in place (server 409s if a turn
1028
+ // raced us, in which case fall through to the new-tab path).
1029
+ try {
1030
+ const resp = await fetch(`${CONFIG.API_BASE}/api/session/${session.storeId}/provider`, {
1031
+ method: 'PUT',
1032
+ headers: { 'Content-Type': 'application/json' },
1033
+ body: JSON.stringify({ provider: name }),
1034
+ });
1035
+ if (resp.ok) {
1036
+ session.provider = name;
1037
+ session.providerDisplayName = p.display_name;
1038
+ session.providerCaps = p.capabilities || null;
1039
+ this._afterEngineChange(session);
1040
+ // The server re-anchors cross-engine picks on bind (a
1041
+ // preferred_model the new engine's catalog doesn't offer
1042
+ // is cleared) — re-pull model state so the chip agrees.
1043
+ this.setSession(session.storeId);
1044
+ showToast(S.engine.switch_toast.replace('{engine}', p.display_name));
1045
+ return;
1046
+ }
1047
+ if (resp.status !== 409) {
1048
+ console.error('Engine switch failed:', resp.status);
1049
+ return;
1050
+ }
1051
+ session.providerLocked = true; // raced a turn — fall through
1052
+ } catch (e) {
1053
+ console.error('Engine switch failed:', e);
1054
+ return;
1055
+ }
1056
+ }
1057
+
1058
+ // Locked session → open a new tab pre-set to the picked engine.
1059
+ // Inherit the project too and connect right away, so the switch is one
1060
+ // action — not "new tab, now go pick the folder again".
1061
+ const created = session.cwd
1062
+ ? window.app?.sessionManager?.create?.({ cwd: session.cwd })
1063
+ : window.app?.createSession?.();
1064
+ if (created) {
1065
+ created.pendingProvider = name;
1066
+ if (session.cwd) {
1067
+ window.app?.switchToSession?.(created);
1068
+ // cwd is inherited, so the tab routes straight to the chat
1069
+ // view — suppress the connection bar's brief flash (same
1070
+ // guard as cloneSession).
1071
+ window.app?.els?.connectionBar?.classList.remove('visible');
1072
+ created.connect();
1073
+ }
1074
+ this._afterEngineChange(created);
1075
+ showToast(S.engine.new_tab_toast.replace('{engine}', p.display_name));
1076
+ }
1077
+ }
1078
+
1079
+ /** Shared refresh after any engine change: persist tabs, redraw the strip
1080
+ * badge + status chips, and re-pull the per-engine vocabularies (each
1081
+ * engine speaks its own permission modes / effort scale / accounts). */
1082
+ _afterEngineChange(session) {
1083
+ window.app?.sessionManager?.saveSessions?.();
1084
+ window.app?.renderTabs?.();
1085
+ this.updateStatus();
1086
+ if (session?.isActive !== false) {
1087
+ window.permissionSettings?.setSession?.(session.storeId || null, {
1088
+ pendingProvider: session.pendingProvider || null,
1089
+ });
1090
+ window.effortSettings?.setSession?.(session.storeId || null);
1091
+ window.tokenProfile?.setSession?.(session.storeId || null);
1092
+ }
1093
+ }
1094
+
1095
+ async _saveEngineDefault(name) {
1096
+ if (!name) return;
1097
+ this._closeEnginePopup();
1098
+ try {
1099
+ const resp = await fetch(`${CONFIG.API_BASE}/api/app/default-provider`, {
1100
+ method: 'PUT',
1101
+ headers: { 'Content-Type': 'application/json' },
1102
+ body: JSON.stringify({ default_provider: name }),
1103
+ });
1104
+ if (resp.ok && PROVIDERS_INFO) {
1105
+ PROVIDERS_INFO.default = name;
1106
+ this.updateStatus();
1107
+ }
1108
+ } catch (e) {
1109
+ console.error('Failed to save default engine:', e);
1110
+ }
1111
+ }
1112
+
1113
+ async _selectModel(modelId) {
1114
+ this.currentModel = modelId || null;
1115
+ this._closeModelPopup();
1116
+ this.updateStatus();
1117
+
1118
+ if (!this.currentSessionId) {
1119
+ if (modelId) await this._saveToGlobal(modelId);
1120
+ return;
1121
+ }
1122
+
1123
+ // Keep the session's pref cache in step so the next tab switch
1124
+ // seeds the pick synchronously.
1125
+ const sess = this.getSession();
1126
+ if (sess?.storeId === this.currentSessionId) {
1127
+ sess.preferredModel = modelId || null;
1128
+ }
1129
+
1130
+ try {
1131
+ await fetch(`${CONFIG.API_BASE}/api/session/${this.currentSessionId}/model`, {
1132
+ method: 'PUT',
1133
+ headers: { 'Content-Type': 'application/json' },
1134
+ // '' (the "Default" row) clears the pin like null does
1135
+ body: JSON.stringify({ preferred_model: modelId || null }),
1136
+ });
1137
+ } catch (e) {
1138
+ console.error('Failed to save model preference:', e);
1139
+ }
1140
+ }
1141
+
1142
+ async _saveToGlobal(modelId, engineName) {
1143
+ if (!modelId) return;
1144
+ this.globalDefaultModel = modelId;
1145
+ this._closeModelPopup();
1146
+ try {
1147
+ // Defaults are per-engine — write THIS engine's entry.
1148
+ const name = engineName || this._activeEngine()?.name || PROVIDERS_INFO?.default;
1149
+ const key = engineInfo(name)?.models_key || name;
1150
+ if (key) this._defaultModelByEngine[key] = modelId;
1151
+ await fetch(`${CONFIG.API_BASE}/api/app/engine-defaults/${encodeURIComponent(name)}`, {
1152
+ method: 'PUT',
1153
+ headers: { 'Content-Type': 'application/json' },
1154
+ body: JSON.stringify({ default_model: modelId }),
1155
+ });
1156
+ } catch (e) {
1157
+ console.error('Failed to save default model:', e);
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * Hide context popover
1163
+ */
1164
+ hideContextPopover() {
1165
+ const popover = document.getElementById('context-popover');
1166
+ if (popover) {
1167
+ popover.classList.remove('visible');
1168
+ setTimeout(() => popover.remove(), 150);
1169
+ }
1170
+ }
1171
+
1172
+ /**
1173
+ * Format milliseconds as relative time string
1174
+ */
1175
+ _formatTimeAgo(ms) {
1176
+ const seconds = Math.floor(ms / 1000);
1177
+ if (seconds < 5) return 'just now';
1178
+ if (seconds < 60) return `${seconds}s ago`;
1179
+ const minutes = Math.floor(seconds / 60);
1180
+ if (minutes < 60) return `${minutes}m ago`;
1181
+ const hours = Math.floor(minutes / 60);
1182
+ return `${hours}h ago`;
1183
+ }
1184
+ }