@aoshizuku/pi-bettertui 0.1.1 → 0.1.2

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/src/gutter.ts CHANGED
@@ -1,236 +1,236 @@
1
- import { type Theme, UserMessageComponent } from "@earendil-works/pi-coding-agent";
2
- import type { Component, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
3
-
4
- import { splitUserImages, UserImageLines } from "./user-images.js";
5
-
6
- /**
7
- * Left gutter shared with pi-editor and pi-hud (pi-shizuku README.md, DESIGN.md §1):
8
- * markers in column 0, content from column 2.
9
- */
10
- export const GUTTER = 2;
11
-
12
- const USER_PATCH_KEY = Symbol.for("pi-bettertui.user-gutter");
13
-
14
- /** Leading SGR sequences, then the first padding space that the marker replaces. */
15
- // eslint-disable-next-line no-control-regex
16
- const LEADING_SPACE = /^((?:\x1b\[[0-9;:]*m)*) /;
17
-
18
- /**
19
- * Put `marker` in column 0 of a line that starts with plain padding. Styles opened before the
20
- * padding (a message background) stay in front, so the background runs on under the marker.
21
- */
22
- export function placeMarker(line: string, marker: string): string {
23
- const match = LEADING_SPACE.exec(line);
24
- if (!match) return line;
25
- const prefix = match[1] ?? "";
26
- return prefix + marker + line.slice(prefix.length + 1);
27
- }
28
-
29
- /** Wraps a block and puts a marker in column 0 of one of its lines. */
30
- export class MarkedBlock implements Component {
31
- constructor(
32
- readonly block: Component,
33
- private readonly line: number,
34
- private readonly marker: () => string,
35
- ) {}
36
-
37
- render(width: number): string[] {
38
- // Components hand out cached arrays; never write into one.
39
- const out = [...this.block.render(width)];
40
- if (out.length > this.line) out[this.line] = placeMarker(out[this.line]!, this.marker());
41
- return out;
42
- }
43
-
44
- handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
45
- return this.block.handleMouse?.(event);
46
- }
47
-
48
- invalidate(): void {
49
- this.block.invalidate();
50
- }
51
- }
52
-
53
- /** Markdown and Text keep their horizontal padding in `paddingX`; both rebuild on invalidate(). */
54
- function setPadding(target: unknown, padding: number): void {
55
- const value = target as { paddingX?: unknown; invalidate?: () => void } | undefined;
56
- if (!value || typeof value.paddingX !== "number" || value.paddingX === padding) return;
57
- value.paddingX = padding;
58
- value.invalidate?.();
59
- }
60
-
61
- function outputPadOf(component: { outputPad?: unknown }): number {
62
- return typeof component.outputPad === "number" ? component.outputPad : 1;
63
- }
64
-
65
- // ---------------------------------------------------------------------------
66
- // Assistant messages (called from the updateContent patch in thinking.ts)
67
- // ---------------------------------------------------------------------------
68
-
69
- /** The text Markdown blocks of an assistant message's last update; pi records each in `markdownSlots`. */
70
- export function assistantTextBlocks(component: any): Set<unknown> {
71
- const blocks = new Set<unknown>();
72
- const slots: unknown[] = Array.isArray(component?.markdownSlots) ? component.markdownSlots : [];
73
- for (const slot of slots) {
74
- const value = slot as { kind?: unknown; markdown?: unknown };
75
- if (value?.kind === "text" && value.markdown) blocks.add(value.markdown);
76
- }
77
- return blocks;
78
- }
79
-
80
- /**
81
- * Move an assistant message's text into the content column and mark each text block with a muted `●`,
82
- * lighter than a tool row's so the two don't compete for column 0 (DESIGN.md §3).
83
- * pi reuses the text Markdown across streaming updates, so disabling must put its padding back.
84
- */
85
- export function applyAssistantGutter(component: any, enabled: boolean, getTheme: () => Theme): void {
86
- const container = component?.contentContainer;
87
- if (!container || !Array.isArray(container.children)) return;
88
- const textBlocks = assistantTextBlocks(component);
89
- const padding = enabled ? GUTTER : outputPadOf(component);
90
-
91
- const children = container.children as unknown[];
92
- for (let index = 0; index < children.length; index++) {
93
- const child = children[index];
94
- // Thinking runs are click regions (handled by the thinking view); spacers have no padding.
95
- if (textBlocks.has(child)) {
96
- setPadding(child, padding);
97
- if (enabled) children[index] = new MarkedBlock(child as Component, 0, () => getTheme().fg("muted", "●"));
98
- } else if (enabled) {
99
- // Truncation, abort and error notes: plain Text built fresh on every update.
100
- setPadding(child, GUTTER);
101
- }
102
- }
103
- }
104
-
105
- // ---------------------------------------------------------------------------
106
- // User messages
107
- // ---------------------------------------------------------------------------
108
-
109
- export interface UserGutterHooks {
110
- isEnabled: () => boolean;
111
- getTheme: () => Theme;
112
- }
113
-
114
- interface UserPatchRecord {
115
- owner: object;
116
- hooks: UserGutterHooks;
117
- original: (...args: any[]) => any;
118
- patched: (...args: any[]) => any;
119
- }
120
-
121
- const userCleanups = new Set<() => void>();
122
- /** Identifies patches made by this module instance; each /reload loads a new one. */
123
- const MODULE_OWNER = {};
124
-
125
- export function installUserMessagePatch(hooks: UserGutterHooks): void {
126
- patchUserPrototype(UserMessageComponent.prototype as any, hooks);
127
- }
128
-
129
- export function uninstallUserMessagePatches(): void {
130
- for (const cleanup of [...userCleanups]) cleanup();
131
- userCleanups.clear();
132
- }
133
-
134
- /**
135
- * pi may build user messages from a different module instance than the one imported here
136
- * (see the thinking patch): patch the prototypes of the messages already on screen and rebuild them.
137
- */
138
- export function refreshLiveUserMessages(tui: unknown, hooks: UserGutterHooks): number {
139
- const components = collect(tui, isUserMessage);
140
- const prototypes = new Set<object>();
141
- for (const component of components) {
142
- const proto = Object.getPrototypeOf(component);
143
- if (proto && typeof proto === "object") prototypes.add(proto);
144
- }
145
- for (const proto of prototypes) patchUserPrototype(proto as any, hooks);
146
- for (const component of components) component.rebuild();
147
- return components.length;
148
- }
149
-
150
- function patchUserPrototype(proto: any, hooks: UserGutterHooks): void {
151
- const existing = proto[USER_PATCH_KEY] as UserPatchRecord | undefined;
152
- if (existing?.owner === MODULE_OWNER) {
153
- existing.hooks = hooks;
154
- return;
155
- }
156
- // A patch from an earlier load of this extension (/reload) would keep running its old code.
157
- if (existing) {
158
- if (proto.rebuild === existing.patched) proto.rebuild = existing.original;
159
- proto[USER_PATCH_KEY] = undefined;
160
- }
161
- const original = proto.rebuild;
162
- if (typeof original !== "function") return;
163
-
164
- const record: UserPatchRecord = {
165
- owner: MODULE_OWNER,
166
- hooks,
167
- original,
168
- patched: function (this: any, ...args: any[]): any {
169
- const result = original.apply(this, args);
170
- decorateUserMessage(this, record.hooks);
171
- return result;
172
- },
173
- };
174
- proto[USER_PATCH_KEY] = record;
175
- proto.rebuild = record.patched;
176
-
177
- userCleanups.add(() => {
178
- if (proto[USER_PATCH_KEY] !== record) return;
179
- if (proto.rebuild === record.patched) proto.rebuild = original;
180
- proto[USER_PATCH_KEY] = undefined;
181
- });
182
- }
183
-
184
- /** rebuild() starts from a fresh Markdown, so only the enabled case needs work. */
185
- function decorateUserMessage(component: any, hooks: UserGutterHooks): void {
186
- if (!hooks.isEnabled() || !Array.isArray(component.children)) return;
187
- const markdown = component.children[0];
188
- if (!markdown || typeof markdown.paddingX !== "number") return;
189
- setPadding(markdown, GUTTER);
190
- // Drop the blank background rows above and below the text: the band hugs the message.
191
- if (typeof markdown.paddingY === "number" && markdown.paddingY !== 0) {
192
- markdown.paddingY = 0;
193
- markdown.invalidate?.();
194
- }
195
- // Image references and pi's image notes leave the band; each image gets a rail line under it (§4.1).
196
- const split = typeof component.text === "string" ? splitUserImages(component.text) : undefined;
197
- if (split && typeof markdown.setText === "function") markdown.setText(split.body);
198
- component.children[0] = new MarkedBlock(markdown, 0, () => hooks.getTheme().fg("muted", "❯"));
199
- if (split && typeof markdown.setText === "function") component.children.push(new UserImageLines(split.images, hooks.getTheme));
200
- }
201
-
202
- export function isUserMessage(value: unknown): boolean {
203
- if (!value || typeof value !== "object") return false;
204
- const candidate = value as any;
205
- return (
206
- typeof candidate.rebuild === "function" &&
207
- typeof candidate.setOutputPad === "function" &&
208
- typeof candidate.text === "string" &&
209
- candidate.markdownTheme !== undefined &&
210
- // Custom and skill messages also rebuild; they carry their message object instead of plain text.
211
- !("message" in candidate) &&
212
- !("skillBlock" in candidate) &&
213
- !("lastMessage" in candidate)
214
- );
215
- }
216
-
217
- function collect(root: unknown, match: (value: unknown) => boolean): any[] {
218
- const out: any[] = [];
219
- const stack: unknown[] = [root];
220
- const seen = new Set<object>();
221
- while (stack.length > 0) {
222
- const value = stack.pop();
223
- if (!value || typeof value !== "object" || seen.has(value)) continue;
224
- seen.add(value);
225
- const candidate = value as any;
226
- if (match(candidate)) {
227
- out.push(candidate);
228
- continue;
229
- }
230
- if (Array.isArray(candidate.children)) {
231
- for (const child of candidate.children) stack.push(child);
232
- }
233
- if (candidate.child) stack.push(candidate.child);
234
- }
235
- return out;
236
- }
1
+ import { type Theme, UserMessageComponent } from "@earendil-works/pi-coding-agent";
2
+ import type { Component, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
3
+
4
+ import { splitUserImages, UserImageLines } from "./user-images.js";
5
+
6
+ /**
7
+ * Left gutter shared with pi-editor and pi-hud (pi-shizuku README.md, DESIGN.md §1):
8
+ * markers in column 0, content from column 2.
9
+ */
10
+ export const GUTTER = 2;
11
+
12
+ const USER_PATCH_KEY = Symbol.for("pi-bettertui.user-gutter");
13
+
14
+ /** Leading SGR sequences, then the first padding space that the marker replaces. */
15
+ // eslint-disable-next-line no-control-regex
16
+ const LEADING_SPACE = /^((?:\x1b\[[0-9;:]*m)*) /;
17
+
18
+ /**
19
+ * Put `marker` in column 0 of a line that starts with plain padding. Styles opened before the
20
+ * padding (a message background) stay in front, so the background runs on under the marker.
21
+ */
22
+ export function placeMarker(line: string, marker: string): string {
23
+ const match = LEADING_SPACE.exec(line);
24
+ if (!match) return line;
25
+ const prefix = match[1] ?? "";
26
+ return prefix + marker + line.slice(prefix.length + 1);
27
+ }
28
+
29
+ /** Wraps a block and puts a marker in column 0 of one of its lines. */
30
+ export class MarkedBlock implements Component {
31
+ constructor(
32
+ readonly block: Component,
33
+ private readonly line: number,
34
+ private readonly marker: () => string,
35
+ ) {}
36
+
37
+ render(width: number): string[] {
38
+ // Components hand out cached arrays; never write into one.
39
+ const out = [...this.block.render(width)];
40
+ if (out.length > this.line) out[this.line] = placeMarker(out[this.line]!, this.marker());
41
+ return out;
42
+ }
43
+
44
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
45
+ return this.block.handleMouse?.(event);
46
+ }
47
+
48
+ invalidate(): void {
49
+ this.block.invalidate();
50
+ }
51
+ }
52
+
53
+ /** Markdown and Text keep their horizontal padding in `paddingX`; both rebuild on invalidate(). */
54
+ function setPadding(target: unknown, padding: number): void {
55
+ const value = target as { paddingX?: unknown; invalidate?: () => void } | undefined;
56
+ if (!value || typeof value.paddingX !== "number" || value.paddingX === padding) return;
57
+ value.paddingX = padding;
58
+ value.invalidate?.();
59
+ }
60
+
61
+ function outputPadOf(component: { outputPad?: unknown }): number {
62
+ return typeof component.outputPad === "number" ? component.outputPad : 1;
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Assistant messages (called from the updateContent patch in thinking.ts)
67
+ // ---------------------------------------------------------------------------
68
+
69
+ /** The text Markdown blocks of an assistant message's last update; pi records each in `markdownSlots`. */
70
+ export function assistantTextBlocks(component: any): Set<unknown> {
71
+ const blocks = new Set<unknown>();
72
+ const slots: unknown[] = Array.isArray(component?.markdownSlots) ? component.markdownSlots : [];
73
+ for (const slot of slots) {
74
+ const value = slot as { kind?: unknown; markdown?: unknown };
75
+ if (value?.kind === "text" && value.markdown) blocks.add(value.markdown);
76
+ }
77
+ return blocks;
78
+ }
79
+
80
+ /**
81
+ * Move an assistant message's text into the content column and mark each text block with a muted `●`,
82
+ * lighter than a tool row's so the two don't compete for column 0 (DESIGN.md §3).
83
+ * pi reuses the text Markdown across streaming updates, so disabling must put its padding back.
84
+ */
85
+ export function applyAssistantGutter(component: any, enabled: boolean, getTheme: () => Theme): void {
86
+ const container = component?.contentContainer;
87
+ if (!container || !Array.isArray(container.children)) return;
88
+ const textBlocks = assistantTextBlocks(component);
89
+ const padding = enabled ? GUTTER : outputPadOf(component);
90
+
91
+ const children = container.children as unknown[];
92
+ for (let index = 0; index < children.length; index++) {
93
+ const child = children[index];
94
+ // Thinking runs are click regions (handled by the thinking view); spacers have no padding.
95
+ if (textBlocks.has(child)) {
96
+ setPadding(child, padding);
97
+ if (enabled) children[index] = new MarkedBlock(child as Component, 0, () => getTheme().fg("muted", "●"));
98
+ } else if (enabled) {
99
+ // Truncation, abort and error notes: plain Text built fresh on every update.
100
+ setPadding(child, GUTTER);
101
+ }
102
+ }
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // User messages
107
+ // ---------------------------------------------------------------------------
108
+
109
+ export interface UserGutterHooks {
110
+ isEnabled: () => boolean;
111
+ getTheme: () => Theme;
112
+ }
113
+
114
+ interface UserPatchRecord {
115
+ owner: object;
116
+ hooks: UserGutterHooks;
117
+ original: (...args: any[]) => any;
118
+ patched: (...args: any[]) => any;
119
+ }
120
+
121
+ const userCleanups = new Set<() => void>();
122
+ /** Identifies patches made by this module instance; each /reload loads a new one. */
123
+ const MODULE_OWNER = {};
124
+
125
+ export function installUserMessagePatch(hooks: UserGutterHooks): void {
126
+ patchUserPrototype(UserMessageComponent.prototype as any, hooks);
127
+ }
128
+
129
+ export function uninstallUserMessagePatches(): void {
130
+ for (const cleanup of [...userCleanups]) cleanup();
131
+ userCleanups.clear();
132
+ }
133
+
134
+ /**
135
+ * pi may build user messages from a different module instance than the one imported here
136
+ * (see the thinking patch): patch the prototypes of the messages already on screen and rebuild them.
137
+ */
138
+ export function refreshLiveUserMessages(tui: unknown, hooks: UserGutterHooks): number {
139
+ const components = collect(tui, isUserMessage);
140
+ const prototypes = new Set<object>();
141
+ for (const component of components) {
142
+ const proto = Object.getPrototypeOf(component);
143
+ if (proto && typeof proto === "object") prototypes.add(proto);
144
+ }
145
+ for (const proto of prototypes) patchUserPrototype(proto as any, hooks);
146
+ for (const component of components) component.rebuild();
147
+ return components.length;
148
+ }
149
+
150
+ function patchUserPrototype(proto: any, hooks: UserGutterHooks): void {
151
+ const existing = proto[USER_PATCH_KEY] as UserPatchRecord | undefined;
152
+ if (existing?.owner === MODULE_OWNER) {
153
+ existing.hooks = hooks;
154
+ return;
155
+ }
156
+ // A patch from an earlier load of this extension (/reload) would keep running its old code.
157
+ if (existing) {
158
+ if (proto.rebuild === existing.patched) proto.rebuild = existing.original;
159
+ proto[USER_PATCH_KEY] = undefined;
160
+ }
161
+ const original = proto.rebuild;
162
+ if (typeof original !== "function") return;
163
+
164
+ const record: UserPatchRecord = {
165
+ owner: MODULE_OWNER,
166
+ hooks,
167
+ original,
168
+ patched: function (this: any, ...args: any[]): any {
169
+ const result = original.apply(this, args);
170
+ decorateUserMessage(this, record.hooks);
171
+ return result;
172
+ },
173
+ };
174
+ proto[USER_PATCH_KEY] = record;
175
+ proto.rebuild = record.patched;
176
+
177
+ userCleanups.add(() => {
178
+ if (proto[USER_PATCH_KEY] !== record) return;
179
+ if (proto.rebuild === record.patched) proto.rebuild = original;
180
+ proto[USER_PATCH_KEY] = undefined;
181
+ });
182
+ }
183
+
184
+ /** rebuild() starts from a fresh Markdown, so only the enabled case needs work. */
185
+ function decorateUserMessage(component: any, hooks: UserGutterHooks): void {
186
+ if (!hooks.isEnabled() || !Array.isArray(component.children)) return;
187
+ const markdown = component.children[0];
188
+ if (!markdown || typeof markdown.paddingX !== "number") return;
189
+ setPadding(markdown, GUTTER);
190
+ // Drop the blank background rows above and below the text: the band hugs the message.
191
+ if (typeof markdown.paddingY === "number" && markdown.paddingY !== 0) {
192
+ markdown.paddingY = 0;
193
+ markdown.invalidate?.();
194
+ }
195
+ // Image references and pi's image notes leave the band; each image gets a rail line under it (§4.1).
196
+ const split = typeof component.text === "string" ? splitUserImages(component.text) : undefined;
197
+ if (split && typeof markdown.setText === "function") markdown.setText(split.body);
198
+ component.children[0] = new MarkedBlock(markdown, 0, () => hooks.getTheme().fg("muted", "❯"));
199
+ if (split && typeof markdown.setText === "function") component.children.push(new UserImageLines(split.images, hooks.getTheme));
200
+ }
201
+
202
+ export function isUserMessage(value: unknown): boolean {
203
+ if (!value || typeof value !== "object") return false;
204
+ const candidate = value as any;
205
+ return (
206
+ typeof candidate.rebuild === "function" &&
207
+ typeof candidate.setOutputPad === "function" &&
208
+ typeof candidate.text === "string" &&
209
+ candidate.markdownTheme !== undefined &&
210
+ // Custom and skill messages also rebuild; they carry their message object instead of plain text.
211
+ !("message" in candidate) &&
212
+ !("skillBlock" in candidate) &&
213
+ !("lastMessage" in candidate)
214
+ );
215
+ }
216
+
217
+ function collect(root: unknown, match: (value: unknown) => boolean): any[] {
218
+ const out: any[] = [];
219
+ const stack: unknown[] = [root];
220
+ const seen = new Set<object>();
221
+ while (stack.length > 0) {
222
+ const value = stack.pop();
223
+ if (!value || typeof value !== "object" || seen.has(value)) continue;
224
+ seen.add(value);
225
+ const candidate = value as any;
226
+ if (match(candidate)) {
227
+ out.push(candidate);
228
+ continue;
229
+ }
230
+ if (Array.isArray(candidate.children)) {
231
+ for (const child of candidate.children) stack.push(child);
232
+ }
233
+ if (candidate.child) stack.push(candidate.child);
234
+ }
235
+ return out;
236
+ }