pi-sakura-cyberdeck 1.5.3 → 1.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/README.md +15 -12
  3. package/README.zh-CN.md +2 -2
  4. package/extensions/changelog/index.ts +186 -42
  5. package/extensions/claude-shimmer/index.ts +336 -140
  6. package/extensions/header/index.ts +84 -41
  7. package/extensions/matrix/index.ts +221 -69
  8. package/extensions/shared/color.ts +90 -36
  9. package/extensions/shared/config-file.ts +324 -0
  10. package/extensions/shared/tui-context.ts +99 -0
  11. package/extensions/zentui/config.ts +87 -128
  12. package/extensions/zentui/extension-status.ts +158 -19
  13. package/extensions/zentui/footer-format.ts +279 -85
  14. package/extensions/zentui/footer-segments.ts +630 -0
  15. package/extensions/zentui/footer.ts +668 -525
  16. package/extensions/zentui/format.ts +43 -19
  17. package/extensions/zentui/git.ts +362 -167
  18. package/extensions/zentui/gradient.ts +102 -61
  19. package/extensions/zentui/index.ts +206 -61
  20. package/extensions/zentui/live-context.ts +2 -1
  21. package/extensions/zentui/package-version.ts +102 -14
  22. package/extensions/zentui/project-refresh.ts +42 -20
  23. package/extensions/zentui/project-state.ts +2 -2
  24. package/extensions/zentui/runtime.ts +140 -51
  25. package/extensions/zentui/selector-border.ts +96 -16
  26. package/extensions/zentui/session-lifecycle.ts +3 -1
  27. package/extensions/zentui/settings-command.ts +403 -245
  28. package/extensions/zentui/shell-call.ts +140 -26
  29. package/extensions/zentui/style.ts +109 -40
  30. package/extensions/zentui/thinking-trail.ts +129 -17
  31. package/extensions/zentui/tool-execution.ts +154 -67
  32. package/extensions/zentui/ui.ts +698 -145
  33. package/extensions/zentui/user-message.ts +34 -16
  34. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -3,6 +3,139 @@
3
3
  All notable changes to pi-sakura-cyberdeck. Pi >= 1.5.0 shows new package entries
4
4
  once after updating; run `/sakura-changelog` on any supported Pi to read this file.
5
5
 
