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,1414 @@
1
+ /**
2
+ * UI Components: MarkdownRenderer and AutocompleteUI
3
+ */
4
+
5
+ import { COMMANDS, getRecentShellCommands } from './config.js';
6
+ import { escapeHtml, escapeAttr, decodeHtml, sanitizeSvg } from './utils.js';
7
+ import { getCommandStore, CommandType } from './command-store.js';
8
+ import { anchorAbove } from './caret-position.js';
9
+ import S from './strings.js';
10
+ import {
11
+ buildPathPattern,
12
+ buildStandalonePattern,
13
+ buildUrlPattern,
14
+ cleanUrlTrailingPunct,
15
+ isValidStandaloneFile,
16
+ parseLineInfo
17
+ } from './linkify-utils.js';
18
+
19
+ // Helper to get app instance
20
+ const getApp = () => window.app;
21
+
22
+ /**
23
+ * Markdown renderer using marked.js and highlight.js
24
+ * (Both are loaded as external scripts in HTML)
25
+ */
26
+ export class MarkdownRenderer {
27
+ constructor() {
28
+ this.setupMarked();
29
+ }
30
+
31
+ setupMarked() {
32
+ const renderer = new marked.Renderer();
33
+
34
+ // Custom code block rendering with syntax highlighting
35
+ renderer.code = (code, language) => {
36
+ // Excalidraw diagram rendering — placeholder for async SVG fetch
37
+ if (language === 'excalidraw' || language === 'excalidraw-json') {
38
+ try {
39
+ const parsed = JSON.parse(code);
40
+ if (parsed.type === 'excalidraw' || (parsed.elements && Array.isArray(parsed.elements))) {
41
+ const id = 'excalidraw-' + Math.random().toString(36).substr(2, 9);
42
+ // base64 the JSON into a data attribute (like vega-lite below) rather
43
+ // than an inline <script> — DOMPurify strips <script>, and a data attr
44
+ // also sidesteps the markdown linkifier corrupting URLs in the spec.
45
+ const encoded = btoa(unescape(encodeURIComponent(code)));
46
+ return `
47
+ <div class="excalidraw-inline" id="${id}" data-excalidraw-json="${encoded}">
48
+ <div class="excalidraw-inline-loading">
49
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
50
+ <path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5L12 2Z"/>
51
+ </svg>
52
+ Rendering diagram...
53
+ </div>
54
+ </div>
55
+ `;
56
+ }
57
+ } catch { /* not valid excalidraw JSON, fall through to normal code block */ }
58
+ }
59
+
60
+ // Vega-Lite chart rendering — placeholder for async SVG fetch
61
+ // Uses base64 data attribute instead of <script> to prevent the markdown
62
+ // linkifier from corrupting URLs in the JSON (e.g., $schema field).
63
+ if (language === 'vega-lite' || language === 'vegalite') {
64
+ try {
65
+ const parsed = JSON.parse(code);
66
+ if (parsed.$schema?.includes('vega-lite') || parsed.mark || parsed.layer || parsed.hconcat || parsed.vconcat) {
67
+ const id = 'chart-' + Math.random().toString(36).substr(2, 9);
68
+ const encoded = btoa(unescape(encodeURIComponent(code)));
69
+ return `
70
+ <div class="chart-inline" id="${id}" data-chart-json="${encoded}">
71
+ <div class="chart-inline-loading">
72
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
73
+ <rect x="3" y="3" width="18" height="18" rx="2"/>
74
+ <path d="M3 15l4-4 3 3 4-6 7 7"/>
75
+ </svg>
76
+ Rendering chart...
77
+ </div>
78
+ </div>
79
+ `;
80
+ }
81
+ } catch { /* not valid Vega-Lite JSON, fall through to normal code block */ }
82
+ }
83
+
84
+ // Handle malformed code fences where language got concatenated with code
85
+ // e.g., "pythonproc = await..." instead of "python" + "proc = await..."
86
+ let lang = language || 'plaintext';
87
+ let actualCode = code;
88
+
89
+ // If language contains spaces, newlines, or is too long, it's likely malformed
90
+ if (lang && (lang.includes(' ') || lang.includes('\n') || lang.length > 20)) {
91
+ // Try to extract real language (first word) and prepend rest to code
92
+ const match = lang.match(/^([a-z]+)(.*)$/is);
93
+ if (match && match[1].length <= 15) {
94
+ const possibleLang = match[1].toLowerCase();
95
+ const rest = match[2];
96
+ // Check if it's a known language
97
+ if (hljs.getLanguage(possibleLang)) {
98
+ lang = possibleLang;
99
+ actualCode = rest + (rest && !rest.endsWith('\n') ? '\n' : '') + code;
100
+ } else {
101
+ lang = 'plaintext';
102
+ }
103
+ } else {
104
+ lang = 'plaintext';
105
+ }
106
+ }
107
+
108
+ // Fall back to plaintext for languages not in the hljs bundle
109
+ if (lang !== 'plaintext' && !hljs.getLanguage(lang)) {
110
+ lang = 'plaintext';
111
+ }
112
+
113
+ let highlighted;
114
+ try {
115
+ highlighted = hljs.highlight(actualCode, { language: lang, ignoreIllegals: true }).value;
116
+ } catch {
117
+ highlighted = hljs.highlightAuto(actualCode).value;
118
+ }
119
+
120
+ const id = 'code-' + Math.random().toString(36).substr(2, 9);
121
+ const wrapped = MarkdownRenderer.getCodeWrapPref();
122
+ return `
123
+ <div class="code-block-wrapper${wrapped ? ' wrapped' : ''}">
124
+ <div class="code-block-header">
125
+ <span class="code-block-lang">${escapeHtml(lang)}</span>
126
+ <button class="code-block-wrap wrap-toggle${wrapped ? ' active' : ''}" data-tooltip="${S.code_block.toggle_wrap}" aria-pressed="${wrapped}">
127
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
128
+ <path d="M3 6h18"/><path d="M3 12h15a3 3 0 1 1 0 6h-4"/><polyline points="16 16 14 18 16 20"/><path d="M3 18h7"/>
129
+ </svg>
130
+ </button>
131
+ <button class="code-block-copy" data-code-id="${id}" data-tooltip="${S.code_block.copy_code}">
132
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
133
+ <rect x="9" y="9" width="13" height="13" rx="2"/>
134
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
135
+ </svg>
136
+ </button>
137
+ </div>
138
+ <pre><code id="${id}" class="hljs language-${lang}">${highlighted}</code></pre>
139
+ </div>
140
+ `;
141
+ };
142
+
143
+ // Links open in new tab. Allow only safe protocols (defense-in-depth on
144
+ // top of DOMPurify) — reject javascript:/data:/vbscript: hrefs outright.
145
+ renderer.link = (href, title, text) => {
146
+ const safe = this.constructor.sanitizeHref(href);
147
+ // escapeAttr, not escapeHtml: both the href and the markdown link
148
+ // title are author-controlled, and escapeHtml leaves quotes intact
149
+ // — a title containing `"` could otherwise close the attribute and
150
+ // inject new ones. DOMPurify runs after this and would strip an
151
+ // injected handler, but that's the backstop, not the seatbelt.
152
+ return `<a href="${escapeAttr(safe)}" target="_blank" rel="noopener noreferrer"${title ? ` data-tooltip="${escapeAttr(title)}"` : ''}>${text}</a>`;
153
+ };
154
+
155
+ // Wrap tables in scrollable container. The extra .table-block around the
156
+ // scroller exists purely to anchor the layout switch: .table-wrapper is
157
+ // the overflow-x container, so a button positioned inside it would scroll
158
+ // away with the content and clip. Keep .table-wrapper's markup and CSS
159
+ // untouched — it's measured directly by markdown_table_wrap_test.json.
160
+ // Every table gets the switch. An earlier version gated it at 3+ columns
161
+ // on the theory that narrow tables aren't awkward enough to need it, but
162
+ // that made the control appear and disappear for no reason the reader can
163
+ // see — and text mode is genuinely useful on a 2-column table, which is
164
+ // exactly the label/value shape it renders.
165
+ renderer.table = (header, body) =>
166
+ `<div class="table-block"><div class="table-wrapper"><table><thead>${header}</thead><tbody>${body}</tbody></table></div>${MarkdownRenderer.layoutSwitchHtml()}</div>`;
167
+
168
+ marked.setOptions({
169
+ renderer,
170
+ gfm: true,
171
+ breaks: true,
172
+ headerIds: false,
173
+ });
174
+
175
+ MarkdownRenderer._installDelegation();
176
+ }
177
+
178
+ /**
179
+ * DOMPurify config for sanitizing rendered markdown. ALLOW_DATA_ATTR is true
180
+ * by default, so every attribute the renderer emits (data-source-start/end,
181
+ * data-selectable, data-chart-json, data-excalidraw-json, data-code-id,
182
+ * data-line-opts, data-resolved, data-tooltip) survives. ADD_ATTR keeps
183
+ * target=_blank on links.
184
+ */
185
+ static _PURIFY_CONFIG = { ADD_ATTR: ['target'] };
186
+
187
+ /**
188
+ * Sanitize rendered HTML before it reaches innerHTML. This is the single XSS
189
+ * gate for all markdown output — marked v4 passes raw HTML through verbatim,
190
+ * so without this a message body could inject same-origin script. Falls back
191
+ * to the raw string only if DOMPurify failed to load (script-tag order bug),
192
+ * which is logged loudly so it can't pass silently.
193
+ */
194
+ static sanitizeHtml(html) {
195
+ if (typeof DOMPurify === 'undefined' || typeof DOMPurify.sanitize !== 'function') {
196
+ // Fail CLOSED: never emit untrusted HTML. Degrade to escaped text
197
+ // so the content is still readable but inert.
198
+ console.error('DOMPurify not loaded — rendering as escaped text (fail-closed)');
199
+ return escapeHtml(html);
200
+ }
201
+ return DOMPurify.sanitize(html, MarkdownRenderer._PURIFY_CONFIG);
202
+ }
203
+
204
+ /**
205
+ * Scrub a markdown link href down to safe schemes. Defense-in-depth on top of
206
+ * DOMPurify: control chars are stripped first (defeats `jav&#9;ascript:` style
207
+ * bypasses) and any scheme outside the allowlist collapses to '#'.
208
+ *
209
+ * Returns a RAW, UNESCAPED url — scheme-checked, not attribute-safe. Every
210
+ * caller must wrap it in escapeAttr() before interpolating into an
211
+ * attribute; tests/test_no_unsafe_sinks.py enforces that at every href site.
212
+ *
213
+ * It used to return escapeHtml(cleaned), which read as safer and was
214
+ * actually worse in both directions. escapeHtml doesn't escape quotes, so
215
+ * the output was never attribute-safe on its own and callers still needed
216
+ * escapeAttr — and layering escapeAttr on top double-escaped `&`, so
217
+ * `?a=1&b=2` reached the DOM as `?a=1&amp;b=2` and the link resolved to the
218
+ * wrong URL. One escape, applied by the caller that knows the context, is
219
+ * the only arrangement that is both safe and correct.
220
+ */
221
+ static sanitizeHref(href) {
222
+ if (!href) return '#';
223
+ const cleaned = String(href).replace(/[\u0000-\u001F\u007F-\u009F]/g, '').trim();
224
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(cleaned);
225
+ if (scheme && !['http', 'https', 'mailto', 'tel', 'ftp'].includes(scheme[1].toLowerCase())) {
226
+ return '#';
227
+ }
228
+ return cleaned;
229
+ }
230
+
231
+ /**
232
+ * Code-block line-wrap preference. Wrapping is ON by default; the user's last
233
+ * choice is remembered in localStorage so it carries across renders and reloads.
234
+ * Stored as '0' (off) / '1' (on) — a missing key reads as on.
235
+ */
236
+ static _WRAP_KEY = 'code-block-wrap';
237
+
238
+ static getCodeWrapPref() {
239
+ try {
240
+ return localStorage.getItem(MarkdownRenderer._WRAP_KEY) !== '0';
241
+ } catch {
242
+ return true;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Flip the wrap preference, persist it, and apply it live to every wrappable
248
+ * block currently in the DOM. One preference drives wrapping everywhere in
249
+ * chat: markdown code blocks (`.code-block-wrapper`) and the monospace tool
250
+ * previews that default to `white-space: pre` (Read / Write blocks). Every
251
+ * toggle button carries the `.wrap-toggle` marker so its `.active` state and
252
+ * aria-pressed stay in sync no matter which one was clicked.
253
+ */
254
+ static toggleCodeWrap() {
255
+ MarkdownRenderer.setCodeWrap(!MarkdownRenderer.getCodeWrapPref());
256
+ }
257
+
258
+ /**
259
+ * Set the wrap preference explicitly, persist it, and apply it live to every
260
+ * wrappable block currently in the DOM. Used both by the per-block toggles
261
+ * (via toggleCodeWrap) and by the Settings → Appearance switch, so the two
262
+ * surfaces can never drift: there is one key and one apply path.
263
+ */
264
+ static setCodeWrap(enabled) {
265
+ const next = !!enabled;
266
+ try {
267
+ localStorage.setItem(MarkdownRenderer._WRAP_KEY, next ? '1' : '0');
268
+ } catch { /* private mode — preference just won't persist */ }
269
+ document.querySelectorAll('.code-block-wrapper, .read-block, .write-block, .edit-diff').forEach((el) => {
270
+ el.classList.toggle('wrapped', next);
271
+ });
272
+ document.querySelectorAll('.wrap-toggle').forEach((btn) => {
273
+ btn.classList.toggle('active', next);
274
+ btn.setAttribute('aria-pressed', String(next));
275
+ });
276
+ // Keep the Settings → Appearance switch honest if it happens to be open.
277
+ const settingsToggle = document.getElementById('code-block-wrap');
278
+ if (settingsToggle) settingsToggle.checked = next;
279
+ }
280
+
281
+ /**
282
+ * The three table layouts, in the order they appear in the switch. `table`
283
+ * is the plain grid and is the DEFAULT, represented by the absence of a
284
+ * data-layout attribute (keeps the CSS to [data-layout="..."] selectors
285
+ * only). `stacked` is the mysql-\G style label|value column pair, and
286
+ * `text` drops all table chrome for a prose report ("**label:** value") —
287
+ * the one you want when you'd rather read a table than cross-reference it.
288
+ */
289
+ static LAYOUTS = ['table', 'stacked', 'text'];
290
+
291
+ /** One glyph per layout, drawn to read as what it produces. */
292
+ static LAYOUT_ICONS = {
293
+ // Grid: header row + first column divider.
294
+ table: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18"/><path d="M9 9v12"/></svg>`,
295
+ // Stacked: short label paired with a long value, three times over.
296
+ stacked: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6h5"/><path d="M13 6h7"/><path d="M4 12h5"/><path d="M13 12h7"/><path d="M4 18h5"/><path d="M13 18h7"/></svg>`,
297
+ // Text: ragged prose lines.
298
+ text: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5h16"/><path d="M4 10h11"/><path d="M4 15h16"/><path d="M4 20h8"/></svg>`,
299
+ };
300
+
301
+ static layoutLabel(layout) {
302
+ return S.table?.[`layout_${layout}`] || `${layout} view`;
303
+ }
304
+
305
+ /**
306
+ * The layout switch: one segmented control of three connected buttons, the
307
+ * active segment highlighted. Deliberately NOT a single cycling button —
308
+ * a cycler can only ever show one state, so it can't tell you which layouts
309
+ * exist or which one you're in without being clicked to find out. Three
310
+ * segments make the whole vocabulary and the current selection readable at
311
+ * a glance, and let you jump straight to the layout you want.
312
+ */
313
+ static layoutSwitchHtml() {
314
+ const opts = MarkdownRenderer.LAYOUTS.map(layout => {
315
+ const label = MarkdownRenderer.layoutLabel(layout);
316
+ const active = layout === 'table';
317
+ return `<button class="table-layout-opt${active ? ' active' : ''}" data-layout-opt="${layout}" data-tooltip="${label}" aria-label="${label}" aria-pressed="${active}">${MarkdownRenderer.LAYOUT_ICONS[layout]}</button>`;
318
+ }).join('');
319
+ const groupLabel = S.table?.layout_switch_label || 'Table layout';
320
+ return `<div class="table-layout-switch" role="group" aria-label="${groupLabel}">${opts}</div>`;
321
+ }
322
+
323
+ /**
324
+ * Put ONE table into the layout its clicked segment names.
325
+ *
326
+ * Deliberately per-table and not persisted, unlike the global code-wrap
327
+ * preference: reformatting a table is a "show me *this* row set differently"
328
+ * gesture, and reformatting every table in a long transcript at once is
329
+ * almost never what you want. State is a data-layout attribute on the
330
+ * table's own .table-block, so nothing re-renders — same live-DOM approach
331
+ * as toggleCodeWrap.
332
+ */
333
+ static setTableLayout(btn) {
334
+ const block = btn.closest('.table-block');
335
+ const layout = btn.dataset.layoutOpt;
336
+ if (!block || !MarkdownRenderer.LAYOUTS.includes(layout)) return;
337
+ if ((block.dataset.layout || 'table') === layout) return;
338
+
339
+ MarkdownRenderer._prepareTableLayouts(block);
340
+ if (layout === 'table') delete block.dataset.layout;
341
+ else block.dataset.layout = layout;
342
+
343
+ // Repaint the whole group, not just the clicked segment — exactly one
344
+ // may be active.
345
+ btn.parentElement?.querySelectorAll('.table-layout-opt').forEach(opt => {
346
+ const on = opt.dataset.layoutOpt === layout;
347
+ opt.classList.toggle('active', on);
348
+ opt.setAttribute('aria-pressed', String(on));
349
+ });
350
+ }
351
+
352
+ /**
353
+ * One-time DOM prep shared by the stacked and text layouts, done on first
354
+ * switch rather than at render time. Two reasons: tables that are never flipped pay nothing,
355
+ * and there is exactly ONE place this can happen — a table feature split
356
+ * across render() and renderWithSourceMap() silently diverged for months
357
+ * once already (table rows had no stash bubbles at all in the previewer).
358
+ *
359
+ * Does two things per body cell:
360
+ *
361
+ * 1. Copies its column header onto it as data-label, which CSS prints via
362
+ * `content: attr(data-label)`. Generated content contributes nothing to
363
+ * textContent, and selection-handler reads element text raw (a row
364
+ * canonicalizes to cells.join(' | ')) — so selection, stash and copy
365
+ * produce identical text in both layouts. Same reasoning as the stash
366
+ * bubble's masked-svg glyph.
367
+ *
368
+ * 2. Wraps the cell's own content in a single .cell-value span. The
369
+ * stacked layout makes each cell a 2-column grid, and a grid container
370
+ * promotes EVERY child element plus every contiguous text run to its own
371
+ * grid item — so a cell like "Add `env=...` to the call" would explode
372
+ * into three items and spill the code span into the label gutter. One
373
+ * wrapper collapses it back to exactly [label, value]. The stash bubble
374
+ * is left outside the wrapper on purpose: it's position:absolute, so it
375
+ * is never a grid item, and moving it would break its cell anchoring.
376
+ *
377
+ * Scoped child selectors keep a nested table's rows from being labelled with
378
+ * the outer table's headers.
379
+ */
380
+ static _prepareTableLayouts(block) {
381
+ if (block.dataset.layoutReady) return;
382
+ block.dataset.layoutReady = '1';
383
+
384
+ block.querySelectorAll('table').forEach(table => {
385
+ const headRow = table.querySelector(':scope > thead > tr');
386
+ if (!headRow) return;
387
+ const labels = [...headRow.cells].map(c => c.textContent.trim());
388
+ // An all-blank header row carries nothing worth stacking.
389
+ if (!labels.some(Boolean)) return;
390
+
391
+ table.querySelectorAll(':scope > tbody > tr').forEach(tr => {
392
+ [...tr.cells].forEach((td, i) => {
393
+ // Ragged rows (more cells than headers) get '' and render
394
+ // full-width — see the [data-label=""] rules in 30-markdown.css.
395
+ td.setAttribute('data-label', labels[i] ?? '');
396
+ if (td.querySelector(':scope > .cell-value')) return;
397
+ const span = document.createElement('span');
398
+ span.className = 'cell-value';
399
+ // Leave out-of-flow chrome where it is: the stash bubble is
400
+ // absolutely positioned against this cell, and the previewer's
401
+ // inline-edit trash button is its own control.
402
+ [...td.childNodes]
403
+ .filter(n => !(n.nodeType === 1 &&
404
+ (n.classList?.contains('stash-bubble') || n.tagName === 'BUTTON')))
405
+ .forEach(n => span.appendChild(n));
406
+ td.insertBefore(span, td.firstChild);
407
+ });
408
+ });
409
+ });
410
+ }
411
+
412
+ /**
413
+ * One document-level click delegate for the interactive chrome the renderer
414
+ * emits — the code-block wrap toggle, copy button, and clickable file paths.
415
+ * Inline onclick handlers were removed so DOMPurify can strip all event
416
+ * attributes; the data they need already lives in data-* attributes.
417
+ */
418
+ static _installDelegation() {
419
+ if (MarkdownRenderer._delegationInstalled) return;
420
+ MarkdownRenderer._delegationInstalled = true;
421
+
422
+ document.addEventListener('click', (event) => {
423
+ const wrapBtn = event.target.closest?.('.wrap-toggle');
424
+ if (wrapBtn) {
425
+ MarkdownRenderer.toggleCodeWrap();
426
+ return;
427
+ }
428
+ const layoutOpt = event.target.closest?.('.table-layout-opt');
429
+ if (layoutOpt) {
430
+ MarkdownRenderer.setTableLayout(layoutOpt);
431
+ return;
432
+ }
433
+ const copyBtn = event.target.closest?.('.code-block-copy');
434
+ if (copyBtn) {
435
+ if (copyBtn.dataset.codeId) window.app?.copyCode(copyBtn.dataset.codeId);
436
+ return;
437
+ }
438
+ const fileLink = event.target.closest?.('.file-path-link');
439
+ if (fileLink) {
440
+ // Links carrying data-act are owned by the action-delegate
441
+ // (tool-renderer file links, which may call previewFile rather
442
+ // than openFileLink). Only markdown-linkified paths — which
443
+ // have no data-act — are handled here.
444
+ if (fileLink.dataset.act) return;
445
+ event.preventDefault();
446
+ let opts = {};
447
+ try {
448
+ opts = fileLink.dataset.lineOpts ? JSON.parse(fileLink.dataset.lineOpts) : {};
449
+ } catch { /* malformed opts — open without line targeting */ }
450
+ // data-resolved (verified path) preferred; data-file is the
451
+ // fallback for tool-renderer links that carry only the raw
452
+ // path. Those links used to have their own inline onclick and
453
+ // double-fired this delegate; now this is their only handler.
454
+ const target = fileLink.dataset.resolved || fileLink.dataset.file;
455
+ if (target) {
456
+ window.app?.openFileLink(target, opts, event);
457
+ }
458
+ }
459
+ });
460
+ }
461
+
462
+ render(text, verifiedFiles = null) {
463
+ try {
464
+ let html = marked.parse(text);
465
+ // Post-process to make file paths clickable
466
+ html = this.linkifyFilePaths(html, verifiedFiles);
467
+ // Add selectable markers for tap-to-select on touch devices
468
+ html = this.addSelectableMarkers(html);
469
+ return MarkdownRenderer.sanitizeHtml(html);
470
+ } catch (e) {
471
+ console.error('Markdown error:', e);
472
+ return escapeHtml(text);
473
+ }
474
+ }
475
+
476
+ /**
477
+ * Render markdown with source map annotations.
478
+ * Each block-level element gets data-source-start and data-source-end
479
+ * attributes indicating byte offsets into the original source string.
480
+ * Used by the file preview inline editor to map clicks → source positions.
481
+ *
482
+ * baseOffset shifts all recorded offsets — pass it when `source` is a
483
+ * substring of the real document (e.g. body after stripped front matter)
484
+ * so offsets still index into the full original content.
485
+ */
486
+ renderWithSourceMap(source, baseOffset = 0) {
487
+ try {
488
+ const tokens = marked.lexer(source);
489
+ const sourceMap = this._buildSourceMap(source, tokens);
490
+ const tableRowMap = this._buildTableRowMap(source, tokens);
491
+ if (baseOffset) {
492
+ for (const entry of [...sourceMap, ...tableRowMap]) {
493
+ entry.start += baseOffset;
494
+ entry.end += baseOffset;
495
+ }
496
+ }
497
+ let html = marked.parser(tokens);
498
+ html = this.linkifyFilePaths(html, null);
499
+ html = this._addSelectableMarkersWithSourceMap(html, sourceMap, tableRowMap);
500
+ return MarkdownRenderer.sanitizeHtml(html);
501
+ } catch (e) {
502
+ console.error('Markdown renderWithSourceMap error:', e);
503
+ return this.render(source);
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Walk marked tokens and compute source byte offsets for each block element.
509
+ * Returns flat array of {type, start, end} in document order.
510
+ *
511
+ * Key challenge: nested lists. marked v4 stores nested sub-lists inside
512
+ * item.tokens, so we must recurse into each item's token stream.
513
+ * We track offset per recursion level to avoid searchFrom drift.
514
+ */
515
+ _buildSourceMap(source, tokens) {
516
+ const entries = [];
517
+
518
+ // Walk top-level tokens — each token.raw is the exact source text for that block.
519
+ // For lists, only map direct (top-level) items. Nested list items have
520
+ // de-indented raw text that can't be reliably found via indexOf, so they
521
+ // fall back to fuzzy matching in the inline editor.
522
+ let searchFrom = 0;
523
+ for (const token of tokens) {
524
+ const type = token.type;
525
+ if (!token.raw) continue;
526
+
527
+ const idx = source.indexOf(token.raw, searchFrom);
528
+ if (idx === -1) continue;
529
+ const end = idx + token.raw.length;
530
+
531
+ if (type === 'heading' || type === 'paragraph' || type === 'blockquote') {
532
+ entries.push({ type, start: idx, end });
533
+ } else if (type === 'list' && token.items) {
534
+ // Only top-level items — their raw IS found verbatim in the source
535
+ let cursor = idx;
536
+ for (const item of token.items) {
537
+ if (!item.raw) continue;
538
+ const itemIdx = source.indexOf(item.raw, cursor);
539
+ if (itemIdx === -1) continue;
540
+ entries.push({ type: 'list_item', start: itemIdx, end: itemIdx + item.raw.length });
541
+ cursor = itemIdx + item.raw.length;
542
+ }
543
+ }
544
+ searchFrom = end;
545
+ }
546
+
547
+ return entries;
548
+ }
549
+
550
+ /**
551
+ * Like addSelectableMarkers but also injects data-source-start/end from sourceMap.
552
+ * DOM elements and sourceMap entries are both in document order, so we zip them.
553
+ *
554
+ * Key subtlety: marked renders <blockquote><p>text</p></blockquote>, so
555
+ * a TreeWalker sees both <blockquote> and inner <p>. But the source map
556
+ * only has a 'blockquote' entry (not a nested 'paragraph'). We must skip
557
+ * inner <p> elements within blockquotes to keep the zip aligned.
558
+ */
559
+ _addSelectableMarkersWithSourceMap(html, sourceMap, tableRowMap = null) {
560
+ const template = document.createElement('template');
561
+ template.innerHTML = html.trim();
562
+ const doc = template.content;
563
+
564
+ // Collect block elements in document order, filtering to only elements
565
+ // that have source map entries:
566
+ // - headings, paragraphs (not inside blockquotes), blockquotes
567
+ // - top-level <li> only (not nested inside another <li>)
568
+ const blockEls = [];
569
+ const walker = document.createTreeWalker(doc, NodeFilter.SHOW_ELEMENT, {
570
+ acceptNode(node) {
571
+ const tag = node.tagName?.toLowerCase();
572
+ if (tag === 'p' && node.closest('blockquote')) {
573
+ return NodeFilter.FILTER_SKIP;
574
+ }
575
+ if (tag === 'li' && node.parentElement?.closest('li')) {
576
+ return NodeFilter.FILTER_SKIP;
577
+ }
578
+ if (/^h[1-6]$/.test(tag) || tag === 'p' || tag === 'li' || tag === 'blockquote') {
579
+ return NodeFilter.FILTER_ACCEPT;
580
+ }
581
+ return NodeFilter.FILTER_SKIP;
582
+ }
583
+ });
584
+ while (walker.nextNode()) {
585
+ blockEls.push(walker.currentNode);
586
+ }
587
+
588
+ // Zip: match DOM elements to sourceMap entries.
589
+ // Both are in document order, so we advance through both lists together.
590
+ // Only skip a few entries on type mismatch to avoid catastrophic drift.
591
+ let mapIdx = 0;
592
+ for (const el of blockEls) {
593
+ if (mapIdx >= sourceMap.length) break;
594
+ const tag = el.tagName.toLowerCase();
595
+
596
+ let expectedType;
597
+ if (/^h[1-6]$/.test(tag)) expectedType = 'heading';
598
+ else if (tag === 'p') expectedType = 'paragraph';
599
+ else if (tag === 'li') expectedType = 'list_item';
600
+ else if (tag === 'blockquote') expectedType = 'blockquote';
601
+
602
+ // Look ahead at most 3 entries for a type match to prevent drift
603
+ let found = -1;
604
+ for (let look = 0; look < 3 && mapIdx + look < sourceMap.length; look++) {
605
+ if (sourceMap[mapIdx + look].type === expectedType) {
606
+ found = mapIdx + look;
607
+ break;
608
+ }
609
+ }
610
+
611
+ if (found !== -1) {
612
+ const entry = sourceMap[found];
613
+ el.setAttribute('data-source-start', entry.start);
614
+ el.setAttribute('data-source-end', entry.end);
615
+ mapIdx = found + 1;
616
+ }
617
+
618
+ // Always add selectable markers regardless of source map match
619
+ if (tag === 'li') {
620
+ el.setAttribute('data-selectable', 'bullet');
621
+ } else if (tag === 'blockquote') {
622
+ el.setAttribute('data-selectable', 'quote');
623
+ } else if (/^h[1-6]$/.test(tag)) {
624
+ el.setAttribute('data-selectable', 'heading');
625
+ } else if (tag === 'p') {
626
+ this.processParagraphSentences(el);
627
+ }
628
+ }
629
+
630
+ // Handle remaining elements not in blockEls
631
+ doc.querySelectorAll('p:not([data-selectable])').forEach(p => {
632
+ this.processParagraphSentences(p);
633
+ });
634
+ doc.querySelectorAll('li:not([data-selectable])').forEach(li => {
635
+ li.setAttribute('data-selectable', 'bullet');
636
+ });
637
+ doc.querySelectorAll('blockquote:not([data-selectable])').forEach(bq => {
638
+ bq.setAttribute('data-selectable', 'quote');
639
+ });
640
+
641
+ // Table rows are marked on their own pass (they're deliberately absent
642
+ // from blockEls/sourceMap so they can't drift the zip above) and get
643
+ // their source offsets from the independent tableRowMap.
644
+ this._markTableRows(doc, tableRowMap);
645
+ this._appendStashBubbles(doc);
646
+
647
+ const wrapper = document.createElement('div');
648
+ wrapper.appendChild(doc);
649
+ return wrapper.innerHTML;
650
+ }
651
+
652
+ /**
653
+ * Mark <tbody> rows as selectable so each row gets its own stash bubble.
654
+ * Shared by BOTH render paths — addSelectableMarkers() (chat messages) and
655
+ * _addSelectableMarkersWithSourceMap() (file-preview rendered view). Keep it
656
+ * that way: table rows were originally only marked on the chat path, which
657
+ * silently left markdown tables in the file previewer with no bubbles at all.
658
+ *
659
+ * @param {DocumentFragment} doc
660
+ * @param {Array<{start:number,end:number}>|null} tableRowMap - optional
661
+ * per-row source offsets, zipped 1:1 in document order. Applied only
662
+ * when the count matches exactly (a table nested in a blockquote or
663
+ * list isn't in the map, so a mismatch means "don't guess").
664
+ */
665
+ _markTableRows(doc, tableRowMap = null) {
666
+ const rows = doc.querySelectorAll('tbody tr');
667
+ const canMap = Array.isArray(tableRowMap) && tableRowMap.length === rows.length;
668
+ rows.forEach((tr, i) => {
669
+ tr.setAttribute('data-selectable', 'table-row');
670
+ if (canMap) {
671
+ tr.setAttribute('data-source-start', tableRowMap[i].start);
672
+ tr.setAttribute('data-source-end', tableRowMap[i].end);
673
+ }
674
+ });
675
+ }
676
+
677
+ /**
678
+ * Byte offsets for every GFM table *body* row, in document order.
679
+ * Kept separate from _buildSourceMap so a 20-row table can't push the
680
+ * heading/paragraph/list zip past its 3-entry lookahead window.
681
+ * Only top-level tables are walked — same reasoning as nested lists.
682
+ */
683
+ _buildTableRowMap(source, tokens) {
684
+ const entries = [];
685
+ let searchFrom = 0;
686
+ for (const token of tokens) {
687
+ if (!token.raw) continue;
688
+ const idx = source.indexOf(token.raw, searchFrom);
689
+ if (idx === -1) continue;
690
+ const end = idx + token.raw.length;
691
+ searchFrom = end;
692
+ if (token.type !== 'table') continue;
693
+
694
+ // A GFM table's raw is: header line, delimiter line, then one line
695
+ // per body row. Walk the raw line-by-line and record the data rows.
696
+ let cursor = idx;
697
+ let lineNo = 0;
698
+ for (const line of token.raw.split('\n')) {
699
+ const lineStart = cursor;
700
+ cursor += line.length + 1; // +1 for the consumed '\n'
701
+ lineNo++;
702
+ if (lineNo <= 2) continue; // header + delimiter
703
+ if (!line.trim()) continue; // trailing blank line
704
+ entries.push({ type: 'table_row', start: lineStart, end: lineStart + line.length });
705
+ }
706
+ }
707
+ return entries;
708
+ }
709
+
710
+ /**
711
+ * Add selectable markers to elements for tap-to-select on touch devices.
712
+ * Adds data-selectable attributes and wraps sentences for easy selection.
713
+ * @param {string} html - HTML to process
714
+ */
715
+ addSelectableMarkers(html) {
716
+ // Parse HTML into DOM
717
+ const template = document.createElement('template');
718
+ template.innerHTML = html.trim();
719
+ const doc = template.content;
720
+
721
+ // PERF: Single querySelectorAll with combined selector for simple elements
722
+ // This reduces 4 DOM scans to 2 (one for simple attrs, one for complex paragraphs)
723
+ doc.querySelectorAll('li, blockquote, h1, h2, h3, h4, h5, h6').forEach(el => {
724
+ const tag = el.tagName.toLowerCase();
725
+ if (tag === 'li') {
726
+ el.setAttribute('data-selectable', 'bullet');
727
+ } else if (tag === 'blockquote') {
728
+ el.setAttribute('data-selectable', 'quote');
729
+ } else {
730
+ el.setAttribute('data-selectable', 'heading');
731
+ }
732
+ });
733
+
734
+ // Process paragraphs - try sentence-level splitting (needs separate pass)
735
+ doc.querySelectorAll('p').forEach(p => {
736
+ this.processParagraphSentences(p);
737
+ });
738
+
739
+ this._markTableRows(doc);
740
+ this._appendStashBubbles(doc);
741
+
742
+ // Serialize back to HTML
743
+ const wrapper = document.createElement('div');
744
+ wrapper.appendChild(doc);
745
+ return wrapper.innerHTML;
746
+ }
747
+
748
+ /**
749
+ * Append a real <span class="stash-bubble"> to every [data-selectable] so
750
+ * the bubble icon can carry data-tooltip and have its own :hover.
751
+ * The glyph is drawn by CSS ::before — a masked svg tinted with
752
+ * background-color (see 30-markdown.css), so it contributes no text and
753
+ * stays out of parent.textContent (selection-handler captures element text
754
+ * raw). It is deliberately NOT an emoji: emoji render in their own fixed
755
+ * colours, so the "has a comment" state couldn't just switch colour.
756
+ * Table rows put the bubble in their LAST CELL (a <tr> can't be a
757
+ * positioning context), tagged with data-stash-cell so CSS and the
758
+ * selection handler can find it without positional guessing. Do NOT go back
759
+ * to `td:last-child`/lastElementChild here: the file-preview widget appends
760
+ * an inline-edit trash <button> as a direct child of the <tr>, which makes
761
+ * the last *child* a BUTTON — that silently broke the bubble's CSS (no
762
+ * position:relative, no hover rule → invisible/mispositioned bubbles) and
763
+ * the has-stash lookup on every table in the previewer.
764
+ */
765
+ _appendStashBubbles(doc) {
766
+ const tipText = S?.ui?.stash?.bubble_tooltip || 'Click to add comment';
767
+ doc.querySelectorAll('[data-selectable]').forEach(el => {
768
+ if (el.tagName === 'TR' && el.dataset.selectable === 'table-row') {
769
+ // el.cells is td+th only, always direct children — trailing
770
+ // non-cell elements can't confuse it.
771
+ const lastCell = el.cells?.[el.cells.length - 1];
772
+ if (lastCell) {
773
+ lastCell.setAttribute('data-stash-cell', '');
774
+ if (!lastCell.querySelector(':scope > .stash-bubble')) {
775
+ lastCell.appendChild(this._buildStashBubble(tipText));
776
+ }
777
+ }
778
+ return;
779
+ }
780
+ if (!el.querySelector(':scope > .stash-bubble')) {
781
+ el.appendChild(this._buildStashBubble(tipText));
782
+ }
783
+ });
784
+ }
785
+
786
+ _buildStashBubble(tipText) {
787
+ const bubble = document.createElement('span');
788
+ bubble.className = 'stash-bubble';
789
+ bubble.setAttribute('data-tooltip', tipText);
790
+ bubble.setAttribute('aria-hidden', 'true');
791
+ return bubble;
792
+ }
793
+
794
+ /**
795
+ * Process a paragraph for sentence-level selection.
796
+ * If paragraph has complex inline elements, marks whole paragraph.
797
+ * Otherwise splits into sentences.
798
+ * @param {HTMLElement} p - Paragraph element
799
+ */
800
+ processParagraphSentences(p) {
801
+ // Skip if paragraph is inside a blockquote (already selectable)
802
+ if (p.closest('blockquote')) return;
803
+
804
+ // Check if paragraph has complex inline elements that would break splitting
805
+ const hasComplexInline = p.querySelector('a, pre, code, img');
806
+
807
+ if (hasComplexInline) {
808
+ // Too complex for sentence splitting, mark whole paragraph
809
+ p.setAttribute('data-selectable', 'paragraph');
810
+ return;
811
+ }
812
+
813
+ // Get text content for sentence detection
814
+ const text = p.textContent.trim();
815
+ if (!text) return;
816
+
817
+ // Split into sentences using regex
818
+ // Matches: .!? followed by space(s) and capital letter or quote
819
+ // Avoids splitting after common abbreviations
820
+ const sentences = this.splitIntoSentences(text);
821
+
822
+ if (sentences.length <= 1) {
823
+ // Single sentence, mark whole paragraph
824
+ p.setAttribute('data-selectable', 'sentence');
825
+ return;
826
+ }
827
+
828
+ // Multiple sentences - check if we can safely split
829
+ // Only split if paragraph has no inline elements (just text)
830
+ if (p.children.length > 0) {
831
+ // Has inline elements like <strong>, <em> - mark whole paragraph
832
+ p.setAttribute('data-selectable', 'paragraph');
833
+ return;
834
+ }
835
+
836
+ // Pure text paragraph - wrap each sentence
837
+ p.textContent = ''; // Clear
838
+ sentences.forEach((sentence, i) => {
839
+ const span = document.createElement('span');
840
+ span.setAttribute('data-selectable', 'sentence');
841
+ span.textContent = sentence.trim();
842
+ p.appendChild(span);
843
+ if (i < sentences.length - 1) {
844
+ p.appendChild(document.createTextNode(' '));
845
+ }
846
+ });
847
+ }
848
+
849
+ /**
850
+ * Split text into sentences.
851
+ * @param {string} text - Plain text to split
852
+ * @returns {string[]} Array of sentences
853
+ */
854
+ splitIntoSentences(text) {
855
+ // Sentence-ending pattern:
856
+ // - Period, exclamation, or question mark
857
+ // - Followed by one or more spaces
858
+ // - Followed by capital letter, quote, or number
859
+ // Negative lookbehind to avoid splitting after abbreviations
860
+ const pattern = /(?<![A-Z][a-z]|Mr|Mrs|Ms|Dr|Jr|Sr|vs|etc|e\.g|i\.e|[0-9])\.\s+(?=[A-Z"'\d])|(?<=[!?])\s+(?=[A-Z"'])/g;
861
+
862
+ const parts = text.split(pattern);
863
+ return parts.filter(s => s && s.trim().length > 0);
864
+ }
865
+
866
+ /**
867
+ * Convert file paths in text to clickable preview links.
868
+ * Skips content inside <pre> (code blocks) and <a> (already linked).
869
+ * Uses server-side verifiedFiles map to determine which paths exist.
870
+ * @param {string} html - HTML to process
871
+ * @param {Object|null} verifiedFiles - Map of {filename: resolvedPath|null} from server
872
+ */
873
+ linkifyFilePaths(html, verifiedFiles = null) {
874
+ // Track tag nesting to skip a tags (avoid nested links)
875
+ // Note: We DO linkify inside <pre> (code blocks) since paths are server-verified
876
+ const tagStack = [];
877
+ const skipTags = new Set(['a']);
878
+ let result = '';
879
+ let lastIndex = 0;
880
+
881
+ // Match all HTML tags
882
+ const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9]*)[^>]*>/g;
883
+ let tagMatch;
884
+
885
+ while ((tagMatch = tagRegex.exec(html)) !== null) {
886
+ // Process text before this tag
887
+ const textBefore = html.slice(lastIndex, tagMatch.index);
888
+
889
+ // Only linkify if we're not inside a skip tag
890
+ const inSkipTag = tagStack.some(t => skipTags.has(t.toLowerCase()));
891
+ if (!inSkipTag && textBefore) {
892
+ result += this.linkifyPathsInText(textBefore, verifiedFiles);
893
+ } else {
894
+ result += textBefore;
895
+ }
896
+
897
+ // Add the tag itself
898
+ result += tagMatch[0];
899
+
900
+ // Update tag stack
901
+ const tagName = tagMatch[1].toLowerCase();
902
+ if (tagMatch[0].startsWith('</')) {
903
+ // Closing tag
904
+ const idx = tagStack.lastIndexOf(tagName);
905
+ if (idx !== -1) tagStack.splice(idx, 1);
906
+ } else if (!tagMatch[0].endsWith('/>')) {
907
+ // Opening tag (not self-closing)
908
+ tagStack.push(tagName);
909
+ }
910
+
911
+ lastIndex = tagMatch.index + tagMatch[0].length;
912
+ }
913
+
914
+ // Process remaining text after last tag
915
+ const remaining = html.slice(lastIndex);
916
+ const inSkipTag = tagStack.some(t => skipTags.has(t.toLowerCase()));
917
+ if (!inSkipTag && remaining) {
918
+ result += this.linkifyPathsInText(remaining, verifiedFiles);
919
+ } else {
920
+ result += remaining;
921
+ }
922
+
923
+ return result;
924
+ }
925
+
926
+ /**
927
+ * Linkify file paths and URLs within a text segment (no HTML tags).
928
+ * Uses position tracking to avoid overlapping matches.
929
+ * File paths are ONLY linked when server-verified (no client-side fallback).
930
+ * URLs are always linked (no verification needed).
931
+ * @param {string} text - Text to process
932
+ * @param {Object|null} verifiedFiles - Map of {filename: resolvedPath|null} from server. Required for file links.
933
+ */
934
+ linkifyPathsInText(text, verifiedFiles = null) {
935
+ const replacements = []; // [{start, end, html}]
936
+
937
+ // 1. Find URLs first (higher priority)
938
+ const urlPattern = buildUrlPattern();
939
+ let match;
940
+ while ((match = urlPattern.exec(text)) !== null) {
941
+ let url = match[0];
942
+ const cleaned = cleanUrlTrailingPunct(url);
943
+ url = cleaned.url;
944
+ const end = match.index + url.length;
945
+
946
+ // Decode HTML entities (text is already escaped by markdown parser)
947
+ // e.g., &amp; -> & so URLs work correctly
948
+ const decodedUrl = decodeHtml(url);
949
+ // Re-escape per context: the href needs quote-safety plus a scheme
950
+ // check (escapeHtml alone gave neither), the link text only needs
951
+ // element-content escaping. Same string, two different escapes —
952
+ // reusing one value for both was the bug shape this gate exists to
953
+ // catch, it just evaded the grep by living on an earlier line.
954
+ const safeHref = escapeAttr(MarkdownRenderer.sanitizeHref(decodedUrl));
955
+ const escapedUrl = escapeHtml(decodedUrl);
956
+ replacements.push({
957
+ start: match.index,
958
+ end: end,
959
+ html: `<a href="${safeHref}" class="external-link" target="_blank" rel="noopener noreferrer">${escapedUrl}</a>`
960
+ });
961
+ }
962
+
963
+ // 2. Find file paths (skip positions covered by URLs)
964
+ const pathPattern = buildPathPattern();
965
+
966
+ while ((match = pathPattern.exec(text)) !== null) {
967
+ const path = match[1];
968
+ const lineInfo = match[2] || '';
969
+ const fullMatch = match[0];
970
+
971
+ // Skip invalid paths
972
+ if (!path.includes('/')) continue;
973
+ if (/^\d+\.\d+/.test(path)) continue;
974
+ if (/^\d+\/\d+/.test(path)) continue;
975
+
976
+ // Only create links for server-verified files (no client-side fallback)
977
+ if (!verifiedFiles) continue;
978
+ const resolvedPath = verifiedFiles[path];
979
+ if (!resolvedPath) continue;
980
+
981
+ // Check for overlap with URL replacements
982
+ const overlaps = replacements.some(r =>
983
+ (match.index < r.end && match.index + fullMatch.length > r.start)
984
+ );
985
+ if (overlaps) continue;
986
+
987
+ const fullDisplay = lineInfo ? path + lineInfo : path;
988
+
989
+ // Parse line info into options for preview
990
+ const lineOpts = parseLineInfo(lineInfo);
991
+ const optsJson = lineOpts ? JSON.stringify(lineOpts).replace(/"/g, '&quot;') : '';
992
+ const optsAttr = optsJson ? ` data-line-opts="${optsJson}"` : '';
993
+
994
+ replacements.push({
995
+ start: match.index,
996
+ end: match.index + fullMatch.length,
997
+ html: `<a href="#" class="file-path-link" data-file="${escapeHtml(path)}" data-resolved="${escapeHtml(resolvedPath)}" data-tooltip="${escapeHtml(resolvedPath)}"${optsAttr}>${escapeHtml(fullDisplay)}</a>`
998
+ });
999
+ }
1000
+
1001
+ // 3. Match standalone filenames (e.g., server.py, CLAUDE.md)
1002
+ // Server verification eliminates false positives, so no inInlineCode restriction needed
1003
+ const standalonePattern = buildStandalonePattern();
1004
+
1005
+ while ((match = standalonePattern.exec(text)) !== null) {
1006
+ const filename = match[1];
1007
+ const lineInfo = match[2] || '';
1008
+ const fullMatch = match[0];
1009
+
1010
+ // Get preceding text for context validation
1011
+ const precedingText = text.slice(Math.max(0, match.index - 20), match.index);
1012
+
1013
+ // Validate the match to reduce false positives
1014
+ if (!isValidStandaloneFile(filename, precedingText)) {
1015
+ continue;
1016
+ }
1017
+
1018
+ // Only create links for server-verified files (no client-side fallback)
1019
+ if (!verifiedFiles) continue;
1020
+ const resolvedPath = verifiedFiles[filename];
1021
+ if (!resolvedPath) continue;
1022
+
1023
+ // Check for overlap with existing replacements
1024
+ const overlaps = replacements.some(r =>
1025
+ (match.index < r.end && match.index + fullMatch.length > r.start)
1026
+ );
1027
+ if (overlaps) continue;
1028
+
1029
+ const fullDisplay = lineInfo ? filename + lineInfo : filename;
1030
+
1031
+ // Parse line info into options for preview
1032
+ const lineOpts = parseLineInfo(lineInfo);
1033
+ const optsJson = lineOpts ? JSON.stringify(lineOpts).replace(/"/g, '&quot;') : '';
1034
+ const optsAttr = optsJson ? ` data-line-opts="${optsJson}"` : '';
1035
+
1036
+ replacements.push({
1037
+ start: match.index,
1038
+ end: match.index + fullMatch.length,
1039
+ html: `<a href="#" class="file-path-link" data-file="${escapeHtml(filename)}" data-resolved="${escapeHtml(resolvedPath)}" data-tooltip="${escapeHtml(resolvedPath)}"${optsAttr}>${escapeHtml(fullDisplay)}</a>`
1040
+ });
1041
+ }
1042
+
1043
+ // 4. Sort by position (descending) and apply replacements
1044
+ replacements.sort((a, b) => b.start - a.start);
1045
+ for (const r of replacements) {
1046
+ text = text.slice(0, r.start) + r.html + text.slice(r.end);
1047
+ }
1048
+
1049
+ return text;
1050
+ }
1051
+
1052
+ /**
1053
+ * Process excalidraw placeholder blocks after DOM insertion.
1054
+ * Finds unprocessed .excalidraw-inline elements, fetches SVG from server,
1055
+ * and replaces the loading state with the rendered diagram.
1056
+ * @param {HTMLElement} container - DOM element to scan for excalidraw blocks
1057
+ */
1058
+ /**
1059
+ * Server-side chart/excalidraw rendering gate. Off unless the server
1060
+ * injected `renderers_enabled: true` (it defaults off — model-authored
1061
+ * specs render via a Node subprocess with an SSRF-capable data loader).
1062
+ * @returns {boolean}
1063
+ */
1064
+ static renderersEnabled() {
1065
+ return window.INSTANCE_CONFIG?.renderers_enabled === true;
1066
+ }
1067
+
1068
+ static processExcalidrawBlocks(container) {
1069
+ const blocks = container.querySelectorAll('.excalidraw-inline:not([data-rendered])');
1070
+ if (blocks.length === 0) return;
1071
+
1072
+ blocks.forEach(block => {
1073
+ block.setAttribute('data-rendered', 'true');
1074
+
1075
+ // Decode base64-encoded JSON from data attribute
1076
+ // (stored as base64 so DOMPurify keeps it and the linkifier can't corrupt it)
1077
+ const encoded = block.dataset.excalidrawJson;
1078
+ if (!encoded) return;
1079
+
1080
+ let jsonText;
1081
+ try {
1082
+ jsonText = decodeURIComponent(escape(atob(encoded)));
1083
+ } catch {
1084
+ return;
1085
+ }
1086
+
1087
+ // Rendering disabled: show an inert notice, never POST the spec.
1088
+ if (!MarkdownRenderer.renderersEnabled()) {
1089
+ block.innerHTML = `
1090
+ <div class="excalidraw-inline-error">
1091
+ <span>${escapeHtml(S.tool_renderer.errors.diagram_disabled)}</span>
1092
+ </div>
1093
+ `;
1094
+ return;
1095
+ }
1096
+
1097
+ fetch('/api/excalidraw/render', {
1098
+ method: 'POST',
1099
+ headers: { 'Content-Type': 'application/json' },
1100
+ body: jsonText,
1101
+ })
1102
+ .then(resp => {
1103
+ if (!resp.ok) throw new Error(`Render failed: ${resp.status}`);
1104
+ return resp.text();
1105
+ })
1106
+ .then(svg => {
1107
+ block.innerHTML = `
1108
+ <div class="excalidraw-inline-rendered">
1109
+ <div class="excalidraw-inline-svg">${sanitizeSvg(svg)}</div>
1110
+ <div class="excalidraw-inline-actions">
1111
+ <button class="excalidraw-copy-btn" data-tooltip="Copy JSON">
1112
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1113
+ <rect x="9" y="9" width="13" height="13" rx="2"/>
1114
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
1115
+ </svg>
1116
+ </button>
1117
+ </div>
1118
+ </div>
1119
+ `;
1120
+ // Store JSON for copy action
1121
+ block._excalidrawJson = jsonText;
1122
+ block.querySelector('.excalidraw-copy-btn')?.addEventListener('click', () => {
1123
+ navigator.clipboard.writeText(jsonText).then(() => {
1124
+ const btn = block.querySelector('.excalidraw-copy-btn');
1125
+ if (btn) { btn.setAttribute('data-tooltip', 'Copied!'); setTimeout(() => btn.setAttribute('data-tooltip', 'Copy JSON'), 1500); }
1126
+ });
1127
+ });
1128
+ })
1129
+ .catch(err => {
1130
+ console.error('Excalidraw render error:', err);
1131
+ block.innerHTML = `
1132
+ <div class="excalidraw-inline-error">
1133
+ <span>Failed to render diagram: ${escapeHtml(err.message)}</span>
1134
+ </div>
1135
+ `;
1136
+ });
1137
+ });
1138
+ }
1139
+
1140
+ /**
1141
+ * Process Vega-Lite chart placeholder blocks after DOM insertion.
1142
+ * Finds unprocessed .chart-inline elements, fetches SVG from server,
1143
+ * and replaces the loading state with the rendered chart.
1144
+ * @param {HTMLElement} container - DOM element to scan for chart blocks
1145
+ */
1146
+ static processChartBlocks(container) {
1147
+ const blocks = container.querySelectorAll('.chart-inline:not([data-rendered])');
1148
+ if (blocks.length === 0) return;
1149
+
1150
+ blocks.forEach(block => {
1151
+ block.setAttribute('data-rendered', 'true');
1152
+
1153
+ // Decode base64-encoded JSON from data attribute
1154
+ // (stored as base64 to prevent linkifier from corrupting URLs in the spec)
1155
+ const encoded = block.dataset.chartJson;
1156
+ if (!encoded) return;
1157
+
1158
+ let jsonText;
1159
+ try {
1160
+ jsonText = decodeURIComponent(escape(atob(encoded)));
1161
+ } catch {
1162
+ return;
1163
+ }
1164
+
1165
+ // Rendering disabled: show an inert notice, never POST the spec.
1166
+ if (!MarkdownRenderer.renderersEnabled()) {
1167
+ block.innerHTML = `
1168
+ <div class="chart-inline-error">
1169
+ <span>${escapeHtml(S.tool_renderer.errors.chart_disabled)}</span>
1170
+ </div>
1171
+ `;
1172
+ return;
1173
+ }
1174
+
1175
+ fetch('/api/chart/render', {
1176
+ method: 'POST',
1177
+ headers: { 'Content-Type': 'application/json' },
1178
+ body: jsonText,
1179
+ })
1180
+ .then(resp => {
1181
+ if (!resp.ok) throw new Error(`Render failed: ${resp.status}`);
1182
+ return resp.text();
1183
+ })
1184
+ .then(svg => {
1185
+ block.innerHTML = `
1186
+ <div class="chart-inline-rendered">
1187
+ <div class="chart-inline-svg">${sanitizeSvg(svg)}</div>
1188
+ <div class="chart-inline-actions">
1189
+ <button class="chart-copy-btn" data-tooltip="Copy JSON">
1190
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1191
+ <rect x="9" y="9" width="13" height="13" rx="2"/>
1192
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
1193
+ </svg>
1194
+ </button>
1195
+ </div>
1196
+ </div>
1197
+ `;
1198
+ block._chartJson = jsonText;
1199
+ block.querySelector('.chart-copy-btn')?.addEventListener('click', () => {
1200
+ navigator.clipboard.writeText(jsonText).then(() => {
1201
+ const btn = block.querySelector('.chart-copy-btn');
1202
+ if (btn) { btn.setAttribute('data-tooltip', 'Copied!'); setTimeout(() => btn.setAttribute('data-tooltip', 'Copy JSON'), 1500); }
1203
+ });
1204
+ });
1205
+ })
1206
+ .catch(err => {
1207
+ console.error('Chart render error:', err);
1208
+ block.innerHTML = `
1209
+ <div class="chart-inline-error">
1210
+ <span>Failed to render chart: ${escapeHtml(err.message)}</span>
1211
+ </div>
1212
+ `;
1213
+ });
1214
+ });
1215
+ }
1216
+ }
1217
+
1218
+ /**
1219
+ * Autocomplete dropdown for slash commands and shell commands
1220
+ */
1221
+ export class AutocompleteUI {
1222
+ constructor(container, input) {
1223
+ this.container = container;
1224
+ this.input = input;
1225
+ this.visible = false;
1226
+ this.items = [];
1227
+ this.selectedIndex = -1;
1228
+ this.mode = null; // 'slash' or 'bang'
1229
+ this.agentCommands = []; // Commands fetched from server
1230
+ this.triggerPos = 0; // index of '/' or start of bang
1231
+ this.query = '';
1232
+ }
1233
+
1234
+ /**
1235
+ * Set Claude commands from system init message
1236
+ * @param {Array} commandNames - ["todo", "compact", "cost", ...] (names without leading /)
1237
+ * @param {Set} [userCommandNames] - Set of user-defined command names (from ~/.claude/commands/)
1238
+ * @param {Object} [descriptions] - {name: "description"} from server
1239
+ */
1240
+ setAgentCommands(commandNames, userCommandNames, descriptions) {
1241
+ this.agentCommands = (commandNames || []).map(name => ({
1242
+ cmd: '/' + name,
1243
+ desc: descriptions?.[name] || (userCommandNames?.has(name) ? 'User command' : 'Claude command'),
1244
+ isAgentCommand: true,
1245
+ }));
1246
+ }
1247
+
1248
+ show(mode, filter = '', triggerPos = 0) {
1249
+ this.mode = mode;
1250
+ this.triggerPos = triggerPos;
1251
+ this.query = filter;
1252
+
1253
+ if (mode === 'slash') {
1254
+ // Build command list: built-in → custom → Claude
1255
+ const allCommands = [];
1256
+ const seenCmds = new Set();
1257
+
1258
+ // 1. Built-in commands (highest priority)
1259
+ for (const cmd of COMMANDS) {
1260
+ allCommands.push(cmd);
1261
+ seenCmds.add(cmd.cmd);
1262
+ }
1263
+
1264
+ // 2. Custom commands from CommandStore
1265
+ const app = getApp();
1266
+ const projectPath = app?.cwd || null;
1267
+ const commandStore = getCommandStore();
1268
+ const customCommands = commandStore.getCommands(projectPath);
1269
+
1270
+ for (const cmd of customCommands) {
1271
+ if (!seenCmds.has(cmd.cmd)) {
1272
+ allCommands.push({
1273
+ cmd: cmd.cmd,
1274
+ desc: cmd.desc || (cmd.type === CommandType.SHELL ? 'Shell command' : 'Custom prompt'),
1275
+ isCustomCommand: true,
1276
+ customData: cmd,
1277
+ });
1278
+ seenCmds.add(cmd.cmd);
1279
+ }
1280
+ }
1281
+
1282
+ // 3. Claude commands (from server, lowest priority)
1283
+ for (const cmd of this.agentCommands) {
1284
+ if (!seenCmds.has(cmd.cmd)) {
1285
+ allCommands.push(cmd);
1286
+ seenCmds.add(cmd.cmd);
1287
+ }
1288
+ }
1289
+
1290
+ // Filter by search term
1291
+ this.items = allCommands.filter(c =>
1292
+ c.cmd.toLowerCase().includes(filter.toLowerCase())
1293
+ );
1294
+ } else if (mode === 'bang') {
1295
+ const recentCommands = getRecentShellCommands();
1296
+ this.items = recentCommands
1297
+ .filter(c => c.toLowerCase().includes(filter.toLowerCase()))
1298
+ .map(c => ({ cmd: '!' + c, desc: 'Recent command' }));
1299
+ }
1300
+
1301
+ if (this.items.length === 0) {
1302
+ this.hide();
1303
+ return;
1304
+ }
1305
+
1306
+ // Auto-select first item so Tab works immediately (suppressed for Tab-cycle browse)
1307
+ this.selectedIndex = this.noPreselectOnce ? -1 : 0;
1308
+ this.noPreselectOnce = false;
1309
+ this.render();
1310
+ this.visible = true;
1311
+ this.container.classList.add('visible');
1312
+ this._detachAnchor?.();
1313
+ this._detachAnchor = anchorAbove(this.container, this.input, this.triggerPos);
1314
+ }
1315
+
1316
+ hide() {
1317
+ this.visible = false;
1318
+ this.container.classList.remove('visible');
1319
+ this.items = [];
1320
+ this.selectedIndex = -1;
1321
+ this.triggerPos = 0;
1322
+ this.query = '';
1323
+ this._detachAnchor?.();
1324
+ this._detachAnchor = null;
1325
+ }
1326
+
1327
+ render() {
1328
+ const sectionTitle = this.mode === 'slash' ? 'Commands' : 'Recent Shell Commands';
1329
+
1330
+ this.container.innerHTML = `
1331
+ <div class="autocomplete-section">${sectionTitle}</div>
1332
+ ${this.items.map((item, i) => `
1333
+ <div class="autocomplete-item ${i === this.selectedIndex ? 'selected' : ''}"
1334
+ data-index="${i}">
1335
+ <span class="autocomplete-cmd">${escapeHtml(item.cmd)}</span>
1336
+ <span class="autocomplete-desc">${escapeHtml(item.desc)}</span>
1337
+ </div>
1338
+ `).join('')}
1339
+ `;
1340
+
1341
+ // Click handlers
1342
+ this.container.querySelectorAll('.autocomplete-item').forEach(el => {
1343
+ el.addEventListener('click', () => {
1344
+ this.select(parseInt(el.dataset.index));
1345
+ });
1346
+ });
1347
+ }
1348
+
1349
+ moveSelection(delta) {
1350
+ if (!this.visible || this.items.length === 0) return;
1351
+
1352
+ this.selectedIndex += delta;
1353
+ if (this.selectedIndex < 0) this.selectedIndex = this.items.length - 1;
1354
+ if (this.selectedIndex >= this.items.length) this.selectedIndex = 0;
1355
+
1356
+ this.render();
1357
+
1358
+ requestAnimationFrame(() => {
1359
+ const selectedEl = this.container.querySelector('.autocomplete-item.selected');
1360
+ if (selectedEl) {
1361
+ selectedEl.scrollIntoView({ block: 'nearest', behavior: 'auto' });
1362
+ }
1363
+ });
1364
+ }
1365
+
1366
+ select(index = this.selectedIndex) {
1367
+ if (index < 0 || index >= this.items.length) return;
1368
+ const item = this.items[index];
1369
+
1370
+ if (this.mode === 'slash') {
1371
+ // Determine whether the command needs args (forces trailing space, no auto-execute)
1372
+ let needsArgs = false;
1373
+ if (item.isCustomCommand) {
1374
+ const customData = item.customData;
1375
+ const needsInput = customData.prompt?.includes('{input}') ||
1376
+ customData.shell?.includes('{input}');
1377
+ if (needsInput) needsArgs = true;
1378
+ } else if (!item.isAgentCommand && item.hasArgs) {
1379
+ needsArgs = true;
1380
+ }
1381
+ const insertText = needsArgs ? item.cmd + ' ' : item.cmd;
1382
+
1383
+ // Position-aware replacement: replace `/query` at triggerPos with insertText.
1384
+ const value = this.input.value;
1385
+ const before = value.slice(0, this.triggerPos);
1386
+ const after = value.slice(this.triggerPos + 1 + this.query.length);
1387
+ this.input.value = before + insertText + after;
1388
+ const newCursor = before.length + insertText.length;
1389
+ this.input.selectionStart = this.input.selectionEnd = newCursor;
1390
+ this.input.dispatchEvent(new Event('input', { bubbles: true }));
1391
+ this.input.focus();
1392
+ this.hide();
1393
+
1394
+ // Auto-execute only when: command was the entire input (start-of-line, no other text),
1395
+ // it takes no args, and it isn't a Claude-side command (those need Enter to forward).
1396
+ const isWholeInput = before === '' && after === '';
1397
+ if (isWholeInput && !needsArgs && !item.isAgentCommand) {
1398
+ const app = getApp();
1399
+ if (app) app.handleInput();
1400
+ }
1401
+ return;
1402
+ }
1403
+
1404
+ // Bang mode: replace whole input with the recent shell command
1405
+ this.input.value = item.cmd;
1406
+ this.input.dispatchEvent(new Event('input', { bubbles: true }));
1407
+ this.input.focus();
1408
+ this.hide();
1409
+ }
1410
+
1411
+ hasSelection() {
1412
+ return this.selectedIndex >= 0;
1413
+ }
1414
+ }