@deathbeam/pi-plan 0.0.1 → 0.0.3

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/inspector.ts CHANGED
@@ -1,13 +1,26 @@
1
- import { rawKeyHint, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
1
+ import { rawKeyHint, getMarkdownTheme, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
+ Markdown,
3
4
  type Component,
4
5
  type Keybinding,
5
6
  type KeybindingsManager,
7
+ matchesKey,
6
8
  type TuiMouseEvent,
7
9
  truncateToWidth,
10
+ visibleWidth,
8
11
  wrapTextWithAnsi,
9
12
  } from "@earendil-works/pi-tui";
10
- import { planCount, planStatus, planSummary, STATUS, taskFacts, taskRow, type Plan, type PlanList } from "./store.ts";
13
+ import {
14
+ doneCount,
15
+ hanging,
16
+ nextTask,
17
+ planCount,
18
+ planStatus,
19
+ statusText,
20
+ type Plan,
21
+ type PlanList,
22
+ type PlanTask,
23
+ } from "./store.ts";
11
24
 
12
25
  type PlansScreenOptions = {
13
26
  plans: Plan[];
@@ -17,41 +30,158 @@ type PlansScreenOptions = {
17
30
  keys: KeybindingsManager;
18
31
  /** Terminal rows, read per frame. */
19
32
  height: () => number;
20
- setActive: (name: string) => void;
33
+ setActive: (id: string) => void;
21
34
  onClose: () => void;
22
35
  requestRender: () => void;
23
36
  };
24
37
 
38
+ type Focus = "list" | "detail";
39
+
25
40
  /** Fixed rows: title, top rule, bottom rule, footer. */
26
41
  const CHROME_ROWS = 4;
42
+ /** Prose past this width is hard to follow on a wide terminal; the pane leaves the rest empty. */
43
+ const MAX_TEXT_WIDTH = 120;
44
+ /** Rendered markdown by theme, then width and text; cleared by invalidate() and on a width change. */
45
+ const MARKDOWN_CACHE = new WeakMap<Theme, Map<string, string[]>>();
27
46
 
28
47
  function hint(keys: KeybindingsManager, ids: Keybinding[], description: string): string {
29
48
  return rawKeyHint(ids.flatMap((id) => keys.getKeys(id)).join("/"), description);
30
49
  }
31
50
 
51
+ /** Markdown reads a lone newline as a space; a planner's one-newline paragraph break is meant as a break. */
52
+ export function hardBreaks(text: string): string {
53
+ const lines = text.split("\n");
54
+ let fenced = false;
55
+ return lines
56
+ .map((line, index) => {
57
+ const fence = /^\s*(```|~~~)/.test(line);
58
+ const block = fenced || fence || /^\s*([-*+]|\d+\.)\s/.test(line) || /^\s*#/.test(line);
59
+ if (fence) fenced = !fenced;
60
+ return block || !lines[index + 1] ? line : `${line} `;
61
+ })
62
+ .join("\n");
63
+ }
64
+
65
+ /** Markdown rendered at one width, cached per theme: render() runs every frame and contexts can be long. */
66
+ function markdown(theme: Theme, text: string, width: number, indent = 0): string[] {
67
+ let cache = MARKDOWN_CACHE.get(theme);
68
+ if (!cache) MARKDOWN_CACHE.set(theme, (cache = new Map()));
69
+ const key = `${width} ${text}`;
70
+ let lines = cache.get(key);
71
+ if (!lines) {
72
+ const component = new Markdown(hardBreaks(text), 0, 0, getMarkdownTheme(), {
73
+ color: (t) => theme.fg("text", t),
74
+ });
75
+ // Markdown pads every row to its width; the pane pads again, so trim before composing.
76
+ lines = component.render(Math.max(1, width)).map((line) => line.trimEnd());
77
+ while (lines.length && !lines[0]) lines.shift();
78
+ while (lines.length && !lines.at(-1)) lines.pop();
79
+ cache.set(key, lines);
80
+ }
81
+ return lines.map((line) => " ".repeat(indent) + line);
82
+ }
83
+
84
+ /** A section heading: the word in accent, a rule to the pane edge, and the tasks heading's own count. */
85
+ function section(theme: Theme, word: string, width: number, trailing = ""): string {
86
+ const head = `${theme.bold(theme.fg("accent", word))} `;
87
+ const rule = "─".repeat(Math.max(0, width - visibleWidth(head) - visibleWidth(trailing)));
88
+ return head + theme.fg("borderMuted", rule) + trailing;
89
+ }
90
+
91
+ /** The title row: the glyph, the title, and the id at the right edge, with the blockers still open after it. */
92
+ function taskLines(plan: Plan, task: PlanTask, theme: Theme, width: number, current: boolean): string[] {
93
+ const open = task.dependsOn.filter((id) => !plan.tasks.some((item) => item.id === id && item.status === "done"));
94
+ const id = theme.fg("muted", open.length ? `${task.id} · after ${open.join(", ")}` : task.id);
95
+ // Accent means headings and labels, so the task the reader is on is bold text instead.
96
+ const title = theme.fg("text", task.title);
97
+ const [first = "", ...rest] = hanging(current ? theme.bold(title) : title, width, 2);
98
+ // The id sits beside the first row only, so that row loses the room the id and its gap take.
99
+ const room = Math.max(1, width - 3 - visibleWidth(id));
100
+ return [`${statusText(theme, task.status)} ${truncateToWidth(first, room, "…", true)} ${id}`, ...rest];
101
+ }
102
+
103
+ /** An accent label padded into one column, then its value in the column beside it. */
104
+ function field(theme: Theme, label: string, value: string, width: number, prose = false): string[] {
105
+ const lead = ` ${theme.fg("accent", label.padEnd(9))} `;
106
+ const column = visibleWidth(lead);
107
+ const lines = prose
108
+ ? markdown(theme, value, Math.max(1, width - column))
109
+ : wrapTextWithAnsi(theme.fg("text", value), Math.max(1, width - column));
110
+ const [first = "", ...rest] = lines;
111
+ return [lead + first, ...rest.map((line) => " ".repeat(column) + line)];
112
+ }
113
+
114
+ /** One task: its title row, then the goal, the brief and notes of every task still open. */
115
+ function taskBlock(
116
+ plan: Plan,
117
+ task: PlanTask,
118
+ theme: Theme,
119
+ width: number,
120
+ current: boolean,
121
+ expanded: boolean,
122
+ ): string[] {
123
+ const head = taskLines(plan, task, theme, width, current);
124
+ if (!expanded && task.status === "done") return head;
125
+ return [
126
+ ...head,
127
+ // Every label pads to nine columns, so the values start in one column.
128
+ ...field(theme, "Goal", task.goal, width, true),
129
+ ...(task.detail ? field(theme, "Detail", task.detail, width, true) : []),
130
+ ...task.notes.flatMap((note) => ["", ...markdown(theme, note, Math.max(1, width - 2), 2)]),
131
+ "",
132
+ ];
133
+ }
134
+
135
+ /** Goal, tasks and detail as three sections; the headings show where the reader is in a long plan. */
136
+ function taskRows(plan: Plan, theme: Theme, width: number, expanded: boolean): string[] {
137
+ const current = plan.tasks.find((task) => task.status === "doing") ?? nextTask(plan);
138
+ const blocks = plan.tasks.flatMap((task) => taskBlock(plan, task, theme, width, task === current, expanded));
139
+ // The next heading brings its own leading blank line, so a task's trailing one would double it.
140
+ if (blocks.at(-1) === "") blocks.pop();
141
+ return [
142
+ ...markdown(theme, plan.goal, width),
143
+ "",
144
+ section(theme, "Tasks", width, theme.fg("muted", ` ${planCount(plan)}`)),
145
+ ...blocks,
146
+ "",
147
+ section(theme, "Detail", width),
148
+ ...markdown(theme, plan.detail, width),
149
+ ...plan.notes.flatMap((note) => ["", ...markdown(theme, note, Math.max(1, width - 2), 2)]),
150
+ ].map((line) => truncateToWidth(line, width, "…", true));
151
+ }
152
+
153
+ /** Two rows per plan, like pi-delegate's job rows: cursor, status glyph, id and count, then the title. */
32
154
  function sidebarRows(
33
155
  plans: Plan[],
34
156
  unreadable: string[],
35
157
  selected: number,
36
158
  active: string | undefined,
159
+ focus: Focus,
37
160
  theme: Theme,
38
161
  width: number,
39
162
  height: number,
40
163
  ): { lines: string[]; indexes: (number | undefined)[] } {
41
- const all: { line: string; index?: number }[] = [
164
+ const all: { lines: string[]; index?: number }[] = [
42
165
  ...plans.map((plan, planIndex) => {
43
166
  const chosen = planIndex === selected;
44
- // pi-delegate's cursor column: the matched glyph, then the name, like its job rows.
45
- const name = theme.fg(chosen ? "accent" : "text", plan.name);
46
- const count = theme.fg(STATUS[planStatus(plan)].color, planCount(plan));
47
- const mark = plan.name === active ? theme.fg("muted", " · active") : "";
48
- const line = `${chosen ? theme.fg("accent", "›") : " "} ${name} ${count}${mark}`;
49
- return { line, index: planIndex };
167
+ // The cursor dims while the detail pane takes the keys, so the user sees which pane is live.
168
+ const cursor = chosen ? theme.fg(focus === "list" ? "accent" : "muted", "›") : " ";
169
+ return {
170
+ lines: [
171
+ `${cursor} ${statusText(theme, planStatus(plan))} ${theme.fg(chosen ? "accent" : "text", plan.id)} ${theme.fg("muted", planCount(plan))}`,
172
+ theme.fg("dim", ` ${plan.id === active ? "active · " : ""}${plan.title}`),
173
+ ],
174
+ index: planIndex,
175
+ };
50
176
  }),
51
- ...unreadable.map((name) => ({ line: theme.fg("error", ` ? ${name} unreadable`) })),
177
+ ...unreadable.map((file) => ({ lines: [theme.fg("error", ` ? ${file} unreadable`)] })),
52
178
  ];
53
- const start = Math.max(0, Math.min(selected - Math.floor(height / 2), all.length - height));
54
- const shown = all.slice(start, start + height);
179
+ const rows = all.flatMap((entry) => entry.lines.map((line, at) => ({ line, index: entry.index, head: at === 0 })));
180
+ const selectedRow = rows.findIndex((row) => row.index === selected);
181
+ let start = Math.max(0, Math.min(selectedRow - Math.floor(height / 2), rows.length - height));
182
+ // A window never opens on a plan's second row, which would show a title with no id above it.
183
+ while (start > 0 && !rows[start]!.head) start--;
184
+ const shown = rows.slice(start, start + height);
55
185
  return {
56
186
  lines: [
57
187
  ...shown.map(
@@ -65,40 +195,29 @@ function sidebarRows(
65
195
  };
66
196
  }
67
197
 
68
- function detailRows(plan: Plan, theme: Theme, width: number): string[] {
69
- const lines = [
70
- ...wrapTextWithAnsi(planSummary(theme, plan), width),
71
- "",
72
- ...wrapTextWithAnsi(theme.fg("muted", `goal: ${plan.goal}`), width),
73
- ...(plan.context ? ["", ...wrapTextWithAnsi(theme.fg("muted", `context: ${plan.context}`), width)] : []),
74
- "",
75
- ];
76
- for (const task of plan.tasks) {
77
- lines.push(...wrapTextWithAnsi(taskRow(theme, plan, task), width));
78
- for (const fact of taskFacts(theme, task)) lines.push(...wrapTextWithAnsi(fact, width));
79
- lines.push("");
80
- }
81
- return lines.map((line) => truncateToWidth(line, width, "…", true));
82
- }
83
-
84
- /** The /plan screen: every plan in the sidebar, the selected one's tasks on the right. */
198
+ /** The /plan screen, laid out like pi-delegate's: the plans on the left, the selected one's tasks on the right. */
85
199
  export class PlansScreen implements Component {
86
200
  private readonly options: PlansScreenOptions;
87
201
  private index: number;
88
202
  private active: string | undefined;
203
+ private focus: Focus = "list";
89
204
  private top = 0;
205
+ private expanded = false;
90
206
  private lastBody = { height: 0, total: 0 };
91
207
  private lastIndexes: (number | undefined)[] = [];
92
208
  private lastSidebar = 0;
209
+ private lastTextWidth = 0;
93
210
 
94
211
  constructor(options: PlansScreenOptions) {
95
212
  this.options = options;
96
213
  this.active = options.active;
97
- const found = options.active ? options.plans.findIndex((plan) => plan.name === options.active) : -1;
214
+ const found = options.active ? options.plans.findIndex((plan) => plan.id === options.active) : -1;
98
215
  this.index = Math.max(0, found);
99
216
  }
100
217
 
101
- invalidate() {}
218
+ invalidate() {
219
+ MARKDOWN_CACHE.delete(this.options.theme);
220
+ }
102
221
 
103
222
  render(width: number): string[] {
104
223
  const { plans, unreadable, theme, height, keys } = this.options;
@@ -108,63 +227,113 @@ export class PlansScreen implements Component {
108
227
  const detailWidth = Math.max(1, width - sidebarWidth - 1);
109
228
  this.lastSidebar = sidebarWidth;
110
229
  const row = (text: string, columns = width) => truncateToWidth(text, columns, "…", true);
230
+ const list = this.focus === "list";
111
231
  const title = row(
112
- `${theme.fg("accent", "Plans")}${theme.fg("dim", ` · ${plans.length + unreadable.length} in .pi/plans`)}`,
232
+ `${theme.fg(list ? "accent" : "muted", list ? "[Plans]" : "Plans")} ` +
233
+ `${theme.fg(list ? "muted" : "accent", list ? "Tasks" : "[Tasks]")}` +
234
+ theme.fg("dim", ` · ${plans.length + unreadable.length} in .pi/plans`),
113
235
  );
114
236
  const rule = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
237
+ // Always-on keys first, so the pane's own hints can spill off a narrow line.
238
+ const paneHints = list
239
+ ? hint(keys, ["tui.select.up", "tui.select.down"], "select plan")
240
+ : `${hint(keys, ["tui.select.up", "tui.select.down"], "scroll")} · ${hint(keys, ["tui.altScreen.pageUp", "tui.altScreen.pageDown"], "page")}`;
115
241
  const footer = row(
116
242
  theme.fg(
117
243
  "dim",
118
244
  [
119
- hint(keys, ["tui.select.up", "tui.select.down"], "select plan"),
245
+ rawKeyHint("←/→", "pane"),
120
246
  hint(keys, ["tui.select.confirm"], "make active"),
121
- hint(keys, ["tui.altScreen.pageUp", "tui.altScreen.pageDown"], "scroll"),
122
247
  hint(keys, ["tui.select.cancel"], "close"),
248
+ hint(keys, ["app.tools.expand"], this.expanded ? "collapse" : "expand"),
249
+ paneHints,
123
250
  ].join(" · "),
124
251
  ),
125
252
  );
126
253
  const plan = plans[this.index];
127
- const sidebar = sidebarRows(plans, unreadable, this.index, this.active, theme, sidebarWidth, body);
254
+ const sidebar = sidebarRows(plans, unreadable, this.index, this.active, this.focus, theme, sidebarWidth, body);
128
255
  this.lastIndexes = sidebar.indexes;
129
256
  const detail = plan
130
- ? detailRows(plan, theme, detailWidth)
257
+ ? this.detail(plan, Math.min(detailWidth, MAX_TEXT_WIDTH), detailWidth, body)
131
258
  : [row(theme.fg("muted", "No readable plans."), detailWidth)];
132
- const start = Math.min(this.top, Math.max(0, detail.length - body));
133
- this.top = start;
134
- this.lastBody = { height: body, total: detail.length };
135
- const shown = detail.slice(start, start + body);
136
- const right = [...shown, ...Array(Math.max(0, body - shown.length)).fill("")];
137
- return [title, rule, ...sidebar.lines.map((line, index) => `${line} ${right[index] ?? ""}`), rule, footer];
259
+ return [title, rule, ...sidebar.lines.map((line, index) => `${line} ${detail[index] ?? ""}`), rule, footer];
138
260
  }
139
261
 
140
262
  handleInput(data: string): void {
141
263
  const { keys, onClose, setActive } = this.options;
264
+ const detail = this.focus === "detail";
142
265
  if (keys.matches(data, "tui.select.cancel")) onClose();
143
- else if (keys.matches(data, "tui.select.up")) this.select(-1);
144
- else if (keys.matches(data, "tui.select.down")) this.select(1);
266
+ else if (matchesKey(data, "left")) this.focus = "list";
267
+ else if (matchesKey(data, "right")) this.focus = "detail";
145
268
  else if (keys.matches(data, "tui.select.confirm")) {
146
269
  const plan = this.options.plans[this.index];
147
270
  if (!plan) return;
148
- this.active = plan.name;
149
- setActive(plan.name);
150
- } else if (keys.matches(data, "tui.altScreen.pageUp")) this.scroll(-this.pageSize());
151
- else if (keys.matches(data, "tui.altScreen.pageDown")) this.scroll(this.pageSize());
271
+ this.active = plan.id;
272
+ setActive(plan.id);
273
+ } else if (keys.matches(data, "app.tools.expand")) {
274
+ this.expanded = !this.expanded;
275
+ this.top = 0;
276
+ } else if (detail && keys.matches(data, "tui.altScreen.pageUp")) this.scroll(-this.pageSize());
277
+ else if (detail && keys.matches(data, "tui.altScreen.pageDown")) this.scroll(this.pageSize());
278
+ else if (detail && keys.matches(data, "tui.altScreen.top")) this.top = 0;
279
+ else if (detail && keys.matches(data, "tui.altScreen.bottom")) this.top = Infinity;
280
+ else if (keys.matches(data, "tui.select.up")) this.move(-1);
281
+ else if (keys.matches(data, "tui.select.down")) this.move(1);
152
282
  this.options.requestRender();
153
283
  }
154
284
 
155
285
  // Fullscreen turns on mouse tracking, so the wheel arrives here instead of as arrow keys.
156
286
  handleMouse(event: TuiMouseEvent) {
157
- if (event.type === "wheel" && event.wheelDelta) this.scroll(event.wheelDelta);
158
- else if (event.type === "click" && event.button === "left" && event.x < this.lastSidebar) {
287
+ if (event.type === "wheel" && event.wheelDelta) {
288
+ if (event.x < this.lastSidebar) this.select(event.wheelDelta < 0 ? -1 : 1);
289
+ else this.scroll(event.wheelDelta);
290
+ } else if (event.type === "click" && event.button === "left" && event.x < this.lastSidebar) {
159
291
  const target = this.lastIndexes[event.y - 2];
160
292
  if (event.y < 2 || event.y - 2 >= this.lastBody.height || target === undefined) return;
161
293
  this.index = target;
162
294
  this.top = 0;
163
- } else return;
295
+ } else if (event.type === "click" && event.button === "left") this.focus = "detail";
296
+ else return;
164
297
  this.options.requestRender();
165
298
  return { handled: true };
166
299
  }
167
300
 
301
+ /** The right pane: the plan's id and title stay put over the goal, tasks and detail, with a counter below. */
302
+ private detail(plan: Plan, textWidth: number, width: number, body: number): string[] {
303
+ const { theme } = this.options;
304
+ if (this.lastTextWidth !== textWidth) {
305
+ this.lastTextWidth = textWidth;
306
+ MARKDOWN_CACHE.delete(theme);
307
+ }
308
+ const blocked = plan.tasks.some((task) => task.status === "blocked") ? " · blocked" : "";
309
+ const progress = theme.fg("muted", `${doneCount(plan)} of ${plan.tasks.length} done${blocked}`);
310
+ const head = `${theme.fg("accent", plan.id)} ${theme.fg("text", plan.title)}`;
311
+ const header = [
312
+ head + " ".repeat(Math.max(0, textWidth - visibleWidth(head) - visibleWidth(progress))) + progress,
313
+ ];
314
+ const height = Math.max(0, body - header.length - 1);
315
+ const all = taskRows(plan, theme, textWidth, this.expanded);
316
+ const start = Math.min(this.top, Math.max(0, all.length - height));
317
+ this.top = start;
318
+ this.lastBody = { height, total: all.length };
319
+ const shown = all.slice(start, start + height);
320
+ const counter = theme.fg(
321
+ "muted",
322
+ shown.length ? `${start + 1}–${start + shown.length}/${all.length}` : `0/${all.length}`,
323
+ );
324
+ // Right-aligned like pi-delegate's counter; every row is padded so the pane's right edge holds still.
325
+ const tail = " ".repeat(Math.max(0, width - visibleWidth(counter))) + counter;
326
+ return [...header, ...shown, ...Array(Math.max(0, height - shown.length)).fill(""), tail].map((line) =>
327
+ truncateToWidth(line, width, "…", true),
328
+ );
329
+ }
330
+
331
+ // Detail focus scrolls by a line; list focus moves the cursor.
332
+ private move(step: number) {
333
+ if (this.focus === "detail") this.scroll(step);
334
+ else this.select(step);
335
+ }
336
+
168
337
  private select(step: number) {
169
338
  this.index = Math.max(0, Math.min(this.options.plans.length - 1, this.index + step));
170
339
  this.top = 0;
@@ -185,7 +354,7 @@ export function openPlans(
185
354
  ctx: ExtensionContext,
186
355
  list: PlanList,
187
356
  active: string | undefined,
188
- setActive: (name: string) => void,
357
+ setActive: (id: string) => void,
189
358
  ): Promise<void> {
190
359
  const screen = { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 } } as const;
191
360
  return ctx.ui.custom<void>(