6
+ ## [1.5.5] - 2026-12-03
7
+
8
+ ### Highlights
9
+
10
+ - **Linear sakura→sky frame gradients**: sent messages, tool cards and selector borders now flow
11
+ linearly from sakura pink (`#F2A7C6`) on the left to sky blue (`#9FD3F2`) on the right, with
12
+ sky-blue right tool rails (`│`) matching `╮` and `╯`.
13
+ - **Fullscreen `auto` scrollbar border clearance**: tool cards and user message hairlines reserve
14
+ 1 right-edge column under Pi's default fullscreen `auto` scrollbar so the scrollbar no longer
15
+ overwrites card right borders.
16
+
17
+ ### Fixed
18
+
19
+ - **Linear sakura→sky frame gradients**: `renderSakuraFrameGradient` now delegates directly to the
20
+ linear sakura→sky gradient (matching the editor and header) instead of curving pink → sky → pink.
21
+ Tool card right vertical rails (`│`) now use sky blue (`#9FD3F2`) so `╮`, `│` and `╯` connect
22
+ seamlessly.
23
+ - **Fullscreen `auto` scrollbar border clearance**: in Pi's fullscreen mode under the default
24
+ `fullscreenScrollbar: "auto"` setting, `ScrollView` passes full width `W` to transcript children
25
+ and overlays the transient scrollbar onto column `W - 1`, overwriting tool card right borders.
26
+ Tool cards and user message hairlines now reserve 1 right-edge column in fullscreen `"auto"` mode
27
+ (leaving `"always"`, `"hidden"` and `regular` mode untouched) so frames stay closed, aligned and
28
+ jitter-free while scrolling, with mouse hit-testing and render caches updated across live mode and
29
+ setting switches.
30
+
31
+ ### Docs
32
+
33
+ - Updated README and social preview screenshots (`docs/screenshots/session.png` and
34
+ `docs/screenshots/social-preview.png`) to match the linear sakura→sky borders and sky-blue right
35
+ tool rails.
36
+
37
+ ## [1.5.4] - 2026-12-03
38
+
39
+ ### Highlights
40
+
41
+ - **Full Pi 1.7.0 compatibility**: honors Pi's `readonly string[]` render contract and `Container`
42
+ frame-identity caching, adapts `/zentui` to Pi 1.7.0's lowercase keybinding-driven `SettingsList`
43
+ hints, adds mouse and keybinding support to dialogs, and resolves config paths lazily for
44
+ `--agent-dir`.
45
+ - **Faster rendering & non-blocking probes**: identity-preserving frame caches for the footer,
46
+ editor and selector borders, gradient/style caching with SGR coalescing, linear parsing for custom
47
+ footer formats and Thought trails, and fully async git, runtime and package-version probes with
48
+ cancellation.
49
+ - **Hardened persistence & lifecycle**: atomic symlink- and size-guarded config saves, live `/theme`
50
+ switches without restarting Pi, BiDi/SGR sanitization for extension statuses, and zero hanging
51
+ timers across all five extensions.
52
+
53
+ ### Added
54
+
55
+ - Mouse and keybinding support in interactive dialogs:
56
+ - `/zentui` settings modal supports clicking section tabs, clicking list items and mouse-wheel
57
+ scrolling with overscroll containment.
58
+ - `/sakura-changelog` supports mouse-wheel scrolling, `Ctrl+C` close and Pi's `tui.select.*`
59
+ keybindings.
60
+ - Atomic JSON config persistence (`extensions/shared/config-file.ts`) with automatic parent
61
+ directory creation, symlink and file-mode preservation, pre-read regular-file and size guards,
62
+ `fsync` + atomic rename and rollback on failure; corrupt config files are never overwritten.
63
+ - Shared TUI context and color-math utilities (`extensions/shared/tui-context.ts`) unifying
64
+ interactive TUI gating, finite width normalization and gradient interpolation across all
65
+ extensions.
66
+
67
+ ### Performance
68
+
69
+ - **Identity-preserving render caches**: static footer renders, `PolishedEditor`,
70
+ `WrappedPolishedEditor` and selector border wrappers reuse cached line arrays on unchanged frames
71
+ so Pi 1.6.0+ `Container` skips redundant redraws. Default segments and `cwd` labels are skipped
72
+ when unused by a custom `footerFormat`, and text-only `$context` no longer wakes the footer pulse
73
+ timer.
74
+ - **Color, gradient & style hot paths**: scalar RGB-to-256 conversion without per-call tuple
75
+ allocations, bounded LRU caches for Sakura gradients, static Macaron gauges and Starship style
76
+ specs, and consecutive-SGR coalescing to reduce ANSI sequences on 256-color terminals.
77
+ - **Non-blocking project probes**: `git`, runtime and package-version probes now use async
78
+ `fs/promises` with `AbortSignal` cancellation and bounded mtime-aware caching instead of
79
+ synchronous filesystem calls.
80
+ - **Linear parsers**: `footer-format` now uses an iterative parser and linear orphan-separator
81
+ cleanup (preventing stack overflows on deeply nested `(` and regex backtracking); `thinking-trail`
82
+ adds a plain-text fast path and linear code-fence scanning.
83
+ - **Streaming & standalone extensions**: `live-context` skips redundant updates when token counts
84
+ are unchanged; `claude-shimmer` skips full-text estimation scans when authoritative usage is
85
+ present; `header` slices artwork to the active width before painting; `matrix` precomputes its
86
+ candy ANSI palette table.
87
+
88
+ ### Fixed
89
+
90
+ - **Pi 1.7.0 & dialogs**:
91
+ - Restored the `Tab/Shift+Tab to switch sections` hint in `/zentui` on Pi 1.7.0 (where
92
+ `SettingsList` renders lowercase keybinding hints) while staying compatible with Pi 1.5.x and
93
+ never rewriting item descriptions at narrow widths.
94
+ - Zentui and Matrix resolve config paths lazily via `getAgentDir()`, honoring Pi 1.7.0's
95
+ `--agent-dir` flag and runtime `PI_CODING_AGENT_DIR` changes.
96
+ - Fixed strict TypeScript compatibility with Pi 1.6.0+'s `Component.render(): readonly string[]`
97
+ and ensured render helpers never mutate frozen caller arrays.
98
+ - **Zentui core, footer & chrome**:
99
+ - Mid-session `/theme` switches now propagate immediately to the editor, footer, tool cards and
100
+ color mode without restarting Pi.
101
+ - Narrow-footer layout no longer overflows its column budget; non-finite context values format
102
+ cleanly as `--`; `toHomePath` matches Windows drive and UNC prefixes case-insensitively.
103
+ - Bare git repositories and `.git/` subdirectories are handled cleanly without spurious errors,
104
+ and transient `git status --show-stash` probe failures are retried instead of cached for the
105
+ whole process.
106
+ - `thinking-trail` handles CRLF fenced code blocks and closing tags inside fenced code cleanly.
107
+ - `tool-execution` resets SGR before the right rail, handles CRLF and empty context lines in diff
108
+ stats, preserves grapheme clusters in card titles, and forwards captured mouse drag/release
109
+ events (matching `PolishedEditor`).
110
+ - Extension statuses strip BiDi override characters, terminate unclosed original SGR spans and
111
+ strip SGR when `colorMode === "none"` (`NO_COLOR` / `TERM=dumb`).
112
+ - Prototype patches roll back atomically on partial install failure, and disabling features across
113
+ `session_start` switches cleanly uninstalls prior UI and timers.
114
+ - Added `thinking-trail` to `/zentui` usage help and argument completions, and validated inputs
115
+ when saving path-display and extension-status settings.
116
+ - **Color detection & standalone extensions**:
117
+ - `detectColorMode` and `syncColorMode` handle `TERM=dumb`, `PI_TRUE_COLOR`, `TMUX`/`screen`
118
+ precedence, `"none"` theme modes and non-finite RGB channels cleanly.
119
+ - `claude-shimmer` pauses its clock and freezes stall timing during `ui_prompt_start` /
120
+ `ui_prompt_end`, suppresses false completion notices after pre-message API errors, resets active
121
+ tool counts across turns and sessions, and restores Pi's working UI on `session_shutdown`.
122
+ - `matrix` pauses during UI prompts, reloads config on `session_start`, rejects extra tokens in
123
+ `/sakura-matrix` commands, and guards invalid widths/heights and `ctx.isIdle?.()`.
124
+ - `header` emits zero ANSI sequences in `NO_COLOR` mode across all widths and only clears a header
125
+ it owns on shutdown.
126
+ - `changelog` handles fenced code blocks, narrow/non-finite widths, empty `0/0` states and
127
+ headless `notify` fallbacks safely.
128
+ - Every timer across all five extensions calls `.unref?.()` so background timers never hold the
129
+ Node process open on exit.
130
+
131
+ ### Development
132
+
133
+ - Bumped `scripts/dev-setup.mjs` default Pi host to `1.7.0`, honored `PI_HOST_ROOT` in
134
+ `test/theme.test.ts`, upgraded `scripts/check.mjs` to a lexer-based import scanner, removed the
135
+ `style.ts` ↔ `config.ts` type import cycle, decomposed high-complexity modules
136
+ (`footer-segments.ts`, `git.ts`, `settings-command.ts`), and added static invariant tests plus an
137
+ end-to-end test suite (`npm run test:e2e`) wired into CI.
138
+
6
139
  ## [1.5.3] - 2026-11-28
