gentle-pi 4.5.1 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-shell.md +69 -19
  15. package/docs/install-wizard.md +1 -1
  16. package/docs/mcp-status.md +52 -0
  17. package/docs/prompt-budget.md +28 -0
  18. package/docs/readme-reference.md +79 -20
  19. package/docs/session-profile-format.md +20 -5
  20. package/docs/sound-notifications.md +1 -1
  21. package/docs/star-prompt.md +32 -0
  22. package/docs/work-continuity.md +46 -0
  23. package/extensions/ask-user-question.ts +1 -0
  24. package/extensions/codegraph-tools.ts +38 -4
  25. package/extensions/gentle-agents.ts +477 -50
  26. package/extensions/gentle-ai.ts +1041 -188
  27. package/extensions/gentle-fast.ts +61 -0
  28. package/extensions/gentle-guide.ts +174 -0
  29. package/extensions/gentle-herdr-activity.ts +21 -1
  30. package/extensions/gentle-herdr-agent.ts +144 -0
  31. package/extensions/gentle-program-identity.ts +61 -0
  32. package/extensions/gentle-shell.ts +642 -97
  33. package/extensions/gentle-star-prompt.ts +334 -0
  34. package/extensions/gentle-stats.ts +5 -5
  35. package/extensions/gentle-todo.ts +42 -22
  36. package/extensions/history/store.ts +18 -12
  37. package/extensions/skill-registry.ts +35 -3
  38. package/extensions/startup-banner.ts +39 -7
  39. package/lib/agent-assets.ts +74 -17
  40. package/lib/agent-profiles.ts +1 -1
  41. package/lib/agents-config.ts +12 -3
  42. package/lib/agents-keys.ts +8 -16
  43. package/lib/agents-protocol.ts +80 -4
  44. package/lib/agents-runner.ts +105 -4
  45. package/lib/agents-view.ts +6 -1
  46. package/lib/agents-widget.ts +132 -9
  47. package/lib/bridge-cost.ts +28 -0
  48. package/lib/codemode-renderer.ts +16 -0
  49. package/lib/command-palette-catalog.ts +1 -0
  50. package/lib/command-palette.ts +21 -8
  51. package/lib/exploration-budget.ts +62 -0
  52. package/lib/gentle-guide.ts +201 -0
  53. package/lib/gentle-shell-launcher.ts +4 -0
  54. package/lib/herdr-activity.ts +9 -3
  55. package/lib/herdr-task-summary-policy.ts +85 -0
  56. package/lib/inprocess-reviewer.ts +33 -13
  57. package/lib/jobs-sidebar-state.ts +5 -6
  58. package/lib/jobs-widget.ts +16 -52
  59. package/lib/keymaps-customize.ts +81 -0
  60. package/lib/keymaps.ts +291 -0
  61. package/lib/model-fallback-notice.ts +61 -0
  62. package/lib/model-fallback-policy.ts +141 -0
  63. package/lib/model-fallback-store.ts +143 -0
  64. package/lib/model-routing-authority.ts +10 -2
  65. package/lib/nan-provider.ts +3 -2
  66. package/lib/native-review-cli.ts +7 -2
  67. package/lib/notification-customize.ts +48 -51
  68. package/lib/openai-fast-tier.ts +22 -0
  69. package/lib/orchestrator-discovery.ts +5 -1
  70. package/lib/orchestrator-fallback.ts +75 -0
  71. package/lib/pasted-image-paths.ts +113 -0
  72. package/lib/questionnaire/questionnaire-view.ts +121 -7
  73. package/lib/review-candidate-view-owner.ts +4 -0
  74. package/lib/review-candidate-view.ts +10 -7
  75. package/lib/review-host-relay.ts +5 -1
  76. package/lib/review-integration-v2.ts +22 -7
  77. package/lib/review-repository.ts +5 -0
  78. package/lib/session-profile-append-controller.ts +21 -6
  79. package/lib/session-profile-authority.ts +119 -0
  80. package/lib/session-profile-binding.ts +54 -5
  81. package/lib/session-profile-freeze.ts +105 -9
  82. package/lib/session-profile-integration.ts +313 -0
  83. package/lib/session-profile-persistence.ts +63 -9
  84. package/lib/shell-bar.ts +171 -56
  85. package/lib/shell-card.ts +26 -6
  86. package/lib/shell-page.ts +120 -0
  87. package/lib/shell-panel.ts +149 -0
  88. package/lib/shell-prompt.ts +53 -1
  89. package/lib/shell-sidebar-layout.ts +98 -25
  90. package/lib/shell-sidebar.ts +54 -1
  91. package/lib/shell-stats.ts +123 -0
  92. package/lib/shell-todo.ts +71 -0
  93. package/lib/shell-usage.ts +12 -2
  94. package/lib/star-prompt.ts +197 -0
  95. package/lib/verifier-admission.ts +18 -8
  96. package/lib/verifier-settle-reminder.ts +64 -0
  97. package/lib/vim-editor-adapter.ts +6 -1
  98. package/lib/visual-customization-policy.ts +41 -6
  99. package/lib/visual-customize-view.ts +164 -26
  100. package/lib/visual-layout-preview.ts +43 -0
  101. package/lib/yolo-session-policy.ts +28 -1
  102. package/package.json +1 -1
  103. package/runtime/gentle-shell-launcher.mjs +4 -0
  104. package/runtime/native-review-cli.mjs +7 -2
  105. package/runtime/review-integration-v2.mjs +22 -7
  106. package/runtime/windows-session-transport.ps1 +60 -3
  107. package/scripts/bootstrap.sh +4 -1
  108. package/scripts/installer-preflight.mjs +1 -1
  109. package/scripts/pi-update.mjs +113 -3
  110. package/scripts/run-test-suite.mjs +17 -1
  111. package/scripts/shell-snapshot.mjs +340 -0
  112. package/scripts/test-packed-runner.mjs +1 -1
  113. package/scripts/update-agent-body-history.mjs +41 -0
  114. package/scripts/verify-installer-tap.mjs +45 -0
  115. package/scripts/verify-package-files.mjs +2 -0
  116. package/skills/gentle-ai/SKILL.md +2 -2
  117. package/skills/tui-design/NOTICE.md +5 -0
  118. package/skills/tui-design/SKILL.md +56 -0
  119. package/skills/tui-design/references/commands.md +75 -0
  120. package/skills/tui-design/references/critique.md +48 -0
  121. package/skills/tui-design/references/design-doc.md +44 -0
  122. package/skills/tui-design/references/terminal-craft.md +64 -0
  123. package/skills/tui-design/references/visual-loop.md +32 -0
  124. package/tests/agents-protocol.test.ts +53 -1
  125. package/tests/agents-runner.test.ts +168 -3
  126. package/tests/agents-view.test.ts +27 -0
  127. package/tests/agents-widget.test.ts +312 -10
  128. package/tests/bounded-scan-contract.test.ts +39 -0
  129. package/tests/bridge-cost.test.ts +32 -0
  130. package/tests/bundled-install.test.ts +6 -4
  131. package/tests/ci-concurrency.test.ts +11 -0
  132. package/tests/ci-merge-base-identity.test.ts +114 -0
  133. package/tests/codegraph-tools.test.ts +69 -0
  134. package/tests/codemode-rendering.test.ts +22 -2
  135. package/tests/command-palette.test.ts +16 -2
  136. package/tests/commit-slice-signal.test.ts +11 -9
  137. package/tests/delegate-for-reason-contract.test.ts +5 -4
  138. package/tests/exploration-budget.test.ts +128 -0
  139. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  140. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  141. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  142. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  143. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  144. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  145. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  148. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  149. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  150. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  151. package/tests/gentle-agents.test.ts +416 -21
  152. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  153. package/tests/gentle-ai.test.ts +1007 -33
  154. package/tests/gentle-fast.test.ts +73 -0
  155. package/tests/gentle-guide.test.ts +208 -0
  156. package/tests/gentle-herdr-activity.test.ts +76 -2
  157. package/tests/gentle-herdr-agent.test.ts +111 -0
  158. package/tests/gentle-program-identity.test.ts +197 -0
  159. package/tests/gentle-shell-bin.test.ts +49 -26
  160. package/tests/gentle-shell-launcher.test.ts +18 -2
  161. package/tests/gentle-shell.test.ts +1068 -37
  162. package/tests/gentle-stats.test.ts +15 -2
  163. package/tests/gentle-todo.test.ts +50 -4
  164. package/tests/herdr-task-summary-policy.test.ts +128 -0
  165. package/tests/history-store-private-mode.test.ts +40 -0
  166. package/tests/image-paste-chips.test.ts +42 -0
  167. package/tests/inprocess-reviewer.test.ts +122 -0
  168. package/tests/installer-posix-bootstrap.test.ts +67 -5
  169. package/tests/installer-server.test.ts +2 -2
  170. package/tests/installer-windows-diagnostics.test.ts +4 -5
  171. package/tests/isolated-config-home.ts +28 -0
  172. package/tests/jobs-widget.test.ts +25 -37
  173. package/tests/keymaps-customize.test.ts +114 -0
  174. package/tests/keymaps.test.ts +103 -0
  175. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  176. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  177. package/tests/model-fallback-notice.test.ts +45 -0
  178. package/tests/model-fallback-policy.test.ts +83 -0
  179. package/tests/model-fallback-store.test.ts +111 -0
  180. package/tests/nan-provider.test.ts +4 -4
  181. package/tests/no-self-pause-contract.test.ts +19 -0
  182. package/tests/notification-customize.test.ts +58 -34
  183. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  184. package/tests/odd-routing-contract.test.ts +1 -1
  185. package/tests/orchestrator-fallback.test.ts +82 -0
  186. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  187. package/tests/package-manifest.test.ts +160 -7
  188. package/tests/pasted-image-paths.test.ts +118 -0
  189. package/tests/persona-reply-language.test.ts +20 -1
  190. package/tests/pi-update-launcher.test.ts +32 -8
  191. package/tests/pi-update-source.test.ts +162 -0
  192. package/tests/profile-fast-tier.test.ts +311 -0
  193. package/tests/profile-tier-footer.test.ts +79 -0
  194. package/tests/questionnaire-view.test.ts +150 -0
  195. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  196. package/tests/review-candidate-view.test.ts +51 -0
  197. package/tests/review-controller-native-routing.test.ts +120 -6
  198. package/tests/review-gate.test.ts +24 -0
  199. package/tests/review-inspect-preflight.test.ts +197 -0
  200. package/tests/review-integration-v2-forward.test.ts +59 -0
  201. package/tests/review-repository.test.ts +52 -1
  202. package/tests/review-sidebar-state.test.ts +5 -5
  203. package/tests/run-test-suite.test.ts +61 -5
  204. package/tests/sensitive-path-tools.test.ts +74 -0
  205. package/tests/session-profile-append-controller.test.ts +63 -0
  206. package/tests/session-profile-authority.test.ts +259 -0
  207. package/tests/session-profile-binding.test.ts +15 -0
  208. package/tests/session-profile-extension.test.ts +615 -0
  209. package/tests/session-profile-freeze.test.ts +110 -2
  210. package/tests/session-profile-integration.test.ts +857 -0
  211. package/tests/session-profile-persistence.test.ts +57 -0
  212. package/tests/session-profile-v1-compat.test.ts +221 -0
  213. package/tests/shell-bar.test.ts +113 -55
  214. package/tests/shell-card.test.ts +13 -1
  215. package/tests/shell-page.test.ts +108 -0
  216. package/tests/shell-panel.test.ts +332 -0
  217. package/tests/shell-prompt.test.ts +54 -0
  218. package/tests/shell-render-cache.test.ts +5 -0
  219. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  220. package/tests/shell-sidebar-layout.test.ts +159 -27
  221. package/tests/shell-stats.test.ts +90 -0
  222. package/tests/shell-usage.test.ts +14 -0
  223. package/tests/skill-registry.test.ts +68 -1
  224. package/tests/star-prompt.test.ts +470 -0
  225. package/tests/startup-banner.test.ts +57 -1
  226. package/tests/task-size-routing-contract.test.ts +45 -1
  227. package/tests/verifier-settle-reminder.test.ts +281 -0
  228. package/tests/verify-first-launch-contract.test.ts +56 -5
  229. package/tests/verify-installer-tap.test.ts +57 -0
  230. package/tests/vim-editor-adapter.test.ts +2 -2
  231. package/tests/visual-customization-policy.test.ts +61 -7
  232. package/tests/visual-customize-view.test.ts +253 -8
  233. package/tests/visual-layout-preview.test.ts +28 -0
  234. package/tests/windows-session-bootstrap.test.ts +105 -2
  235. package/tests/work-continuity-contract.test.ts +86 -0
  236. package/tests/writer-surfaces.test.ts +12 -10
  237. package/tests/yolo-customize.test.ts +30 -11
  238. package/tests/yolo-mode-runtime.test.ts +4 -2
  239. package/tests/yolo-mode.test.ts +16 -2
