gentle-pi 3.6.0 → 4.0.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.
- package/README.md +37 -6
- package/assets/agents/gentle-ai-explore.md +4 -4
- package/assets/agents/gentle-ai-verify.md +6 -4
- package/assets/agents/gentle-ai-worker.md +7 -9
- package/assets/orchestrator-delegation.md +40 -41
- package/assets/orchestrator-memory.md +1 -22
- package/assets/orchestrator-skills.md +1 -1
- package/assets/orchestrator.md +12 -24
- package/assets/support/strict-tdd-verify.md +4 -266
- package/assets/support/strict-tdd.md +8 -360
- package/bin/gentle-shell.mjs +254 -29
- package/docs/delegated-verification.md +26 -1
- package/docs/gentle-agents-activity.md +24 -0
- package/docs/gentle-shell.md +95 -30
- package/docs/native-authority-architecture.md +2 -2
- package/docs/prompt-history.md +280 -0
- package/docs/readme-reference.md +117 -235
- package/docs/telemetry.md +1 -1
- package/docs/yolo-mode.md +86 -0
- package/extensions/child-context.ts +26 -0
- package/extensions/child-safety.ts +23 -0
- package/extensions/gentle-agents.ts +509 -275
- package/extensions/gentle-ai.ts +781 -683
- package/extensions/gentle-shell.ts +1375 -88
- package/extensions/gentle-stats.ts +101 -0
- package/extensions/gentle-todo.ts +18 -7
- package/extensions/history/atomic-write.ts +38 -0
- package/extensions/history/hide-prompts.ts +183 -0
- package/extensions/history/index.ts +1419 -0
- package/extensions/history/load-shared-history.ts +39 -0
- package/extensions/history/selector-helpers.ts +538 -0
- package/extensions/history/session-scan.ts +233 -0
- package/extensions/history/store.ts +1119 -0
- package/extensions/nan-provider.ts +6 -0
- package/extensions/quiet-tools.ts +179 -87
- package/extensions/resume-hint.ts +60 -0
- package/extensions/skill-registry.ts +16 -12
- package/extensions/startup-banner.ts +60 -31
- package/lib/agent-assets.ts +604 -0
- package/lib/agent-profile-pin.ts +12 -0
- package/lib/agents-message-delivery.ts +181 -0
- package/lib/agents-protocol.ts +60 -0
- package/lib/agents-runner.ts +105 -98
- package/lib/agents-view.ts +26 -3
- package/lib/agents-widget.ts +16 -9
- package/lib/append-system-prompt.ts +21 -0
- package/lib/bounded-writer-admission.ts +147 -0
- package/lib/card-style-policy.ts +60 -0
- package/lib/child-context-files.ts +166 -0
- package/lib/codemode-renderer.ts +185 -0
- package/lib/command-palette-catalog.ts +3 -9
- package/lib/command-palette.ts +25 -14
- package/lib/destructive-command-guard.ts +144 -0
- package/lib/foreign-target-grants.ts +32 -0
- package/lib/gentle-ai-elapsed-store.ts +87 -0
- package/lib/gentle-ai-renderer.ts +196 -39
- package/lib/gentle-shell-launcher.ts +24 -13
- package/lib/gentle-shell-resume-hint.ts +176 -0
- package/lib/history-capture-policy.ts +95 -0
- package/lib/model-routing-authority.ts +5 -1
- package/lib/nan-provider.ts +227 -0
- package/lib/native-review-cli.ts +53 -108
- package/lib/odd-phase-inference.ts +231 -0
- package/lib/odd-phase.ts +141 -0
- package/lib/overlay-repaint.ts +26 -0
- package/lib/pi-tui-keys.ts +53 -0
- package/lib/review-candidate-view-owner.ts +67 -17
- package/lib/review-candidate-view.ts +112 -25
- package/lib/review-reminder-receipt.ts +48 -8
- package/lib/review-risk-assessment.ts +156 -11
- package/lib/review-sidebar-state.ts +223 -0
- package/lib/selection-engine.ts +515 -0
- package/lib/session-change-capture.ts +10 -1
- package/lib/session-messaging-grants.ts +135 -0
- package/lib/session-worktree-registry.ts +14 -2
- package/lib/shell-bar.ts +179 -24
- package/lib/shell-card.ts +287 -18
- package/lib/shell-changes-view.ts +2 -1
- package/lib/shell-prompt.ts +102 -6
- package/lib/shell-sidebar-layout.ts +78 -14
- package/lib/shell-sidebar.ts +15 -1
- package/lib/shell-todo.ts +23 -13
- package/lib/shell-usage-view.ts +9 -4
- package/lib/shell-usage.ts +66 -10
- package/lib/stats-collector.ts +381 -0
- package/lib/stats-view.ts +431 -0
- package/lib/theme-customization.ts +52 -0
- package/lib/vim-editor-adapter.ts +379 -0
- package/lib/vim-normal-engine.ts +154 -0
- package/lib/vim-operator-engine.ts +416 -0
- package/lib/vim-policy.ts +49 -0
- package/lib/vim-visual-engine.ts +107 -0
- package/lib/visual-customization-policy.ts +108 -0
- package/lib/visual-customize-view.ts +330 -0
- package/lib/visual-profiles.ts +228 -0
- package/lib/yolo-session-policy.ts +240 -0
- package/package.json +20 -8
- package/runtime/gentle-shell-launcher.mjs +23 -12
- package/runtime/gentle-shell-resume-hint.mjs +177 -0
- package/runtime/native-review-cli.mjs +53 -108
- package/runtime/review-risk-assessment.mjs +154 -9
- package/scripts/build-runtime-modules.mjs +1 -0
- package/scripts/gentle-ai-installer.mjs +14 -13
- package/scripts/mirror-odd-routing.mjs +2 -2
- package/scripts/run-test-suite.mjs +76 -0
- package/scripts/test-packed-runner.mjs +31 -14
- package/scripts/verify-package-files.mjs +11 -22
- package/skills/branch-pr/SKILL.md +24 -52
- package/skills/chained-pr/SKILL.md +31 -15
- package/skills/chained-pr/references/chaining-details.md +31 -20
- package/skills/gentle-ai/SKILL.md +9 -15
- package/skills/issue-creation/SKILL.md +8 -2
- package/skills/issue-creation/references/delegated-workflow-actions.md +19 -0
- package/skills/work-unit-commits/SKILL.md +4 -3
- package/tests/agent-profiles.test.ts +18 -0
- package/tests/agents-fake-child.ts +2 -2
- package/tests/agents-message-delivery.test.ts +106 -0
- package/tests/agents-protocol.test.ts +40 -0
- package/tests/agents-runner.test.ts +400 -89
- package/tests/agents-view-thread-identity.test.ts +169 -0
- package/tests/agents-view.test.ts +8 -2
- package/tests/agents-widget.test.ts +154 -15
- package/tests/append-system-prompt-route.test.ts +160 -0
- package/tests/append-system-prompt.test.ts +46 -0
- package/tests/artifact-language.test.ts +19 -213
- package/tests/ask-user-question.test.ts +44 -1
- package/tests/asset-installation-runtime.test.ts +5 -16
- package/tests/autonomous-guard.test.ts +69 -1
- package/tests/bounded-writer-admission.test.ts +95 -0
- package/tests/branch-pr-skill.test.ts +43 -0
- package/tests/card-style-policy.test.ts +55 -0
- package/tests/chained-pr-skill.test.ts +124 -0
- package/tests/child-context-files.test.ts +255 -0
- package/tests/child-safety.test.ts +82 -0
- package/tests/codemode-rendering.test.ts +491 -0
- package/tests/command-palette.test.ts +39 -3
- package/tests/delegated-key-learnings-contract.test.ts +0 -76
- package/tests/destructive-command-guard.test.ts +84 -0
- package/tests/devbinary/native-review-parity.devtest.ts +170 -2
- package/tests/devbinary/non-git-subagent-bootstrap.devtest.ts +193 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +7 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +3 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T08-00-00-000Z_ddd.jsonl +2 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T09-00-00-000Z_eee.jsonl +3 -0
- package/tests/fixtures/stats/sessions/--work-alpha--/run-1/session.jsonl +2 -0
- package/tests/fixtures/stats/sessions/--work-beta--/2026-09-01T12-00-00-000Z_ccc.jsonl +2 -0
- package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +2 -0
- package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +4 -0
- package/tests/fixtures/stats/user-pi/sessions/--work-gamma--/2026-09-20T09-00-00-000Z_fff.jsonl +3 -0
- package/tests/foreign-target-grants.test.ts +58 -0
- package/tests/generic-agent-tools.test.ts +54 -0
- package/tests/gentle-agents.test.ts +1411 -256
- package/tests/gentle-ai-binary.test.ts +3 -3
- package/tests/gentle-ai-elapsed-store.test.ts +68 -0
- package/tests/gentle-ai-installer.test.ts +68 -54
- package/tests/gentle-ai-renderer.test.ts +487 -8
- package/tests/gentle-ai.test.ts +288 -65
- package/tests/gentle-card-text.ts +2 -1
- package/tests/gentle-shell-bin.test.ts +651 -114
- package/tests/gentle-shell-launcher.test.ts +99 -52
- package/tests/gentle-shell-resume-hint.test.ts +270 -0
- package/tests/gentle-shell.test.ts +3839 -187
- package/tests/gentle-stats.test.ts +152 -0
- package/tests/gentle-theme.test.ts +4 -1
- package/tests/gentle-todo.test.ts +80 -8
- package/tests/history-atomic-write.test.ts +57 -0
- package/tests/history-capture-policy.test.ts +102 -0
- package/tests/history-command-registration.test.ts +164 -0
- package/tests/history-dedupe-entries.test.ts +123 -0
- package/tests/history-delete-backfill.test.ts +190 -0
- package/tests/history-delete-confirm.test.ts +460 -0
- package/tests/history-dispatch.test.ts +180 -0
- package/tests/history-drain-hidden.test.ts +110 -0
- package/tests/history-drain-order.test.ts +98 -0
- package/tests/history-expanded-globals.test.ts +62 -0
- package/tests/history-gc.test.ts +832 -0
- package/tests/history-header-layout.test.ts +265 -0
- package/tests/history-hide-prompts.test.ts +275 -0
- package/tests/history-lazy-windowing.test.ts +508 -0
- package/tests/history-legacy-migrate-v2.test.ts +297 -0
- package/tests/history-load-shared-history.test.ts +53 -0
- package/tests/history-max-results-cap.test.ts +76 -0
- package/tests/history-multi-reader.test.ts +203 -0
- package/tests/history-off-path.test.ts +170 -0
- package/tests/history-openflow-integration.test.ts +173 -0
- package/tests/history-overlay-margin.test.ts +326 -0
- package/tests/history-preview-layout.test.ts +93 -0
- package/tests/history-registry.test.ts +143 -0
- package/tests/history-scope-delete.test.ts +411 -0
- package/tests/history-search-caret-keys.test.ts +142 -0
- package/tests/history-seed-bootstrap.test.ts +170 -0
- package/tests/history-seed-regen.test.ts +129 -0
- package/tests/history-selector-windowing.test.ts +94 -0
- package/tests/history-session-scan-directory.test.ts +87 -0
- package/tests/history-session-scan-extract.test.ts +583 -0
- package/tests/history-session-writer.test.ts +351 -0
- package/tests/history-store-paths.test.ts +79 -0
- package/tests/history-tombstone-exact.test.ts +139 -0
- package/tests/history-wheel-mouse.test.ts +242 -0
- package/tests/inprocess-reviewer.test.ts +29 -19
- package/tests/issue-creation-skill.test.ts +61 -0
- package/tests/model-routing-authority.test.ts +16 -0
- package/tests/nan-provider.test.ts +471 -0
- package/tests/native-review-capability-contract.test.ts +13 -1
- package/tests/native-review-cli.test.ts +6 -120
- package/tests/native-review-parity-runtime.test.ts +100 -3
- package/tests/odd-integration.test.ts +67 -0
- package/tests/odd-phase-inference.test.ts +213 -0
- package/tests/odd-phase-loader.test.ts +253 -0
- package/tests/odd-phase.test.ts +307 -0
- package/tests/odd-routing-canonical-ratchet.test.ts +11 -6
- package/tests/odd-routing-contract.test.ts +86 -35
- package/tests/orchestrator-budget.test.ts +14 -39
- package/tests/orchestrator-rdd-ownership.test.ts +3 -3
- package/tests/overlay-repaint.test.ts +74 -0
- package/tests/package-manifest.test.ts +252 -115
- package/tests/packed-runner-owned-path.test.ts +46 -0
- package/tests/persona-single-channel.test.ts +6 -6
- package/tests/provider-defect-handoff.test.ts +3 -11
- package/tests/quiet-bash-runtime.test.ts +76 -0
- package/tests/quiet-tool-rendering.test.ts +409 -184
- package/tests/rdd-aware-verification-contract.test.ts +76 -1
- package/tests/rdd-status-line.test.ts +9 -4
- package/tests/resume-hint-extension.test.ts +122 -0
- package/tests/review-agent-end-preflight.test.ts +176 -12
- package/tests/review-candidate-owner-retry.test.ts +22 -1
- package/tests/review-candidate-view.test.ts +298 -0
- package/tests/review-contract-prompt.test.ts +108 -43
- package/tests/review-controller-lock-status.test.ts +0 -1
- package/tests/review-controller-native-routing.test.ts +611 -5
- package/tests/review-controller-workspace-root.test.ts +163 -4
- package/tests/review-host-relay-routing.test.ts +338 -2
- package/tests/review-integration-v2-forward.test.ts +200 -0
- package/tests/review-ledger-contract.test.ts +10 -34
- package/tests/review-reminder-receipt.test.ts +47 -1
- package/tests/review-risk-assessment.test.ts +498 -6
- package/tests/review-sidebar-state.test.ts +402 -0
- package/tests/run-test-suite.test.ts +124 -0
- package/tests/runtime-harness.mjs +145 -786
- package/tests/runtime-metrics-children.test.ts +16 -23
- package/tests/selection-engine.test.ts +421 -0
- package/tests/session-change-capture.test.ts +12 -1
- package/tests/session-messaging-grants.test.ts +255 -0
- package/tests/session-worktree-registry.test.ts +77 -0
- package/tests/shell-bar.test.ts +382 -1
- package/tests/shell-card.test.ts +353 -1
- package/tests/shell-changes-view.test.ts +52 -0
- package/tests/shell-prompt.test.ts +94 -2
- package/tests/shell-sidebar-layout.test.ts +325 -21
- package/tests/shell-sidebar-scroll-benchmark.test.ts +255 -0
- package/tests/shell-todo.test.ts +87 -1
- package/tests/shell-usage-view.test.ts +27 -0
- package/tests/shell-usage.test.ts +73 -0
- package/tests/skill-registry.test.ts +50 -1
- package/tests/startup-banner.test.ts +130 -2
- package/tests/stats-collector.test.ts +195 -0
- package/tests/stats-view.test.ts +202 -0
- package/tests/telemetry-trigger.test.ts +81 -20
- package/tests/theme-customization.test.ts +72 -0
- package/tests/vim-editor-adapter-host-resolution.test.ts +37 -0
- package/tests/vim-editor-adapter.test.ts +804 -0
- package/tests/vim-normal-engine.test.ts +101 -0
- package/tests/vim-operator-engine.test.ts +215 -0
- package/tests/vim-policy.test.ts +19 -0
- package/tests/vim-visual-engine.test.ts +52 -0
- package/tests/visual-customization-policy.test.ts +110 -0
- package/tests/visual-customize-view.test.ts +418 -0
- package/tests/visual-profiles.test.ts +87 -0
- package/tests/yolo-customize.test.ts +256 -0
- package/tests/yolo-mode-runtime.test.ts +161 -0
- package/tests/yolo-mode.test.ts +261 -0
- package/tests/yolo-session-policy.test.ts +59 -0
- package/themes/Gentle.json +2 -1
- package/themes/Gentleman-Cute.json +2 -1
- package/themes/Gentleman-Sexy.json +2 -1
- package/assets/agents/sdd-apply.md +0 -159
- package/assets/agents/sdd-archive.md +0 -228
- package/assets/agents/sdd-design.md +0 -49
- package/assets/agents/sdd-explore.md +0 -48
- package/assets/agents/sdd-init.md +0 -56
- package/assets/agents/sdd-onboard.md +0 -52
- package/assets/agents/sdd-proposal.md +0 -64
- package/assets/agents/sdd-remediate.md +0 -37
- package/assets/agents/sdd-research.md +0 -49
- package/assets/agents/sdd-spec.md +0 -192
- package/assets/agents/sdd-status.md +0 -54
- package/assets/agents/sdd-tasks.md +0 -108
- package/assets/agents/sdd-verify.md +0 -124
- package/assets/chains/sdd-full.chain.md +0 -83
- package/assets/chains/sdd-plan.chain.md +0 -56
- package/assets/chains/sdd-verify.chain.md +0 -43
- package/assets/sdd-orchestrator-workflow.md +0 -319
- package/assets/support/sdd-status-contract.md +0 -77
- package/docs/assets/diagrams/sdd-cycle.svg +0 -14
- package/extensions/sdd-init.ts +0 -816
- package/lib/openspec-deltas.ts +0 -156
- package/lib/sdd-preflight.ts +0 -1066
- package/lib/sdd-research-capabilities.ts +0 -94
- package/lib/sdd-status.ts +0 -26
- package/tests/fixtures/legacy/sdd-research-v2.5.0.md +0 -54
- package/tests/fixtures/native-review-cli/v2.1.3/bind-sdd.json +0 -25
- package/tests/fixtures/v0.10.7/assets/agents/sdd-apply.md +0 -132
- package/tests/openspec-deltas.test.ts +0 -209
- package/tests/sdd-agent-tools.test.ts +0 -156
- package/tests/sdd-archive-replay.test.ts +0 -82
- package/tests/sdd-classical-continuation.test.ts +0 -74
- package/tests/sdd-execution-routing-contract.test.ts +0 -44
- package/tests/sdd-managed-runtime-settlement.test.ts +0 -155
- package/tests/sdd-native-managed-uptake.test.ts +0 -243
- package/tests/sdd-no-attempts-contract.test.ts +0 -15
- package/tests/sdd-odd-integration.test.ts +0 -33
- package/tests/sdd-optional-research.test.ts +0 -124
- package/tests/sdd-planning-routing-contract.test.ts +0 -45
- package/tests/sdd-preflight-rpc-input.test.ts +0 -125
- package/tests/sdd-preflight.test.ts +0 -541
- package/tests/sdd-research-capabilities.test.ts +0 -114
- package/tests/sdd-research-live.test.ts +0 -241
- package/tests/sdd-selection-transport.test.ts +0 -653
- package/tests/sdd-status.test.ts +0 -9
- package/tests/sdd-task-truth.test.ts +0 -43
|
@@ -1,22 +1,107 @@
|
|
|
1
1
|
import { CustomEditor, keyHint, type ExtensionAPI, type ExtensionContext, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import type
|
|
2
|
+
import { Editor, decodeKittyPrintable, isKeyRelease, matchesKey, parseKey, truncateToWidth, visibleWidth, type EditorTheme, type TUI } from "@earendil-works/pi-tui";
|
|
3
3
|
import { execFile, spawnSync } from "node:child_process";
|
|
4
|
-
import { statSync } from "node:fs";
|
|
5
|
-
import {
|
|
4
|
+
import { realpathSync, statSync } from "node:fs";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { profilesFilePath, profileRoleEntries, readProfilesFileResult } from "../lib/agent-profiles.ts";
|
|
7
|
+
import { resolveProfilePin } from "../lib/agent-profile-pin.ts";
|
|
6
8
|
import * as os from "node:os";
|
|
7
|
-
import { join } from "node:path";
|
|
8
|
-
import { buildShellHeaderModel, renderShellBar,
|
|
9
|
+
import { dirname, join, resolve } from "node:path";
|
|
10
|
+
import { buildShellHeaderModel, renderShellBar, renderShellBelowInputFloat, renderShellBottomOnlyBar, renderShellHeaderChrome, renderShellSidebarBar, shellEnabled, shellHeaderUsageHit, type ShellBarModel, type ShellBarTheme } from "../lib/shell-bar.ts";
|
|
9
11
|
import { CHANGE_STATUS, RootBranchLabels, renderChangesWidget, type ChangedFile, type ChangesModel, type GitRunner, type WorktreeChanges } from "../lib/shell-changes.ts";
|
|
10
12
|
import { WorktreeChangesView } from "../lib/shell-changes-view.ts";
|
|
11
|
-
import { SessionWorktreeRegistry, resolveSessionWorktree, worktreeGitEnvironment, type WorktreeResolver } from "../lib/session-worktree-registry.ts";
|
|
12
|
-
import { CARD_TONE, renderCard, type Card, type CardTheme } from "../lib/shell-card.ts";
|
|
13
|
+
import { SessionWorktreeRegistry, resolveSessionWorktree, worktreeGitEnvironment, type WorktreeResolver, type WorktreeIdentity } from "../lib/session-worktree-registry.ts";
|
|
14
|
+
import { CARD_STYLE, CARD_TONE, cardStyle, renderCard, setCardStyle, type Card, type CardTheme } from "../lib/shell-card.ts";
|
|
15
|
+
import { resolveCardStyle, writeCardStyle } from "../lib/card-style-policy.ts";
|
|
13
16
|
import { CommandPalette, commandsKey, type CommandPaletteResult } from "../lib/command-palette.ts";
|
|
14
17
|
import { buildCommandPaletteGroups } from "../lib/command-palette-catalog.ts";
|
|
18
|
+
import { discoverYoloUiAdapter, YOLO_DISPLAY, type YoloDisplay, type YoloUiAdapter } from "../lib/yolo-session-policy.ts";
|
|
19
|
+
import { VisualCustomizeView, type CustomizeCategory, type CustomizeRow, type ProfileActions } from "../lib/visual-customize-view.ts";
|
|
20
|
+
import { deleteVisualProfile, getVisualProfile, listVisualProfiles, resetVisualProfiles, saveVisualProfile } from "../lib/visual-profiles.ts";
|
|
21
|
+
import { sourcePalettePreview } from "../lib/theme-customization.ts";
|
|
22
|
+
import { DEFAULT_VISUAL_SETTINGS, DENSITY, HEADER_PLACEMENT, STATUS_PLACEMENT, VISUAL_SECTION_KEYS, resolveVisualSettings, writeVisualSettings } from "../lib/visual-customization-policy.ts";
|
|
23
|
+
import { BANNER_COLORS, DEFAULT_BANNER_CONFIG, readBannerConfig, readBannerConfigForEdit, writeBannerConfig } from "./startup-banner.ts";
|
|
15
24
|
import { agentsViewKey } from "../lib/agents-keys.ts";
|
|
16
25
|
import { GentleAiDevBinaryOverrideError, resolveGentleAiDevBinaryOverride } from "../lib/gentle-ai-binary.ts";
|
|
17
|
-
import { DOUBLE_ESC_CANCEL_HINT, framePromptLines, IDLE_ESC_CLEAR_HINT, PROMPT_HINT, PROMPT_STATE, SHELL_PULSE_MS, withPromptHint, type PromptState } from "../lib/shell-prompt.ts";
|
|
26
|
+
import { DOUBLE_ESC_CANCEL_HINT, floatPromptRow, framePromptLines, resolvePromptLayout, IDLE_ESC_CLEAR_HINT, PROMPT_HINT, PROMPT_STATE, SHELL_PULSE_MS, withPromptHint, type PromptState } from "../lib/shell-prompt.ts";
|
|
27
|
+
import { oddPhaseRegistry } from "../lib/odd-phase.ts";
|
|
28
|
+
import { inferOddPhase } from "../lib/odd-phase-inference.ts";
|
|
29
|
+
import { isInteractiveMode } from "../lib/rpc-host.ts";
|
|
18
30
|
import { gentlePiConfigHome } from "../lib/agent-home.ts";
|
|
19
31
|
import { resolveAnimationPolicy, writeAnimationPolicy, type AnimationPolicy } from "../lib/animation-policy.ts";
|
|
32
|
+
import { resolveVimPolicy, writeVimPolicy, type VimPolicy } from "../lib/vim-policy.ts";
|
|
33
|
+
import { resolveHistoryCapture, writeHistoryCapturePolicy } from "../lib/history-capture-policy.ts";
|
|
34
|
+
import { createRequire } from "node:module";
|
|
35
|
+
import { createVimEditorAdapter, isAuditedPiEditorVersion } from "../lib/vim-editor-adapter.ts";
|
|
36
|
+
import { VimNormalEngine } from "../lib/vim-normal-engine.ts";
|
|
37
|
+
import { VimOperatorEngine, type OperatorResult } from "../lib/vim-operator-engine.ts";
|
|
38
|
+
import { VimVisualEngine } from "../lib/vim-visual-engine.ts";
|
|
39
|
+
|
|
40
|
+
// Canonical entrypoint and index patterns across POSIX and Windows separators.
|
|
41
|
+
// Exported for cross-platform unit testing of candidate path resolution.
|
|
42
|
+
export const VIM_CLI_ENTRY_PATTERN = /(?:^|[\\/])dist[\\/]bundle[\\/]cli\.js$/;
|
|
43
|
+
export const VIM_AGENT_INDEX_PATTERN = /(?:^|[\\/])dist[\\/]index\.js$/;
|
|
44
|
+
|
|
45
|
+
// Candidate paths provide only package roots, never version authority. Both
|
|
46
|
+
// constructors must come from that same canonical agent/TUI pair before its
|
|
47
|
+
// metadata can admit private editing (jiti may alias imports to host modules).
|
|
48
|
+
export function resolveVimRuntime(entry = process.argv[1], customClass: typeof CustomEditor = CustomEditor):
|
|
49
|
+
{ version: string; editorClass: typeof Editor } | undefined {
|
|
50
|
+
const editorPrototype = Object.getPrototypeOf(customClass.prototype) as typeof Editor.prototype | undefined;
|
|
51
|
+
const editorClass = editorPrototype?.constructor as typeof Editor | undefined;
|
|
52
|
+
const candidates: string[] = [];
|
|
53
|
+
// Audited CLIs (AUDITED_PI_EDITOR_VERSIONS) use the bundled virtual module graph.
|
|
54
|
+
// Its public index exports the very CustomEditor class supplied to extensions by that graph.
|
|
55
|
+
try {
|
|
56
|
+
if (entry) {
|
|
57
|
+
const cli = realpathSync(entry);
|
|
58
|
+
if (VIM_CLI_ENTRY_PATTERN.test(cli)) {
|
|
59
|
+
const root = resolve(dirname(cli), "../..");
|
|
60
|
+
const bundlePath = resolve(root, "dist", "bundle", "index.js");
|
|
61
|
+
if (realpathSync(bundlePath) === bundlePath) {
|
|
62
|
+
const requireFromBundle = createRequire(bundlePath);
|
|
63
|
+
const bundled = requireFromBundle(bundlePath) as { CustomEditor?: typeof CustomEditor; VERSION?: string };
|
|
64
|
+
const metadata = requireFromBundle(resolve(root, "package.json")) as { name?: string; version?: string };
|
|
65
|
+
if (metadata.name === "@earendil-works/pi-coding-agent" && isAuditedPiEditorVersion(metadata.version) &&
|
|
66
|
+
bundled.VERSION === metadata.version && bundled.CustomEditor === customClass &&
|
|
67
|
+
typeof editorClass === "function" && editorClass.name === "Editor" &&
|
|
68
|
+
editorPrototype === editorClass.prototype &&
|
|
69
|
+
Object.getPrototypeOf(customClass) === editorClass) {
|
|
70
|
+
return { version: metadata.version, editorClass };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
} catch { /* Unknown bundled host: do not authorize private editing. */ }
|
|
76
|
+
try {
|
|
77
|
+
if (entry) {
|
|
78
|
+
const cli = realpathSync(entry);
|
|
79
|
+
if (VIM_CLI_ENTRY_PATTERN.test(cli)) candidates.push(resolve(dirname(cli), "../.."));
|
|
80
|
+
}
|
|
81
|
+
} catch { /* The CLI is only a candidate, not proof. */ }
|
|
82
|
+
try {
|
|
83
|
+
const localIndex = realpathSync(fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent")));
|
|
84
|
+
if (VIM_AGENT_INDEX_PATTERN.test(localIndex)) candidates.push(resolve(dirname(localIndex), ".."));
|
|
85
|
+
} catch { /* No local candidate; do not trust extension-relative metadata. */ }
|
|
86
|
+
for (const root of new Set(candidates)) {
|
|
87
|
+
try {
|
|
88
|
+
const agentIndex = realpathSync(resolve(root, "dist", "index.js"));
|
|
89
|
+
if (agentIndex !== resolve(root, "dist", "index.js")) continue;
|
|
90
|
+
const requireFromRuntime = createRequire(agentIndex);
|
|
91
|
+
const agent = requireFromRuntime(agentIndex) as { CustomEditor?: typeof CustomEditor };
|
|
92
|
+
const agentMetadata = requireFromRuntime(resolve(root, "package.json")) as { version?: string; name?: string };
|
|
93
|
+
const tuiPath = realpathSync(requireFromRuntime.resolve("@earendil-works/pi-tui"));
|
|
94
|
+
const tui = requireFromRuntime(tuiPath) as { Editor?: typeof Editor };
|
|
95
|
+
const tuiRoot = resolve(dirname(tuiPath), "..");
|
|
96
|
+
const tuiMetadata = requireFromRuntime(resolve(tuiRoot, "package.json")) as { version?: string; name?: string };
|
|
97
|
+
if (agent.CustomEditor === customClass && tui.Editor === editorClass &&
|
|
98
|
+
agentMetadata.name === "@earendil-works/pi-coding-agent" && tuiMetadata.name === "@earendil-works/pi-tui" &&
|
|
99
|
+
isAuditedPiEditorVersion(agentMetadata.version) &&
|
|
100
|
+
agentMetadata.version === tuiMetadata.version) return { version: tuiMetadata.version, editorClass };
|
|
101
|
+
} catch { /* Unknown package or constructor: ordinary editing stays active. */ }
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
20
105
|
import {
|
|
21
106
|
DOUBLE_ESC_CANCEL_WINDOW_MS,
|
|
22
107
|
resolveDoubleEscCancelPolicy,
|
|
@@ -24,12 +109,15 @@ import {
|
|
|
24
109
|
type DoubleEscCancelPolicy,
|
|
25
110
|
type DoubleEscCancelResolution,
|
|
26
111
|
} from "../lib/double-esc-cancel-policy.ts";
|
|
27
|
-
import { accountIdFromToken, CODEX_PROVIDER, CODEX_USAGE_URL, NAN_PROVIDER, NAN_QUOTA_URL, parseCodexUsage, parseNanQuota, parseProviderUsage, parseUsageHeaders, parseUsageSource, UsageSourceRegistry, UsageStore, USAGE_SOURCE_EVENT, type ProviderUsage, type UsageSource } from "../lib/shell-usage.ts";
|
|
112
|
+
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";
|
|
28
113
|
import { UsageView } from "../lib/shell-usage-view.ts";
|
|
29
|
-
import { sidebarHeader, sidebarPart } from "../lib/shell-sidebar.ts";
|
|
30
|
-
import { installSidebar, invalidateSidebar } from "../lib/shell-sidebar-layout.ts";
|
|
114
|
+
import { sidebarHeader, sidebarPart, sidebarState, VISUAL_SETTINGS_CHANGED, type SidebarRail } from "../lib/shell-sidebar.ts";
|
|
115
|
+
import { installSidebar, invalidateSidebar, narrowStatusOwner, STATUS_OWNER } from "../lib/shell-sidebar-layout.ts";
|
|
31
116
|
import { SessionChanges, SESSION_CHANGE_EVENT } from "../lib/session-changes.ts";
|
|
117
|
+
import { REVIEW_SIDEBAR_EVENT, isReviewSidebarSnapshot, type ReviewSidebarSnapshot } from "../lib/review-sidebar-state.ts";
|
|
32
118
|
import { installSessionChangeCapture } from "../lib/session-change-capture.ts";
|
|
119
|
+
import { SelectionEngine } from "../lib/selection-engine.ts";
|
|
120
|
+
import { withOverlayRepaint } from "../lib/overlay-repaint.ts";
|
|
33
121
|
|
|
34
122
|
// Gentle Shell: the visual layer gentle-pi puts on top of pi. It installs the
|
|
35
123
|
// status bar, the petal prompt, the working-tree changes widget and overlay,
|
|
@@ -69,16 +157,26 @@ export interface ShellDeps {
|
|
|
69
157
|
devBinary(): DevBinaryNotice | undefined;
|
|
70
158
|
resolveWorktree: WorktreeResolver;
|
|
71
159
|
gitRunner(cwd: string): GitRunner;
|
|
160
|
+
vimRuntimeVersion?(): string | undefined;
|
|
72
161
|
}
|
|
73
162
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
163
|
+
export type ActiveProfileReader = (() => string | undefined) & {
|
|
164
|
+
bind(cwd: string, resolveWorktree: WorktreeResolver): boolean;
|
|
165
|
+
refresh(): boolean;
|
|
166
|
+
reset(): void;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// Unbound reads retain the global file-identity cache, including atomic replacements.
|
|
170
|
+
// Bound reads are snapshots: no filesystem or Git work is done during a frame.
|
|
171
|
+
export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env): ActiveProfileReader {
|
|
78
172
|
const path = profilesFilePath(env.GENTLE_PI_CONFIG_HOME ?? join(os.homedir(), ".pi", "gentle-ai"));
|
|
79
173
|
let fingerprint: string | undefined;
|
|
80
174
|
let name: string | undefined;
|
|
81
|
-
|
|
175
|
+
let bound = false;
|
|
176
|
+
let cwd: string | undefined;
|
|
177
|
+
let identity: WorktreeIdentity | undefined;
|
|
178
|
+
let effective: string | undefined;
|
|
179
|
+
const global = () => {
|
|
82
180
|
try {
|
|
83
181
|
const stat = statSync(path, { bigint: true });
|
|
84
182
|
const next = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
@@ -94,6 +192,28 @@ export function createActiveProfileReader(env: NodeJS.ProcessEnv = process.env):
|
|
|
94
192
|
return undefined;
|
|
95
193
|
}
|
|
96
194
|
};
|
|
195
|
+
const reader = (() => bound ? effective : global()) as ActiveProfileReader;
|
|
196
|
+
reader.refresh = () => {
|
|
197
|
+
if (!bound) return false;
|
|
198
|
+
const pin = identity && cwd ? resolveProfilePin({
|
|
199
|
+
cwd,
|
|
200
|
+
configHome: env.GENTLE_PI_CONFIG_HOME ?? join(os.homedir(), ".pi", "gentle-ai"),
|
|
201
|
+
resolveWorktree: () => identity!,
|
|
202
|
+
}) : undefined;
|
|
203
|
+
const next = pin ? `${pin.profile} (${pin.source})` : global();
|
|
204
|
+
const changed = next !== effective;
|
|
205
|
+
effective = next;
|
|
206
|
+
return changed;
|
|
207
|
+
};
|
|
208
|
+
reader.bind = (nextCwd, resolveWorktree) => {
|
|
209
|
+
reader.reset();
|
|
210
|
+
cwd = nextCwd;
|
|
211
|
+
try { identity = resolveWorktree(nextCwd, nextCwd); } catch { identity = undefined; }
|
|
212
|
+
bound = true;
|
|
213
|
+
return reader.refresh();
|
|
214
|
+
};
|
|
215
|
+
reader.reset = () => { bound = false; cwd = undefined; identity = undefined; effective = undefined; };
|
|
216
|
+
return reader;
|
|
97
217
|
}
|
|
98
218
|
|
|
99
219
|
function ambientDevBinary(): DevBinaryNotice | undefined {
|
|
@@ -106,7 +226,7 @@ function ambientDevBinary(): DevBinaryNotice | undefined {
|
|
|
106
226
|
}
|
|
107
227
|
}
|
|
108
228
|
|
|
109
|
-
const defaultShellDeps: Omit<ShellDeps, "activeProfile"> = { fetch: (
|
|
229
|
+
const defaultShellDeps: Omit<ShellDeps, "activeProfile"> = { fetch: (input, init) => globalThis.fetch(input, init), now: () => Date.now(), devBinary: ambientDevBinary, resolveWorktree: resolveSessionWorktree, gitRunner: shellGitRunner };
|
|
110
230
|
|
|
111
231
|
interface AssistantUsageEntry {
|
|
112
232
|
type: string;
|
|
@@ -169,6 +289,7 @@ export function createShellBarComponent(
|
|
|
169
289
|
footerData: ShellFooterData,
|
|
170
290
|
dirty: () => number | undefined = () => undefined,
|
|
171
291
|
usage: () => ProviderUsage | undefined = () => undefined,
|
|
292
|
+
presentation?: () => ReturnType<typeof resolveVisualSettings>["settings"],
|
|
172
293
|
): ShellBarComponent {
|
|
173
294
|
const unsubscribe = footerData.onBranchChange(() => {
|
|
174
295
|
host.invalidateSidebar?.();
|
|
@@ -176,7 +297,7 @@ export function createShellBarComponent(
|
|
|
176
297
|
});
|
|
177
298
|
return {
|
|
178
299
|
render(width: number) {
|
|
179
|
-
return renderShellBar(buildShellBarModel(pi, ctx, footerData, { dirty: dirty(), usage: usage() }), theme, width);
|
|
300
|
+
return renderShellBar(buildShellBarModel(pi, ctx, footerData, { dirty: dirty(), usage: usage() }), theme, width, presentation?.());
|
|
180
301
|
},
|
|
181
302
|
invalidate() {},
|
|
182
303
|
dispose() {
|
|
@@ -187,6 +308,7 @@ export function createShellBarComponent(
|
|
|
187
308
|
|
|
188
309
|
interface PromptEditorDeps {
|
|
189
310
|
fg: (color: string, text: string) => string;
|
|
311
|
+
bg?: (color: string, text: string) => string;
|
|
190
312
|
bold: (text: string) => string;
|
|
191
313
|
requestRender(): void;
|
|
192
314
|
pending(): boolean;
|
|
@@ -195,12 +317,26 @@ interface PromptEditorDeps {
|
|
|
195
317
|
doubleEscCancelEnabled(): boolean;
|
|
196
318
|
/** Hand off text reconstructed from Pi's Esc-abort restore so it is sent as the next turn instead of sitting in the editor. */
|
|
197
319
|
dispatchQueuedText(text: string): void;
|
|
320
|
+
/** Override only for isolated adapter compatibility tests; production reads installed metadata. */
|
|
321
|
+
tuiVersion?: () => string | undefined;
|
|
322
|
+
/** Report a single warning if this editor cannot safely provide modal editing. */
|
|
323
|
+
notifyCompatibility?: (message: string) => void;
|
|
324
|
+
/**
|
|
325
|
+
* Read fresh on every render while WORKING: the explicit, orchestrator-reported
|
|
326
|
+
* ODD phase label for the current session, or undefined to fall back to the
|
|
327
|
+
* generic "working…" label. Never applied to IDLE or QUEUED.
|
|
328
|
+
*/
|
|
329
|
+
workingLabel?: () => string | undefined;
|
|
198
330
|
}
|
|
199
331
|
|
|
200
332
|
const PROMPT_FRAME_ROLE = "border";
|
|
201
333
|
// Matches Pi's own idle double-Esc window (empty editor -> /tree or /fork);
|
|
202
334
|
// this is the same muscle memory applied to clearing a non-empty draft.
|
|
203
335
|
const IDLE_ESC_CLEAR_WINDOW_MS = 500;
|
|
336
|
+
const BRACKETED_PASTE_START = "\x1b[200~";
|
|
337
|
+
const BRACKETED_PASTE_END = "\x1b[201~";
|
|
338
|
+
// Bound our framing buffer even when a terminal never sends the closing marker.
|
|
339
|
+
const MAX_BRACKETED_PASTE_CHARS = 1024 * 1024;
|
|
204
340
|
|
|
205
341
|
/**
|
|
206
342
|
* Pi's own Esc-abort handler (`restoreQueuedMessagesToEditor({ abort: true
|
|
@@ -231,8 +367,28 @@ export class GentlePromptEditor extends CustomEditor {
|
|
|
231
367
|
private promptState: PromptState = PROMPT_STATE.IDLE;
|
|
232
368
|
private tick = 0;
|
|
233
369
|
private animationPolicy: AnimationPolicy = "quality";
|
|
370
|
+
private vimPolicy: VimPolicy = "off";
|
|
371
|
+
private vimRejected = false;
|
|
372
|
+
private vimNormal = false;
|
|
373
|
+
private compatibilityNotified = false;
|
|
374
|
+
private readonly vimEngine = new VimNormalEngine();
|
|
375
|
+
private readonly vimOperator = new VimOperatorEngine();
|
|
376
|
+
private vimInsertIntent?: { operator?: OperatorResult; command?: string };
|
|
377
|
+
private readonly vimVisual = new VimVisualEngine();
|
|
378
|
+
private pasteFrame: string | undefined;
|
|
379
|
+
private pasteOverflow = false;
|
|
380
|
+
private pasteTail = "";
|
|
381
|
+
private visualReplacePending = false;
|
|
382
|
+
private visualObjectPending: "i" | "a" | undefined;
|
|
383
|
+
private visualAnchor: { line: number; col: number } | undefined;
|
|
234
384
|
private pulse: NodeJS.Timeout | undefined;
|
|
235
385
|
private readonly deps: PromptEditorDeps;
|
|
386
|
+
private floatMouseLayout?: ReturnType<typeof resolvePromptLayout>;
|
|
387
|
+
// Native selection engine (shift+home/end, alt+a, replace-on-key): ported
|
|
388
|
+
// from pi-select-del so the petal prompt owns the feature without factory
|
|
389
|
+
// composition. Constructed with `this`; the internals probe degrades to
|
|
390
|
+
// passthrough on pi drift, costing only the selection features.
|
|
391
|
+
private readonly selectionEngine: SelectionEngine;
|
|
236
392
|
// CustomEditor keeps its own `keybindings` private, so this class holds
|
|
237
393
|
// its own reference to run the same app.interrupt match before deciding
|
|
238
394
|
// whether to swallow the keystroke.
|
|
@@ -246,6 +402,7 @@ export class GentlePromptEditor extends CustomEditor {
|
|
|
246
402
|
|
|
247
403
|
constructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager, deps: PromptEditorDeps) {
|
|
248
404
|
super(tui, theme, keybindings);
|
|
405
|
+
this.selectionEngine = new SelectionEngine(this);
|
|
249
406
|
this.deps = deps;
|
|
250
407
|
this.keybindingsManager = keybindings;
|
|
251
408
|
}
|
|
@@ -258,6 +415,87 @@ export class GentlePromptEditor extends CustomEditor {
|
|
|
258
415
|
this.deps.requestRender();
|
|
259
416
|
}
|
|
260
417
|
|
|
418
|
+
get effectiveVimPolicy(): VimPolicy { return this.vimPolicy; }
|
|
419
|
+
|
|
420
|
+
setVimPolicy(policy: VimPolicy): void {
|
|
421
|
+
this.vimRejected = false;
|
|
422
|
+
if (policy === "on") {
|
|
423
|
+
try { this.vimAdapter(); }
|
|
424
|
+
catch {
|
|
425
|
+
this.vimRejected = true;
|
|
426
|
+
if (!this.compatibilityNotified) {
|
|
427
|
+
this.compatibilityNotified = true;
|
|
428
|
+
this.deps.notifyCompatibility?.("Gentle Vim unsupported by this Pi editor layout/version; ordinary editing remains active.");
|
|
429
|
+
}
|
|
430
|
+
policy = "off";
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (this.vimPolicy === policy) return;
|
|
434
|
+
this.pasteFrame = undefined;
|
|
435
|
+
this.pasteOverflow = false;
|
|
436
|
+
this.pasteTail = "";
|
|
437
|
+
if (this.vimPolicy === "on" && !this.disablingUnsupportedVim) {
|
|
438
|
+
try { this.vimAdapter().endInsertSession(); } catch { /* Unsupported editor cannot group inserts. */ }
|
|
439
|
+
}
|
|
440
|
+
this.vimInsertIntent = undefined;
|
|
441
|
+
this.vimPolicy = policy;
|
|
442
|
+
this.vimNormal = false;
|
|
443
|
+
this.vimOperator.forgetRepeat();
|
|
444
|
+
this.vimOperator.cancel();
|
|
445
|
+
this.visualAnchor = undefined;
|
|
446
|
+
this.vimVisual.cancel();
|
|
447
|
+
this.visualReplacePending = false;
|
|
448
|
+
this.visualObjectPending = undefined;
|
|
449
|
+
this.deps.requestRender();
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
private notifyUnsafeVisual(stage: "range" | "readRange" | "beginInsertSession" | "replace" | "move" | "operation", error?: unknown): void {
|
|
453
|
+
// Only fixed reason codes reach UI; never include a draft, path, or raw host error.
|
|
454
|
+
const message = error instanceof Error ? error.message : "";
|
|
455
|
+
const reason = /duplicate registered paste marker/i.test(message) ? "duplicate-marker" :
|
|
456
|
+
/paste marker/i.test(message) ? "paste-marker" :
|
|
457
|
+
/unsupported pi editor layout/i.test(message) ? "unsupported-layout" :
|
|
458
|
+
/valid grapheme or paste boundary|invalid cursor boundary/i.test(message) ? "invalid-boundary" :
|
|
459
|
+
/invalid selection range|invalid operator range/i.test(message) ? "invalid-range" :
|
|
460
|
+
/insert session already active/i.test(message) ? "session-active" :
|
|
461
|
+
error === undefined ? "no-range" : "unexpected";
|
|
462
|
+
this.deps.notifyCompatibility?.((reason === "paste-marker"
|
|
463
|
+
? "Vim selection contains a registered paste marker; edit it in INSERT mode instead."
|
|
464
|
+
: "Vim selection cannot be edited safely; try a different selection.") + ` [${stage}:${reason}]`);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
private disablingUnsupportedVim = false;
|
|
468
|
+
private vimAdapter(): ReturnType<typeof createVimEditorAdapter> {
|
|
469
|
+
const runtime = resolveVimRuntime();
|
|
470
|
+
try {
|
|
471
|
+
return createVimEditorAdapter(this, this.deps.tuiVersion?.() ?? runtime?.version ?? "unknown", runtime?.editorClass ?? Editor, runtime?.version);
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (this.vimPolicy === "on" && !this.disablingUnsupportedVim) {
|
|
474
|
+
this.disablingUnsupportedVim = true;
|
|
475
|
+
try { this.setVimPolicy("off"); this.vimRejected = true; } finally { this.disablingUnsupportedVim = false; }
|
|
476
|
+
if (!this.compatibilityNotified) {
|
|
477
|
+
this.compatibilityNotified = true;
|
|
478
|
+
this.deps.notifyCompatibility?.("Gentle Vim unsupported by this Pi editor layout/version; ordinary editing remains active.");
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private enterVimInsert(resetEngine = true, cancelOperator = true, beginSession = true): void {
|
|
486
|
+
if (this.vimNormal && beginSession) {
|
|
487
|
+
try { this.vimAdapter().beginInsertSession(); } catch { /* Unknown layout: normal edits remain disabled. */ }
|
|
488
|
+
}
|
|
489
|
+
this.vimNormal = false;
|
|
490
|
+
if (cancelOperator) this.vimOperator.cancel();
|
|
491
|
+
if (resetEngine) this.vimEngine.reset();
|
|
492
|
+
this.visualAnchor = undefined;
|
|
493
|
+
this.vimVisual.cancel();
|
|
494
|
+
this.visualReplacePending = false;
|
|
495
|
+
this.visualObjectPending = undefined;
|
|
496
|
+
this.deps.requestRender();
|
|
497
|
+
}
|
|
498
|
+
|
|
261
499
|
private startPulse(): void {
|
|
262
500
|
if (this.animationPolicy === "potato") return;
|
|
263
501
|
this.pulse = setInterval(() => {
|
|
@@ -294,12 +532,336 @@ export class GentlePromptEditor extends CustomEditor {
|
|
|
294
532
|
* and never reach this branch.
|
|
295
533
|
*/
|
|
296
534
|
override handleInput(data: string): void {
|
|
297
|
-
//
|
|
298
|
-
//
|
|
535
|
+
// Selection and Vim handlers can consume input before the native chain;
|
|
536
|
+
// any intervening key invalidates an idle Esc confirmation.
|
|
299
537
|
if (this.pendingIdleClearDeadline !== undefined && !this.keybindingsManager.matches(data, "app.interrupt")) {
|
|
300
538
|
this.pendingIdleClearDeadline = undefined;
|
|
301
539
|
this.pendingIdleClearText = undefined;
|
|
302
540
|
}
|
|
541
|
+
// Vim owns its modal keys and paste frames. Ordinary editing retains
|
|
542
|
+
// native selection before the prompt's existing input chain.
|
|
543
|
+
if (this.vimPolicy === "on") this.handleInputNative(data);
|
|
544
|
+
else this.selectionEngine.handleInput(data, (d) => this.handleInputNative(d));
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
private handleInputNative(data: string): void {
|
|
548
|
+
if ((this.vimPolicy === "on" || this.vimRejected) && this.handleVimPasteFrame(data)) return;
|
|
549
|
+
if (this.vimPolicy === "on" && isKeyRelease(data)) return;
|
|
550
|
+
if (this.vimPolicy === "on" && this.vimNormal && matchesKey(data, "escape") && this.vimVisual.active) {
|
|
551
|
+
if (this.isShowingAutocomplete()) {
|
|
552
|
+
try { this.vimAdapter().dismissAutocomplete(); } catch { return; }
|
|
553
|
+
}
|
|
554
|
+
this.vimVisual.cancel(); this.visualAnchor = undefined;
|
|
555
|
+
this.visualReplacePending = false; this.visualObjectPending = undefined;
|
|
556
|
+
this.vimOperator.cancel(); this.vimEngine.cancelPendingFind();
|
|
557
|
+
this.deps.requestRender();
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (this.vimPolicy === "on" && this.vimNormal && matchesKey(data, "escape") &&
|
|
561
|
+
(this.vimOperator.cancel() || this.vimEngine.cancelPendingFind())) {
|
|
562
|
+
this.deps.requestRender();
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
// Pi owns autocomplete and shell input except while a VISUAL command
|
|
566
|
+
// owns the key. Defer that handoff until after shortcut priority.
|
|
567
|
+
const bashMode = this.getText().trimStart().startsWith("!");
|
|
568
|
+
if (this.vimPolicy === "on" && this.vimNormal && ((this.isShowingAutocomplete() && !this.vimVisual.active) ||
|
|
569
|
+
(bashMode && !this.keybindingsManager.matches(data, "app.interrupt") && !matchesKey(data, "escape")))) {
|
|
570
|
+
this.enterVimInsert();
|
|
571
|
+
}
|
|
572
|
+
if (this.vimPolicy === "on" && !this.vimNormal && !this.isShowingAutocomplete() &&
|
|
573
|
+
(this.keybindingsManager.matches(data, "app.interrupt") || matchesKey(data, "escape"))) {
|
|
574
|
+
try {
|
|
575
|
+
const inserted = this.vimAdapter().endInsertSession();
|
|
576
|
+
if (matchesKey(data, "escape") && inserted && this.vimInsertIntent?.operator)
|
|
577
|
+
this.vimOperator.rememberInsert(this.vimInsertIntent.operator, inserted);
|
|
578
|
+
else if (matchesKey(data, "escape") && inserted && this.vimInsertIntent?.command)
|
|
579
|
+
this.vimOperator.rememberLiteralInsert(this.vimInsertIntent.command, inserted);
|
|
580
|
+
} catch { /* Unknown layout: no grouping or repeat. */ }
|
|
581
|
+
this.vimInsertIntent = undefined;
|
|
582
|
+
this.vimNormal = true;
|
|
583
|
+
this.visualAnchor = undefined;
|
|
584
|
+
this.vimVisual.cancel();
|
|
585
|
+
this.pendingEscapeCancelDeadline = undefined;
|
|
586
|
+
this.pendingIdleClearDeadline = undefined;
|
|
587
|
+
this.pendingIdleClearText = undefined;
|
|
588
|
+
this.deps.requestRender();
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
if (this.vimPolicy === "on" && (!this.isShowingAutocomplete() || this.vimVisual.active) && !bashMode) {
|
|
592
|
+
// CustomEditor gives extension, clipboard and app shortcuts priority
|
|
593
|
+
// over editor input. Preserve that order even when a shortcut shares
|
|
594
|
+
// a modal command key, and transfer ownership before its callback.
|
|
595
|
+
if (this.vimNormal && !this.keybindingsManager.matches(data, "app.interrupt") && !matchesKey(data, "escape")) {
|
|
596
|
+
if (this.onExtensionShortcut) {
|
|
597
|
+
const draft = this.getText();
|
|
598
|
+
const anchor = this.visualAnchor;
|
|
599
|
+
const visualMode = this.vimVisual.kind;
|
|
600
|
+
const replacePending = this.visualReplacePending;
|
|
601
|
+
const objectPending = this.visualObjectPending;
|
|
602
|
+
const restoreMode = () => {
|
|
603
|
+
this.vimNormal = true;
|
|
604
|
+
this.visualAnchor = anchor;
|
|
605
|
+
this.visualReplacePending = replacePending;
|
|
606
|
+
this.visualObjectPending = objectPending;
|
|
607
|
+
if (anchor) this.vimVisual.start(visualMode, anchor);
|
|
608
|
+
this.deps.requestRender();
|
|
609
|
+
};
|
|
610
|
+
this.enterVimInsert(false, false);
|
|
611
|
+
let consumed: boolean;
|
|
612
|
+
try { consumed = this.onExtensionShortcut(data); }
|
|
613
|
+
catch (error) {
|
|
614
|
+
if (this.getText() === draft) {
|
|
615
|
+
try { this.vimAdapter().endInsertSession(); } catch { /* Preserve the callback failure. */ }
|
|
616
|
+
restoreMode();
|
|
617
|
+
} else {
|
|
618
|
+
this.vimOperator.cancel();
|
|
619
|
+
this.vimEngine.reset();
|
|
620
|
+
}
|
|
621
|
+
throw error;
|
|
622
|
+
}
|
|
623
|
+
if (consumed || this.getText() !== draft) {
|
|
624
|
+
this.vimOperator.cancel();
|
|
625
|
+
this.vimEngine.reset();
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
// A non-owning shortcut probe temporarily entered INSERT; close
|
|
629
|
+
// its session before restoring NORMAL and dispatching this key.
|
|
630
|
+
try { this.vimAdapter().endInsertSession(); } catch { return; }
|
|
631
|
+
restoreMode();
|
|
632
|
+
}
|
|
633
|
+
if (this.keybindingsManager.matches(data, "app.clipboard.pasteImage")) {
|
|
634
|
+
this.enterVimInsert();
|
|
635
|
+
this.onPasteImage?.();
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if (this.keybindingsManager.matches(data, "tui.editor.historyPrevious") ||
|
|
639
|
+
this.keybindingsManager.matches(data, "tui.editor.historyNext")) {
|
|
640
|
+
this.enterVimInsert();
|
|
641
|
+
super.handleInput(data);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
for (const [action, handler] of this.actionHandlers) {
|
|
645
|
+
if (action !== "app.interrupt" && this.keybindingsManager.matches(data, action)) {
|
|
646
|
+
if (action === "app.exit" && this.getText().length !== 0) continue;
|
|
647
|
+
this.enterVimInsert();
|
|
648
|
+
handler();
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
const parsed = parseKey(data);
|
|
654
|
+
const singleGrapheme = (value: string): boolean =>
|
|
655
|
+
[...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(value)].length === 1;
|
|
656
|
+
const printable = decodeKittyPrintable(data) ??
|
|
657
|
+
(parsed && singleGrapheme(parsed) ? parsed : undefined) ??
|
|
658
|
+
(singleGrapheme(data) ? data : undefined);
|
|
659
|
+
// Only unmodified presses become modal commands; other shortcuts
|
|
660
|
+
// remain available to Pi's application keybindings.
|
|
661
|
+
const command = printable && (matchesKey(data, printable as Parameters<typeof matchesKey>[1]) || data === printable)
|
|
662
|
+
? printable : matchesKey(data, "space") ? "Space" : undefined;
|
|
663
|
+
// A stale Pi menu must never take a VISUAL motion, count or
|
|
664
|
+
// operator. Dismiss it only after app/extension shortcut priority;
|
|
665
|
+
// outside VISUAL Pi retains its ordinary completion ownership.
|
|
666
|
+
if (this.vimNormal && this.vimVisual.active && this.isShowingAutocomplete()) {
|
|
667
|
+
try { this.vimAdapter().dismissAutocomplete(); } catch { return; }
|
|
668
|
+
}
|
|
669
|
+
if (this.vimNormal && !this.vimVisual.active && command === "/") {
|
|
670
|
+
// Pi 0.85.1 opens slash completion only at the start of the
|
|
671
|
+
// first line. Let its editor insert the slash and decide whether
|
|
672
|
+
// to open the menu; never relocate or replace an existing draft.
|
|
673
|
+
this.enterVimInsert();
|
|
674
|
+
super.handleInput(data);
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (this.vimNormal && command) {
|
|
678
|
+
if (this.visualObjectPending && this.vimVisual.active) {
|
|
679
|
+
const around = this.visualObjectPending;
|
|
680
|
+
this.visualObjectPending = undefined;
|
|
681
|
+
try {
|
|
682
|
+
const adapter = this.vimAdapter();
|
|
683
|
+
const stops = adapter.motionBoundaries();
|
|
684
|
+
const range = this.vimVisual.object(this.getText(), this.getCursor(), stops, around, command);
|
|
685
|
+
if (range) {
|
|
686
|
+
adapter.readRange(range.start, range.end);
|
|
687
|
+
const endStops = stops[range.end.line]!;
|
|
688
|
+
const endIndex = endStops.indexOf(range.end.col);
|
|
689
|
+
const last = endIndex > 0 ? { line: range.end.line, col: endStops[endIndex - 1]! } :
|
|
690
|
+
range.end.line > 0 ? { line: range.end.line - 1, col: stops[range.end.line - 1]!.at(-1)! } : undefined;
|
|
691
|
+
if (last) {
|
|
692
|
+
this.visualAnchor = range.start;
|
|
693
|
+
this.vimVisual.start("char", range.start);
|
|
694
|
+
adapter.move(last);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
} catch { /* Registered paste markers and unknown layouts leave the visual range intact. */ }
|
|
698
|
+
this.deps.requestRender(); return;
|
|
699
|
+
}
|
|
700
|
+
if (this.visualReplacePending && this.vimVisual.active) {
|
|
701
|
+
this.visualReplacePending = false;
|
|
702
|
+
if (singleGrapheme(command) && !command.includes("\n")) {
|
|
703
|
+
try {
|
|
704
|
+
const adapter = this.vimAdapter();
|
|
705
|
+
const range = this.vimVisual.range(this.getText(), this.getCursor(), adapter.motionBoundaries());
|
|
706
|
+
if (range) {
|
|
707
|
+
adapter.readRange(range.start, range.end);
|
|
708
|
+
const edit = this.vimOperator.visualEdit("r" + command, this.getText(), range).edit;
|
|
709
|
+
if (edit) { adapter.replace(edit.start, edit.end, edit.text); adapter.move(edit.cursor); }
|
|
710
|
+
this.vimVisual.cancel(); this.visualAnchor = undefined;
|
|
711
|
+
this.vimOperator.cancel(); this.vimEngine.reset();
|
|
712
|
+
}
|
|
713
|
+
} catch { /* Preserve selection when a paste marker or layout is unsafe. */ }
|
|
714
|
+
}
|
|
715
|
+
this.deps.requestRender(); return;
|
|
716
|
+
}
|
|
717
|
+
if (command === "v" || command === "V") {
|
|
718
|
+
if (this.vimVisual.active && this.vimVisual.kind === (command === "v" ? "char" : "line")) {
|
|
719
|
+
this.vimVisual.cancel(); this.visualAnchor = undefined;
|
|
720
|
+
} else {
|
|
721
|
+
let anchor = this.visualAnchor ?? this.getCursor();
|
|
722
|
+
if (command === "v" && !this.vimVisual.active) {
|
|
723
|
+
try {
|
|
724
|
+
const adapter = this.vimAdapter();
|
|
725
|
+
const stops = adapter.motionBoundaries()[anchor.line];
|
|
726
|
+
if (!stops) return;
|
|
727
|
+
if (stops.length > 1 && anchor.col === stops[stops.length - 1]) {
|
|
728
|
+
anchor = { line: anchor.line, col: stops[stops.length - 2]! };
|
|
729
|
+
adapter.move(anchor);
|
|
730
|
+
}
|
|
731
|
+
} catch { return; }
|
|
732
|
+
}
|
|
733
|
+
this.visualAnchor = anchor;
|
|
734
|
+
this.vimVisual.start(command === "v" ? "char" : "line", anchor);
|
|
735
|
+
}
|
|
736
|
+
this.vimOperator.cancel();
|
|
737
|
+
this.vimEngine.reset();
|
|
738
|
+
this.deps.requestRender();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
let adapter;
|
|
742
|
+
try { adapter = this.vimAdapter(); } catch { return; }
|
|
743
|
+
if (this.vimVisual.active) {
|
|
744
|
+
if (command === "i" || command === "a") { this.visualObjectPending = command; return; }
|
|
745
|
+
if (command === "r") { this.visualReplacePending = true; return; }
|
|
746
|
+
if (command === "o") {
|
|
747
|
+
const target = this.vimVisual.swap(this.getCursor());
|
|
748
|
+
if (target) { this.visualAnchor = this.getCursor(); adapter.move(target); }
|
|
749
|
+
this.deps.requestRender(); return;
|
|
750
|
+
}
|
|
751
|
+
if (["d", "x", "c", "s", "y", "p", "~", "u", "U", ">", "<", "J"].includes(command)) {
|
|
752
|
+
let range;
|
|
753
|
+
try { range = this.vimVisual.range(this.getText(), this.getCursor(), adapter.motionBoundaries()); }
|
|
754
|
+
catch (error) { this.notifyUnsafeVisual("range", error); return; }
|
|
755
|
+
if (!range) { this.notifyUnsafeVisual("range"); return; }
|
|
756
|
+
let stage: "readRange" | "operation" | "beginInsertSession" | "replace" | "move" = "readRange";
|
|
757
|
+
let beganInsert = false;
|
|
758
|
+
try {
|
|
759
|
+
const selected = adapter.readRange(range.start, range.end);
|
|
760
|
+
if (!selected && (!range.linewise || !this.getText())) {
|
|
761
|
+
this.vimVisual.cancel(); this.visualAnchor = undefined;
|
|
762
|
+
this.vimEngine.reset(); this.deps.requestRender();
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
stage = "operation";
|
|
766
|
+
const operation = this.vimOperator.visualEdit(command === "x" ? "d" : command === "s" ? "c" : command, this.getText(), range);
|
|
767
|
+
if (command === "p" && !operation.edit) {
|
|
768
|
+
this.deps.notifyCompatibility?.("Vim register is empty; yank text before visual paste.");
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if (operation.edit) {
|
|
772
|
+
this.vimOperator.forgetRepeat();
|
|
773
|
+
if (operation.edit.insert) { stage = "beginInsertSession"; adapter.beginInsertSession(); beganInsert = true; }
|
|
774
|
+
if (operation.edit.start.line !== operation.edit.end.line || operation.edit.start.col !== operation.edit.end.col || operation.edit.text) {
|
|
775
|
+
stage = "replace"; adapter.replace(operation.edit.start, operation.edit.end, operation.edit.text);
|
|
776
|
+
}
|
|
777
|
+
stage = "move"; adapter.move(operation.edit.cursor);
|
|
778
|
+
}
|
|
779
|
+
if (["d", "x", "c", "s", "y", "p"].includes(command)) this.vimOperator.visualRegister(range.linewise ? selected + "\n" : selected, range.linewise);
|
|
780
|
+
this.vimVisual.cancel(); this.visualAnchor = undefined;
|
|
781
|
+
this.vimOperator.cancel(); this.vimEngine.reset();
|
|
782
|
+
if (operation.edit?.insert) this.enterVimInsert(true, true, false);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
if (beganInsert) { try { adapter.endInsertSession(); } catch { /* Retain the original failure. */ } }
|
|
785
|
+
this.notifyUnsafeVisual(stage, error);
|
|
786
|
+
}
|
|
787
|
+
this.deps.requestRender(); return;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
if (command === "." && !this.vimVisual.active && !this.vimOperator.isPending) {
|
|
791
|
+
const count = this.vimOperator.takeRepeatCount();
|
|
792
|
+
this.vimEngine.reset();
|
|
793
|
+
for (let i = 0; i < count; i++) {
|
|
794
|
+
const literal = this.vimOperator.repeatInsertCommand;
|
|
795
|
+
const inserted = this.vimOperator.repeatInsertion;
|
|
796
|
+
const destination = literal ? new VimNormalEngine().input(literal, this.getText(), this.getCursor(), adapter.motionBoundaries()) : undefined;
|
|
797
|
+
const change = literal ? undefined : this.vimOperator.repeatAt(this.getText(), this.getCursor(), adapter.motionBoundaries());
|
|
798
|
+
if (!change?.edit && !(destination?.handled && inserted)) break;
|
|
799
|
+
try {
|
|
800
|
+
if (inserted && /[\r\t]/.test(inserted)) break;
|
|
801
|
+
if (change?.edit?.insert) {
|
|
802
|
+
adapter.readRange(change.edit.start, change.edit.end);
|
|
803
|
+
adapter.beginInsertSession();
|
|
804
|
+
}
|
|
805
|
+
if (change?.edit) {
|
|
806
|
+
if (change.edit.text || change.edit.start.line !== change.edit.end.line || change.edit.start.col !== change.edit.end.col)
|
|
807
|
+
adapter.replace(change.edit.start, change.edit.end, change.edit.text);
|
|
808
|
+
adapter.move(change.edit.cursor);
|
|
809
|
+
}
|
|
810
|
+
if (inserted && (change?.edit?.insert || destination)) {
|
|
811
|
+
const at = destination?.cursor ?? change!.edit!.cursor;
|
|
812
|
+
adapter.replace(at, at, inserted);
|
|
813
|
+
}
|
|
814
|
+
if (change?.edit?.insert) adapter.endInsertSession();
|
|
815
|
+
else if (change?.edit) adapter.move(change.edit.cursor);
|
|
816
|
+
} catch { if (change?.edit?.insert) adapter.endInsertSession(); break; /* Unsafe paste marker: stop replay. */ }
|
|
817
|
+
}
|
|
818
|
+
this.deps.requestRender(); return;
|
|
819
|
+
}
|
|
820
|
+
const wasPending = this.vimOperator.isPending;
|
|
821
|
+
const operator = this.vimVisual.active ? null : this.vimOperator.input(command, this.getText(), this.getCursor(), adapter.motionBoundaries());
|
|
822
|
+
if (operator && (wasPending || !/^[0-9]$/.test(command))) {
|
|
823
|
+
if (!wasPending) this.vimEngine.reset();
|
|
824
|
+
if (operator.edit) {
|
|
825
|
+
try {
|
|
826
|
+
if (operator.edit.insert) adapter.beginInsertSession();
|
|
827
|
+
if (operator.edit.text || operator.edit.start.line !== operator.edit.end.line ||
|
|
828
|
+
operator.edit.start.col !== operator.edit.end.col) {
|
|
829
|
+
adapter.replace(operator.edit.start, operator.edit.end, operator.edit.text);
|
|
830
|
+
}
|
|
831
|
+
adapter.move(operator.edit.cursor);
|
|
832
|
+
if (operator.edit.insert) {
|
|
833
|
+
adapter.markInsertAnchor();
|
|
834
|
+
this.vimInsertIntent = { operator };
|
|
835
|
+
} else this.vimOperator.remember(operator);
|
|
836
|
+
if (operator.edit.insert) this.enterVimInsert(true, true, false);
|
|
837
|
+
} catch { if (operator.edit.insert) adapter.endInsertSession(); this.vimOperator.cancel(); }
|
|
838
|
+
}
|
|
839
|
+
this.deps.requestRender();
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
if (command === "u" && !this.vimVisual.active) { adapter.undo(); this.vimEngine.reset(); this.deps.requestRender(); return; }
|
|
843
|
+
const motion = this.vimEngine.input(command, this.getText(), this.getCursor(), adapter.motionBoundaries());
|
|
844
|
+
if (motion.handled) {
|
|
845
|
+
if (this.vimVisual.active && motion.insert !== undefined) return;
|
|
846
|
+
try {
|
|
847
|
+
adapter.move(motion.cursor);
|
|
848
|
+
if (motion.insert !== undefined) {
|
|
849
|
+
this.enterVimInsert();
|
|
850
|
+
this.vimInsertIntent = { command };
|
|
851
|
+
}
|
|
852
|
+
if (motion.insert === "\n") {
|
|
853
|
+
this.insertTextAtCursor("\n");
|
|
854
|
+
if (command === "O") this.vimAdapter().move({ line: motion.cursor.line, col: 0 });
|
|
855
|
+
}
|
|
856
|
+
this.deps.requestRender();
|
|
857
|
+
} catch { this.vimEngine.reset(); /* Unsupported private layout: no modal mutation. */ }
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// Encoded Return, Tab, IME and paste are editor input, not
|
|
862
|
+
// app actions. Never forward an unowned NORMAL byte to insertion.
|
|
863
|
+
if (this.vimNormal && !this.keybindingsManager.matches(data, "app.interrupt") && !matchesKey(data, "escape")) return;
|
|
864
|
+
}
|
|
303
865
|
if (
|
|
304
866
|
this.promptState === PROMPT_STATE.WORKING &&
|
|
305
867
|
!this.isShowingAutocomplete() &&
|
|
@@ -355,6 +917,47 @@ export class GentlePromptEditor extends CustomEditor {
|
|
|
355
917
|
super.handleInput(data);
|
|
356
918
|
}
|
|
357
919
|
|
|
920
|
+
/** Buffer a whole paste before any bytes reach Vim's command router. Pi's
|
|
921
|
+
* editor receives the complete frame in INSERT so it retains native paste
|
|
922
|
+
* normalization, marker registration and undo behavior. In NORMAL, discard
|
|
923
|
+
* the entire frame rather than interpreting its contents as keystrokes.
|
|
924
|
+
*/
|
|
925
|
+
private handleVimPasteFrame(data: string): boolean {
|
|
926
|
+
if (this.pasteFrame === undefined) {
|
|
927
|
+
const start = data.indexOf(BRACKETED_PASTE_START);
|
|
928
|
+
if (start < 0) return false;
|
|
929
|
+
// A frame is an atomic event: bytes before its marker must not be
|
|
930
|
+
// accidentally interpreted as a Vim command either.
|
|
931
|
+
this.pasteFrame = "";
|
|
932
|
+
this.pasteOverflow = false;
|
|
933
|
+
data = data.slice(start + BRACKETED_PASTE_START.length);
|
|
934
|
+
}
|
|
935
|
+
// Retain only the terminator's possible prefix between events. This
|
|
936
|
+
// avoids rescanning the entire paste for each single-character chunk.
|
|
937
|
+
const chunk = this.pasteTail + data;
|
|
938
|
+
const end = chunk.indexOf(BRACKETED_PASTE_END);
|
|
939
|
+
const content = end < 0 ? chunk.slice(0, -(BRACKETED_PASTE_END.length - 1)) : chunk.slice(0, end);
|
|
940
|
+
if (!this.pasteOverflow) {
|
|
941
|
+
if (this.pasteFrame.length + content.length > MAX_BRACKETED_PASTE_CHARS) {
|
|
942
|
+
this.pasteFrame = "";
|
|
943
|
+
this.pasteOverflow = true;
|
|
944
|
+
} else this.pasteFrame += content;
|
|
945
|
+
}
|
|
946
|
+
if (end < 0) {
|
|
947
|
+
this.pasteTail = chunk.slice(-(BRACKETED_PASTE_END.length - 1));
|
|
948
|
+
return true;
|
|
949
|
+
}
|
|
950
|
+
const paste = this.pasteFrame;
|
|
951
|
+
const overflow = this.pasteOverflow;
|
|
952
|
+
this.pasteFrame = undefined;
|
|
953
|
+
this.pasteOverflow = false;
|
|
954
|
+
this.pasteTail = "";
|
|
955
|
+
if (!overflow && !this.vimNormal) super.handleInput(BRACKETED_PASTE_START + paste + BRACKETED_PASTE_END);
|
|
956
|
+
const remaining = chunk.slice(end + BRACKETED_PASTE_END.length);
|
|
957
|
+
if (remaining) this.handleInput(remaining);
|
|
958
|
+
return true;
|
|
959
|
+
}
|
|
960
|
+
|
|
358
961
|
/**
|
|
359
962
|
* Runs the Esc that actually aborts the turn. Pi's own onEscape (invoked
|
|
360
963
|
* synchronously by `super.handleInput`) restores `queuedText + draft`
|
|
@@ -386,24 +989,74 @@ export class GentlePromptEditor extends CustomEditor {
|
|
|
386
989
|
this.deps.dispatchQueuedText(queued);
|
|
387
990
|
}
|
|
388
991
|
|
|
992
|
+
handleMouse(event: Parameters<CustomEditor["handleMouse"]>[0]): ReturnType<CustomEditor["handleMouse"]> {
|
|
993
|
+
const layout = this.floatMouseLayout;
|
|
994
|
+
if (!layout) return super.handleMouse(event);
|
|
995
|
+
// Row coordinates stay native: padding=0, content=1…N, hint=N+1.
|
|
996
|
+
// Only float translates x; the existing neon/fallback path is unchanged.
|
|
997
|
+
if (event.x < layout.prefixWidth || event.x >= layout.width - 1) return undefined;
|
|
998
|
+
return super.handleMouse({ ...event, x: event.x - layout.prefixWidth, width: layout.nativeWidth });
|
|
999
|
+
}
|
|
1000
|
+
|
|
389
1001
|
render(width: number): string[] {
|
|
390
|
-
const
|
|
1002
|
+
const layout = resolvePromptLayout(width, cardStyle(), this.deps.bg);
|
|
1003
|
+
this.floatMouseLayout = layout.background ? layout : undefined;
|
|
1004
|
+
const inner = layout.nativeWidth;
|
|
1005
|
+
const lines = super.render(inner);
|
|
391
1006
|
if (this.getText() === "" && lines.length === 3) lines[1] = withPromptHint(lines[1], PROMPT_HINT, this.deps.fg);
|
|
392
1007
|
const state = this.promptState === PROMPT_STATE.WORKING && this.deps.pending() ? PROMPT_STATE.QUEUED : this.promptState;
|
|
393
|
-
//
|
|
394
|
-
//
|
|
395
|
-
|
|
1008
|
+
// Neon keeps the shell's border role; float follows Pi's live public
|
|
1009
|
+
// borderColor callback so thinking/bash mode accents survive.
|
|
1010
|
+
// Selection is applied only to the owned Pi editor rows, before Gentle
|
|
1011
|
+
// frames them. No second editor factory or private layout mutation.
|
|
1012
|
+
let editorLines = lines;
|
|
1013
|
+
if (this.vimPolicy === "on" && this.vimVisual.active) {
|
|
1014
|
+
try {
|
|
1015
|
+
const adapter = this.vimAdapter();
|
|
1016
|
+
const range = this.vimVisual.range(this.getText(), this.getCursor(), adapter.motionBoundaries());
|
|
1017
|
+
if (range) editorLines = adapter.renderSelection(inner, range.start, range.end, lines);
|
|
1018
|
+
} catch { /* Unknown layout: keep the original rendered prompt. */ }
|
|
1019
|
+
}
|
|
1020
|
+
if (this.vimPolicy !== "on") editorLines = this.selectionEngine.decorateRows(editorLines, inner, 0);
|
|
1021
|
+
const visibleCount = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount;
|
|
1022
|
+
const borderEnd = Number.isInteger(visibleCount) && visibleCount! >= 1 && visibleCount! + 2 <= editorLines.length
|
|
1023
|
+
? visibleCount! + 2 : editorLines.length;
|
|
1024
|
+
const framed = framePromptLines(editorLines.slice(0, borderEnd), width, {
|
|
396
1025
|
state,
|
|
397
1026
|
tick: this.tick,
|
|
398
|
-
borderColor: (text) => this.deps.fg(PROMPT_FRAME_ROLE, text),
|
|
1027
|
+
borderColor: (text) => layout.background ? this.borderColor(text) : this.deps.fg(PROMPT_FRAME_ROLE, text),
|
|
399
1028
|
fg: this.deps.fg,
|
|
400
1029
|
bold: this.deps.bold,
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
1030
|
+
workingLabel: this.promptState === PROMPT_STATE.WORKING ? this.deps.workingLabel?.() : undefined,
|
|
1031
|
+
escHint: [
|
|
1032
|
+
this.vimPolicy === "on" ? (this.vimVisual.active ? (this.vimVisual.kind === "line" ? "VISUAL LINE" : "VISUAL") : this.vimNormal ? "NORMAL" : "INSERT") : undefined,
|
|
1033
|
+
this.promptState === PROMPT_STATE.WORKING && this.isPendingEscapeCancel()
|
|
1034
|
+
? DOUBLE_ESC_CANCEL_HINT
|
|
1035
|
+
: this.promptState === PROMPT_STATE.IDLE && this.isPendingIdleClear()
|
|
1036
|
+
? IDLE_ESC_CLEAR_HINT
|
|
1037
|
+
: undefined,
|
|
1038
|
+
].filter(Boolean).join(" · ") || undefined,
|
|
1039
|
+
}, layout);
|
|
1040
|
+
if (this.vimPolicy !== "on") {
|
|
1041
|
+
framed[framed.length - 1] = layout.background
|
|
1042
|
+
? floatPromptRow(this.selectionEngine.decorateBottomRule("", layout.nativeWidth, ""), layout, (text) => this.borderColor(text))
|
|
1043
|
+
: this.selectionEngine.decorateBottomRule(framed[framed.length - 1] ?? "", width, "╯");
|
|
1044
|
+
}
|
|
1045
|
+
// Pi places autocomplete after its bottom border. Keep those rows below
|
|
1046
|
+
// Gentle's frame and preserve their terminal width and row coordinates.
|
|
1047
|
+
for (const line of editorLines.slice(borderEnd)) {
|
|
1048
|
+
if (layout.background) {
|
|
1049
|
+
framed.push(floatPromptRow(line, layout, (text) => this.borderColor(text)));
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
const available = Math.max(0, width);
|
|
1053
|
+
const border = available >= 2 ? "│" : "";
|
|
1054
|
+
const inner = available - border.length * 2;
|
|
1055
|
+
const clipped = truncateToWidth(line, inner, "");
|
|
1056
|
+
framed.push(this.deps.fg(PROMPT_FRAME_ROLE, border) + clipped +
|
|
1057
|
+
" ".repeat(Math.max(0, inner - visibleWidth(clipped))) + this.deps.fg(PROMPT_FRAME_ROLE, border));
|
|
1058
|
+
}
|
|
1059
|
+
return framed;
|
|
407
1060
|
}
|
|
408
1061
|
|
|
409
1062
|
dispose(): void {
|
|
@@ -436,20 +1089,30 @@ type PromptFactory = NonNullable<ReturnType<ExtensionContext["ui"]["getEditorCom
|
|
|
436
1089
|
function installPrompt(
|
|
437
1090
|
ctx: ExtensionContext,
|
|
438
1091
|
onCreated: (prompt: GentlePromptEditor) => void,
|
|
439
|
-
promptDeps: { now: () => number; doubleEscCancelEnabled: () => boolean; dispatchQueuedText: (text: string) => void },
|
|
1092
|
+
promptDeps: { now: () => number; doubleEscCancelEnabled: () => boolean; dispatchQueuedText: (text: string) => void; vimRuntimeVersion?: () => string | undefined },
|
|
440
1093
|
): boolean {
|
|
441
1094
|
const previous = ctx.ui.getEditorComponent() as PromptFactory | undefined;
|
|
442
1095
|
if (previous && !previous[PROMPT_OWNER]) return false;
|
|
443
1096
|
const factory: PromptFactory = (tui, theme, keybindings) => {
|
|
444
1097
|
const prompt = new GentlePromptEditor(tui, theme, keybindings, {
|
|
445
1098
|
fg: (color, text) => ctx.ui.theme.fg(color as Parameters<typeof ctx.ui.theme.fg>[0], text),
|
|
1099
|
+
bg: (color, text) => ctx.ui.theme.bg(color as Parameters<typeof ctx.ui.theme.bg>[0], text),
|
|
446
1100
|
bold: (text) => ctx.ui.theme.bold(text),
|
|
447
1101
|
requestRender: () => tui.requestRender(),
|
|
448
1102
|
pending: () => ctx.hasPendingMessages(),
|
|
449
1103
|
now: promptDeps.now,
|
|
450
1104
|
doubleEscCancelEnabled: promptDeps.doubleEscCancelEnabled,
|
|
451
1105
|
dispatchQueuedText: promptDeps.dispatchQueuedText,
|
|
1106
|
+
notifyCompatibility: (message) => ctx.ui.notify(message, "warning"),
|
|
1107
|
+
tuiVersion: promptDeps.vimRuntimeVersion,
|
|
1108
|
+
workingLabel: () => oddPhaseRegistry.label(ctx.sessionManager.getSessionId()),
|
|
452
1109
|
});
|
|
1110
|
+
// Pi's own docs require an explicit requestRender() after a state change
|
|
1111
|
+
// (docs/tui.md: "Call tui.requestRender() after state changes"); no host
|
|
1112
|
+
// re-render is implicitly guaranteed, and the WORKING pulse loop does not
|
|
1113
|
+
// run at all under the "potato" animation policy. Register this session's
|
|
1114
|
+
// redraw so a phase reported by the tool is visible immediately.
|
|
1115
|
+
oddPhaseRegistry.setRenderRequest(ctx.sessionManager.getSessionId(), () => tui.requestRender());
|
|
453
1116
|
onCreated(prompt);
|
|
454
1117
|
return prompt;
|
|
455
1118
|
};
|
|
@@ -498,6 +1161,7 @@ function renderDoubleEscCancelReport(
|
|
|
498
1161
|
}
|
|
499
1162
|
|
|
500
1163
|
const CHANGES_WIDGET_KEY = "gentle-shell-changes";
|
|
1164
|
+
const HEADER_WIDGET_KEY = "gentle-shell-below-input-header";
|
|
501
1165
|
const CHANGES_COMMAND_NAME = "gentle:changes";
|
|
502
1166
|
const CHANGES_SHORTCUT_DEFAULT = "alt+g";
|
|
503
1167
|
const CHANGES_POLL_DEFAULT_MS = 2000;
|
|
@@ -573,6 +1237,12 @@ function changesPollMs(env: NodeJS.ProcessEnv): number {
|
|
|
573
1237
|
return positiveMs(env.GENTLE_PI_SHELL_CHANGES_POLL_MS, CHANGES_POLL_DEFAULT_MS);
|
|
574
1238
|
}
|
|
575
1239
|
|
|
1240
|
+
// One bounded window per provider refresh: a credential lookup or fetch that
|
|
1241
|
+
// never answers must not hold the other providers — or the panel opening on
|
|
1242
|
+
// them — past it. Tunable (tests, slow networks); invalid values fall back.
|
|
1243
|
+
const USAGE_FETCH_TIMEOUT_DEFAULT_MS = 10_000;
|
|
1244
|
+
const usageFetchTimeoutMs = (env: NodeJS.ProcessEnv): number => positiveMs(env.GENTLE_PI_SHELL_USAGE_TIMEOUT_MS, USAGE_FETCH_TIMEOUT_DEFAULT_MS);
|
|
1245
|
+
|
|
576
1246
|
function changesFingerprint(model: ChangesModel): string {
|
|
577
1247
|
return [model.notice ?? "", ...model.files.map((file) => `${file.path}:${file.status}:${file.added}:${file.deleted}:${file.diffRevision ?? ""}:${file.countsUnavailable ?? ""}`)].join("|");
|
|
578
1248
|
}
|
|
@@ -608,14 +1278,15 @@ async function showChangesOverlay(ctx: ExtensionContext, deps: OverlayDeps): Pro
|
|
|
608
1278
|
try {
|
|
609
1279
|
const chosen = await ctx.ui.custom<{ root: string; file: ChangedFile } | null>(
|
|
610
1280
|
(tui, theme, _keybindings, done) => {
|
|
1281
|
+
const close = withOverlayRepaint(tui, done);
|
|
611
1282
|
host = tui;
|
|
612
1283
|
view = new WorktreeChangesView(worktrees(), {
|
|
613
1284
|
theme,
|
|
614
1285
|
rows: () => Math.max(OVERLAY_MIN_ROWS, Math.floor(tui.terminal.rows * OVERLAY_HEIGHT_RATIO)),
|
|
615
1286
|
loadDiff: (root, file) => Promise.resolve(deps.loadDiff(root, file)),
|
|
616
|
-
onOpen: (root, file) =>
|
|
1287
|
+
onOpen: (root, file) => close({ root, file }),
|
|
617
1288
|
onRefresh: () => void refresh(),
|
|
618
|
-
onClose: () =>
|
|
1289
|
+
onClose: () => close(null),
|
|
619
1290
|
requestRender: () => tui.requestRender(),
|
|
620
1291
|
});
|
|
621
1292
|
return view;
|
|
@@ -648,14 +1319,14 @@ async function showCommandPalette(pi: ExtensionAPI, ctx: ExtensionContext, env:
|
|
|
648
1319
|
return;
|
|
649
1320
|
}
|
|
650
1321
|
const result = await ctx.ui.custom<CommandPaletteResult>(
|
|
651
|
-
(tui, theme, _keybindings, done) => new CommandPalette(groups, done, theme, () => Math.max(0, tui.terminal.rows)),
|
|
1322
|
+
(tui, theme, _keybindings, done) => new CommandPalette(groups, withOverlayRepaint(tui, done), theme, () => Math.max(0, tui.terminal.rows)),
|
|
652
1323
|
{ overlay: true, overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" } },
|
|
653
1324
|
);
|
|
654
1325
|
if (result?.type === "run") pi.sendUserMessage(`/${result.name}`, { expandPromptTemplates: true });
|
|
655
1326
|
}
|
|
656
1327
|
|
|
657
|
-
function showChanges(ctx: ExtensionContext, model: ChangesModel): void {
|
|
658
|
-
if (model.files.length === 0) {
|
|
1328
|
+
function showChanges(ctx: ExtensionContext, model: ChangesModel, visible = true, grouped: (width: number) => boolean = () => false): void {
|
|
1329
|
+
if (!visible || model.files.length === 0) {
|
|
659
1330
|
ctx.ui.setWidget(CHANGES_WIDGET_KEY, undefined);
|
|
660
1331
|
return;
|
|
661
1332
|
}
|
|
@@ -663,7 +1334,7 @@ function showChanges(ctx: ExtensionContext, model: ChangesModel): void {
|
|
|
663
1334
|
CHANGES_WIDGET_KEY,
|
|
664
1335
|
(tui, theme) => sidebarPart(tui, "changes", {
|
|
665
1336
|
render(width: number) {
|
|
666
|
-
return renderChangesWidget(model, theme, width);
|
|
1337
|
+
return grouped(width) ? [] : renderChangesWidget(model, theme, width);
|
|
667
1338
|
},
|
|
668
1339
|
invalidate() {},
|
|
669
1340
|
}),
|
|
@@ -684,6 +1355,7 @@ function messageText(content: string | Array<{ type: string; text?: string }>):
|
|
|
684
1355
|
|
|
685
1356
|
interface CardComponentOptions {
|
|
686
1357
|
expanded: boolean;
|
|
1358
|
+
previewRows?: number;
|
|
687
1359
|
hint?: string;
|
|
688
1360
|
}
|
|
689
1361
|
|
|
@@ -707,15 +1379,19 @@ function spaced(component: { render(width: number): string[]; invalidate(): void
|
|
|
707
1379
|
};
|
|
708
1380
|
}
|
|
709
1381
|
|
|
1382
|
+
// Same rose identity as the Gentle AI tool cards (lib/gentle-ai-renderer.ts).
|
|
1383
|
+
const GENTLE_AI_GLYPH = "\u{1F339}";
|
|
1384
|
+
|
|
710
1385
|
export function devBinaryCard(notice: DevBinaryNotice): Card {
|
|
711
1386
|
if (notice.state === "invalid") {
|
|
712
|
-
return { title: "
|
|
1387
|
+
return { title: "gentle-ai", subtitle: "dev binary override invalid", body: [notice.reason], tone: CARD_TONE.ERROR, glyph: GENTLE_AI_GLYPH };
|
|
713
1388
|
}
|
|
714
1389
|
return {
|
|
715
|
-
title: "
|
|
1390
|
+
title: "gentle-ai",
|
|
716
1391
|
subtitle: "dev binary override · field-test only",
|
|
717
1392
|
body: [`${notice.path} · sha256:${notice.sha256.slice(0, SHA_PREFIX_LENGTH)}`],
|
|
718
1393
|
tone: CARD_TONE.WARNING,
|
|
1394
|
+
glyph: GENTLE_AI_GLYPH,
|
|
719
1395
|
};
|
|
720
1396
|
}
|
|
721
1397
|
|
|
@@ -773,7 +1449,15 @@ async function fetchFromSource(source: UsageSource, apiKey: string | undefined,
|
|
|
773
1449
|
export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = process.env, overrides: Partial<ShellDeps> = {}): void {
|
|
774
1450
|
installSessionChangeCapture(pi, env, overrides.resolveWorktree ?? resolveSessionWorktree);
|
|
775
1451
|
if (!shellEnabled(env)) return;
|
|
776
|
-
const
|
|
1452
|
+
const profileReader = createActiveProfileReader(env);
|
|
1453
|
+
const deps: ShellDeps = { ...defaultShellDeps, activeProfile: profileReader, ...overrides };
|
|
1454
|
+
let closeCustomize: (() => void) | undefined;
|
|
1455
|
+
let profilePoll: ReturnType<typeof setInterval> | undefined;
|
|
1456
|
+
const stopProfilePoll = () => {
|
|
1457
|
+
if (profilePoll) clearInterval(profilePoll);
|
|
1458
|
+
profilePoll = undefined;
|
|
1459
|
+
profileReader.reset();
|
|
1460
|
+
};
|
|
777
1461
|
const usage = new UsageStore();
|
|
778
1462
|
// Providers gentle-shell has never heard of get a usage source too, when
|
|
779
1463
|
// the extension that owns them registers one on pi.events; see the
|
|
@@ -783,30 +1467,137 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
783
1467
|
// The 5-minute rule is per provider: one provider's fetch cannot leave the
|
|
784
1468
|
// next one waiting for an interval it never used.
|
|
785
1469
|
const usageFetchedAt = new Map<string, number>();
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
if (
|
|
806
|
-
|
|
1470
|
+
// Actual failures, per provider: a refresh that settled without a snapshot.
|
|
1471
|
+
// In-flight fetches are never in here, so they cannot read as failed; a
|
|
1472
|
+
// successful refresh (or a snapshot otherwise recorded) clears the provider.
|
|
1473
|
+
const usageFailures = new Set<string>();
|
|
1474
|
+
// Monotonic per-provider generation: each dispatched refresh takes the next
|
|
1475
|
+
// number, and only the newest one for a provider may mutate its state. Two
|
|
1476
|
+
// overlapping refreshes of the SAME source (or of builtins) can otherwise
|
|
1477
|
+
// let an older failure settle after a newer success and poison it.
|
|
1478
|
+
const usageGenerations = new Map<string, number>();
|
|
1479
|
+
// One spelling of the config home, so the pin resolver, the global profiles
|
|
1480
|
+
// store and the profile reader cannot drift onto two different stores.
|
|
1481
|
+
const usageConfigHome = gentlePiConfigHome(env);
|
|
1482
|
+
const usageFetchTimeout = usageFetchTimeoutMs(env);
|
|
1483
|
+
// The subagent routing in force for this session: a repository pin first,
|
|
1484
|
+
// then the global active profile. Only the profile's own role entries count;
|
|
1485
|
+
// the reserved orchestrator key is not a route.
|
|
1486
|
+
const activeRoutingModels = (ctx: ExtensionContext): Array<string | undefined> => {
|
|
1487
|
+
const pin = resolveProfilePin({ cwd: ctx.cwd, configHome: usageConfigHome, resolveWorktree: deps.resolveWorktree });
|
|
1488
|
+
const config = pin ? pin.modelProfiles : undefined;
|
|
1489
|
+
if (config) return [...profileRoleEntries(config).map(([, entry]) => entry.model)];
|
|
1490
|
+
const store = readProfilesFileResult(profilesFilePath(usageConfigHome));
|
|
1491
|
+
const active = store.status === "valid" && store.file.active !== undefined ? store.file.profiles[store.file.active] : undefined;
|
|
1492
|
+
return active ? profileRoleEntries(active).map(([, entry]) => entry.model) : [];
|
|
1493
|
+
};
|
|
1494
|
+
// A bare model id names a provider only when exactly one provider in the
|
|
1495
|
+
// registry carries that id; anything else stays untargeted rather than guessed.
|
|
1496
|
+
const bareModelProvider = (ctx: ExtensionContext, modelId: string): string | undefined => {
|
|
1497
|
+
try {
|
|
1498
|
+
const providers = new Set(ctx.modelRegistry.getAll().filter((model) => model.id === modelId).map((model) => model.provider));
|
|
1499
|
+
return providers.size === 1 ? [...providers][0] : undefined;
|
|
1500
|
+
} catch {
|
|
1501
|
+
return undefined;
|
|
1502
|
+
}
|
|
1503
|
+
};
|
|
1504
|
+
const usageScopeFor = (ctx: ExtensionContext): string[] =>
|
|
1505
|
+
usageScopeProviders(ctx.model?.provider, activeRoutingModels(ctx), (modelId) => bareModelProvider(ctx, modelId));
|
|
1506
|
+
let usageScope: string[] = [];
|
|
1507
|
+
// The scope is Git/filesystem work, so it is resolved once per refresh and
|
|
1508
|
+
// per registration — never per panel render, which only reads the cache.
|
|
1509
|
+
const resolveUsageScope = (ctx: ExtensionContext): string[] => {
|
|
1510
|
+
usageScope = usageScopeFor(ctx);
|
|
1511
|
+
return usageScope;
|
|
1512
|
+
};
|
|
1513
|
+
// One notification per settled provider — snapshot or failure — so the
|
|
1514
|
+
// shell and the open overlay repaint immediately instead of waiting for
|
|
1515
|
+
// the whole refresh, whose slowest member is the bounded window itself.
|
|
1516
|
+
const notifyUsageSettled = () => {
|
|
807
1517
|
renderHost?.invalidateSidebar?.();
|
|
808
1518
|
renderHost?.requestRender();
|
|
809
1519
|
};
|
|
1520
|
+
// One bounded, self-contained refresh per provider. Providers run
|
|
1521
|
+
// concurrently: a stalled credential lookup or fetch for one can never hold
|
|
1522
|
+
// the others — or the overlay opening on them — past its own window.
|
|
1523
|
+
const refreshProvider = async (ctx: ExtensionContext, provider: string, source: UsageSource | undefined, force: boolean, now: number): Promise<boolean> => {
|
|
1524
|
+
if (!source && provider !== CODEX_PROVIDER && provider !== NAN_PROVIDER) return false;
|
|
1525
|
+
if (!force && now - (usageFetchedAt.get(provider) ?? 0) < USAGE_REFRESH_MS) return false;
|
|
1526
|
+
usageFetchedAt.set(provider, now);
|
|
1527
|
+
const generation = (usageGenerations.get(provider) ?? 0) + 1;
|
|
1528
|
+
usageGenerations.set(provider, generation);
|
|
1529
|
+
// The window covers credential resolution and the fetch together. The
|
|
1530
|
+
// abort signal reaches the underlying fetch through the wrapped fetchFn —
|
|
1531
|
+
// built-ins and registered sources alike — so an expired provider is
|
|
1532
|
+
// actually cancelled when its caller honors the signal. The race is the
|
|
1533
|
+
// only path to state mutation: whatever the work resolves after the
|
|
1534
|
+
// window expired is a value nobody reads, so a late answer — success or
|
|
1535
|
+
// failure — cannot mutate anything.
|
|
1536
|
+
const controller = new AbortController();
|
|
1537
|
+
let expire: (() => void) | undefined;
|
|
1538
|
+
const expired = new Promise<"timeout">((resolve) => { expire = () => resolve("timeout"); });
|
|
1539
|
+
const timer = setTimeout(() => {
|
|
1540
|
+
controller.abort();
|
|
1541
|
+
expire?.();
|
|
1542
|
+
}, usageFetchTimeout);
|
|
1543
|
+
// The window's signal composes with whatever the caller already carries —
|
|
1544
|
+
// init.signal, or a Request input's own signal — instead of replacing it:
|
|
1545
|
+
// either side aborting still aborts, exactly like a plain fetch. With no
|
|
1546
|
+
// caller signal the window's signal passes through unchanged.
|
|
1547
|
+
const boundedFetch: typeof fetch = (input, init) => {
|
|
1548
|
+
const callerSignal = init?.signal ?? (typeof Request !== "undefined" && input instanceof Request ? input.signal : undefined);
|
|
1549
|
+
return deps.fetch(input, {
|
|
1550
|
+
...init,
|
|
1551
|
+
signal: callerSignal ? AbortSignal.any([callerSignal, controller.signal]) : controller.signal,
|
|
1552
|
+
});
|
|
1553
|
+
};
|
|
1554
|
+
const work = (async () => {
|
|
1555
|
+
const apiKey = await ctx.modelRegistry.getApiKeyForProvider(provider).catch(() => undefined);
|
|
1556
|
+
// The window may have expired while the credential was resolving: an
|
|
1557
|
+
// aborted provider must not start its fetch at all.
|
|
1558
|
+
if (controller.signal.aborted) return undefined;
|
|
1559
|
+
return source
|
|
1560
|
+
? fetchFromSource(source, apiKey, boundedFetch, deps.now())
|
|
1561
|
+
: provider === NAN_PROVIDER
|
|
1562
|
+
? fetchNanUsage(apiKey, boundedFetch, deps.now())
|
|
1563
|
+
: fetchCodexUsage(apiKey, boundedFetch, deps.now());
|
|
1564
|
+
})();
|
|
1565
|
+
// The race's loser still runs to completion in the background: guard it so
|
|
1566
|
+
// its rejection (a foreign source escaping its own catch) can never
|
|
1567
|
+
// surface as unhandled, and clear the timer so nothing dangles.
|
|
1568
|
+
const guarded = work.catch(() => undefined);
|
|
1569
|
+
const settled = await Promise.race([guarded, expired]);
|
|
1570
|
+
clearTimeout(timer);
|
|
1571
|
+
// Discard before any state mutation: a generation mismatch means a newer
|
|
1572
|
+
// refresh for this provider was dispatched and owns the state, and a
|
|
1573
|
+
// replaced source's answer belongs to neither. A late success must not
|
|
1574
|
+
// overwrite the newer snapshot, and a late failure must not mark the
|
|
1575
|
+
// provider failed after its replacement succeeded.
|
|
1576
|
+
if (usageGenerations.get(provider) !== generation) return false;
|
|
1577
|
+
if (source && usageSources.get(provider) !== source) return false;
|
|
1578
|
+
if (settled === "timeout" || !settled) {
|
|
1579
|
+
usageFailures.add(provider);
|
|
1580
|
+
notifyUsageSettled();
|
|
1581
|
+
return false;
|
|
1582
|
+
}
|
|
1583
|
+
usage.record(settled);
|
|
1584
|
+
usageFailures.delete(provider);
|
|
1585
|
+
notifyUsageSettled();
|
|
1586
|
+
return true;
|
|
1587
|
+
};
|
|
1588
|
+
const refreshUsage = async (ctx: ExtensionContext, force: boolean, only?: string) => {
|
|
1589
|
+
const scope = resolveUsageScope(ctx);
|
|
1590
|
+
const now = deps.now();
|
|
1591
|
+
// Concurrent per provider; each settle notifies the shell (and repaints
|
|
1592
|
+
// the open overlay) on its own, so a fast provider never waits for the
|
|
1593
|
+
// slowest one's window. A discarded late answer notifies nothing: the
|
|
1594
|
+
// refresh that owns the state notifies at its own settle.
|
|
1595
|
+
await Promise.all(
|
|
1596
|
+
scope
|
|
1597
|
+
.filter((provider) => only === undefined || provider === only)
|
|
1598
|
+
.map((provider) => refreshProvider(ctx, provider, usageSources.get(provider), force, now)),
|
|
1599
|
+
);
|
|
1600
|
+
};
|
|
810
1601
|
// Subscribed once, for the life of the extension: a registration can
|
|
811
1602
|
// arrive before the first session_start (the owning extension's factory
|
|
812
1603
|
// runs first) or after it (its own session_start fires later, or it
|
|
@@ -817,36 +1608,49 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
817
1608
|
const source = parseUsageSource(payload);
|
|
818
1609
|
if (!source) return;
|
|
819
1610
|
usageSources.register(source);
|
|
820
|
-
if (currentContext
|
|
1611
|
+
if (!currentContext) return;
|
|
1612
|
+
// A registration is interesting when its provider is targeted at all —
|
|
1613
|
+
// the session's own or a subagent route of the active profile — and then
|
|
1614
|
+
// only that provider is forced, never the whole scope.
|
|
1615
|
+
if (resolveUsageScope(currentContext).includes(source.provider)) void refreshUsage(currentContext, true, source.provider);
|
|
821
1616
|
});
|
|
822
1617
|
pi.on("after_provider_response", (event) => {
|
|
823
1618
|
const parsed = parseUsageHeaders(event.headers, deps.now());
|
|
824
1619
|
if (!parsed) return;
|
|
825
1620
|
usage.record(parsed);
|
|
1621
|
+
// A snapshot that arrived with a response is evidence the provider is
|
|
1622
|
+
// answering: a failure some earlier refresh recorded no longer stands.
|
|
1623
|
+
usageFailures.delete(parsed.provider);
|
|
826
1624
|
renderHost?.invalidateSidebar?.();
|
|
827
1625
|
renderHost?.requestRender();
|
|
828
1626
|
});
|
|
829
1627
|
pi.registerMessageRenderer(REVIEW_PREFLIGHT_TYPE, (message, options, theme) => {
|
|
830
|
-
const
|
|
1628
|
+
const lines = messageText(message.content as string | Array<{ type: string; text?: string }>).split("\n");
|
|
1629
|
+
const body = options.expanded ? lines : lines.filter((line) => line.trim() !== "");
|
|
831
1630
|
const hint = keyHint("app.tools.expand", options.expanded ? "collapse" : "expand");
|
|
832
|
-
return cardComponent({ title: "Gentle AI", subtitle: "review preflight", body, tone: CARD_TONE.INFO }, theme, { expanded: options.expanded, hint });
|
|
1631
|
+
return cardComponent({ title: "Gentle AI", subtitle: "review preflight", body, tone: CARD_TONE.INFO }, theme, { expanded: options.expanded, previewRows: 3, hint });
|
|
833
1632
|
});
|
|
834
|
-
const openUsage =
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
new UsageView(usage, {
|
|
1633
|
+
const openUsage = (ctx: ExtensionContext) =>
|
|
1634
|
+
ctx.ui.custom<null>(
|
|
1635
|
+
(tui, theme, _keybindings, done) => {
|
|
1636
|
+
const view = new UsageView(usage, {
|
|
839
1637
|
theme,
|
|
840
1638
|
now: () => deps.now(),
|
|
841
1639
|
active: () => (ctx.model ? { provider: ctx.model.provider } : undefined),
|
|
842
1640
|
registry: () => usageSources,
|
|
843
1641
|
onRefresh: () => refreshUsage(ctx, true),
|
|
844
|
-
onClose: () => done(null),
|
|
1642
|
+
onClose: () => withOverlayRepaint(tui, done)(null),
|
|
845
1643
|
requestRender: () => tui.requestRender(),
|
|
846
|
-
|
|
1644
|
+
scope: () => ({ providers: usageScope, failed: new Set(usageFailures) }),
|
|
1645
|
+
});
|
|
1646
|
+
// Open promptly: the panel draws whatever the store already holds
|
|
1647
|
+
// while the forced refresh runs underneath it, and repaints when
|
|
1648
|
+
// the refresh settles — answers, failures, or the bounded timeout.
|
|
1649
|
+
view.refresh();
|
|
1650
|
+
return view;
|
|
1651
|
+
},
|
|
847
1652
|
{ overlay: true, overlayOptions: { width: "70%", minWidth: 60, anchor: "center" } },
|
|
848
1653
|
);
|
|
849
|
-
};
|
|
850
1654
|
pi.registerCommand(USAGE_COMMAND_NAME, {
|
|
851
1655
|
description: "Show subscription usage windows for the connected providers. Press r to refetch.",
|
|
852
1656
|
handler: async (_args, ctx) => openUsage(ctx),
|
|
@@ -875,6 +1679,29 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
875
1679
|
const doubleEscCancelConfigHome = gentlePiConfigHome(env);
|
|
876
1680
|
const animationOptions = { gentlePiConfigHome: doubleEscCancelConfigHome };
|
|
877
1681
|
let animationPolicy = resolveAnimationPolicy(animationOptions).policy;
|
|
1682
|
+
let vimPolicy = resolveVimPolicy(animationOptions).policy;
|
|
1683
|
+
// Conversation cards read the style from a process-wide slot; the saved
|
|
1684
|
+
// preference fills it at startup and again on every session start.
|
|
1685
|
+
const applyCardStyle = () => setCardStyle(resolveCardStyle(animationOptions).style);
|
|
1686
|
+
applyCardStyle();
|
|
1687
|
+
const reportVim = (ctx: ExtensionContext, result: ReturnType<typeof resolveVimPolicy>) => {
|
|
1688
|
+
const source = result.source === "default" ? "built-in default" : `global file ${result.globalFile}`;
|
|
1689
|
+
const effective = prompt?.effectiveVimPolicy;
|
|
1690
|
+
const state = effective === undefined ? "No active Gentle prompt; preference applies when one starts" :
|
|
1691
|
+
effective !== result.policy ? `Effective prompt: ${effective}; saved preference and prompt differ; ordinary editing remains active` :
|
|
1692
|
+
result.policy === "off" ? "Prompt applies now; ordinary editing active" : "Prompt applies now";
|
|
1693
|
+
ctx.ui.notify(`vim: ${result.policy} (decided by ${source})${result.malformed ? "; malformed or unreadable file, falling back to off" : ""}. ${state}.`, result.malformed || (effective !== undefined && effective !== result.policy) ? "warning" : "info");
|
|
1694
|
+
};
|
|
1695
|
+
let visualSettings = resolveVisualSettings(animationOptions).settings;
|
|
1696
|
+
let sidebarTui: TUI | undefined;
|
|
1697
|
+
let groupedChangesOwner: (width: number) => boolean = () => false;
|
|
1698
|
+
const refreshVisual = () => {
|
|
1699
|
+
visualSettings = resolveVisualSettings(animationOptions).settings;
|
|
1700
|
+
if (currentContext && changes) showChanges(currentContext, changes.model, visualSettings.visibility.changes, (width) => groupedChangesOwner(width));
|
|
1701
|
+
if (sidebarTui?.terminal) sidebarState(sidebarTui).visibility = { todo: visualSettings.visibility.todo };
|
|
1702
|
+
renderHost?.invalidateSidebar?.();
|
|
1703
|
+
renderHost?.requestRender();
|
|
1704
|
+
};
|
|
878
1705
|
let doubleEscCancelPolicy: DoubleEscCancelPolicy = resolveDoubleEscCancelPolicy({
|
|
879
1706
|
env,
|
|
880
1707
|
gentlePiConfigHome: doubleEscCancelConfigHome,
|
|
@@ -882,12 +1709,28 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
882
1709
|
let changes: SessionChanges | undefined;
|
|
883
1710
|
let registry: SessionWorktreeRegistry | undefined;
|
|
884
1711
|
let currentContext: ExtensionContext | undefined;
|
|
1712
|
+
let review: ReviewSidebarSnapshot | undefined;
|
|
1713
|
+
const redrawReview = () => {
|
|
1714
|
+
renderHost?.invalidateSidebar?.();
|
|
1715
|
+
renderHost?.requestRender();
|
|
1716
|
+
};
|
|
1717
|
+
const unsubscribeReview = pi.events.on(REVIEW_SIDEBAR_EVENT, (value) => {
|
|
1718
|
+
const event = value as { sessionId?: unknown; snapshot?: unknown } | undefined;
|
|
1719
|
+
if (!currentContext || event?.sessionId !== currentContext.sessionManager.getSessionId()) return;
|
|
1720
|
+
if (!isReviewSidebarSnapshot(event.snapshot)) return;
|
|
1721
|
+
review = { state: event.snapshot.state, scope: event.snapshot.scope };
|
|
1722
|
+
redrawReview();
|
|
1723
|
+
});
|
|
1724
|
+
pi.on("session_tree", () => {
|
|
1725
|
+
review = undefined;
|
|
1726
|
+
redrawReview();
|
|
1727
|
+
});
|
|
885
1728
|
let shown = "";
|
|
886
1729
|
const applyChanges = (ctx: ExtensionContext, model: ChangesModel) => {
|
|
887
1730
|
const fingerprint = changesFingerprint(model);
|
|
888
1731
|
if (fingerprint === shown) return;
|
|
889
1732
|
shown = fingerprint;
|
|
890
|
-
showChanges(ctx, model);
|
|
1733
|
+
showChanges(ctx, model, visualSettings.visibility.changes, (width) => groupedChangesOwner(width));
|
|
891
1734
|
};
|
|
892
1735
|
const refreshChanges = async (ctx: ExtensionContext) => {
|
|
893
1736
|
const tracker = changes;
|
|
@@ -916,17 +1759,38 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
916
1759
|
},
|
|
917
1760
|
});
|
|
918
1761
|
pi.on("session_start", async (_event, ctx) => {
|
|
1762
|
+
closeCustomize?.();
|
|
1763
|
+
if (review) {
|
|
1764
|
+
review = undefined;
|
|
1765
|
+
redrawReview();
|
|
1766
|
+
}
|
|
1767
|
+
stopProfilePoll();
|
|
919
1768
|
registry?.close();
|
|
920
1769
|
currentContext = ctx;
|
|
921
1770
|
changes = undefined;
|
|
922
1771
|
registry = new SessionWorktreeRegistry(pi, ctx.sessionManager, ctx.cwd, deps.resolveWorktree);
|
|
923
1772
|
registry.start();
|
|
1773
|
+
applyCardStyle();
|
|
924
1774
|
if (!ctx.hasUI) return;
|
|
1775
|
+
visualSettings = resolveVisualSettings(animationOptions).settings;
|
|
1776
|
+
if (!overrides.activeProfile) {
|
|
1777
|
+
profileReader.bind(ctx.cwd, deps.resolveWorktree);
|
|
1778
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
1779
|
+
profilePoll = setInterval(() => {
|
|
1780
|
+
if (currentContext !== ctx || ctx.sessionManager.getSessionId() !== sessionId) return;
|
|
1781
|
+
if (!profileReader.refresh()) return;
|
|
1782
|
+
renderHost?.invalidateSidebar?.();
|
|
1783
|
+
renderHost?.requestRender();
|
|
1784
|
+
}, 2_000);
|
|
1785
|
+
profilePoll.unref?.();
|
|
1786
|
+
}
|
|
925
1787
|
changes = new SessionChanges(ctx.sessionManager.getSessionId(), ctx.sessionManager.getEntries());
|
|
926
1788
|
const tracker = changes;
|
|
927
1789
|
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
1790
|
+
sidebarTui = tui;
|
|
1791
|
+
if (tui.terminal) sidebarState(tui).visibility = { todo: visualSettings.visibility.todo };
|
|
928
1792
|
renderHost = { requestRender: () => tui.requestRender(), invalidateSidebar: () => invalidateSidebar(tui) };
|
|
929
|
-
const bottom = createShellBarComponent(pi, ctx, renderHost, theme, footerData, () => tracker.model.files.length, () => usage.get(ctx.model?.provider ?? ""));
|
|
1793
|
+
const bottom = createShellBarComponent(pi, ctx, renderHost, theme, footerData, () => tracker.model.files.length, () => usage.get(ctx.model?.provider ?? ""), () => visualSettings);
|
|
930
1794
|
// The Status card paints live session state that no event re-registers a
|
|
931
1795
|
// part for: model, effort, context, cost, session name and extension
|
|
932
1796
|
// statuses. The digest is what keeps the fullscreen memo honest, and it
|
|
@@ -934,31 +1798,79 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
934
1798
|
const footerModel = (): ShellBarModel => ({
|
|
935
1799
|
...buildShellBarModel(pi, ctx, footerData, { dirty: tracker.model.files.length, usage: usage.get(ctx.model?.provider ?? ""), profile: deps.activeProfile() }),
|
|
936
1800
|
changes: { files: tracker.model.files.length, added: tracker.model.added, deleted: tracker.model.deleted, notice: tracker.model.notice },
|
|
1801
|
+
review,
|
|
937
1802
|
});
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
1803
|
+
// At narrow fullscreen widths only one status row paints: a top header
|
|
1804
|
+
// suppresses the bottom bar in the layout, and otherwise the bottom bar
|
|
1805
|
+
// takes over the header's data while the below-input header steps aside.
|
|
1806
|
+
const statusOwner = () => narrowStatusOwner({ mode: (tui as TUI & { mode?: string }).mode, columns: tui.terminal?.columns ?? 0, statusPlacement: visualSettings.statusPlacement, headerPlacement: visualSettings.headerPlacement });
|
|
1807
|
+
const belowFloat = (width: number, statuses: boolean) => (tui as TUI & { mode?: string }).mode === "fullscreen"
|
|
1808
|
+
? renderShellBelowInputFloat({ ...footerModel(), ...(statuses ? {} : { statuses: [] }) }, theme, width, usageShortcutKey, visualSettings, tracker.model)
|
|
1809
|
+
: undefined;
|
|
1810
|
+
// Match sidebarPart's live paint ownership, including an unavailable rail.
|
|
1811
|
+
const footerSuppressed = () => {
|
|
1812
|
+
if (!tui.terminal) return false;
|
|
1813
|
+
const state = sidebarState(tui);
|
|
1814
|
+
return Boolean(state.statusHidden?.() || state.headerOwnsStatus?.() || (state.active && state.ownsHost?.()));
|
|
1815
|
+
};
|
|
1816
|
+
groupedChangesOwner = (width) => belowFloat(width, !footerSuppressed()) !== undefined;
|
|
1817
|
+
const bottomBar = {
|
|
1818
|
+
...bottom,
|
|
1819
|
+
render: (width: number) => belowFloat(width, true)?.rows ?? (statusOwner() === STATUS_OWNER.BOTTOM ? renderShellBottomOnlyBar(footerModel(), theme, width, usageShortcutKey, visualSettings) : bottom.render(width)),
|
|
1820
|
+
handleMouse(event: Parameters<NonNullable<SidebarRail["handleMouse"]>>[0]) {
|
|
1821
|
+
if (footerSuppressed() || event.type !== "click" || event.button !== "left") return undefined;
|
|
1822
|
+
const chrome = belowFloat(event.width, true);
|
|
1823
|
+
if (!chrome || !shellHeaderUsageHit(chrome, event.x, event.y)) return undefined;
|
|
1824
|
+
void openUsage(ctx);
|
|
1825
|
+
return { handled: true, render: true };
|
|
1826
|
+
},
|
|
1827
|
+
};
|
|
1828
|
+
const part = sidebarPart(tui, "footer", bottomBar, {
|
|
1829
|
+
digest: () => JSON.stringify([footerModel(), tracker.model, visualSettings, cardStyle()]),
|
|
1830
|
+
render: (width) => renderShellSidebarBar(footerModel(), theme, width, visualSettings),
|
|
941
1831
|
invalidate() {},
|
|
942
1832
|
});
|
|
943
1833
|
// The header row carries everything that ticks every frame (model,
|
|
944
1834
|
// effort, context, cost, usage) plus session identity; it never sees
|
|
945
1835
|
// extension statuses or the working/thinking state.
|
|
946
|
-
const headerBar = (width: number) =>
|
|
1836
|
+
const headerBar = (width: number) => renderShellHeaderChrome(buildShellHeaderModel(footerModel()), theme, width, usageShortcutKey, visualSettings);
|
|
947
1837
|
const disposeHeader = sidebarHeader(tui, {
|
|
948
|
-
digest: () => JSON.stringify(
|
|
949
|
-
render: (width) =>
|
|
1838
|
+
digest: () => JSON.stringify([footerModel(), tracker.model, visualSettings, cardStyle()]),
|
|
1839
|
+
render: (width) => headerBar(width).rows,
|
|
950
1840
|
invalidate() {},
|
|
951
1841
|
handleMouse(event) {
|
|
952
1842
|
if (event.type !== "click" || event.button !== "left") return undefined;
|
|
953
|
-
if (event.
|
|
954
|
-
const { usageSpan } = headerBar(event.width);
|
|
955
|
-
if (!usageSpan || event.x < usageSpan.start || event.x >= usageSpan.end) return undefined;
|
|
1843
|
+
if (!shellHeaderUsageHit(headerBar(event.width), event.x, event.y)) return undefined;
|
|
956
1844
|
void openUsage(ctx);
|
|
957
1845
|
return { handled: true, render: true };
|
|
958
1846
|
},
|
|
959
1847
|
});
|
|
960
|
-
const uninstall = installSidebar(tui, theme);
|
|
961
|
-
|
|
1848
|
+
const uninstall = installSidebar(tui, theme, () => visualSettings.statusPlacement, () => visualSettings.headerPlacement, () => visualSettings.density);
|
|
1849
|
+
// The public widget slot follows the editor even when the rail is absent.
|
|
1850
|
+
const belowHeader = () => visualSettings.headerPlacement === "below-input" && (tui as TUI & { mode?: string }).mode === "fullscreen" && statusOwner() !== STATUS_OWNER.BOTTOM;
|
|
1851
|
+
const widgetChrome = (width: number) => belowFloat(width, false) ?? headerBar(width);
|
|
1852
|
+
ctx.ui.setWidget(HEADER_WIDGET_KEY, () => ({
|
|
1853
|
+
render(width: number) {
|
|
1854
|
+
if (belowFloat(width, false)) return footerSuppressed() ? widgetChrome(width).rows : [];
|
|
1855
|
+
return belowHeader() ? headerBar(width).rows : [];
|
|
1856
|
+
},
|
|
1857
|
+
invalidate() {},
|
|
1858
|
+
handleMouse(event) {
|
|
1859
|
+
const grouped = belowFloat(event.width, false);
|
|
1860
|
+
if ((grouped ? !footerSuppressed() : !belowHeader()) || event.type !== "click" || event.button !== "left") return undefined;
|
|
1861
|
+
if (!shellHeaderUsageHit(widgetChrome(event.width), event.x, event.y)) return undefined;
|
|
1862
|
+
void openUsage(ctx);
|
|
1863
|
+
return { handled: true, render: true };
|
|
1864
|
+
},
|
|
1865
|
+
}), { placement: "belowEditor" });
|
|
1866
|
+
return { ...part,
|
|
1867
|
+
render(width: number) {
|
|
1868
|
+
const rows = part.render(width);
|
|
1869
|
+
// Preserve a shrinkable exterior dock row, outside prompt/completion geometry.
|
|
1870
|
+
return rows.length === 0 && (tui as TUI & { mode?: string }).mode === "fullscreen"
|
|
1871
|
+
&& resolvePromptLayout(width, cardStyle(), theme.bg?.bind(theme)).background ? [""] : rows;
|
|
1872
|
+
},
|
|
1873
|
+
dispose() { ctx.ui.setWidget(HEADER_WIDGET_KEY, undefined); disposeHeader(); uninstall(); part.dispose(); if (sidebarTui === tui) { sidebarTui = undefined; groupedChangesOwner = () => false; } } };
|
|
962
1874
|
});
|
|
963
1875
|
void refreshUsage(ctx, true);
|
|
964
1876
|
const ownsPrompt = installPrompt(
|
|
@@ -967,8 +1879,9 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
967
1879
|
prompt?.dispose();
|
|
968
1880
|
prompt = created;
|
|
969
1881
|
prompt.setAnimationPolicy(animationPolicy);
|
|
1882
|
+
prompt.setVimPolicy(vimPolicy);
|
|
970
1883
|
},
|
|
971
|
-
{ now: () => deps.now(), doubleEscCancelEnabled: () => doubleEscCancelPolicy === "on", dispatchQueuedText: (text) => { pendingQueuedText = pendingQueuedText === undefined ? text : `${pendingQueuedText}\n\n${text}`; } },
|
|
1884
|
+
{ now: () => deps.now(), doubleEscCancelEnabled: () => doubleEscCancelPolicy === "on", dispatchQueuedText: (text) => { pendingQueuedText = pendingQueuedText === undefined ? text : `${pendingQueuedText}\n\n${text}`; }, vimRuntimeVersion: deps.vimRuntimeVersion },
|
|
972
1885
|
);
|
|
973
1886
|
// Hide native feedback only when our petal replaces it. Native transcript
|
|
974
1887
|
// thinking blocks remain Pi-owned; this changes only the supported loader UI.
|
|
@@ -977,7 +1890,7 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
977
1890
|
ctx.ui.setWidget(
|
|
978
1891
|
DEV_BINARY_WIDGET_KEY,
|
|
979
1892
|
notice
|
|
980
|
-
? (_tui, theme) => spaced(cardComponent(devBinaryCard(notice), theme, { expanded: true }))
|
|
1893
|
+
? (_tui, theme) => spaced(cardComponent(devBinaryCard(notice), theme, { expanded: true, previewRows: 3 }))
|
|
981
1894
|
: undefined,
|
|
982
1895
|
);
|
|
983
1896
|
if (changes !== tracker) return;
|
|
@@ -985,6 +1898,17 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
985
1898
|
applyChanges(ctx, tracker.model);
|
|
986
1899
|
});
|
|
987
1900
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
1901
|
+
closeCustomize?.();
|
|
1902
|
+
if (review) {
|
|
1903
|
+
review = undefined;
|
|
1904
|
+
redrawReview();
|
|
1905
|
+
}
|
|
1906
|
+
// Pi rebuilds the extension runtime after every shutdown (reload, replacement,
|
|
1907
|
+
// fork, quit), so the factory-level subscription never needs to be restored.
|
|
1908
|
+
unsubscribeReview();
|
|
1909
|
+
stopProfilePoll();
|
|
1910
|
+
oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
|
|
1911
|
+
oddPhaseRegistry.clearRenderRequest(ctx.sessionManager.getSessionId());
|
|
988
1912
|
pendingQueuedText = undefined;
|
|
989
1913
|
prompt?.dispose();
|
|
990
1914
|
prompt = undefined;
|
|
@@ -1030,6 +1954,345 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
1030
1954
|
handler: async (ctx) => showCommandPalette(pi, ctx, env),
|
|
1031
1955
|
});
|
|
1032
1956
|
}
|
|
1957
|
+
pi.registerCommand("gentle:customize", {
|
|
1958
|
+
description: "Configure appearance, global Vim prompt editing, session-only YOLO permission and prompt history capture.",
|
|
1959
|
+
handler: async (_args, ctx) => {
|
|
1960
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
1961
|
+
if (ctx.hasUI) ctx.ui.notify("Visual customization requires an interactive terminal.", "warning");
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
closeCustomize?.();
|
|
1965
|
+
let closed = false;
|
|
1966
|
+
let adapter: YoloUiAdapter | undefined;
|
|
1967
|
+
let unobserve: (() => void) | undefined;
|
|
1968
|
+
let finish: (() => void) | undefined;
|
|
1969
|
+
const close = () => {
|
|
1970
|
+
if (closed) return;
|
|
1971
|
+
closed = true;
|
|
1972
|
+
unobserve?.(); adapter?.dispose(); finish?.();
|
|
1973
|
+
if (closeCustomize === close) closeCustomize = undefined;
|
|
1974
|
+
};
|
|
1975
|
+
closeCustomize = close;
|
|
1976
|
+
const home = { gentlePiConfigHome: doubleEscCancelConfigHome };
|
|
1977
|
+
const rows: CustomizeRow[] = [];
|
|
1978
|
+
const bannerHome = doubleEscCancelConfigHome;
|
|
1979
|
+
let banner = await readBannerConfig(bannerHome).catch(error => { close(); throw error; });
|
|
1980
|
+
if (closed) return;
|
|
1981
|
+
let activeTheme = ctx.ui.theme.name;
|
|
1982
|
+
let customizeView: VisualCustomizeView | undefined;
|
|
1983
|
+
let requestCustomizeRender: (() => void) | undefined;
|
|
1984
|
+
let category: CustomizeCategory = "Animations";
|
|
1985
|
+
const add = (label: CustomizeRow["label"], notice: string, action: () => void | false | Promise<void | false>, preview?: CustomizeRow["preview"]) => rows.push({ category, label, preview, action: async () => {
|
|
1986
|
+
if (await action() === false) return;
|
|
1987
|
+
ctx.ui.notify(notice, "info");
|
|
1988
|
+
} });
|
|
1989
|
+
for (const policy of ["quality", "performance", "potato"] as const) add(
|
|
1990
|
+
() => `Animations: ${policy}${resolveAnimationPolicy(animationOptions).policy === policy ? " (current)" : ""}`,
|
|
1991
|
+
"Animation saved. Prompt applies now; startup banner applies at next startup.",
|
|
1992
|
+
() => {
|
|
1993
|
+
writeAnimationPolicy(policy, animationOptions);
|
|
1994
|
+
animationPolicy = resolveAnimationPolicy(animationOptions).policy;
|
|
1995
|
+
prompt?.setAnimationPolicy(animationPolicy);
|
|
1996
|
+
},
|
|
1997
|
+
() => ({ title: `${policy} · static animation sample`, sample: policy === "potato" ? "✿ idle → working (no pulse)" : policy === "performance" ? "✿ short pulse → settle (static)" : "✿ gentle wave → settle (static)" }),
|
|
1998
|
+
);
|
|
1999
|
+
category = "Banner";
|
|
2000
|
+
const bannerColors = { pink: [255, 118, 195], cyan: [95, 210, 255], yellow: [255, 210, 95], green: [110, 220, 145] } as const;
|
|
2001
|
+
const bannerPreview = (next: typeof banner) => {
|
|
2002
|
+
const [r, g, b] = bannerColors[next.color];
|
|
2003
|
+
return { title: `Banner · ${next.color} (static)`, sample: `${next.showRose ? `\x1b[38;2;${r};${g};${b}m🌹\x1b[0m` : "·"} ${next.showTextLogo ? "GENTLE SHELL" : "(logo hidden)"}` };
|
|
2004
|
+
};
|
|
2005
|
+
add(() => `Banner rose: ${banner.showRose ? "on" : "off"}`, "Banner saved; applies at next startup.", async () => {
|
|
2006
|
+
const next = { ...await readBannerConfigForEdit(bannerHome) };
|
|
2007
|
+
next.showRose = !next.showRose;
|
|
2008
|
+
await writeBannerConfig(next, bannerHome);
|
|
2009
|
+
banner = next;
|
|
2010
|
+
}, () => bannerPreview({ ...banner, showRose: !banner.showRose }));
|
|
2011
|
+
add(() => `Banner text logo: ${banner.showTextLogo ? "on" : "off"}`, "Banner saved; applies at next startup.", async () => {
|
|
2012
|
+
const next = { ...await readBannerConfigForEdit(bannerHome) };
|
|
2013
|
+
next.showTextLogo = !next.showTextLogo;
|
|
2014
|
+
await writeBannerConfig(next, bannerHome);
|
|
2015
|
+
banner = next;
|
|
2016
|
+
}, () => bannerPreview({ ...banner, showTextLogo: !banner.showTextLogo }));
|
|
2017
|
+
for (const color of BANNER_COLORS) add(
|
|
2018
|
+
() => `Banner color: ${color}${banner.color === color ? " (current)" : ""}`,
|
|
2019
|
+
"Banner saved; applies at next startup.",
|
|
2020
|
+
async () => { const next = { ...await readBannerConfigForEdit(bannerHome), color }; await writeBannerConfig(next, bannerHome); banner = next; },
|
|
2021
|
+
() => bannerPreview({ ...banner, color }),
|
|
2022
|
+
);
|
|
2023
|
+
category = "Themes";
|
|
2024
|
+
try {
|
|
2025
|
+
if (typeof ctx.ui.getAllThemes !== "function" || typeof ctx.ui.getTheme !== "function" || typeof ctx.ui.setTheme !== "function") throw new Error("theme API unavailable");
|
|
2026
|
+
const themes = ctx.ui.getAllThemes();
|
|
2027
|
+
if (!Array.isArray(themes)) throw new Error("invalid theme list");
|
|
2028
|
+
const names = [...new Set(themes.map((item) => item?.name).filter((name): name is string => typeof name === "string" && !!name && !name.includes("/")))];
|
|
2029
|
+
if (names.length === 0) throw new Error("no installed themes");
|
|
2030
|
+
for (const name of names) rows.push({
|
|
2031
|
+
category,
|
|
2032
|
+
label: () => `Theme: ${name}${activeTheme === name ? " (current)" : ""}`,
|
|
2033
|
+
preview: () => {
|
|
2034
|
+
const selected = ctx.ui.getTheme(name);
|
|
2035
|
+
if (selected?.name !== name) throw new Error("Selected theme is unavailable.");
|
|
2036
|
+
const source = selected.sourcePath ?? ctx.ui.getAllThemes().find((item) => item.name === name)?.path;
|
|
2037
|
+
return sourcePalettePreview(name, source);
|
|
2038
|
+
},
|
|
2039
|
+
action: () => {
|
|
2040
|
+
if (!ctx.ui.getTheme(name)) throw new Error(`Theme ${name} is unavailable or invalid.`);
|
|
2041
|
+
const result = ctx.ui.setTheme(name);
|
|
2042
|
+
if (!result.success) throw new Error(result.error ?? `Could not activate theme ${name}.`);
|
|
2043
|
+
activeTheme = name;
|
|
2044
|
+
ctx.ui.notify("Theme applies now and is saved by Pi.", "info");
|
|
2045
|
+
},
|
|
2046
|
+
});
|
|
2047
|
+
} catch {
|
|
2048
|
+
rows.push({ category, label: "Themes unavailable; use Pi /settings", preview: () => ({ title: "Themes unavailable", sample: "Use Pi /settings to select a theme" }), action: () => ctx.ui.notify("Installed themes are unavailable in this session.", "warning") });
|
|
2049
|
+
}
|
|
2050
|
+
const updateVisual = (change: (settings: ReturnType<typeof resolveVisualSettings>["settings"]) => ReturnType<typeof resolveVisualSettings>["settings"]) => {
|
|
2051
|
+
const current = resolveVisualSettings(home);
|
|
2052
|
+
if (current.malformed || current.readError) throw new Error(`Cannot update unreadable or malformed visual settings: ${current.globalFile}`);
|
|
2053
|
+
writeVisualSettings(change(current.settings), home);
|
|
2054
|
+
refreshVisual();
|
|
2055
|
+
pi.events.emit(VISUAL_SETTINGS_CHANGED, { configHome: doubleEscCancelConfigHome });
|
|
2056
|
+
};
|
|
2057
|
+
const visual = () => resolveVisualSettings(home).settings;
|
|
2058
|
+
const pending = "Preference saved and applied.";
|
|
2059
|
+
const layoutPreview = (settings: ReturnType<typeof visual>) => ({
|
|
2060
|
+
title: `Layout · ${settings.density} (schematic)`,
|
|
2061
|
+
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]"}`,
|
|
2062
|
+
});
|
|
2063
|
+
category = "Editor";
|
|
2064
|
+
for (const [label, policy] of [["enable", "on"], ["disable", "off"]] as const) rows.push({
|
|
2065
|
+
category,
|
|
2066
|
+
label: () => `Vim: ${label}${resolveVimPolicy(animationOptions).policy === policy ? " (current preference)" : ""}`,
|
|
2067
|
+
preview: () => {
|
|
2068
|
+
const result = resolveVimPolicy(animationOptions);
|
|
2069
|
+
const effective = prompt?.effectiveVimPolicy ?? "no active prompt";
|
|
2070
|
+
return { title: "Vim · global prompt editing", sample: `preference: ${result.policy} · effective: ${effective}${result.malformed ? " · malformed or unreadable file" : result.policy !== effective && effective !== "no active prompt" ? " · preference and prompt differ" : ""}` };
|
|
2071
|
+
},
|
|
2072
|
+
action: () => {
|
|
2073
|
+
const current = resolveVimPolicy(animationOptions);
|
|
2074
|
+
if (current.malformed) throw new Error(`Cannot update malformed or unreadable Vim policy: ${current.globalFile}`);
|
|
2075
|
+
writeVimPolicy(policy, animationOptions);
|
|
2076
|
+
const result = resolveVimPolicy(animationOptions);
|
|
2077
|
+
vimPolicy = result.policy;
|
|
2078
|
+
prompt?.setVimPolicy(vimPolicy);
|
|
2079
|
+
reportVim(ctx, result);
|
|
2080
|
+
},
|
|
2081
|
+
});
|
|
2082
|
+
let yoloDisplay: YoloDisplay = YOLO_DISPLAY.unavailable;
|
|
2083
|
+
let requestYoloRender = () => {};
|
|
2084
|
+
let refreshing: Promise<void> | undefined;
|
|
2085
|
+
let refreshAgain = false;
|
|
2086
|
+
// One in-flight read and one dirty bit coalesce slash/action/revocation
|
|
2087
|
+
// changes. Labels and previews only read the authority-free snapshot.
|
|
2088
|
+
const refreshYolo = (): Promise<void> => {
|
|
2089
|
+
refreshAgain = true;
|
|
2090
|
+
if (refreshing) return refreshing;
|
|
2091
|
+
refreshing = (async () => {
|
|
2092
|
+
while (refreshAgain && !closed) {
|
|
2093
|
+
refreshAgain = false;
|
|
2094
|
+
const next = await adapter?.read().catch(() => YOLO_DISPLAY.unavailable) ?? YOLO_DISPLAY.unavailable;
|
|
2095
|
+
if (closed) return;
|
|
2096
|
+
yoloDisplay = next;
|
|
2097
|
+
requestYoloRender();
|
|
2098
|
+
}
|
|
2099
|
+
})().finally(() => { refreshing = undefined; });
|
|
2100
|
+
return refreshing;
|
|
2101
|
+
};
|
|
2102
|
+
rows.push({
|
|
2103
|
+
category,
|
|
2104
|
+
label: () => `YOLO: ${yoloDisplay} · session only`,
|
|
2105
|
+
preview: () => ({ title: "YOLO · session permission", sample: "ordinary scoped commits/push/PR · destructive confirmations remain · review consent unchanged · reset on reload" }),
|
|
2106
|
+
action: async () => {
|
|
2107
|
+
if (closed) return;
|
|
2108
|
+
if (!adapter || yoloDisplay === YOLO_DISPLAY.unavailable) {
|
|
2109
|
+
ctx.ui.notify("YOLO is unavailable in this live primary session.", "warning");
|
|
2110
|
+
return;
|
|
2111
|
+
}
|
|
2112
|
+
await adapter.toggle();
|
|
2113
|
+
await refreshYolo();
|
|
2114
|
+
},
|
|
2115
|
+
});
|
|
2116
|
+
category = "History";
|
|
2117
|
+
// The prompt-history extension re-reads this preference per prompt, so a
|
|
2118
|
+
// change applies without restart. An explicit GENTLE_PI_HISTORY_CAPTURE
|
|
2119
|
+
// value wins; the rows say so instead of silently ignoring the choice.
|
|
2120
|
+
const historyCapture = () => resolveHistoryCapture({ env, gentlePiConfigHome: doubleEscCancelConfigHome });
|
|
2121
|
+
for (const [label, policy] of [["enable", "on"], ["disable", "off"]] as const) rows.push({
|
|
2122
|
+
category,
|
|
2123
|
+
label: () => {
|
|
2124
|
+
const result = historyCapture();
|
|
2125
|
+
return `Prompt history capture: ${label}${result.preference === policy && !result.malformed ? " (current)" : ""}${result.envOverride ? " · env override" : ""}`;
|
|
2126
|
+
},
|
|
2127
|
+
preview: () => {
|
|
2128
|
+
const result = historyCapture();
|
|
2129
|
+
const effective = result.enabled ? "on" : "off";
|
|
2130
|
+
return { title: "Prompt history capture · Customize preference", sample: `preference: ${result.preference} · effective: ${effective}${result.malformed ? " · malformed or unreadable file" : ""}${result.envOverride ? " · GENTLE_PI_HISTORY_CAPTURE overrides this preference" : ""}` };
|
|
2131
|
+
},
|
|
2132
|
+
action: () => {
|
|
2133
|
+
const current = historyCapture();
|
|
2134
|
+
if (current.malformed) throw new Error(`Cannot update malformed or unreadable history capture preference: ${current.globalFile}`);
|
|
2135
|
+
writeHistoryCapturePolicy(policy, { gentlePiConfigHome: doubleEscCancelConfigHome });
|
|
2136
|
+
const result = historyCapture();
|
|
2137
|
+
if (result.envOverride) ctx.ui.notify(`Prompt history capture preference saved: ${result.preference}. GENTLE_PI_HISTORY_CAPTURE=${result.envOverride} overrides it; capture stays ${result.envOverride}.`, "warning");
|
|
2138
|
+
else ctx.ui.notify(result.enabled ? "Prompt history capture: on. Applies from the next prompt; stored history is kept." : "Prompt history capture: off. New prompts are not recorded; stored history is kept.", "info");
|
|
2139
|
+
},
|
|
2140
|
+
});
|
|
2141
|
+
category = "Layout";
|
|
2142
|
+
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 }));
|
|
2143
|
+
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 }));
|
|
2144
|
+
for (const value of Object.values(DENSITY)) add(() => `Density: ${value}${visual().density === value ? " (current)" : ""}`, pending, () => updateVisual((settings) => ({ ...settings, density: value })), () => layoutPreview({ ...visual(), density: value }));
|
|
2145
|
+
category = "Cards";
|
|
2146
|
+
// One live style for conversation cards, panels, header/footer and prompt.
|
|
2147
|
+
const cardStylePreview = { [CARD_STYLE.NEON]: "╭─ ✿ read ─╮ outlined chrome + prompt", [CARD_STYLE.FLOAT]: "▎ ✿ read painted chrome + prompt" };
|
|
2148
|
+
for (const style of Object.values(CARD_STYLE)) add(
|
|
2149
|
+
() => {
|
|
2150
|
+
const current = resolveCardStyle(home);
|
|
2151
|
+
return `Card style: ${style}${current.style === style && !current.malformed ? " (current)" : ""}`;
|
|
2152
|
+
},
|
|
2153
|
+
`Card style: ${style}. Conversation cards and shell chrome redraw now.`,
|
|
2154
|
+
() => {
|
|
2155
|
+
writeCardStyle(style, home);
|
|
2156
|
+
setCardStyle(style);
|
|
2157
|
+
renderHost?.invalidateSidebar?.();
|
|
2158
|
+
renderHost?.requestRender();
|
|
2159
|
+
requestCustomizeRender?.();
|
|
2160
|
+
},
|
|
2161
|
+
() => ({ title: `Cards · ${style}`, sample: `${cardStylePreview[style]}${resolveCardStyle(home).malformed ? " · malformed or unreadable file" : ""}` }),
|
|
2162
|
+
);
|
|
2163
|
+
category = "Sections";
|
|
2164
|
+
for (const key of VISUAL_SECTION_KEYS) add(
|
|
2165
|
+
() => `Section ${key}: ${visual().visibility[key] ? "shown" : "hidden"}`,
|
|
2166
|
+
pending,
|
|
2167
|
+
() => updateVisual((settings) => ({ ...settings, visibility: { ...settings.visibility, [key]: !settings.visibility[key] } })),
|
|
2168
|
+
() => {
|
|
2169
|
+
const visibility = { ...visual().visibility, [key]: !visual().visibility[key] };
|
|
2170
|
+
return { title: `Sections · ${key} ${visibility[key] ? "shown" : "hidden"}`, sample: `[${Object.entries(visibility).filter(([, shown]) => shown).map(([section]) => section).join("] [") || "no optional sections"}]` };
|
|
2171
|
+
},
|
|
2172
|
+
);
|
|
2173
|
+
const catalog = () => listVisualProfiles(home).map(name => getVisualProfile(name, home)!);
|
|
2174
|
+
category = "Profiles";
|
|
2175
|
+
rows.push({ category, label: "Visual profiles (preview, save, apply, delete)", preview: () => {
|
|
2176
|
+
const saved = catalog()[0];
|
|
2177
|
+
return saved ? { title: `${saved.name} · saved profile`, sample: `${saved.visual.headerPlacement === "top" ? "[Header] → [Input]" : "[Input] → [Header]"} [${saved.visual.statusPlacement} status]` } : { title: "No saved profiles", sample: "Enter to save the current appearance" };
|
|
2178
|
+
}, action: () => {
|
|
2179
|
+
catalog();
|
|
2180
|
+
customizeView?.openProfiles();
|
|
2181
|
+
ctx.ui.notify("Profile preview opened; selections do not change preferences.", "info");
|
|
2182
|
+
} });
|
|
2183
|
+
category = "Reset";
|
|
2184
|
+
add("Reset visual, banner and animation defaults", "Defaults saved. Layout and prompt apply now; banner at next startup.", async (): Promise<void | false> => {
|
|
2185
|
+
// Validate the banner before touching any store. The writes below are
|
|
2186
|
+
// independent, not a transaction: report precisely what succeeded.
|
|
2187
|
+
await readBannerConfigForEdit(bannerHome);
|
|
2188
|
+
const changed: string[] = [];
|
|
2189
|
+
try {
|
|
2190
|
+
writeVisualSettings(structuredClone(DEFAULT_VISUAL_SETTINGS), home);
|
|
2191
|
+
refreshVisual();
|
|
2192
|
+
pi.events.emit(VISUAL_SETTINGS_CHANGED, { configHome: doubleEscCancelConfigHome });
|
|
2193
|
+
changed.push("visual");
|
|
2194
|
+
await writeBannerConfig({ ...DEFAULT_BANNER_CONFIG }, bannerHome);
|
|
2195
|
+
banner = { ...DEFAULT_BANNER_CONFIG };
|
|
2196
|
+
changed.push("banner");
|
|
2197
|
+
writeAnimationPolicy("quality", animationOptions);
|
|
2198
|
+
animationPolicy = resolveAnimationPolicy(animationOptions).policy;
|
|
2199
|
+
prompt?.setAnimationPolicy(animationPolicy);
|
|
2200
|
+
changed.push("animation");
|
|
2201
|
+
} catch (error) {
|
|
2202
|
+
const state = ["visual", "banner", "animation"].map((store) => `${store} ${changed.includes(store) ? "changed" : "unchanged"}`).join(", ");
|
|
2203
|
+
ctx.ui.notify(`Partial reset: ${state}. ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
2204
|
+
return false;
|
|
2205
|
+
}
|
|
2206
|
+
}, () => ({ title: "Restore visual defaults", sample: "[Header] → [Input] [responsive status] · quality" }));
|
|
2207
|
+
const profiles: ProfileActions = {
|
|
2208
|
+
list: catalog,
|
|
2209
|
+
save: async (name, replace) => {
|
|
2210
|
+
const visual = resolveVisualSettings(home);
|
|
2211
|
+
if (visual.malformed || visual.readError) throw new Error("Visual settings unavailable for snapshot.");
|
|
2212
|
+
const currentBanner = await readBannerConfigForEdit(bannerHome);
|
|
2213
|
+
const currentAnimation = resolveAnimationPolicy(animationOptions);
|
|
2214
|
+
if (currentAnimation.malformed) throw new Error(`Cannot read animation policy: ${currentAnimation.globalFile}`);
|
|
2215
|
+
const themeName = ctx.ui.theme.name;
|
|
2216
|
+
if (!themeName || !ctx.ui.getAllThemes?.().some((item) => item.name === themeName) || !ctx.ui.getTheme?.(themeName)) throw new Error("Active theme is not installed or valid; profile not saved.");
|
|
2217
|
+
saveVisualProfile(name, { themeName, animationPolicy: currentAnimation.policy, banner: currentBanner, visual: visual.settings }, { ...home, replace });
|
|
2218
|
+
ctx.ui.notify(`Visual profile ${name} saved.`, "info");
|
|
2219
|
+
},
|
|
2220
|
+
apply: async (name) => {
|
|
2221
|
+
const profile = getVisualProfile(name, home);
|
|
2222
|
+
if (!profile) throw new Error(`Visual profile ${name} not found.`);
|
|
2223
|
+
const changed: string[] = [];
|
|
2224
|
+
const failures: string[] = [];
|
|
2225
|
+
const step = async (label: string, action: () => void | Promise<void>) => {
|
|
2226
|
+
try { await action(); changed.push(label); } catch (error) { failures.push(`${label}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
2227
|
+
};
|
|
2228
|
+
await step("theme", () => {
|
|
2229
|
+
if (!ctx.ui.getTheme?.(profile.themeName)) throw new Error("Installed theme unavailable.");
|
|
2230
|
+
const result = ctx.ui.setTheme(profile.themeName);
|
|
2231
|
+
if (!result.success) throw new Error(result.error ?? "Theme activation failed.");
|
|
2232
|
+
activeTheme = profile.themeName;
|
|
2233
|
+
});
|
|
2234
|
+
await step("visual", () => {
|
|
2235
|
+
const current = resolveVisualSettings(home);
|
|
2236
|
+
if (current.malformed || current.readError) throw new Error("Visual settings unreadable.");
|
|
2237
|
+
writeVisualSettings(profile.visual, home);
|
|
2238
|
+
refreshVisual();
|
|
2239
|
+
pi.events.emit(VISUAL_SETTINGS_CHANGED, { configHome: doubleEscCancelConfigHome });
|
|
2240
|
+
});
|
|
2241
|
+
await step("banner", async () => { await readBannerConfigForEdit(bannerHome); await writeBannerConfig(profile.banner, bannerHome); banner = profile.banner; });
|
|
2242
|
+
await step("animation", () => { writeAnimationPolicy(profile.animationPolicy, animationOptions); animationPolicy = profile.animationPolicy; prompt?.setAnimationPolicy(animationPolicy); });
|
|
2243
|
+
ctx.ui.notify(failures.length ? `PARTIAL profile apply: ${changed.join(", ") || "none"} changed; ${failures.join("; ")}` : `Visual profile ${name} applied; banner applies at next startup.`, failures.length ? "warning" : "info");
|
|
2244
|
+
},
|
|
2245
|
+
delete: (name) => { deleteVisualProfile(name, home); ctx.ui.notify(`Visual profile ${name} deleted.`, "info"); },
|
|
2246
|
+
reset: () => { resetVisualProfiles(home); ctx.ui.notify("Visual profile catalog cleared; active settings unchanged.", "info"); },
|
|
2247
|
+
};
|
|
2248
|
+
try {
|
|
2249
|
+
adapter = await discoverYoloUiAdapter(pi, ctx);
|
|
2250
|
+
if (closed) { adapter?.dispose(); return; }
|
|
2251
|
+
unobserve = adapter?.observe(() => { void refreshYolo(); });
|
|
2252
|
+
await refreshYolo();
|
|
2253
|
+
if (closed) return;
|
|
2254
|
+
await ctx.ui.custom<null>((tui, theme, _keys, done) => {
|
|
2255
|
+
finish = () => done(null);
|
|
2256
|
+
if (closed) done(null);
|
|
2257
|
+
requestYoloRender = () => { if (!closed) tui.requestRender(); };
|
|
2258
|
+
requestCustomizeRender = requestYoloRender;
|
|
2259
|
+
customizeView = new VisualCustomizeView({ rows, profiles, theme, requestRender: requestYoloRender, rowsAvailable: () => Math.max(0, Math.floor(tui.terminal.rows * 0.85) - 2), onError: (error) => { if (!closed) ctx.ui.notify(`Visual customization: ${error.message}`, "error"); }, onClose: close });
|
|
2260
|
+
const view = customizeView;
|
|
2261
|
+
// Own interaction lifetime here, leaving the shared view unchanged.
|
|
2262
|
+
return {
|
|
2263
|
+
render: (width) => closed ? [] : view.render(width),
|
|
2264
|
+
handleInput: (data) => { if (!closed) view.handleInput(data); },
|
|
2265
|
+
invalidate: () => { if (!closed) view.invalidate(); },
|
|
2266
|
+
dispose: close,
|
|
2267
|
+
};
|
|
2268
|
+
}, { overlay: true, overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" } });
|
|
2269
|
+
} finally { close(); }
|
|
2270
|
+
},
|
|
2271
|
+
});
|
|
2272
|
+
pi.registerCommand("gentle:vim", {
|
|
2273
|
+
description: "Show or set global Vim prompt editing (status|enable|disable); no argument opens a menu.",
|
|
2274
|
+
handler: async (args, ctx) => {
|
|
2275
|
+
let action = args.trim() || "status";
|
|
2276
|
+
if (!args.trim() && ctx.hasUI && typeof ctx.ui.select === "function") {
|
|
2277
|
+
const selected = await ctx.ui.select(`Gentle Vim (current: ${vimPolicy})`, ["enable", "disable", "status"]);
|
|
2278
|
+
if (selected === undefined) return;
|
|
2279
|
+
action = selected;
|
|
2280
|
+
}
|
|
2281
|
+
if (action !== "status" && action !== "enable" && action !== "disable") {
|
|
2282
|
+
ctx.ui.notify("Use /gentle:vim status|enable|disable.", "warning");
|
|
2283
|
+
return;
|
|
2284
|
+
}
|
|
2285
|
+
try {
|
|
2286
|
+
if (action !== "status") writeVimPolicy(action === "enable" ? "on" : "off", animationOptions);
|
|
2287
|
+
const result = resolveVimPolicy(animationOptions);
|
|
2288
|
+
vimPolicy = result.policy;
|
|
2289
|
+
prompt?.setVimPolicy(vimPolicy);
|
|
2290
|
+
reportVim(ctx, result);
|
|
2291
|
+
} catch (error) {
|
|
2292
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
2293
|
+
}
|
|
2294
|
+
},
|
|
2295
|
+
});
|
|
1033
2296
|
pi.registerCommand("gentle:animations", {
|
|
1034
2297
|
description: "Show or set global animations; no argument opens a selectable menu (quality|performance|potato, plus status).",
|
|
1035
2298
|
// No argument opens a selectable menu when an interactive UI is present;
|
|
@@ -1101,15 +2364,39 @@ export default function gentleShell(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
|
|
|
1101
2364
|
// below has delivered the pending text. Nothing is sent from here: Pi
|
|
1102
2365
|
// is mid-turn, so the text simply waits and goes out, once, when that
|
|
1103
2366
|
// turn settles. It is never dropped.
|
|
2367
|
+
// A new turn always starts unlabeled: any ODD phase reported for the
|
|
2368
|
+
// previous turn must never leak into this one. The new turn's tool
|
|
2369
|
+
// activity, or an explicit orchestrator report, labels it again.
|
|
2370
|
+
oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
|
|
1104
2371
|
prompt?.setWorking(true);
|
|
1105
2372
|
// The dev-binary card is a startup notice: it leaves with the first prompt.
|
|
1106
2373
|
if (ctx.hasUI) ctx.ui.setWidget(DEV_BINARY_WIDGET_KEY, undefined);
|
|
1107
2374
|
});
|
|
2375
|
+
pi.on("tool_execution_start", (event, ctx) => {
|
|
2376
|
+
// The working label follows the primary session's own tool activity so
|
|
2377
|
+
// it never depends on the model remembering gentle_odd_phase, which
|
|
2378
|
+
// stays the explicit refinement (its report is already explicit).
|
|
2379
|
+
// Subagents run as headless `pi --mode rpc` children whose env never
|
|
2380
|
+
// carries the interactive-host signal (lib/agents-runner.ts), so they
|
|
2381
|
+
// never infer; their process-local registry could not reach this
|
|
2382
|
+
// label anyway.
|
|
2383
|
+
if (!ctx.hasUI || !isInteractiveMode(ctx.mode) || event.toolName === "gentle_odd_phase") return;
|
|
2384
|
+
const phase = inferOddPhase(event.toolName, event.args);
|
|
2385
|
+
if (phase) {
|
|
2386
|
+
const delegated = event.toolName === "subagent_run" || /^mcp__.+?__subagent_run$/.test(event.toolName);
|
|
2387
|
+
oddPhaseRegistry.infer(ctx.sessionManager.getSessionId(), phase, delegated ? "delegation" : "tool");
|
|
2388
|
+
}
|
|
2389
|
+
});
|
|
1108
2390
|
pi.on("agent_settled", (_event, ctx) => {
|
|
1109
2391
|
// Pi clears its own run-active flag before emitting agent_settled, so
|
|
1110
2392
|
// this is normally idle; if a run is somehow still in flight the prompt
|
|
1111
2393
|
// stays working and the pending text waits for the next settle.
|
|
1112
2394
|
if (!ctx.isIdle()) return;
|
|
2395
|
+
// Covers both a normal finish and an aborted turn settling idle: the
|
|
2396
|
+
// input falls back to the generic "working…" label until the next
|
|
2397
|
+
// turn's own agent_start clears it again (belt-and-suspenders with the
|
|
2398
|
+
// clear above).
|
|
2399
|
+
oddPhaseRegistry.clear(ctx.sessionManager.getSessionId());
|
|
1113
2400
|
prompt?.setWorking(false);
|
|
1114
2401
|
if (pendingQueuedText === undefined) return;
|
|
1115
2402
|
const queued = pendingQueuedText;
|