7
140
 
8
141
  ### Highlights
package/README.md CHANGED
@@ -18,7 +18,7 @@ Then pick the theme in `/settings` → **sakura-macaron** and restart Pi once. D
18
18
  <sub>Real Pi 1.5.2 session rendered by this pack (scripted demo model; GohuFont uni14 Nerd Font Mono).</sub>
19
19
  </p>
20
20
 
21
- **v1.5.3** — turns inline `<thinking>` / `<think>` / `<thought>` tags in replies into Thought trails, and publishes to npm via GitHub Actions OIDC Trusted Publishing. See [what changed](#153).
21
+ **v1.5.5** — linear sakura→sky frame gradients, fullscreen `auto` scrollbar clearance so tool card right borders stay intact, and updated preview screenshots. See [what changed](#155).
22
22
 
23
23
  ## What’s inside
24
24
 
@@ -99,7 +99,7 @@ Other editor extensions (e.g. `pi-fff`) keep their input and autocomplete inside
99
99
 
100
100
  ## Requirements
101
101
 
102
- - Pi **>= 0.87.1** (tested on 0.87.1, 0.99.1 and 1.5.2)
102
+ - Pi **>= 0.87.1** (tested on 0.87.1, 0.99.1, 1.5.2 and 1.7.0)
103
103
  - Dark terminal background (the theme does not paint a background)
104
104
  - Truecolor recommended; 256-color terminals get the nearest palette colors, `NO_COLOR` disables the pack’s own colors
105
105
  - Nerd Font for the default icons (`icons.mode: "ascii"` works without)
@@ -147,9 +147,9 @@ Restart Pi after updating. Pi **>= 1.5.0** shows what changed under **Extension
147
147
  Pi does not push package updates automatically. Users who pinned a version, tag or commit must explicitly select the new version:
148
148
 
149
149
  ```bash
150
- pi install npm:pi-sakura-cyberdeck@1.5.3
150
+ pi install npm:pi-sakura-cyberdeck@1.5.5
151
151
  # or
152
- pi install git:github.com/beautifulrem/pi-sakura-cyberdeck@v1.5.3
152
+ pi install git:github.com/beautifulrem/pi-sakura-cyberdeck@v1.5.5
153
153
  ```
154
154
 
155
155
  Notes for 1.2.0:
@@ -175,7 +175,7 @@ Or start with `pi --tui-mode fullscreen`. Pack styling (editor chrome, footer, s
175
175
 
176
176
  ### Load only some pieces
177
177
 
178
- Pi can filter a package's resources. Replace the plain source string in `~/.pi/agent/settings.json` with an object. Keep `source` exactly as it is in your settings (a Git source, or an npm version pin such as `npm:pi-sakura-cyberdeck@1.5.3`); changing it installs a different package rather than filtering the one you have.
178
+ Pi can filter a package's resources. Replace the plain source string in `~/.pi/agent/settings.json` with an object. Keep `source` exactly as it is in your settings (a Git source, or an npm version pin such as `npm:pi-sakura-cyberdeck@1.5.5`); changing it installs a different package rather than filtering the one you have.
179
179
 
180
180
  ```jsonc
181
181
  {
@@ -239,23 +239,26 @@ Avoid stacking with `pi-zentui`, `pi-powerline-footer`, stock `pi-claude-shimmer
239
239
 
240
240
  Full history: [CHANGELOG.md](CHANGELOG.md) (also available in Pi via `/sakura-changelog`).
241
241
 
242
- ### 1.5.3
242
+ ### 1.5.5
243
243
 
244
- - Reasoning that a model writes into its answer as `<thinking>…</thinking>` (also `<think>` and
245
- `<thought>`, common with Gemini behind OpenAI-compatible endpoints) is now shown as a
246
- `✦ Thought trail` instead of literal tags (display-only; `/zentui thinking-trail off` keeps
247
- Pi's stock rendering).
248
- - Added GitHub Actions CI and npm Trusted Publishing (OIDC) with automatic provenance.
244
+ - Linear sakura→sky frame gradients: `renderSakuraFrameGradient` now runs linearly from sakura
245
+ pink (`#F2A7C6`) on the left to sky blue (`#9FD3F2`) on the right (matching the editor and header),
246
+ and tool card right rails (`│`) use sky blue so `╮`, `│` and `╯` connect seamlessly.
247
+ - Fullscreen `auto` scrollbar clearance: tool cards and user message hairlines now reserve 1
248
+ right-edge column under Pi's fullscreen `auto` scrollbar mode so the scrollbar no longer overwrites
249
+ card right borders, while keeping `"always"`, `"hidden"` and `regular` mode untouched.
250
+ - Updated README and social preview screenshots to match the linear borders and sky-blue right rails.
249
251
 
250
252
  ### Earlier versions
251
253
 
252
- See [CHANGELOG.md](CHANGELOG.md) for 1.0.0 – 1.5.2.
254
+ See [CHANGELOG.md](CHANGELOG.md) for 1.0.0 – 1.5.4.
253
255
 
254
256
  ## Development
255
257
 
256
258
  ```bash
257
259
  npm run dev:setup # installs Pi + TypeScript into .dev/ (not shipped, no package deps)
258
260
  npm run verify # package check + strict typecheck + unit tests
261
+ npm run test:e2e # end-to-end suite against the installed Pi host
259
262
  PI_HOST_ROOT=/path/to/node_modules/@earendil-works/pi-coding-agent npm test # test against another Pi
260
263
  ```
261
264
 
package/README.zh-CN.md CHANGED
@@ -42,7 +42,7 @@ pi install npm:pi-sakura-cyberdeck
42
42
 
43
43
  ## 要求
44
44
 
45
- - Pi **>= 0.87.1**(在 0.87.1、0.99.1、1.5.2 上测试过)
45
+ - Pi **>= 0.87.1**(在 0.87.1、0.99.1、1.5.2、1.7.0 上测试过)
46
46
  - 深色终端背景;推荐真彩色终端
47
47
  - 默认图标需要 Nerd Font(没有的话设置 `icons.mode: "ascii"`)
48
48
 
@@ -50,7 +50,7 @@ pi install npm:pi-sakura-cyberdeck
50
50
 
51
51
  ## 只加载部分组件
52
52
 
53
- 在 `~/.pi/agent/settings.json` 里把包来源写成对象,可以按需过滤。`source` 保持你设置里原来的写法(比如 Git 来源,或者 `npm:pi-sakura-cyberdeck@1.5.3` 这样锁定版本的写法);改了它就等于装了另一个包,而不是过滤现有的这个。
53
+ 在 `~/.pi/agent/settings.json` 里把包来源写成对象,可以按需过滤。`source` 保持你设置里原来的写法(比如 Git 来源,或者 `npm:pi-sakura-cyberdeck@1.5.5` 这样锁定版本的写法);改了它就等于装了另一个包,而不是过滤现有的这个。
54
54
 
55
55
  ```jsonc
56
56
  {
@@ -9,8 +9,18 @@
9
9
  import { existsSync, readFileSync } from "node:fs";
10
10
  import { dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
13
- import { type Component, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
12
+ import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
13
+ import {
14
+ type Component,
15
+ type Keybinding,
16
+ type KeyId,
17
+ matchesKey,
18
+ type TuiMouseEvent,
19
+ type TuiMouseEventResult,
20
+ truncateToWidth,
21
+ wrapTextWithAnsi,
22
+ } from "@earendil-works/pi-tui";
23
+ import { isInteractiveTui, normalizeWidth } from "../shared/tui-context";
14
24
 
15
25
  export interface ChangelogSection {
16
26
  title: string;
@@ -28,6 +38,26 @@ const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
28
38
  // ---------------------------------------------------------------------------
29
39
  // Parsing (pure)
30
40
 
41
+ const FENCE_OPEN = /^\s*(`{3,}|~{3,})/;
42
+ const FENCE_CLOSE = /^\s*(`{3,}|~{3,})[ \t]*$/;
43
+
44
+ function matchFenceOpen(line: string): string | undefined {
45
+ const match = FENCE_OPEN.exec(line);
46
+ if (!match) return undefined;
47
+ const marker = match[1]!;
48
+ // CommonMark §4.5: backtick fence info strings cannot contain backticks
49
+ // (single-line inline spans like ```code``` do not open a fenced block).
50
+ if (marker[0] === "`" && line.indexOf("`", match.index + match[0].length) !== -1) {
51
+ return undefined;
52
+ }
53
+ return marker;
54
+ }
55
+
56
+ function closesFence(line: string, fence: string): boolean {
57
+ const match = FENCE_CLOSE.exec(line);
58
+ return !!match && match[1]![0] === fence[0] && match[1]!.length >= fence.length;
59
+ }
60
+
31
61
  /** Parses `## [1.2.0] - 2026-09-30` / `## 1.2.0` headings with `###` sections and `-` bullets. */
32
62
  export function parseChangelog(markdown: string): ChangelogEntry[] {
33
63
  const entries: ChangelogEntry[] = [];
@@ -36,8 +66,36 @@ export function parseChangelog(markdown: string): ChangelogEntry[] {
36
66
  // Markdown soft line breaks: a hard-wrapped bullet or paragraph continues on the next
37
67
  // non-bullet line until a blank line or heading ends it.
38
68
  let open = false;
69
+ let fence: string | undefined;
70
+
71
+ const pushLineToSection = (line: string) => {
72
+ if (!entry) return;
73
+ if (!section) {
74
+ section = { title: "", lines: [] };
75
+ entry.sections.push(section);
76
+ }
77
+ section.lines.push(line);
78
+ };
79
+
39
80
  for (const raw of markdown.split(/\r?\n/)) {
40
81
  const line = raw.trimEnd();
82
+ if (fence !== undefined) {
83
+ if (closesFence(line, fence)) {
84
+ fence = undefined;
85
+ open = false;
86
+ }
87
+ pushLineToSection(line);
88
+ continue;
89
+ }
90
+
91
+ const fenceOpen = matchFenceOpen(line);
92
+ if (fenceOpen !== undefined) {
93
+ fence = fenceOpen;
94
+ open = false;
95
+ pushLineToSection(line);
96
+ continue;
97
+ }
98
+
41
99
  const heading = line.match(/^##\s+\[?v?(\d+\.\d+\.\d+[^\]\s]*)\]?(?:\s+[-–—]\s+(.+))?\s*$/);
42
100
  if (heading) {
43
101
  entry = { version: heading[1]!, date: heading[2]?.trim(), sections: [] };
@@ -69,11 +127,7 @@ export function parseChangelog(markdown: string): ChangelogEntry[] {
69
127
  continue;
70
128
  }
71
129
  open = true;
72
- if (!section) {
73
- section = { title: "", lines: [] };
74
- entry.sections.push(section);
75
- }
76
- section.lines.push(line);
130
+ pushLineToSection(line);
77
131
  }
78
132
  return entries;
79
133
  }
@@ -97,28 +151,51 @@ function bulletText(line: string): string {
97
151
 
98
152
  /** Full changelog lines (used by the scrollable viewer). */
99
153
  export function renderChangelogLines(entries: ChangelogEntry[], width: number, theme: Paint): string[] {
154
+ const safeWidth = normalizeWidth(width);
155
+ if (safeWidth <= 0) return [];
156
+ const compact = safeWidth < 16;
157
+ const baseIndent = compact ? "" : " ";
100
158
  const out: string[] = [];
101
159
  const wrap = (text: string, indent: string, hanging: string) => {
102
- const body = wrapTextWithAnsi(text, Math.max(10, width - hanging.length));
160
+ const body = wrapTextWithAnsi(text, Math.max(1, safeWidth - hanging.length));
103
161
  body.forEach((part, index) => out.push(`${index === 0 ? indent : hanging}${part}`));
104
162
  };
105
163
  for (const entry of entries) {
106
164
  if (out.length) out.push("");
107
165
  out.push(theme.bold(theme.fg("accent", `✿ ${entry.version}`)) + (entry.date ? theme.fg("dim", ` ${entry.date}`) : ""));
108
166
  for (const section of entry.sections) {
109
- if (section.title) out.push(theme.fg("mdHeading", ` ${section.title}`));
167
+ if (section.title) out.push(theme.fg("mdHeading", compact ? section.title : ` ${section.title}`));
168
+ let fence: string | undefined;
110
169
  for (const line of section.lines) {
170
+ if (fence !== undefined) {
171
+ if (closesFence(line, fence)) {
172
+ fence = undefined;
173
+ wrap(theme.fg("dim", line.trim()), baseIndent, baseIndent);
174
+ } else if (!line.trim()) {
175
+ out.push("");
176
+ } else {
177
+ wrap(line, baseIndent, baseIndent);
178
+ }
179
+ continue;
180
+ }
181
+ const fenceOpen = matchFenceOpen(line);
182
+ if (fenceOpen !== undefined) {
183
+ fence = fenceOpen;
184
+ wrap(theme.fg("dim", line.trim()), baseIndent, baseIndent);
185
+ continue;
186
+ }
111
187
  const nested = /^\s{2,}[-*]\s+/.test(line);
112
188
  if (isBullet(line)) {
113
- const indent = nested ? " " : " ";
114
- wrap(`${theme.fg("dim", nested ? "◦" : "•")} ${bulletText(line)}`, indent, `${indent} `);
189
+ const indent = compact ? "" : nested ? " " : " ";
190
+ const hanging = compact ? "" : `${indent} `;
191
+ wrap(`${theme.fg("dim", nested ? "◦" : "•")} ${bulletText(line)}`, indent, hanging);
115
192
  } else {
116
- wrap(stripInlineMarkdown(line.trim()), " ", " ");
193
+ wrap(stripInlineMarkdown(line.trim()), baseIndent, baseIndent);
117
194
  }
118
195
  }
119
196
  }
120
197
  }
121
- return out.map((line) => truncateToWidth(line, width, ""));
198
+ return out.map((line) => truncateToWidth(line, safeWidth, ""));
122
199
  }
123
200
 
124
201
  export type Paint = Pick<Theme, "fg" | "bold">;
@@ -139,83 +216,149 @@ function readChangelog(): ChangelogEntry[] {
139
216
  // ---------------------------------------------------------------------------
140
217
  // Scrollable viewer
141
218
 
142
- class ChangelogViewer implements Component {
219
+ type KeybindingsMatcher = {
220
+ matches?: (data: string, keybinding: Keybinding) => boolean;
221
+ };
222
+
223
+ export class ChangelogViewer implements Component {
224
+ readonly capturesViewportInput = true;
143
225
  private offset = 0;
144
226
  private lastWidth = 0;
145
227
  private cache: string[] = [];
228
+ private lastFrameKey = "";
229
+ private lastFrameLines: string[] = [];
146
230
  private readonly entries: ChangelogEntry[];
147
- private readonly theme: Theme;
231
+ private readonly theme: Paint;
148
232
  private readonly rows: () => number;
149
233
  private readonly requestRender: () => void;
150
234
  private readonly done: () => void;
235
+ private readonly keybindings: KeybindingsMatcher | undefined;
151
236
 
152
237
  constructor(
153
238
  entries: ChangelogEntry[],
154
- theme: Theme,
239
+ theme: Paint,
155
240
  rows: () => number,
156
241
  requestRender: () => void,
157
242
  done: () => void,
243
+ keybindings?: KeybindingsMatcher,
158
244
  ) {
159
245
  this.entries = entries;
160
246
  this.theme = theme;
161
247
  this.rows = rows;
162
248
  this.requestRender = requestRender;
163
249
  this.done = done;
250
+ this.keybindings = keybindings;
164
251
  }
165
252
 
166
253
  private pageSize(): number {
167
- return Math.max(5, Math.min(40, this.rows() - 8));
254
+ const rawRows = this.rows();
255
+ const safeRows = typeof rawRows === "number" && Number.isFinite(rawRows) && rawRows > 0 ? Math.floor(rawRows) : 24;
256
+ return Math.max(5, Math.min(40, safeRows - 8));
168
257
  }
169
258
 
170
259
  private maxOffset(): number {
171
260
  return Math.max(0, this.cache.length - this.pageSize());
172
261
  }
173
262
 
263
+ private matchesBinding(data: string, binding: Keybinding, fallbackKeys: readonly KeyId[]): boolean {
264
+ if (typeof this.keybindings?.matches === "function") {
265
+ return this.keybindings.matches(data, binding);
266
+ }
267
+ return fallbackKeys.some((key) => matchesKey(data, key));
268
+ }
269
+
270
+ private isCloseInput(data: string): boolean {
271
+ return (
272
+ this.matchesBinding(data, "tui.select.cancel", ["escape", "ctrl+c"]) ||
273
+ matchesKey(data, "ctrl+c") ||
274
+ data === "q" ||
275
+ matchesKey(data, "return")
276
+ );
277
+ }
278
+
279
+ private nextScrollOffset(data: string, max: number): number | undefined {
280
+ if (this.matchesBinding(data, "tui.select.up", ["up"]) || data === "k") return this.offset - 1;
281
+ if (this.matchesBinding(data, "tui.select.down", ["down"]) || data === "j") return this.offset + 1;
282
+ if (this.matchesBinding(data, "tui.select.pageUp", ["pageUp"])) return this.offset - this.pageSize();
283
+ if (this.matchesBinding(data, "tui.select.pageDown", ["pageDown"]) || data === " ") return this.offset + this.pageSize();
284
+ if (matchesKey(data, "home") || data === "g") return 0;
285
+ if (matchesKey(data, "end") || data === "G") return max;
286
+ return undefined;
287
+ }
288
+
174
289
  handleInput(data: string): void {
175
- const max = this.maxOffset();
176
- if (matchesKey(data, "escape") || data === "q" || matchesKey(data, "return")) {
290
+ if (this.isCloseInput(data)) {
177
291
  this.done();
178
292
  return;
179
293
  }
180
- if (matchesKey(data, "up") || data === "k") this.offset -= 1;
181
- else if (matchesKey(data, "down") || data === "j") this.offset += 1;
182
- else if (matchesKey(data, "pageUp")) this.offset -= this.pageSize();
183
- else if (matchesKey(data, "pageDown") || data === " ") this.offset += this.pageSize();
184
- else if (matchesKey(data, "home") || data === "g") this.offset = 0;
185
- else if (matchesKey(data, "end") || data === "G") this.offset = max;
186
- this.offset = Math.max(0, Math.min(max, this.offset));
187
- this.requestRender();
294
+ const max = this.maxOffset();
295
+ const target = this.nextScrollOffset(data, max);
296
+ if (target === undefined) return;
297
+ const previous = this.offset;
298
+ this.offset = Math.max(0, Math.min(max, target));
299
+ if (this.offset !== previous) this.requestRender();
300
+ }
301
+
302
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
303
+ if (event.type !== "wheel") return undefined;
304
+ const rawDelta = event.wheelDelta;
305
+ if (typeof rawDelta !== "number" || !Number.isFinite(rawDelta) || rawDelta === 0) {
306
+ return { handled: true, render: false };
307
+ }
308
+ const step = rawDelta < 0 ? Math.min(-1, Math.trunc(rawDelta)) : Math.max(1, Math.trunc(rawDelta));
309
+ const previous = this.offset;
310
+ this.offset = Math.max(0, Math.min(this.maxOffset(), this.offset + step));
311
+ const changed = this.offset !== previous;
312
+ if (changed) this.requestRender();
313
+ return { handled: true, render: changed };
188
314
  }
189
315
 
190
316
  render(width: number): string[] {
191
- if (width !== this.lastWidth) {
192
- this.cache = renderChangelogLines(this.entries, width, this.theme);
193
- this.lastWidth = width;
317
+ const safeWidth = normalizeWidth(width);
318
+ if (safeWidth <= 0) return [];
319
+ if (safeWidth !== this.lastWidth) {
320
+ this.cache = renderChangelogLines(this.entries, safeWidth, this.theme);
321
+ this.lastWidth = safeWidth;
322
+ this.lastFrameKey = "";
194
323
  }
195
324
  // A wider width shortens the text and a taller terminal grows the page, so the offset
196
325
  // a key press clamped earlier can point past the end: clamp again on every render.
197
326
  this.offset = Math.max(0, Math.min(this.maxOffset(), this.offset));
198
327
  const size = this.pageSize();
328
+ const frameKey = `${safeWidth}:${this.offset}:${size}`;
329
+ if (frameKey === this.lastFrameKey) return this.lastFrameLines;
199
330
  const visible = this.cache.slice(this.offset, this.offset + size);
200
331
  const end = Math.min(this.cache.length, this.offset + size);
332
+ const range = this.cache.length === 0 ? "0/0" : `${this.offset + 1}-${end}/${this.cache.length}`;
201
333
  const footer = this.theme.fg(
202
334
  "muted",
203
- ` ${this.offset + 1}-${end}/${this.cache.length} · ↑↓ j/k scroll · PgUp/PgDn · q/Esc close`,
335
+ ` ${range} · ↑↓ j/k scroll · PgUp/PgDn · q/Esc close`,
204
336
  );
205
- return [...visible, "", truncateToWidth(footer, width, "…")];
337
+ this.lastFrameLines = [...visible, "", truncateToWidth(footer, safeWidth, "…")];
338
+ this.lastFrameKey = frameKey;
339
+ return this.lastFrameLines;
206
340
  }
207
341
 
208
342
  invalidate(): void {
209
343
  this.lastWidth = 0;
344
+ this.lastFrameKey = "";
210
345
  }
211
346
  }
212
347
 
213
348
  // ---------------------------------------------------------------------------
214
349
  // Extension
215
350
 
216
- function isTui(ctx: ExtensionContext): boolean {
217
- const mode = (ctx as { mode?: string }).mode;
218
- return mode ? mode === "tui" : ctx.hasUI;
351
+ function safeNotify(
352
+ ctx: { hasUI?: boolean; ui?: { notify?: (message: string, type?: "info" | "warning" | "error") => void } } | null | undefined,
353
+ message: string,
354
+ type: "info" | "warning" | "error",
355
+ ): void {
356
+ if (!ctx?.hasUI || typeof ctx.ui?.notify !== "function") return;
357
+ try {
358
+ ctx.ui.notify(message, type);
359
+ } catch {
360
+ // Headless/disposed UI: fail soft.
361
+ }
219
362
  }
220
363
 
221
364
  export default function sakuraChangelog(pi: ExtensionAPI) {
@@ -223,26 +366,27 @@ export default function sakuraChangelog(pi: ExtensionAPI) {
223
366
  description: "Show the pi-sakura-cyberdeck changelog (optionally for one version)",
224
367
  handler: async (args, ctx) => {
225
368
  const all = readChangelog();
226
- const wanted = args.trim().replace(/^v/, "");
369
+ const wanted = (typeof args === "string" ? args : "").trim().replace(/^v/, "");
227
370
  const entries = wanted ? all.filter((e) => e.version === wanted) : all;
228
371
  if (!entries.length) {
229
- ctx.ui.notify(
372
+ safeNotify(
373
+ ctx,
230
374
  wanted ? `No changelog entry for ${wanted}.` : "Changelog not found in this installation.",
231
375
  "warning",
232
376
  );
233
377
  return;
234
378
  }
235
- if (!isTui(ctx)) {
379
+ if (!isInteractiveTui(ctx)) {
236
380
  const plain = renderChangelogLines(entries, 100, { fg: (_c: string, t: string) => t, bold: (t: string) => t });
237
- ctx.ui.notify(plain.slice(0, 40).join("\n"), "info");
381
+ safeNotify(ctx, plain.slice(0, 40).join("\n"), "info");
238
382
  return;
239
383
  }
240
- await ctx.ui.custom<void>((tui, theme, _kb, done) => {
384
+ await ctx.ui.custom<void>((tui, theme, kb, done) => {
241
385
  const rows = () => {
242
386
  const value = (tui as { terminal?: { rows?: number } }).terminal?.rows;
243
- return typeof value === "number" && value > 0 ? value : 24;
387
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 24;
244
388
  };
245
- return new ChangelogViewer(entries, theme, rows, () => tui.requestRender(), () => done());
389
+ return new ChangelogViewer(entries, theme, rows, () => tui.requestRender(), () => done(), kb);
246
390
  });
247
391
  },
248
392
  });