@@ -1,7 +1,9 @@
1
+ import { sharedCooldown, syncUsageCooldown } from "../lib/model-fallback-policy.ts";
1
2
  import { CustomEditor, keyHint, type ExtensionAPI, type ExtensionContext, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
2
3
  import { isHomeOrBroadUserDirectory } from "../lib/bounded-writer-admission.ts";
3
- import { Editor, Image, decodeKittyPrintable, getCapabilities, isKeyRelease, matchesKey, parseKey, truncateToWidth, visibleWidth, type Component, type EditorTheme, type TUI } from "@earendil-works/pi-tui";
4
+ import { Editor, Image, Key, decodeKittyPrintable, getCapabilities, isKeyRelease, matchesKey, parseKey, truncateToWidth, visibleWidth, type Component, type EditorTheme, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
4
5
  import { readClipboardImage, type ClipboardImage } from "../lib/clipboard-image.ts";
6
+ import { readPastedImagePaths } from "../lib/pasted-image-paths.ts";
5
7
  import { describeAttachment, ImageAttachments } from "../lib/image-attachments.ts";
6
8
  import { execFile, spawnSync } from "node:child_process";
7
9
  import { openInExternalEditor, type ExternalEditorHost } from "../lib/external-editor.ts";
@@ -12,7 +14,7 @@ import { profilesFilePath, profileRoleEntries, readProfilesFileResult } from "..
12
14
  import { resolveSessionProfile, sessionProfileLabel, sessionProfileModelProfiles } from "../lib/session-profile-freeze.ts";
13
15
  import * as os from "node:os";
14
16
  import { dirname, join, resolve } from "node:path";
15
- import { buildShellHeaderModel, renderShellBar, renderShellBelowInputFloat, renderShellBottomOnlyBar, renderShellHeaderChrome, renderShellSidebarBar, keepNativeWorkingRow, shellEnabled, shellHeaderUsageHit, shellJobsCount, type ShellBarModel, type ShellBarTheme } from "../lib/shell-bar.ts";
17
+ import { buildShellHeaderModel, renderShellBar, renderShellBelowInputFloat, renderShellBottomOnlyBar, renderShellHeaderChrome, renderShellSidebarBar, renderShellStatusBar, renderShellStatusSections, renderShellTitleRow, type StatusSection, type StatusTarget, keepNativeWorkingRow, shellEnabled, shellHeaderUsageHit, shellJobsCount, type ShellBarModel, type ShellBarTheme } from "../lib/shell-bar.ts";
16
18
  import { CHANGE_STATUS, DIFF_MAX_BYTES, DIFF_MAX_LINES, DIFF_TOO_LARGE, WorktreeChangesTracker, changesDigest, renderChangesWidget, type ChangedFile, type ChangesModel, type FileRevision, type GitRunner, type LineCounter, type WorktreeChanges } from "../lib/shell-changes.ts";
17
19
  import { WorktreeChangesView } from "../lib/shell-changes-view.ts";
18
20
  import { createNativeFullscreenInteraction } from "../lib/native-fullscreen-interaction.ts";
@@ -22,18 +24,21 @@ import { resolveCardStyle, writeCardStyle } from "../lib/card-style-policy.ts";
22
24
  import { CARD_CONTENT, resolveCardContent, setCardContent, writeCardContent } from "../lib/card-content-policy.ts";
23
25
  import { CommandPalette, commandsKey, type CommandPaletteResult } from "../lib/command-palette.ts";
24
26
  import { buildCommandPaletteGroups } from "../lib/command-palette-catalog.ts";
25
- import { discoverYoloUiAdapter, YOLO_DISPLAY, type YoloDisplay, type YoloUiAdapter } from "../lib/yolo-session-policy.ts";
27
+ import { buildKeymapRows } from "../lib/keymaps-customize.ts";
28
+ import { discoverYoloUiAdapter, MODE_STATUS_KEY, YOLO_DISPLAY, YOLO_STATUS_KEY, type YoloDisplay, type YoloUiAdapter } from "../lib/yolo-session-policy.ts";
26
29
  import { VisualCustomizeView, type CustomizeCategory, type CustomizeRow, type ProfileActions } from "../lib/visual-customize-view.ts";
27
30
  import { deleteVisualProfile, getVisualProfile, listVisualProfiles, resetVisualProfiles, saveVisualProfile } from "../lib/visual-profiles.ts";
28
31
  import { gaugePaintFor } from "../lib/gauge-theme.ts";
29
32
  import type { GaugePaint } from "../lib/shell-gauge.ts";
30
33
  import { sourcePalettePreview } from "../lib/theme-customization.ts";
31
- import { DEFAULT_VISUAL_SETTINGS, DENSITY, HEADER_PLACEMENT, STATUS_PLACEMENT, VISUAL_SECTION_KEYS, resolveVisualSettings, writeVisualSettings } from "../lib/visual-customization-policy.ts";
34
+ import { applyVisualPreset, DEFAULT_VISUAL_SETTINGS, DENSITY, HEADER_PLACEMENT, STATUS_PLACEMENT, VISUAL_PRESET, VISUAL_SECTION_KEYS, resolveVisualSettings, visualPresetOf, writeVisualSettings, type VisualPreset } from "../lib/visual-customization-policy.ts";
32
35
  import { BANNER_COLORS, DEFAULT_BANNER_CONFIG, readBannerConfig, readBannerConfigForEdit, writeBannerConfig } from "./startup-banner.ts";
33
- import { agentsViewKey } from "../lib/agents-keys.ts";
36
+ import { commandKeymapId, commandKeymapIds, effectiveKey, keymapCommand, keymapLabel, keymapSavedNotice, loadKeymaps, prepareKeymapChange, writeKeymaps, type KeymapBindings, type PiKeybindings } from "../lib/keymaps.ts";
34
37
  import { GentleAiDevBinaryOverrideError, resolveGentleAiDevBinaryOverride } from "../lib/gentle-ai-binary.ts";
35
- import { DOUBLE_ESC_CANCEL_HINT, floatPromptRow, framePromptLines, resolvePromptLayout, IDLE_ESC_CLEAR_HINT, PROMPT_HINT, PROMPT_STATE, SHELL_PULSE_WATCHDOG_MS, withPromptHint, type PromptState } from "../lib/shell-prompt.ts";
38
+ import { DOUBLE_ESC_CANCEL_HINT, floatPromptRow, framePromptLines, panelPromptRow, resolvePromptLayout, IDLE_ESC_CLEAR_HINT, PANEL_BUTTON, PROMPT_HINT, PROMPT_STATE, SHELL_PULSE_WATCHDOG_MS, withPromptHint, type PromptState } from "../lib/shell-prompt.ts";
39
+ import { stripAnsi } from "../lib/terminal-theme.ts";
36
40
  import { oddPhaseRegistry } from "../lib/odd-phase.ts";
41
+ import { CLAUDE_BRIDGE_PROVIDER, priceBridgeMessage } from "../lib/bridge-cost.ts";
37
42
  import { inferOddPhase } from "../lib/odd-phase-inference.ts";
38
43
  import { isInteractiveMode } from "../lib/rpc-host.ts";
39
44
  import { gentlePiConfigHome } from "../lib/agent-home.ts";
@@ -121,12 +126,17 @@ import {
121
126
  } from "../lib/double-esc-cancel-policy.ts";
122
127
  import { accountIdFromToken, CODEX_PROVIDER, CODEX_USAGE_URL, NAN_PROVIDER, NAN_QUOTA_URL, parseCodexUsage, parseNanQuota, parseProviderUsage, parseUsageHeaders, parseUsageSource, usageScopeProviders, UsageSourceRegistry, UsageStore, USAGE_SOURCE_EVENT, type ProviderUsage, type UsageSource } from "../lib/shell-usage.ts";
123
128
  import { UsageView } from "../lib/shell-usage-view.ts";
124
- import { sidebarHeader, sidebarPart, sidebarState, VISUAL_SETTINGS_CHANGED, type SidebarRail } from "../lib/shell-sidebar.ts";
129
+ import { releaseSidebarHover, setSidebarHover, sidebarHeader, sidebarPart, sidebarState, sidebarStatusBar, VISUAL_SETTINGS_CHANGED, type SidebarRail } from "../lib/shell-sidebar.ts";
125
130
  import { installSidebar, invalidateSidebar, narrowStatusOwner, SIDEBAR_BREAKPOINT, STATUS_OWNER } from "../lib/shell-sidebar-layout.ts";
131
+ import { panelSheetBackHit, renderPanelSheet, renderWorkRow, workRowLead } from "../lib/shell-panel.ts";
132
+ import { installPagePaint, type PageTheme } from "../lib/shell-page.ts";
133
+ import { layoutSchematic } from "../lib/visual-layout-preview.ts";
134
+ import { collectSessionStats, type SessionStats } from "../lib/shell-stats.ts";
126
135
  import { sessionChangeRoots } from "../lib/session-changes.ts";
127
136
  import { REVIEW_SIDEBAR_EVENT, isReviewSidebarSnapshot, type ReviewSidebarSnapshot } from "../lib/review-sidebar-state.ts";
128
137
  import { JOBS_SIDEBAR_EVENT, JOBS_STATUS_KEY, isJobsSidebarSnapshot, jobsCollapseKey, type RunningJobDisplay } from "../lib/jobs-sidebar-state.ts";
129
- import { JOBS_FINISHED_TTL_MS, jobsCardTone, renderJobsCard } from "../lib/jobs-widget.ts";
138
+ import { JOBS_FINISHED_TTL_MS, renderJobsSection } from "../lib/jobs-widget.ts";
139
+ import { todoCollapseKey } from "../lib/shell-todo.ts";
130
140
  import { NativePointerRegion } from "../lib/native-pointer-region.ts";
131
141
  import { installSessionChangeCapture } from "../lib/session-change-capture.ts";
132
142
  import { SelectionEngine } from "../lib/selection-engine.ts";
@@ -158,6 +168,7 @@ interface ShellBarComponent {
158
168
  interface BuildOptions {
159
169
  jobs?: RunningJobDisplay[];
160
170
  profile?: string;
171
+ profileTier?: ShellBarModel["profileTier"];
161
172
  home?: string;
162
173
  dirty?: number;
163
174
  usage?: ProviderUsage;
@@ -181,6 +192,7 @@ export interface ShellDeps {
181
192
  }
182
193
 
183
194
  export type ActiveProfileReader = (() => string | undefined) & {
195
+ tier(): ShellBarModel["profileTier"];
184
196
  bind(cwd: string, resolveWorktree: WorktreeResolver, sessionId?: string): boolean;
185
197
  refresh(): boolean;
186
198
  reset(): void;
@@ -192,6 +204,8 @@ export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env):
192
204
  const path = profilesFilePath(gentlePiConfigHome(env));
193
205
  let fingerprint: string | undefined;
194
206
  let name: string | undefined;
207
+ let tiers: Record<string, ShellBarModel["profileTier"]> = {};
208
+ let effectiveTier: ShellBarModel["profileTier"];
195
209
  let bound = false;
196
210
  let cwd: string | undefined;
197
211
  let identity: WorktreeIdentity | undefined;
@@ -204,6 +218,7 @@ export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env):
204
218
  if (next !== fingerprint) {
205
219
  const result = readProfilesFileResult(path);
206
220
  name = result.status === "valid" ? result.file.active : undefined;
221
+ tiers = result.status === "valid" ? Object.fromEntries(Object.entries(result.file.profiles).map(([name, config]) => [name, config.orchestrator?.tier])) : {};
207
222
  fingerprint = next;
208
223
  }
209
224
  return name;
@@ -214,6 +229,11 @@ export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env):
214
229
  }
215
230
  };
216
231
  const reader = (() => bound ? effective : global()) as ActiveProfileReader;
232
+ reader.tier = () => {
233
+ if (bound) return effectiveTier;
234
+ const active = global();
235
+ return active ? tiers[active] : undefined;
236
+ };
217
237
  reader.refresh = () => {
218
238
  if (!bound) return false;
219
239
  // gentle-shell#1064: the status shows the profile launches use, through
@@ -221,15 +241,20 @@ export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env):
221
241
  // startup → live p → P → G only in follow mode), with the existing
222
242
  // spelling: "name (session)", "name (local)", "name (repo)", or the bare
223
243
  // global name.
224
- const next = cwd === undefined ? global() : sessionProfileLabel(resolveSessionProfile({
244
+ global();
245
+ const selected = cwd === undefined ? undefined : resolveSessionProfile({
225
246
  sessionId,
226
247
  cwd,
227
248
  configHome: gentlePiConfigHome(env),
228
249
  resolveWorktree: () => identity,
229
250
  env,
230
- }));
231
- const changed = next !== effective;
251
+ });
252
+ const next = selected ? sessionProfileLabel(selected) : name;
253
+ const configuredName = selected ? selected.kind === "explicit" ? selected.name : selected.profile?.name : name;
254
+ const nextTier = configuredName ? tiers[configuredName] : undefined;
255
+ const changed = next !== effective || nextTier !== effectiveTier;
232
256
  effective = next;
257
+ effectiveTier = nextTier;
233
258
  return changed;
234
259
  };
235
260
  reader.bind = (nextCwd, resolveWorktree, nextSessionId) => {
@@ -240,7 +265,7 @@ export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env):
240
265
  bound = true;
241
266
  return reader.refresh();
242
267
  };
243
- reader.reset = () => { bound = false; cwd = undefined; identity = undefined; sessionId = undefined; effective = undefined; };
268
+ reader.reset = () => { bound = false; cwd = undefined; identity = undefined; sessionId = undefined; effective = undefined; effectiveTier = undefined; };
244
269
  return reader;
245
270
  }
246
271
 
