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.
- painapple_code/__init__.py +30 -0
- painapple_code/__main__.py +18 -0
- painapple_code/_version.py +24 -0
- painapple_code/auth_middleware.py +930 -0
- painapple_code/cli/__init__.py +204 -0
- painapple_code/cli/deploy/__init__.py +15 -0
- painapple_code/cli/deploy/claude_seed.py +41 -0
- painapple_code/cli/deploy/config.py +260 -0
- painapple_code/cli/deploy/container.py +715 -0
- painapple_code/cli/deploy/launch.py +163 -0
- painapple_code/cli/deploy/runtime.py +223 -0
- painapple_code/cli/lifecycle_cmd.py +443 -0
- painapple_code/cli/list_cmd.py +572 -0
- painapple_code/cli/manage_cmd.py +670 -0
- painapple_code/cli/netinfo.py +125 -0
- painapple_code/cli/profiles.py +390 -0
- painapple_code/cli/serve_args.py +163 -0
- painapple_code/cli/serve_config.py +256 -0
- painapple_code/cli/setup_cmd.py +664 -0
- painapple_code/cli/ui.py +438 -0
- painapple_code/cost_analytics.py +879 -0
- painapple_code/data/models.defaults.yaml +18 -0
- painapple_code/data/models.yaml +18 -0
- painapple_code/data/presets.defaults.json +32 -0
- painapple_code/data/strings.yaml +2269 -0
- painapple_code/helpers.py +406 -0
- painapple_code/paths.py +1514 -0
- painapple_code/prompt_explorer.py +984 -0
- painapple_code/providers/__init__.py +224 -0
- painapple_code/providers/base.py +710 -0
- painapple_code/providers/claude/__init__.py +74 -0
- painapple_code/providers/claude/capabilities.py +218 -0
- painapple_code/providers/claude/errors.py +79 -0
- painapple_code/providers/claude/launch.py +50 -0
- painapple_code/providers/claude/summary.py +89 -0
- painapple_code/providers/claude/translate.py +74 -0
- painapple_code/providers/claude_sdk/__init__.py +139 -0
- painapple_code/providers/claude_sdk/driver.py +412 -0
- painapple_code/providers/codex/__init__.py +87 -0
- painapple_code/providers/codex/capabilities.py +321 -0
- painapple_code/providers/codex/errors.py +70 -0
- painapple_code/providers/codex/launch.py +142 -0
- painapple_code/providers/codex/summary.py +196 -0
- painapple_code/providers/codex/translate.py +204 -0
- painapple_code/providers/codex_app_server/__init__.py +100 -0
- painapple_code/providers/codex_app_server/capabilities.py +41 -0
- painapple_code/providers/codex_app_server/launch.py +202 -0
- painapple_code/providers/codex_app_server/summary.py +291 -0
- painapple_code/providers/codex_app_server/translate.py +263 -0
- painapple_code/providers/codex_app_server/transport.py +238 -0
- painapple_code/routes/__init__.py +0 -0
- painapple_code/routes/api_agents.py +441 -0
- painapple_code/routes/api_app.py +368 -0
- painapple_code/routes/api_app_commit_sections.py +127 -0
- painapple_code/routes/api_app_config.py +997 -0
- painapple_code/routes/api_app_session_prefs.py +217 -0
- painapple_code/routes/api_browser.py +690 -0
- painapple_code/routes/api_commands.py +374 -0
- painapple_code/routes/api_costs.py +128 -0
- painapple_code/routes/api_drafts.py +139 -0
- painapple_code/routes/api_exec.py +149 -0
- painapple_code/routes/api_files.py +542 -0
- painapple_code/routes/api_git.py +657 -0
- painapple_code/routes/api_logs.py +649 -0
- painapple_code/routes/api_plugins.py +275 -0
- painapple_code/routes/api_project_config.py +418 -0
- painapple_code/routes/api_prompts.py +231 -0
- painapple_code/routes/api_providers.py +53 -0
- painapple_code/routes/api_search.py +411 -0
- painapple_code/routes/api_session_stash.py +234 -0
- painapple_code/routes/api_session_welcome.py +151 -0
- painapple_code/routes/api_sessions.py +742 -0
- painapple_code/routes/api_shadow.py +323 -0
- painapple_code/routes/api_shadow_db.py +512 -0
- painapple_code/routes/api_shadow_files.py +332 -0
- painapple_code/routes/api_shadow_search.py +476 -0
- painapple_code/routes/api_skills.py +610 -0
- painapple_code/routes/api_tasks.py +147 -0
- painapple_code/routes/api_terminal.py +540 -0
- painapple_code/routes/api_upload.py +293 -0
- painapple_code/routes/api_viewer.py +229 -0
- painapple_code/routes/dependencies.py +109 -0
- painapple_code/routes/ws_chat.py +837 -0
- painapple_code/server.py +2208 -0
- painapple_code/server_logging.py +263 -0
- painapple_code/services/__init__.py +0 -0
- painapple_code/services/agent_session.py +2738 -0
- painapple_code/session_store.py +253 -0
- painapple_code/session_store_core.py +879 -0
- painapple_code/shadow_db.py +830 -0
- painapple_code/shadow_db_plans.py +369 -0
- painapple_code/shadow_db_queries.py +595 -0
- painapple_code/shadow_db_schema.py +676 -0
- painapple_code/shadow_git.py +1296 -0
- painapple_code/shadow_git_frontmatter.py +314 -0
- painapple_code/shadow_git_sections.py +520 -0
- painapple_code/shadow_git_summary.py +462 -0
- painapple_code/shadow_parser.py +560 -0
- painapple_code/static/css/00-variables.css +276 -0
- painapple_code/static/css/01-base.css +245 -0
- painapple_code/static/css/02-tooltips.css +36 -0
- painapple_code/static/css/09-left-rail.css +448 -0
- painapple_code/static/css/10-header.css +777 -0
- painapple_code/static/css/11-connection-bar.css +120 -0
- painapple_code/static/css/20-messages.css +750 -0
- painapple_code/static/css/21-tool-blocks.css +2340 -0
- painapple_code/static/css/22-edit-diff.css +619 -0
- painapple_code/static/css/23-thinking.css +1584 -0
- painapple_code/static/css/24-background-tasks.css +359 -0
- painapple_code/static/css/25-context-block.css +252 -0
- painapple_code/static/css/26-session-setup.css +144 -0
- painapple_code/static/css/30-markdown.css +854 -0
- painapple_code/static/css/40-input.css +2418 -0
- painapple_code/static/css/41-autocomplete.css +127 -0
- painapple_code/static/css/42-activity-strip.css +97 -0
- painapple_code/static/css/43-file-autocomplete.css +121 -0
- painapple_code/static/css/44-snippets-autocomplete.css +224 -0
- painapple_code/static/css/45-selection-bar.css +433 -0
- painapple_code/static/css/46-keyboard-bar.css +119 -0
- painapple_code/static/css/47-keyboard-longpress.css +116 -0
- painapple_code/static/css/47-token-profile.css +106 -0
- painapple_code/static/css/50-welcome.css +3095 -0
- painapple_code/static/css/51-modals.css +301 -0
- painapple_code/static/css/52-utilities.css +77 -0
- painapple_code/static/css/53-image-upload.css +456 -0
- painapple_code/static/css/54-todo-list.css +102 -0
- painapple_code/static/css/55-file-upload.css +113 -0
- painapple_code/static/css/56-chat-navigator.css +218 -0
- painapple_code/static/css/56-permission-card.css +332 -0
- painapple_code/static/css/56-plan-approval.css +204 -0
- painapple_code/static/css/56-question-form.css +602 -0
- painapple_code/static/css/57-swipe-indicator.css +95 -0
- painapple_code/static/css/58-session-families.css +627 -0
- painapple_code/static/css/59-about.css +196 -0
- painapple_code/static/css/61-log-explorer.css +723 -0
- painapple_code/static/css/62-json-tree.css +489 -0
- painapple_code/static/css/62-skills-widget.css +650 -0
- painapple_code/static/css/63-commands-widget.css +30 -0
- painapple_code/static/css/63-plugins-widget.css +174 -0
- painapple_code/static/css/63-terminal.css +516 -0
- painapple_code/static/css/64-search-files-widget.css +448 -0
- painapple_code/static/css/65-snippets-widget.css +426 -0
- painapple_code/static/css/66-active-sessions.css +979 -0
- painapple_code/static/css/66-agents-widget.css +265 -0
- painapple_code/static/css/66-file-explorer-widget.css +855 -0
- painapple_code/static/css/66-git-panel.css +791 -0
- painapple_code/static/css/66-history-explorer.css +1496 -0
- painapple_code/static/css/67-diff-viewer.css +602 -0
- painapple_code/static/css/67-editor-view.css +748 -0
- painapple_code/static/css/67-file-preview-widget.css +1873 -0
- painapple_code/static/css/68-browser-widget.css +337 -0
- painapple_code/static/css/68-compare-wizard.css +355 -0
- painapple_code/static/css/68-csv-preview.css +106 -0
- painapple_code/static/css/68-diff-preview.css +103 -0
- painapple_code/static/css/68-helpers-install-widget.css +491 -0
- painapple_code/static/css/68-image-annotate.css +346 -0
- painapple_code/static/css/68-terminal-view.css +98 -0
- painapple_code/static/css/68-uploads-widget.css +229 -0
- painapple_code/static/css/69-cost-analytics.css +537 -0
- painapple_code/static/css/70-config-panel.css +3736 -0
- painapple_code/static/css/70-excalidraw.css +136 -0
- painapple_code/static/css/70-prompt-explorer.css +890 -0
- painapple_code/static/css/71-chart.css +111 -0
- painapple_code/static/css/72-discussion-sidebar.css +678 -0
- painapple_code/static/css/74-debug-logs.css +656 -0
- painapple_code/static/css/80-open-dialog.css +146 -0
- painapple_code/static/css/80-quick-switcher.css +383 -0
- painapple_code/static/css/80-widget-system.css +1763 -0
- painapple_code/static/css/81-quick-actions.css +1020 -0
- painapple_code/static/css/82-context-popover.css +1233 -0
- painapple_code/static/css/83-context-menu.css +339 -0
- painapple_code/static/css/85-lazy-loading.css +102 -0
- painapple_code/static/css/86-zen-mode.css +708 -0
- painapple_code/static/css/87-grid-switcher.css +346 -0
- painapple_code/static/css/login.css +198 -0
- painapple_code/static/dist/app.bundle.js +7177 -0
- painapple_code/static/feature-triage.html +446 -0
- painapple_code/static/icons/apple-touch-icon.png +0 -0
- painapple_code/static/icons/favicon-32.png +0 -0
- painapple_code/static/icons/favicon.ico +0 -0
- painapple_code/static/icons/icon-128.png +0 -0
- painapple_code/static/icons/icon-144.png +0 -0
- painapple_code/static/icons/icon-152.png +0 -0
- painapple_code/static/icons/icon-180.png +0 -0
- painapple_code/static/icons/icon-192.png +0 -0
- painapple_code/static/icons/icon-384.png +0 -0
- painapple_code/static/icons/icon-512.png +0 -0
- painapple_code/static/icons/icon-72.png +0 -0
- painapple_code/static/icons/icon-96.png +0 -0
- painapple_code/static/js/action-delegate.js +187 -0
- painapple_code/static/js/activity-strip.js +193 -0
- painapple_code/static/js/app/context-menus.js +619 -0
- painapple_code/static/js/app/file-preview.js +163 -0
- painapple_code/static/js/app/init-ui.js +574 -0
- painapple_code/static/js/app/input-events.js +561 -0
- painapple_code/static/js/app/input-resize.js +313 -0
- painapple_code/static/js/app/message-actions.js +419 -0
- painapple_code/static/js/app/panels.js +210 -0
- painapple_code/static/js/app/rendering-delegators.js +246 -0
- painapple_code/static/js/app/server-loading.js +365 -0
- painapple_code/static/js/app/session-ops.js +287 -0
- painapple_code/static/js/app/session-switch.js +443 -0
- painapple_code/static/js/app/settings-helpers.js +280 -0
- painapple_code/static/js/app/startup-welcome.js +290 -0
- painapple_code/static/js/app-context.js +157 -0
- painapple_code/static/js/app.js +2134 -0
- painapple_code/static/js/auth-fetch.js +46 -0
- painapple_code/static/js/background-tasks.js +274 -0
- painapple_code/static/js/boot.js +73 -0
- painapple_code/static/js/caret-position.js +171 -0
- painapple_code/static/js/chat-navigator.js +710 -0
- painapple_code/static/js/chat-search.js +323 -0
- painapple_code/static/js/command-executor.js +176 -0
- painapple_code/static/js/command-store.js +497 -0
- painapple_code/static/js/components.js +1414 -0
- painapple_code/static/js/config.js +218 -0
- painapple_code/static/js/context-menu.js +740 -0
- painapple_code/static/js/controllers/chat-controller.js +4252 -0
- painapple_code/static/js/controllers/dialog-controller.js +217 -0
- painapple_code/static/js/controllers/tab-controller.js +1828 -0
- painapple_code/static/js/controllers/thinking-controller.js +915 -0
- painapple_code/static/js/diff-utils.js +486 -0
- painapple_code/static/js/drafts-pill.js +95 -0
- painapple_code/static/js/editor-view.js +815 -0
- painapple_code/static/js/effort-settings.js +430 -0
- painapple_code/static/js/feature-triage.js +811 -0
- painapple_code/static/js/file-autocomplete.js +516 -0
- painapple_code/static/js/file-tabs.js +123 -0
- painapple_code/static/js/gestures.js +448 -0
- painapple_code/static/js/grid-switcher.js +334 -0
- painapple_code/static/js/input-handler.js +1472 -0
- painapple_code/static/js/keyboard-bar.js +495 -0
- painapple_code/static/js/layout-switcher.js +109 -0
- painapple_code/static/js/linkify-utils.js +200 -0
- painapple_code/static/js/login.js +141 -0
- painapple_code/static/js/open-dialog.js +879 -0
- painapple_code/static/js/orphan-terminals.js +373 -0
- painapple_code/static/js/path-utils.js +179 -0
- painapple_code/static/js/perf-marks.js +102 -0
- painapple_code/static/js/permission-settings.js +475 -0
- painapple_code/static/js/pointer-input.js +59 -0
- painapple_code/static/js/preview/json-tree-menu.js +226 -0
- painapple_code/static/js/preview/json-tree-toolbar.js +291 -0
- painapple_code/static/js/preview/json-tree.js +457 -0
- painapple_code/static/js/preview/preview-breadcrumb.js +387 -0
- painapple_code/static/js/preview/preview-edit.js +367 -0
- painapple_code/static/js/preview/preview-events.js +361 -0
- painapple_code/static/js/preview/preview-history.js +567 -0
- painapple_code/static/js/preview/preview-inline-edit.js +869 -0
- painapple_code/static/js/preview/preview-poll.js +108 -0
- painapple_code/static/js/preview/preview-render.js +572 -0
- painapple_code/static/js/preview/preview-search.js +421 -0
- painapple_code/static/js/preview/preview-state.js +256 -0
- painapple_code/static/js/preview/preview-utils.js +251 -0
- painapple_code/static/js/preview-plugins/chart-plugin.js +22 -0
- painapple_code/static/js/preview-plugins/csv-plugin.js +188 -0
- painapple_code/static/js/preview-plugins/diff-plugin.js +258 -0
- painapple_code/static/js/preview-plugins/excalidraw-plugin.js +25 -0
- painapple_code/static/js/preview-plugins/html-plugin.js +104 -0
- painapple_code/static/js/preview-plugins/image-plugin.js +20 -0
- painapple_code/static/js/preview-plugins/index.js +34 -0
- painapple_code/static/js/preview-plugins/json-plugin.js +99 -0
- painapple_code/static/js/preview-plugins/jsonl-plugin.js +152 -0
- painapple_code/static/js/preview-plugins/markdown-plugin.js +266 -0
- painapple_code/static/js/preview-plugins/panzoom-plugin.js +63 -0
- painapple_code/static/js/preview-plugins/plugin-helpers.js +282 -0
- painapple_code/static/js/project-color-picker.js +110 -0
- painapple_code/static/js/project-colors.js +163 -0
- painapple_code/static/js/prompt-favorites.js +187 -0
- painapple_code/static/js/quick-actions-menu.js +1736 -0
- painapple_code/static/js/quick-actions-registry.js +1239 -0
- painapple_code/static/js/quick-switcher/controller.js +294 -0
- painapple_code/static/js/quick-switcher/fuzzy-scorer.js +123 -0
- painapple_code/static/js/quick-switcher/index.js +30 -0
- painapple_code/static/js/quick-switcher/providers/base-provider.js +51 -0
- painapple_code/static/js/quick-switcher/providers/command-provider.js +56 -0
- painapple_code/static/js/quick-switcher/providers/file-provider.js +291 -0
- painapple_code/static/js/quick-switcher/providers/panel-provider.js +132 -0
- painapple_code/static/js/quick-switcher/providers/project-provider.js +361 -0
- painapple_code/static/js/quick-switcher/providers/read-files-provider.js +104 -0
- painapple_code/static/js/quick-switcher/providers/skills-provider.js +129 -0
- painapple_code/static/js/quick-switcher/registry.js +69 -0
- painapple_code/static/js/quick-switcher/ui/item.js +54 -0
- painapple_code/static/js/quick-switcher/ui/picker.js +464 -0
- painapple_code/static/js/recent-opens.js +40 -0
- painapple_code/static/js/scroll-manager.js +530 -0
- painapple_code/static/js/scroll-state-machine.js +359 -0
- painapple_code/static/js/selection/action-bar.js +793 -0
- painapple_code/static/js/selection/index.js +15 -0
- painapple_code/static/js/selection/selection-handler.js +877 -0
- painapple_code/static/js/selection/state.js +181 -0
- painapple_code/static/js/session/agent-progress.js +202 -0
- painapple_code/static/js/session/handle-agent-message.js +481 -0
- painapple_code/static/js/session/handle-message.js +550 -0
- painapple_code/static/js/session/interactive.js +587 -0
- painapple_code/static/js/session/message-store.js +271 -0
- painapple_code/static/js/session/messages.js +253 -0
- painapple_code/static/js/session/persistence.js +179 -0
- painapple_code/static/js/session/restore.js +136 -0
- painapple_code/static/js/session/sync.js +333 -0
- painapple_code/static/js/session-container-pool.js +371 -0
- painapple_code/static/js/session-setup-panel.js +274 -0
- painapple_code/static/js/session.js +1047 -0
- painapple_code/static/js/shortcut-hints.js +272 -0
- painapple_code/static/js/shortcuts.js +1146 -0
- painapple_code/static/js/skills-autocomplete.js +262 -0
- painapple_code/static/js/snippets-autocomplete.js +738 -0
- painapple_code/static/js/stash-refs-view.js +83 -0
- painapple_code/static/js/stash-ui.js +768 -0
- painapple_code/static/js/stash.js +785 -0
- painapple_code/static/js/status-bar.js +1184 -0
- painapple_code/static/js/token-profile.js +274 -0
- painapple_code/static/js/tool-renderer-blocks.js +1626 -0
- painapple_code/static/js/tool-renderer-thinking.js +813 -0
- painapple_code/static/js/tool-renderer.js +1500 -0
- painapple_code/static/js/tooltips.js +197 -0
- painapple_code/static/js/upload-manager.js +1019 -0
- painapple_code/static/js/utils.js +521 -0
- painapple_code/static/js/welcome/api.js +363 -0
- painapple_code/static/js/welcome/cards.js +626 -0
- painapple_code/static/js/welcome/context-menu.js +585 -0
- painapple_code/static/js/welcome/families.js +801 -0
- painapple_code/static/js/welcome/preview.js +234 -0
- painapple_code/static/js/welcome/state.js +129 -0
- painapple_code/static/js/welcome.js +1874 -0
- painapple_code/static/js/widget-system/base-widget.js +717 -0
- painapple_code/static/js/widget-system/device-manager.js +178 -0
- painapple_code/static/js/widget-system/event-bus.js +152 -0
- painapple_code/static/js/widget-system/icons.js +120 -0
- painapple_code/static/js/widget-system/index.js +49 -0
- painapple_code/static/js/widget-system/init.js +54 -0
- painapple_code/static/js/widget-system/types/bottom-sheet.js +307 -0
- painapple_code/static/js/widget-system/types/floating.js +915 -0
- painapple_code/static/js/widget-system/types/index.js +40 -0
- painapple_code/static/js/widget-system/types/modal.js +147 -0
- painapple_code/static/js/widget-system/types/sidebar.js +158 -0
- painapple_code/static/js/widget-system/types/tab.js +146 -0
- painapple_code/static/js/widget-system/types/top-sheet.js +203 -0
- painapple_code/static/js/widget-system/widget-manager.js +1187 -0
- painapple_code/static/js/widgets/about-widget.js +260 -0
- painapple_code/static/js/widgets/active-sessions-widget.js +760 -0
- painapple_code/static/js/widgets/agents-widget.js +897 -0
- painapple_code/static/js/widgets/browser-widget.js +579 -0
- painapple_code/static/js/widgets/commands-widget.js +694 -0
- painapple_code/static/js/widgets/config/commit-sections.js +449 -0
- painapple_code/static/js/widgets/config/dir-autocomplete.js +224 -0
- painapple_code/static/js/widgets/config/gestures.js +161 -0
- painapple_code/static/js/widgets/config/models-tab.js +988 -0
- painapple_code/static/js/widgets/config/quick-actions-tab.js +882 -0
- painapple_code/static/js/widgets/config/shortcut-editor.js +587 -0
- painapple_code/static/js/widgets/config/state.js +517 -0
- painapple_code/static/js/widgets/config/system-controls.js +90 -0
- painapple_code/static/js/widgets/config-widget.js +1535 -0
- painapple_code/static/js/widgets/cost-analytics-widget.js +621 -0
- painapple_code/static/js/widgets/debug-widget.js +693 -0
- painapple_code/static/js/widgets/diff-viewer-widget.js +1420 -0
- painapple_code/static/js/widgets/discussion-widget.js +1107 -0
- painapple_code/static/js/widgets/file-explorer-widget.js +2166 -0
- painapple_code/static/js/widgets/file-preview-widget.js +861 -0
- painapple_code/static/js/widgets/git-widget.js +794 -0
- painapple_code/static/js/widgets/helpers-install-widget.js +720 -0
- painapple_code/static/js/widgets/history-explorer-widget.js +1804 -0
- painapple_code/static/js/widgets/image-annotate-widget.js +951 -0
- painapple_code/static/js/widgets/image-preview-widget.js +692 -0
- painapple_code/static/js/widgets/index.js +176 -0
- painapple_code/static/js/widgets/log-explorer-widget.js +1057 -0
- painapple_code/static/js/widgets/plugins-widget.js +305 -0
- painapple_code/static/js/widgets/prompt-explorer-widget.js +1119 -0
- painapple_code/static/js/widgets/search-files-widget.js +529 -0
- painapple_code/static/js/widgets/skills-widget.js +843 -0
- painapple_code/static/js/widgets/snippets-widget.js +479 -0
- painapple_code/static/js/widgets/sub-agents-widget.js +333 -0
- painapple_code/static/js/widgets/tasks-widget.js +379 -0
- painapple_code/static/js/widgets/terminal/connection.js +283 -0
- painapple_code/static/js/widgets/terminal/gestures.js +357 -0
- painapple_code/static/js/widgets/terminal/init.js +642 -0
- painapple_code/static/js/widgets/terminal/link-providers.js +532 -0
- painapple_code/static/js/widgets/terminal/osc52.js +213 -0
- painapple_code/static/js/widgets/terminal/render.js +159 -0
- painapple_code/static/js/widgets/terminal/size.js +54 -0
- painapple_code/static/js/widgets/terminal/state.js +211 -0
- painapple_code/static/js/widgets/terminal/wrap-utils.js +101 -0
- painapple_code/static/js/widgets/terminal-widget.js +793 -0
- painapple_code/static/js/widgets/uploads-widget.js +461 -0
- painapple_code/static/js/widgets/zen-widget.js +1001 -0
- painapple_code/static/login.html +51 -0
- painapple_code/static/manifest.json +73 -0
- painapple_code/static/sw.js +293 -0
- painapple_code/static/vendor/LICENSES.txt +769 -0
- painapple_code/static/vendor/README.md +103 -0
- painapple_code/static/vendor/codemirror.js +35 -0
- painapple_code/static/vendor/codemirror.js.LEGAL.txt +304 -0
- painapple_code/static/vendor/github-markdown-dark.min.css +1124 -0
- painapple_code/static/vendor/highlight-github-dark.min.css +10 -0
- painapple_code/static/vendor/highlight-lang-dockerfile.min.js +8 -0
- painapple_code/static/vendor/highlight-lang-nginx.min.js +21 -0
- painapple_code/static/vendor/highlight-lang-properties.min.js +10 -0
- painapple_code/static/vendor/highlight-lang-scala.min.js +28 -0
- painapple_code/static/vendor/highlight.min.js +1213 -0
- painapple_code/static/vendor/marked.min.js +6 -0
- painapple_code/static/vendor/purify.min.js +3 -0
- painapple_code/static/vendor/xterm-addon-fit.js +2 -0
- painapple_code/static/vendor/xterm.css +209 -0
- painapple_code/static/vendor/xterm.js +2 -0
- painapple_code/static/web-client.html +635 -0
- painapple_code/subprocess_registry.py +535 -0
- painapple_code/tls_cert.py +79 -0
- painapple_code/tools/agents/shadow-git-helper.md +400 -0
- painapple_code/tools/excalidraw-to-svg.js +143 -0
- painapple_code/tools/install-helpers.sh +148 -0
- painapple_code/tools/shadow-git +320 -0
- painapple_code/tools/shadow-query +120 -0
- painapple_code/tools/vegalite-to-svg.js +79 -0
- painapple_code/turn_query.py +766 -0
- painapple_code/turn_tracker.py +221 -0
- painapple_code/utils/__init__.py +0 -0
- painapple_code/utils/agent_cli.py +306 -0
- painapple_code/utils/chart.py +103 -0
- painapple_code/utils/excalidraw.py +107 -0
- painapple_code/utils/file_lock.py +162 -0
- painapple_code/utils/file_paths.py +648 -0
- painapple_code/utils/generate_icons.py +251 -0
- painapple_code/utils/proc.py +205 -0
- painapple_code/utils/pty_backend.py +59 -0
- painapple_code/utils/pty_posix.py +160 -0
- painapple_code/utils/pty_windows.py +245 -0
- painapple_code/utils/token_profiles.py +91 -0
- painapple_code/viewer_templates.py +657 -0
- painapple_code/welcome_search.py +879 -0
- painapple_code-1.0.0.dist-info/METADATA +292 -0
- painapple_code-1.0.0.dist-info/RECORD +436 -0
- painapple_code-1.0.0.dist-info/WHEEL +5 -0
- painapple_code-1.0.0.dist-info/entry_points.txt +2 -0
- painapple_code-1.0.0.dist-info/licenses/LICENSE +661 -0
- painapple_code-1.0.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +261 -0
- painapple_code-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,4252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ChatController - Handles message rendering and chat display
|
|
3
|
+
*
|
|
4
|
+
* Manages: message list, scroll position, history loading, welcome screen
|
|
5
|
+
*
|
|
6
|
+
* Performance optimization: Uses SessionContainerPool for O(1) tab switching
|
|
7
|
+
* instead of O(n) DOM rebuilds on every session switch.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { CONFIG, HAS_PHYSICAL_KEYBOARD, debug } from '../config.js';
|
|
11
|
+
import { MarkdownRenderer } from '../components.js';
|
|
12
|
+
import { escapeHtml, escapeAttr, formatTime, formatRelativeTime, highlightThinkingKeywords } from '../utils.js';
|
|
13
|
+
import { isThinkingKeywordsHighlightingEnabled } from '../widgets/config-widget.js';
|
|
14
|
+
import {
|
|
15
|
+
initWelcomeScreen,
|
|
16
|
+
handleWelcomeTask,
|
|
17
|
+
resetWelcomeScreen,
|
|
18
|
+
isTaskMode,
|
|
19
|
+
refreshSessions,
|
|
20
|
+
restoreWelcomeState,
|
|
21
|
+
clearSavedWelcomeState,
|
|
22
|
+
getSavedWelcomeState
|
|
23
|
+
} from '../welcome.js';
|
|
24
|
+
import { SessionContainerPool, useContainerPool } from '../session-container-pool.js';
|
|
25
|
+
import { showToast } from '../context-menu.js';
|
|
26
|
+
import { engineAuthorLabel } from '../status-bar.js';
|
|
27
|
+
import S from '../strings.js';
|
|
28
|
+
import { basename, isAbsolutePath, joinPath } from '../path-utils.js';
|
|
29
|
+
import { renderStashRefs } from '../stash-refs-view.js';
|
|
30
|
+
|
|
31
|
+
// Turn-summary files row: current-turn pills (changed files + image thumbs)
|
|
32
|
+
// always render in full; session-accumulated pills (changed first, then image
|
|
33
|
+
// thumbs) top the row up to this many total pills.
|
|
34
|
+
const FILES_ROW_CAP = 10;
|
|
35
|
+
|
|
36
|
+
// Kept in sync with image-preview-widget.js IMAGE_EXT_RE and the backend's
|
|
37
|
+
// turn_tracker.IMAGE_EXTENSIONS.
|
|
38
|
+
const FILES_ROW_IMAGE_RE = /\.(png|jpg|jpeg|gif|webp|svg|bmp|ico)$/i;
|
|
39
|
+
|
|
40
|
+
// Distance (px) a touch must move for the subsequent touchend to be treated
|
|
41
|
+
// as the end of a scroll gesture rather than a tap.
|
|
42
|
+
const TAP_MOVE_THRESHOLD = 10;
|
|
43
|
+
// Matches the long-press threshold used by the document-level file-menu handler
|
|
44
|
+
// in app.js — a touch held this long has already opened a context menu, so the
|
|
45
|
+
// subsequent touchend must not also fire the tap action.
|
|
46
|
+
const LONG_PRESS_MS = 400;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Bind click + touch tap handler to an element, skipping touchend when the
|
|
50
|
+
* touch moved beyond TAP_MOVE_THRESHOLD — i.e. the user was scrolling, not
|
|
51
|
+
* tapping. click is bound as-is so desktop/trackpad clicks still work, and
|
|
52
|
+
* modern iOS suppresses the synthetic click after a scroll anyway.
|
|
53
|
+
*
|
|
54
|
+
* Also skips when an iOS long-press just triggered a file context menu
|
|
55
|
+
* (app.js binds that at document level on the same elements); without this
|
|
56
|
+
* guard, tapping a .turn-file-pill opened both the menu and the preview.
|
|
57
|
+
*/
|
|
58
|
+
function bindTapHandler(element, handler) {
|
|
59
|
+
let startX = 0, startY = 0, moved = false, startTime = 0;
|
|
60
|
+
const contextMenuOpen = () => !!window.app?.contextMenu?.visible;
|
|
61
|
+
element.addEventListener('touchstart', (e) => {
|
|
62
|
+
const t = e.touches[0];
|
|
63
|
+
startX = t.clientX;
|
|
64
|
+
startY = t.clientY;
|
|
65
|
+
moved = false;
|
|
66
|
+
startTime = Date.now();
|
|
67
|
+
}, { passive: true });
|
|
68
|
+
element.addEventListener('touchmove', (e) => {
|
|
69
|
+
if (moved) return;
|
|
70
|
+
const t = e.touches[0];
|
|
71
|
+
if (Math.abs(t.clientX - startX) > TAP_MOVE_THRESHOLD ||
|
|
72
|
+
Math.abs(t.clientY - startY) > TAP_MOVE_THRESHOLD) {
|
|
73
|
+
moved = true;
|
|
74
|
+
}
|
|
75
|
+
}, { passive: true });
|
|
76
|
+
element.addEventListener('touchend', (e) => {
|
|
77
|
+
if (moved) return;
|
|
78
|
+
if (Date.now() - startTime >= LONG_PRESS_MS) return;
|
|
79
|
+
if (contextMenuOpen()) return;
|
|
80
|
+
// Kill any pending app.js long-press timer — handler() calls
|
|
81
|
+
// stopPropagation, so the document's touchend never runs to clear it,
|
|
82
|
+
// and otherwise the 400 ms timer would fire and open the context
|
|
83
|
+
// menu on top of the preview we're about to show.
|
|
84
|
+
window.__cancelFileLongPress?.();
|
|
85
|
+
handler(e);
|
|
86
|
+
}, { passive: false });
|
|
87
|
+
element.addEventListener('click', (e) => {
|
|
88
|
+
if (contextMenuOpen()) return;
|
|
89
|
+
window.__cancelFileLongPress?.();
|
|
90
|
+
handler(e);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class ChatController {
|
|
95
|
+
constructor(ctx, thinkingController) {
|
|
96
|
+
this.ctx = ctx;
|
|
97
|
+
this.thinkingCtrl = thinkingController;
|
|
98
|
+
|
|
99
|
+
// Container pool for instant tab switching (initialized lazily)
|
|
100
|
+
this._containerPool = null;
|
|
101
|
+
this._useContainerPool = useContainerPool();
|
|
102
|
+
|
|
103
|
+
// Cache for recent sessions to prevent flickering
|
|
104
|
+
this._recentSessionsCache = null;
|
|
105
|
+
this._recentSessionsCacheTime = 0;
|
|
106
|
+
|
|
107
|
+
// Session file pills hidden by user: sessionId → Set<filePath>
|
|
108
|
+
this._hiddenSessionFiles = new Map();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Returns the active welcome container in #welcome-view (or null) */
|
|
112
|
+
_activeWelcomeContainer() {
|
|
113
|
+
return this.ctx.app?.els?.welcomeView?.querySelector('#welcome-container') || null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ═══════════════════════════════════════════════════════════════
|
|
117
|
+
// CONTEXT BLOCK RENDERING
|
|
118
|
+
// ═══════════════════════════════════════════════════════════════
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Check if content looks like /context command output
|
|
122
|
+
*/
|
|
123
|
+
_isContextOutput(content) {
|
|
124
|
+
return content && (
|
|
125
|
+
content.startsWith('## Context Usage') ||
|
|
126
|
+
content.includes('**Model:**') && content.includes('**Tokens:**')
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Parse context output and extract summary info
|
|
132
|
+
*/
|
|
133
|
+
_parseContextSummary(content) {
|
|
134
|
+
const summary = { model: 'Unknown', tokens: '?', limit: '?', percent: '?' };
|
|
135
|
+
|
|
136
|
+
// Parse model: **Model:** claude-opus-4-5-20251101
|
|
137
|
+
const modelMatch = content.match(/\*\*Model:\*\*\s*(\S+)/);
|
|
138
|
+
if (modelMatch) {
|
|
139
|
+
summary.model = modelMatch[1];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Parse tokens: **Tokens:** 76.5k / 200.0k (38%)
|
|
143
|
+
const tokensMatch = content.match(/\*\*Tokens:\*\*\s*([\d.]+k?)\s*\/\s*([\d.]+k?)\s*\((\d+%)\)/);
|
|
144
|
+
if (tokensMatch) {
|
|
145
|
+
summary.tokens = tokensMatch[1];
|
|
146
|
+
summary.limit = tokensMatch[2];
|
|
147
|
+
summary.percent = tokensMatch[3];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return summary;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Render /context output as a collapsible block
|
|
155
|
+
*/
|
|
156
|
+
_renderContextBlock(content, timestamp) {
|
|
157
|
+
const summary = this._parseContextSummary(content);
|
|
158
|
+
const fullContent = this.ctx.markdown.render(content);
|
|
159
|
+
const id = `context-${Date.now()}`;
|
|
160
|
+
|
|
161
|
+
return `
|
|
162
|
+
<div class="context-block collapsed" id="${id}">
|
|
163
|
+
<div class="context-header" data-act="toggle-class" data-block=".context-block" data-cls="collapsed">
|
|
164
|
+
<span class="context-icon">
|
|
165
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
166
|
+
<circle cx="12" cy="12" r="10"/>
|
|
167
|
+
<path d="M12 6v6l4 2"/>
|
|
168
|
+
</svg>
|
|
169
|
+
</span>
|
|
170
|
+
<span class="context-label">Context</span>
|
|
171
|
+
<span class="context-summary">
|
|
172
|
+
<span class="context-tokens">${summary.tokens} / ${summary.limit}</span>
|
|
173
|
+
<span class="context-percent">${summary.percent}</span>
|
|
174
|
+
</span>
|
|
175
|
+
<span class="context-model">${summary.model}</span>
|
|
176
|
+
<span class="context-time">${formatTime(timestamp)}</span>
|
|
177
|
+
<span class="context-expand">▶</span>
|
|
178
|
+
</div>
|
|
179
|
+
<div class="context-content">
|
|
180
|
+
<div class="markdown-content">${fullContent}</div>
|
|
181
|
+
</div>
|
|
182
|
+
</div>
|
|
183
|
+
`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ═══════════════════════════════════════════════════════════════
|
|
187
|
+
// MESSAGE RENDERING
|
|
188
|
+
// ═══════════════════════════════════════════════════════════════
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Initialize container pool lazily (first use)
|
|
192
|
+
* @private
|
|
193
|
+
*/
|
|
194
|
+
_initContainerPool() {
|
|
195
|
+
if (this._containerPool || !this._useContainerPool) return;
|
|
196
|
+
this._containerPool = new SessionContainerPool(this.ctx.els.messages, {
|
|
197
|
+
// When a session is LRU-evicted, save its scrollTop on the session object
|
|
198
|
+
// so it can be restored if the container is re-created later.
|
|
199
|
+
// scrollTop may be null = "was at bottom" → restore scrolls to bottom.
|
|
200
|
+
onBeforeEvict: (sessionId, scrollTop) => {
|
|
201
|
+
const session = this.ctx.app?.sessionManager?.get(sessionId);
|
|
202
|
+
if (session) {
|
|
203
|
+
session.scrollPosition = scrollTop;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Get the active message container for appending new messages
|
|
211
|
+
* CRITICAL: Use this instead of ctx.els.messages when appending messages
|
|
212
|
+
* to ensure messages go to the correct session container
|
|
213
|
+
* @private
|
|
214
|
+
*/
|
|
215
|
+
_getActiveMessageContainer() {
|
|
216
|
+
// Initialize pool on first use (lazy init)
|
|
217
|
+
this._initContainerPool();
|
|
218
|
+
|
|
219
|
+
if (this._useContainerPool && this._containerPool) {
|
|
220
|
+
const session = this.ctx.session;
|
|
221
|
+
const sessionId = session?.id || session?.storeId || session?.sessionId;
|
|
222
|
+
if (sessionId) {
|
|
223
|
+
// IMPORTANT: Use acquire() to get or create container
|
|
224
|
+
// Never fall back to #messages or messages will appear in all tabs
|
|
225
|
+
const container = this._containerPool.acquire(sessionId);
|
|
226
|
+
|
|
227
|
+
// If this container isn't currently active (visible), activate it
|
|
228
|
+
// This handles the case where we're appending to a new session
|
|
229
|
+
// that hasn't been fully initialized yet
|
|
230
|
+
if (this._containerPool.activeId !== sessionId) {
|
|
231
|
+
debug.log('[_getActiveMessageContainer] Activating container for', sessionId,
|
|
232
|
+
'was active:', this._containerPool.activeId);
|
|
233
|
+
this._containerPool.activate(sessionId);
|
|
234
|
+
// Mark as rendered to prevent renderMessages() from clearing it
|
|
235
|
+
this._containerPool.markRendered(sessionId, 0);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return container;
|
|
239
|
+
} else {
|
|
240
|
+
console.warn('[_getActiveMessageContainer] No sessionId available!', session);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
// Fallback to #messages - but log a warning because this could cause cross-tab bleed
|
|
244
|
+
console.warn('[_getActiveMessageContainer] Falling back to #messages - pool disabled or no session');
|
|
245
|
+
return this.ctx.els.messages;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Render all messages for the active session
|
|
250
|
+
*
|
|
251
|
+
* Performance: Uses container pooling for O(1) tab switches.
|
|
252
|
+
* - First visit: renders all messages O(n)
|
|
253
|
+
* - Subsequent visits: show/hide cached container O(1)
|
|
254
|
+
*/
|
|
255
|
+
renderMessages() {
|
|
256
|
+
const session = this.ctx.session;
|
|
257
|
+
if (!session) return;
|
|
258
|
+
|
|
259
|
+
const sessionId = session.id || session.storeId || session.sessionId;
|
|
260
|
+
|
|
261
|
+
// Filter out system messages (they go to system log now)
|
|
262
|
+
const messages = session.messages.filter(m => m.role !== 'system');
|
|
263
|
+
|
|
264
|
+
// Welcome view is its own top-level view rendered by App.renderWelcome;
|
|
265
|
+
// _doSessionSwitch routes there via TabController.switchToWelcome before
|
|
266
|
+
// renderMessages is ever called for an empty session. renderMessages only
|
|
267
|
+
// renders chat content into the session's container.
|
|
268
|
+
|
|
269
|
+
// Clear skipWelcome flag once we've bypassed it
|
|
270
|
+
if (session.skipWelcome) {
|
|
271
|
+
session.skipWelcome = false;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ─────────────────────────────────────────────────────────────────
|
|
275
|
+
// CONTAINER POOL: Check for cached container (O(1) switch)
|
|
276
|
+
// ─────────────────────────────────────────────────────────────────
|
|
277
|
+
this._initContainerPool();
|
|
278
|
+
|
|
279
|
+
debug.log('[ChatCtrl] renderMessages:', sessionId,
|
|
280
|
+
'usePool:', this._useContainerPool,
|
|
281
|
+
'poolExists:', !!this._containerPool,
|
|
282
|
+
'needsRender:', this._containerPool?.needsRender(sessionId));
|
|
283
|
+
|
|
284
|
+
if (this._useContainerPool && this._containerPool) {
|
|
285
|
+
// Check if we have a cached, rendered container
|
|
286
|
+
if (!this._containerPool.needsRender(sessionId)) {
|
|
287
|
+
// O(1) switch - browser natively preserves scrollTop on display:none elements
|
|
288
|
+
debug.log('[ChatCtrl] O(1) SWITCH - using cached container');
|
|
289
|
+
this._containerPool.activate(sessionId);
|
|
290
|
+
|
|
291
|
+
// Handle back-to-sessions pill
|
|
292
|
+
this._hideBackToSessionsPill();
|
|
293
|
+
const savedState = getSavedWelcomeState();
|
|
294
|
+
if (session.openedFromWelcome && savedState) {
|
|
295
|
+
this._showBackToSessionsPill(session);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Retarget scroll-aware components, but skip initState() —
|
|
299
|
+
// the browser preserved scrollTop natively, and we restore
|
|
300
|
+
// isUserScrolledUp from the session object below.
|
|
301
|
+
this._retargetScrollComponents({ skipInitState: true });
|
|
302
|
+
|
|
303
|
+
// Restore scroll manager state from the session's saved state
|
|
304
|
+
// (saved in switchSession PHASE 1 before the switch)
|
|
305
|
+
const scrollManager = this.ctx.app?.scrollManager;
|
|
306
|
+
if (scrollManager) {
|
|
307
|
+
scrollManager.isUserScrolledUp = !!session.isUserScrolledUp;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Self-heal: if the user was at the bottom when they left this
|
|
311
|
+
// session, pin it back to the bottom. Browsers normally preserve
|
|
312
|
+
// scrollTop through display:none, but iPadOS WKWebView can drop
|
|
313
|
+
// the offset after a long background stay / memory pressure —
|
|
314
|
+
// which used to re-show the tab scrolled to the top.
|
|
315
|
+
if (!session.isUserScrolledUp) {
|
|
316
|
+
const el = this._containerPool.get(sessionId);
|
|
317
|
+
if (el) el.scrollTop = el.scrollHeight;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// First render for this session - get/create container
|
|
324
|
+
debug.log('[ChatCtrl] FIRST RENDER - creating container for', sessionId);
|
|
325
|
+
const container = this._containerPool.acquire(sessionId);
|
|
326
|
+
container.innerHTML = '';
|
|
327
|
+
|
|
328
|
+
// Render into the session-specific container
|
|
329
|
+
this._renderMessagesIntoContainer(container, session, messages);
|
|
330
|
+
|
|
331
|
+
// Mark as rendered and activate
|
|
332
|
+
this._containerPool.markRendered(sessionId, messages.length);
|
|
333
|
+
this._containerPool.activate(sessionId);
|
|
334
|
+
} else {
|
|
335
|
+
// No pool - use legacy rendering (clear and rebuild)
|
|
336
|
+
debug.log('[ChatCtrl] LEGACY RENDER - no pool');
|
|
337
|
+
this.ctx.els.messages.innerHTML = '';
|
|
338
|
+
this._renderMessagesIntoContainer(this.ctx.els.messages, session, messages);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Retarget scroll-aware components to the active session container
|
|
342
|
+
this._retargetScrollComponents();
|
|
343
|
+
|
|
344
|
+
// Restore scroll position or scroll to bottom
|
|
345
|
+
this.restoreScrollPosition();
|
|
346
|
+
|
|
347
|
+
// Check gutter space for all thinking sections and tool groups after DOM is ready
|
|
348
|
+
requestAnimationFrame(() => {
|
|
349
|
+
this.thinkingCtrl.checkAllGutterSpace();
|
|
350
|
+
this.checkAllToolGroupGutterSpace();
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Render messages into a specific container element
|
|
356
|
+
* Extracted from renderMessages for container pool support
|
|
357
|
+
* @private
|
|
358
|
+
*/
|
|
359
|
+
_renderMessagesIntoContainer(container, session, messages) {
|
|
360
|
+
// Handle "Back to sessions" floating pill
|
|
361
|
+
this._hideBackToSessionsPill();
|
|
362
|
+
const savedState = getSavedWelcomeState();
|
|
363
|
+
if (session.openedFromWelcome && savedState) {
|
|
364
|
+
this._showBackToSessionsPill(session);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Show "more history" notice if there are older messages
|
|
368
|
+
if (session.hasMoreMessages && session.totalMessageCount > 0) {
|
|
369
|
+
const loadedCount = session.messages.length;
|
|
370
|
+
const totalCount = session.totalMessageCount;
|
|
371
|
+
const remaining = totalCount - loadedCount;
|
|
372
|
+
if (remaining > 0) {
|
|
373
|
+
const notice = document.createElement('div');
|
|
374
|
+
notice.className = 'message-history-notice';
|
|
375
|
+
notice.onclick = () => this.handleScrollTop();
|
|
376
|
+
notice.innerHTML = `
|
|
377
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
378
|
+
<polyline points="17 11 12 6 7 11"/>
|
|
379
|
+
<polyline points="17 18 12 13 7 18"/>
|
|
380
|
+
</svg>
|
|
381
|
+
<span>${remaining.toLocaleString()} older messages • scroll up to load</span>
|
|
382
|
+
`;
|
|
383
|
+
container.appendChild(notice);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Temporarily override ctx.els.messages for renderMessage calls
|
|
388
|
+
const originalMessages = this.ctx.els.messages;
|
|
389
|
+
this.ctx.els.messages = container;
|
|
390
|
+
|
|
391
|
+
try {
|
|
392
|
+
// Group consecutive thinking messages and tool messages
|
|
393
|
+
let i = 0;
|
|
394
|
+
while (i < messages.length) {
|
|
395
|
+
const msg = messages[i];
|
|
396
|
+
|
|
397
|
+
if (msg.role === 'thinking') {
|
|
398
|
+
// Collect consecutive thinking messages from the same turn
|
|
399
|
+
const thinkingGroup = [msg];
|
|
400
|
+
let j = i + 1;
|
|
401
|
+
while (j < messages.length && messages[j].role === 'thinking' &&
|
|
402
|
+
messages[j].turnId === msg.turnId) {
|
|
403
|
+
thinkingGroup.push(messages[j]);
|
|
404
|
+
j++;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (thinkingGroup.length >= 2) {
|
|
408
|
+
this.thinkingCtrl.renderThinkingGroup(thinkingGroup);
|
|
409
|
+
} else {
|
|
410
|
+
this.renderMessage(msg, false);
|
|
411
|
+
}
|
|
412
|
+
i = j;
|
|
413
|
+
} else if (msg.role === 'tool') {
|
|
414
|
+
// Collect consecutive tool messages from the same turn
|
|
415
|
+
const toolGroup = [msg];
|
|
416
|
+
let j = i + 1;
|
|
417
|
+
while (j < messages.length && messages[j].role === 'tool' &&
|
|
418
|
+
messages[j].turnId === msg.turnId) {
|
|
419
|
+
toolGroup.push(messages[j]);
|
|
420
|
+
j++;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (toolGroup.length >= 2) {
|
|
424
|
+
this._renderToolGroup(toolGroup);
|
|
425
|
+
} else {
|
|
426
|
+
this.renderMessage(msg, false);
|
|
427
|
+
}
|
|
428
|
+
i = j;
|
|
429
|
+
} else {
|
|
430
|
+
this.renderMessage(msg, false);
|
|
431
|
+
i++;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
} finally {
|
|
435
|
+
// Move plan-approval cards to after turn summary bars
|
|
436
|
+
this._repositionPlanApproval(container);
|
|
437
|
+
// Restore original messages element
|
|
438
|
+
this.ctx.els.messages = originalMessages;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Invalidate a session's cached container (force re-render on next switch)
|
|
444
|
+
* Call this when messages change while session is not visible
|
|
445
|
+
*/
|
|
446
|
+
invalidateSession(sessionId) {
|
|
447
|
+
if (this._containerPool) {
|
|
448
|
+
this._containerPool.invalidate(sessionId);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Release a session's container (when session is closed)
|
|
454
|
+
*/
|
|
455
|
+
releaseSession(sessionId) {
|
|
456
|
+
if (this._containerPool) {
|
|
457
|
+
this._containerPool.release(sessionId);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Author shown in a bubble's header. Every role but `assistant` names
|
|
463
|
+
* itself; the assistant is the session's ENGINE ("claude", "codex", …),
|
|
464
|
+
* so a Codex transcript never claims to be authored by Claude. Shared by
|
|
465
|
+
* the live path (renderMessage) and the re-render/lazy-load path
|
|
466
|
+
* (createMessageElement) so both agree after a reload.
|
|
467
|
+
*/
|
|
468
|
+
_authorLabel(msg) {
|
|
469
|
+
return msg.role === 'assistant'
|
|
470
|
+
? escapeHtml(engineAuthorLabel(this.ctx.session))
|
|
471
|
+
: msg.role;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Render a single message
|
|
476
|
+
*/
|
|
477
|
+
renderMessage(msg, scroll = true) {
|
|
478
|
+
// Skip system messages - they go to system log
|
|
479
|
+
if (msg.role === 'system') return;
|
|
480
|
+
|
|
481
|
+
// Skip result messages - they're metadata-only (cost, duration)
|
|
482
|
+
if (msg.role === 'result') return;
|
|
483
|
+
|
|
484
|
+
// CRITICAL: Get the correct container for the active session
|
|
485
|
+
// With pool: this is the session-specific .session-messages container
|
|
486
|
+
// Without pool: this is the shared #messages element
|
|
487
|
+
const messageContainer = this._getActiveMessageContainer();
|
|
488
|
+
|
|
489
|
+
// Handle error messages (from Claude Code's local-command-stderr)
|
|
490
|
+
if (msg.role === 'error') {
|
|
491
|
+
const div = document.createElement('div');
|
|
492
|
+
div.className = 'message error';
|
|
493
|
+
div.id = `msg-${msg.id}`;
|
|
494
|
+
div.innerHTML = `
|
|
495
|
+
<div class="message-header">
|
|
496
|
+
<span class="message-role error">
|
|
497
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
498
|
+
<circle cx="12" cy="12" r="10"/>
|
|
499
|
+
<line x1="12" y1="8" x2="12" y2="12"/>
|
|
500
|
+
<line x1="12" y1="16" x2="12.01" y2="16"/>
|
|
501
|
+
</svg>
|
|
502
|
+
error
|
|
503
|
+
</span>
|
|
504
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
505
|
+
<button class="message-copy-btn" data-msg-id="${msg.id}" data-id="${escapeAttr(msg.id)}" data-act="copy-message" data-tooltip="Copy message">
|
|
506
|
+
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
507
|
+
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
|
|
508
|
+
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
509
|
+
</svg>
|
|
510
|
+
<span class="copy-label">Copy</span>
|
|
511
|
+
</button>
|
|
512
|
+
</div>
|
|
513
|
+
<div class="message-content">${escapeHtml(msg.content)}</div>
|
|
514
|
+
`;
|
|
515
|
+
messageContainer.appendChild(div);
|
|
516
|
+
if (scroll) this.scrollToBottom();
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Handle auth-error affordance — Claude CLI returned 401 / expired token.
|
|
521
|
+
if (msg.role === 'auth_error') {
|
|
522
|
+
messageContainer.appendChild(this._renderAuthError(msg));
|
|
523
|
+
if (scroll) this.scrollToBottom();
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Handle info messages (e.g., compaction summary, /context results)
|
|
528
|
+
if (msg.role === 'info') {
|
|
529
|
+
const div = document.createElement('div');
|
|
530
|
+
div.id = `msg-${msg.id}`;
|
|
531
|
+
|
|
532
|
+
// Check if this is /context output - render as collapsible block
|
|
533
|
+
if (msg.source === 'local-command-stdout' && this._isContextOutput(msg.content)) {
|
|
534
|
+
div.className = 'message context';
|
|
535
|
+
div.innerHTML = this._renderContextBlock(msg.content, msg.timestamp);
|
|
536
|
+
} else if (msg.source === 'fork-reference') {
|
|
537
|
+
// Fork reference - show link to parent session
|
|
538
|
+
div.className = 'message info fork-reference';
|
|
539
|
+
const parentName = escapeHtml(msg.forkedFromName || 'parent session');
|
|
540
|
+
const parentId = msg.forkedFromId;
|
|
541
|
+
div.innerHTML = `
|
|
542
|
+
<div class="message-header">
|
|
543
|
+
<span class="message-role fork">
|
|
544
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
545
|
+
<circle cx="12" cy="18" r="3"/>
|
|
546
|
+
<circle cx="6" cy="6" r="3"/>
|
|
547
|
+
<circle cx="18" cy="6" r="3"/>
|
|
548
|
+
<path d="M18 9v1a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V9"/>
|
|
549
|
+
<line x1="12" y1="12" x2="12" y2="15"/>
|
|
550
|
+
</svg>
|
|
551
|
+
fork
|
|
552
|
+
</span>
|
|
553
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
554
|
+
</div>
|
|
555
|
+
<div class="message-content">
|
|
556
|
+
Forked from <a href="/app?session=${parentId}"
|
|
557
|
+
class="fork-parent-link"
|
|
558
|
+
target="_blank"
|
|
559
|
+
data-session-id="${parentId}"
|
|
560
|
+
data-tooltip="Open parent session in new tab">"${parentName}"</a>
|
|
561
|
+
<span class="fork-hint">— Claude has full context from the parent conversation</span>
|
|
562
|
+
</div>
|
|
563
|
+
`;
|
|
564
|
+
} else {
|
|
565
|
+
div.className = 'message info';
|
|
566
|
+
// Use markdown rendering for command output (has tables), plain text for simple info
|
|
567
|
+
const contentHtml = msg.source === 'local-command-stdout'
|
|
568
|
+
? `<div class="markdown-content">${this.ctx.markdown.render(msg.content)}</div>`
|
|
569
|
+
: escapeHtml(msg.content);
|
|
570
|
+
div.innerHTML = `
|
|
571
|
+
<div class="message-header">
|
|
572
|
+
<span class="message-role info">
|
|
573
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
574
|
+
<circle cx="12" cy="12" r="10"/>
|
|
575
|
+
<line x1="12" y1="16" x2="12" y2="12"/>
|
|
576
|
+
<line x1="12" y1="8" x2="12.01" y2="8"/>
|
|
577
|
+
</svg>
|
|
578
|
+
info
|
|
579
|
+
</span>
|
|
580
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
581
|
+
</div>
|
|
582
|
+
<div class="message-content">${contentHtml}</div>
|
|
583
|
+
`;
|
|
584
|
+
}
|
|
585
|
+
messageContainer.appendChild(div);
|
|
586
|
+
if (scroll) this.scrollToBottom();
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// Handle context usage indicators (from /context command or turn_summary)
|
|
591
|
+
// Upgrades existing partial bar or creates new full/partial bar
|
|
592
|
+
if (msg.role === 'context') {
|
|
593
|
+
const turnNumber = msg.turnNumber;
|
|
594
|
+
// Find existing bar with same turn number — but only replace if it's a
|
|
595
|
+
// partial/shimmer bar (live upgrade from turn_summary → context_update).
|
|
596
|
+
// Full bars from earlier compaction epochs keep their position (turn numbers
|
|
597
|
+
// restart after compaction, so T1 can appear multiple times).
|
|
598
|
+
const existingBar = turnNumber
|
|
599
|
+
? messageContainer.querySelector(`#turn-summary-T${turnNumber}`)
|
|
600
|
+
: null;
|
|
601
|
+
const isPartialBar = existingBar?.querySelector('.context-bar-loading');
|
|
602
|
+
const existingPartial = isPartialBar ? existingBar : null;
|
|
603
|
+
// Don't replace rate-limit token switcher with context bar
|
|
604
|
+
if (existingBar?.querySelector('.rate-limited-bar')) {
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
// Unique ID: use msg.id when available to avoid cross-epoch collisions
|
|
608
|
+
const barId = msg.id ? `turn-summary-${msg.id}` : (turnNumber ? `turn-summary-T${turnNumber}` : `turn-${Date.now()}`);
|
|
609
|
+
// Partial context messages (from turn_summary, before context fetch completes)
|
|
610
|
+
// render as shimmer bars showing tools/cost/duration but no context fill.
|
|
611
|
+
// Keyed on missing data, not the _partial flag: a sync merge can land
|
|
612
|
+
// full context data on a message without clearing the flag.
|
|
613
|
+
if (!msg.contextTokens) {
|
|
614
|
+
const div = document.createElement('div');
|
|
615
|
+
div.className = 'turn-summary-bar';
|
|
616
|
+
div.id = barId;
|
|
617
|
+
div.dataset.turnNumber = turnNumber || '';
|
|
618
|
+
div.dataset.cwd = msg.cwd || window.app?.activeSession?.cwd || '';
|
|
619
|
+
let headerHtml = '<div class="turn-header-row"><div class="turn-badge-group">';
|
|
620
|
+
if (turnNumber) headerHtml += `<span class="turn-number">T${turnNumber}</span>`;
|
|
621
|
+
headerHtml += '<span class="turn-expand-chevron" data-tooltip="Details">▼</span></div>';
|
|
622
|
+
headerHtml += '<div class="context-bar-mini context-bar-loading"></div></div>';
|
|
623
|
+
const toolsInline = this._buildToolsInline(msg.toolsSummary || {});
|
|
624
|
+
const filesHtml = this._buildFilesRowHtml(msg.changedFiles || [], msg.fileActions || {});
|
|
625
|
+
const toolsHtml = this._buildToolsRowHtml(toolsInline, this._formatDuration(msg.durationMs || 0), this._formatCost(msg.costUsd || 0), msg.model);
|
|
626
|
+
div.innerHTML = headerHtml + filesHtml + toolsHtml;
|
|
627
|
+
this._attachFilePillHandlers(div);
|
|
628
|
+
if (existingPartial) {
|
|
629
|
+
existingPartial.replaceWith(div);
|
|
630
|
+
} else {
|
|
631
|
+
messageContainer.appendChild(div);
|
|
632
|
+
}
|
|
633
|
+
this._repositionPlanApproval(messageContainer);
|
|
634
|
+
if (scroll) this.scrollToBottom();
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const div = this._renderContextIndicator(msg);
|
|
638
|
+
if (div) {
|
|
639
|
+
if (existingPartial) {
|
|
640
|
+
existingPartial.replaceWith(div);
|
|
641
|
+
} else {
|
|
642
|
+
messageContainer.appendChild(div);
|
|
643
|
+
}
|
|
644
|
+
this._repositionPlanApproval(messageContainer);
|
|
645
|
+
if (scroll) this.scrollToBottom();
|
|
646
|
+
}
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Handle real-time grouping for thinking messages
|
|
651
|
+
if (msg.role === 'thinking') {
|
|
652
|
+
this.thinkingCtrl.renderThinkingMessageWithGrouping(msg);
|
|
653
|
+
if (scroll) this.scrollToBottom();
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// Handle real-time grouping for tool messages
|
|
658
|
+
if (msg.role === 'tool') {
|
|
659
|
+
this._renderToolMessageWithGrouping(msg);
|
|
660
|
+
if (scroll) this.scrollToBottom();
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Handle AskUserQuestion - interactive question form
|
|
665
|
+
if (msg.role === 'question') {
|
|
666
|
+
const div = this._renderQuestionForm(msg);
|
|
667
|
+
messageContainer.appendChild(div);
|
|
668
|
+
if (scroll) this.scrollToBottom();
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// Handle ExitPlanMode - interactive plan approval
|
|
673
|
+
if (msg.role === 'plan_approval') {
|
|
674
|
+
const div = this._renderPlanApproval(msg);
|
|
675
|
+
messageContainer.appendChild(div);
|
|
676
|
+
if (scroll) this.scrollToBottom();
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// Handle interactive permission ask (claude-sdk can_use_tool)
|
|
681
|
+
if (msg.role === 'permission') {
|
|
682
|
+
const div = this._renderPermissionCard(msg);
|
|
683
|
+
messageContainer.appendChild(div);
|
|
684
|
+
if (scroll) this.scrollToBottom();
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
const div = document.createElement('div');
|
|
689
|
+
const planModeClass = msg.planMode ? ' plan-mode' : '';
|
|
690
|
+
div.className = `message ${msg.role}${planModeClass}`;
|
|
691
|
+
div.id = `msg-${msg.id}`;
|
|
692
|
+
|
|
693
|
+
const content = this._renderMessageContent(msg);
|
|
694
|
+
|
|
695
|
+
const copyButton = (msg.role === 'assistant' || msg.role === 'user') ? `
|
|
696
|
+
<button class="message-copy-btn" data-msg-id="${msg.id}" data-id="${escapeAttr(msg.id)}" data-act="copy-message" data-tooltip="Copy message">
|
|
697
|
+
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
698
|
+
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
|
|
699
|
+
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
700
|
+
</svg>
|
|
701
|
+
<span class="copy-label">Copy</span>
|
|
702
|
+
</button>
|
|
703
|
+
` : '';
|
|
704
|
+
|
|
705
|
+
// Favorite button for user messages (only if promptId is known)
|
|
706
|
+
const favoriteButton = (msg.role === 'user') ? `
|
|
707
|
+
<button class="message-favorite-btn${msg.isFavorite ? ' active' : ''}${msg.promptId ? '' : ' hidden'}"
|
|
708
|
+
data-msg-id="${msg.id}"
|
|
709
|
+
data-prompt-id="${msg.promptId || ''}"
|
|
710
|
+
data-act="toggle-message-favorite"
|
|
711
|
+
data-tooltip="${msg.isFavorite ? 'Remove from favorites' : 'Add to favorites'}">
|
|
712
|
+
<svg class="heart-outline" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
713
|
+
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
|
|
714
|
+
</svg>
|
|
715
|
+
<svg class="heart-filled" width="12" height="12" viewBox="0 0 24 24" fill="currentColor" stroke="none">
|
|
716
|
+
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
|
|
717
|
+
</svg>
|
|
718
|
+
</button>
|
|
719
|
+
` : '';
|
|
720
|
+
|
|
721
|
+
// Thinking indicator for user messages
|
|
722
|
+
const effortIndicator = msg.role === 'user' ? this._renderEffortIndicator(msg.effort_level) : '';
|
|
723
|
+
|
|
724
|
+
div.innerHTML = `
|
|
725
|
+
<div class="message-header">
|
|
726
|
+
<span class="message-role ${msg.role}">${this._authorLabel(msg)}</span>
|
|
727
|
+
${effortIndicator}
|
|
728
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
729
|
+
${favoriteButton}
|
|
730
|
+
${copyButton}
|
|
731
|
+
</div>
|
|
732
|
+
<div class="message-content">${content}</div>
|
|
733
|
+
`;
|
|
734
|
+
|
|
735
|
+
messageContainer.appendChild(div);
|
|
736
|
+
|
|
737
|
+
// Render excalidraw code blocks as SVG diagrams
|
|
738
|
+
MarkdownRenderer.processExcalidrawBlocks(div);
|
|
739
|
+
// Render Vega-Lite chart code blocks as SVG charts
|
|
740
|
+
MarkdownRenderer.processChartBlocks(div);
|
|
741
|
+
|
|
742
|
+
// Track new assistant messages for the "new messages" indicator
|
|
743
|
+
if (scroll && msg.role === 'assistant') {
|
|
744
|
+
this.ctx.scrollManager?.trackNewMessage();
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
if (scroll) this.scrollToBottom();
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Generate thinking indicator HTML for user messages
|
|
752
|
+
* Shows the thinking budget that was active when the message was sent
|
|
753
|
+
* @private
|
|
754
|
+
*/
|
|
755
|
+
_renderEffortIndicator(effortLevel) {
|
|
756
|
+
if (!effortLevel) return '';
|
|
757
|
+
|
|
758
|
+
const labels = { low: 'Lo', medium: 'Med', xhigh: 'XHi', max: 'Max' };
|
|
759
|
+
const label = labels[effortLevel] || effortLevel;
|
|
760
|
+
|
|
761
|
+
return `<span class="effort-indicator" data-level="${effortLevel}" data-tooltip="Effort: ${effortLevel}">
|
|
762
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="10" height="10">
|
|
763
|
+
<circle cx="12" cy="12" r="10"/>
|
|
764
|
+
<path d="M12 6v6l4 2" stroke-linecap="round"/>
|
|
765
|
+
</svg>
|
|
766
|
+
<span class="effort-indicator-label">${label}</span>
|
|
767
|
+
</span>`;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Render message content with attachment indicators
|
|
772
|
+
* Handles both new format (metadata fields) and old format (suffix in content)
|
|
773
|
+
* @private
|
|
774
|
+
*/
|
|
775
|
+
_renderMessageContent(msg) {
|
|
776
|
+
if (msg.role === 'assistant') {
|
|
777
|
+
return `<div class="markdown-content">${this.ctx.markdown.render(msg.content, msg.verifiedFiles)}</div>`;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// User message - render markdown, then append attachment indicators
|
|
781
|
+
let content = msg.content || '';
|
|
782
|
+
|
|
783
|
+
// Strip old format "[X images attached]" suffix before rendering
|
|
784
|
+
const oldFormatMatch = content.match(/\n\[(\d+ files?, )?(\d+) images? attached\]$/);
|
|
785
|
+
if (oldFormatMatch) {
|
|
786
|
+
content = content.slice(0, oldFormatMatch.index);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
let rendered = this.ctx.markdown.render(content, msg.verifiedFiles);
|
|
790
|
+
|
|
791
|
+
// Highlight thinking keywords after markdown rendering
|
|
792
|
+
if (isThinkingKeywordsHighlightingEnabled()) {
|
|
793
|
+
rendered = highlightThinkingKeywords(rendered);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
let displayText = `<div class="markdown-content">${rendered}</div>`;
|
|
797
|
+
|
|
798
|
+
// Render image thumbnails if available
|
|
799
|
+
if (msg.imageThumbnails && msg.imageThumbnails.length > 0) {
|
|
800
|
+
const thumbsHtml = msg.imageThumbnails.map(src =>
|
|
801
|
+
`<div class="message-image-thumb" data-src="${escapeHtml(src)}"><img src="${escapeHtml(src)}" alt="Attached image"></div>`
|
|
802
|
+
).join('');
|
|
803
|
+
displayText += `<div class="message-images">${thumbsHtml}</div>`;
|
|
804
|
+
} else if (msg.hasImages && msg.imageCount > 0) {
|
|
805
|
+
const attachments = [];
|
|
806
|
+
if (msg.hasFiles && msg.fileCount > 0) {
|
|
807
|
+
attachments.push(`${msg.fileCount} file${msg.fileCount > 1 ? 's' : ''}`);
|
|
808
|
+
}
|
|
809
|
+
attachments.push(`${msg.imageCount} image${msg.imageCount > 1 ? 's' : ''}`);
|
|
810
|
+
displayText += `<span class="attachment-indicator">[${attachments.join(', ')} attached]</span>`;
|
|
811
|
+
} else if (msg.hasFiles && msg.fileCount > 0) {
|
|
812
|
+
displayText += `<span class="attachment-indicator">[${msg.fileCount} file${msg.fileCount > 1 ? 's' : ''} attached]</span>`;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// Old format fallback indicator
|
|
816
|
+
if (oldFormatMatch) {
|
|
817
|
+
const suffix = oldFormatMatch[0].slice(1);
|
|
818
|
+
displayText += `<span class="attachment-indicator">${escapeHtml(suffix)}</span>`;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// Render stash references if attached
|
|
822
|
+
if (msg.hasRefs && msg.stashRefs && msg.stashRefs.length > 0) {
|
|
823
|
+
displayText += renderStashRefs(msg.stashRefs);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
return displayText;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// ═══════════════════════════════════════════════════════════════
|
|
830
|
+
// TURN SUMMARY BAR (formerly Context Indicator)
|
|
831
|
+
// ═══════════════════════════════════════════════════════════════
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Context-token count of the bar immediately preceding `msg` in the same
|
|
835
|
+
* session — the baseline for this turn's "added tokens" delta and the
|
|
836
|
+
* lighter "gain" segment of the mini bar.
|
|
837
|
+
*
|
|
838
|
+
* Derived from the session's ordered `messages` (the source of truth in
|
|
839
|
+
* every render path) instead of a mutable per-controller field, so the
|
|
840
|
+
* delta no longer depends on render order, lazy-load windows, tab switches,
|
|
841
|
+
* or which session rendered last. Partial (shimmer) bars carry no tokens
|
|
842
|
+
* and are skipped. Returns 0 when no prior context bar is loaded.
|
|
843
|
+
* @private
|
|
844
|
+
*/
|
|
845
|
+
_prevContextTokens(msg) {
|
|
846
|
+
const msgs = this.ctx.session?.messages;
|
|
847
|
+
if (!Array.isArray(msgs)) return 0;
|
|
848
|
+
// Locate this message, then walk back to the previous real context bar.
|
|
849
|
+
let idx = msg?.id ? msgs.findIndex(m => m.id === msg.id) : msgs.indexOf(msg);
|
|
850
|
+
if (idx < 0) idx = msgs.length; // Transient msg (not stored) → scan from end
|
|
851
|
+
for (let i = idx - 1; i >= 0; i--) {
|
|
852
|
+
const m = msgs[i];
|
|
853
|
+
if (m.role === 'context' && !m._partial && typeof m.contextTokens === 'number') {
|
|
854
|
+
return m.contextTokens;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
return 0;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Render a Turn Summary Bar after each turn completes.
|
|
862
|
+
* Shows: turn number, duration, cost, context bar, delta, files changed
|
|
863
|
+
* Expandable to show file list, tools used, and context breakdown.
|
|
864
|
+
* @private
|
|
865
|
+
*/
|
|
866
|
+
_renderContextIndicator(msg) {
|
|
867
|
+
const tokens = msg.contextTokens;
|
|
868
|
+
const ctxWindow = msg.contextWindow;
|
|
869
|
+
const percentage = msg.percentage || Math.round((tokens / ctxWindow) * 100);
|
|
870
|
+
|
|
871
|
+
// Baseline for this turn's "added tokens" delta + gain segment: the
|
|
872
|
+
// context bar immediately preceding this one in the SAME session, read
|
|
873
|
+
// from the ordered message list rather than a mutable field. Keeps the
|
|
874
|
+
// delta stable across the live path, full re-renders, lazy-load windows,
|
|
875
|
+
// tab switches, and compaction epochs. Turn numbers restart after a
|
|
876
|
+
// compaction/process restart, so a raw "last rendered anywhere" tracker
|
|
877
|
+
// mismeasured the first turn of a new epoch — e.g. showing +100k on a
|
|
878
|
+
// turn that changed nothing.
|
|
879
|
+
const prevContext = this._prevContextTokens(msg);
|
|
880
|
+
const delta = tokens - prevContext;
|
|
881
|
+
|
|
882
|
+
// Don't show if no change AND no turn number (e.g., duplicate /context call)
|
|
883
|
+
// Always render when there's a turnNumber — every turn deserves its bar
|
|
884
|
+
if (delta === 0 && prevContext > 0 && !msg.turnNumber) return null;
|
|
885
|
+
|
|
886
|
+
// Format helpers
|
|
887
|
+
const formatK = (n) => {
|
|
888
|
+
const abs = Math.abs(n);
|
|
889
|
+
if (abs >= 1000) return `${(n / 1000).toFixed(1)}k`;
|
|
890
|
+
return String(n);
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
// Calculate reserved buffer percentage (from breakdown if available)
|
|
894
|
+
const reservedBuffer = msg.breakdown?.autocompact_buffer?.tokens || 0;
|
|
895
|
+
const reservedPct = Math.round((reservedBuffer / ctxWindow) * 100);
|
|
896
|
+
|
|
897
|
+
// Calculate effective percentage (used / usable window, excluding reserved)
|
|
898
|
+
const usableWindow = ctxWindow - reservedBuffer;
|
|
899
|
+
const effectivePct = reservedBuffer > 0 ? Math.round((tokens / usableWindow) * 100) : percentage;
|
|
900
|
+
|
|
901
|
+
// Determine status class based on EFFECTIVE usage (what actually matters)
|
|
902
|
+
let statusClass = '';
|
|
903
|
+
let statusIcon = '';
|
|
904
|
+
if (effectivePct >= 95) {
|
|
905
|
+
statusClass = 'critical';
|
|
906
|
+
statusIcon = '⚠️';
|
|
907
|
+
} else if (effectivePct >= 85) {
|
|
908
|
+
statusClass = 'danger';
|
|
909
|
+
statusIcon = '⚡';
|
|
910
|
+
} else if (effectivePct >= 70) {
|
|
911
|
+
statusClass = 'warning';
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// Delta display
|
|
915
|
+
const deltaText = delta > 0 ? `+${formatK(delta)}` : formatK(delta);
|
|
916
|
+
|
|
917
|
+
// Turn data from server
|
|
918
|
+
const turnNumber = msg.turnNumber || null;
|
|
919
|
+
const durationMs = msg.durationMs || 0;
|
|
920
|
+
const costUsd = msg.costUsd || 0;
|
|
921
|
+
const changedFiles = msg.changedFiles || [];
|
|
922
|
+
const toolsSummary = msg.toolsSummary || {};
|
|
923
|
+
const fileActions = msg.fileActions || {};
|
|
924
|
+
const readImages = msg.readImages || [];
|
|
925
|
+
|
|
926
|
+
// Format turn data
|
|
927
|
+
const durationStr = this._formatDuration(durationMs);
|
|
928
|
+
const costStr = this._formatCost(costUsd);
|
|
929
|
+
const fileCount = changedFiles.length;
|
|
930
|
+
|
|
931
|
+
// Build tools summary string (e.g., "Edit ×3 Bash ×2 Read ×5")
|
|
932
|
+
const toolsStr = Object.entries(toolsSummary)
|
|
933
|
+
.sort((a, b) => b[1] - a[1]) // Sort by count descending
|
|
934
|
+
.map(([name, count]) => `${name} ×${count}`)
|
|
935
|
+
.join(' ');
|
|
936
|
+
|
|
937
|
+
const div = document.createElement('div');
|
|
938
|
+
div.className = `turn-summary-bar ${statusClass}`;
|
|
939
|
+
div.id = msg.id ? `turn-summary-${msg.id}` : (turnNumber ? `turn-summary-T${turnNumber}` : `turn-${Date.now()}`);
|
|
940
|
+
if (turnNumber) div.dataset.turnNumber = String(turnNumber);
|
|
941
|
+
if (msg.dbTurnId) div.dataset.turnId = msg.dbTurnId;
|
|
942
|
+
|
|
943
|
+
// Store cwd for file preview (use msg.cwd from server, fallback to active session)
|
|
944
|
+
const sessionCwd = msg.cwd || window.app?.activeSession?.cwd || '';
|
|
945
|
+
div.dataset.cwd = sessionCwd;
|
|
946
|
+
|
|
947
|
+
// Bar math
|
|
948
|
+
const prevEffective = prevContext > 0 && usableWindow > 0 ? Math.round((prevContext / usableWindow) * 100) : 0;
|
|
949
|
+
const gainEffectivePct = Math.max(0, effectivePct - prevEffective);
|
|
950
|
+
const freePct = 100 - effectivePct;
|
|
951
|
+
|
|
952
|
+
const toolsInline = this._buildToolsInline(toolsSummary);
|
|
953
|
+
|
|
954
|
+
// Build header row HTML - [T16 ▼] [bar] [+11k]
|
|
955
|
+
let headerHtml = '<div class="turn-header-row">';
|
|
956
|
+
|
|
957
|
+
// Turn number + chevron grouped together (no gap between them)
|
|
958
|
+
headerHtml += '<div class="turn-badge-group">';
|
|
959
|
+
if (turnNumber) {
|
|
960
|
+
headerHtml += `<span class="turn-number">T${turnNumber}</span>`;
|
|
961
|
+
}
|
|
962
|
+
headerHtml += `<span class="turn-expand-chevron" data-tooltip="Details">▼</span>`;
|
|
963
|
+
headerHtml += '</div>';
|
|
964
|
+
|
|
965
|
+
// Full-width context bar with fill segments and gain visualization
|
|
966
|
+
const prevFillPct = Math.max(0, effectivePct - gainEffectivePct);
|
|
967
|
+
headerHtml += `
|
|
968
|
+
<div class="context-bar-mini ${statusClass}">
|
|
969
|
+
<div class="context-fill-mini" style="width: ${prevFillPct}%"></div>
|
|
970
|
+
<div class="context-gain-mini" style="left: ${prevFillPct}%; width: ${gainEffectivePct}%"></div>
|
|
971
|
+
<div class="context-bar-text">
|
|
972
|
+
<span class="context-pct-effective">${statusIcon}${effectivePct}%</span>
|
|
973
|
+
<span class="context-tokens">${formatK(tokens)}/${formatK(usableWindow)}</span>
|
|
974
|
+
</div>
|
|
975
|
+
</div>`;
|
|
976
|
+
|
|
977
|
+
// Delta display (token gain/loss this turn)
|
|
978
|
+
if (delta !== 0) {
|
|
979
|
+
headerHtml += `<span class="context-delta ${delta > 0 ? 'up' : 'down'}">${deltaText}</span>`;
|
|
980
|
+
}
|
|
981
|
+
headerHtml += '</div>';
|
|
982
|
+
|
|
983
|
+
const sessionFiles = this._getSessionFiles(changedFiles);
|
|
984
|
+
const filesHtml = this._buildFilesRowHtml(changedFiles, fileActions, sessionFiles, readImages, sessionCwd);
|
|
985
|
+
const toolsHtml = this._buildToolsRowHtml(toolsInline, durationStr, costStr, msg.model);
|
|
986
|
+
|
|
987
|
+
// Build expanded details HTML - context breakdown (cost moved to tools row)
|
|
988
|
+
let expandedHtml = '<div class="turn-expanded-details">';
|
|
989
|
+
|
|
990
|
+
// Context breakdown
|
|
991
|
+
if (msg.breakdown) {
|
|
992
|
+
expandedHtml += this._renderContextBreakdown(msg.breakdown);
|
|
993
|
+
} else {
|
|
994
|
+
expandedHtml += `<div class="turn-context-simple">${formatK(tokens)} / ${formatK(usableWindow)} tokens (${effectivePct}% used)</div>`;
|
|
995
|
+
}
|
|
996
|
+
expandedHtml += '</div>';
|
|
997
|
+
|
|
998
|
+
div.innerHTML = headerHtml + filesHtml + toolsHtml + expandedHtml;
|
|
999
|
+
|
|
1000
|
+
// Store msg for later use
|
|
1001
|
+
div._contextMsg = msg;
|
|
1002
|
+
|
|
1003
|
+
// Expand toggle - only on chevron or header row (not files/tools)
|
|
1004
|
+
const handleExpandToggle = (e) => {
|
|
1005
|
+
// Prevent keyboard on iOS
|
|
1006
|
+
e.preventDefault();
|
|
1007
|
+
if (document.activeElement && document.activeElement.blur) {
|
|
1008
|
+
document.activeElement.blur();
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// Don't toggle when clicking interactive elements
|
|
1012
|
+
if (e.target.closest('.turn-file-pill') ||
|
|
1013
|
+
e.target.closest('.session-file-row') ||
|
|
1014
|
+
e.target.closest('.session-compact-file') ||
|
|
1015
|
+
e.target.closest('button') ||
|
|
1016
|
+
e.target.closest('a')) {
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
const wasExpanded = div.classList.contains('expanded');
|
|
1021
|
+
div.classList.toggle('expanded');
|
|
1022
|
+
|
|
1023
|
+
if (!wasExpanded) {
|
|
1024
|
+
// Lazy-load session files on first expand
|
|
1025
|
+
if (!div._sessionFilesRendered) {
|
|
1026
|
+
this._renderSessionFilesExpanded(div);
|
|
1027
|
+
}
|
|
1028
|
+
requestAnimationFrame(() => {
|
|
1029
|
+
div.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
};
|
|
1033
|
+
|
|
1034
|
+
bindTapHandler(div, handleExpandToggle);
|
|
1035
|
+
|
|
1036
|
+
this._attachFilePillHandlers(div);
|
|
1037
|
+
this._attachCompactFileHandlers(div);
|
|
1038
|
+
|
|
1039
|
+
// Async git status decoration (fire-and-forget)
|
|
1040
|
+
setTimeout(() => this._fetchGitStatusForTurn(div), 0);
|
|
1041
|
+
|
|
1042
|
+
return div;
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Render a partial Turn Summary Bar immediately when turn completes.
|
|
1047
|
+
* Shows files, tools, cost, duration — but no context bar (still loading).
|
|
1048
|
+
* Will be upgraded in-place when context_update arrives.
|
|
1049
|
+
* @param {Object} msg - turn_summary message from server
|
|
1050
|
+
*/
|
|
1051
|
+
renderTurnSummaryPartial(msg) {
|
|
1052
|
+
const messageContainer = this._getActiveMessageContainer();
|
|
1053
|
+
if (!messageContainer) return;
|
|
1054
|
+
|
|
1055
|
+
const turnNumber = msg.turnNumber || null;
|
|
1056
|
+
const durationMs = msg.durationMs || 0;
|
|
1057
|
+
const costUsd = msg.costUsd || 0;
|
|
1058
|
+
const changedFiles = msg.changedFiles || [];
|
|
1059
|
+
const toolsSummary = msg.toolsSummary || {};
|
|
1060
|
+
const fileActions = msg.fileActions || {};
|
|
1061
|
+
const readImages = msg.readImages || [];
|
|
1062
|
+
|
|
1063
|
+
const durationStr = this._formatDuration(durationMs);
|
|
1064
|
+
const costStr = this._formatCost(costUsd);
|
|
1065
|
+
const toolsInline = this._buildToolsInline(toolsSummary);
|
|
1066
|
+
|
|
1067
|
+
const div = document.createElement('div');
|
|
1068
|
+
div.className = 'turn-summary-bar';
|
|
1069
|
+
div.id = turnNumber ? `turn-summary-T${turnNumber}` : `turn-${Date.now()}`;
|
|
1070
|
+
|
|
1071
|
+
const sessionCwd = msg.cwd || window.app?.activeSession?.cwd || '';
|
|
1072
|
+
div.dataset.cwd = sessionCwd;
|
|
1073
|
+
if (msg.dbTurnId) div.dataset.turnId = msg.dbTurnId;
|
|
1074
|
+
|
|
1075
|
+
// Header row with turn badge + context bar (or rate-limit switcher)
|
|
1076
|
+
let headerHtml = '<div class="turn-header-row">';
|
|
1077
|
+
headerHtml += '<div class="turn-badge-group">';
|
|
1078
|
+
if (turnNumber) {
|
|
1079
|
+
headerHtml += `<span class="turn-number">T${turnNumber}</span>`;
|
|
1080
|
+
}
|
|
1081
|
+
headerHtml += `<span class="turn-expand-chevron" data-tooltip="Details">▼</span>`;
|
|
1082
|
+
headerHtml += '</div>';
|
|
1083
|
+
|
|
1084
|
+
if (msg.rateLimited) {
|
|
1085
|
+
headerHtml += `<div class="context-bar-mini rate-limited-bar">
|
|
1086
|
+
<div class="context-bar-text">
|
|
1087
|
+
<span class="rate-limit-label">Switch token:</span>
|
|
1088
|
+
<span class="rate-limit-profiles"></span>
|
|
1089
|
+
</div>
|
|
1090
|
+
</div>`;
|
|
1091
|
+
} else {
|
|
1092
|
+
headerHtml += '<div class="context-bar-mini context-bar-loading"></div>';
|
|
1093
|
+
}
|
|
1094
|
+
headerHtml += '</div>';
|
|
1095
|
+
|
|
1096
|
+
const sessionFiles = this._getSessionFiles(changedFiles);
|
|
1097
|
+
const filesHtml = this._buildFilesRowHtml(changedFiles, fileActions, sessionFiles, readImages, sessionCwd);
|
|
1098
|
+
const toolsHtml = this._buildToolsRowHtml(toolsInline, durationStr, costStr, msg.model);
|
|
1099
|
+
|
|
1100
|
+
div.innerHTML = headerHtml + filesHtml + toolsHtml;
|
|
1101
|
+
this._attachFilePillHandlers(div);
|
|
1102
|
+
this._attachCompactFileHandlers(div);
|
|
1103
|
+
|
|
1104
|
+
messageContainer.appendChild(div);
|
|
1105
|
+
this._repositionPlanApproval(messageContainer);
|
|
1106
|
+
|
|
1107
|
+
if (msg.rateLimited) {
|
|
1108
|
+
this._initRateLimitSwitcher(div);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
this.scrollToBottom();
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* Initialize rate-limit token profile switcher inside a turn summary bar.
|
|
1116
|
+
* Fetches available profiles and wires up the apply button.
|
|
1117
|
+
* @private
|
|
1118
|
+
*/
|
|
1119
|
+
_initRateLimitSwitcher(barEl) {
|
|
1120
|
+
const container = barEl.querySelector('.rate-limit-profiles');
|
|
1121
|
+
if (!container) return;
|
|
1122
|
+
|
|
1123
|
+
// Use tokenProfile's color function if available
|
|
1124
|
+
const getColor = window.tokenProfile?.constructor
|
|
1125
|
+
? (name) => {
|
|
1126
|
+
const colors = ['#4a9eff','#67c23a','#e6a23c','#f56c6c','#b37feb','#36cfc9','#ff85c0','#ffd666'];
|
|
1127
|
+
let h = 0;
|
|
1128
|
+
for (let i = 0; i < name.length; i++) h = ((h << 5) - h + name.charCodeAt(i)) | 0;
|
|
1129
|
+
return colors[Math.abs(h) % colors.length];
|
|
1130
|
+
}
|
|
1131
|
+
: () => 'var(--text-secondary)';
|
|
1132
|
+
|
|
1133
|
+
fetch('/api/app/token-profiles')
|
|
1134
|
+
.then(r => r.json())
|
|
1135
|
+
.then(data => {
|
|
1136
|
+
if (!data.profiles?.length) {
|
|
1137
|
+
container.textContent = 'No profiles available';
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
for (const p of data.profiles) {
|
|
1141
|
+
const btn = document.createElement('button');
|
|
1142
|
+
btn.className = 'rate-limit-profile-btn';
|
|
1143
|
+
btn.dataset.profile = p.name;
|
|
1144
|
+
const dot = document.createElement('span');
|
|
1145
|
+
dot.className = 'rate-limit-dot';
|
|
1146
|
+
dot.style.background = getColor(p.name);
|
|
1147
|
+
btn.appendChild(dot);
|
|
1148
|
+
btn.appendChild(document.createTextNode(p.name));
|
|
1149
|
+
container.appendChild(btn);
|
|
1150
|
+
}
|
|
1151
|
+
})
|
|
1152
|
+
.catch(() => {
|
|
1153
|
+
container.textContent = 'Error loading profiles';
|
|
1154
|
+
});
|
|
1155
|
+
|
|
1156
|
+
container.addEventListener('click', (e) => {
|
|
1157
|
+
const btn = e.target.closest('.rate-limit-profile-btn');
|
|
1158
|
+
if (!btn) return;
|
|
1159
|
+
// Update the toolbar button state — will be sent with next message
|
|
1160
|
+
window.tokenProfile?.selectProfile(btn.dataset.profile);
|
|
1161
|
+
btn.classList.add('applied');
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
/**
|
|
1166
|
+
* Move any plan-approval card to appear after the last turn-summary-bar.
|
|
1167
|
+
* Called after turn summary renders so the approval card sits at the end of the turn.
|
|
1168
|
+
* @private
|
|
1169
|
+
*/
|
|
1170
|
+
_repositionPlanApproval(container) {
|
|
1171
|
+
const approvals = container.querySelectorAll('.message.plan-approval:not(.answered)');
|
|
1172
|
+
if (!approvals.length) return;
|
|
1173
|
+
|
|
1174
|
+
const lastApproval = approvals[approvals.length - 1];
|
|
1175
|
+
const bars = container.querySelectorAll('.turn-summary-bar');
|
|
1176
|
+
if (!bars.length) return;
|
|
1177
|
+
|
|
1178
|
+
const lastBar = bars[bars.length - 1];
|
|
1179
|
+
|
|
1180
|
+
// If approval comes before bar in DOM order, move it after
|
|
1181
|
+
if (lastApproval.compareDocumentPosition(lastBar) & Node.DOCUMENT_POSITION_FOLLOWING) {
|
|
1182
|
+
lastBar.after(lastApproval);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/**
|
|
1187
|
+
* Render context breakdown HTML for expanded view
|
|
1188
|
+
* @private
|
|
1189
|
+
*/
|
|
1190
|
+
_renderContextBreakdown(breakdown) {
|
|
1191
|
+
const formatK = (n) => {
|
|
1192
|
+
if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
|
|
1193
|
+
return String(n);
|
|
1194
|
+
};
|
|
1195
|
+
|
|
1196
|
+
const order = ['system_prompt', 'system_tools', 'custom_agents', 'memory_files', 'skills', 'messages', 'free_space', 'autocompact_buffer'];
|
|
1197
|
+
const labels = {
|
|
1198
|
+
system_prompt: 'System prompt',
|
|
1199
|
+
system_tools: 'Tool definitions',
|
|
1200
|
+
custom_agents: 'Custom agents',
|
|
1201
|
+
memory_files: 'Memory files',
|
|
1202
|
+
skills: 'Skills',
|
|
1203
|
+
messages: 'Conversation',
|
|
1204
|
+
free_space: 'Free space',
|
|
1205
|
+
autocompact_buffer: 'Reserved buffer'
|
|
1206
|
+
};
|
|
1207
|
+
|
|
1208
|
+
// Collect valid items
|
|
1209
|
+
const items = [];
|
|
1210
|
+
for (const key of order) {
|
|
1211
|
+
if (breakdown[key]) {
|
|
1212
|
+
const { tokens, pct } = breakdown[key];
|
|
1213
|
+
const isFree = key === 'free_space' || key === 'autocompact_buffer';
|
|
1214
|
+
items.push({ label: labels[key] || key, tokens, pct, muted: isFree });
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// Flipped table: labels as column headers, values below
|
|
1219
|
+
let html = '<table class="turn-context-breakdown">';
|
|
1220
|
+
// Header row — all labels
|
|
1221
|
+
html += '<tr>';
|
|
1222
|
+
for (const item of items) {
|
|
1223
|
+
const cls = item.muted ? ' class="muted"' : '';
|
|
1224
|
+
html += `<th${cls}>${item.label}</th>`;
|
|
1225
|
+
}
|
|
1226
|
+
html += '</tr>';
|
|
1227
|
+
// Values row — tokens + pct combined
|
|
1228
|
+
html += '<tr>';
|
|
1229
|
+
for (const item of items) {
|
|
1230
|
+
const mutedCls = item.muted ? ' muted' : '';
|
|
1231
|
+
html += `<td><span class="breakdown-tokens${mutedCls}">${formatK(item.tokens)}</span> <span class="breakdown-pct${mutedCls}">${item.pct.toFixed(1)}%</span></td>`;
|
|
1232
|
+
}
|
|
1233
|
+
html += '</tr>';
|
|
1234
|
+
html += '</table>';
|
|
1235
|
+
return html;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/** @private */
|
|
1239
|
+
_formatDuration(ms) {
|
|
1240
|
+
if (!ms || ms <= 0) return null;
|
|
1241
|
+
const sec = Math.floor(ms / 1000);
|
|
1242
|
+
if (sec < 60) return `${sec}s`;
|
|
1243
|
+
const min = Math.floor(sec / 60);
|
|
1244
|
+
const remSec = sec % 60;
|
|
1245
|
+
return remSec > 0 ? `${min}m ${remSec}s` : `${min}m`;
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/** @private */
|
|
1249
|
+
_formatCost(usd) {
|
|
1250
|
+
if (!usd || usd <= 0) return null;
|
|
1251
|
+
if (usd < 0.01) return `$${usd.toFixed(3)}`;
|
|
1252
|
+
if (usd < 0.10) return `$${usd.toFixed(2)}`;
|
|
1253
|
+
return `$${usd.toFixed(2)}`;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/** @private */
|
|
1257
|
+
_buildToolsInline(toolsSummary) {
|
|
1258
|
+
return Object.entries(toolsSummary)
|
|
1259
|
+
.sort((a, b) => b[1] - a[1])
|
|
1260
|
+
.slice(0, 4)
|
|
1261
|
+
.map(([name, count]) => `${name} ×${count}`)
|
|
1262
|
+
.join(' • ');
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/** @private */
|
|
1266
|
+
_buildFilesRowHtml(changedFiles, fileActions, sessionFiles, readImages, cwd) {
|
|
1267
|
+
const escHtml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
1268
|
+
const changedSet = new Set(changedFiles || []);
|
|
1269
|
+
const turnImages = (readImages || []).filter(fp => FILES_ROW_IMAGE_RE.test(fp) && !changedSet.has(fp));
|
|
1270
|
+
|
|
1271
|
+
// Filter out user-hidden session files
|
|
1272
|
+
const hiddenSet = this._hiddenSessionFiles.get(window.app?.activeSession?.id) || new Set();
|
|
1273
|
+
const visibleSession = sessionFiles ? [...sessionFiles.entries()].filter(([fp]) => !hiddenSet.has(fp)) : [];
|
|
1274
|
+
|
|
1275
|
+
// Row budget: current-turn pills (changed + image thumbs) always render
|
|
1276
|
+
// in full, even past the cap. Session-accumulated pills fill the
|
|
1277
|
+
// remaining slots — changed files first, image thumbs last. Truncation
|
|
1278
|
+
// always drops the OLDEST items; display stays chronological
|
|
1279
|
+
// (oldest → newest), matching the session-changed pill convention.
|
|
1280
|
+
let budget = Math.max(0, FILES_ROW_CAP - changedSet.size - turnImages.length);
|
|
1281
|
+
const sessionChanged = budget > 0 ? visibleSession.slice(-budget) : [];
|
|
1282
|
+
budget -= sessionChanged.length;
|
|
1283
|
+
let sessionImages = [];
|
|
1284
|
+
if (budget > 0) {
|
|
1285
|
+
// Never show a thumb for a file modified anywhere in the session
|
|
1286
|
+
// (or hidden by the user) — changed pills own those paths.
|
|
1287
|
+
const exclude = new Set([...changedSet, ...turnImages, ...hiddenSet]);
|
|
1288
|
+
if (sessionFiles) for (const fp of sessionFiles.keys()) exclude.add(fp);
|
|
1289
|
+
const taken = [];
|
|
1290
|
+
for (const group of this._getSessionReadImages(exclude)) { // newest turn first
|
|
1291
|
+
if (budget <= 0) break;
|
|
1292
|
+
const take = group.slice(0, budget);
|
|
1293
|
+
taken.push(take);
|
|
1294
|
+
budget -= take.length;
|
|
1295
|
+
}
|
|
1296
|
+
sessionImages = taken.reverse().flat(); // display oldest → newest
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
const hasChanged = changedSet.size > 0;
|
|
1300
|
+
const hasImages = turnImages.length > 0 || sessionImages.length > 0;
|
|
1301
|
+
if (!hasChanged && sessionChanged.length === 0 && !hasImages) return '';
|
|
1302
|
+
|
|
1303
|
+
let html = '<div class="turn-files-row">';
|
|
1304
|
+
if (hasChanged) {
|
|
1305
|
+
for (const filePath of changedFiles) {
|
|
1306
|
+
const fileName = basename(filePath);
|
|
1307
|
+
const stats = fileActions[filePath] || {};
|
|
1308
|
+
const adds = stats.adds || 0;
|
|
1309
|
+
const dels = stats.dels || 0;
|
|
1310
|
+
const isNew = stats.created || false;
|
|
1311
|
+
|
|
1312
|
+
let pillContent = `<span class="file-name">${escHtml(fileName)}</span>`;
|
|
1313
|
+
if (isNew) pillContent += `<span class="file-new">new</span>`;
|
|
1314
|
+
if (adds > 0) pillContent += `<span class="file-adds">+${adds}</span>`;
|
|
1315
|
+
if (dels > 0) pillContent += `<span class="file-dels">-${dels}</span>`;
|
|
1316
|
+
|
|
1317
|
+
html += `<span class="turn-file-pill" data-file-path="${escHtml(filePath)}"${isNew ? ' data-file-created="true"' : ''} data-tooltip="${escHtml(filePath)}">${pillContent}</span>`;
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
if (sessionChanged.length > 0) {
|
|
1321
|
+
if (hasChanged) html += '<span class="turn-files-sep"></span>';
|
|
1322
|
+
for (const [fp, stats] of sessionChanged) {
|
|
1323
|
+
const name = basename(fp);
|
|
1324
|
+
let pillContent = `<span class="file-name">${escHtml(name)}</span>`;
|
|
1325
|
+
if (stats.created) pillContent += `<span class="file-new">new</span>`;
|
|
1326
|
+
if (stats.adds > 0) pillContent += `<span class="file-adds">+${stats.adds}</span>`;
|
|
1327
|
+
if (stats.dels > 0) pillContent += `<span class="file-dels">-${stats.dels}</span>`;
|
|
1328
|
+
pillContent += `<span class="session-file-hide" data-hide-path="${escHtml(fp)}" data-tooltip="Hide">×</span>`;
|
|
1329
|
+
html += `<span class="turn-file-pill session-compact-file" data-file-path="${escHtml(fp)}"${stats.created ? ' data-file-created="true"' : ''} data-tooltip="${escHtml(fp)}">${pillContent}</span>`;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
if (hasImages) {
|
|
1333
|
+
if (hasChanged || sessionChanged.length > 0) html += '<span class="turn-files-sep"></span>';
|
|
1334
|
+
// Thumbs keep .turn-read-file so git-dot exclusion and pill handlers
|
|
1335
|
+
// apply; a tap routes through previewFile → image gallery, where
|
|
1336
|
+
// collectImages() picks these pills up for session-wide navigation.
|
|
1337
|
+
const thumb = (fp, extraClass, tooltip) => {
|
|
1338
|
+
const full = isAbsolutePath(fp) ? fp : (cwd ? joinPath(cwd, fp) : fp);
|
|
1339
|
+
return `<span class="turn-file-pill turn-read-file turn-image-thumb${extraClass}" data-file-path="${escHtml(fp)}" data-tooltip="${escHtml(tooltip.replace('{path}', fp))}"><img src="/api/file-raw?path=${encodeURIComponent(full)}" alt="${escHtml(basename(fp))}" loading="lazy"></span>`;
|
|
1340
|
+
};
|
|
1341
|
+
for (const fp of turnImages) html += thumb(fp, '', S.turn_bar.read_tooltip);
|
|
1342
|
+
for (const fp of sessionImages) html += thumb(fp, ' session-read', S.turn_bar.read_session_tooltip);
|
|
1343
|
+
}
|
|
1344
|
+
html += '</div>';
|
|
1345
|
+
return html;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/** @private */
|
|
1349
|
+
_buildToolsRowHtml(toolsInline, durationStr, costStr, modelId) {
|
|
1350
|
+
if (!toolsInline && !durationStr && !costStr) return '';
|
|
1351
|
+
let html = '<div class="turn-tools-row">';
|
|
1352
|
+
if (toolsInline) {
|
|
1353
|
+
html += `<span class="turn-tools-list">${toolsInline}</span>`;
|
|
1354
|
+
}
|
|
1355
|
+
html += `<span class="turn-expand-hint">${S.turn_bar.expand_hint}</span>`;
|
|
1356
|
+
html += '<span class="turn-right-stats">';
|
|
1357
|
+
if (modelId) {
|
|
1358
|
+
const short = modelId.replace('claude-', '').replace(/-\d{8}$/, '');
|
|
1359
|
+
html += `<span class="turn-model-inline">${short}</span>`;
|
|
1360
|
+
html += '<span class="turn-stats-sep">•</span>';
|
|
1361
|
+
}
|
|
1362
|
+
if (costStr) {
|
|
1363
|
+
html += `<span class="turn-cost-inline">${costStr}</span>`;
|
|
1364
|
+
}
|
|
1365
|
+
if (durationStr) {
|
|
1366
|
+
if (costStr) html += '<span class="turn-stats-sep">•</span>';
|
|
1367
|
+
html += `<span class="turn-duration-inline">${durationStr}</span>`;
|
|
1368
|
+
}
|
|
1369
|
+
html += '</span>';
|
|
1370
|
+
html += '</div>';
|
|
1371
|
+
return html;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* Get session-accumulated files (from previous turns), excluding current turn files.
|
|
1376
|
+
* Returns Map of path → { adds, dels, created } or null if empty.
|
|
1377
|
+
* @private
|
|
1378
|
+
*/
|
|
1379
|
+
_getSessionFiles(currentChangedFiles) {
|
|
1380
|
+
const session = window.app?.activeSession;
|
|
1381
|
+
if (!session) return null;
|
|
1382
|
+
|
|
1383
|
+
const currentSet = new Set(currentChangedFiles || []);
|
|
1384
|
+
const sessionFiles = new Map();
|
|
1385
|
+
|
|
1386
|
+
for (const msg of session.messages) {
|
|
1387
|
+
if (msg.role !== 'context' || !msg.changedFiles) continue;
|
|
1388
|
+
for (const fp of msg.changedFiles) {
|
|
1389
|
+
if (currentSet.has(fp)) continue;
|
|
1390
|
+
if (!sessionFiles.has(fp)) sessionFiles.set(fp, { adds: 0, dels: 0, created: false });
|
|
1391
|
+
const entry = sessionFiles.get(fp);
|
|
1392
|
+
const actions = msg.fileActions?.[fp];
|
|
1393
|
+
if (actions) {
|
|
1394
|
+
entry.adds += actions.adds || 0;
|
|
1395
|
+
entry.dels += actions.dels || 0;
|
|
1396
|
+
if (actions.created) entry.created = true;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
return sessionFiles.size > 0 ? sessionFiles : null;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* Get Read-tool images accumulated from previous turns, as one group per
|
|
1406
|
+
* turn, NEWEST turn first (so budget truncation keeps the most recent
|
|
1407
|
+
* shots) with in-turn read order preserved. Callers reverse the kept
|
|
1408
|
+
* groups for chronological display. Mirrors _getSessionFiles.
|
|
1409
|
+
* @private
|
|
1410
|
+
*/
|
|
1411
|
+
_getSessionReadImages(excludeSet) {
|
|
1412
|
+
const session = window.app?.activeSession;
|
|
1413
|
+
if (!session) return [];
|
|
1414
|
+
|
|
1415
|
+
const groups = [];
|
|
1416
|
+
const seen = new Set();
|
|
1417
|
+
for (let i = session.messages.length - 1; i >= 0; i--) {
|
|
1418
|
+
const msg = session.messages[i];
|
|
1419
|
+
if (msg.role !== 'context' || !msg.readImages) continue;
|
|
1420
|
+
const group = [];
|
|
1421
|
+
for (const fp of msg.readImages) {
|
|
1422
|
+
if (!FILES_ROW_IMAGE_RE.test(fp) || seen.has(fp) || excludeSet.has(fp)) continue;
|
|
1423
|
+
seen.add(fp);
|
|
1424
|
+
group.push(fp);
|
|
1425
|
+
}
|
|
1426
|
+
if (group.length) groups.push(group);
|
|
1427
|
+
}
|
|
1428
|
+
return groups;
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
/**
|
|
1432
|
+
* Attach click/touch handlers to .turn-file-pill elements within a container.
|
|
1433
|
+
* @private
|
|
1434
|
+
*/
|
|
1435
|
+
_attachFilePillHandlers(container) {
|
|
1436
|
+
// Image thumbs whose file vanished (test screenshots get overwritten
|
|
1437
|
+
// between runs) would render as broken-image glyphs — hide them.
|
|
1438
|
+
container.querySelectorAll('.turn-image-thumb img').forEach(img => {
|
|
1439
|
+
img.addEventListener('error', () => {
|
|
1440
|
+
img.closest('.turn-image-thumb')?.remove();
|
|
1441
|
+
}, { once: true });
|
|
1442
|
+
});
|
|
1443
|
+
container.querySelectorAll('.turn-file-pill').forEach(pill => {
|
|
1444
|
+
const handleFileTap = async (e) => {
|
|
1445
|
+
e.preventDefault();
|
|
1446
|
+
e.stopPropagation();
|
|
1447
|
+
if (document.activeElement && document.activeElement.blur) {
|
|
1448
|
+
document.activeElement.blur();
|
|
1449
|
+
}
|
|
1450
|
+
const filePath = pill.dataset.filePath;
|
|
1451
|
+
const cwd = container.dataset.cwd;
|
|
1452
|
+
if (!filePath) return;
|
|
1453
|
+
const fullPath = isAbsolutePath(filePath) ? filePath : (cwd ? joinPath(cwd, filePath) : filePath);
|
|
1454
|
+
|
|
1455
|
+
if ((e.metaKey || e.ctrlKey) && e.shiftKey) {
|
|
1456
|
+
// Cmd+Shift+Click → foreground new tab
|
|
1457
|
+
this._openFileInTab(fullPath);
|
|
1458
|
+
return;
|
|
1459
|
+
} else if (e.metaKey || e.ctrlKey) {
|
|
1460
|
+
// Cmd/Ctrl+Click → background tab (browser convention)
|
|
1461
|
+
this._openFileInTab(fullPath, { background: true });
|
|
1462
|
+
return;
|
|
1463
|
+
} else {
|
|
1464
|
+
// Default → plain file preview
|
|
1465
|
+
this._openFilePreviewDirect(fullPath);
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
bindTapHandler(pill, handleFileTap);
|
|
1469
|
+
pill.addEventListener('auxclick', (e) => {
|
|
1470
|
+
if (e.button === 1) {
|
|
1471
|
+
// Middle-click → background tab (browser convention)
|
|
1472
|
+
e.preventDefault();
|
|
1473
|
+
const filePath = pill.dataset.filePath;
|
|
1474
|
+
const cwd = container.dataset.cwd;
|
|
1475
|
+
if (!filePath) return;
|
|
1476
|
+
const fullPath = isAbsolutePath(filePath) ? filePath : (cwd ? joinPath(cwd, filePath) : filePath);
|
|
1477
|
+
this._openFileInTab(fullPath, { background: true });
|
|
1478
|
+
}
|
|
1479
|
+
});
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
/**
|
|
1484
|
+
* Attach click/touch handlers to .session-compact-file elements.
|
|
1485
|
+
* @private
|
|
1486
|
+
*/
|
|
1487
|
+
_attachCompactFileHandlers(container) {
|
|
1488
|
+
container.querySelectorAll('.session-compact-file').forEach(el => {
|
|
1489
|
+
const handleTap = (e) => {
|
|
1490
|
+
// Hide button click — remove this pill from all turn bars
|
|
1491
|
+
if (e.target.closest('.session-file-hide')) {
|
|
1492
|
+
e.preventDefault();
|
|
1493
|
+
e.stopPropagation();
|
|
1494
|
+
const hidePath = e.target.closest('.session-file-hide').dataset.hidePath;
|
|
1495
|
+
if (hidePath) this._hideSessionFile(hidePath);
|
|
1496
|
+
return;
|
|
1497
|
+
}
|
|
1498
|
+
e.preventDefault();
|
|
1499
|
+
e.stopPropagation();
|
|
1500
|
+
const filePath = el.dataset.filePath;
|
|
1501
|
+
const cwd = container.dataset.cwd;
|
|
1502
|
+
if (filePath) {
|
|
1503
|
+
const fullPath = isAbsolutePath(filePath) ? filePath : (cwd ? joinPath(cwd, filePath) : filePath);
|
|
1504
|
+
this._openFilePreviewDirect(fullPath);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
bindTapHandler(el, handleTap);
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
/**
|
|
1512
|
+
* Hide a session file from all turn summary bars' inline pills.
|
|
1513
|
+
* File remains visible in expanded session files view.
|
|
1514
|
+
* @private
|
|
1515
|
+
*/
|
|
1516
|
+
_hideSessionFile(filePath) {
|
|
1517
|
+
const sessionId = window.app?.activeSession?.id;
|
|
1518
|
+
if (sessionId) {
|
|
1519
|
+
if (!this._hiddenSessionFiles.has(sessionId)) {
|
|
1520
|
+
this._hiddenSessionFiles.set(sessionId, new Set());
|
|
1521
|
+
}
|
|
1522
|
+
this._hiddenSessionFiles.get(sessionId).add(filePath);
|
|
1523
|
+
}
|
|
1524
|
+
// Remove all matching session-compact pills from DOM
|
|
1525
|
+
document.querySelectorAll(`.session-compact-file[data-file-path="${CSS.escape(filePath)}"]`).forEach(el => {
|
|
1526
|
+
el.remove();
|
|
1527
|
+
});
|
|
1528
|
+
// Clean up empty separators and files rows
|
|
1529
|
+
document.querySelectorAll('.turn-files-row').forEach(row => {
|
|
1530
|
+
const sep = row.querySelector('.turn-files-sep');
|
|
1531
|
+
if (sep && !row.querySelector('.session-compact-file')) {
|
|
1532
|
+
sep.remove();
|
|
1533
|
+
}
|
|
1534
|
+
if (row.children.length === 0) {
|
|
1535
|
+
row.remove();
|
|
1536
|
+
}
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
1541
|
+
// Git status indicators on turn summary bars
|
|
1542
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
1543
|
+
|
|
1544
|
+
/**
|
|
1545
|
+
* Normalize a file path to be relative to cwd for git status matching.
|
|
1546
|
+
* Turn tracker stores absolute paths; git status returns repo-relative paths.
|
|
1547
|
+
* @private
|
|
1548
|
+
*/
|
|
1549
|
+
_normalizePathForGit(filePath, cwd) {
|
|
1550
|
+
if (!filePath || !cwd) return filePath;
|
|
1551
|
+
if (filePath.startsWith(cwd + '/')) {
|
|
1552
|
+
return filePath.slice(cwd.length + 1);
|
|
1553
|
+
}
|
|
1554
|
+
return filePath;
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/**
|
|
1558
|
+
* Fetch git status and decorate a turn summary bar's file pills.
|
|
1559
|
+
* Called after the full bar (context_update) renders. Fire-and-forget.
|
|
1560
|
+
* @private
|
|
1561
|
+
*/
|
|
1562
|
+
async _fetchGitStatusForTurn(barElement) {
|
|
1563
|
+
const cwd = barElement.dataset.cwd;
|
|
1564
|
+
if (!cwd) return;
|
|
1565
|
+
|
|
1566
|
+
try {
|
|
1567
|
+
const resp = await fetch(`${CONFIG.API_BASE}/api/git/status?cwd=${encodeURIComponent(cwd)}`);
|
|
1568
|
+
if (!resp.ok) return;
|
|
1569
|
+
const data = await resp.json();
|
|
1570
|
+
if (data.error) return;
|
|
1571
|
+
|
|
1572
|
+
// Build lookup: relative path → status
|
|
1573
|
+
const gitFileMap = new Map();
|
|
1574
|
+
for (const f of (data.staged || [])) gitFileMap.set(f.path, 'staged');
|
|
1575
|
+
for (const f of (data.modified || [])) gitFileMap.set(f.path, 'modified');
|
|
1576
|
+
for (const f of (data.untracked || [])) gitFileMap.set(f.path, 'untracked');
|
|
1577
|
+
|
|
1578
|
+
// Store on element for expanded view reuse
|
|
1579
|
+
barElement._gitFileMap = gitFileMap;
|
|
1580
|
+
|
|
1581
|
+
this._decorateFilePillsWithGitStatus(barElement, gitFileMap, cwd);
|
|
1582
|
+
this._renderGitSummaryIndicator(barElement, gitFileMap, cwd);
|
|
1583
|
+
} catch (err) {
|
|
1584
|
+
// Graceful degradation: pills stay as-is
|
|
1585
|
+
console.debug('Git status fetch failed for turn bar:', err);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
/**
|
|
1590
|
+
* Add git status indicators to file pills within a turn summary bar.
|
|
1591
|
+
* @private
|
|
1592
|
+
*/
|
|
1593
|
+
_decorateFilePillsWithGitStatus(barElement, gitFileMap, cwd) {
|
|
1594
|
+
// Read-only chips stay undecorated — a workspace M/S/? dot on a file
|
|
1595
|
+
// this turn merely read implies a change it didn't make.
|
|
1596
|
+
for (const pill of barElement.querySelectorAll('.turn-file-pill:not(.turn-read-file)')) {
|
|
1597
|
+
const rawPath = pill.dataset.filePath;
|
|
1598
|
+
const relPath = this._normalizePathForGit(rawPath, cwd);
|
|
1599
|
+
const status = gitFileMap.get(relPath);
|
|
1600
|
+
|
|
1601
|
+
// Remove any previous indicator
|
|
1602
|
+
pill.querySelector('.git-status-dot')?.remove();
|
|
1603
|
+
pill.classList.remove('git-modified', 'git-staged', 'git-untracked');
|
|
1604
|
+
|
|
1605
|
+
if (status) {
|
|
1606
|
+
// Uncommitted file — add status dot badge
|
|
1607
|
+
pill.classList.add(`git-${status}`);
|
|
1608
|
+
const dot = document.createElement('span');
|
|
1609
|
+
dot.className = `git-status-dot git-dot-${status}`;
|
|
1610
|
+
dot.textContent = status === 'staged' ? 'S' : status === 'modified' ? 'M' : '?';
|
|
1611
|
+
pill.prepend(dot);
|
|
1612
|
+
}
|
|
1613
|
+
// Committed files: no decoration, keep original pill appearance
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* Render a compact git status summary in the tools row.
|
|
1619
|
+
* Shows "N uncommitted" or checkmark if all clean.
|
|
1620
|
+
* @private
|
|
1621
|
+
*/
|
|
1622
|
+
_renderGitSummaryIndicator(barElement, gitFileMap, cwd) {
|
|
1623
|
+
// Collect ALL session file paths (all turns), not just this turn's pills
|
|
1624
|
+
const session = this.session;
|
|
1625
|
+
const sessionPaths = new Set();
|
|
1626
|
+
if (session?.messages) {
|
|
1627
|
+
for (const msg of session.messages) {
|
|
1628
|
+
if (msg.role !== 'context' || !msg.changedFiles) continue;
|
|
1629
|
+
for (const filePath of msg.changedFiles) {
|
|
1630
|
+
sessionPaths.add(this._normalizePathForGit(filePath, cwd));
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
// Fallback: if no context messages yet, use turn pills
|
|
1635
|
+
if (sessionPaths.size === 0) {
|
|
1636
|
+
for (const pill of barElement.querySelectorAll('.turn-file-pill:not(.turn-read-file)')) {
|
|
1637
|
+
sessionPaths.add(this._normalizePathForGit(pill.dataset.filePath, cwd));
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
let uncommittedCount = 0;
|
|
1642
|
+
for (const relPath of sessionPaths) {
|
|
1643
|
+
if (gitFileMap.has(relPath)) uncommittedCount++;
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
const rightStats = barElement.querySelector('.turn-right-stats');
|
|
1647
|
+
if (!rightStats) return;
|
|
1648
|
+
|
|
1649
|
+
// Remove existing indicators + separators
|
|
1650
|
+
for (const el of rightStats.querySelectorAll('.turn-git-summary, .turn-git-project-count, .turn-git-sep')) {
|
|
1651
|
+
el.remove();
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// Count "other" files (not in this session) by status type
|
|
1655
|
+
let otherM = 0, otherS = 0, otherU = 0, otherD = 0;
|
|
1656
|
+
for (const [path, status] of gitFileMap) {
|
|
1657
|
+
if (sessionPaths.has(path)) continue;
|
|
1658
|
+
if (status === 'modified') otherM++;
|
|
1659
|
+
else if (status === 'staged') otherS++;
|
|
1660
|
+
else if (status === 'untracked') otherU++;
|
|
1661
|
+
else if (status === 'deleted') otherD++;
|
|
1662
|
+
}
|
|
1663
|
+
const otherTotal = otherM + otherS + otherU + otherD;
|
|
1664
|
+
|
|
1665
|
+
// "Other" breakdown — e.g. "1M 2?" or "3M 1S 5?"
|
|
1666
|
+
if (otherTotal > 0) {
|
|
1667
|
+
const parts = [];
|
|
1668
|
+
if (otherM > 0) parts.push(`${otherM}M`);
|
|
1669
|
+
if (otherS > 0) parts.push(`${otherS}S`);
|
|
1670
|
+
if (otherD > 0) parts.push(`${otherD}D`);
|
|
1671
|
+
if (otherU > 0) parts.push(`${otherU}?`);
|
|
1672
|
+
|
|
1673
|
+
const projectSep = document.createElement('span');
|
|
1674
|
+
projectSep.className = 'turn-stats-sep turn-git-sep';
|
|
1675
|
+
projectSep.textContent = '•';
|
|
1676
|
+
const projectSpan = document.createElement('span');
|
|
1677
|
+
projectSpan.className = 'turn-git-project-count';
|
|
1678
|
+
projectSpan.textContent = parts.join(' ');
|
|
1679
|
+
projectSpan.setAttribute('data-tooltip', `${otherTotal} other uncommitted: ${parts.join(', ')}`);
|
|
1680
|
+
rightStats.prepend(projectSep);
|
|
1681
|
+
rightStats.prepend(projectSpan);
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
// Session indicator
|
|
1685
|
+
const indicator = document.createElement('span');
|
|
1686
|
+
indicator.className = 'turn-git-summary';
|
|
1687
|
+
|
|
1688
|
+
if (uncommittedCount === 0) {
|
|
1689
|
+
indicator.classList.add('git-all-clean');
|
|
1690
|
+
indicator.innerHTML = '✓';
|
|
1691
|
+
indicator.setAttribute('data-tooltip', 'All turn files committed');
|
|
1692
|
+
} else {
|
|
1693
|
+
indicator.classList.add('git-has-uncommitted');
|
|
1694
|
+
indicator.textContent = `${uncommittedCount} uncommitted`;
|
|
1695
|
+
indicator.setAttribute('data-tooltip', `${uncommittedCount} file${uncommittedCount > 1 ? 's' : ''} not yet committed`);
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
const sep = document.createElement('span');
|
|
1699
|
+
sep.className = 'turn-stats-sep turn-git-sep';
|
|
1700
|
+
sep.textContent = '•';
|
|
1701
|
+
rightStats.prepend(sep);
|
|
1702
|
+
rightStats.prepend(indicator);
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
/**
|
|
1706
|
+
* Render aggregated session files in the expanded details section.
|
|
1707
|
+
* Shows all files changed across the session with git status.
|
|
1708
|
+
* Lazy-loaded on first expand.
|
|
1709
|
+
* @private
|
|
1710
|
+
*/
|
|
1711
|
+
async _renderSessionFilesExpanded(barElement) {
|
|
1712
|
+
if (barElement._sessionFilesRendered) return;
|
|
1713
|
+
barElement._sessionFilesRendered = true;
|
|
1714
|
+
|
|
1715
|
+
const session = window.app?.activeSession;
|
|
1716
|
+
if (!session) return;
|
|
1717
|
+
|
|
1718
|
+
const cwd = barElement.dataset.cwd || session.cwd || '';
|
|
1719
|
+
|
|
1720
|
+
// Aggregate all changed files from session context messages
|
|
1721
|
+
const sessionFileMap = new Map(); // relPath → { turns: Set, adds: 0, dels: 0 }
|
|
1722
|
+
for (const msg of session.messages) {
|
|
1723
|
+
if (msg.role !== 'context' || !msg.changedFiles) continue;
|
|
1724
|
+
const tn = msg.turnNumber;
|
|
1725
|
+
for (const filePath of msg.changedFiles) {
|
|
1726
|
+
const relPath = this._normalizePathForGit(filePath, cwd);
|
|
1727
|
+
if (!sessionFileMap.has(relPath)) {
|
|
1728
|
+
sessionFileMap.set(relPath, { turns: new Set(), adds: 0, dels: 0 });
|
|
1729
|
+
}
|
|
1730
|
+
const entry = sessionFileMap.get(relPath);
|
|
1731
|
+
if (tn) entry.turns.add(tn);
|
|
1732
|
+
const actions = msg.fileActions?.[filePath];
|
|
1733
|
+
if (actions) {
|
|
1734
|
+
entry.adds += actions.adds || 0;
|
|
1735
|
+
entry.dels += actions.dels || 0;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
// Reuse cached git status or fetch fresh
|
|
1741
|
+
let gitFileMap = barElement._gitFileMap;
|
|
1742
|
+
if (!gitFileMap) {
|
|
1743
|
+
try {
|
|
1744
|
+
const resp = await fetch(`${CONFIG.API_BASE}/api/git/status?cwd=${encodeURIComponent(cwd)}`);
|
|
1745
|
+
const data = await resp.json();
|
|
1746
|
+
gitFileMap = new Map();
|
|
1747
|
+
for (const f of (data.staged || [])) gitFileMap.set(f.path, 'staged');
|
|
1748
|
+
for (const f of (data.modified || [])) gitFileMap.set(f.path, 'modified');
|
|
1749
|
+
for (const f of (data.untracked || [])) gitFileMap.set(f.path, 'untracked');
|
|
1750
|
+
barElement._gitFileMap = gitFileMap;
|
|
1751
|
+
} catch {
|
|
1752
|
+
gitFileMap = new Map();
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// Nothing to show if no session files and no dirty project files
|
|
1757
|
+
if (sessionFileMap.size === 0 && gitFileMap.size === 0) return;
|
|
1758
|
+
|
|
1759
|
+
const escHtml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
1760
|
+
|
|
1761
|
+
let html = '<div class="turn-session-files">';
|
|
1762
|
+
|
|
1763
|
+
// Session changes section (only if session has files)
|
|
1764
|
+
if (sessionFileMap.size > 0) {
|
|
1765
|
+
let uncommitted = 0;
|
|
1766
|
+
for (const relPath of sessionFileMap.keys()) {
|
|
1767
|
+
if (gitFileMap.has(relPath)) uncommitted++;
|
|
1768
|
+
}
|
|
1769
|
+
const summaryText = uncommitted === 0
|
|
1770
|
+
? `${sessionFileMap.size} files — all committed`
|
|
1771
|
+
: `${sessionFileMap.size} files — ${uncommitted} uncommitted`;
|
|
1772
|
+
|
|
1773
|
+
html += `<div class="session-files-header">Session Changes <span class="session-files-count">${summaryText}</span></div>`;
|
|
1774
|
+
|
|
1775
|
+
// Sort: uncommitted first, then committed
|
|
1776
|
+
const sorted = [...sessionFileMap.entries()].sort((a, b) => {
|
|
1777
|
+
const aUncommitted = gitFileMap.has(a[0]) ? 0 : 1;
|
|
1778
|
+
const bUncommitted = gitFileMap.has(b[0]) ? 0 : 1;
|
|
1779
|
+
return aUncommitted - bUncommitted;
|
|
1780
|
+
});
|
|
1781
|
+
|
|
1782
|
+
html += '<div class="session-files-grid">';
|
|
1783
|
+
for (const [relPath, info] of sorted) {
|
|
1784
|
+
const gitStatus = gitFileMap.get(relPath);
|
|
1785
|
+
const statusClass = gitStatus || 'committed';
|
|
1786
|
+
const statusIcon = gitStatus
|
|
1787
|
+
? (gitStatus === 'staged' ? 'S' : gitStatus === 'modified' ? 'M' : '?')
|
|
1788
|
+
: '✓';
|
|
1789
|
+
const fileName = basename(relPath);
|
|
1790
|
+
const turnsStr = info.turns.size > 0 ? [...info.turns].map(t => `T${t}`).join(' ') : '';
|
|
1791
|
+
const statsStr = (info.adds > 0 || info.dels > 0)
|
|
1792
|
+
? `<span class="sf-stats">${info.adds > 0 ? `<span class="file-adds">+${info.adds}</span>` : ''}${info.dels > 0 ? `<span class="file-dels">-${info.dels}</span>` : ''}</span>`
|
|
1793
|
+
: '';
|
|
1794
|
+
|
|
1795
|
+
html += `<div class="session-file-row git-${statusClass}" data-file-path="${escHtml(relPath)}">
|
|
1796
|
+
<span class="session-file-status">${statusIcon}</span>
|
|
1797
|
+
<span class="session-file-name" data-tooltip="${escHtml(relPath)}">${escHtml(fileName)}</span>
|
|
1798
|
+
${statsStr}
|
|
1799
|
+
<span class="session-file-turns">${turnsStr}</span>
|
|
1800
|
+
</div>`;
|
|
1801
|
+
}
|
|
1802
|
+
html += '</div>';
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
// Other uncommitted files not touched by session
|
|
1806
|
+
const otherDirty = [];
|
|
1807
|
+
for (const [path, status] of gitFileMap) {
|
|
1808
|
+
if (!sessionFileMap.has(path)) otherDirty.push({ path, status });
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
if (otherDirty.length > 0) {
|
|
1812
|
+
const label = sessionFileMap.size > 0 ? `${otherDirty.length} other uncommitted` : `${otherDirty.length} uncommitted in project`;
|
|
1813
|
+
html += `<div class="session-files-header other-files-header">${label}</div>`;
|
|
1814
|
+
html += '<div class="session-files-grid">';
|
|
1815
|
+
for (const { path, status } of otherDirty.slice(0, 20)) {
|
|
1816
|
+
const statusIcon = status === 'staged' ? 'S' : status === 'modified' ? 'M' : '?';
|
|
1817
|
+
const fileName = basename(path);
|
|
1818
|
+
html += `<div class="session-file-row git-${status}" data-file-path="${escHtml(path)}">
|
|
1819
|
+
<span class="session-file-status">${statusIcon}</span>
|
|
1820
|
+
<span class="session-file-name" data-tooltip="${escHtml(path)}">${escHtml(fileName)}</span>
|
|
1821
|
+
</div>`;
|
|
1822
|
+
}
|
|
1823
|
+
if (otherDirty.length > 20) {
|
|
1824
|
+
html += `<div class="session-files-more">...${otherDirty.length - 20} more</div>`;
|
|
1825
|
+
}
|
|
1826
|
+
html += '</div>';
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
html += '</div>';
|
|
1830
|
+
|
|
1831
|
+
// Insert into expanded details
|
|
1832
|
+
const expandedDetails = barElement.querySelector('.turn-expanded-details');
|
|
1833
|
+
if (expandedDetails) {
|
|
1834
|
+
expandedDetails.insertAdjacentHTML('beforeend', html);
|
|
1835
|
+
// Attach click handlers to session file rows for file preview
|
|
1836
|
+
this._attachSessionFileRowHandlers(expandedDetails, cwd);
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
/**
|
|
1841
|
+
* Attach click handlers to .session-file-row elements for file preview.
|
|
1842
|
+
* @private
|
|
1843
|
+
*/
|
|
1844
|
+
_attachSessionFileRowHandlers(container, cwd) {
|
|
1845
|
+
for (const row of container.querySelectorAll('.session-file-row[data-file-path]')) {
|
|
1846
|
+
row.style.cursor = 'pointer';
|
|
1847
|
+
row.addEventListener('click', (e) => {
|
|
1848
|
+
e.stopPropagation();
|
|
1849
|
+
const filePath = row.dataset.filePath;
|
|
1850
|
+
if (filePath) {
|
|
1851
|
+
const fullPath = isAbsolutePath(filePath) ? filePath : (cwd ? joinPath(cwd, filePath) : filePath);
|
|
1852
|
+
this._openFilePreviewDirect(fullPath);
|
|
1853
|
+
}
|
|
1854
|
+
});
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
/**
|
|
1859
|
+
* Open file in file preview widget (absolute path)
|
|
1860
|
+
* @private
|
|
1861
|
+
*/
|
|
1862
|
+
_openFilePreviewDirect(fullPath) {
|
|
1863
|
+
// Use app.previewFile which has the correctly-imported FilePreviewWidget
|
|
1864
|
+
// (dynamic import would load a separate module instance due to cache-bust
|
|
1865
|
+
// query params, creating disconnected state from WidgetManager)
|
|
1866
|
+
if (window.app?.previewFile) {
|
|
1867
|
+
window.app.previewFile(fullPath);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
/**
|
|
1872
|
+
* Open file in a full tab (via TabController)
|
|
1873
|
+
* @param {string} fullPath - Absolute file path
|
|
1874
|
+
* @param {Object} options - Options passed to openFilePreviewTab
|
|
1875
|
+
* @private
|
|
1876
|
+
*/
|
|
1877
|
+
_openFileInTab(fullPath, options = {}) {
|
|
1878
|
+
const tabCtrl = window.app?.tabCtrl;
|
|
1879
|
+
if (tabCtrl) {
|
|
1880
|
+
tabCtrl.openFilePreviewTab(fullPath, null, options);
|
|
1881
|
+
} else {
|
|
1882
|
+
// Fallback to floating preview if TabController not available
|
|
1883
|
+
this._openFilePreviewDirect(fullPath);
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1888
|
+
// TOOL GROUPING
|
|
1889
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1890
|
+
|
|
1891
|
+
/**
|
|
1892
|
+
* Render a group of consecutive tool messages with collapse-all button
|
|
1893
|
+
* @private
|
|
1894
|
+
*/
|
|
1895
|
+
_renderToolGroup(toolMessages) {
|
|
1896
|
+
const groupId = `tool-group-${toolMessages[0].id}`;
|
|
1897
|
+
|
|
1898
|
+
// Create group container
|
|
1899
|
+
const groupDiv = document.createElement('div');
|
|
1900
|
+
groupDiv.className = 'tool-group';
|
|
1901
|
+
groupDiv.id = groupId;
|
|
1902
|
+
|
|
1903
|
+
// Add collapse-all button at the START for sticky positioning
|
|
1904
|
+
const collapseAllBtn = `
|
|
1905
|
+
<button class="tool-group-collapse-btn" data-act="toggle-tool-group" data-id="${escapeAttr(groupId)}" data-tooltip="Collapse/expand all tools">
|
|
1906
|
+
<svg class="collapse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
1907
|
+
<path d="M7 13l5 5 5-5M7 6l5 5 5-5"/>
|
|
1908
|
+
</svg>
|
|
1909
|
+
<svg class="expand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
1910
|
+
<path d="M13 17l5-5-5-5M6 17l5-5-5-5"/>
|
|
1911
|
+
</svg>
|
|
1912
|
+
</button>
|
|
1913
|
+
`;
|
|
1914
|
+
groupDiv.insertAdjacentHTML('afterbegin', collapseAllBtn);
|
|
1915
|
+
|
|
1916
|
+
// Render each tool message
|
|
1917
|
+
for (const msg of toolMessages) {
|
|
1918
|
+
const div = document.createElement('div');
|
|
1919
|
+
div.className = 'message tool';
|
|
1920
|
+
div.id = `msg-${msg.id}`;
|
|
1921
|
+
div.innerHTML = this.ctx.toolRenderer.renderToolBlock(msg);
|
|
1922
|
+
this.ctx.toolRenderer.processWriteCharts(div);
|
|
1923
|
+
this.ctx.toolRenderer.processWriteExcalidraw(div);
|
|
1924
|
+
this.ctx.toolRenderer.processReadExcalidraw(div);
|
|
1925
|
+
groupDiv.appendChild(div);
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
// Append to correct container (session-specific with pool, or #messages)
|
|
1929
|
+
this._getActiveMessageContainer().appendChild(groupDiv);
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
/**
|
|
1933
|
+
* Create a tool group DOM element without appending it
|
|
1934
|
+
* Used by prependMessages for older messages
|
|
1935
|
+
* @private
|
|
1936
|
+
*/
|
|
1937
|
+
_createToolGroupElement(toolMessages) {
|
|
1938
|
+
const groupId = `tool-group-${toolMessages[0].id}`;
|
|
1939
|
+
|
|
1940
|
+
const groupDiv = document.createElement('div');
|
|
1941
|
+
groupDiv.className = 'tool-group';
|
|
1942
|
+
groupDiv.id = groupId;
|
|
1943
|
+
|
|
1944
|
+
// Add collapse-all button at the START
|
|
1945
|
+
const collapseAllBtn = `
|
|
1946
|
+
<button class="tool-group-collapse-btn" data-act="toggle-tool-group" data-id="${escapeAttr(groupId)}" data-tooltip="Collapse/expand all tools">
|
|
1947
|
+
<svg class="collapse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
1948
|
+
<path d="M7 13l5 5 5-5M7 6l5 5 5-5"/>
|
|
1949
|
+
</svg>
|
|
1950
|
+
<svg class="expand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
1951
|
+
<path d="M13 17l5-5-5-5M6 17l5-5-5-5"/>
|
|
1952
|
+
</svg>
|
|
1953
|
+
</button>
|
|
1954
|
+
`;
|
|
1955
|
+
groupDiv.insertAdjacentHTML('afterbegin', collapseAllBtn);
|
|
1956
|
+
|
|
1957
|
+
// Create each tool message
|
|
1958
|
+
for (const msg of toolMessages) {
|
|
1959
|
+
const div = document.createElement('div');
|
|
1960
|
+
div.className = 'message tool';
|
|
1961
|
+
div.id = `msg-${msg.id}`;
|
|
1962
|
+
div.innerHTML = this.ctx.toolRenderer.renderToolBlock(msg);
|
|
1963
|
+
this.ctx.toolRenderer.processWriteCharts(div);
|
|
1964
|
+
this.ctx.toolRenderer.processWriteExcalidraw(div);
|
|
1965
|
+
this.ctx.toolRenderer.processReadExcalidraw(div);
|
|
1966
|
+
groupDiv.appendChild(div);
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
return groupDiv;
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/**
|
|
1973
|
+
* Render a tool message with real-time grouping
|
|
1974
|
+
* During streaming, this checks if we should add to an existing group or create a new one
|
|
1975
|
+
* Also nests sub-agent tools inside their parent Task block
|
|
1976
|
+
* @private
|
|
1977
|
+
*/
|
|
1978
|
+
_renderToolMessageWithGrouping(msg) {
|
|
1979
|
+
const messages = this._getActiveMessageContainer();
|
|
1980
|
+
|
|
1981
|
+
// Check if this tool has a parent Task (from server's parent_task_id)
|
|
1982
|
+
// This is the authoritative mechanism for sub-agent tool nesting
|
|
1983
|
+
// Query by data-tool-use-id attribute (stores Claude's tool_use_id)
|
|
1984
|
+
// Note: Only nest if parentTaskId is provided - no fallback heuristics
|
|
1985
|
+
// (fallback to "any running Task" would incorrectly nest unrelated tools)
|
|
1986
|
+
if (msg.parentTaskId && msg.toolName !== 'Task') {
|
|
1987
|
+
const parentTaskBlock = messages.querySelector(`.task-block[data-tool-use-id="${msg.parentTaskId}"]`);
|
|
1988
|
+
if (parentTaskBlock) {
|
|
1989
|
+
this._nestToolInTaskBlock(parentTaskBlock, msg);
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
// Create the tool message element
|
|
1995
|
+
const div = document.createElement('div');
|
|
1996
|
+
div.className = 'message tool';
|
|
1997
|
+
div.id = `msg-${msg.id}`;
|
|
1998
|
+
div.dataset.turnId = msg.turnId;
|
|
1999
|
+
div.innerHTML = this.ctx.toolRenderer.renderToolBlock(msg);
|
|
2000
|
+
this.ctx.toolRenderer.processWriteCharts(div);
|
|
2001
|
+
this.ctx.toolRenderer.processWriteExcalidraw(div);
|
|
2002
|
+
this.ctx.toolRenderer.processReadExcalidraw(div);
|
|
2003
|
+
|
|
2004
|
+
// Check the last element in messages container
|
|
2005
|
+
const lastChild = messages.lastElementChild;
|
|
2006
|
+
|
|
2007
|
+
// Only group tools from the same turn (never across turn boundaries)
|
|
2008
|
+
if (lastChild?.classList.contains('tool-group') &&
|
|
2009
|
+
lastChild.dataset.turnId == msg.turnId) {
|
|
2010
|
+
// Last element is already a tool group from same turn - add to it
|
|
2011
|
+
lastChild.appendChild(div);
|
|
2012
|
+
// Check gutter space for the group
|
|
2013
|
+
requestAnimationFrame(() => this.checkToolGroupGutterSpace(lastChild));
|
|
2014
|
+
} else if (lastChild?.classList.contains('message') && lastChild.classList.contains('tool') &&
|
|
2015
|
+
lastChild.dataset.turnId == msg.turnId) {
|
|
2016
|
+
// Last element is a single tool message from same turn - wrap both in a group
|
|
2017
|
+
const groupId = `tool-group-${lastChild.id.replace('msg-', '')}`;
|
|
2018
|
+
const groupDiv = document.createElement('div');
|
|
2019
|
+
groupDiv.className = 'tool-group';
|
|
2020
|
+
groupDiv.id = groupId;
|
|
2021
|
+
groupDiv.dataset.turnId = msg.turnId;
|
|
2022
|
+
|
|
2023
|
+
// Add collapse-all button
|
|
2024
|
+
const collapseAllBtn = `
|
|
2025
|
+
<button class="tool-group-collapse-btn" data-act="toggle-tool-group" data-id="${escapeAttr(groupId)}" data-tooltip="Collapse/expand all tools">
|
|
2026
|
+
<svg class="collapse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
2027
|
+
<path d="M7 13l5 5 5-5M7 6l5 5 5-5"/>
|
|
2028
|
+
</svg>
|
|
2029
|
+
<svg class="expand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
2030
|
+
<path d="M13 17l5-5-5-5M6 17l5-5-5-5"/>
|
|
2031
|
+
</svg>
|
|
2032
|
+
</button>
|
|
2033
|
+
`;
|
|
2034
|
+
groupDiv.insertAdjacentHTML('afterbegin', collapseAllBtn);
|
|
2035
|
+
|
|
2036
|
+
// Remove single tool's has-gutter-space (now handled by group)
|
|
2037
|
+
lastChild.classList.remove('has-gutter-space');
|
|
2038
|
+
|
|
2039
|
+
// Move existing tool to group
|
|
2040
|
+
messages.removeChild(lastChild);
|
|
2041
|
+
groupDiv.appendChild(lastChild);
|
|
2042
|
+
groupDiv.appendChild(div);
|
|
2043
|
+
messages.appendChild(groupDiv);
|
|
2044
|
+
|
|
2045
|
+
// Check gutter space for the new group
|
|
2046
|
+
requestAnimationFrame(() => this.checkToolGroupGutterSpace(groupDiv));
|
|
2047
|
+
} else {
|
|
2048
|
+
// Not following a tool - render as single tool message
|
|
2049
|
+
messages.appendChild(div);
|
|
2050
|
+
// Check gutter space for single tool
|
|
2051
|
+
requestAnimationFrame(() => this.checkSingleToolGutterSpace(div));
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
/**
|
|
2056
|
+
* Nest a sub-agent tool inside a running Task block
|
|
2057
|
+
* @private
|
|
2058
|
+
*/
|
|
2059
|
+
_nestToolInTaskBlock(taskBlock, msg) {
|
|
2060
|
+
// Get or create children container inside the task block body
|
|
2061
|
+
let childrenContainer = taskBlock.querySelector('.task-block-children');
|
|
2062
|
+
if (!childrenContainer) {
|
|
2063
|
+
// Create children container inside the body
|
|
2064
|
+
let body = taskBlock.querySelector('.task-block-body');
|
|
2065
|
+
if (!body) {
|
|
2066
|
+
// Create body if it doesn't exist
|
|
2067
|
+
body = document.createElement('div');
|
|
2068
|
+
body.className = 'task-block-body';
|
|
2069
|
+
taskBlock.appendChild(body);
|
|
2070
|
+
}
|
|
2071
|
+
childrenContainer = document.createElement('div');
|
|
2072
|
+
childrenContainer.className = 'task-block-children';
|
|
2073
|
+
body.appendChild(childrenContainer);
|
|
2074
|
+
|
|
2075
|
+
// Auto-expand the task block when children are added
|
|
2076
|
+
taskBlock.classList.add('expanded');
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
// Render the tool and add to children (agent context for collapse mode)
|
|
2080
|
+
const toolHtml = this.ctx.toolRenderer.renderToolBlock(msg, { isAgent: true });
|
|
2081
|
+
const wrapper = document.createElement('div');
|
|
2082
|
+
wrapper.className = 'task-block-child';
|
|
2083
|
+
wrapper.id = `msg-${msg.id}`;
|
|
2084
|
+
wrapper.setAttribute('data-tool-id', msg.toolId || msg.id);
|
|
2085
|
+
wrapper.innerHTML = toolHtml;
|
|
2086
|
+
this.ctx.toolRenderer.processWriteCharts(wrapper);
|
|
2087
|
+
this.ctx.toolRenderer.processWriteExcalidraw(wrapper);
|
|
2088
|
+
this.ctx.toolRenderer.processReadExcalidraw(wrapper);
|
|
2089
|
+
childrenContainer.appendChild(wrapper);
|
|
2090
|
+
|
|
2091
|
+
// Update child count badge in header
|
|
2092
|
+
this._updateTaskBlockChildCount(taskBlock);
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
/**
|
|
2096
|
+
* Update the child count badge on a Task block
|
|
2097
|
+
* @private
|
|
2098
|
+
*/
|
|
2099
|
+
_updateTaskBlockChildCount(taskBlock) {
|
|
2100
|
+
const children = taskBlock.querySelectorAll('.task-block-children .task-block-child');
|
|
2101
|
+
const count = children.length;
|
|
2102
|
+
|
|
2103
|
+
// Find or create count badge
|
|
2104
|
+
const header = taskBlock.querySelector('.task-block-header');
|
|
2105
|
+
if (!header) return;
|
|
2106
|
+
|
|
2107
|
+
let countBadge = header.querySelector('.task-block-count');
|
|
2108
|
+
if (count > 0) {
|
|
2109
|
+
if (!countBadge) {
|
|
2110
|
+
// Create badge before the status badge
|
|
2111
|
+
countBadge = document.createElement('span');
|
|
2112
|
+
countBadge.className = 'task-block-count';
|
|
2113
|
+
const statusBadge = header.querySelector('.task-block-badge');
|
|
2114
|
+
if (statusBadge) {
|
|
2115
|
+
statusBadge.before(countBadge);
|
|
2116
|
+
} else {
|
|
2117
|
+
header.appendChild(countBadge);
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
countBadge.textContent = `${count} tool${count !== 1 ? 's' : ''}`;
|
|
2121
|
+
} else if (countBadge) {
|
|
2122
|
+
countBadge.remove();
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
/**
|
|
2127
|
+
* Check gutter space for a single tool group
|
|
2128
|
+
*/
|
|
2129
|
+
checkToolGroupGutterSpace(group) {
|
|
2130
|
+
// Use the scrolling container for measurement
|
|
2131
|
+
const container = document.getElementById('messages-container');
|
|
2132
|
+
if (!container) return;
|
|
2133
|
+
|
|
2134
|
+
// Get the first message element in the group
|
|
2135
|
+
const firstMessage = group.querySelector('.message.tool');
|
|
2136
|
+
if (!firstMessage) return;
|
|
2137
|
+
|
|
2138
|
+
const messageRect = firstMessage.getBoundingClientRect();
|
|
2139
|
+
const containerRect = container.getBoundingClientRect();
|
|
2140
|
+
|
|
2141
|
+
// Right space: distance from message edge to container edge
|
|
2142
|
+
// Subtract ~20px for scrollbar buffer
|
|
2143
|
+
const rightSpace = containerRect.right - messageRect.right - 20;
|
|
2144
|
+
|
|
2145
|
+
if (rightSpace >= 40) {
|
|
2146
|
+
group.classList.add('has-gutter-space');
|
|
2147
|
+
} else {
|
|
2148
|
+
group.classList.remove('has-gutter-space');
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
/**
|
|
2153
|
+
* Check gutter space for a single standalone tool message
|
|
2154
|
+
*/
|
|
2155
|
+
checkSingleToolGutterSpace(messageEl) {
|
|
2156
|
+
// Skip if this tool is in a group (groups have their own space check)
|
|
2157
|
+
if (messageEl.closest('.tool-group')) return;
|
|
2158
|
+
|
|
2159
|
+
const container = document.getElementById('messages-container');
|
|
2160
|
+
if (!container) return;
|
|
2161
|
+
|
|
2162
|
+
const messageRect = messageEl.getBoundingClientRect();
|
|
2163
|
+
const containerRect = container.getBoundingClientRect();
|
|
2164
|
+
|
|
2165
|
+
// Right space: distance from message edge to container edge
|
|
2166
|
+
const rightSpace = containerRect.right - messageRect.right - 20;
|
|
2167
|
+
|
|
2168
|
+
if (rightSpace >= 40) {
|
|
2169
|
+
messageEl.classList.add('has-gutter-space');
|
|
2170
|
+
} else {
|
|
2171
|
+
messageEl.classList.remove('has-gutter-space');
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
/**
|
|
2176
|
+
* Check gutter space for all visible tool groups and single tool messages
|
|
2177
|
+
* Called on window resize and after rendering
|
|
2178
|
+
*/
|
|
2179
|
+
checkAllToolGroupGutterSpace() {
|
|
2180
|
+
// Check tool groups
|
|
2181
|
+
document.querySelectorAll('.tool-group').forEach(group => {
|
|
2182
|
+
this.checkToolGroupGutterSpace(group);
|
|
2183
|
+
});
|
|
2184
|
+
|
|
2185
|
+
// Check single tool messages (not in groups)
|
|
2186
|
+
document.querySelectorAll('.message.tool:not(.tool-group .message.tool)').forEach(msg => {
|
|
2187
|
+
this.checkSingleToolGutterSpace(msg);
|
|
2188
|
+
});
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2192
|
+
// SCROLL MANAGEMENT
|
|
2193
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2194
|
+
|
|
2195
|
+
/**
|
|
2196
|
+
* Retarget scroll-aware components (ScrollManager, ChatNavigator) to the
|
|
2197
|
+
* active per-session scroll container. Called after container pool activation
|
|
2198
|
+
* so all paths (O(1) switch, first render, welcome→session) stay in sync.
|
|
2199
|
+
* @param {Object} [options]
|
|
2200
|
+
* @param {boolean} [options.skipInitState] - Pass to ScrollManager.setContainer()
|
|
2201
|
+
* to skip recalculating scroll state (used by O(1) switch path)
|
|
2202
|
+
* @private
|
|
2203
|
+
*/
|
|
2204
|
+
_retargetScrollComponents(options = {}) {
|
|
2205
|
+
const scrollEl = this.ctx.app?.getActiveScrollContainer();
|
|
2206
|
+
if (!scrollEl) return;
|
|
2207
|
+
this.ctx.app.scrollManager?.setContainer(scrollEl, options);
|
|
2208
|
+
this.ctx.app.chatNavigator?.setScrollContainer(scrollEl);
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
/**
|
|
2212
|
+
* Restore scroll position for the active session
|
|
2213
|
+
*/
|
|
2214
|
+
restoreScrollPosition() {
|
|
2215
|
+
const session = this.ctx.session;
|
|
2216
|
+
if (!session) return;
|
|
2217
|
+
|
|
2218
|
+
// Use the active per-session scroll container (not the shared outer container)
|
|
2219
|
+
const container = this.ctx.app?.getActiveScrollContainer() || this.ctx.els.messagesContainer;
|
|
2220
|
+
if (!container) return;
|
|
2221
|
+
|
|
2222
|
+
// Force layout calculation to ensure DOM is ready
|
|
2223
|
+
void container.offsetHeight;
|
|
2224
|
+
|
|
2225
|
+
if (session.scrollPosition !== null && session.scrollPosition !== undefined) {
|
|
2226
|
+
// Explicit saved offset — an LRU-evicted container being rebuilt, or
|
|
2227
|
+
// a position captured just before an invalidate-triggered re-render.
|
|
2228
|
+
// ONE-SHOT: consume it after applying. Leaving it set replayed stale
|
|
2229
|
+
// offsets (worst case 0 = top) on every later re-render, which is
|
|
2230
|
+
// what pinned "return to tab" at the top of the transcript.
|
|
2231
|
+
container.scrollTop = session.scrollPosition;
|
|
2232
|
+
session.scrollPosition = null;
|
|
2233
|
+
} else if (session.isUserScrolledUp && container.scrollTop > 0) {
|
|
2234
|
+
// User was reading scrolled up and the browser preserved the offset
|
|
2235
|
+
// on the cached container — leave their place alone.
|
|
2236
|
+
} else {
|
|
2237
|
+
// Default: bottom (scrollPosition === null means "was at bottom",
|
|
2238
|
+
// and a rebuilt container that lost its offset lands here too).
|
|
2239
|
+
container.scrollTop = container.scrollHeight;
|
|
2240
|
+
}
|
|
2241
|
+
void container.scrollTop;
|
|
2242
|
+
|
|
2243
|
+
// Re-sync the scrolled-up flag AFTER positioning: _retargetScrollComponents()
|
|
2244
|
+
// ran initState() while a rebuilt container was still at scrollTop 0, which
|
|
2245
|
+
// left isUserScrolledUp stuck true and made every soft scrollToBottom()
|
|
2246
|
+
// refuse to move afterwards. Use the setter (not initState) — it leaves the
|
|
2247
|
+
// state machine alone while a tab switch is in flight.
|
|
2248
|
+
const scrollManager = this.ctx.app?.scrollManager;
|
|
2249
|
+
if (scrollManager && scrollManager.container === container) {
|
|
2250
|
+
scrollManager.isUserScrolledUp = !scrollManager.isNearBottom();
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
scrollToBottom() {
|
|
2255
|
+
this.ctx.scrollManager?.scrollToBottom();
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
/**
|
|
2259
|
+
* Update a message's favorite state in the DOM
|
|
2260
|
+
* Called when server confirms promptId or when favorite is toggled
|
|
2261
|
+
* @param {string} msgId - Client message ID
|
|
2262
|
+
* @param {string} promptId - Server prompt ID (sessionId:lineNumber)
|
|
2263
|
+
* @param {boolean} isFavorite - Whether the prompt is favorited
|
|
2264
|
+
*/
|
|
2265
|
+
updateMessageFavoriteState(msgId, promptId, isFavorite) {
|
|
2266
|
+
const msgDiv = document.getElementById(`msg-${msgId}`);
|
|
2267
|
+
if (!msgDiv) return;
|
|
2268
|
+
|
|
2269
|
+
const btn = msgDiv.querySelector('.message-favorite-btn');
|
|
2270
|
+
if (!btn) return;
|
|
2271
|
+
|
|
2272
|
+
// Update button state
|
|
2273
|
+
btn.dataset.promptId = promptId;
|
|
2274
|
+
btn.classList.remove('hidden');
|
|
2275
|
+
btn.classList.toggle('active', isFavorite);
|
|
2276
|
+
btn.setAttribute('data-tooltip', isFavorite ? 'Remove from favorites' : 'Add to favorites');
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
/**
|
|
2280
|
+
* Re-render the content of a user message (e.g., after verifiedFiles arrives from server)
|
|
2281
|
+
* @param {Object} msg - Message object with updated fields
|
|
2282
|
+
*/
|
|
2283
|
+
updateMessageContent(msg) {
|
|
2284
|
+
const msgDiv = document.getElementById(`msg-${msg.id}`);
|
|
2285
|
+
if (!msgDiv) return;
|
|
2286
|
+
const bubble = msgDiv.querySelector('.message-content');
|
|
2287
|
+
if (!bubble) return;
|
|
2288
|
+
bubble.innerHTML = this._renderMessageContent(msg);
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
/**
|
|
2292
|
+
* Scroll to a specific message, loading older messages if necessary
|
|
2293
|
+
* Used by Prompt Explorer to jump to a specific prompt
|
|
2294
|
+
* @param {string} targetTimestamp - ISO timestamp of the target message
|
|
2295
|
+
* @param {string} targetPromptId - Optional promptId for user messages (sessionId:lineNumber)
|
|
2296
|
+
* @returns {Promise<boolean>} True if message was found and scrolled to
|
|
2297
|
+
*/
|
|
2298
|
+
async scrollToMessage(targetTimestamp, targetPromptId = null) {
|
|
2299
|
+
const session = this.ctx.session;
|
|
2300
|
+
if (!session) return false;
|
|
2301
|
+
|
|
2302
|
+
// Helper to find the target message
|
|
2303
|
+
const findTarget = () => {
|
|
2304
|
+
// Try by promptId first (more reliable for user messages)
|
|
2305
|
+
if (targetPromptId) {
|
|
2306
|
+
const byPromptId = session.messages.find(m => m.promptId === targetPromptId);
|
|
2307
|
+
if (byPromptId) return byPromptId;
|
|
2308
|
+
}
|
|
2309
|
+
// Fall back to timestamp
|
|
2310
|
+
if (targetTimestamp) {
|
|
2311
|
+
return session.messages.find(m => m.timestamp === targetTimestamp);
|
|
2312
|
+
}
|
|
2313
|
+
return null;
|
|
2314
|
+
};
|
|
2315
|
+
|
|
2316
|
+
// Check if message is already loaded
|
|
2317
|
+
let targetMsg = findTarget();
|
|
2318
|
+
|
|
2319
|
+
// Load older messages until found or exhausted
|
|
2320
|
+
let loadAttempts = 0;
|
|
2321
|
+
const maxAttempts = 20; // Prevent infinite loops (20 * 50 = 1000 messages max)
|
|
2322
|
+
|
|
2323
|
+
while (!targetMsg && session.hasMoreMessages && loadAttempts < maxAttempts) {
|
|
2324
|
+
loadAttempts++;
|
|
2325
|
+
const countBefore = session.messages.length;
|
|
2326
|
+
const result = await session.loadOlderMessages(50);
|
|
2327
|
+
|
|
2328
|
+
if (result.loaded === 0 || result.error) {
|
|
2329
|
+
break;
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
// Prepend newly loaded messages to DOM
|
|
2333
|
+
const newMessages = session.messages.slice(0, result.loaded);
|
|
2334
|
+
this.prependMessages(newMessages);
|
|
2335
|
+
|
|
2336
|
+
// Check again
|
|
2337
|
+
targetMsg = findTarget();
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
if (!targetMsg) {
|
|
2341
|
+
console.warn('[ChatController] Message not found after loading', { targetTimestamp, targetPromptId });
|
|
2342
|
+
return false;
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2345
|
+
// Find the DOM element and scroll to it
|
|
2346
|
+
const el = document.getElementById(`msg-${targetMsg.id}`);
|
|
2347
|
+
if (!el) {
|
|
2348
|
+
console.warn('[ChatController] Message element not found in DOM:', targetMsg.id);
|
|
2349
|
+
return false;
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
// Scroll into view with highlight effect
|
|
2353
|
+
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
2354
|
+
|
|
2355
|
+
// Add highlight animation
|
|
2356
|
+
el.classList.add('scroll-highlight');
|
|
2357
|
+
setTimeout(() => el.classList.remove('scroll-highlight'), 2000);
|
|
2358
|
+
|
|
2359
|
+
return true;
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2363
|
+
// HISTORY LOADING
|
|
2364
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2365
|
+
|
|
2366
|
+
/**
|
|
2367
|
+
* Handle scroll-to-top to load more messages
|
|
2368
|
+
*/
|
|
2369
|
+
async handleScrollTop() {
|
|
2370
|
+
const session = this.ctx.session;
|
|
2371
|
+
if (!session || !session.hasMoreMessages || session.isLoadingMore) {
|
|
2372
|
+
return;
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
// Don't load more if there are no messages - nothing to load more of
|
|
2376
|
+
// This prevents triggering on welcome screen or empty sessions
|
|
2377
|
+
if (!session.messages || session.messages.length === 0) {
|
|
2378
|
+
return;
|
|
2379
|
+
}
|
|
2380
|
+
|
|
2381
|
+
// Don't trigger load-more while initially loading from server
|
|
2382
|
+
if (session.isLoadingFromServer) {
|
|
2383
|
+
return;
|
|
2384
|
+
}
|
|
2385
|
+
|
|
2386
|
+
// Don't trigger during session switching (check app flag)
|
|
2387
|
+
const app = window.app;
|
|
2388
|
+
if (app?._switchingSession) {
|
|
2389
|
+
return;
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// Debounce: don't load if messages were just loaded (within 1000ms)
|
|
2393
|
+
// Longer debounce for mobile Safari which has slower rendering
|
|
2394
|
+
const timeSinceLoad = Date.now() - (session._lastLoadTime || 0);
|
|
2395
|
+
if (timeSinceLoad < 1000) {
|
|
2396
|
+
return;
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
this.showLoadMoreIndicator(true);
|
|
2400
|
+
|
|
2401
|
+
try {
|
|
2402
|
+
const result = await session.loadOlderMessages(50);
|
|
2403
|
+
if (result.loaded > 0) {
|
|
2404
|
+
const newMessages = session.messages.slice(0, result.loaded);
|
|
2405
|
+
this.prependMessages(newMessages);
|
|
2406
|
+
}
|
|
2407
|
+
this.updateHistoryNotice();
|
|
2408
|
+
} catch (error) {
|
|
2409
|
+
console.error('Failed to load older messages:', error);
|
|
2410
|
+
this.ctx.addSystemLog(`Failed to load older messages: ${error.message}`, 'error');
|
|
2411
|
+
} finally {
|
|
2412
|
+
this.showLoadMoreIndicator(false);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
/**
|
|
2417
|
+
* Update or remove the "more history" notice at the top
|
|
2418
|
+
*/
|
|
2419
|
+
updateHistoryNotice() {
|
|
2420
|
+
const session = this.ctx.session;
|
|
2421
|
+
const messagesContainer = this._getActiveMessageContainer();
|
|
2422
|
+
const existingNotice = messagesContainer.querySelector('.message-history-notice');
|
|
2423
|
+
|
|
2424
|
+
if (!session?.hasMoreMessages) {
|
|
2425
|
+
if (existingNotice) {
|
|
2426
|
+
existingNotice.remove();
|
|
2427
|
+
}
|
|
2428
|
+
return;
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
const loadedCount = session.messages.length;
|
|
2432
|
+
const totalCount = session.totalMessageCount;
|
|
2433
|
+
const remaining = totalCount - loadedCount;
|
|
2434
|
+
|
|
2435
|
+
if (existingNotice) {
|
|
2436
|
+
existingNotice.querySelector('span').textContent =
|
|
2437
|
+
`${remaining.toLocaleString()} older messages • scroll up to load`;
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
/**
|
|
2442
|
+
* Show/hide loading indicator when loading more messages
|
|
2443
|
+
*/
|
|
2444
|
+
showLoadMoreIndicator(show) {
|
|
2445
|
+
const messagesContainer = this._getActiveMessageContainer();
|
|
2446
|
+
let indicator = messagesContainer.querySelector('#load-more-indicator');
|
|
2447
|
+
|
|
2448
|
+
if (show) {
|
|
2449
|
+
if (!indicator) {
|
|
2450
|
+
indicator = document.createElement('div');
|
|
2451
|
+
indicator.id = 'load-more-indicator';
|
|
2452
|
+
indicator.className = 'loading-indicator';
|
|
2453
|
+
indicator.innerHTML = `
|
|
2454
|
+
<svg class="spinner" viewBox="0 0 24 24">
|
|
2455
|
+
<circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="2" stroke-dasharray="40 60"/>
|
|
2456
|
+
</svg>
|
|
2457
|
+
<span>Loading older messages...</span>
|
|
2458
|
+
`;
|
|
2459
|
+
|
|
2460
|
+
const historyNotice = messagesContainer.querySelector('.message-history-notice');
|
|
2461
|
+
if (historyNotice) {
|
|
2462
|
+
historyNotice.insertAdjacentElement('afterend', indicator);
|
|
2463
|
+
} else {
|
|
2464
|
+
messagesContainer.insertAdjacentElement('afterbegin', indicator);
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
} else if (indicator) {
|
|
2468
|
+
indicator.classList.add('fade-out');
|
|
2469
|
+
setTimeout(() => indicator.remove(), 300);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
|
|
2473
|
+
/**
|
|
2474
|
+
* Prepend older messages to the top while preserving scroll position
|
|
2475
|
+
*/
|
|
2476
|
+
prependMessages(messages) {
|
|
2477
|
+
if (!messages || messages.length === 0) return;
|
|
2478
|
+
|
|
2479
|
+
// Use the per-session scroll container (which IS the message container)
|
|
2480
|
+
const container = this.ctx.app?.getActiveScrollContainer() || this.ctx.els.messagesContainer;
|
|
2481
|
+
const messagesDiv = this._getActiveMessageContainer();
|
|
2482
|
+
|
|
2483
|
+
// Save current scroll state
|
|
2484
|
+
const prevScrollHeight = container.scrollHeight;
|
|
2485
|
+
const prevScrollTop = container.scrollTop;
|
|
2486
|
+
|
|
2487
|
+
// Create a document fragment for efficient prepending
|
|
2488
|
+
const fragment = document.createDocumentFragment();
|
|
2489
|
+
|
|
2490
|
+
// Group consecutive thinking and tool messages
|
|
2491
|
+
let i = 0;
|
|
2492
|
+
while (i < messages.length) {
|
|
2493
|
+
const msg = messages[i];
|
|
2494
|
+
|
|
2495
|
+
if (msg.role === 'thinking') {
|
|
2496
|
+
const thinkingGroup = [msg];
|
|
2497
|
+
let j = i + 1;
|
|
2498
|
+
while (j < messages.length && messages[j].role === 'thinking') {
|
|
2499
|
+
thinkingGroup.push(messages[j]);
|
|
2500
|
+
j++;
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
if (thinkingGroup.length >= 2) {
|
|
2504
|
+
const groupDiv = this.thinkingCtrl.createThinkingGroupElement(thinkingGroup);
|
|
2505
|
+
fragment.appendChild(groupDiv);
|
|
2506
|
+
} else {
|
|
2507
|
+
const div = this.createMessageElement(msg);
|
|
2508
|
+
if (div) fragment.appendChild(div);
|
|
2509
|
+
}
|
|
2510
|
+
i = j;
|
|
2511
|
+
} else if (msg.role === 'tool') {
|
|
2512
|
+
// Group consecutive tool messages
|
|
2513
|
+
const toolGroup = [msg];
|
|
2514
|
+
let j = i + 1;
|
|
2515
|
+
while (j < messages.length && messages[j].role === 'tool') {
|
|
2516
|
+
toolGroup.push(messages[j]);
|
|
2517
|
+
j++;
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
if (toolGroup.length >= 2) {
|
|
2521
|
+
const groupDiv = this._createToolGroupElement(toolGroup);
|
|
2522
|
+
fragment.appendChild(groupDiv);
|
|
2523
|
+
} else {
|
|
2524
|
+
const div = this.createMessageElement(msg);
|
|
2525
|
+
if (div) fragment.appendChild(div);
|
|
2526
|
+
}
|
|
2527
|
+
i = j;
|
|
2528
|
+
} else if (msg.role === 'system' || msg.role === 'result') {
|
|
2529
|
+
i++;
|
|
2530
|
+
} else {
|
|
2531
|
+
const div = this.createMessageElement(msg);
|
|
2532
|
+
if (div) fragment.appendChild(div);
|
|
2533
|
+
i++;
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
// Prepend to the messages container
|
|
2538
|
+
const historyNotice = messagesDiv.querySelector('.message-history-notice');
|
|
2539
|
+
const loadIndicator = messagesDiv.querySelector('#load-more-indicator');
|
|
2540
|
+
let insertBefore = historyNotice?.nextSibling || loadIndicator?.nextSibling || messagesDiv.firstChild;
|
|
2541
|
+
|
|
2542
|
+
if (insertBefore) {
|
|
2543
|
+
messagesDiv.insertBefore(fragment, insertBefore);
|
|
2544
|
+
} else {
|
|
2545
|
+
messagesDiv.appendChild(fragment);
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
// Restore scroll position so view doesn't jump
|
|
2549
|
+
requestAnimationFrame(() => {
|
|
2550
|
+
const newScrollHeight = container.scrollHeight;
|
|
2551
|
+
const scrollDiff = newScrollHeight - prevScrollHeight;
|
|
2552
|
+
container.scrollTop = prevScrollTop + scrollDiff;
|
|
2553
|
+
|
|
2554
|
+
// Enable gutter icons for prepended tool groups/messages
|
|
2555
|
+
this.checkAllToolGroupGutterSpace();
|
|
2556
|
+
this.ctx.app?.thinkingCtrl?.checkAllGutterSpace();
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
/**
|
|
2561
|
+
* Trim old messages from DOM to improve scroll performance.
|
|
2562
|
+
* Keeps only the last N messages, but always includes the last complete turn
|
|
2563
|
+
* (user prompt + all AI responses that followed).
|
|
2564
|
+
* Old messages can be reloaded via lazy loading.
|
|
2565
|
+
* @param {number} keepCount - Number of recent messages to keep (default 100)
|
|
2566
|
+
* @returns {number} Number of messages trimmed
|
|
2567
|
+
*/
|
|
2568
|
+
trimOldMessages(keepCount = 100) {
|
|
2569
|
+
const session = this.ctx.session;
|
|
2570
|
+
if (!session || !session.messages) {
|
|
2571
|
+
return 0;
|
|
2572
|
+
}
|
|
2573
|
+
|
|
2574
|
+
const totalMessages = session.messages.length;
|
|
2575
|
+
if (totalMessages <= keepCount) {
|
|
2576
|
+
return 0;
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
const trimCount = totalMessages - keepCount;
|
|
2580
|
+
|
|
2581
|
+
// Get IDs of messages to remove
|
|
2582
|
+
const messagesToRemove = session.messages.slice(0, trimCount);
|
|
2583
|
+
const idsToRemove = new Set(messagesToRemove.map(m => m.id));
|
|
2584
|
+
|
|
2585
|
+
// Remove DOM elements
|
|
2586
|
+
const messagesDiv = this._getActiveMessageContainer();
|
|
2587
|
+
const allMsgElements = messagesDiv.querySelectorAll('[id^="msg-"], .thinking-group, .tool-group');
|
|
2588
|
+
|
|
2589
|
+
for (const el of allMsgElements) {
|
|
2590
|
+
// Check if this element or any of its children should be removed
|
|
2591
|
+
if (el.id?.startsWith('msg-')) {
|
|
2592
|
+
const msgId = el.id.replace('msg-', '');
|
|
2593
|
+
if (idsToRemove.has(msgId)) {
|
|
2594
|
+
el.remove();
|
|
2595
|
+
}
|
|
2596
|
+
} else if (el.classList.contains('thinking-group') || el.classList.contains('tool-group')) {
|
|
2597
|
+
// For groups, check if ALL messages in group should be removed
|
|
2598
|
+
const groupMsgIds = Array.from(el.querySelectorAll('[id^="msg-"]'))
|
|
2599
|
+
.map(child => child.id.replace('msg-', ''));
|
|
2600
|
+
if (groupMsgIds.length > 0 && groupMsgIds.every(id => idsToRemove.has(id))) {
|
|
2601
|
+
el.remove();
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
|
|
2606
|
+
// Remove from session.messages array
|
|
2607
|
+
session.messages.splice(0, trimCount);
|
|
2608
|
+
|
|
2609
|
+
// Mark that there are more messages available for lazy loading
|
|
2610
|
+
session.hasMoreMessages = true;
|
|
2611
|
+
|
|
2612
|
+
// Update the history notice to show there's more
|
|
2613
|
+
this.updateHistoryNotice();
|
|
2614
|
+
|
|
2615
|
+
return trimCount;
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
/**
|
|
2619
|
+
* Get count of messages that would be trimmed
|
|
2620
|
+
* Uses same logic as trimOldMessages to ensure complete turns are preserved
|
|
2621
|
+
* @param {number} keepCount - Number to keep (default 100)
|
|
2622
|
+
* @returns {number} Count that would be trimmed
|
|
2623
|
+
*/
|
|
2624
|
+
getTrimCount(keepCount = 100) {
|
|
2625
|
+
const session = this.ctx.session;
|
|
2626
|
+
if (!session || !session.messages) return 0;
|
|
2627
|
+
|
|
2628
|
+
const totalMessages = session.messages.length;
|
|
2629
|
+
if (totalMessages <= keepCount) return 0;
|
|
2630
|
+
|
|
2631
|
+
return totalMessages - keepCount;
|
|
2632
|
+
}
|
|
2633
|
+
|
|
2634
|
+
/**
|
|
2635
|
+
* Create a message DOM element without appending it
|
|
2636
|
+
*/
|
|
2637
|
+
createMessageElement(msg) {
|
|
2638
|
+
if (msg.role === 'system' || msg.role === 'result') return null;
|
|
2639
|
+
|
|
2640
|
+
if (msg.role === 'thinking') {
|
|
2641
|
+
const div = document.createElement('div');
|
|
2642
|
+
div.className = 'message thinking';
|
|
2643
|
+
div.id = `msg-${msg.id}`;
|
|
2644
|
+
div.innerHTML = this.thinkingCtrl.renderThinkingBlock(msg);
|
|
2645
|
+
return div;
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
// Handle info messages (e.g., compaction summary, /context results)
|
|
2649
|
+
if (msg.role === 'info') {
|
|
2650
|
+
const div = document.createElement('div');
|
|
2651
|
+
div.id = `msg-${msg.id}`;
|
|
2652
|
+
|
|
2653
|
+
// Check if this is /context output - render as collapsible block
|
|
2654
|
+
if (msg.source === 'local-command-stdout' && this._isContextOutput(msg.content)) {
|
|
2655
|
+
div.className = 'message context';
|
|
2656
|
+
div.innerHTML = this._renderContextBlock(msg.content, msg.timestamp);
|
|
2657
|
+
} else {
|
|
2658
|
+
div.className = 'message info';
|
|
2659
|
+
// Use markdown rendering for command output (has tables), plain text for simple info
|
|
2660
|
+
const contentHtml = msg.source === 'local-command-stdout'
|
|
2661
|
+
? `<div class="markdown-content">${this.ctx.markdown.render(msg.content)}</div>`
|
|
2662
|
+
: escapeHtml(msg.content);
|
|
2663
|
+
div.innerHTML = `
|
|
2664
|
+
<div class="message-header">
|
|
2665
|
+
<span class="message-role info">
|
|
2666
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2667
|
+
<circle cx="12" cy="12" r="10"/>
|
|
2668
|
+
<line x1="12" y1="16" x2="12" y2="12"/>
|
|
2669
|
+
<line x1="12" y1="8" x2="12.01" y2="8"/>
|
|
2670
|
+
</svg>
|
|
2671
|
+
info
|
|
2672
|
+
</span>
|
|
2673
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
2674
|
+
</div>
|
|
2675
|
+
<div class="message-content">${contentHtml}</div>
|
|
2676
|
+
`;
|
|
2677
|
+
}
|
|
2678
|
+
return div;
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2681
|
+
// Handle auth-error affordance — Claude CLI returned 401 / expired token.
|
|
2682
|
+
if (msg.role === 'auth_error') {
|
|
2683
|
+
return this._renderAuthError(msg);
|
|
2684
|
+
}
|
|
2685
|
+
|
|
2686
|
+
// Handle AskUserQuestion - interactive question form
|
|
2687
|
+
if (msg.role === 'question') {
|
|
2688
|
+
return this._renderQuestionForm(msg);
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
// Handle ExitPlanMode - interactive plan approval
|
|
2692
|
+
if (msg.role === 'plan_approval') {
|
|
2693
|
+
return this._renderPlanApproval(msg);
|
|
2694
|
+
}
|
|
2695
|
+
|
|
2696
|
+
// Handle interactive permission ask (claude-sdk can_use_tool)
|
|
2697
|
+
if (msg.role === 'permission') {
|
|
2698
|
+
return this._renderPermissionCard(msg);
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
const div = document.createElement('div');
|
|
2702
|
+
const planModeClass = msg.planMode ? ' plan-mode' : '';
|
|
2703
|
+
div.className = `message ${msg.role}${planModeClass}`;
|
|
2704
|
+
div.id = `msg-${msg.id}`;
|
|
2705
|
+
|
|
2706
|
+
if (msg.role === 'tool') {
|
|
2707
|
+
div.innerHTML = this.ctx.toolRenderer.renderToolBlock(msg);
|
|
2708
|
+
} else {
|
|
2709
|
+
const content = this._renderMessageContent(msg);
|
|
2710
|
+
|
|
2711
|
+
const copyButton = (msg.role === 'assistant' || msg.role === 'user') ? `
|
|
2712
|
+
<button class="message-copy-btn" data-msg-id="${msg.id}" data-id="${escapeAttr(msg.id)}" data-act="copy-message" data-tooltip="Copy message">
|
|
2713
|
+
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2714
|
+
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
|
|
2715
|
+
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
2716
|
+
</svg>
|
|
2717
|
+
<span class="copy-label">Copy</span>
|
|
2718
|
+
</button>
|
|
2719
|
+
` : '';
|
|
2720
|
+
|
|
2721
|
+
// Favorite button for user messages
|
|
2722
|
+
const favoriteButton = (msg.role === 'user') ? `
|
|
2723
|
+
<button class="message-favorite-btn${msg.isFavorite ? ' active' : ''}${msg.promptId ? '' : ' hidden'}"
|
|
2724
|
+
data-msg-id="${msg.id}"
|
|
2725
|
+
data-prompt-id="${msg.promptId || ''}"
|
|
2726
|
+
data-act="toggle-message-favorite"
|
|
2727
|
+
data-tooltip="${msg.isFavorite ? 'Remove from favorites' : 'Add to favorites'}">
|
|
2728
|
+
<svg class="heart-outline" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2729
|
+
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
|
|
2730
|
+
</svg>
|
|
2731
|
+
<svg class="heart-filled" width="12" height="12" viewBox="0 0 24 24" fill="currentColor" stroke="none">
|
|
2732
|
+
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
|
|
2733
|
+
</svg>
|
|
2734
|
+
</button>
|
|
2735
|
+
` : '';
|
|
2736
|
+
|
|
2737
|
+
// Thinking indicator for user messages
|
|
2738
|
+
const effortIndicator = msg.role === 'user' ? this._renderEffortIndicator(msg.effort_level) : '';
|
|
2739
|
+
|
|
2740
|
+
div.innerHTML = `
|
|
2741
|
+
<div class="message-header">
|
|
2742
|
+
<span class="message-role ${msg.role}">${this._authorLabel(msg)}</span>
|
|
2743
|
+
${effortIndicator}
|
|
2744
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
2745
|
+
${favoriteButton}
|
|
2746
|
+
${copyButton}
|
|
2747
|
+
</div>
|
|
2748
|
+
<div class="message-content">${content}</div>
|
|
2749
|
+
`;
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
// Render excalidraw code blocks as SVG diagrams
|
|
2753
|
+
MarkdownRenderer.processExcalidrawBlocks(div);
|
|
2754
|
+
// Render Vega-Lite chart code blocks as SVG charts
|
|
2755
|
+
MarkdownRenderer.processChartBlocks(div);
|
|
2756
|
+
|
|
2757
|
+
return div;
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2761
|
+
// WELCOME SCREEN
|
|
2762
|
+
// ═══════════════════════════════════════════════════════════════
|
|
2763
|
+
|
|
2764
|
+
/**
|
|
2765
|
+
* Render recent projects/sessions in the welcome screen
|
|
2766
|
+
* Uses a short cache (5s) to prevent flickering from redundant API calls
|
|
2767
|
+
*/
|
|
2768
|
+
async renderRecentProjects(container) {
|
|
2769
|
+
if (!container) return;
|
|
2770
|
+
|
|
2771
|
+
const CACHE_TTL = 5000; // 5 seconds
|
|
2772
|
+
const now = Date.now();
|
|
2773
|
+
|
|
2774
|
+
// Use cached data if fresh (prevents flicker on rapid re-renders)
|
|
2775
|
+
if (this._recentSessionsCache && (now - this._recentSessionsCacheTime) < CACHE_TTL) {
|
|
2776
|
+
this._renderSessionsList(container, this._recentSessionsCache);
|
|
2777
|
+
return;
|
|
2778
|
+
}
|
|
2779
|
+
|
|
2780
|
+
container.innerHTML = '<div class="loading-sessions">Loading sessions...</div>';
|
|
2781
|
+
|
|
2782
|
+
try {
|
|
2783
|
+
const response = await fetch(`${CONFIG.API_BASE}/api/sessions`);
|
|
2784
|
+
|
|
2785
|
+
// Check if container is still in DOM (might have been removed by re-render)
|
|
2786
|
+
if (!container.isConnected) {
|
|
2787
|
+
return;
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
const data = await response.json();
|
|
2791
|
+
const sessions = data.sessions || [];
|
|
2792
|
+
|
|
2793
|
+
// Update cache
|
|
2794
|
+
this._recentSessionsCache = sessions;
|
|
2795
|
+
this._recentSessionsCacheTime = now;
|
|
2796
|
+
|
|
2797
|
+
// Double-check container is still connected before updating
|
|
2798
|
+
if (container.isConnected) {
|
|
2799
|
+
this._renderSessionsList(container, sessions);
|
|
2800
|
+
}
|
|
2801
|
+
} catch (error) {
|
|
2802
|
+
console.error('Failed to load sessions:', error);
|
|
2803
|
+
if (container.isConnected) {
|
|
2804
|
+
this._renderHistoryFallback(container);
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
/**
|
|
2810
|
+
* Render the sessions list (used by cache hit and fresh fetch)
|
|
2811
|
+
* @private
|
|
2812
|
+
*/
|
|
2813
|
+
_renderSessionsList(container, sessions) {
|
|
2814
|
+
if (sessions.length > 0) {
|
|
2815
|
+
const recentSessions = sessions.slice(0, 5);
|
|
2816
|
+
container.innerHTML = `
|
|
2817
|
+
<h4>Continue</h4>
|
|
2818
|
+
<div class="session-list">
|
|
2819
|
+
${recentSessions.map(s => {
|
|
2820
|
+
const name = s.name || basename(s.cwd) || 'Session';
|
|
2821
|
+
const msgCount = s.message_count || 0;
|
|
2822
|
+
const timeAgo = formatRelativeTime(s.last_activity);
|
|
2823
|
+
const cost = s.total_cost > 0 ? `$${s.total_cost.toFixed(3)}` : '';
|
|
2824
|
+
return `
|
|
2825
|
+
<div class="session-item" data-session-id="${escapeHtml(s.id)}" data-path="${escapeHtml(s.cwd || '')}">
|
|
2826
|
+
<div class="session-item-icon">
|
|
2827
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2828
|
+
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
|
2829
|
+
</svg>
|
|
2830
|
+
${msgCount > 0 ? `<span class="msg-badge">${msgCount}</span>` : ''}
|
|
2831
|
+
</div>
|
|
2832
|
+
<div class="session-item-info">
|
|
2833
|
+
<div class="session-item-name">${escapeHtml(name)}</div>
|
|
2834
|
+
<div class="session-item-meta">
|
|
2835
|
+
<span>${timeAgo}</span>
|
|
2836
|
+
${cost ? `<span class="session-cost">${cost}</span>` : ''}
|
|
2837
|
+
</div>
|
|
2838
|
+
</div>
|
|
2839
|
+
<svg class="session-item-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2840
|
+
<path d="M9 18l6-6-6-6"/>
|
|
2841
|
+
</svg>
|
|
2842
|
+
</div>
|
|
2843
|
+
`;
|
|
2844
|
+
}).join('')}
|
|
2845
|
+
</div>
|
|
2846
|
+
`;
|
|
2847
|
+
|
|
2848
|
+
// Add click handlers for sessions
|
|
2849
|
+
container.querySelectorAll('.session-item').forEach(item => {
|
|
2850
|
+
item.addEventListener('click', () => {
|
|
2851
|
+
const sessionId = item.dataset.sessionId;
|
|
2852
|
+
const cwd = item.dataset.path;
|
|
2853
|
+
this.ctx.emit('sessionItemClicked', { sessionId, cwd });
|
|
2854
|
+
});
|
|
2855
|
+
});
|
|
2856
|
+
|
|
2857
|
+
} else {
|
|
2858
|
+
// No sessions - check for history
|
|
2859
|
+
this._renderHistoryFallback(container);
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
|
|
2863
|
+
/**
|
|
2864
|
+
* Fallback to localStorage history if no server sessions
|
|
2865
|
+
*/
|
|
2866
|
+
_renderHistoryFallback(container) {
|
|
2867
|
+
const history = window.app?.getCwdHistory?.() || [];
|
|
2868
|
+
|
|
2869
|
+
if (history.length > 0) {
|
|
2870
|
+
const projects = history.slice(0, 5);
|
|
2871
|
+
container.innerHTML = `
|
|
2872
|
+
<h4>Recent Projects</h4>
|
|
2873
|
+
<div class="project-list">
|
|
2874
|
+
${projects.map(path => {
|
|
2875
|
+
const name = basename(path);
|
|
2876
|
+
return `
|
|
2877
|
+
<div class="project-item" data-path="${escapeHtml(path)}">
|
|
2878
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2879
|
+
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
|
|
2880
|
+
</svg>
|
|
2881
|
+
<div>
|
|
2882
|
+
<div class="project-name">${escapeHtml(name)}</div>
|
|
2883
|
+
<div class="project-path">${escapeHtml(path)}</div>
|
|
2884
|
+
</div>
|
|
2885
|
+
</div>
|
|
2886
|
+
`;
|
|
2887
|
+
}).join('')}
|
|
2888
|
+
</div>
|
|
2889
|
+
`;
|
|
2890
|
+
|
|
2891
|
+
container.querySelectorAll('.project-item').forEach(item => {
|
|
2892
|
+
item.addEventListener('click', () => {
|
|
2893
|
+
const path = item.dataset.path;
|
|
2894
|
+
this.ctx.emit('projectItemClicked', { path });
|
|
2895
|
+
});
|
|
2896
|
+
});
|
|
2897
|
+
} else {
|
|
2898
|
+
container.innerHTML = '';
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
|
|
2902
|
+
// ─────────────────────────────────────────────────────────────────
|
|
2903
|
+
// New Welcome Screen API
|
|
2904
|
+
// ─────────────────────────────────────────────────────────────────
|
|
2905
|
+
|
|
2906
|
+
/**
|
|
2907
|
+
* Check if the welcome view is currently the active top-level view.
|
|
2908
|
+
*/
|
|
2909
|
+
isWelcomeShowing() {
|
|
2910
|
+
return this.ctx.app?.tabCtrl?.activeMode === 'welcome';
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
/**
|
|
2914
|
+
* Handle a task message from welcome screen.
|
|
2915
|
+
* Searches for related sessions and shows options to continue or start fresh.
|
|
2916
|
+
* @param {string} task - Task/message to send
|
|
2917
|
+
*/
|
|
2918
|
+
async welcomeTask(task) {
|
|
2919
|
+
const c = this._activeWelcomeContainer();
|
|
2920
|
+
if (c) await handleWelcomeTask(task, c);
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
/**
|
|
2924
|
+
* Check if welcome is in task mode (showing related sessions)
|
|
2925
|
+
*/
|
|
2926
|
+
isWelcomeInTaskMode() {
|
|
2927
|
+
return this.isWelcomeShowing() && isTaskMode();
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
/**
|
|
2931
|
+
* Reset welcome screen to default state
|
|
2932
|
+
*/
|
|
2933
|
+
welcomeReset() {
|
|
2934
|
+
const c = this._activeWelcomeContainer();
|
|
2935
|
+
if (c) resetWelcomeScreen(c);
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
/**
|
|
2939
|
+
* Refresh welcome screen sessions
|
|
2940
|
+
*/
|
|
2941
|
+
async welcomeRefresh() {
|
|
2942
|
+
const c = this._activeWelcomeContainer();
|
|
2943
|
+
if (c) await refreshSessions(c);
|
|
2944
|
+
}
|
|
2945
|
+
|
|
2946
|
+
/**
|
|
2947
|
+
* Show the floating "Back to sessions" pill at bottom-left
|
|
2948
|
+
* @param {Object} session - The current session
|
|
2949
|
+
*/
|
|
2950
|
+
_showBackToSessionsPill(session) {
|
|
2951
|
+
// Remove any existing pill first
|
|
2952
|
+
this._hideBackToSessionsPill();
|
|
2953
|
+
|
|
2954
|
+
const pill = document.createElement('div');
|
|
2955
|
+
pill.className = 'back-to-sessions-pill';
|
|
2956
|
+
pill.id = 'back-to-sessions-pill';
|
|
2957
|
+
pill.innerHTML = `
|
|
2958
|
+
<button class="back-pill-btn" data-tooltip="Return to session list (Backspace)">
|
|
2959
|
+
<span class="back-pill-key">⌫</span>
|
|
2960
|
+
<span>Back to sessions</span>
|
|
2961
|
+
</button>
|
|
2962
|
+
<button class="back-pill-dismiss" data-tooltip="Dismiss (Esc)">
|
|
2963
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2964
|
+
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
2965
|
+
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
2966
|
+
</svg>
|
|
2967
|
+
</button>
|
|
2968
|
+
`;
|
|
2969
|
+
|
|
2970
|
+
// Back button click handler
|
|
2971
|
+
pill.querySelector('.back-pill-btn').addEventListener('click', () => {
|
|
2972
|
+
this._handleBackToSessions();
|
|
2973
|
+
});
|
|
2974
|
+
|
|
2975
|
+
// Dismiss button click handler
|
|
2976
|
+
pill.querySelector('.back-pill-dismiss').addEventListener('click', () => {
|
|
2977
|
+
session.openedFromWelcome = false;
|
|
2978
|
+
clearSavedWelcomeState();
|
|
2979
|
+
this._hideBackToSessionsPill();
|
|
2980
|
+
});
|
|
2981
|
+
|
|
2982
|
+
// Setup swipe-right gesture for touch devices (iPad)
|
|
2983
|
+
this._setupSwipeGesture(pill);
|
|
2984
|
+
|
|
2985
|
+
// Append to body (fixed positioning, so location doesn't matter)
|
|
2986
|
+
document.body.appendChild(pill);
|
|
2987
|
+
|
|
2988
|
+
// Fade in animation
|
|
2989
|
+
requestAnimationFrame(() => {
|
|
2990
|
+
pill.classList.add('visible');
|
|
2991
|
+
});
|
|
2992
|
+
|
|
2993
|
+
// Auto-hide after 8 seconds (soft fade to not annoy user)
|
|
2994
|
+
// Clear any existing timeout first
|
|
2995
|
+
if (this._backPillTimeout) {
|
|
2996
|
+
clearTimeout(this._backPillTimeout);
|
|
2997
|
+
}
|
|
2998
|
+
this._backPillTimeout = setTimeout(() => {
|
|
2999
|
+
this._dismissBackToSessionsPill();
|
|
3000
|
+
}, 8000);
|
|
3001
|
+
}
|
|
3002
|
+
|
|
3003
|
+
/**
|
|
3004
|
+
* Hide the "Back to sessions" pill
|
|
3005
|
+
*/
|
|
3006
|
+
_hideBackToSessionsPill() {
|
|
3007
|
+
// Clear auto-hide timeout
|
|
3008
|
+
if (this._backPillTimeout) {
|
|
3009
|
+
clearTimeout(this._backPillTimeout);
|
|
3010
|
+
this._backPillTimeout = null;
|
|
3011
|
+
}
|
|
3012
|
+
const pill = document.getElementById('back-to-sessions-pill');
|
|
3013
|
+
if (pill) {
|
|
3014
|
+
pill.classList.remove('visible');
|
|
3015
|
+
setTimeout(() => pill.remove(), 150);
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
/**
|
|
3020
|
+
* Check if back-to-sessions is available (for Escape key handler)
|
|
3021
|
+
* @returns {boolean}
|
|
3022
|
+
*/
|
|
3023
|
+
canGoBackToSessions() {
|
|
3024
|
+
const session = this.ctx.session;
|
|
3025
|
+
return session?.openedFromWelcome && !!getSavedWelcomeState();
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
/**
|
|
3029
|
+
* Dismiss the pill without navigating (called by Escape key)
|
|
3030
|
+
* Clears the flag and state so pill won't reappear
|
|
3031
|
+
*/
|
|
3032
|
+
_dismissBackToSessionsPill() {
|
|
3033
|
+
const session = this.ctx.session;
|
|
3034
|
+
if (session) {
|
|
3035
|
+
session.openedFromWelcome = false;
|
|
3036
|
+
clearSavedWelcomeState();
|
|
3037
|
+
}
|
|
3038
|
+
this._hideBackToSessionsPill();
|
|
3039
|
+
}
|
|
3040
|
+
|
|
3041
|
+
/**
|
|
3042
|
+
* Setup swipe-right gesture on pill for touch devices
|
|
3043
|
+
* Swipe right from left edge triggers back-to-sessions
|
|
3044
|
+
* @param {HTMLElement} pill - The pill element
|
|
3045
|
+
*/
|
|
3046
|
+
_setupSwipeGesture(pill) {
|
|
3047
|
+
let touchStartX = 0;
|
|
3048
|
+
let touchStartY = 0;
|
|
3049
|
+
const SWIPE_THRESHOLD = 80;
|
|
3050
|
+
const VERTICAL_TOLERANCE = 50;
|
|
3051
|
+
|
|
3052
|
+
// Also setup edge swipe on the messages container
|
|
3053
|
+
const messagesEl = this.ctx.els.messages;
|
|
3054
|
+
if (!messagesEl) return;
|
|
3055
|
+
|
|
3056
|
+
const handleTouchStart = (e) => {
|
|
3057
|
+
const touch = e.touches[0];
|
|
3058
|
+
// Only track touches starting from left edge (within 30px)
|
|
3059
|
+
if (touch.clientX <= 30) {
|
|
3060
|
+
touchStartX = touch.clientX;
|
|
3061
|
+
touchStartY = touch.clientY;
|
|
3062
|
+
} else {
|
|
3063
|
+
touchStartX = 0;
|
|
3064
|
+
}
|
|
3065
|
+
};
|
|
3066
|
+
|
|
3067
|
+
const handleTouchEnd = (e) => {
|
|
3068
|
+
if (touchStartX === 0) return;
|
|
3069
|
+
|
|
3070
|
+
const touch = e.changedTouches[0];
|
|
3071
|
+
const deltaX = touch.clientX - touchStartX;
|
|
3072
|
+
const deltaY = Math.abs(touch.clientY - touchStartY);
|
|
3073
|
+
|
|
3074
|
+
// Check if it's a rightward swipe from left edge
|
|
3075
|
+
if (deltaX > SWIPE_THRESHOLD && deltaY < VERTICAL_TOLERANCE) {
|
|
3076
|
+
this._handleBackToSessions();
|
|
3077
|
+
}
|
|
3078
|
+
|
|
3079
|
+
touchStartX = 0;
|
|
3080
|
+
};
|
|
3081
|
+
|
|
3082
|
+
messagesEl.addEventListener('touchstart', handleTouchStart, { passive: true });
|
|
3083
|
+
messagesEl.addEventListener('touchend', handleTouchEnd, { passive: true });
|
|
3084
|
+
|
|
3085
|
+
// Store cleanup function
|
|
3086
|
+
this._swipeCleanup = () => {
|
|
3087
|
+
messagesEl.removeEventListener('touchstart', handleTouchStart);
|
|
3088
|
+
messagesEl.removeEventListener('touchend', handleTouchEnd);
|
|
3089
|
+
};
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
/**
|
|
3093
|
+
* Handle "Back to sessions" - close current session and return to welcome
|
|
3094
|
+
* Restores the previous welcome screen state (search, scroll, etc.)
|
|
3095
|
+
*/
|
|
3096
|
+
_handleBackToSessions() {
|
|
3097
|
+
const session = this.ctx.session;
|
|
3098
|
+
if (!session) return;
|
|
3099
|
+
|
|
3100
|
+
// Hide the pill first
|
|
3101
|
+
this._hideBackToSessionsPill();
|
|
3102
|
+
|
|
3103
|
+
// Cleanup swipe gesture listeners
|
|
3104
|
+
if (this._swipeCleanup) {
|
|
3105
|
+
this._swipeCleanup();
|
|
3106
|
+
this._swipeCleanup = null;
|
|
3107
|
+
}
|
|
3108
|
+
|
|
3109
|
+
// Clear the flag
|
|
3110
|
+
session.openedFromWelcome = false;
|
|
3111
|
+
|
|
3112
|
+
// Get the app reference
|
|
3113
|
+
const app = this.ctx.app;
|
|
3114
|
+
if (!app) return;
|
|
3115
|
+
|
|
3116
|
+
// Remove this session from the tab list
|
|
3117
|
+
app.sessionManager.remove(session);
|
|
3118
|
+
|
|
3119
|
+
// Create a new session (shows welcome screen)
|
|
3120
|
+
app.createSession();
|
|
3121
|
+
|
|
3122
|
+
// Restore the welcome state after render (welcome lives in #welcome-view now)
|
|
3123
|
+
requestAnimationFrame(() => {
|
|
3124
|
+
const welcomeContainer = app.els.welcomeView?.querySelector('#welcome-container');
|
|
3125
|
+
if (welcomeContainer) {
|
|
3126
|
+
restoreWelcomeState(welcomeContainer);
|
|
3127
|
+
}
|
|
3128
|
+
});
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3132
|
+
// UTILITIES
|
|
3133
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3134
|
+
|
|
3135
|
+
clearMessages() {
|
|
3136
|
+
if (this.ctx.session) {
|
|
3137
|
+
this.ctx.session.clearServer();
|
|
3138
|
+
this.ctx.session.clear();
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3143
|
+
// EXITPLANMODE APPROVAL RENDERING
|
|
3144
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3145
|
+
|
|
3146
|
+
/**
|
|
3147
|
+
* Render an interactive plan approval card for ExitPlanMode tool
|
|
3148
|
+
* @param {Object} msg - Plan approval message with answered/decision state
|
|
3149
|
+
* @returns {HTMLElement} The approval card element
|
|
3150
|
+
*/
|
|
3151
|
+
/**
|
|
3152
|
+
* Auth-error affordance — the engine CLI returned 401 / expired token.
|
|
3153
|
+
* Renders the reason plus a one-click button into the engine's own login
|
|
3154
|
+
* PTY (`claude auth login` / `codex login --device-auth`, carried on the
|
|
3155
|
+
* message as `loginCommand`; label from `engine`). Shared by renderMessage
|
|
3156
|
+
* (live) and createMessageElement (re-render/lazy-load) so the button
|
|
3157
|
+
* survives session switches and page reloads.
|
|
3158
|
+
*/
|
|
3159
|
+
_renderAuthError(msg) {
|
|
3160
|
+
const engine = msg.engine || 'Claude';
|
|
3161
|
+
const div = document.createElement('div');
|
|
3162
|
+
div.className = 'message error auth-error';
|
|
3163
|
+
div.id = `msg-${msg.id}`;
|
|
3164
|
+
div.innerHTML = `
|
|
3165
|
+
<div class="message-header">
|
|
3166
|
+
<span class="message-role error">
|
|
3167
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3168
|
+
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
|
|
3169
|
+
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
|
|
3170
|
+
</svg>
|
|
3171
|
+
${escapeHtml(S.auth.error_role)}
|
|
3172
|
+
</span>
|
|
3173
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
3174
|
+
</div>
|
|
3175
|
+
<div class="message-content">
|
|
3176
|
+
<div class="auth-error-reason">${escapeHtml(msg.content)}</div>
|
|
3177
|
+
<button class="auth-error-login-btn" data-act="open-login-terminal">
|
|
3178
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3179
|
+
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
|
|
3180
|
+
<polyline points="10 17 15 12 10 7"/>
|
|
3181
|
+
<line x1="15" y1="12" x2="3" y2="12"/>
|
|
3182
|
+
</svg>
|
|
3183
|
+
${escapeHtml(S.auth.login_button.replace('{engine}', engine))}
|
|
3184
|
+
</button>
|
|
3185
|
+
</div>
|
|
3186
|
+
`;
|
|
3187
|
+
// Dataset assignment (not string interpolation) so the command needs
|
|
3188
|
+
// no attribute escaping.
|
|
3189
|
+
const btn = div.querySelector('.auth-error-login-btn');
|
|
3190
|
+
if (btn && msg.loginCommand) btn.dataset.command = msg.loginCommand;
|
|
3191
|
+
return div;
|
|
3192
|
+
}
|
|
3193
|
+
|
|
3194
|
+
_renderPlanApproval(msg) {
|
|
3195
|
+
const div = document.createElement('div');
|
|
3196
|
+
div.className = `message plan-approval${msg.answered ? ' answered' : ''}`;
|
|
3197
|
+
div.id = `msg-${msg.id}`;
|
|
3198
|
+
|
|
3199
|
+
const isAnswered = msg.answered;
|
|
3200
|
+
const decision = msg.decision;
|
|
3201
|
+
|
|
3202
|
+
// Preview Plan button (disabled if no plan file found)
|
|
3203
|
+
const hasPlanFile = !!msg.planFile;
|
|
3204
|
+
const previewBtn = `
|
|
3205
|
+
<button class="plan-preview-btn" data-act="preview-plan"${hasPlanFile ? '' : ' disabled'}>
|
|
3206
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3207
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
3208
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
3209
|
+
<line x1="16" y1="13" x2="8" y2="13"/>
|
|
3210
|
+
<line x1="16" y1="17" x2="8" y2="17"/>
|
|
3211
|
+
</svg>
|
|
3212
|
+
Preview Plan
|
|
3213
|
+
</button>`;
|
|
3214
|
+
|
|
3215
|
+
let statusHtml;
|
|
3216
|
+
if (isAnswered && decision === 'approve') {
|
|
3217
|
+
statusHtml = `
|
|
3218
|
+
<div class="plan-approval-status approved">
|
|
3219
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3220
|
+
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
|
|
3221
|
+
<polyline points="22 4 12 14.01 9 11.01"/>
|
|
3222
|
+
</svg>
|
|
3223
|
+
Approved — proceeding with implementation
|
|
3224
|
+
</div>
|
|
3225
|
+
<div class="plan-approval-actions">
|
|
3226
|
+
${previewBtn}
|
|
3227
|
+
</div>`;
|
|
3228
|
+
} else if (isAnswered && decision === 'revise') {
|
|
3229
|
+
// Final revise — user sent a message without clicking Approve (no undo)
|
|
3230
|
+
statusHtml = `
|
|
3231
|
+
<div class="plan-approval-status rejected">
|
|
3232
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3233
|
+
<path d="M1 4v6h6M23 20v-6h-6"/>
|
|
3234
|
+
<path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
|
|
3235
|
+
</svg>
|
|
3236
|
+
Revised
|
|
3237
|
+
</div>
|
|
3238
|
+
<div class="plan-approval-actions">
|
|
3239
|
+
${previewBtn}
|
|
3240
|
+
</div>`;
|
|
3241
|
+
} else if (decision === 'revise') {
|
|
3242
|
+
// Soft revise — show status but keep Approve button (user can change mind)
|
|
3243
|
+
statusHtml = `
|
|
3244
|
+
<div class="plan-approval-status rejected">
|
|
3245
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3246
|
+
<path d="M1 4v6h6M23 20v-6h-6"/>
|
|
3247
|
+
<path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
|
|
3248
|
+
</svg>
|
|
3249
|
+
Revising — provide feedback below
|
|
3250
|
+
</div>
|
|
3251
|
+
<div class="plan-approval-actions">
|
|
3252
|
+
<button class="plan-approve-btn" data-act="approve-plan" data-id="${escapeAttr(msg.id)}">
|
|
3253
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3254
|
+
<polyline points="20 6 9 17 4 12"/>
|
|
3255
|
+
</svg>
|
|
3256
|
+
Approve & Proceed
|
|
3257
|
+
</button>
|
|
3258
|
+
${previewBtn}
|
|
3259
|
+
</div>`;
|
|
3260
|
+
} else {
|
|
3261
|
+
statusHtml = `
|
|
3262
|
+
<div class="plan-approval-actions">
|
|
3263
|
+
<button class="plan-approve-btn" data-act="approve-plan" data-id="${escapeAttr(msg.id)}">
|
|
3264
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3265
|
+
<polyline points="20 6 9 17 4 12"/>
|
|
3266
|
+
</svg>
|
|
3267
|
+
Approve & Proceed
|
|
3268
|
+
</button>
|
|
3269
|
+
<button class="plan-reject-btn" data-act="reject-plan" data-id="${escapeAttr(msg.id)}">
|
|
3270
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3271
|
+
<path d="M1 4v6h6M23 20v-6h-6"/>
|
|
3272
|
+
<path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
|
|
3273
|
+
</svg>
|
|
3274
|
+
Revise Plan
|
|
3275
|
+
</button>
|
|
3276
|
+
${previewBtn}
|
|
3277
|
+
</div>`;
|
|
3278
|
+
}
|
|
3279
|
+
|
|
3280
|
+
div.innerHTML = `
|
|
3281
|
+
<div class="message-header">
|
|
3282
|
+
<span class="message-role plan-approval">
|
|
3283
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3284
|
+
<path d="M9 11l3 3L22 4"/>
|
|
3285
|
+
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>
|
|
3286
|
+
</svg>
|
|
3287
|
+
Plan ready for review
|
|
3288
|
+
</span>
|
|
3289
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
3290
|
+
</div>
|
|
3291
|
+
<div class="plan-approval-body">
|
|
3292
|
+
<p class="plan-approval-desc">Claude has finished the plan. Review it above and choose how to proceed.</p>
|
|
3293
|
+
${statusHtml}
|
|
3294
|
+
</div>
|
|
3295
|
+
`;
|
|
3296
|
+
|
|
3297
|
+
return div;
|
|
3298
|
+
}
|
|
3299
|
+
|
|
3300
|
+
/**
|
|
3301
|
+
* Render an interactive permission card (claude-sdk can_use_tool ask).
|
|
3302
|
+
* The provider process is paused until the user answers — Allow/Deny plus
|
|
3303
|
+
* an optional deny-guidance input.
|
|
3304
|
+
* @param {Object} msg - {requestId, toolName, toolInput, description, answered, decision}
|
|
3305
|
+
*/
|
|
3306
|
+
_renderPermissionCard(msg) {
|
|
3307
|
+
const div = document.createElement('div');
|
|
3308
|
+
div.className = `message permission-card${msg.answered ? ' answered' : ''}`;
|
|
3309
|
+
div.id = `msg-${msg.id}`;
|
|
3310
|
+
|
|
3311
|
+
const PC = S.permission_card;
|
|
3312
|
+
const toolName = escapeHtml(msg.toolName || 'tool');
|
|
3313
|
+
|
|
3314
|
+
// Tool-input preview: rendered per-tool in human-friendly form
|
|
3315
|
+
// (Write → file + content preview, Edit → diff, Bash → command,
|
|
3316
|
+
// everything else → key/value table) rather than a raw JSON dump.
|
|
3317
|
+
const inputHtml = this._renderPermissionInput(msg.toolName, msg.toolInput || {});
|
|
3318
|
+
|
|
3319
|
+
const descHtml = msg.description
|
|
3320
|
+
? `<p class="permission-desc">${escapeHtml(msg.description)}</p>` : '';
|
|
3321
|
+
|
|
3322
|
+
// Elapsed-wait timer (unanswered cards only). Asks pause the process
|
|
3323
|
+
// indefinitely — there's no countdown, this just shows how long the
|
|
3324
|
+
// ask has been waiting. A 1s ticker updates it in place.
|
|
3325
|
+
const startMs = Date.parse(msg.timestamp) || Date.now();
|
|
3326
|
+
const elapsed0 = this._formatDuration(Math.max(0, Date.now() - startMs)) || '0s';
|
|
3327
|
+
|
|
3328
|
+
let statusHtml;
|
|
3329
|
+
if (msg.answered) {
|
|
3330
|
+
const statusMap = {
|
|
3331
|
+
allow: { cls: 'allowed', label: PC.status_allowed, icon: '<polyline points="20 6 9 17 4 12"/>' },
|
|
3332
|
+
allow_always: { cls: 'allowed', label: PC.status_allowed_always, icon: '<polyline points="20 6 9 17 4 12"/>' },
|
|
3333
|
+
deny: { cls: 'denied', label: PC.status_denied, icon: '<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>' },
|
|
3334
|
+
expired: { cls: 'expired', label: PC.status_expired, icon: '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>' },
|
|
3335
|
+
};
|
|
3336
|
+
const st = statusMap[msg.decision] || statusMap.expired;
|
|
3337
|
+
// How long the ask waited before resolving/expiring (frozen).
|
|
3338
|
+
const waitedHtml = (typeof msg.waitedMs === 'number')
|
|
3339
|
+
? `<span class="permission-status-elapsed">${escapeHtml(PC.waited.replace('{elapsed}', this._formatDuration(msg.waitedMs) || '0s'))}</span>`
|
|
3340
|
+
: '';
|
|
3341
|
+
// Deny guidance the user typed, echoed on the resolved card so the
|
|
3342
|
+
// decision reads complete at a glance: Denied · waited 2s · "…".
|
|
3343
|
+
const feedbackHtml = (msg.decision === 'deny' && msg.feedback)
|
|
3344
|
+
? `<span class="permission-status-feedback" data-tooltip="${escapeHtml(msg.feedback)}">${escapeHtml(PC.deny_feedback_quote.replace('{feedback}', msg.feedback))}</span>`
|
|
3345
|
+
: '';
|
|
3346
|
+
statusHtml = `
|
|
3347
|
+
<div class="permission-status ${st.cls}">
|
|
3348
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">${st.icon}</svg>
|
|
3349
|
+
${st.label}
|
|
3350
|
+
${waitedHtml}
|
|
3351
|
+
${feedbackHtml}
|
|
3352
|
+
</div>`;
|
|
3353
|
+
} else {
|
|
3354
|
+
// "Always allow" rows — one per engine rule-suggestion on the ask.
|
|
3355
|
+
// Answering with a row allows the call AND has the engine persist
|
|
3356
|
+
// that rule (addRules / addDirectories / setMode), like the CLI's
|
|
3357
|
+
// "yes, don't ask again" options.
|
|
3358
|
+
const sugRows = (Array.isArray(msg.suggestions) ? msg.suggestions : [])
|
|
3359
|
+
.map((s, i) => {
|
|
3360
|
+
const label = this._permissionSuggestionLabel(s);
|
|
3361
|
+
if (!label) return '';
|
|
3362
|
+
return `<button class="permission-suggestion-btn" data-act="respond-permission" data-id="${escapeAttr(msg.id)}" data-decision="allow" data-i="${i}">
|
|
3363
|
+
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3364
|
+
<polyline points="20 6 9 17 4 12"/><line x1="12" y1="18" x2="20" y2="18"/>
|
|
3365
|
+
</svg>
|
|
3366
|
+
<span>${label}</span>
|
|
3367
|
+
</button>`;
|
|
3368
|
+
}).join('');
|
|
3369
|
+
statusHtml = `
|
|
3370
|
+
<input type="text" class="permission-feedback" id="perm-feedback-${msg.id}"
|
|
3371
|
+
placeholder="${escapeHtml(PC.feedback_placeholder)}">
|
|
3372
|
+
<div class="permission-actions">
|
|
3373
|
+
<button class="permission-allow-btn" data-act="respond-permission" data-id="${escapeAttr(msg.id)}" data-decision="allow">
|
|
3374
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3375
|
+
<polyline points="20 6 9 17 4 12"/>
|
|
3376
|
+
</svg>
|
|
3377
|
+
${PC.allow}
|
|
3378
|
+
</button>
|
|
3379
|
+
<button class="permission-deny-btn" data-act="respond-permission" data-id="${escapeAttr(msg.id)}" data-decision="deny">
|
|
3380
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3381
|
+
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
|
3382
|
+
</svg>
|
|
3383
|
+
${PC.deny}
|
|
3384
|
+
</button>
|
|
3385
|
+
<span class="permission-waiting">
|
|
3386
|
+
<span class="permission-elapsed" data-start="${startMs}">${escapeHtml(elapsed0)}</span>
|
|
3387
|
+
${PC.waiting}
|
|
3388
|
+
</span>
|
|
3389
|
+
</div>
|
|
3390
|
+
${sugRows ? `<div class="permission-suggestions">${sugRows}</div>` : ''}`;
|
|
3391
|
+
}
|
|
3392
|
+
|
|
3393
|
+
div.innerHTML = `
|
|
3394
|
+
<div class="message-header">
|
|
3395
|
+
<span class="message-role permission">
|
|
3396
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3397
|
+
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
|
|
3398
|
+
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
|
|
3399
|
+
</svg>
|
|
3400
|
+
${PC.title}
|
|
3401
|
+
</span>
|
|
3402
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
3403
|
+
</div>
|
|
3404
|
+
<div class="permission-body">
|
|
3405
|
+
<p class="permission-tool">${PC.wants_to_use.replace('{tool}', `<strong>${toolName}</strong>`)}</p>
|
|
3406
|
+
${descHtml}
|
|
3407
|
+
${inputHtml}
|
|
3408
|
+
${statusHtml}
|
|
3409
|
+
</div>
|
|
3410
|
+
`;
|
|
3411
|
+
|
|
3412
|
+
if (!msg.answered) this._startPermissionTicker();
|
|
3413
|
+
return div;
|
|
3414
|
+
}
|
|
3415
|
+
|
|
3416
|
+
/**
|
|
3417
|
+
* Run a 1s ticker that updates the elapsed-wait timer on every unanswered
|
|
3418
|
+
* permission card. Self-stops once no `.permission-elapsed` elements remain
|
|
3419
|
+
* (all cards answered/expired drop the timer on re-render). Idempotent.
|
|
3420
|
+
*/
|
|
3421
|
+
_startPermissionTicker() {
|
|
3422
|
+
if (this._permTicker) return;
|
|
3423
|
+
this._permTicker = setInterval(() => {
|
|
3424
|
+
const els = document.querySelectorAll('.permission-elapsed[data-start]');
|
|
3425
|
+
if (!els.length) {
|
|
3426
|
+
clearInterval(this._permTicker);
|
|
3427
|
+
this._permTicker = null;
|
|
3428
|
+
return;
|
|
3429
|
+
}
|
|
3430
|
+
const now = Date.now();
|
|
3431
|
+
els.forEach(el => {
|
|
3432
|
+
const start = parseInt(el.dataset.start, 10);
|
|
3433
|
+
if (start) el.textContent = this._formatDuration(Math.max(0, now - start)) || '0s';
|
|
3434
|
+
});
|
|
3435
|
+
}, 1000);
|
|
3436
|
+
}
|
|
3437
|
+
|
|
3438
|
+
/**
|
|
3439
|
+
* Human-friendly preview of a tool call's input for the permission card.
|
|
3440
|
+
* Mirrors the transcript's tool rendering instead of dumping raw JSON:
|
|
3441
|
+
* Bash/Shell → `$ command`
|
|
3442
|
+
* Write → file header + truncated content preview
|
|
3443
|
+
* Edit/MultiEdit → file header + old→new diff
|
|
3444
|
+
* Read/Grep/Glob/other → the tool-renderer one-liner or key/value table
|
|
3445
|
+
* @param {string} toolName
|
|
3446
|
+
* @param {Object} input
|
|
3447
|
+
* @returns {string} HTML
|
|
3448
|
+
*/
|
|
3449
|
+
_renderPermissionInput(toolName, input) {
|
|
3450
|
+
input = input || {};
|
|
3451
|
+
const PC = S.permission_card;
|
|
3452
|
+
const tr = this.ctx.toolRenderer;
|
|
3453
|
+
|
|
3454
|
+
// Bash / Shell — command headline
|
|
3455
|
+
if ((toolName === 'Bash' || toolName === 'Shell') && typeof input.command === 'string') {
|
|
3456
|
+
return `<pre class="permission-input"><code>$ ${escapeHtml(input.command)}</code></pre>`;
|
|
3457
|
+
}
|
|
3458
|
+
|
|
3459
|
+
// Write — file header + content preview
|
|
3460
|
+
if (toolName === 'Write' && input.file_path) {
|
|
3461
|
+
const filename = basename(input.file_path) || input.file_path;
|
|
3462
|
+
const content = typeof input.content === 'string' ? input.content : '';
|
|
3463
|
+
const nLines = content ? content.split('\n').length : 0;
|
|
3464
|
+
const tag = nLines
|
|
3465
|
+
? `<span class="permission-file-tag">${escapeHtml(PC.lines_count.replace('{n}', nLines))}</span>`
|
|
3466
|
+
: '';
|
|
3467
|
+
const preview = this._truncateForPreview(content, 40, 2000);
|
|
3468
|
+
const previewHtml = content
|
|
3469
|
+
? `<pre class="permission-input permission-file-preview"><code>${escapeHtml(preview)}</code></pre>`
|
|
3470
|
+
: '';
|
|
3471
|
+
return `<div class="permission-file-head">${tr.fileLink(input.file_path, filename, 'permission-file-name')}${tag}</div>${previewHtml}`;
|
|
3472
|
+
}
|
|
3473
|
+
|
|
3474
|
+
// Edit / MultiEdit — file header + old→new diff
|
|
3475
|
+
if ((toolName === 'Edit' || toolName === 'MultiEdit') && input.file_path) {
|
|
3476
|
+
const filename = basename(input.file_path) || input.file_path;
|
|
3477
|
+
const edits = (toolName === 'MultiEdit' && Array.isArray(input.edits))
|
|
3478
|
+
? input.edits
|
|
3479
|
+
: [{ old_string: input.old_string, new_string: input.new_string }];
|
|
3480
|
+
const tag = edits.length > 1
|
|
3481
|
+
? `<span class="permission-file-tag">${escapeHtml(PC.edits_count.replace('{n}', edits.length))}</span>`
|
|
3482
|
+
: '';
|
|
3483
|
+
const diffHtml = edits
|
|
3484
|
+
.map(e => this._renderPermissionDiff(e.old_string, e.new_string))
|
|
3485
|
+
.join('');
|
|
3486
|
+
return `<div class="permission-file-head">${tr.fileLink(input.file_path, filename, 'permission-file-name')}${tag}</div>`
|
|
3487
|
+
+ `<div class="permission-input permission-diff">${diffHtml}</div>`;
|
|
3488
|
+
}
|
|
3489
|
+
|
|
3490
|
+
// Read / Grep / Glob and everything else — one-liner or key/value table
|
|
3491
|
+
const body = tr.formatToolInput(toolName, input);
|
|
3492
|
+
return body ? `<div class="permission-input">${body}</div>` : '';
|
|
3493
|
+
}
|
|
3494
|
+
|
|
3495
|
+
/**
|
|
3496
|
+
* Truncate text to at most maxLines lines and maxChars characters,
|
|
3497
|
+
* appending an ellipsis line when clipped. Used for Write previews.
|
|
3498
|
+
*/
|
|
3499
|
+
_truncateForPreview(text, maxLines, maxChars) {
|
|
3500
|
+
if (!text) return '';
|
|
3501
|
+
let out = text;
|
|
3502
|
+
let clipped = false;
|
|
3503
|
+
const lines = out.split('\n');
|
|
3504
|
+
if (lines.length > maxLines) { out = lines.slice(0, maxLines).join('\n'); clipped = true; }
|
|
3505
|
+
if (out.length > maxChars) { out = out.slice(0, maxChars); clipped = true; }
|
|
3506
|
+
return clipped ? out + '\n…' : out;
|
|
3507
|
+
}
|
|
3508
|
+
|
|
3509
|
+
/**
|
|
3510
|
+
* Render one Edit hunk as a removed/added diff. Lines are capped so a huge
|
|
3511
|
+
* replacement doesn't blow out the card; the container scrolls.
|
|
3512
|
+
*/
|
|
3513
|
+
_renderPermissionDiff(oldStr, newStr) {
|
|
3514
|
+
const CAP = 30;
|
|
3515
|
+
const rows = [];
|
|
3516
|
+
const push = (arr, cls) => {
|
|
3517
|
+
arr.slice(0, CAP).forEach(l => {
|
|
3518
|
+
rows.push(`<div class="permission-diff-line ${cls}">${escapeHtml(l) || ' '}</div>`);
|
|
3519
|
+
});
|
|
3520
|
+
if (arr.length > CAP) rows.push(`<div class="permission-diff-line ${cls}">…</div>`);
|
|
3521
|
+
};
|
|
3522
|
+
if (typeof oldStr === 'string' && oldStr.length) push(oldStr.split('\n'), 'removed');
|
|
3523
|
+
if (typeof newStr === 'string' && newStr.length) push(newStr.split('\n'), 'added');
|
|
3524
|
+
return `<div class="permission-diff-hunk">${rows.join('')}</div>`;
|
|
3525
|
+
}
|
|
3526
|
+
|
|
3527
|
+
/**
|
|
3528
|
+
* Human label for one engine permission-rule suggestion. Unknown types
|
|
3529
|
+
* return null and are not rendered (we never offer what we can't explain).
|
|
3530
|
+
*/
|
|
3531
|
+
_permissionSuggestionLabel(s) {
|
|
3532
|
+
const PC = S.permission_card;
|
|
3533
|
+
const scopeMap = {
|
|
3534
|
+
session: PC.scope_session,
|
|
3535
|
+
localSettings: PC.scope_local_settings,
|
|
3536
|
+
projectSettings: PC.scope_project_settings,
|
|
3537
|
+
userSettings: PC.scope_user_settings,
|
|
3538
|
+
};
|
|
3539
|
+
const scope = escapeHtml(scopeMap[s.destination] || '');
|
|
3540
|
+
if (s.type === 'addRules' && Array.isArray(s.rules) && s.rules.length) {
|
|
3541
|
+
const detail = s.rules
|
|
3542
|
+
.map(r => r.rule_content ? `${r.tool_name}(${r.rule_content})` : r.tool_name)
|
|
3543
|
+
.join(', ');
|
|
3544
|
+
return PC.suggestion_add_rules
|
|
3545
|
+
.replace('{detail}', `<code>${escapeHtml(detail)}</code>`)
|
|
3546
|
+
.replace('{scope}', scope);
|
|
3547
|
+
}
|
|
3548
|
+
if (s.type === 'addDirectories' && Array.isArray(s.directories) && s.directories.length) {
|
|
3549
|
+
return PC.suggestion_add_directories
|
|
3550
|
+
.replace('{detail}', `<code>${escapeHtml(s.directories.join(', '))}</code>`)
|
|
3551
|
+
.replace('{scope}', scope);
|
|
3552
|
+
}
|
|
3553
|
+
if (s.type === 'setMode' && s.mode) {
|
|
3554
|
+
return PC.suggestion_set_mode
|
|
3555
|
+
.replace('{detail}', `<strong>${escapeHtml(String(s.mode))}</strong>`)
|
|
3556
|
+
.replace('{scope}', scope);
|
|
3557
|
+
}
|
|
3558
|
+
return null;
|
|
3559
|
+
}
|
|
3560
|
+
|
|
3561
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3562
|
+
// ASKUSERQUESTION FORM RENDERING
|
|
3563
|
+
// ═══════════════════════════════════════════════════════════════
|
|
3564
|
+
|
|
3565
|
+
/**
|
|
3566
|
+
* Render an interactive question form for AskUserQuestion tool
|
|
3567
|
+
* Supports both single questions and grouped wizard-style multiple questions
|
|
3568
|
+
* @param {Object} msg - Question message with questions array or entries array
|
|
3569
|
+
* @returns {HTMLElement} The form container element
|
|
3570
|
+
*/
|
|
3571
|
+
_renderQuestionForm(msg) {
|
|
3572
|
+
// `_editing` is a transient flag set when the user re-opens an already
|
|
3573
|
+
// answered card to change and resend their answer — treat it as unanswered
|
|
3574
|
+
// for rendering (enabled inputs + submit, active styling) while keeping
|
|
3575
|
+
// msg.answered true underneath.
|
|
3576
|
+
const isEditing = msg.answered && msg._editing;
|
|
3577
|
+
const isAnswered = msg.answered && !msg._editing;
|
|
3578
|
+
|
|
3579
|
+
const div = document.createElement('div');
|
|
3580
|
+
div.className = `message question${isAnswered ? ' answered' : ''}${isEditing ? ' editing' : ''}`;
|
|
3581
|
+
div.id = `msg-${msg.id}`;
|
|
3582
|
+
|
|
3583
|
+
// Check if this is a grouped question (wizard mode) or single question
|
|
3584
|
+
const entries = msg.entries || [{
|
|
3585
|
+
toolId: msg.toolId,
|
|
3586
|
+
questions: msg.questions || [],
|
|
3587
|
+
answers: msg.answers || {}
|
|
3588
|
+
}];
|
|
3589
|
+
|
|
3590
|
+
const isWizard = entries.length > 1;
|
|
3591
|
+
const activeTab = msg.activeTab || 0;
|
|
3592
|
+
|
|
3593
|
+
// Build wizard tabs (only if multiple entries)
|
|
3594
|
+
let tabsHtml = '';
|
|
3595
|
+
if (isWizard) {
|
|
3596
|
+
tabsHtml = `
|
|
3597
|
+
<div class="question-wizard-tabs">
|
|
3598
|
+
${entries.map((entry, idx) => {
|
|
3599
|
+
const hasAnswer = Object.keys(entry.answers || {}).length > 0;
|
|
3600
|
+
return `
|
|
3601
|
+
<button class="wizard-tab ${idx === activeTab ? 'active' : ''} ${hasAnswer ? 'answered' : ''}"
|
|
3602
|
+
data-tab="${idx}">
|
|
3603
|
+
<span class="wizard-tab-num">${idx + 1}</span>
|
|
3604
|
+
${hasAnswer ? '<svg class="wizard-tab-check" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>' : ''}
|
|
3605
|
+
</button>
|
|
3606
|
+
`;
|
|
3607
|
+
}).join('')}
|
|
3608
|
+
</div>
|
|
3609
|
+
`;
|
|
3610
|
+
}
|
|
3611
|
+
|
|
3612
|
+
// Build content for each entry (only show active tab content)
|
|
3613
|
+
let entriesHtml = entries.map((entry, entryIdx) => {
|
|
3614
|
+
// Defensive: some turns (and sessions persisted before the parse
|
|
3615
|
+
// fix) stored `questions` as a JSON string instead of an array,
|
|
3616
|
+
// which rendered an empty "Claude is asking" card. Recover here.
|
|
3617
|
+
let questions = entry.questions;
|
|
3618
|
+
if (!Array.isArray(questions)) {
|
|
3619
|
+
if (typeof questions === 'string' && questions.trim()) {
|
|
3620
|
+
try { const p = JSON.parse(questions); questions = Array.isArray(p) ? p : []; }
|
|
3621
|
+
catch { questions = []; }
|
|
3622
|
+
} else {
|
|
3623
|
+
questions = [];
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
const answers = entry.answers || {};
|
|
3627
|
+
const isActive = entryIdx === activeTab;
|
|
3628
|
+
|
|
3629
|
+
let questionsHtml = questions.map((q, qIdx) => {
|
|
3630
|
+
const header = q.header || `Q${qIdx + 1}`;
|
|
3631
|
+
const options = q.options || [];
|
|
3632
|
+
const isMulti = q.multiSelect === true;
|
|
3633
|
+
const selectedValue = answers[header] || '';
|
|
3634
|
+
|
|
3635
|
+
return `
|
|
3636
|
+
<div class="question-item" data-header="${escapeHtml(header)}" data-multi="${isMulti}" data-entry="${entryIdx}">
|
|
3637
|
+
<div class="question-header">
|
|
3638
|
+
<span class="question-badge">${escapeHtml(header)}</span>
|
|
3639
|
+
</div>
|
|
3640
|
+
<div class="question-text">${escapeHtml(q.question)}</div>
|
|
3641
|
+
<div class="question-options">
|
|
3642
|
+
${options.map(opt => {
|
|
3643
|
+
const isSelected = isMulti
|
|
3644
|
+
? (selectedValue || '').includes(opt.label)
|
|
3645
|
+
: selectedValue === opt.label;
|
|
3646
|
+
return `
|
|
3647
|
+
<button class="question-option${isSelected ? ' selected' : ''}"
|
|
3648
|
+
data-value="${escapeHtml(opt.label)}"
|
|
3649
|
+
${isAnswered ? 'disabled' : ''}>
|
|
3650
|
+
<span class="option-label">${escapeHtml(opt.label)}</span>
|
|
3651
|
+
${opt.description ? `<span class="option-desc">${escapeHtml(opt.description)}</span>` : ''}
|
|
3652
|
+
</button>
|
|
3653
|
+
`;
|
|
3654
|
+
}).join('')}
|
|
3655
|
+
<button class="question-option question-option-other${selectedValue && !options.some(o => o.label === selectedValue) ? ' selected' : ''}"
|
|
3656
|
+
data-value="__other__"
|
|
3657
|
+
${isAnswered ? 'disabled' : ''}>
|
|
3658
|
+
<span class="option-label">Other...</span>
|
|
3659
|
+
<span class="option-desc">Provide custom answer</span>
|
|
3660
|
+
</button>
|
|
3661
|
+
</div>
|
|
3662
|
+
<input type="text" class="question-other-input" placeholder="Type your answer..."
|
|
3663
|
+
style="display: ${selectedValue && !options.some(o => o.label === selectedValue) && !isMulti ? 'block' : 'none'}"
|
|
3664
|
+
value="${escapeHtml(selectedValue && !options.some(o => o.label === selectedValue) ? selectedValue : '')}"
|
|
3665
|
+
${isAnswered ? 'disabled' : ''}>
|
|
3666
|
+
</div>
|
|
3667
|
+
`;
|
|
3668
|
+
}).join('');
|
|
3669
|
+
|
|
3670
|
+
return `
|
|
3671
|
+
<div class="question-entry ${isActive ? 'active' : ''}" data-entry-idx="${entryIdx}" data-tool-id="${entry.toolId}">
|
|
3672
|
+
${questionsHtml}
|
|
3673
|
+
</div>
|
|
3674
|
+
`;
|
|
3675
|
+
}).join('');
|
|
3676
|
+
|
|
3677
|
+
// Navigation buttons for wizard
|
|
3678
|
+
let navHtml = '';
|
|
3679
|
+
if (isWizard && !isAnswered) {
|
|
3680
|
+
const canGoBack = activeTab > 0;
|
|
3681
|
+
const canGoNext = activeTab < entries.length - 1;
|
|
3682
|
+
const isLast = activeTab === entries.length - 1;
|
|
3683
|
+
|
|
3684
|
+
navHtml = `
|
|
3685
|
+
<div class="question-wizard-nav">
|
|
3686
|
+
<button class="wizard-nav-btn prev" ${canGoBack ? '' : 'disabled'} data-action="prev">
|
|
3687
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3688
|
+
<path d="M15 18l-6-6 6-6"/>
|
|
3689
|
+
</svg>
|
|
3690
|
+
Previous
|
|
3691
|
+
</button>
|
|
3692
|
+
<span class="wizard-progress">${activeTab + 1} of ${entries.length}</span>
|
|
3693
|
+
${isLast ? '' : `
|
|
3694
|
+
<button class="wizard-nav-btn next" data-action="next">
|
|
3695
|
+
Next
|
|
3696
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3697
|
+
<path d="M9 18l6-6-6-6"/>
|
|
3698
|
+
</svg>
|
|
3699
|
+
</button>
|
|
3700
|
+
`}
|
|
3701
|
+
</div>
|
|
3702
|
+
`;
|
|
3703
|
+
}
|
|
3704
|
+
|
|
3705
|
+
// Status and submit button
|
|
3706
|
+
let statusHtml;
|
|
3707
|
+
if (isAnswered) {
|
|
3708
|
+
if (msg.ignored) {
|
|
3709
|
+
statusHtml = `<div class="question-status ignored">
|
|
3710
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3711
|
+
<circle cx="12" cy="12" r="10"/>
|
|
3712
|
+
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/>
|
|
3713
|
+
</svg>
|
|
3714
|
+
${S.question_form.status_ignored}
|
|
3715
|
+
</div>`;
|
|
3716
|
+
} else if (msg.skipped) {
|
|
3717
|
+
statusHtml = `<div class="question-status skipped">
|
|
3718
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3719
|
+
<polygon points="5 4 15 12 5 20 5 4"/>
|
|
3720
|
+
<line x1="19" y1="5" x2="19" y2="19"/>
|
|
3721
|
+
</svg>
|
|
3722
|
+
${S.question_form.status_skipped}
|
|
3723
|
+
</div>`;
|
|
3724
|
+
} else {
|
|
3725
|
+
statusHtml = `<button class="question-edit" data-act="edit-question-answer" data-id="${escapeAttr(msg.id)}" data-tooltip="${S.question_form.edit_hint}">
|
|
3726
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3727
|
+
<path d="M12 20h9"/>
|
|
3728
|
+
<path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>
|
|
3729
|
+
</svg>
|
|
3730
|
+
${S.question_form.edit_answer}
|
|
3731
|
+
</button>
|
|
3732
|
+
<div class="question-status answered">
|
|
3733
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3734
|
+
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
|
|
3735
|
+
<polyline points="22 4 12 14.01 9 11.01"/>
|
|
3736
|
+
</svg>
|
|
3737
|
+
${S.question_form.status_answered}
|
|
3738
|
+
</div>`;
|
|
3739
|
+
}
|
|
3740
|
+
} else {
|
|
3741
|
+
// When editing an already-answered card the left button cancels the
|
|
3742
|
+
// edit (restores the answered view) instead of ignoring the question.
|
|
3743
|
+
const leftBtn = isEditing
|
|
3744
|
+
? `<button class="question-ignore" data-act="cancel-edit-question" data-id="${escapeAttr(msg.id)}" data-tooltip="${S.question_form.cancel_edit_hint}">
|
|
3745
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3746
|
+
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
3747
|
+
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
3748
|
+
</svg>
|
|
3749
|
+
${S.question_form.cancel_edit}
|
|
3750
|
+
</button>`
|
|
3751
|
+
: `<button class="question-ignore" data-act="ignore-question" data-id="${escapeAttr(msg.id)}" data-tooltip="${S.question_form.ignore_hint}">
|
|
3752
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3753
|
+
<circle cx="12" cy="12" r="10"/>
|
|
3754
|
+
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/>
|
|
3755
|
+
</svg>
|
|
3756
|
+
Ignore
|
|
3757
|
+
</button>`;
|
|
3758
|
+
statusHtml = `${leftBtn}
|
|
3759
|
+
<button class="question-submit" data-act="submit-question-answers" data-id="${escapeAttr(msg.id)}">
|
|
3760
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3761
|
+
<line x1="22" y1="2" x2="11" y2="13"/>
|
|
3762
|
+
<polygon points="22 2 15 22 11 13 2 9 22 2"/>
|
|
3763
|
+
</svg>
|
|
3764
|
+
${isEditing ? S.question_form.resend_answers : `Submit ${isWizard ? 'All ' : ''}Answers`}
|
|
3765
|
+
</button>`;
|
|
3766
|
+
}
|
|
3767
|
+
|
|
3768
|
+
// Free-text comment box (shared across the whole card, independent of
|
|
3769
|
+
// which options are picked). Editable while unanswered/editing; shown
|
|
3770
|
+
// read-only afterwards only if the user actually left a comment.
|
|
3771
|
+
const commentValue = msg.comment || '';
|
|
3772
|
+
let commentHtml = '';
|
|
3773
|
+
if (!isAnswered) {
|
|
3774
|
+
commentHtml = `
|
|
3775
|
+
<div class="question-comment-wrap">
|
|
3776
|
+
<label class="question-comment-label" for="qc-${msg.id}">${S.question_form.comment_label}</label>
|
|
3777
|
+
<textarea id="qc-${msg.id}" class="question-comment" rows="2"
|
|
3778
|
+
placeholder="${escapeHtml(S.question_form.comment_placeholder)}">${escapeHtml(commentValue)}</textarea>
|
|
3779
|
+
</div>
|
|
3780
|
+
`;
|
|
3781
|
+
} else if (commentValue) {
|
|
3782
|
+
commentHtml = `
|
|
3783
|
+
<div class="question-comment-wrap">
|
|
3784
|
+
<label class="question-comment-label">${S.question_form.comment_label}</label>
|
|
3785
|
+
<textarea class="question-comment" rows="2" disabled>${escapeHtml(commentValue)}</textarea>
|
|
3786
|
+
</div>
|
|
3787
|
+
`;
|
|
3788
|
+
}
|
|
3789
|
+
|
|
3790
|
+
// Footer note + inline toggle reflecting the global "stop on questions"
|
|
3791
|
+
// setting. Filled and revealed by _setupQuestionStopNote once the
|
|
3792
|
+
// current setting is known: on → Claude pauses for you here; off →
|
|
3793
|
+
// Claude answered on its own, with a one-click affordance to enable.
|
|
3794
|
+
const stopNoteHtml = `
|
|
3795
|
+
<div class="question-stop-note" style="display:none">
|
|
3796
|
+
<svg class="question-stop-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3797
|
+
<circle cx="12" cy="12" r="10"/>
|
|
3798
|
+
<line x1="12" y1="16" x2="12" y2="12"/>
|
|
3799
|
+
<line x1="12" y1="8" x2="12.01" y2="8"/>
|
|
3800
|
+
</svg>
|
|
3801
|
+
<span class="question-stop-text"></span>
|
|
3802
|
+
<label class="question-stop-toggle" data-tooltip="${S.question_form.stop_toggle_hint}">
|
|
3803
|
+
<input type="checkbox" class="question-stop-checkbox">
|
|
3804
|
+
<span>${S.question_form.stop_toggle_label}</span>
|
|
3805
|
+
</label>
|
|
3806
|
+
</div>
|
|
3807
|
+
`;
|
|
3808
|
+
|
|
3809
|
+
div.innerHTML = `
|
|
3810
|
+
<div class="message-header">
|
|
3811
|
+
<span class="message-role question">
|
|
3812
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
3813
|
+
<circle cx="12" cy="12" r="10"/>
|
|
3814
|
+
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
|
|
3815
|
+
<line x1="12" y1="17" x2="12.01" y2="17"/>
|
|
3816
|
+
</svg>
|
|
3817
|
+
Claude is asking${isWizard ? ` (${entries.length} questions)` : ''}
|
|
3818
|
+
</span>
|
|
3819
|
+
<span class="message-time">${formatTime(msg.timestamp)}</span>
|
|
3820
|
+
</div>
|
|
3821
|
+
${tabsHtml}
|
|
3822
|
+
<div class="question-form ${isWizard ? 'wizard-mode' : ''}" data-msg-id="${msg.id}">
|
|
3823
|
+
${entriesHtml}
|
|
3824
|
+
${navHtml}
|
|
3825
|
+
${commentHtml}
|
|
3826
|
+
<div class="question-actions">
|
|
3827
|
+
${statusHtml}
|
|
3828
|
+
</div>
|
|
3829
|
+
</div>
|
|
3830
|
+
${stopNoteHtml}
|
|
3831
|
+
`;
|
|
3832
|
+
|
|
3833
|
+
// Attach event listeners for option selection and wizard navigation
|
|
3834
|
+
if (!isAnswered) {
|
|
3835
|
+
this._attachQuestionFormListeners(div, msg);
|
|
3836
|
+
}
|
|
3837
|
+
this._setupQuestionStopNote(div);
|
|
3838
|
+
|
|
3839
|
+
return div;
|
|
3840
|
+
}
|
|
3841
|
+
|
|
3842
|
+
/**
|
|
3843
|
+
* Fill and wire the question card's footer note/toggle from the global
|
|
3844
|
+
* "stop on questions" setting. On → Claude pauses for you on questions
|
|
3845
|
+
* like this; off → Claude answered on its own, and the toggle offers a
|
|
3846
|
+
* one-click way to be asked instead. The inline checkbox flips the setting
|
|
3847
|
+
* live (shared with the System-tab control).
|
|
3848
|
+
* @param {HTMLElement} container - The rendered question card
|
|
3849
|
+
*/
|
|
3850
|
+
_setupQuestionStopNote(container) {
|
|
3851
|
+
const note = container.querySelector('.question-stop-note');
|
|
3852
|
+
const cb = container.querySelector('.question-stop-checkbox');
|
|
3853
|
+
const text = container.querySelector('.question-stop-text');
|
|
3854
|
+
if (!note || !cb || !text) return;
|
|
3855
|
+
|
|
3856
|
+
const apply = (on) => {
|
|
3857
|
+
note.style.display = '';
|
|
3858
|
+
cb.checked = on;
|
|
3859
|
+
text.textContent = on
|
|
3860
|
+
? S.question_form.stop_on_text
|
|
3861
|
+
: S.question_form.auto_deny_text;
|
|
3862
|
+
note.dataset.mode = on ? 'on' : 'off';
|
|
3863
|
+
};
|
|
3864
|
+
|
|
3865
|
+
// Reflect the current global setting (one GET per question card).
|
|
3866
|
+
fetch('/api/app/sigint-on-ask')
|
|
3867
|
+
.then(r => r.ok ? r.json() : null)
|
|
3868
|
+
.then(d => { if (d) apply(!!d.sigint_on_ask); })
|
|
3869
|
+
.catch(() => {});
|
|
3870
|
+
|
|
3871
|
+
cb.addEventListener('change', async () => {
|
|
3872
|
+
const value = cb.checked;
|
|
3873
|
+
try {
|
|
3874
|
+
const resp = await fetch('/api/app/sigint-on-ask', {
|
|
3875
|
+
method: 'PUT',
|
|
3876
|
+
headers: { 'Content-Type': 'application/json' },
|
|
3877
|
+
body: JSON.stringify({ sigint_on_ask: value }),
|
|
3878
|
+
});
|
|
3879
|
+
if (resp.ok) {
|
|
3880
|
+
const data = await resp.json();
|
|
3881
|
+
apply(!!data.sigint_on_ask);
|
|
3882
|
+
showToast(data.sigint_on_ask
|
|
3883
|
+
? S.question_form.stop_toggle_on
|
|
3884
|
+
: S.question_form.stop_toggle_off);
|
|
3885
|
+
} else {
|
|
3886
|
+
cb.checked = !value;
|
|
3887
|
+
}
|
|
3888
|
+
} catch (e) {
|
|
3889
|
+
console.error('Failed to toggle sigint_on_ask:', e);
|
|
3890
|
+
cb.checked = !value;
|
|
3891
|
+
}
|
|
3892
|
+
});
|
|
3893
|
+
}
|
|
3894
|
+
|
|
3895
|
+
/**
|
|
3896
|
+
* Attach event listeners to question form options and wizard navigation
|
|
3897
|
+
* @param {HTMLElement} container - The form container
|
|
3898
|
+
* @param {Object} msg - The question message
|
|
3899
|
+
*/
|
|
3900
|
+
_attachQuestionFormListeners(container, msg) {
|
|
3901
|
+
const form = container.querySelector('.question-form');
|
|
3902
|
+
if (!form) return;
|
|
3903
|
+
|
|
3904
|
+
const entries = msg.entries || [{
|
|
3905
|
+
toolId: msg.toolId,
|
|
3906
|
+
questions: msg.questions || [],
|
|
3907
|
+
answers: msg.answers || {}
|
|
3908
|
+
}];
|
|
3909
|
+
const isWizard = entries.length > 1;
|
|
3910
|
+
const totalQuestions = entries.reduce(
|
|
3911
|
+
(n, e) => n + (Array.isArray(e.questions) ? e.questions.length : 0), 0
|
|
3912
|
+
);
|
|
3913
|
+
|
|
3914
|
+
// Option selection
|
|
3915
|
+
form.querySelectorAll('.question-option').forEach(btn => {
|
|
3916
|
+
btn.addEventListener('click', (e) => {
|
|
3917
|
+
e.preventDefault();
|
|
3918
|
+
const questionItem = btn.closest('.question-item');
|
|
3919
|
+
const isMulti = questionItem.dataset.multi === 'true';
|
|
3920
|
+
const value = btn.dataset.value;
|
|
3921
|
+
const isOther = value === '__other__';
|
|
3922
|
+
const entryIdx = parseInt(questionItem.dataset.entry || '0', 10);
|
|
3923
|
+
const header = questionItem.dataset.header;
|
|
3924
|
+
|
|
3925
|
+
if (isMulti) {
|
|
3926
|
+
// Toggle selection for multiSelect
|
|
3927
|
+
btn.classList.toggle('selected');
|
|
3928
|
+
} else {
|
|
3929
|
+
// Single select - deselect others
|
|
3930
|
+
questionItem.querySelectorAll('.question-option').forEach(b => {
|
|
3931
|
+
b.classList.remove('selected');
|
|
3932
|
+
});
|
|
3933
|
+
btn.classList.add('selected');
|
|
3934
|
+
}
|
|
3935
|
+
|
|
3936
|
+
// Show/hide "Other" input
|
|
3937
|
+
const otherInput = questionItem.querySelector('.question-other-input');
|
|
3938
|
+
if (otherInput) {
|
|
3939
|
+
if (isOther && btn.classList.contains('selected')) {
|
|
3940
|
+
otherInput.style.display = 'block';
|
|
3941
|
+
otherInput.focus();
|
|
3942
|
+
} else if (!isMulti) {
|
|
3943
|
+
otherInput.style.display = 'none';
|
|
3944
|
+
}
|
|
3945
|
+
}
|
|
3946
|
+
|
|
3947
|
+
// Update answer in msg.entries for persistence
|
|
3948
|
+
if (entries[entryIdx]) {
|
|
3949
|
+
if (!entries[entryIdx].answers) entries[entryIdx].answers = {};
|
|
3950
|
+
const selectedBtns = questionItem.querySelectorAll('.question-option.selected');
|
|
3951
|
+
if (isMulti) {
|
|
3952
|
+
entries[entryIdx].answers[header] = Array.from(selectedBtns)
|
|
3953
|
+
.map(b => b.dataset.value)
|
|
3954
|
+
.filter(v => v !== '__other__')
|
|
3955
|
+
.join(', ');
|
|
3956
|
+
} else if (!isOther) {
|
|
3957
|
+
entries[entryIdx].answers[header] = value;
|
|
3958
|
+
}
|
|
3959
|
+
|
|
3960
|
+
// Update wizard tab indicator if answered
|
|
3961
|
+
if (isWizard) {
|
|
3962
|
+
this._updateWizardTabState(container, msg);
|
|
3963
|
+
}
|
|
3964
|
+
}
|
|
3965
|
+
});
|
|
3966
|
+
});
|
|
3967
|
+
|
|
3968
|
+
// "Other" input changes — persist the typed value as the answer.
|
|
3969
|
+
form.querySelectorAll('.question-other-input').forEach(input => {
|
|
3970
|
+
const questionItem = input.closest('.question-item');
|
|
3971
|
+
const entryIdx = parseInt(questionItem?.dataset.entry || '0', 10);
|
|
3972
|
+
const header = questionItem?.dataset.header;
|
|
3973
|
+
|
|
3974
|
+
input.addEventListener('input', () => {
|
|
3975
|
+
if (entries[entryIdx] && header) {
|
|
3976
|
+
if (!entries[entryIdx].answers) entries[entryIdx].answers = {};
|
|
3977
|
+
entries[entryIdx].answers[header] = input.value;
|
|
3978
|
+
}
|
|
3979
|
+
});
|
|
3980
|
+
});
|
|
3981
|
+
|
|
3982
|
+
// Free-text comment box — persist typed value onto the message so it
|
|
3983
|
+
// survives re-render (wizard tab switches, edit re-open). Swallow keydown
|
|
3984
|
+
// so the form's question-navigation handler doesn't hijack Enter/Tab
|
|
3985
|
+
// while the user is typing a multi-line comment.
|
|
3986
|
+
const commentEl = form.querySelector('.question-comment');
|
|
3987
|
+
if (commentEl && !commentEl.disabled) {
|
|
3988
|
+
commentEl.addEventListener('input', () => { msg.comment = commentEl.value; });
|
|
3989
|
+
commentEl.addEventListener('keydown', (e) => { e.stopPropagation(); });
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3992
|
+
// Keyboard navigation: Enter / Tab move forward through the questions,
|
|
3993
|
+
// Shift+Tab moves back, and the final forward step lands on the Submit
|
|
3994
|
+
// button so sending is always a deliberate second keystroke (never a
|
|
3995
|
+
// stray Enter on the first question). Arrow keys pick between options
|
|
3996
|
+
// within a question. See _handleQuestionFormKey for the full model.
|
|
3997
|
+
form.addEventListener('keydown', (e) => {
|
|
3998
|
+
this._handleQuestionFormKey(e, { container, form, msg, entries, isWizard, totalQuestions });
|
|
3999
|
+
});
|
|
4000
|
+
|
|
4001
|
+
// Wizard tab clicks
|
|
4002
|
+
container.querySelectorAll('.wizard-tab').forEach(tab => {
|
|
4003
|
+
tab.addEventListener('click', () => {
|
|
4004
|
+
const tabIdx = parseInt(tab.dataset.tab, 10);
|
|
4005
|
+
this._switchWizardTab(container, msg, tabIdx);
|
|
4006
|
+
});
|
|
4007
|
+
});
|
|
4008
|
+
|
|
4009
|
+
// Wizard navigation buttons
|
|
4010
|
+
container.querySelectorAll('.wizard-nav-btn').forEach(btn => {
|
|
4011
|
+
btn.addEventListener('click', () => {
|
|
4012
|
+
const action = btn.dataset.action;
|
|
4013
|
+
const newTab = action === 'prev' ? msg.activeTab - 1 : msg.activeTab + 1;
|
|
4014
|
+
this._switchWizardTab(container, msg, newTab);
|
|
4015
|
+
});
|
|
4016
|
+
});
|
|
4017
|
+
}
|
|
4018
|
+
|
|
4019
|
+
/**
|
|
4020
|
+
* Keyboard model for the question form.
|
|
4021
|
+
*
|
|
4022
|
+
* Each question is a single "stop". Enter and plain Tab advance to the next
|
|
4023
|
+
* stop; Shift+Tab goes back. Landing on a question focuses its custom-answer
|
|
4024
|
+
* input (if visible) otherwise its selected/first option. Moving forward off
|
|
4025
|
+
* the last question focuses the Submit button — in a wizard it first walks to
|
|
4026
|
+
* the next tab's questions — so submitting is always one extra, deliberate
|
|
4027
|
+
* keystroke. Up/Down (and Left/Right) move focus between the options of the
|
|
4028
|
+
* question the focus is currently in; Space selects the focused option.
|
|
4029
|
+
* Enter on an option selects it and then advances (jumps to the next
|
|
4030
|
+
* question). On the Submit button Enter still submits natively.
|
|
4031
|
+
*
|
|
4032
|
+
* "Other..." is the exception: focus landing on it (arrow key or Tab stop)
|
|
4033
|
+
* selects it and jumps into the revealed custom-answer input so typing can
|
|
4034
|
+
* start immediately — see _focusQuestionOption. Up gets back out of that
|
|
4035
|
+
* input onto the option list.
|
|
4036
|
+
* @param {KeyboardEvent} e
|
|
4037
|
+
* @param {Object} refs - { container, form, msg, entries, isWizard, totalQuestions }
|
|
4038
|
+
*/
|
|
4039
|
+
_handleQuestionFormKey(e, { container, form, msg, entries, isWizard, totalQuestions }) {
|
|
4040
|
+
const target = e.target;
|
|
4041
|
+
const submit = form.querySelector('.question-submit');
|
|
4042
|
+
const isOption = target.classList?.contains('question-option');
|
|
4043
|
+
const inTextInput = target.classList?.contains('question-other-input');
|
|
4044
|
+
|
|
4045
|
+
// Arrow keys move between the options of the focused question.
|
|
4046
|
+
if (isOption && ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
|
|
4047
|
+
const opts = Array.from(target.closest('.question-item').querySelectorAll('.question-option'));
|
|
4048
|
+
const cur = opts.indexOf(target);
|
|
4049
|
+
const fwd = e.key === 'ArrowDown' || e.key === 'ArrowRight';
|
|
4050
|
+
const next = opts[cur + (fwd ? 1 : -1)];
|
|
4051
|
+
if (next) { e.preventDefault(); this._focusQuestionOption(next); return; }
|
|
4052
|
+
// Down off "Other..." drops back into its revealed input, which sits
|
|
4053
|
+
// below the option list — the mirror of the Up escape below.
|
|
4054
|
+
if (fwd && target.dataset.value === '__other__') {
|
|
4055
|
+
const input = target.closest('.question-item').querySelector('.question-other-input');
|
|
4056
|
+
if (input && input.offsetParent !== null) { e.preventDefault(); input.focus(); }
|
|
4057
|
+
}
|
|
4058
|
+
return;
|
|
4059
|
+
}
|
|
4060
|
+
|
|
4061
|
+
// Up out of the custom-answer input goes back to its option list (the
|
|
4062
|
+
// input sits directly below "Other...", so Up lands on that button).
|
|
4063
|
+
// Left/Right stay with the caret. Without this the revealed input is a
|
|
4064
|
+
// dead end for arrow-key users.
|
|
4065
|
+
if (inTextInput && e.key === 'ArrowUp') {
|
|
4066
|
+
const opts = Array.from(target.closest('.question-item').querySelectorAll('.question-option'));
|
|
4067
|
+
const other = opts[opts.length - 1];
|
|
4068
|
+
if (other) { e.preventDefault(); other.focus(); }
|
|
4069
|
+
return;
|
|
4070
|
+
}
|
|
4071
|
+
|
|
4072
|
+
if (e.key !== 'Enter' && e.key !== 'Tab') return;
|
|
4073
|
+
|
|
4074
|
+
// The active entry's questions are the navigable stops.
|
|
4075
|
+
const activeEntry = form.querySelector('.question-entry.active') || form;
|
|
4076
|
+
const stops = Array.from(activeEntry.querySelectorAll('.question-item'));
|
|
4077
|
+
|
|
4078
|
+
// The control we focus when landing on a question.
|
|
4079
|
+
const stopTarget = (qi) => {
|
|
4080
|
+
const other = qi.querySelector('.question-other-input');
|
|
4081
|
+
if (other && other.offsetParent !== null) return other;
|
|
4082
|
+
return qi.querySelector('.question-option.selected')
|
|
4083
|
+
|| qi.querySelector('.question-option');
|
|
4084
|
+
};
|
|
4085
|
+
const focusStop = (el) => {
|
|
4086
|
+
if (!el) return;
|
|
4087
|
+
if (el.classList?.contains('question-option')) { this._focusQuestionOption(el); return; }
|
|
4088
|
+
el.focus();
|
|
4089
|
+
if (el.tagName === 'INPUT' && typeof el.select === 'function') el.select();
|
|
4090
|
+
el.scrollIntoView({ block: 'nearest' });
|
|
4091
|
+
};
|
|
4092
|
+
|
|
4093
|
+
// Move focus to the next question, else the next wizard tab's first
|
|
4094
|
+
// question, else the Submit button (so the final step prompts to submit).
|
|
4095
|
+
const currentItem = target.closest?.('.question-item');
|
|
4096
|
+
const goForward = () => {
|
|
4097
|
+
const idx = currentItem ? stops.indexOf(currentItem) : -1;
|
|
4098
|
+
if (idx > -1 && idx < stops.length - 1) {
|
|
4099
|
+
focusStop(stopTarget(stops[idx + 1]));
|
|
4100
|
+
} else if (isWizard && msg.activeTab < entries.length - 1) {
|
|
4101
|
+
this._switchWizardTab(container, msg, msg.activeTab + 1);
|
|
4102
|
+
const next = Array.from(form.querySelectorAll('.question-entry.active .question-item'));
|
|
4103
|
+
focusStop(stopTarget(next[0]));
|
|
4104
|
+
} else {
|
|
4105
|
+
focusStop(submit);
|
|
4106
|
+
}
|
|
4107
|
+
};
|
|
4108
|
+
|
|
4109
|
+
// On the Submit button: let Enter/Space submit natively; Shift+Tab steps
|
|
4110
|
+
// back to the last question; there's nothing past Submit for plain Tab.
|
|
4111
|
+
if (target === submit) {
|
|
4112
|
+
if (e.key === 'Tab' && e.shiftKey && stops.length) {
|
|
4113
|
+
e.preventDefault();
|
|
4114
|
+
focusStop(stopTarget(stops[stops.length - 1]));
|
|
4115
|
+
}
|
|
4116
|
+
return;
|
|
4117
|
+
}
|
|
4118
|
+
|
|
4119
|
+
// Enter on an option selects it, then advances — except "Other", which
|
|
4120
|
+
// reveals its text input, so we stay put to let the user type.
|
|
4121
|
+
if (e.key === 'Enter' && isOption) {
|
|
4122
|
+
e.preventDefault();
|
|
4123
|
+
target.click();
|
|
4124
|
+
if (target.dataset.value !== '__other__') goForward();
|
|
4125
|
+
return;
|
|
4126
|
+
}
|
|
4127
|
+
|
|
4128
|
+
// Single-question card: Enter in the sole text input submits directly.
|
|
4129
|
+
if (e.key === 'Enter' && inTextInput && totalQuestions <= 1) {
|
|
4130
|
+
e.preventDefault();
|
|
4131
|
+
submit?.click();
|
|
4132
|
+
return;
|
|
4133
|
+
}
|
|
4134
|
+
|
|
4135
|
+
if (!currentItem) return; // focus on a tab / nav button — leave it to the browser
|
|
4136
|
+
const idx = stops.indexOf(currentItem);
|
|
4137
|
+
const back = e.key === 'Tab' && e.shiftKey;
|
|
4138
|
+
e.preventDefault();
|
|
4139
|
+
|
|
4140
|
+
if (back) {
|
|
4141
|
+
if (idx > 0) {
|
|
4142
|
+
focusStop(stopTarget(stops[idx - 1]));
|
|
4143
|
+
} else if (isWizard && msg.activeTab > 0) {
|
|
4144
|
+
this._switchWizardTab(container, msg, msg.activeTab - 1);
|
|
4145
|
+
const prev = Array.from(form.querySelectorAll('.question-entry.active .question-item'));
|
|
4146
|
+
focusStop(stopTarget(prev[prev.length - 1]));
|
|
4147
|
+
}
|
|
4148
|
+
return;
|
|
4149
|
+
}
|
|
4150
|
+
|
|
4151
|
+
// Forward (plain Tab, or Enter from a text input): jump to next question.
|
|
4152
|
+
goForward();
|
|
4153
|
+
}
|
|
4154
|
+
|
|
4155
|
+
/**
|
|
4156
|
+
* Move keyboard focus onto an option button.
|
|
4157
|
+
*
|
|
4158
|
+
* Landing on "Other..." also selects it and drops focus straight into its
|
|
4159
|
+
* custom-answer input, so a keyboard user can just start typing instead of
|
|
4160
|
+
* having to reach for the mouse. Selecting is not optional: submit reads
|
|
4161
|
+
* `.question-other-input` only for an option carrying `.selected`, so
|
|
4162
|
+
* revealing the input without selecting would silently discard whatever
|
|
4163
|
+
* was typed. Already-selected is left alone — re-clicking would toggle a
|
|
4164
|
+
* multiSelect "Other" back off.
|
|
4165
|
+
* @param {HTMLElement} btn - a `.question-option`
|
|
4166
|
+
*/
|
|
4167
|
+
_focusQuestionOption(btn) {
|
|
4168
|
+
if (!btn) return;
|
|
4169
|
+
const input = btn.dataset.value === '__other__' && !btn.disabled
|
|
4170
|
+
? btn.closest('.question-item')?.querySelector('.question-other-input')
|
|
4171
|
+
: null;
|
|
4172
|
+
|
|
4173
|
+
if (input) {
|
|
4174
|
+
if (btn.classList.contains('selected')) {
|
|
4175
|
+
input.style.display = 'block'; // click handler does this on the other branch
|
|
4176
|
+
input.focus();
|
|
4177
|
+
} else {
|
|
4178
|
+
btn.click(); // selects, reveals and focuses the input
|
|
4179
|
+
}
|
|
4180
|
+
if (typeof input.select === 'function') input.select();
|
|
4181
|
+
input.scrollIntoView({ block: 'nearest' });
|
|
4182
|
+
return;
|
|
4183
|
+
}
|
|
4184
|
+
|
|
4185
|
+
btn.focus();
|
|
4186
|
+
btn.scrollIntoView({ block: 'nearest' });
|
|
4187
|
+
}
|
|
4188
|
+
|
|
4189
|
+
/**
|
|
4190
|
+
* Switch wizard tab
|
|
4191
|
+
*/
|
|
4192
|
+
_switchWizardTab(container, msg, newTab) {
|
|
4193
|
+
const entries = msg.entries || [];
|
|
4194
|
+
if (newTab < 0 || newTab >= entries.length) return;
|
|
4195
|
+
|
|
4196
|
+
msg.activeTab = newTab;
|
|
4197
|
+
|
|
4198
|
+
// Update tab buttons
|
|
4199
|
+
container.querySelectorAll('.wizard-tab').forEach((tab, idx) => {
|
|
4200
|
+
tab.classList.toggle('active', idx === newTab);
|
|
4201
|
+
});
|
|
4202
|
+
|
|
4203
|
+
// Update entry visibility
|
|
4204
|
+
container.querySelectorAll('.question-entry').forEach((entry, idx) => {
|
|
4205
|
+
entry.classList.toggle('active', idx === newTab);
|
|
4206
|
+
});
|
|
4207
|
+
|
|
4208
|
+
// Update navigation
|
|
4209
|
+
const prevBtn = container.querySelector('.wizard-nav-btn.prev');
|
|
4210
|
+
const nextBtn = container.querySelector('.wizard-nav-btn.next');
|
|
4211
|
+
const progress = container.querySelector('.wizard-progress');
|
|
4212
|
+
|
|
4213
|
+
if (prevBtn) prevBtn.disabled = newTab === 0;
|
|
4214
|
+
if (nextBtn) nextBtn.style.display = newTab === entries.length - 1 ? 'none' : '';
|
|
4215
|
+
if (progress) progress.textContent = `${newTab + 1} of ${entries.length}`;
|
|
4216
|
+
}
|
|
4217
|
+
|
|
4218
|
+
/**
|
|
4219
|
+
* Update wizard tab state (checkmarks for answered tabs)
|
|
4220
|
+
*/
|
|
4221
|
+
_updateWizardTabState(container, msg) {
|
|
4222
|
+
const entries = msg.entries || [];
|
|
4223
|
+
container.querySelectorAll('.wizard-tab').forEach((tab, idx) => {
|
|
4224
|
+
const entry = entries[idx];
|
|
4225
|
+
const hasAnswer = entry && Object.keys(entry.answers || {}).length > 0;
|
|
4226
|
+
tab.classList.toggle('answered', hasAnswer);
|
|
4227
|
+
|
|
4228
|
+
// Add/update checkmark
|
|
4229
|
+
let check = tab.querySelector('.wizard-tab-check');
|
|
4230
|
+
if (hasAnswer && !check) {
|
|
4231
|
+
check = document.createElement('span');
|
|
4232
|
+
check.className = 'wizard-tab-check';
|
|
4233
|
+
check.innerHTML = '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>';
|
|
4234
|
+
tab.appendChild(check);
|
|
4235
|
+
} else if (!hasAnswer && check) {
|
|
4236
|
+
check.remove();
|
|
4237
|
+
}
|
|
4238
|
+
});
|
|
4239
|
+
}
|
|
4240
|
+
|
|
4241
|
+
/**
|
|
4242
|
+
* Update a question message after it's been answered
|
|
4243
|
+
* @param {Object} msg - The updated question message
|
|
4244
|
+
*/
|
|
4245
|
+
updateQuestionMessage(msg) {
|
|
4246
|
+
const existing = document.getElementById(`msg-${msg.id}`);
|
|
4247
|
+
if (existing) {
|
|
4248
|
+
const newElement = this._renderQuestionForm(msg);
|
|
4249
|
+
existing.replaceWith(newElement);
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
}
|