fisi-dock 0.0.0-stage → 0.3.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.
@@ -0,0 +1,227 @@
1
+ import { entranceRows, hasEntrance, parseAhead, parseBranch, parseGitChanges, runsSpinner, sessionSnapshot, type LiveParts } from "./live-data.ts";
2
+ import { SHIMMER_STEP_MS, SPINNER_MS, spinnerFrameIndex, type OrbMotion } from "./orbs.ts";
3
+ import type { AgentInfo, PanelModel } from "./panel-model.ts";
4
+ import { panelDigest } from "./panel.ts";
5
+
6
+ // The live panel state between refresh triggers. Frames only read the cached
7
+ // model and digest; adapters write through update(), which reports whether
8
+ // anything drawn changed so the caller can request a repaint.
9
+
10
+ export interface LiveStore {
11
+ model(): PanelModel;
12
+ digest(): string;
13
+ /** Merge `patch`; true when the panel model changed. */
14
+ update(patch: Partial<LiveParts>): boolean;
15
+ /** True while a run is active (agent_start until agent_settled). */
16
+ runActive(): boolean;
17
+ /** True while a running spinner is drawn (S31, L61). */
18
+ spinning(): boolean;
19
+ /** True while a row plays its entrance (S54). */
20
+ entering(): boolean;
21
+ /** Fisi Dock's first reads are done: rows shown now stay still, rows that appear from here on enter (S54). */
22
+ loaded(): void;
23
+ }
24
+
25
+ export interface LiveStoreOptions {
26
+ /** Gentle Shell's animation level, read when a row appears; potato rows never enter (S54). */
27
+ motion?(): OrbMotion;
28
+ }
29
+
30
+ /**
31
+ * Gives each running agent of `agents` without its own start time the time it
32
+ * was first seen running (S35), kept in `seen` under `prefix` + its id or
33
+ * name (job ids). Names that left the list are forgotten, so one that comes
34
+ * back starts again. Queued and finished agents get none.
35
+ */
36
+ function stampStarts<T extends AgentInfo & { id?: string }>(agents: T[] | undefined, seen: Map<string, number>, prefix: string, at: number): T[] | undefined {
37
+ if (!agents) return agents;
38
+ const key = (agent: T) => prefix + (agent.id ?? agent.name);
39
+ const keys = new Set(agents.map(key));
40
+ for (const known of [...seen.keys()]) if (known.startsWith(prefix) && !keys.has(known)) seen.delete(known);
41
+ return agents.map((agent) => {
42
+ if (agent.startedAt !== undefined || agent.state !== "running") return agent;
43
+ const since = seen.get(key(agent)) ?? at;
44
+ seen.set(key(agent), since);
45
+ return { ...agent, startedAt: since };
46
+ });
47
+ }
48
+
49
+ /**
50
+ * `now` stamps when a running agent without a start time was first seen (S35),
51
+ * when a row that can enter appeared (S54), and times the running reviews and
52
+ * the entrances on each update (S50).
53
+ */
54
+ export function createLiveStore(project: string, now: () => number = () => Date.now(), options: LiveStoreOptions = {}): LiveStore {
55
+ let parts: LiveParts = { project };
56
+ let model = sessionSnapshot(parts, now());
57
+ let digest = panelDigest(model);
58
+ const seen = new Map<string, number>();
59
+ /** Rows that can enter, by entranceRows key: when they appeared, or undefined for a row that stays still. */
60
+ const appeared = new Map<string, number | undefined>();
61
+ let loadedAt: number | undefined;
62
+ const animated = () => {
63
+ try {
64
+ return options.motion?.() !== "potato";
65
+ } catch {
66
+ return true;
67
+ }
68
+ };
69
+ /** Rows that left are forgotten, so one that comes back enters again. */
70
+ const stampEntrances = (next: LiveParts, at: number): Map<string, number> => {
71
+ const rows = entranceRows(next);
72
+ const keys = new Set(rows.map((row) => row.key));
73
+ for (const known of [...appeared.keys()]) if (!keys.has(known)) appeared.delete(known);
74
+ for (const row of rows) {
75
+ if (appeared.has(row.key)) continue;
76
+ // Before load, or an agent that started before Fisi Dock loaded: already there.
77
+ const old = loadedAt === undefined || (row.startedAt !== undefined && row.startedAt < loadedAt);
78
+ appeared.set(row.key, old || !animated() ? undefined : at);
79
+ }
80
+ const entering = new Map<string, number>();
81
+ for (const [key, since] of appeared) if (since !== undefined) entering.set(key, since);
82
+ return entering;
83
+ };
84
+ return {
85
+ model: () => model,
86
+ digest: () => digest,
87
+ runActive: () => parts.runSettled === false,
88
+ spinning: () => runsSpinner(model, parts.runSettled === false),
89
+ entering: () => hasEntrance(model),
90
+ loaded() {
91
+ loadedAt ??= now();
92
+ },
93
+ update(patch) {
94
+ const at = now();
95
+ const nextParts = { ...parts, ...patch };
96
+ if ("agents" in patch) nextParts.agents = stampStarts(patch.agents, seen, "job:", at);
97
+ const nextModel = sessionSnapshot(nextParts, at, stampEntrances(nextParts, at));
98
+ const nextDigest = panelDigest(nextModel);
99
+ parts = nextParts;
100
+ if (nextDigest === digest) return false;
101
+ model = nextModel;
102
+ digest = nextDigest;
103
+ return true;
104
+ },
105
+ };
106
+ }
107
+
108
+ export interface SpinnerClockOptions {
109
+ now(): number;
110
+ /** Called with the spinner frame to show at each step. */
111
+ onFrame(frame: number): void;
112
+ /** Gentle Shell's animation level, read each time work starts; quality when absent. */
113
+ motion?(): OrbMotion;
114
+ setInterval?(tick: () => void, ms: number): unknown;
115
+ clearInterval?(handle: unknown): void;
116
+ }
117
+
118
+ export interface SpinnerClock {
119
+ /** Whether a spinner is drawn now and whether a row plays its entrance (S54); starts, retimes or stops the timer on a change. */
120
+ sync(running: boolean, entering?: boolean): void;
121
+ dispose(): void;
122
+ }
123
+
124
+ /**
125
+ * The running spinner's wall clock (S31). While something runs, one timer
126
+ * reports the frame at the spinner rate; the frame comes from `now`, never
127
+ * from a count. While a row enters (S54) the same timer runs at the entrance
128
+ * step instead, so every step is painted. Nothing running or entering, potato
129
+ * motion or dispose: no timer.
130
+ */
131
+ export function createSpinnerClock(options: SpinnerClockOptions): SpinnerClock {
132
+ const startTimer = options.setInterval ?? ((tick: () => void, ms: number) => {
133
+ const handle = setInterval(tick, ms);
134
+ (handle as { unref?(): void }).unref?.();
135
+ return handle;
136
+ });
137
+ const stopTimer = options.clearInterval ?? ((handle: unknown) => clearInterval(handle as ReturnType<typeof setInterval>));
138
+ let running = false;
139
+ let disposed = false;
140
+ let timer: unknown;
141
+ let timerMs = SPINNER_MS;
142
+ let motion: OrbMotion = "quality";
143
+ const frame = () => options.onFrame(spinnerFrameIndex(options.now(), motion));
144
+ const stop = () => {
145
+ if (timer !== undefined) stopTimer(timer);
146
+ timer = undefined;
147
+ };
148
+ return {
149
+ sync(spinning, entering = false) {
150
+ const next = spinning || entering;
151
+ const ms = entering ? SHIMMER_STEP_MS : SPINNER_MS;
152
+ if (disposed || (next === running && (!next || ms === timerMs))) return;
153
+ const starting = next && !running;
154
+ running = next;
155
+ timerMs = ms;
156
+ if (!running) return stop();
157
+ if (starting) {
158
+ try {
159
+ motion = options.motion?.() ?? "quality";
160
+ } catch {
161
+ motion = "quality";
162
+ }
163
+ }
164
+ stop();
165
+ // The timer first: onFrame may call sync again with the same state, which is then a no-op.
166
+ if (motion !== "potato") timer = startTimer(frame, ms);
167
+ if (starting) frame();
168
+ },
169
+ dispose() {
170
+ disposed = true;
171
+ running = false;
172
+ stop();
173
+ },
174
+ };
175
+ }
176
+
177
+ /** Runs one git command in the session cwd; Pi's exec in the extension. */
178
+ export type GitExec = (args: string[]) => Promise<{ stdout: string; code: number }>;
179
+
180
+ async function gitOutput(exec: GitExec, args: string[]): Promise<string | undefined> {
181
+ try {
182
+ const result = await exec(args);
183
+ return result.code === 0 ? result.stdout : undefined;
184
+ } catch {
185
+ return undefined;
186
+ }
187
+ }
188
+
189
+ /** Branch, ahead count and uncommitted changes; each one is omitted when its command fails. */
190
+ export async function readGit(exec: GitExec): Promise<Pick<LiveParts, "branch" | "ahead" | "changes">> {
191
+ const branch = parseBranch(await gitOutput(exec, ["rev-parse", "--abbrev-ref", "HEAD"]));
192
+ const ahead = parseAhead(await gitOutput(exec, ["rev-list", "--count", "@{upstream}..HEAD"]));
193
+ const status = await gitOutput(exec, ["status", "--porcelain=v1", "-z"]);
194
+ // A repository without commits has no HEAD to diff against: files, no counts.
195
+ const numstat = status === undefined ? undefined : await gitOutput(exec, ["diff", "--numstat", "-z", "HEAD"]);
196
+ return { branch, ahead, changes: status === undefined ? undefined : parseGitChanges(status, numstat ?? "") };
197
+ }
198
+
199
+ /**
200
+ * Wraps `run` so it never overlaps itself. Triggers that arrive while a run is
201
+ * in flight collapse into one more run after it. Failures are swallowed.
202
+ */
203
+ export function createSerialRefresh(run: () => Promise<void>): () => void {
204
+ let running = false;
205
+ let again = false;
206
+ const start = (): void => {
207
+ if (running) {
208
+ again = true;
209
+ return;
210
+ }
211
+ running = true;
212
+ again = false;
213
+ let pending: Promise<void>;
214
+ try {
215
+ pending = run();
216
+ } catch (error) {
217
+ pending = Promise.reject(error);
218
+ }
219
+ pending
220
+ .catch(() => {})
221
+ .finally(() => {
222
+ running = false;
223
+ if (again) start();
224
+ });
225
+ };
226
+ return start;
227
+ }
@@ -0,0 +1,315 @@
1
+ // Pi's list of loaded skills, prompts and extensions as one box under the
2
+ // welcome card (design start-screen/02 "Loaded box"): `loaded` on the top rule,
3
+ // one row per kind with its count, the names cut to the row, and Pi's expand key
4
+ // on the bottom rule. Pi is never imported: its loaded-resources container is
5
+ // found next to the card in the TUI tree and only that instance's render is
6
+ // wrapped, so a removed or reloaded Fisi Dock leaves Pi's own listing.
7
+ import { readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { fg, palette } from "./palette.ts";
11
+ import { ellipsize, padEnd, visibleWidth } from "./text.ts";
12
+
13
+ /** Same frame as the welcome card (lib/welcome-card.ts): 63 columns, or the screen's width down to 34. */
14
+ const BOX_WIDTH = 63;
15
+ const MIN_BOX_WIDTH = 34;
16
+ /** A border and two spaces on each side. */
17
+ const SIDE = 3;
18
+ const TITLE = "loaded";
19
+ /** Cells of the top rule other than its dashes: `╭─ ` (3), the title, ` ` (1) and `╮` (1). */
20
+ const TOP_RULE_CHROME = 5 + TITLE.length;
21
+ /**
22
+ * Pi's default for app.tools.expand, the key that lists the names in full
23
+ * (core/keybindings.js). Pi's package exports neither its keybinding defaults
24
+ * nor its key formatter, so this copy is checked against the installed Pi by
25
+ * tests/loaded-box.test.ts.
26
+ */
27
+ const DEFAULT_EXPAND_KEY = "ctrl+o";
28
+ const EXPAND_KEYBINDING = "app.tools.expand";
29
+ /** The id Pi migrates to app.tools.expand from older keybindings files. */
30
+ const LEGACY_EXPAND_KEYBINDING = "expandTools";
31
+ /** Columns between the kind, its count and the names. */
32
+ const GAP = " ";
33
+
34
+ export type LoadedKind = { label: string; names: string[] };
35
+
36
+ const text = (value: string) => fg(palette.text, value);
37
+ const muted = (value: string) => fg(palette.muted, value);
38
+ const frame = (value: string) => fg(palette.frame, value);
39
+
40
+ const ESCAPES = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
41
+ const SECTION_HEADER = /^\[([^\]]+)\]$/;
42
+ /** Pi's warning sections ([Skill warnings], [Prompt conflicts], [Extension issues], [Theme conflicts]) are never folded. */
43
+ const DIAGNOSTIC = /warning|conflict|issue|error/i;
44
+
45
+ /**
46
+ * One of Pi's collapsed listing sections, `[Skills]` then ` btw, chained-pr`,
47
+ * as its kind (`skills`) and names in Pi's order. Undefined without a `[Name]`
48
+ * header, or for a warning section.
49
+ */
50
+ export function loadedKind(value: string): LoadedKind | undefined {
51
+ const [header = "", ...body] = value.replace(ESCAPES, "").split("\n");
52
+ const name = SECTION_HEADER.exec(header.trim())?.[1].trim();
53
+ if (!name || DIAGNOSTIC.test(name)) return undefined;
54
+ const names = body.join(" ").split(",").map((item) => item.trim()).filter((item) => item.length > 0);
55
+ return { label: name.toLowerCase(), names };
56
+ }
57
+
58
+ /** `skills 24 btw, chained-pr, g…`: the kind padded, its count right-aligned, the names cut to `width`. */
59
+ function kindRow({ label, names }: LoadedKind, labelWidth: number, countWidth: number, width: number): string {
60
+ const prefix = `${padEnd(label, labelWidth)}${GAP}${String(names.length).padStart(countWidth)}${GAP}`;
61
+ const room = width - visibleWidth(prefix);
62
+ if (room < 1) return muted(ellipsize(prefix.trimEnd(), width));
63
+ return muted(padEnd(label, labelWidth)) + GAP + text(String(names.length).padStart(countWidth)) + GAP + muted(ellipsize(names.join(", "), room));
64
+ }
65
+
66
+ /**
67
+ * The loaded box for `width` columns, centered like the welcome card; kinds
68
+ * with nothing loaded are left out, and nothing loaded draws nothing. Under the
69
+ * card's 34-column minimum the rows print without a frame or hint. The bottom
70
+ * rule names `key`, Pi's expand key; an empty key leaves the rule plain.
71
+ */
72
+ export function renderLoadedBox(kinds: readonly LoadedKind[], width: number, key = DEFAULT_EXPAND_KEY): string[] {
73
+ const columns = Math.max(0, Math.floor(width));
74
+ const shown = kinds.filter((kind) => kind.names.length > 0);
75
+ if (columns < 1 || shown.length === 0) return [];
76
+ const labelWidth = Math.max(...shown.map((kind) => visibleWidth(kind.label)));
77
+ const countWidth = Math.max(...shown.map((kind) => String(kind.names.length).length));
78
+ if (columns < MIN_BOX_WIDTH) return shown.map((kind) => kindRow(kind, labelWidth, countWidth, columns));
79
+
80
+ const boxWidth = Math.min(BOX_WIDTH, columns);
81
+ const inner = boxWidth - 2 * SIDE;
82
+ const indent = " ".repeat((columns - boxWidth) >> 1);
83
+ const row = (content: string) => `${indent}${frame("│")} ${padEnd(content, inner)} ${frame("│")}`;
84
+ const hint = key ? ` ${key} lists them ` : "";
85
+ const dashes = boxWidth - 3 - visibleWidth(hint);
86
+ const bottom = hint && dashes >= 1 ? `${frame(`╰${"─".repeat(dashes)}`)}${muted(hint)}${frame("─╯")}` : frame(`╰${"─".repeat(boxWidth - 2)}╯`);
87
+ return [
88
+ `${indent}${frame("╭─ ")}${muted(TITLE)}${frame(` ${"─".repeat(boxWidth - TOP_RULE_CHROME)}╮`)}`,
89
+ ...shown.map((kind) => row(kindRow(kind, labelWidth, countWidth, inner))),
90
+ `${indent}${bottom}`,
91
+ ];
92
+ }
93
+
94
+ type Render = (width: number) => string[];
95
+ type Node = { children?: unknown; render?: unknown };
96
+ /** Pi's ExpandableText: a ThemedText whose `build` gives the collapsed or expanded text by `state.expanded`. */
97
+ type PiSection = { state: { expanded: boolean }; build(): string; setExpanded(expanded: boolean): void; render: Render };
98
+
99
+ // Pi's tree: TUI > document > [header container > the card, loaded resources,
100
+ // chat]. The walk stops a few levels down and never descends into the chat.
101
+ const MAX_DEPTH = 3;
102
+ const MAX_NODES = 200;
103
+ /** Ours on a patched container; shared across reloads so a newer Fisi Dock wraps Pi's render, not an older wrapper. */
104
+ const PATCH = Symbol.for("fisi-dock.loaded-box");
105
+
106
+ type Patch = { original: Render; own: PropertyDescriptor | undefined; render: Render };
107
+
108
+ const childrenOf = (node: unknown): unknown[] | undefined => {
109
+ const children = node && typeof node === "object" ? (node as Node).children : undefined;
110
+ return Array.isArray(children) ? children : undefined;
111
+ };
112
+
113
+ /** Breadth-first over the top of the tree, with each node's parent; bounded. */
114
+ function walk(root: unknown, visit: (node: unknown, parent: unknown) => boolean): void {
115
+ const seen = new Set<unknown>();
116
+ let level: [unknown, unknown][] = [[root, undefined]];
117
+ for (let depth = 0; depth <= MAX_DEPTH && level.length > 0; depth++) {
118
+ const next: [unknown, unknown][] = [];
119
+ for (const [node, parent] of level) {
120
+ if (!node || typeof node !== "object" || seen.has(node) || seen.size >= MAX_NODES) continue;
121
+ seen.add(node);
122
+ if (visit(node, parent)) return;
123
+ if (depth < MAX_DEPTH) for (const child of childrenOf(node) ?? []) next.push([child, node]);
124
+ }
125
+ level = next;
126
+ }
127
+ }
128
+
129
+ /** Pi's loaded-resources container: the sibling right after the container holding `header`. */
130
+ function findLoadedResources(root: unknown, header: object): Node | undefined {
131
+ let found: Node | undefined;
132
+ walk(root, (node, parent) => {
133
+ if (!childrenOf(node)?.includes(header)) return false;
134
+ const siblings = childrenOf(parent);
135
+ const candidate = siblings?.[siblings.indexOf(node) + 1] as Node | undefined;
136
+ if (candidate && typeof candidate === "object" && childrenOf(candidate) && typeof candidate.render === "function") found = candidate;
137
+ return true;
138
+ });
139
+ return found;
140
+ }
141
+
142
+ /** Pi's keybindings.json: in its agent dir, `PI_CODING_AGENT_DIR` (`~` for the home), else `~/.pi/agent`. */
143
+ export function piKeybindingsPath(env: Record<string, string | undefined>, home: string): string {
144
+ const custom = env.PI_CODING_AGENT_DIR;
145
+ const agentDir = custom ? (custom === "~" ? home : custom.startsWith("~/") ? join(home, custom.slice(2)) : custom) : join(home, ".pi", "agent");
146
+ return join(agentDir, "keybindings.json");
147
+ }
148
+
149
+ // Pi's key ids (core/key-id-schema.js): up to four distinct modifiers, then a
150
+ // letter, a digit or one of pi-tui's key names.
151
+ const MODIFIERS = ["ctrl", "shift", "alt", "super"];
152
+ const KEY_NAMES = "escape esc enter return tab space backspace delete insert clear home end pageUp pageDown up down left right f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 ` - = [ ] \\ ; ' , . / ! @ # $ % ^ & * ( ) _ + | ~ { } : < > ?".split(" ");
153
+ const KEY_ID = new RegExp(
154
+ `^(?!.*(?:${MODIFIERS.map((modifier) => `${modifier}\\+.*${modifier}\\+`).join("|")}))(?:(?:${MODIFIERS.join("|")})\\+){0,4}(?:[a-z0-9]|${KEY_NAMES.map((name) => name.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&")).join("|")})$`,
155
+ );
156
+ const isKeyId = (value: unknown): value is string => typeof value === "string" && KEY_ID.test(value);
157
+
158
+ /** Keys as the hint names them: each once, joined with `/`; empty for none (no hint). */
159
+ const keyText = (keys: readonly string[]) => [...new Set(keys)].join("/");
160
+
161
+ /**
162
+ * The keys Pi binds to app.tools.expand by the keybindings file at `path`, the
163
+ * way Pi reads it (core/keybindings.js): app.tools.expand, else the legacy
164
+ * expandTools; a key id or a list of them (`[]` unbinds it, so empty); a value
165
+ * Pi rejects, a malformed or missing file: Pi's default.
166
+ */
167
+ export function readExpandKey(path: string): string {
168
+ let config: unknown;
169
+ try {
170
+ config = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
171
+ } catch {
172
+ return DEFAULT_EXPAND_KEY;
173
+ }
174
+ if (!config || typeof config !== "object") return DEFAULT_EXPAND_KEY;
175
+ const id = Object.hasOwn(config, EXPAND_KEYBINDING) ? EXPAND_KEYBINDING : LEGACY_EXPAND_KEYBINDING;
176
+ const value = (config as Record<string, unknown>)[id];
177
+ if (isKeyId(value)) return value;
178
+ return Array.isArray(value) && value.every(isKeyId) ? keyText(value) : DEFAULT_EXPAND_KEY;
179
+ }
180
+
181
+ /**
182
+ * Pi's configured expand key from its keybindings, which its editor holds,
183
+ * read on each call; without them, from Pi's keybindings file at
184
+ * `keybindingsPath`, read once.
185
+ */
186
+ function expandKeyReader(root: unknown, keybindingsPath: () => string): () => string {
187
+ let keybindings: { getKeys(id: string): unknown } | undefined;
188
+ walk(root, (node) => {
189
+ const candidate = (node as { keybindings?: { getKeys?: unknown } }).keybindings;
190
+ if (typeof candidate?.getKeys !== "function") return false;
191
+ keybindings = candidate as { getKeys(id: string): unknown };
192
+ return true;
193
+ });
194
+ let configured: string | undefined;
195
+ const fromFile = () => {
196
+ if (configured !== undefined) return configured;
197
+ try {
198
+ configured = readExpandKey(keybindingsPath());
199
+ } catch {
200
+ // No home to find the file in: Pi's default.
201
+ configured = DEFAULT_EXPAND_KEY;
202
+ }
203
+ return configured;
204
+ };
205
+ if (!keybindings) fromFile();
206
+ return () => {
207
+ if (!keybindings) return fromFile();
208
+ const keys = keybindings.getKeys(EXPAND_KEYBINDING);
209
+ return Array.isArray(keys) ? keyText(keys.filter((key) => typeof key === "string")) : fromFile();
210
+ };
211
+ }
212
+
213
+ const isSection = (child: unknown): child is PiSection => {
214
+ const section = child as Partial<PiSection> | null;
215
+ return typeof section === "object" && section !== null && typeof section.setExpanded === "function" && typeof section.build === "function" && typeof section.state?.expanded === "boolean";
216
+ };
217
+ /** Pi's Spacer: blank rows, `lines` of them. */
218
+ const isSpacer = (child: unknown) => typeof (child as { lines?: unknown }).lines === "number" && typeof (child as { setLines?: unknown }).setLines === "function";
219
+ /** Pi's warning sections and other texts: a ThemedText (`build`) or a Text (`text`). */
220
+ const isText = (child: unknown) => typeof (child as { build?: unknown }).build === "function" || typeof (child as { text?: unknown }).text === "string";
221
+
222
+ /**
223
+ * The container's lines with the box in place of Pi's listing sections, or
224
+ * undefined when Pi's own lines should show: no listing, a section expanded
225
+ * (Pi's expand toggle), or any child of a shape Pi's listing never has.
226
+ *
227
+ * The names come from each section's collapsed text, the same lists Pi would
228
+ * print (the compact labels Pi derives for extensions have no public API, and
229
+ * pi.getCommands() knows neither extensions nor context files).
230
+ */
231
+ function boxedLines(container: Node & { mouseLayout?: unknown }, width: number, key: string): string[] | undefined {
232
+ const children = childrenOf(container) ?? [];
233
+ const kinds: LoadedKind[] = [];
234
+ const listed = new Set<number>();
235
+ for (const [index, child] of children.entries()) {
236
+ if (isSection(child)) {
237
+ if (child.state.expanded) return undefined;
238
+ const kind = loadedKind(child.build());
239
+ if (!kind) return undefined;
240
+ kinds.push(kind);
241
+ listed.add(index);
242
+ } else if (!isSpacer(child) && !isText(child)) return undefined;
243
+ }
244
+ if (listed.size === 0) return undefined;
245
+ const box = renderLoadedBox(kinds, width, key);
246
+ const first = Math.min(...listed);
247
+ // Pi's spacers around its sections give way to one blank row under the box.
248
+ const beside = (index: number) => isSpacer(children[index]) && (listed.has(index - 1) || listed.has(index + 1));
249
+ const lines: string[] = [];
250
+ const layout: { component: unknown; height: number }[] = [];
251
+ for (const [index, child] of children.entries()) {
252
+ if (index === first) {
253
+ const rows = box.length > 0 ? [...box, ""] : [];
254
+ lines.push(...rows);
255
+ layout.push({ component: {}, height: rows.length });
256
+ }
257
+ if (listed.has(index) || beside(index)) continue;
258
+ const rows = (child as { render: Render }).render(width);
259
+ lines.push(...rows);
260
+ layout.push({ component: child, height: rows.length });
261
+ }
262
+ // Pi's Container routes the mouse by these heights; the box itself has nothing to click.
263
+ container.mouseLayout = { width, children: layout };
264
+ return lines;
265
+ }
266
+
267
+ export type LoadedBoxOptions = {
268
+ /** True while the box should show: Fisi Dock on and its welcome card in the header. */
269
+ active(): boolean;
270
+ /** Pi's keybindings file, for the hint when the tree holds no keybindings; piKeybindingsPath for this process by default. */
271
+ keybindingsPath?: string;
272
+ };
273
+
274
+ /**
275
+ * Wrap the render of Pi's loaded-resources container instance, found next to
276
+ * the container holding `header` (the welcome card) in the TUI tree under
277
+ * `root`. Each render reads the current sections, so Pi clearing and refilling
278
+ * the container (reload, settings) keeps the box. Never Container.prototype.
279
+ * Returns the restore that puts back exactly what was there, or undefined when
280
+ * Pi's tree is not recognized (nothing patched).
281
+ */
282
+ export function installLoadedBox(root: unknown, header: object, options: LoadedBoxOptions): (() => void) | undefined {
283
+ const container = findLoadedResources(root, header) as (Node & Record<PropertyKey, unknown>) | undefined;
284
+ if (!container) return undefined;
285
+ const key = expandKeyReader(root, () => options.keybindingsPath ?? piKeybindingsPath(process.env, homedir()));
286
+ // An earlier Fisi Dock that never restored (a crashed reload): wrap Pi's render it kept, not its wrapper.
287
+ const earlier = container[PATCH] as Patch | undefined;
288
+ const original = earlier?.original ?? (container.render as Render);
289
+ const own = earlier ? earlier.own : Object.getOwnPropertyDescriptor(container, "render");
290
+ let restored = false;
291
+ const render: Render = function (this: unknown, width: number): string[] {
292
+ if (!restored) {
293
+ try {
294
+ if (options.active()) {
295
+ const lines = boxedLines(container, width, key());
296
+ if (lines) return lines;
297
+ }
298
+ } catch {
299
+ // Deliberately ignored: anything unexpected shows Pi's own listing.
300
+ }
301
+ }
302
+ return original.call(this, width);
303
+ };
304
+ container.render = render;
305
+ container[PATCH] = { original, own, render } satisfies Patch;
306
+ return () => {
307
+ if (restored) return;
308
+ restored = true;
309
+ // Someone wrapped it after us: ours stays in their chain, passing through to Pi.
310
+ if (container.render !== render) return;
311
+ if (own) Object.defineProperty(container, "render", own);
312
+ else delete container.render;
313
+ delete container[PATCH];
314
+ };
315
+ }
package/lib/logo.ts ADDED
@@ -0,0 +1,97 @@
1
+ import { bold, fg, palette, type Rgb } from "./palette.ts";
2
+
3
+ // The "GENTLESHELL" wordmark in a 5-pixel-tall font, drawn with braille dots
4
+ // (S21, design rail-wordmark/04 "Tinted braille"). Each terminal cell holds two
5
+ // pixels stacked: the upper pixel is the top two dot rows, the lower pixel the
6
+ // bottom two, so 5 pixel rows take 3 terminal rows. The words are joined and told
7
+ // apart by color: GENTLE in a gray fade, SHELL in Gentle Shell's Gentleman-Sexy pinks,
8
+ // from its accent down to its deepPink. Two sizes: artboard 08's letters for
9
+ // Gentle Shell fisi/custom's wider rail, and the compact one for the official
10
+ // 47-column rail. Narrower rails get one bold text row in the same two colors,
11
+ // its letters spaced from 21 columns (design rail-wordmark/10 "Text mark").
12
+
13
+ type Font = Record<string, string[]>;
14
+
15
+ // Artboard 08 (.px grid): 4-column letters (L is 3).
16
+ const WIDE: Font = {
17
+ G: [".###", "#...", "#.##", "#..#", ".###"],
18
+ E: ["####", "#...", "###.", "#...", "####"],
19
+ N: ["#..#", "##.#", "#.##", "#..#", "#..#"],
20
+ T: ["####", ".##.", ".##.", ".##.", ".##."],
21
+ L: ["#..", "#..", "#..", "#..", "###"],
22
+ S: [".###", "#...", ".##.", "...#", "###."],
23
+ H: ["#..#", "#..#", "####", "#..#", "#..#"],
24
+ };
25
+
26
+ // The wide G, N and L (a 2-column L reads cut off); E, T, S and H narrow, so the
27
+ // joined mark is 45 columns and the 47-column rail centers it.
28
+ const COMPACT: Font = {
29
+ ...WIDE,
30
+ E: ["###", "#..", "##.", "#..", "###"],
31
+ T: ["###", ".#.", ".#.", ".#.", ".#."],
32
+ S: [".##", "#..", ".#.", "..#", "##."],
33
+ H: ["#.#", "#.#", "###", "#.#", "#.#"],
34
+ };
35
+
36
+ /** Each word's color for each pixel row, top to bottom. */
37
+ const SHADES: Rgb[][] = [
38
+ // GENTLE: near white down to mid gray.
39
+ [230, 205, 180, 155, 130].map((level): Rgb => [level, level, level]),
40
+ // SHELL: the Gentleman-Sexy accent down to its deepPink.
41
+ [0, 1, 2, 3, 4].map((step): Rgb => palette.sexyPink.map((channel, index) => Math.round(channel + ((palette.sexyDeepPink[index] - channel) * step) / 4)) as unknown as Rgb),
42
+ ];
43
+
44
+ const WORDS = ["GENTLE", "SHELL"];
45
+
46
+ /** Per pixel, the index of the word it lights, or -1 when unlit. One gap column between all letters. */
47
+ function pixelGrid(font: Font): number[][] {
48
+ const lit: number[][] = SHADES[0].map(() => []);
49
+ WORDS.join("").split("").forEach((letter, index) => {
50
+ if (index > 0) for (const row of lit) row.push(-1);
51
+ const word = index < WORDS[0].length ? 0 : 1;
52
+ font[letter].forEach((pixels, y) => lit[y].push(...[...pixels].map((pixel) => (pixel === "#" ? word : -1))));
53
+ });
54
+ return lit;
55
+ }
56
+
57
+ const BRAILLE = { upper: "⠛", lower: "⣤", both: "⣿" };
58
+
59
+ // A cell has one foreground color: the color of its upper lit pixel row.
60
+ function pixelLines(font: Font): string[] {
61
+ const grid = pixelGrid(font);
62
+ const lines: string[] = [];
63
+ for (let y = 0; y < grid.length; y += 2) {
64
+ const top = grid[y];
65
+ const bottom = grid[y + 1] ?? [];
66
+ const cells = top.map((upper, x) => {
67
+ const lower = bottom[x] ?? -1;
68
+ if (upper >= 0) return fg(SHADES[upper][y], lower >= 0 ? BRAILLE.both : BRAILLE.upper);
69
+ return lower >= 0 ? fg(SHADES[lower][y + 1], BRAILLE.lower) : " ";
70
+ });
71
+ lines.push(cells.join(""));
72
+ }
73
+ return lines;
74
+ }
75
+
76
+ const WIDE_LINES = pixelLines(WIDE);
77
+ const COMPACT_LINES = pixelLines(COMPACT);
78
+ const spaced = (word: string) => [...word].join(" ");
79
+ // Design rail-wordmark/10 "1 row, spaced": letters one column apart, so the row reads wider.
80
+ const SPACED_LINE = bold(fg(SHADES[0][1], `${spaced(WORDS[0])} `) + fg(palette.sexyPink, spaced(WORDS[1])));
81
+ const SPACED_WIDTH = spaced(WORDS.join("")).length;
82
+ const TEXT_LINE = bold(fg(SHADES[0][2], WORDS[0]) + fg(palette.sexyPink, WORDS[1]));
83
+
84
+ /** Visible columns of the wide wordmark (51); fisi/custom's 55-column rail fits it with its indent. */
85
+ export const LOGO_WIDTH = pixelGrid(WIDE)[0].length;
86
+ /** Visible columns of the compact wordmark (45), for the official 47-column rail. */
87
+ export const COMPACT_LOGO_WIDTH = pixelGrid(COMPACT)[0].length;
88
+
89
+ /** The wordmark for `width` columns: wide braille, compact braille, spaced text, joined text, then nothing. */
90
+ export function renderLogo(width: number): string[] {
91
+ const columns = Math.max(0, Math.floor(width));
92
+ if (columns >= LOGO_WIDTH) return WIDE_LINES;
93
+ if (columns >= COMPACT_LOGO_WIDTH) return COMPACT_LINES;
94
+ if (columns >= SPACED_WIDTH) return [SPACED_LINE];
95
+ if (columns >= WORDS.join("").length) return [TEXT_LINE];
96
+ return [];
97
+ }