@@ -326,13 +351,20 @@ export function buildShellBarModel(
326
351
  const { usage, costTotal } = sessionStats(ctx);
327
352
  const model = ctx.model;
328
353
  const adaptiveReasoning = isNanAdaptiveReasoningModel(model);
329
- const statuses = Array.from(footerData.getExtensionStatuses().entries())
330
- .filter(([key]) => options.jobs === undefined || key !== JOBS_STATUS_KEY)
331
- .sort(([a], [b]) => a.localeCompare(b))
332
- .map(([, text]) => text);
354
+ const entries = Array.from(footerData.getExtensionStatuses().entries())
355
+ .filter(([key]) => key !== "gentle-fast" && (options.jobs === undefined || key !== JOBS_STATUS_KEY))
356
+ .sort(([a], [b]) => a.localeCompare(b));
357
+ const statuses = entries.map(([, text]) => text);
358
+ // The permission mode has its own status keys: the wide chrome shows the mode
359
+ // once in its status bar and the rail only says what it means.
360
+ const modeText = entries.find(([key]) => key === MODE_STATUS_KEY)?.[1];
361
+ const yoloText = entries.find(([key]) => key === YOLO_STATUS_KEY)?.[1];
362
+ const mode = modeText?.replace(/^Permissions:\s*/, "").trim();
363
+ const detail = yoloText?.includes(" — ") ? yoloText.slice(yoloText.indexOf(" — ") + 3).trim() : yoloText?.trim();
333
364
  return {
334
365
  cwd: shortenHome(ctx.sessionManager.getCwd(), home),
335
366
  profile: options.profile,
367
+ ...(options.profileTier ? { profileTier: options.profileTier } : {}),
336
368
  branch: footerData.getGitBranch(),
337
369
  dirty: options.dirty,
338
370
  sessionName: ctx.sessionManager.getSessionName(),
@@ -341,10 +373,13 @@ export function buildShellBarModel(
341
373
  contextPercent: usage?.percent ?? null,
342
374
  contextWindow: usage?.contextWindow ?? model?.contextWindow ?? 0,
343
375
  costTotal,
344
- subscription: model ? ctx.modelRegistry.isUsingOAuth(model) : false,
376
+ // claude-bridge runs on a Claude subscription without a Pi OAuth credential.
377
+ subscription: model ? model.provider === CLAUDE_BRIDGE_PROVIDER || ctx.modelRegistry.isUsingOAuth(model) : false,
345
378
  usage: options.usage,
346
379
  ...(options.jobs !== undefined ? { jobs: options.jobs } : {}),
347
380
  statuses,
381
+ ...(mode ? { permission: { mode, ...(detail ? { detail } : {}) } } : {}),
382
+ integrations: entries.filter(([key]) => key !== MODE_STATUS_KEY && key !== YOLO_STATUS_KEY).map(([, text]) => text),
348
383
  };
349
384
  }
350
385
 
@@ -354,6 +389,7 @@ export interface FooterStatusMemoDeps {
354
389
  footerData: ShellFooterData;
355
390
  usage: () => ProviderUsage | undefined;
356
391
  profile: () => string | undefined;
392
+ profileTier?: () => ShellBarModel["profileTier"];
357
393
  jobs: () => RunningJobDisplay[] | undefined;
358
394
  review: () => ReviewSidebarSnapshot | undefined;
359
395
  tracker: () => Pick<WorktreeChangesTracker, "model" | "unbornRoots">;
@@ -388,6 +424,7 @@ export function createFooterStatusMemo(deps: FooterStatusMemoDeps): { key(): str
388
424
  model ? ctx.modelRegistry.isUsingOAuth(model) : false,
389
425
  footerData.getGitBranch(),
390
426
  deps.profile(),
427
+ deps.profileTier?.(),
391
428
  ctx.sessionManager.getSessionName(),
392
429
  ctx.sessionManager.getCwd(),
393
430
  [...footerData.getExtensionStatuses()].sort(([a], [b]) => a.localeCompare(b)),
@@ -407,7 +444,7 @@ export function createFooterStatusMemo(deps: FooterStatusMemoDeps): { key(): str
407
444
  if (cache?.key === k) return cache.model;
408
445
  const tracker = deps.tracker();
409
446
  const built: ShellBarModel = {
410
- ...buildShellBarModel(pi, ctx, footerData, { dirty: tracker.model.files.length, usage: deps.usage(), profile: deps.profile(), jobs: deps.jobs() }),
447
+ ...buildShellBarModel(pi, ctx, footerData, { dirty: tracker.model.files.length, usage: deps.usage(), profile: deps.profile(), profileTier: deps.profileTier?.(), jobs: deps.jobs() }),
411
448
  changes: { files: tracker.model.files.length, added: tracker.model.added, deleted: tracker.model.deleted },
412
449
  review: deps.review(),
413
450
  };
@@ -478,6 +515,16 @@ interface PromptEditorDeps {
478
515
  readClipboardImage?: () => Promise<ClipboardImage | null>;
479
516
  /** Injectable silence-watchdog window; production and tests default to SHELL_PULSE_WATCHDOG_MS. */
480
517
  watchdogMs?: number;
518
+ /** Read on every render: true while the wide IDE chrome shows, so the editor draws its panel frame. */
519
+ panelChrome?: () => boolean;
520
+ /** The Panel action is available only in the shell's narrow chrome. */
521
+ panelButton?: () => boolean;
522
+ /** Rows the editor draws right above its rule (the mobile work row, agent questions), so no widget lands between them and the input; `hovered` is the top row under the pointer. */
523
+ topRows?: (width: number, hovered?: number) => string[];
524
+ /** A left click on one of the top rows (index into topRows). */
525
+ onTopRowClick?: (index: number) => void;
526
+ /** Open the same sheet as /gentle:panel. */
527
+ onPanelClick?: () => void;
481
528
  }
482
529
 
483
530
  const PROMPT_FRAME_ROLE = "border";
@@ -537,7 +584,12 @@ export class GentlePromptEditor extends CustomEditor {
537
584
  // quality watchdog repaints only when now() drifts past its window.
538
585
  private lastRenderAt = 0;
539
586
  private readonly deps: PromptEditorDeps;
587
+ private readonly pointerTui: TUI;
540
588
  private floatMouseLayout?: ReturnType<typeof resolvePromptLayout>;
589
+ private topRowCount = 0;
590
+ private hoveredTopRow: number | undefined;
591
+ private hoveredPanel = false;
592
+ private panelStart: number | undefined;
541
593
  // Native selection engine (shift+home/end, alt+a, replace-on-key): ported
542
594
  // from pi-select-del so the petal prompt owns the feature without factory
543
595
  // composition. Constructed with `this`; the internals probe degrades to
@@ -567,6 +619,7 @@ export class GentlePromptEditor extends CustomEditor {
567
619
  super(tui, theme, keybindings);
568
620
  this.selectionEngine = new SelectionEngine(this);
569
621
  this.deps = deps;
622
+ this.pointerTui = tui;
570
623
  this.keybindingsManager = keybindings;
571
624
  const attachments = deps.attachments;
572
625
  if (!attachments || !deps.readClipboardImage) return;
@@ -575,10 +628,16 @@ export class GentlePromptEditor extends CustomEditor {
575
628
  // segment; if a future Pi drops the method, chips degrade to plain text.
576
629
  const host = this as unknown as {
577
630
  segment?: (text: string, mode?: string) => Iterable<{ segment: string; index: number; input: string }>;
631
+ handlePaste?: (text: string) => void;
578
632
  submitValue?: () => void;
579
633
  };
580
634
  const segment = host.segment;
581
635
  if (typeof segment === "function") host.segment = (text, mode) => attachments.segment(text, segment.call(this, text, mode));
636
+ // SAFETY: Pi hands a complete bracketed paste to its private handlePaste().
637
+ // Wrapping it only turns a paste made of image paths into chips; if a future
638
+ // Pi drops the method, such a paste inserts its paths as text as before.
639
+ const handlePaste = host.handlePaste;
640
+ if (typeof handlePaste === "function") host.handlePaste = (text) => { if (!this.pasteImagePaths(attachments, text)) handlePaste.call(this, text); };
582
641
  // SAFETY: Pi empties the draft in its private submitValue() before onSubmit.
583
642
  // Counting here only marks the draft boundary; if a future Pi drops the
584
643
  // method, a late read falls back to landing in the next draft.
@@ -626,19 +685,42 @@ export class GentlePromptEditor extends CustomEditor {
626
685
  }
627
686
  try {
628
687
  if (!image) { this.piPasteImage?.(); return; }
629
- const { token } = attachments.add(image);
630
- const cursor = this.getCursor();
631
- const line = this.getLines()[cursor.line] ?? "";
632
- const before = cursor.col > 0 && !/\s/.test(line[cursor.col - 1] ?? "") ? " " : "";
633
- const after = cursor.col < line.length && !/\s/.test(line[cursor.col] ?? "") ? " " : "";
634
- this.insertTextAtCursor(`${before}${token}${after}`);
635
- this.deps.requestRender();
688
+ this.insertChip(attachments, image);
636
689
  } catch (error) {
637
690
  // Never let a paste reject unhandled: Node 24 ends the process on it.
638
691
  this.deps.notifyCompatibility?.(`Image paste failed: ${error instanceof Error ? error.message : String(error)}`);
639
692
  }
640
693
  }
641
694
 
695
+ /** One `[Image#N]` at the cursor, spaced from adjacent text. */
696
+ private insertChip(attachments: ImageAttachments, image: ClipboardImage): void {
697
+ const { token } = attachments.add(image);
698
+ const cursor = this.getCursor();
699
+ const line = this.getLines()[cursor.line] ?? "";
700
+ const before = cursor.col > 0 && !/\s/.test(line[cursor.col - 1] ?? "") ? " " : "";
701
+ const after = cursor.col < line.length && !/\s/.test(line[cursor.col] ?? "") ? " " : "";
702
+ this.insertTextAtCursor(`${before}${token}${after}`);
703
+ this.deps.requestRender();
704
+ }
705
+
706
+ /**
707
+ * Herdr (desktop app, `--remote`, drops) and file managers paste an image as
708
+ * a path. Read those synchronously and insert chips; false means the paste is
709
+ * not only image paths and Pi handles it.
710
+ */
711
+ private pasteImagePaths(attachments: ImageAttachments, text: string): boolean {
712
+ if (this.disposed || !text) return false;
713
+ let images: ClipboardImage[];
714
+ try { images = readPastedImagePaths(text); } catch { return false; }
715
+ if (images.length === 0) return false;
716
+ try {
717
+ for (const image of images) this.insertChip(attachments, image);
718
+ } catch (error) {
719
+ this.deps.notifyCompatibility?.(`Image paste failed: ${error instanceof Error ? error.message : String(error)}`);
720
+ }
721
+ return true;
722
+ }
723
+
642
724
  setAnimationPolicy(policy: AnimationPolicy): void {
643
725
  if (this.animationPolicy === policy) return;
644
726
  this.animationPolicy = policy;
@@ -1230,12 +1312,69 @@ export class GentlePromptEditor extends CustomEditor {
1230
1312
  this.deps.dispatchQueuedText(queued);
1231
1313
  }
1232
1314
 
1315
+ private clearPanelHover(): void {
1316
+ if (!this.hoveredPanel) return;
1317
+ this.hoveredPanel = false;
1318
+ this.deps.requestRender();
1319
+ }
1320
+
1321
+ private clearEditorHover(): void {
1322
+ this.clearPanelHover();
1323
+ if (this.hoveredTopRow !== undefined) {
1324
+ this.hoveredTopRow = undefined;
1325
+ this.deps.requestRender();
1326
+ }
1327
+ releaseSidebarHover(this.pointerTui, this);
1328
+ }
1329
+
1233
1330
  handleMouse(event: Parameters<CustomEditor["handleMouse"]>[0]): ReturnType<CustomEditor["handleMouse"]> {
1331
+ const onPanel = (this.deps.panelButton?.() ?? true) && this.panelStart !== undefined && this.floatMouseLayout?.panel && event.width === this.floatMouseLayout.width && event.y === this.topRowCount &&
1332
+ event.x >= this.panelStart && event.x < this.panelStart + visibleWidth(PANEL_BUTTON);
1333
+ if (event.type === "move" && event.button === "none") {
1334
+ if (onPanel || (event.y >= 0 && event.y < this.topRowCount)) setSidebarHover(this.pointerTui, this, () => this.clearEditorHover());
1335
+ else setSidebarHover(this.pointerTui);
1336
+ if (onPanel) {
1337
+ const changed = this.hoveredTopRow !== undefined || !this.hoveredPanel;
1338
+ if (this.hoveredTopRow !== undefined) { this.hoveredTopRow = undefined; this.deps.requestRender(); }
1339
+ if (!this.hoveredPanel) { this.hoveredPanel = true; this.deps.requestRender(); }
1340
+ return changed ? { handled: true, render: true } : { handled: true };
1341
+ }
1342
+ this.clearPanelHover();
1343
+ }
1344
+ if (onPanel && (event.type === "press" || event.type === "click")) {
1345
+ if (event.type === "click" && event.button === "left") {
1346
+ this.clearEditorHover();
1347
+ this.deps.onPanelClick?.();
1348
+ }
1349
+ return { handled: true, render: event.type === "click" };
1350
+ }
1351
+ // Rows drawn above the panel rule belong to the shell, not to Pi's editor.
1352
+ if (this.topRowCount > 0) {
1353
+ if (event.y < this.topRowCount) {
1354
+ // Hovering a top row paints it as clickable, like every other control.
1355
+ if (event.type === "move" && event.button === "none") {
1356
+ if (this.hoveredTopRow !== event.y) {
1357
+ this.hoveredTopRow = event.y;
1358
+ this.deps.requestRender();
1359
+ return { handled: true, render: true };
1360
+ }
1361
+ return { handled: true };
1362
+ }
1363
+ if (event.type !== "click" || event.button !== "left") return undefined;
1364
+ this.deps.onTopRowClick?.(event.y);
1365
+ return { handled: true, render: true };
1366
+ }
1367
+ if (this.hoveredTopRow !== undefined) {
1368
+ this.hoveredTopRow = undefined;
1369
+ this.deps.requestRender();
1370
+ }
1371
+ event = { ...event, y: event.y - this.topRowCount, height: event.height - this.topRowCount };
1372
+ }
1234
1373
  const layout = this.floatMouseLayout;
1235
1374
  if (!layout) return super.handleMouse(event);
1236
1375
  // Row coordinates stay native: padding=0, content=1…N, hint=N+1.
1237
- // Only float translates x; the existing neon/fallback path is unchanged.
1238
- if (event.x < layout.prefixWidth || event.x >= layout.width - 1) return undefined;
1376
+ // Float and panel translate x; the existing neon/fallback path is unchanged.
1377
+ if (event.x < layout.prefixWidth || event.x >= (layout.panel ? layout.prefixWidth + layout.nativeWidth : layout.width - 1)) return undefined;
1239
1378
  return super.handleMouse({ ...event, x: event.x - layout.prefixWidth, width: layout.nativeWidth });
1240
1379
  }
1241
1380
 
@@ -1247,8 +1386,8 @@ export class GentlePromptEditor extends CustomEditor {
1247
1386
  this.tick += 1;
1248
1387
  this.lastRenderAt = this.deps.now();
1249
1388
  }
1250
- const layout = resolvePromptLayout(width, cardStyle(), this.deps.bg);
1251
- this.floatMouseLayout = layout.background ? layout : undefined;
1389
+ const layout = resolvePromptLayout(width, cardStyle(), this.deps.bg, this.deps.panelChrome?.() ?? false);
1390
+ this.floatMouseLayout = layout.background || layout.panel ? layout : undefined;
1252
1391
  const inner = layout.nativeWidth;
1253
1392
  const lines = super.render(inner);
1254
1393
  if (this.getText() === "" && lines.length === 3) lines[1] = withPromptHint(lines[1], PROMPT_HINT, this.deps.fg);
@@ -1274,10 +1413,12 @@ export class GentlePromptEditor extends CustomEditor {
1274
1413
  const framed = framePromptLines(editorLines.slice(0, borderEnd), width, {
1275
1414
  state,
1276
1415
  tick: this.tick,
1277
- borderColor: (text) => layout.background ? this.borderColor(text) : this.deps.fg(PROMPT_FRAME_ROLE, text),
1416
+ borderColor: (text) => layout.background || layout.panel ? this.borderColor(text) : this.deps.fg(PROMPT_FRAME_ROLE, text),
1278
1417
  fg: this.deps.fg,
1279
1418
  bold: this.deps.bold,
1280
1419
  workingLabel: this.promptState === PROMPT_STATE.WORKING ? this.deps.workingLabel?.() : undefined,
1420
+ panelButton: Boolean(layout.panel && this.deps.onPanelClick && (this.deps.panelButton?.() ?? true)),
1421
+ panelHovered: this.hoveredPanel,
1281
1422
  escHint: [
1282
1423
  this.vimPolicy === "on" ? (this.vimVisual.active ? (this.vimVisual.kind === "line" ? "VISUAL LINE" : "VISUAL") : this.vimNormal ? "NORMAL" : "INSERT") : undefined,
1283
1424
  this.promptState === PROMPT_STATE.WORKING && this.isPendingEscapeCancel()
@@ -1288,13 +1429,28 @@ export class GentlePromptEditor extends CustomEditor {
1288
1429
  ].filter(Boolean).join(" · ") || undefined,
1289
1430
  }, layout);
1290
1431
  if (this.vimPolicy !== "on") {
1291
- framed[framed.length - 1] = layout.background
1292
- ? floatPromptRow(this.selectionEngine.decorateBottomRule("", layout.nativeWidth, ""), layout, (text) => this.borderColor(text))
1293
- : this.selectionEngine.decorateBottomRule(framed[framed.length - 1] ?? "", width, "╯");
1432
+ framed[framed.length - 1] = layout.panel
1433
+ ? panelPromptRow(this.selectionEngine.decorateBottomRule("", layout.nativeWidth, ""), layout, " ".repeat(layout.prefixWidth))
1434
+ : layout.background
1435
+ ? floatPromptRow(this.selectionEngine.decorateBottomRule("", layout.nativeWidth, ""), layout, (text) => this.borderColor(text))
1436
+ : this.selectionEngine.decorateBottomRule(framed[framed.length - 1] ?? "", width, "╯");
1294
1437
  }
1438
+ // The shell decides what goes above the editor (work row, agent questions) for every frame style.
1439
+ const topRows = this.deps.topRows?.(width, this.hoveredTopRow) ?? [];
1440
+ if (this.hoveredTopRow !== undefined && this.hoveredTopRow >= topRows.length) this.hoveredTopRow = undefined;
1441
+ this.topRowCount = topRows.length;
1442
+ const plainRule = stripAnsi(framed[0] ?? "");
1443
+ const panelAt = layout.panel && this.deps.onPanelClick && (this.deps.panelButton?.() ?? true) ? plainRule.lastIndexOf(PANEL_BUTTON) : -1;
1444
+ this.panelStart = panelAt < 0 ? undefined : visibleWidth(plainRule.slice(0, panelAt));
1445
+ if (this.panelStart === undefined && this.hoveredPanel) this.clearEditorHover();
1446
+ framed.unshift(...topRows);
1295
1447
  // Pi places autocomplete after its bottom border. Keep those rows below
1296
1448
  // Gentle's frame and preserve their terminal width and row coordinates.
1297
1449
  for (const line of editorLines.slice(borderEnd)) {
1450
+ if (layout.panel) {
1451
+ framed.push(panelPromptRow(line, layout, " ".repeat(layout.prefixWidth)));
1452
+ continue;
1453
+ }
1298
1454
  if (layout.background) {
1299
1455
  framed.push(floatPromptRow(line, layout, (text) => this.borderColor(text)));
1300
1456
  continue;
@@ -1309,8 +1465,15 @@ export class GentlePromptEditor extends CustomEditor {
1309
1465
  return framed;
1310
1466
  }
1311
1467
 
1468
+ invalidate(): void {
1469
+ super.invalidate();
1470
+ this.panelStart = undefined;
1471
+ this.clearEditorHover();
1472
+ }
1473
+
1312
1474
  dispose(): void {
1313
1475
  this.disposed = true;
1476
+ this.clearEditorHover();
1314
1477
  this.stopWatchdog();
1315
1478
  }
1316
1479
 
@@ -1389,7 +1552,7 @@ type PromptFactory = NonNullable<ReturnType<ExtensionContext["ui"]["getEditorCom
1389
1552
  function installPrompt(
1390
1553
  ctx: ExtensionContext,
1391
1554
  onCreated: (prompt: GentlePromptEditor) => void,
1392
- promptDeps: { now: () => number; doubleEscCancelEnabled: () => boolean; dispatchQueuedText: (text: string) => void; vimRuntimeVersion?: () => string | undefined; attachments?: ImageAttachments; readClipboardImage?: () => Promise<ClipboardImage | null> },
1555
+ promptDeps: { now: () => number; doubleEscCancelEnabled: () => boolean; dispatchQueuedText: (text: string) => void; vimRuntimeVersion?: () => string | undefined; attachments?: ImageAttachments; readClipboardImage?: () => Promise<ClipboardImage | null>; panelChrome?: (tui: TUI) => boolean; panelButton?: (tui: TUI) => boolean; topRows?: (tui: TUI, width: number, hovered?: number) => string[]; onTopRowClick?: (tui: TUI, index: number) => void; onPanelClick?: () => void },
1393
1556
  ): boolean {
1394
1557
  const previous = ctx.ui.getEditorComponent() as PromptFactory | undefined;
1395
1558
  if (previous && !previous[PROMPT_OWNER]) return false;
@@ -1408,6 +1571,11 @@ function installPrompt(
1408
1571
  workingLabel: () => oddPhaseRegistry.label(ctx.sessionManager.getSessionId()),
1409
1572
  attachments: promptDeps.attachments,
1410
1573
  readClipboardImage: promptDeps.readClipboardImage,
1574
+ panelChrome: promptDeps.panelChrome ? () => promptDeps.panelChrome!(tui) : undefined,
1575
+ panelButton: promptDeps.panelButton ? () => promptDeps.panelButton!(tui) : undefined,
1576
+ topRows: promptDeps.topRows ? (width, hovered) => promptDeps.topRows!(tui, width, hovered) : undefined,
1577
+ onTopRowClick: promptDeps.onTopRowClick ? (index) => promptDeps.onTopRowClick!(tui, index) : undefined,
1578
+ onPanelClick: promptDeps.onPanelClick,
1411
1579
  });
1412
1580
  // Pi's own docs require an explicit requestRender() after a state change
1413
1581
  // (docs/tui.md: "Call tui.requestRender() after state changes"); no host
@@ -1465,7 +1633,6 @@ function renderDoubleEscCancelReport(
1465
1633
  const CHANGES_WIDGET_KEY = "gentle-shell-changes";
1466
1634
  const HEADER_WIDGET_KEY = "gentle-shell-below-input-header";
1467
1635
  const CHANGES_COMMAND_NAME = "gentle:changes";
1468
- const CHANGES_SHORTCUT_DEFAULT = "alt+g";
1469
1636
  const CHANGES_POLL_DEFAULT_MS = 2000;
1470
1637
  const GIT_TIMEOUT_MS = 5000;
1471
1638
  const COMMANDS_COMMAND_NAME = "gentle:commands";
@@ -1514,16 +1681,17 @@ const fileRevision = (root: string): FileRevision => async (path) => {
1514
1681
  };
1515
1682
 
1516
1683
  export { openInExternalEditor, type ExternalEditorHost } from "../lib/external-editor.ts";
1517
- export function changesShortcut(env: NodeJS.ProcessEnv = process.env): string | undefined {
1518
- const value = env.GENTLE_PI_SHELL_CHANGES_KEY?.trim();
1519
- if (value === undefined) return CHANGES_SHORTCUT_DEFAULT;
1520
- return value === "" || value.toLowerCase() === "off" ? undefined : value;
1684
+ // Each key reads its environment variable, then keymaps.json, then its default (lib/keymaps.ts).
1685
+ export function changesShortcut(env: NodeJS.ProcessEnv = process.env, bindings: KeymapBindings = {}): string | undefined {
1686
+ return effectiveKey("changes", env, bindings);
1521
1687
  }
1522
1688
 
1523
- export function usageShortcut(env: NodeJS.ProcessEnv = process.env): string | undefined {
1524
- const value = env.GENTLE_PI_SHELL_USAGE_KEY?.trim();
1525
- if (value === undefined) return USAGE_SHORTCUT_DEFAULT;
1526
- return value === "" || value.toLowerCase() === "off" ? undefined : value;
1689
+ export function presetShortcut(env: NodeJS.ProcessEnv = process.env, bindings: KeymapBindings = {}): string | undefined {
1690
+ return effectiveKey("preset", env, bindings);
1691
+ }
1692
+
1693
+ export function usageShortcut(env: NodeJS.ProcessEnv = process.env, bindings: KeymapBindings = {}): string | undefined {
1694
+ return effectiveKey("usage", env, bindings);
1527
1695
  }
1528
1696
 
1529
1697
  function positiveMs(value: string | undefined, fallback: number): number {
@@ -1608,21 +1776,61 @@ async function showChangesOverlay(ctx: ExtensionContext, deps: OverlayDeps): Pro
1608
1776
  // entries that are actually registered, so a missing extension never shows
1609
1777
  // a dead row. Selecting an entry runs it exactly as if the user had typed
1610
1778
  // the underlying slash command.
1611
- async function showCommandPalette(pi: ExtensionAPI, ctx: ExtensionContext, env: NodeJS.ProcessEnv): Promise<void> {
1779
+ // Each row shows the key saved now; one that differs from the key Pi loaded at
1780
+ // startup is marked "(reload)", since Pi only applies it after /reload.
1781
+ function paletteShortcuts(pi: ExtensionAPI, env: NodeJS.ProcessEnv, loaded: KeymapBindings): Record<string, string | undefined> {
1782
+ const saved = loadKeymaps(env).bindings;
1783
+ const shortcuts: Record<string, string | undefined> = {};
1784
+ for (const { name } of pi.getCommands()) {
1785
+ const id = commandKeymapId(name);
1786
+ const now = effectiveKey(id, env, saved);
1787
+ const active = effectiveKey(id, env, loaded);
1788
+ shortcuts[name] = now === active ? now : `${now ?? "none"} (reload)`;
1789
+ }
1790
+ return shortcuts;
1791
+ }
1792
+
1793
+ /**
1794
+ * The palette commands Customize lists under Keymaps. The command list is an
1795
+ * extra there: when Pi cannot report it yet (before its runtime is
1796
+ * initialized), Customize still opens with the built-in actions only.
1797
+ */
1798
+ function paletteCommandsForKeymaps(pi: ExtensionAPI): { command: string; label: string }[] {
1799
+ try {
1800
+ return buildCommandPaletteGroups(pi.getCommands(), {}).flatMap((group) => group.items);
1801
+ } catch {
1802
+ return [];
1803
+ }
1804
+ }
1805
+
1806
+ /** Tab in the palette: assign the captured key to the command, through the same checks as /gentle:customize. */
1807
+ async function bindFromPalette(ctx: ExtensionContext, env: NodeJS.ProcessEnv, command: string, data: string, keybindings: PiKeybindings | undefined): Promise<void> {
1808
+ const id = commandKeymapId(command);
1809
+ const file = loadKeymaps(env);
1810
+ const change = prepareKeymapChange(id, data, env, file, keybindings);
1811
+ if (change.kind === "refused") return ctx.ui.notify(change.message, change.type);
1812
+ if (change.confirm && !(await ctx.ui.confirm("Keymaps", change.confirm))) return;
1813
+ writeKeymaps(gentlePiConfigHome(env), change.bindings);
1814
+ ctx.ui.notify(keymapSavedNotice(id, keymapLabel(id), env, change.bindings), "info");
1815
+ }
1816
+
1817
+ async function showCommandPalette(pi: ExtensionAPI, ctx: ExtensionContext, env: NodeJS.ProcessEnv, loaded: KeymapBindings = {}): Promise<void> {
1612
1818
  if (!ctx.hasUI) return;
1613
- const groups = buildCommandPaletteGroups(pi.getCommands(), {
1614
- "gentle:changes": changesShortcut(env),
1615
- "gentle:agents": agentsViewKey(env),
1616
- });
1819
+ const groups = buildCommandPaletteGroups(pi.getCommands(), paletteShortcuts(pi, env, loaded));
1617
1820
  if (groups.length === 0) {
1618
1821
  ctx.ui.notify("No Gentle commands are registered.", "info");
1619
1822
  return;
1620
1823
  }
1824
+ let piKeybindings: PiKeybindings | undefined;
1621
1825
  const result = await ctx.ui.custom<CommandPaletteResult>(
1622
- (tui, theme, _keybindings, done) => new CommandPalette(groups, withOverlayRepaint(tui, done), theme, () => Math.max(0, tui.terminal.rows)),
1826
+ (tui, theme, keybindings, done) => {
1827
+ if (typeof (keybindings as Partial<PiKeybindings> | undefined)?.getKeys === "function") piKeybindings = keybindings as PiKeybindings;
1828
+ return new CommandPalette(groups, withOverlayRepaint(tui, done), theme, () => Math.max(0, tui.terminal.rows));
1829
+ },
1623
1830
  { overlay: true, overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" } },
1624
1831
  );
1625
1832
  if (result?.type === "run") pi.sendUserMessage(`/${result.name}`, { expandPromptTemplates: true });
1833
+ if (result?.type === "bind") await bindFromPalette(ctx, env, result.name, result.data, piKeybindings);
1626
1834
  }
1627
1835
 
1628
1836
  function showChanges(ctx: ExtensionContext, model: ChangesModel, visible = true, grouped: (width: number) => boolean = () => false): void {
@@ -1643,7 +1851,15 @@ function showChanges(ctx: ExtensionContext, model: ChangesModel, visible = true,
1643
1851
  }
1644
1852
 
1645
1853
  const USAGE_COMMAND_NAME = "gentle:usage";
1646
- const USAGE_SHORTCUT_DEFAULT = "alt+u";
1854
+ const PANEL_COMMAND_NAME = "gentle:panel";
1855
+ /** Rows the panel sheet leaves free at the bottom: work row, editor rule, input, closing row, status bar and a spare. */
1856
+ const SHEET_RESERVED_ROWS = 6;
1857
+ const PRESET_LABEL: Record<VisualPreset, string> = { [VISUAL_PRESET.LIGHT]: "Light", [VISUAL_PRESET.NEUTRAL]: "Neutral", [VISUAL_PRESET.POWER_USER]: "Power user" };
1858
+ /** The order the preset shortcut walks; a hand-tuned mix starts it on Neutral. */
1859
+ const PRESET_CYCLE: readonly VisualPreset[] = [VISUAL_PRESET.LIGHT, VISUAL_PRESET.NEUTRAL, VISUAL_PRESET.POWER_USER];
1860
+ export function nextVisualPreset(current: VisualPreset | undefined): VisualPreset {
1861
+ return current === undefined ? VISUAL_PRESET.NEUTRAL : PRESET_CYCLE[(PRESET_CYCLE.indexOf(current) + 1) % PRESET_CYCLE.length]!;
1862
+ }
1647
1863
  const REVIEW_PREFLIGHT_TYPE = "gentle-pi.review-preflight";
1648
1864
  const DEV_BINARY_WIDGET_KEY = "gentle-shell-dev-binary";
1649
1865
  const SHA_PREFIX_LENGTH = 16;
@@ -1765,7 +1981,22 @@ export async function backgroundChangeRefreshesSettled(timeoutMs = 2000): Promis
1765
1981
 
1766
1982
  export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = process.env, overrides: Partial<ShellDeps> = {}): void {
1767
1983
  installSessionChangeCapture(pi, env, overrides.resolveWorktree ?? resolveSessionWorktree);
1984
+ // Replaced before persistence, so the footer, /gentle:stats and the session file
1985
+ // all carry the API-equivalent cost of claude-bridge turns instead of $0. It runs
1986
+ // in subagent children too: the parent sums their message_end cost over RPC.
1987
+ pi.on("message_end", (event, ctx) => {
1988
+ const priced = priceBridgeMessage(event.message, (provider, id) => ctx.modelRegistry.find(provider, id)?.cost);
1989
+ return priced ? { message: priced } : undefined;
1990
+ });
1768
1991
  if (!shellEnabled(env)) return;
1992
+ // Pi reads shortcuts once (startup and /reload), so the saved keymaps are read once too.
1993
+ const keymaps = loadKeymaps(env);
1994
+ let keymapsReported = false;
1995
+ pi.on("session_start", (_event, ctx) => {
1996
+ if (!keymaps.malformed || keymapsReported || !ctx.hasUI) return;
1997
+ keymapsReported = true;
1998
+ ctx.ui.notify(`Keymaps: ${keymaps.path} is unreadable or malformed; using the default keys.`, "warning");
1999
+ });
1769
2000
  const profileReader = createActiveProfileReader(env);
1770
2001
  const deps: ShellDeps = { ...defaultShellDeps, activeProfile: profileReader, ...overrides };
1771
2002
  let closeCustomize: (() => void) | undefined;
@@ -1775,7 +2006,8 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
1775
2006
  profilePoll = undefined;
1776
2007
  profileReader.reset();
1777
2008
  };
1778
- const usage = new UsageStore();
2009
+ // A full subscription window makes model fallbacks skip that provider until it resets.
2010
+ const usage = new UsageStore((reading) => syncUsageCooldown(reading, sharedCooldown(), Date.now()));
1779
2011
  // Providers gentle-shell has never heard of get a usage source too, when
1780
2012
  // the extension that owns them registers one on pi.events; see the
1781
2013
  // USAGE_SOURCE_EVENT subscription below.
@@ -1946,9 +2178,14 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
1946
2178
  // only that provider is forced, never the whole scope.
1947
2179
  if (resolveUsageScope(currentContext).includes(source.provider)) void refreshUsage(currentContext, true, source.provider);
1948
2180
  });
1949
- pi.on("after_provider_response", (event) => {
1950
- const parsed = parseUsageHeaders(event.headers, deps.now());
1951
- if (!parsed) return;
2181
+ pi.on("after_provider_response", (event, ctx) => {
2182
+ const headerUsage = parseUsageHeaders(event.headers, deps.now());
2183
+ if (!headerUsage) return;
2184
+ // The headers name a format, not the provider: pi-claude-bridge reports
2185
+ // Claude Code's usage as the Anthropic unified headers. File the snapshot
2186
+ // under the provider that served the response, which the bar looks up.
2187
+ const served = ctx?.model?.provider;
2188
+ const parsed = served ? { ...headerUsage, provider: served } : headerUsage;
1952
2189
  usage.record(parsed);
1953
2190
  // A snapshot that arrived with a response is evidence the provider is
1954
2191
  // answering: a failure some earlier refresh recorded no longer stands.
@@ -1962,6 +2199,105 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
1962
2199
  const hint = keyHint("app.tools.expand", options.expanded ? "collapse" : "expand");
1963
2200
  return cardComponent({ title: "Gentle AI", subtitle: "review preflight", body, tone: CARD_TONE.INFO }, theme, { expanded: options.expanded, previewRows: 3, hint });
1964
2201
  });
2202
+ // Which IDE chrome the fullscreen shell draws: "wide" while the rail owns the
2203
+ // host, "narrow" (mobile) below the rail breakpoint or with Status at the
2204
+ // bottom (the minimal edition), undefined for the below-input header, a
2205
+ // hidden Status, and regular mode.
2206
+ const chromeMode = (tui: TUI): "wide" | "narrow" | undefined => {
2207
+ if (visualSettings.headerPlacement !== "top" || (tui as TUI & { mode?: string }).mode !== "fullscreen" || !tui.terminal) return undefined;
2208
+ const state = sidebarState(tui);
2209
+ if (state.active && state.ownsHost?.()) return "wide";
2210
+ // The compact chrome replaces the bottom bar, so it only applies while the
2211
+ // layout that draws its title row and status bar is installed.
2212
+ if (!state.layoutAttached?.()) return undefined;
2213
+ const placement = visualSettings.statusPlacement;
2214
+ // "bottom" (the Light preset) is the minimal edition: the phone layout at any width, no rail.
2215
+ if (placement === "bottom") return "narrow";
2216
+ return tui.terminal.columns < SIDEBAR_BREAKPOINT && (placement === "auto" || placement === "right") ? "narrow" : undefined;
2217
+ };
2218
+ // The live-work digests the mobile work row folds, honoring the Todos switch.
2219
+ const workParts = (tui: TUI) => {
2220
+ const state = sidebarState(tui);
2221
+ return ["agents", "todo"].filter((key) => key !== "todo" || state.visibility?.todo !== false).flatMap((key) => {
2222
+ const part = state.parts.get(key);
2223
+ const summary = part?.summary?.();
2224
+ return part && summary ? [{ part, summary }] : [];
2225
+ });
2226
+ };
2227
+ const workSummaries = (tui: TUI) => workParts(tui).map((work) => work.summary);
2228
+ // A tap on the work row opens the leading section's own view (an agent opens
2229
+ // /gentle:agents); a section without one, such as Todos, opens the panel sheet.
2230
+ const openWorkRow = (tui: TUI, ctx: ExtensionContext) => {
2231
+ const parts = workParts(tui);
2232
+ const lead = parts[workRowLead(parts.map((work) => work.summary))];
2233
+ if (!lead) return;
2234
+ if (lead.part.open) lead.part.open();
2235
+ else void openPanelSheet(ctx);
2236
+ };
2237
+ // What the panel editor draws above its rule: the mobile work row, then any
2238
+ // agent question, so nothing another widget adds can land between them and the input.
2239
+ const panelTopRows = (tui: TUI, width: number, theme: Parameters<typeof renderWorkRow>[1], hovered?: number): string[] => {
2240
+ if (!tui.terminal) return [];
2241
+ const state = sidebarState(tui);
2242
+ const row = chromeMode(tui) === "narrow" ? renderWorkRow(workSummaries(tui), theme, width, hovered === 0) : undefined;
2243
+ // An agent question needs its own row whenever the above-editor Agents
2244
+ // card is hidden: the rail owns the host (any header placement) or the
2245
+ // work row folded the card.
2246
+ const cardHidden = Boolean(state.active && state.ownsHost?.()) || Boolean(state.compactWork?.());
2247
+ return [...(row ? [row] : []), ...(cardHidden ? (state.parts.get("agents")?.alert?.(width) ?? []) : [])];
2248
+ };
2249
+ // The rail's sections as a full-width sheet: /gentle:panel, or a tap on the mobile work row.
2250
+ const openPanelSheet = (ctx: ExtensionContext) =>
2251
+ ctx.ui.custom<null>(
2252
+ (tui, theme, _keybindings, done) => {
2253
+ const close = withOverlayRepaint(tui, done);
2254
+ let scrollTop = 0;
2255
+ let maxScroll = 0;
2256
+ let backHovered = false;
2257
+ let sheetWidth = 0;
2258
+ return {
2259
+ render(width: number) {
2260
+ sheetWidth = width;
2261
+ // Hang from the top and leave the bottom rows to the work row, the
2262
+ // editor and the status bar, so the input stays visible.
2263
+ // The sections live on the shell's sidebar terminal, the one its footer drew on,
2264
+ // and a section the rail hides (the Todos switch) stays hidden here too.
2265
+ const host = (sidebarTui ?? tui) as TUI;
2266
+ const rows = Math.max(4, (host.terminal?.rows ?? 24) - SHEET_RESERVED_ROWS);
2267
+ const state = sidebarState(host);
2268
+ const parts = new Map([...state.parts].filter(([key]) => key !== "todo" || state.visibility?.todo !== false));
2269
+ const sheet = renderPanelSheet(parts, theme, width, { rows, scrollTop, backHovered });
2270
+ maxScroll = sheet.maxScroll;
2271
+ scrollTop = Math.min(scrollTop, maxScroll);
2272
+ return sheet.lines;
2273
+ },
2274
+ handleInput(data: string) {
2275
+ if (matchesKey(data, Key.escape) || data === "q") { close(null); return; }
2276
+ if (matchesKey(data, Key.down) || data === "j") scrollTop = Math.min(maxScroll, scrollTop + 1);
2277
+ else if (matchesKey(data, Key.up) || data === "k") scrollTop = Math.max(0, scrollTop - 1);
2278
+ else return;
2279
+ tui.requestRender();
2280
+ },
2281
+ // `esc back` is a control too: hover paints it, a click closes the sheet; the wheel scrolls.
2282
+ handleMouse(event: TuiMouseEvent) {
2283
+ const onBack = panelSheetBackHit(sheetWidth || event.width, event.x, event.y);
2284
+ if (event.type === "move" && onBack !== backHovered) { backHovered = onBack; return { handled: true, render: true }; }
2285
+ if (event.type === "click" && event.button === "left" && onBack) { close(null); return { handled: true, render: true }; }
2286
+ if (event.type === "wheel") {
2287
+ scrollTop = Math.max(0, Math.min(maxScroll, scrollTop + Math.sign(event.wheelDelta ?? 0)));
2288
+ return { handled: true, render: true };
2289
+ }
2290
+ return undefined;
2291
+ },
2292
+ invalidate() {},
2293
+ };
2294
+ },
2295
+ { overlay: true, overlayOptions: { width: "100%", anchor: "top-center" } },
2296
+ );
2297
+ pi.registerCommand(PANEL_COMMAND_NAME, {
2298
+ description: "Show the sidebar panel (todos, jobs, agents, changes, review, integrations) as a full-width sheet.",
2299
+ handler: async (_args, ctx) => openPanelSheet(ctx),
2300
+ });
1965
2301
  const openUsage = (ctx: ExtensionContext) =>
1966
2302
  ctx.ui.custom<null>(
1967
2303
  (tui, theme, _keybindings, done) => {
@@ -1988,7 +2324,8 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
1988
2324
  description: "Show subscription usage windows for the connected providers. Press r to refetch.",
1989
2325
  handler: async (_args, ctx) => openUsage(ctx),
1990
2326
  });
1991
- const usageShortcutKey = usageShortcut(env);
2327
+ const usageShortcutKey = usageShortcut(env, keymaps.bindings);
2328
+ const todoKey = todoCollapseKey(env, keymaps.bindings);
1992
2329
  if (usageShortcutKey) {
1993
2330
  pi.registerShortcut(usageShortcutKey as Parameters<ExtensionAPI["registerShortcut"]>[0], {
1994
2331
  description: "Show subscription usage windows for the connected providers",
@@ -2048,6 +2385,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2048
2385
  let changes: WorktreeChangesTracker | undefined;
2049
2386
  let registry: SessionWorktreeRegistry | undefined;
2050
2387
  let currentContext: ExtensionContext | undefined;
2388
+ let disposeFooter: (() => void) | undefined;
2051
2389
  let review: ReviewSidebarSnapshot | undefined;
2052
2390
  let runningJobs: RunningJobDisplay[] | undefined;
2053
2391
  let jobsCollapsed = false;
@@ -2145,6 +2483,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2145
2483
  changes = changesTracker(ctx);
2146
2484
  const tracker = changes;
2147
2485
  ctx.ui.setFooter((tui, theme, footerData) => {
2486
+ disposeFooter?.();
2148
2487
  sidebarTui = tui;
2149
2488
  if (tui.terminal) sidebarState(tui).visibility = { todo: visualSettings.visibility.todo };
2150
2489
  renderHost = { requestRender: () => tui.requestRender(), invalidateSidebar: () => invalidateSidebar(tui) };
@@ -2159,6 +2498,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2159
2498
  pi, ctx, footerData,
2160
2499
  usage: () => usage.get(ctx.model?.provider ?? ""),
2161
2500
  profile: () => deps.activeProfile(),
2501
+ profileTier: () => deps.activeProfile === profileReader ? profileReader.tier() : undefined,
2162
2502
  // The compact bar and header derive ⧗ N jobs from model.jobs.length,
2163
2503
  // so this input is running-only: the snapshot carries the finished tail.
2164
2504
  jobs: () => runningJobs?.filter((job) => job.status === undefined),
@@ -2194,10 +2534,79 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2194
2534
  return { handled: true, render: true };
2195
2535
  },
2196
2536
  };
2537
+ // The rail's Status is a panel: Changes, Review and Integrations, then
2538
+ // the key hints that close the rail (the section headers carry none).
2539
+ const railHints = [todoKey ? `${todoKey} todos` : "", usageShortcutKey ? `${usageShortcutKey} usage` : "", "/ commands"].filter(Boolean).join(" · ");
2540
+ // Status sections are clickable like the other rail sections: a header
2541
+ // folds its section, the Changes row opens /gentle:changes.
2542
+ const statusCollapsed = new Set<StatusSection>();
2543
+ let statusHover: StatusSection | "open-changes" | undefined;
2544
+ // Keyed by width: the rail and the full-width panel sheet render the same part.
2545
+ const statusTargets = new Map<number, StatusTarget[]>();
2546
+ const statusCard: Component = {
2547
+ render(width: number) {
2548
+ // The rail drops what the wide chrome's title row and status bar show
2549
+ // (session, permission mode) only while that chrome actually draws.
2550
+ const view = statusCardVisible() && visualSettings.headerPlacement === "top"
2551
+ ? renderShellStatusSections(withStats(footerModel()), theme, width, visualSettings, railHints, { collapsed: statusCollapsed, hovered: statusHover })
2552
+ : renderShellStatusSections(withStats({ ...footerModel(), integrations: undefined, permission: undefined }), theme, width, visualSettings, railHints, { session: true, collapsed: statusCollapsed, hovered: statusHover });
2553
+ statusTargets.set(width, view.targets);
2554
+ return view.lines;
2555
+ },
2556
+ invalidate() {
2557
+ statusHover = undefined;
2558
+ },
2559
+ };
2560
+ // The Stats section (on in Power user); walked once per session leaf, like sessionStats.
2561
+ let statsMemo: { key: SessionStatsKey | undefined; stats: SessionStats } | undefined;
2562
+ const currentStats = (): SessionStats => {
2563
+ const key = sessionStatsKey(ctx);
2564
+ if (key && statsMemo?.key && statsMemo.key.every((value, index) => value === key[index])) return statsMemo.stats;
2565
+ const stats = collectSessionStats(ctx.sessionManager.getEntries());
2566
+ statsMemo = { key, stats };
2567
+ return stats;
2568
+ };
2569
+ const statsOn = () => visualSettings.visibility.stats;
2570
+ // Subagent spend comes from the Agents section, which owns the task records.
2571
+ const subagentSpend = () => sidebarState(tui).parts.get("agents")?.spend?.();
2572
+ const withStats = (model: ShellBarModel): ShellBarModel => (statsOn() ? { ...model, stats: { ...currentStats(), subagents: subagentSpend() } } : model);
2573
+ const targetAt = (y: number, width: number) => statusTargets.get(width)?.find((target) => target.row === y);
2574
+ const statusRegion = new NativePointerRegion(statusCard, {
2575
+ onHover(event) {
2576
+ const target = targetAt(event.y, event.width);
2577
+ const next = !target ? undefined : target.kind === "toggle" ? target.section : "open-changes";
2578
+ if (next) setSidebarHover(tui, statusRegion, () => statusRegion.clearHover());
2579
+ else setSidebarHover(tui);
2580
+ if (next === statusHover) return { handled: true };
2581
+ statusHover = next;
2582
+ return { handled: true, render: true };
2583
+ },
2584
+ onLeave() {
2585
+ releaseSidebarHover(tui, statusRegion);
2586
+ if (!statusHover) return;
2587
+ statusHover = undefined;
2588
+ tui.requestRender();
2589
+ },
2590
+ onClick(event) {
2591
+ const target = event.button === "left" ? targetAt(event.y, event.width) : undefined;
2592
+ if (!target) return undefined;
2593
+ if (target.kind === "open-changes") void openChanges(ctx);
2594
+ else if (statusCollapsed.has(target.section)) statusCollapsed.delete(target.section);
2595
+ else statusCollapsed.add(target.section);
2596
+ invalidateSidebar(tui);
2597
+ return { handled: true, render: true };
2598
+ },
2599
+ });
2197
2600
  const part = sidebarPart(tui, "footer", bottomBar, {
2198
- digest: () => footerStatus.key(),
2199
- render: (width) => renderShellSidebarBar(footerModel(), theme, width, visualSettings),
2200
- invalidate() {},
2601
+ surface: "panel",
2602
+ digest: () => {
2603
+ const stats = statsOn() ? currentStats() : undefined;
2604
+ const spend = stats ? subagentSpend() : undefined;
2605
+ return JSON.stringify([footerStatus.key(), [...statusCollapsed], statusHover ?? "", stats ? [stats.turns, stats.toolCalls, stats.cost, stats.spanMs, spend?.runs, spend?.tokens, spend?.cost] : ""]);
2606
+ },
2607
+ render: (width) => statusRegion.render(width),
2608
+ handleMouse: (event) => statusRegion.handleMouse(event),
2609
+ invalidate: () => statusRegion.invalidate(),
2201
2610
  });
2202
2611
  // The Jobs card: its own rail section, like Agents and Todos, fed by the
2203
2612
  // same running-job display snapshot the Status card used to print. The
@@ -2210,9 +2619,10 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2210
2619
  render(width: number) {
2211
2620
  const jobs = runningJobs ?? [];
2212
2621
  if (jobs.length === 0) { jobsPainted = false; return []; }
2213
- const lines = renderJobsCard(jobs, theme, width, deps.now(), { collapsed: jobsCollapsed, collapseKey: jobsKey, collapseControl: true, hovered: jobsHovered });
2622
+ // The rail draws Jobs as a panel section: its header is row 0.
2623
+ const lines = renderJobsSection(jobs, theme, width, deps.now(), { collapsed: jobsCollapsed, hovered: jobsHovered });
2214
2624
  jobsPainted = lines.length > 0;
2215
- jobsHeaderRow = jobsPainted ? panelHeaderRow(theme, width, jobsCardTone(jobs)) : 0;
2625
+ jobsHeaderRow = 0;
2216
2626
  return lines;
2217
2627
  },
2218
2628
  invalidate() {
@@ -2222,11 +2632,14 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2222
2632
  const jobsRegion = new NativePointerRegion(jobsRailCard, {
2223
2633
  onHover(event) {
2224
2634
  const next = event.y === jobsHeaderRow;
2635
+ if (next) setSidebarHover(tui, jobsRegion, () => jobsRegion.clearHover());
2636
+ else setSidebarHover(tui);
2225
2637
  if (next === jobsHovered) return { handled: true };
2226
2638
  jobsHovered = next;
2227
2639
  return { handled: true, render: true };
2228
2640
  },
2229
2641
  onLeave() {
2642
+ releaseSidebarHover(tui, jobsRegion);
2230
2643
  if (!jobsHovered) return;
2231
2644
  jobsHovered = false;
2232
2645
  tui.requestRender();
@@ -2239,7 +2652,8 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2239
2652
  return { handled: true, render: true };
2240
2653
  },
2241
2654
  });
2242
- const jobsRail: Component & { digest(): string; dispose(): void } = {
2655
+ const jobsRail: Component & { digest(): string; dispose(): void; surface: "panel" } = {
2656
+ surface: "panel",
2243
2657
  digest: () => JSON.stringify([jobsCollapsed, jobsHovered, runningJobs, Math.floor(deps.now() / 1000)]),
2244
2658
  render: (width) => jobsRegion.render(width),
2245
2659
  handleMouse: (event) => jobsRegion.handleMouse(event),
@@ -2265,28 +2679,61 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2265
2679
  // effort, context, cost, usage) plus session identity and the jobs count
2266
2680
  // when Status is absent. Opaque statuses and working state stay excluded.
2267
2681
  const headerBar = (width: number) => renderShellHeaderChrome(buildShellHeaderModel(footerModel(), !statusCardVisible() && (statusOwner() === STATUS_OWNER.HEADER || visualSettings.statusPlacement === "hidden")), theme, width, usageShortcutKey, visualSettings, gaugePaint(ctx));
2682
+ // With the rail shown and the header on top, the chrome splits like an
2683
+ // IDE: a title row with the project identity above, and a status bar
2684
+ // with the per-frame counters below (design/shell-rework/02-proposal.html).
2685
+ const ideChrome = () => statusCardVisible() && visualSettings.headerPlacement === "top";
2686
+ // Mobile (design/shell-rework/05-mobile.html): below the rail breakpoint the
2687
+ // same split stays, with the model in the title row and live work folded
2688
+ // into one row above the editor.
2689
+ const narrowChrome = () => chromeMode(tui) === "narrow";
2690
+ if (tui.terminal) {
2691
+ sidebarState(tui).compactWork = narrowChrome;
2692
+ // Both IDE chromes draw a status bar that shows the permission mode.
2693
+ sidebarState(tui).statusBarShowsMode = () => chromeMode(tui) !== undefined;
2694
+ }
2695
+ const statusBarChrome = (width: number) => narrowChrome()
2696
+ ? renderShellStatusBar(footerModel(), theme, width, usageShortcutKey, { ...visualSettings, visibility: { ...visualSettings.visibility, modelDetails: false } }, gaugePaint(ctx), { jobs: true })
2697
+ : renderShellStatusBar(footerModel(), theme, width, usageShortcutKey, visualSettings, gaugePaint(ctx));
2268
2698
  const disposeHeader = sidebarHeader(tui, {
2269
2699
  digest: () => footerStatus.key(),
2270
- render: (width) => headerBar(width).rows,
2700
+ render: (width) => ideChrome() ? [renderShellTitleRow(footerModel(), theme, width)] : narrowChrome() ? [renderShellTitleRow(footerModel(), theme, width, { model: true })] : headerBar(width).rows,
2271
2701
  invalidate() {},
2272
2702
  handleMouse(event) {
2273
- if (event.type !== "click" || event.button !== "left") return undefined;
2703
+ if (ideChrome() || narrowChrome() || event.type !== "click" || event.button !== "left") return undefined;
2274
2704
  if (!shellHeaderUsageHit(headerBar(event.width), event.x, event.y)) return undefined;
2275
2705
  void openUsage(ctx);
2276
2706
  return { handled: true, render: true };
2277
2707
  },
2278
2708
  });
2709
+ const disposeStatusBar = sidebarStatusBar(tui, {
2710
+ digest: () => footerStatus.key(),
2711
+ render: (width) => ideChrome() || narrowChrome() ? statusBarChrome(width).rows : [],
2712
+ invalidate() {},
2713
+ handleMouse(event) {
2714
+ if (!(ideChrome() || narrowChrome()) || event.type !== "click" || event.button !== "left") return undefined;
2715
+ if (!shellHeaderUsageHit(statusBarChrome(event.width), event.x, event.y)) return undefined;
2716
+ void openUsage(ctx);
2717
+ return { handled: true, render: true };
2718
+ },
2719
+ });
2279
2720
  const uninstall = installSidebar(tui, theme, () => visualSettings.statusPlacement, () => visualSettings.headerPlacement, () => visualSettings.density);
2721
+ // A light theme paints the whole fullscreen frame (prose, gaps, the
2722
+ // column beside the rail) instead of leaving the terminal's dark cells.
2723
+ const unpaintPage = installPagePaint(tui as never, () => ((tui as TUI & { mode?: string }).mode === "fullscreen" ? ctx.ui.theme as PageTheme : {}));
2280
2724
  // The public widget slot follows the editor even when the rail is absent.
2281
2725
  const belowHeader = () => visualSettings.headerPlacement === "below-input" && (tui as TUI & { mode?: string }).mode === "fullscreen" && statusOwner() !== STATUS_OWNER.BOTTOM;
2282
2726
  const widgetChrome = (width: number) => belowFloat(width, false) ?? headerBar(width);
2727
+ let disposed = false;
2283
2728
  ctx.ui.setWidget(HEADER_WIDGET_KEY, () => ({
2284
2729
  render(width: number) {
2730
+ if (disposed) return [];
2285
2731
  if (belowFloat(width, false)) return footerSuppressed() ? widgetChrome(width).rows : [];
2286
2732
  return belowHeader() ? headerBar(width).rows : [];
2287
2733
  },
2288
2734
  invalidate() {},
2289
2735
  handleMouse(event) {
2736
+ if (disposed) return undefined;
2290
2737
  const grouped = belowFloat(event.width, false);
2291
2738
  if ((grouped ? !footerSuppressed() : !belowHeader()) || event.type !== "click" || event.button !== "left") return undefined;
2292
2739
  if (!shellHeaderUsageHit(widgetChrome(event.width), event.x, event.y)) return undefined;
@@ -2294,8 +2741,27 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2294
2741
  return { handled: true, render: true };
2295
2742
  },
2296
2743
  }), { placement: "belowEditor" });
2744
+ // Pi still owns the footer component; shutdown releases its session-bound
2745
+ // hooks before the old context becomes invalid, even if Pi disposes later.
2746
+ const dispose = () => {
2747
+ if (disposed) return;
2748
+ disposed = true;
2749
+ if (disposeFooter === dispose) disposeFooter = undefined;
2750
+ clearInterval(jobsTimer);
2751
+ jobsPart.dispose();
2752
+ ctx.ui.setWidget(HEADER_WIDGET_KEY, undefined);
2753
+ disposeHeader();
2754
+ disposeStatusBar();
2755
+ statusRegion.dispose();
2756
+ uninstall();
2757
+ unpaintPage();
2758
+ part.dispose();
2759
+ if (sidebarTui === tui) { sidebarTui = undefined; renderHost = undefined; groupedChangesOwner = () => false; }
2760
+ };
2761
+ disposeFooter = dispose;
2297
2762
  return { ...part,
2298
2763
  render(width: number) {
2764
+ if (disposed) return [];
2299
2765
  // Running-only: a finished tail must never paint a ⧗ 0 jobs row.
2300
2766
  const compactRunningJobs = runningJobs?.filter((job) => job.status === undefined);
2301
2767
  if (visualSettings.statusPlacement === "hidden" && (tui as TUI & { mode?: string }).mode !== "fullscreen" && compactRunningJobs?.length) {
@@ -2306,7 +2772,10 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2306
2772
  return rows.length === 0 && (tui as TUI & { mode?: string }).mode === "fullscreen"
2307
2773
  && resolvePromptLayout(width, cardStyle(), theme.bg?.bind(theme)).background ? [""] : rows;
2308
2774
  },
2309
- dispose() { clearInterval(jobsTimer); jobsPart.dispose(); ctx.ui.setWidget(HEADER_WIDGET_KEY, undefined); disposeHeader(); uninstall(); part.dispose(); if (sidebarTui === tui) { sidebarTui = undefined; groupedChangesOwner = () => false; } } };
2775
+ handleMouse(event: Parameters<NonNullable<SidebarRail["handleMouse"]>>[0]) {
2776
+ return disposed ? undefined : part.handleMouse?.(event);
2777
+ },
2778
+ dispose };
2310
2779
  });
2311
2780
  void refreshUsage(ctx, true);
2312
2781
  const ownsPrompt = installPrompt(
@@ -2317,7 +2786,14 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2317
2786
  prompt.setAnimationPolicy(animationPolicy);
2318
2787
  prompt.setVimPolicy(vimPolicy);
2319
2788
  },
2320
- { now: () => deps.now(), doubleEscCancelEnabled: () => doubleEscCancelPolicy === "on", dispatchQueuedText: (text) => { pendingQueuedText = pendingQueuedText === undefined ? text : `${pendingQueuedText}\n\n${text}`; }, vimRuntimeVersion: deps.vimRuntimeVersion, attachments: imageAttachments, readClipboardImage: () => (deps.readClipboardImage ?? readClipboardImage)() },
2789
+ { now: () => deps.now(), doubleEscCancelEnabled: () => doubleEscCancelPolicy === "on", dispatchQueuedText: (text) => { pendingQueuedText = pendingQueuedText === undefined ? text : `${pendingQueuedText}\n\n${text}`; }, vimRuntimeVersion: deps.vimRuntimeVersion, attachments: imageAttachments, readClipboardImage: () => (deps.readClipboardImage ?? readClipboardImage)(),
2790
+ // The editor joins the wide IDE chrome while the rail owns the host with the header on top.
2791
+ panelChrome: (tui) => chromeMode(tui) !== undefined,
2792
+ panelButton: (tui) => chromeMode(tui) === "narrow",
2793
+ topRows: (tui, width, hovered) => panelTopRows(tui, width, ctx.ui.theme, hovered),
2794
+ // The mobile work row is the first top row; a tap on it opens the leading section's view.
2795
+ onTopRowClick: (tui, index) => { if (chromeMode(tui) === "narrow" && index === 0) openWorkRow(tui, ctx); },
2796
+ onPanelClick: () => { void openPanelSheet(ctx); } },
2321
2797
  );
2322
2798
  imageAttachments.clear();
2323
2799
  ctx.ui.setWidget(IMAGE_ATTACHMENTS_WIDGET_KEY, ownsPrompt
@@ -2356,6 +2832,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2356
2832
  return { action: "transform", text: submitted.text, images: [...(event.images ?? []), ...submitted.images] };
2357
2833
  });
2358
2834
  pi.on("session_shutdown", (_event, ctx) => {
2835
+ disposeFooter?.();
2359
2836
  closeCustomize?.();
2360
2837
  if (review) {
2361
2838
  review = undefined;
@@ -2409,7 +2886,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2409
2886
  description: "Browse uncommitted Git changes (working tree vs HEAD, untracked included) in this session's repository and its subagents' worktrees. Press o to open $EDITOR.",
2410
2887
  handler: async (_args, ctx) => openChanges(ctx),
2411
2888
  });
2412
- const shortcut = changesShortcut(env);
2889
+ const shortcut = changesShortcut(env, keymaps.bindings);
2413
2890
  if (shortcut) {
2414
2891
  pi.registerShortcut(shortcut as Parameters<ExtensionAPI["registerShortcut"]>[0], {
2415
2892
  description: "Open the session's uncommitted Git changes",
@@ -2418,16 +2895,32 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2418
2895
  }
2419
2896
  pi.registerCommand(COMMANDS_COMMAND_NAME, {
2420
2897
  description: "Open the command palette: a curated, grouped menu of Gentle commands.",
2421
- handler: async (_args, ctx) => showCommandPalette(pi, ctx, env),
2898
+ handler: async (_args, ctx) => showCommandPalette(pi, ctx, env, keymaps.bindings),
2422
2899
  });
2423
- const commandsShortcut = commandsKey(env);
2900
+ const commandsShortcut = commandsKey(env, keymaps.bindings);
2424
2901
  if (commandsShortcut) {
2425
2902
  pi.registerShortcut(commandsShortcut as Parameters<ExtensionAPI["registerShortcut"]>[0], {
2426
2903
  description: "Open the command palette",
2427
- handler: async (ctx) => showCommandPalette(pi, ctx, env),
2904
+ handler: async (ctx) => showCommandPalette(pi, ctx, env, keymaps.bindings),
2428
2905
  });
2429
2906
  }
2430
- const jobsKey = jobsCollapseKey(env);
2907
+ // A palette command the user gave a key runs exactly as if typed.
2908
+ for (const id of commandKeymapIds(keymaps.bindings)) {
2909
+ const key = effectiveKey(id, env, keymaps.bindings);
2910
+ const command = keymapCommand(id);
2911
+ if (!key || !command) continue;
2912
+ pi.registerShortcut(key as Parameters<ExtensionAPI["registerShortcut"]>[0], {
2913
+ description: `Run /${command}`,
2914
+ handler: async (ctx) => {
2915
+ if (!pi.getCommands().some((registered) => registered.name === command)) {
2916
+ ctx.ui.notify(`${key} runs /${command}, which is not available in this session.`, "warning");
2917
+ return;
2918
+ }
2919
+ pi.sendUserMessage(`/${command}`, { expandPromptTemplates: true });
2920
+ },
2921
+ });
2922
+ }
2923
+ const jobsKey = jobsCollapseKey(env, keymaps.bindings);
2431
2924
  if (jobsKey) {
2432
2925
  pi.registerShortcut(jobsKey as Parameters<ExtensionAPI["registerShortcut"]>[0], {
2433
2926
  description: "Collapse or expand the jobs card",
@@ -2438,6 +2931,24 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2438
2931
  },
2439
2932
  });
2440
2933
  }
2934
+ const presetKey = presetShortcut(env, keymaps.bindings);
2935
+ if (presetKey) {
2936
+ pi.registerShortcut(presetKey as Parameters<ExtensionAPI["registerShortcut"]>[0], {
2937
+ description: "Cycle the visual preset: Light, Neutral, Power user",
2938
+ handler: async (ctx) => {
2939
+ const current = resolveVisualSettings(animationOptions);
2940
+ if (current.malformed || current.readError) {
2941
+ ctx.ui.notify(`Cannot switch presets: unreadable or malformed visual settings (${current.globalFile}).`, "error");
2942
+ return;
2943
+ }
2944
+ const next = nextVisualPreset(visualPresetOf(current.settings));
2945
+ writeVisualSettings(applyVisualPreset(current.settings, next), animationOptions);
2946
+ refreshVisual();
2947
+ pi.events.emit(VISUAL_SETTINGS_CHANGED, { configHome: doubleEscCancelConfigHome });
2948
+ ctx.ui.notify(`Preset: ${PRESET_LABEL[next]}`, "info");
2949
+ },
2950
+ });
2951
+ }
2441
2952
  pi.registerCommand("gentle:customize", {
2442
2953
  description: "Configure appearance, audio notifications, Vim editing, session permissions and global Auto/YOLO defaults, and prompt history capture.",
2443
2954
  handler: async (_args, ctx) => {
@@ -2467,10 +2978,11 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2467
2978
  let activeTheme = ctx.ui.theme.name;
2468
2979
  let requestCustomizeRender: (() => void) | undefined;
2469
2980
  let category: CustomizeCategory = "Animations";
2470
- const add = (label: CustomizeRow["label"], notice: string, action: () => void | false | Promise<void | false>, preview?: CustomizeRow["preview"]) => rows.push({ category, label, preview, action: async () => {
2981
+ const add = (label: CustomizeRow["label"], notice: string, action: () => void | false | Promise<void | false>, preview?: CustomizeRow["preview"], choice?: CustomizeRow["choice"]) => rows.push({ category, label, preview, choice, action: async () => {
2471
2982
  if (await action() === false) return;
2472
2983
  ctx.ui.notify(notice, "info");
2473
2984
  } });
2985
+ const explicitChoice = (setting: string, value: string, current: () => boolean): CustomizeRow["choice"] => ({ setting, value, current, applyOnMove: false });
2474
2986
  for (const policy of ["quality", "performance", "potato"] as const) add(
2475
2987
  () => `Animations: ${policy}${resolveAnimationPolicy(animationOptions).policy === policy ? " (current)" : ""}`,
2476
2988
  "Animation saved. Prompt applies now; startup banner applies at next startup.",
@@ -2480,6 +2992,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2480
2992
  prompt?.setAnimationPolicy(animationPolicy);
2481
2993
  },
2482
2994
  () => ({ title: `${policy} · static animation sample`, sample: policy === "potato" ? "✿ idle → working (no pulse)" : policy === "performance" ? "✿ short pulse → settle (static)" : "✿ gentle wave → settle (static)" }),
2995
+ { setting: "Animations", value: policy, current: () => resolveAnimationPolicy(animationOptions).policy === policy, hint: "Prompt and startup motion; potato turns it off" },
2483
2996
  );
2484
2997
  category = "Banner";
2485
2998
  const bannerColors = { pink: [255, 118, 195], cyan: [95, 210, 255], yellow: [255, 210, 95], green: [110, 220, 145] } as const;
@@ -2487,23 +3000,25 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2487
3000
  const [r, g, b] = bannerColors[next.color];
2488
3001
  return { title: `Banner · ${next.color} (static)`, sample: `${next.showRose ? `\x1b[38;2;${r};${g};${b}m🌹\x1b[0m` : "·"} ${next.showTextLogo ? "GENTLE SHELL" : "(logo hidden)"}` };
2489
3002
  };
2490
- add(() => `Banner rose: ${banner.showRose ? "on" : "off"}`, "Banner saved; applies at next startup.", async () => {
2491
- const next = { ...await readBannerConfigForEdit(bannerHome) };
2492
- next.showRose = !next.showRose;
2493
- await writeBannerConfig(next, bannerHome);
2494
- banner = next;
2495
- }, () => bannerPreview({ ...banner, showRose: !banner.showRose }));
2496
- add(() => `Banner text logo: ${banner.showTextLogo ? "on" : "off"}`, "Banner saved; applies at next startup.", async () => {
2497
- const next = { ...await readBannerConfigForEdit(bannerHome) };
2498
- next.showTextLogo = !next.showTextLogo;
2499
- await writeBannerConfig(next, bannerHome);
2500
- banner = next;
2501
- }, () => bannerPreview({ ...banner, showTextLogo: !banner.showTextLogo }));
3003
+ for (const [setting, key] of [["Banner rose", "showRose"], ["Banner text logo", "showTextLogo"]] as const) {
3004
+ for (const enabled of [true, false]) add(
3005
+ () => `${setting}: ${enabled ? "on" : "off"}${banner[key] === enabled ? " (current)" : ""}`,
3006
+ "Banner saved; applies at next startup.",
3007
+ async () => {
3008
+ const next = { ...await readBannerConfigForEdit(bannerHome), [key]: enabled };
3009
+ await writeBannerConfig(next, bannerHome);
3010
+ banner = next;
3011
+ },
3012
+ () => bannerPreview({ ...banner, [key]: enabled }),
3013
+ explicitChoice(setting, enabled ? "on" : "off", () => banner[key] === enabled),
3014
+ );
3015
+ }
2502
3016
  for (const color of BANNER_COLORS) add(
2503
3017
  () => `Banner color: ${color}${banner.color === color ? " (current)" : ""}`,
2504
3018
  "Banner saved; applies at next startup.",
2505
3019
  async () => { const next = { ...await readBannerConfigForEdit(bannerHome), color }; await writeBannerConfig(next, bannerHome); banner = next; },
2506
3020
  () => bannerPreview({ ...banner, color }),
3021
+ { setting: "Banner color", value: color, current: () => banner.color === color, hint: "Startup banner color; applies at next startup" },
2507
3022
  );
2508
3023
  category = "Themes";
2509
3024
  try {
@@ -2515,6 +3030,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2515
3030
  for (const name of names) rows.push({
2516
3031
  category,
2517
3032
  label: () => `Theme: ${name}${activeTheme === name ? " (current)" : ""}`,
3033
+ choice: explicitChoice("Theme", name, () => activeTheme === name),
2518
3034
  preview: () => {
2519
3035
  const selected = ctx.ui.getTheme(name);
2520
3036
  if (selected?.name !== name) throw new Error("Selected theme is unavailable.");
@@ -2543,12 +3059,14 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2543
3059
  const pending = "Preference saved and applied.";
2544
3060
  const layoutPreview = (settings: ReturnType<typeof visual>) => ({
2545
3061
  title: `Layout · ${settings.density} (schematic)`,
2546
- sample: `${settings.headerPlacement === "top" ? "[Header] → [Input]" : "[Input] → [Header]"} ${settings.statusPlacement === "auto" ? "[responsive status]" : settings.statusPlacement === "right" ? "[Right rail, wide]" : settings.statusPlacement === "hidden" ? "[No status bar or rail]" : "[Bottom status]"}`,
3062
+ sample: layoutSchematic(settings),
2547
3063
  });
3064
+ const layoutChoice = (setting: string, value: string, current: () => boolean, hint: string): CustomizeRow["choice"] => ({ setting, value, current, hint });
2548
3065
  category = "Editor";
2549
3066
  for (const [label, policy] of [["enable", "on"], ["disable", "off"]] as const) rows.push({
2550
3067
  category,
2551
3068
  label: () => `Vim: ${label}${resolveVimPolicy(animationOptions).policy === policy ? " (current preference)" : ""}`,
3069
+ choice: explicitChoice("Vim", policy, () => resolveVimPolicy(animationOptions).policy === policy),
2552
3070
  preview: () => {
2553
3071
  const result = resolveVimPolicy(animationOptions);
2554
3072
  const effective = prompt?.effectiveVimPolicy ?? "no active prompt";
@@ -2592,23 +3110,25 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2592
3110
  })().finally(() => { refreshing = undefined; });
2593
3111
  return refreshing;
2594
3112
  };
2595
- rows.push({
3113
+ for (const value of [YOLO_DISPLAY.on, YOLO_DISPLAY.off]) rows.push({
2596
3114
  category,
2597
- label: () => `YOLO: ${yoloDisplay} · session only`,
2598
- preview: () => ({ title: "YOLO · session permission", sample: "ordinary scoped commits/push/PR · destructive confirmations remain · review consent unchanged · reset on reload" }),
3115
+ label: () => `YOLO: ${value} · session only`,
3116
+ choice: explicitChoice("YOLO", value, () => yoloDisplay === value),
3117
+ preview: () => ({ title: `YOLO: ${yoloDisplay} · session only`, sample: "ordinary scoped commits/push/PR · destructive confirmations remain · review consent unchanged · reset on reload" }),
2599
3118
  action: async () => {
2600
3119
  if (closed) return;
2601
3120
  if (!adapter || yoloDisplay === YOLO_DISPLAY.unavailable) {
2602
3121
  ctx.ui.notify("YOLO is unavailable in this live primary session.", "warning");
2603
3122
  return;
2604
3123
  }
2605
- await adapter.toggle();
3124
+ if (yoloDisplay !== value) await adapter.toggle();
2606
3125
  await refreshYolo();
2607
3126
  },
2608
3127
  });
2609
3128
  for (const mode of ["normal", "auto", "yolo", "super-yolo"] as const) rows.push({
2610
3129
  category,
2611
3130
  label: () => `Session permissions: ${mode.toUpperCase()}${mode === "auto" ? " (beta)" : ""}${permissionDisplay === mode ? " (current)" : ""}`,
3131
+ choice: explicitChoice("Session permissions", mode === "auto" ? "AUTO (beta)" : mode.toUpperCase(), () => permissionDisplay === mode),
2612
3132
  preview: () => ({ title: "Permissions · current session", sample: mode === "auto"
2613
3133
  ? "independent session-model action checks · extra inference cost · hard safety and native consent remain"
2614
3134
  : mode === "yolo" ? "ordinary scoped delivery permission · destructive confirmations remain"
@@ -2623,6 +3143,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2623
3143
  for (const mode of ["normal", "auto", "yolo", "super-yolo"] as const) rows.push({
2624
3144
  category,
2625
3145
  label: () => `Default permissions: ${mode.toUpperCase()}${mode === "auto" ? " (beta)" : ""}${permissionDefault === mode ? " (saved)" : ""}`,
3146
+ choice: explicitChoice("Default permissions", mode === "auto" ? "AUTO (beta)" : mode.toUpperCase(), () => permissionDefault === mode),
2626
3147
  preview: () => ({ title: "Permissions · user-global default", sample: `New primary sessions start in ${mode.toUpperCase()}; current session stays unchanged. ${mode === "auto" ? "Additional classifier inference uses the session model; usage is separate." : "Independent safety and consent remain."}` }),
2627
3148
  action: async () => {
2628
3149
  if (closed) return;
@@ -2641,6 +3162,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2641
3162
  const result = historyCapture();
2642
3163
  return `Prompt history capture: ${label}${result.preference === policy && !result.malformed ? " (current)" : ""}${result.envOverride ? " · env override" : ""}`;
2643
3164
  },
3165
+ choice: explicitChoice("History capture", policy, () => { const result = historyCapture(); return result.preference === policy && !result.malformed; }),
2644
3166
  preview: () => {
2645
3167
  const result = historyCapture();
2646
3168
  const effective = result.enabled ? "on" : "off";
@@ -2657,9 +3179,15 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2657
3179
  });
2658
3180
  rows.push(...buildNotificationRows(ctx));
2659
3181
  category = "Layout";
2660
- for (const value of Object.values(STATUS_PLACEMENT)) add(() => `Status placement: ${value}${visual().statusPlacement === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, statusPlacement: value })), () => layoutPreview({ ...visual(), statusPlacement: value }));
2661
- for (const value of Object.values(HEADER_PLACEMENT)) add(() => `Header placement: ${value}${visual().headerPlacement === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, headerPlacement: value })), () => layoutPreview({ ...visual(), headerPlacement: value }));
2662
- for (const value of Object.values(DENSITY)) add(() => `Density: ${value}${visual().density === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, density: value })), () => layoutPreview({ ...visual(), density: value }));
3182
+ // Presets set density and visibility together and keep the placements; any switch below still overrides them.
3183
+ for (const preset of Object.values(VISUAL_PRESET)) add(() => `Preset: ${PRESET_LABEL[preset]}${visualPresetOf(visual()) === preset ? " (current)" : ""}`, pending, () => updateVisual((settings) => applyVisualPreset(settings, preset)), () => layoutPreview(applyVisualPreset(visual(), preset)),
3184
+ layoutChoice("Preset", PRESET_LABEL[preset], () => visualPresetOf(visual()) === preset, "Light hides the rail, Power user adds Stats; alt+l cycles them"));
3185
+ for (const value of Object.values(STATUS_PLACEMENT)) add(() => `Status placement: ${value}${visual().statusPlacement === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, statusPlacement: value })), () => layoutPreview({ ...visual(), statusPlacement: value }),
3186
+ layoutChoice("Status", value, () => visual().statusPlacement === value, "Where Status lives; auto uses the rail from 140 columns"));
3187
+ for (const value of Object.values(HEADER_PLACEMENT)) add(() => `Header placement: ${value}${visual().headerPlacement === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, headerPlacement: value })), () => layoutPreview({ ...visual(), headerPlacement: value }),
3188
+ layoutChoice("Header", value, () => visual().headerPlacement === value, "The model, context and cost row: above the conversation or under the input"));
3189
+ for (const value of Object.values(DENSITY)) add(() => `Density: ${value}${visual().density === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, density: value })), () => layoutPreview({ ...visual(), density: value }),
3190
+ layoutChoice("Density", value, () => visual().density === value, "Space between rail sections"));
2663
3191
  category = "Cards";
2664
3192
  // One live style for conversation cards, panels, header/footer and prompt.
2665
3193
  const cardStylePreview = { [CARD_STYLE.NEON]: "╭─ ✿ read ─╮ outlined chrome + prompt", [CARD_STYLE.FLOAT]: "▎ ✿ read painted chrome + prompt" };
@@ -2677,6 +3205,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2677
3205
  requestCustomizeRender?.();
2678
3206
  },
2679
3207
  () => ({ title: `Cards · ${style}`, sample: `${cardStylePreview[style]}${resolveCardStyle(home).malformed ? " · malformed or unreadable file" : ""}` }),
3208
+ { setting: "Card style", value: style, current: () => { const current = resolveCardStyle(home); return current.style === style && !current.malformed; }, hint: "How conversation cards are drawn" },
2680
3209
  );
2681
3210
  // The content level picks between the quiet tools' result previews
2682
3211
  // (default) and command-only cards (minimal).
@@ -2697,17 +3226,30 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2697
3226
  requestCustomizeRender?.();
2698
3227
  },
2699
3228
  () => ({ title: `Cards · content ${content}`, sample: `${cardContentPreview[content]}${resolveCardContent(home).malformed ? " · malformed or unreadable file" : ""}` }),
3229
+ { setting: "Card content", value: content, current: () => { const current = resolveCardContent(home); return current.content === content && !current.malformed; }, hint: "Tool cards: result previews, or the command only" },
2700
3230
  );
2701
3231
  category = "Sections";
2702
- for (const key of VISUAL_SECTION_KEYS) add(
2703
- () => `Section ${key}: ${visual().visibility[key] ? "shown" : "hidden"}`,
3232
+ for (const key of VISUAL_SECTION_KEYS) for (const shown of [true, false]) add(
3233
+ () => `Section ${key}: ${shown ? "shown" : "hidden"}`,
2704
3234
  pending,
2705
- () => updateVisual((settings) => ({ ...settings, visibility: { ...settings.visibility, [key]: !settings.visibility[key] } })),
3235
+ () => updateVisual((settings) => ({ ...settings, visibility: { ...settings.visibility, [key]: shown } })),
2706
3236
  () => {
2707
- const visibility = { ...visual().visibility, [key]: !visual().visibility[key] };
2708
- return { title: `Sections · ${key} ${visibility[key] ? "shown" : "hidden"}`, sample: `[${Object.entries(visibility).filter(([, shown]) => shown).map(([section]) => section).join("] [") || "no optional sections"}]` };
3237
+ const visibility = { ...visual().visibility, [key]: shown };
3238
+ return { title: `Sections · ${key} ${shown ? "shown" : "hidden"}`, sample: `[${Object.entries(visibility).filter(([, value]) => value).map(([section]) => section).join("] [") || "no optional sections"}]` };
2709
3239
  },
3240
+ explicitChoice(key, shown ? "shown" : "hidden", () => visual().visibility[key] === shown),
2710
3241
  );
3242
+ let piKeybindings: PiKeybindings | undefined;
3243
+ let reloadRequested = false;
3244
+ rows.push(...buildKeymapRows({
3245
+ env,
3246
+ configHome: doubleEscCancelConfigHome,
3247
+ keybindings: () => piKeybindings,
3248
+ commands: paletteCommandsForKeymaps(pi),
3249
+ notify: (message, type) => ctx.ui.notify(message, type),
3250
+ // Pi reloads after this card closes, as the command's last step.
3251
+ reload: () => { reloadRequested = true; close(); },
3252
+ }));
2711
3253
  const catalog = () => listVisualProfiles(home).map(name => getVisualProfile(name, home)!);
2712
3254
  category = "Profiles";
2713
3255
  rows.push({ category, label: "Visual profiles (preview, save, apply, delete)", preview: () => {
@@ -2789,7 +3331,8 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2789
3331
  unobserve = adapter?.observe(() => { void refreshYolo(); });
2790
3332
  await refreshYolo();
2791
3333
  if (closed) return;
2792
- await ctx.ui.custom<null>((tui, theme, _keys, done) => {
3334
+ await ctx.ui.custom<null>((tui, theme, keys, done) => {
3335
+ if (typeof (keys as Partial<PiKeybindings> | undefined)?.getKeys === "function") piKeybindings = keys as PiKeybindings;
2793
3336
  finish = () => done(null);
2794
3337
  if (closed) done(null);
2795
3338
  requestYoloRender = () => { if (!closed) tui.requestRender(); };
@@ -2800,11 +3343,13 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
2800
3343
  return {
2801
3344
  render: (width) => closed ? [] : view.render(width),
2802
3345
  handleInput: (data) => { if (!closed) view.handleInput(data); },
3346
+ focus: (label: string) => !closed && view.focus(label),
2803
3347
  invalidate: () => { if (!closed) view.invalidate(); },
2804
3348
  dispose: close,
2805
3349
  };
2806
3350
  }, { overlay: true, overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" } });
2807
3351
  } finally { close(); }
3352
+ if (reloadRequested) await ctx.reload();
2808
3353
  },
2809
3354
  });
2810
3355
  pi.registerCommand("gentle:vim", {