proper-base 0.2.8 → 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.
package/README.md CHANGED
@@ -29,7 +29,7 @@ and footer layout.
29
29
 
30
30
  | Input | Behavior |
31
31
  | --- | --- |
32
- | Shift+Enter or Alt+Enter | Insert a newline. Alt+Enter no longer queues a follow-up. |
32
+ | Alt+Enter | Insert a newline instead of queuing a follow-up. Pi's own Shift+Enter and Ctrl+J stay intact. |
33
33
  | Home | Move to the current visible-row start, then the full prompt start. |
34
34
  | End | Move to the current logical-line end, then the full prompt end. |
35
35
  | Ctrl+C with text | Clear the prompt without arming exit. |
package/index.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  type ExtensionAPI,
16
16
  type ExtensionContext,
17
17
  getAgentDir,
18
+ SessionManager,
18
19
  } from "@earendil-works/pi-coding-agent";
19
20
 
20
21
  import {
@@ -30,6 +31,11 @@ import {
30
31
  installReverseHistorySearch,
31
32
  type ReverseHistorySearchController,
32
33
  } from "./src/editor-navigation.ts";
34
+ import {
35
+ FastOverlay,
36
+ fastToggleNotice,
37
+ isFastToggle,
38
+ } from "./src/fast-mode.ts";
33
39
  import { installFooterColors } from "./src/footer-colors.ts";
34
40
  import {
35
41
  isRecallable,
@@ -51,6 +57,8 @@ import {
51
57
  } from "./src/prompt-display.ts";
52
58
  import { installPromptJump } from "./src/prompt-jump.ts";
53
59
  import { installRecorder } from "./src/recorder.ts";
60
+ import { installSelectionDismiss } from "./src/selection-dismiss.ts";
61
+ import { installFastSessionList } from "./src/session-list.ts";
54
62
  import { pinSkillContext } from "./src/skill-context.ts";
55
63
  import { installSmartSelection } from "./src/smart-selection.ts";
56
64
  import {
@@ -111,10 +119,11 @@ function installKeybindings(keybindings: EditorKeybindings): void {
111
119
  "ctrl+shift+v" as const,
112
120
  ]),
113
121
  ];
122
+ // Shift+Enter is already Pi's `tui.input.newLine` default; only Alt+Enter
123
+ // needs adding, and only because it must leave `app.message.followUp`.
114
124
  const newLineKeys = [
115
125
  ...new Set([
116
126
  ...keybindings.getKeys("tui.input.newLine"),
117
- "shift+enter" as const,
118
127
  "alt+enter" as const,
119
128
  ]),
120
129
  ];
@@ -162,8 +171,33 @@ type PendingPrompt = {
162
171
  processed: boolean;
163
172
  cancelled: boolean;
164
173
  entryId?: string;
174
+ originId?: string | undefined;
165
175
  };
166
- type RestoreRequest = { entryId: string };
176
+ type RestoreRequest = { entryId: string; originId?: string | undefined };
177
+
178
+ /**
179
+ * Extensions may append transcript entries between submission and the prompt's
180
+ * own session entry; proper-pacify writes one before it rewrites the text. Those
181
+ * entries are the prompt's parents, so navigating to the prompt keeps them and
182
+ * leaves orphan rows behind. Aim at the leaf the submission started from, unless
183
+ * it is a prompt entry of its own (navigating there would drop that turn too) or
184
+ * no longer an ancestor because the tree moved meanwhile.
185
+ */
186
+ function cancelTargetId(
187
+ ctx: ExtensionContext,
188
+ request: RestoreRequest,
189
+ ): string {
190
+ if (!request.originId) return request.entryId;
191
+ const origin = ctx.sessionManager.getEntry(request.originId);
192
+ if (!origin || origin.type === "custom_message") return request.entryId;
193
+ if (origin.type === "message" && origin.message.role === "user") {
194
+ return request.entryId;
195
+ }
196
+ const ancestor = ctx.sessionManager
197
+ .getBranch(request.entryId)
198
+ .some((entry) => entry.id === request.originId);
199
+ return ancestor ? request.originId : request.entryId;
200
+ }
167
201
 
168
202
  /**
169
203
  * `details` shape of the `ask_user_question` tool result, from
@@ -214,18 +248,52 @@ function decodeModelReference(value: string): ModelReference | undefined {
214
248
 
215
249
  export default function (pi: ExtensionAPI) {
216
250
  enableScribeImageCapability();
251
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session listing]]
252
+ installFastSessionList(SessionManager, getAgentDir());
253
+
254
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Fast tier scopes]]
255
+ const fastOverlay = new FastOverlay(getAgentDir());
256
+ pi.on("before_provider_request", (event, ctx) =>
257
+ fastOverlay.rewritePayload(event.payload, ctx.model ?? undefined),
258
+ );
259
+ pi.registerCommand?.("fast-global", {
260
+ description: "Toggle CLIProxyAPI Fast mode for all sessions.",
261
+ handler: async (args, ctx) => {
262
+ if (args.trim()) {
263
+ ctx.ui.notify("Usage: /fast-global", "error");
264
+ return;
265
+ }
266
+ let enabled: boolean;
267
+ try {
268
+ enabled = fastOverlay.toggleGlobal();
269
+ } catch (error) {
270
+ const message = error instanceof Error ? error.message : String(error);
271
+ ctx.ui.notify(`Failed to save Fast mode: ${message}`, "error");
272
+ return;
273
+ }
274
+ const notice = fastToggleNotice({
275
+ scope: "global",
276
+ enabled,
277
+ otherEnabled: fastOverlay.isSessionEnabled(),
278
+ modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
279
+ });
280
+ ctx.ui.notify(notice.message, notice.level);
281
+ },
282
+ });
217
283
 
218
284
  let removeFooterColors: (() => void) | undefined;
219
285
  let removeJumpToBottom: (() => void) | undefined;
220
286
  let removePromptJump: (() => void) | undefined;
221
287
  let removePromptClear: (() => void) | undefined;
222
288
  let removeSmartSelection: (() => void) | undefined;
289
+ let removeSelectionDismiss: (() => void) | undefined;
223
290
  let imagePreview: ImagePreviewController | undefined;
224
291
  let removeTerminalInput: (() => void) | undefined;
225
292
  let transcriptCleanup: TranscriptCleanupController | undefined;
226
293
  let activeEditor: PromptEditor | undefined;
227
294
  let activeTui: EditorTui | undefined;
228
295
  let submittedPrompt: string | undefined;
296
+ let submittedOriginId: string | undefined;
229
297
  let pendingPrompt: PendingPrompt | undefined;
230
298
  let restoreRequest: RestoreRequest | undefined;
231
299
  let sessionTitlePending = false;
@@ -299,11 +367,12 @@ export default function (pi: ExtensionAPI) {
299
367
 
300
368
  const target = ctx.sessionManager.getEntry(request.entryId);
301
369
  if (target?.type !== "message" || target.message.role !== "user") return;
370
+ const targetId = cancelTargetId(ctx, request);
302
371
  try {
303
- if (ctx.sessionManager.getLeafId() === request.entryId) {
304
- pi.appendEntry(CANCEL_ANCHOR, { targetId: request.entryId });
372
+ if (ctx.sessionManager.getLeafId() === targetId) {
373
+ pi.appendEntry(CANCEL_ANCHOR, { targetId });
305
374
  }
306
- await ctx.navigateTree(request.entryId, { summarize: false });
375
+ await ctx.navigateTree(targetId, { summarize: false });
307
376
  } catch (error) {
308
377
  ctx.ui.notify(
309
378
  `Could not remove cancelled prompt: ${error instanceof Error ? error.message : String(error)}`,
@@ -329,6 +398,7 @@ export default function (pi: ExtensionAPI) {
329
398
  if (event.source !== "interactive" || !event.text.trim()) return;
330
399
  pendingPrompt = {
331
400
  text: submittedPrompt ?? event.text,
401
+ originId: submittedPrompt ? submittedOriginId : undefined,
332
402
  processed: false,
333
403
  cancelled: false,
334
404
  };
@@ -454,7 +524,7 @@ export default function (pi: ExtensionAPI) {
454
524
  ? ctx.sessionManager.getEntry(candidate.entryId)
455
525
  : findPendingEntry(ctx);
456
526
  if (entry?.type === "message" && entry.message.role === "user") {
457
- restoreRequest = { entryId: entry.id };
527
+ restoreRequest = { entryId: entry.id, originId: candidate.originId };
458
528
  pendingPrompt = undefined;
459
529
  pi.sendUserMessage(`/${CANCEL_PROMPT_COMMAND}`, {
460
530
  expandPromptTemplates: true,
@@ -489,6 +559,8 @@ export default function (pi: ExtensionAPI) {
489
559
  removePromptClear = undefined;
490
560
  removeSmartSelection?.();
491
561
  removeSmartSelection = undefined;
562
+ removeSelectionDismiss?.();
563
+ removeSelectionDismiss = undefined;
492
564
  imagePreview?.dispose();
493
565
  imagePreview = undefined;
494
566
  removeTerminalInput?.();
@@ -505,6 +577,8 @@ export default function (pi: ExtensionAPI) {
505
577
  });
506
578
 
507
579
  pi.on("session_start", async (_event, ctx) => {
580
+ // Session Fast never survives into a new or restored session.
581
+ fastOverlay.resetSession();
508
582
  promptDisplay.restore(ctx.sessionManager.getBranch());
509
583
  sessionTitlePending =
510
584
  !pi.getSessionName?.() &&
@@ -569,6 +643,10 @@ export default function (pi: ExtensionAPI) {
569
643
  !sourceText.trimStart().startsWith("!")
570
644
  ) {
571
645
  submittedPrompt = sourceText;
646
+ // Captured here rather than on the `input` event: extensions that
647
+ // wrap Pi's input dispatch have already appended their own entries
648
+ // by the time that event reaches this extension.
649
+ submittedOriginId = ctx.sessionManager.getLeafId() ?? undefined;
572
650
  }
573
651
  };
574
652
 
@@ -587,6 +665,8 @@ export default function (pi: ExtensionAPI) {
587
665
  transcriptCleanup = installTranscriptCleanup(tui, ctx);
588
666
  removeSmartSelection?.();
589
667
  removeSmartSelection = installSmartSelection(tui);
668
+ removeSelectionDismiss?.();
669
+ removeSelectionDismiss = installSelectionDismiss(tui);
590
670
  historyGuard = installHistoryGuard(editor);
591
671
  removeJumpToBottom?.();
592
672
  removeJumpToBottom = installJumpToBottom(editor, tui);
@@ -606,6 +686,20 @@ export default function (pi: ExtensionAPI) {
606
686
  editor,
607
687
  record,
608
688
  (text) => imagePreview?.prepare(text) ?? text,
689
+ // pi dispatches extension commands before the `input` event, so the
690
+ // provider's global `/fast` can only be repurposed as a session
691
+ // toggle by consuming it at the editor before pi ever parses it.
692
+ (text) => {
693
+ if (!isFastToggle(text)) return false;
694
+ const notice = fastToggleNotice({
695
+ scope: "session",
696
+ enabled: fastOverlay.toggleSession(),
697
+ otherEnabled: fastOverlay.isGlobalEnabled(),
698
+ modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
699
+ });
700
+ ctx.ui.notify(notice.message, notice.level);
701
+ return true;
702
+ },
609
703
  );
610
704
  installModelAutocompleteSubmit(editor, keybindings);
611
705
  removePromptClear?.();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.2.8",
3
+ "version": "0.3.0",
4
4
  "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -19,6 +19,16 @@ const INLINE_SLASH_INSTALLED = Symbol.for(
19
19
  "pi-proper-base.inline-slash-autocomplete",
20
20
  );
21
21
 
22
+ /**
23
+ * One collator for the `/model` sort. `localeCompare` with an options object
24
+ * constructs a collator per call, which the per-keystroke sort would pay
25
+ * hundreds of times per keypress.
26
+ */
27
+ const MODEL_ORDER = new Intl.Collator("en", {
28
+ numeric: true,
29
+ sensitivity: "base",
30
+ });
31
+
22
32
  type AutocompleteEditor = Component & {
23
33
  autocompleteList?: {
24
34
  getSelectedItem(): { description?: string } | null;
@@ -192,10 +202,8 @@ export function sortModelAutocompleteDescending(
192
202
  ...suggestions,
193
203
  items: [...items].sort(
194
204
  (a, b) =>
195
- b.label.localeCompare(a.label, "en", {
196
- numeric: true,
197
- sensitivity: "base",
198
- }) || b.value.localeCompare(a.value),
205
+ MODEL_ORDER.compare(b.label, a.label) ||
206
+ b.value.localeCompare(a.value),
199
207
  ),
200
208
  };
201
209
  },
@@ -335,9 +343,17 @@ export function installAutocompleteDetails(
335
343
  const render = target.render.bind(target);
336
344
  target.render = (width: number) => {
337
345
  const lines = render(width);
346
+ // rowsBelow re-renders every component below the editor, so frames
347
+ // without a selected description skip the measurement entirely.
348
+ const description = target.autocompleteList?.getSelectedItem()?.description;
349
+ if (!description) {
350
+ detail.setDescription(undefined, 0);
351
+ releaseOverlay();
352
+ return lines;
353
+ }
338
354
  margin.bottom = lines.length + rowsBelow(tui, target, width);
339
355
  detail.setDescription(
340
- target.autocompleteList?.getSelectedItem()?.description,
356
+ description,
341
357
  Math.max(0, tui.terminal.rows - margin.bottom),
342
358
  );
343
359
  if (detail.isVisible() && isMounted(tui, target)) ensureOverlay();
@@ -0,0 +1,210 @@
1
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ const CONFIG_FILE_NAME = "cliproxyapi.json";
5
+ const MODELS_CACHE_FILE_NAME = "cliproxyapi-models.json";
6
+ const DEFAULT_PROVIDER_ID = "cliproxyapi";
7
+ const PRIORITY_TIER = "priority";
8
+ const FAST_COMMAND = "/fast";
9
+
10
+ type JsonObject = Record<string, unknown>;
11
+
12
+ /** The request-model fields this module reads. */
13
+ export type FastModel = { provider: string; id: string };
14
+
15
+ export type FastNotice = { message: string; level: "info" | "warning" };
16
+
17
+ function readJsonObject(path: string): JsonObject | undefined {
18
+ try {
19
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
20
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
21
+ ? (parsed as JsonObject)
22
+ : undefined;
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
27
+
28
+ /** Mirror of the provider's boolean-setting grammar for `CLIPROXYAPI_FAST`. */
29
+ function parseBooleanSetting(value: string): boolean | undefined {
30
+ switch (value.trim().toLowerCase()) {
31
+ case "1":
32
+ case "true":
33
+ case "yes":
34
+ case "on":
35
+ return true;
36
+ case "0":
37
+ case "false":
38
+ case "no":
39
+ case "off":
40
+ return false;
41
+ default:
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ /** Whether submitted editor text is exactly the `/fast` toggle. */
47
+ export function isFastToggle(text: string): boolean {
48
+ return text.trim() === FAST_COMMAND;
49
+ }
50
+
51
+ /**
52
+ * Session and global Fast preferences layered over the CLIProxyAPI provider.
53
+ *
54
+ * The provider's own `/fast` persists one flag and refreshes it only at
55
+ * extension load, so it is neither session-scoped nor live across sessions.
56
+ * This overlay owns the final `service_tier` decision instead: the session
57
+ * flag lives in memory and dies with the session, while the global flag is
58
+ * the provider's persisted `fast` key, re-read on every request so a toggle
59
+ * in one session reaches every running session's next request.
60
+ */
61
+ export class FastOverlay {
62
+ private sessionEnabled = false;
63
+ private modelsCache: { mtimeMs: number; ids: Set<string> } | undefined;
64
+ private readonly agentDir: string;
65
+ private readonly env: Record<string, string | undefined>;
66
+
67
+ constructor(
68
+ agentDir: string,
69
+ env: Record<string, string | undefined> = process.env,
70
+ ) {
71
+ this.agentDir = agentDir;
72
+ this.env = env;
73
+ }
74
+
75
+ private configPath(): string {
76
+ return join(this.agentDir, CONFIG_FILE_NAME);
77
+ }
78
+
79
+ /** Session Fast is never persisted; a new session always starts off. */
80
+ resetSession(): void {
81
+ this.sessionEnabled = false;
82
+ }
83
+
84
+ isSessionEnabled(): boolean {
85
+ return this.sessionEnabled;
86
+ }
87
+
88
+ toggleSession(): boolean {
89
+ this.sessionEnabled = !this.sessionEnabled;
90
+ return this.sessionEnabled;
91
+ }
92
+
93
+ /**
94
+ * The provider's Fast default: `CLIPROXYAPI_FAST` when set, else the
95
+ * persisted `fast` key. Re-read per call so other sessions' writes count.
96
+ */
97
+ isGlobalEnabled(): boolean {
98
+ const envValue = this.env.CLIPROXYAPI_FAST;
99
+ if (envValue !== undefined) {
100
+ const parsed = parseBooleanSetting(envValue);
101
+ if (parsed !== undefined) return parsed;
102
+ }
103
+ return readJsonObject(this.configPath())?.fast === true;
104
+ }
105
+
106
+ /**
107
+ * Flip the persisted global flag, preserving every other config key and
108
+ * the provider's own file format. Write failures propagate to the caller.
109
+ */
110
+ toggleGlobal(): boolean {
111
+ const existing = readJsonObject(this.configPath()) ?? {};
112
+ const next = !this.isGlobalEnabled();
113
+ writeFileSync(
114
+ this.configPath(),
115
+ `${JSON.stringify({ ...existing, fast: next }, null, 2)}\n`,
116
+ "utf8",
117
+ );
118
+ return next;
119
+ }
120
+
121
+ /** The configured provider id the overlay scopes itself to. */
122
+ providerId(): string {
123
+ const envId = this.env.CLIPROXYAPI_PROVIDER_ID?.trim();
124
+ if (envId) return envId;
125
+ const fileId = readJsonObject(this.configPath())?.providerId;
126
+ return typeof fileId === "string" && fileId.trim()
127
+ ? fileId.trim()
128
+ : DEFAULT_PROVIDER_ID;
129
+ }
130
+
131
+ /** Whether the provider's cached catalog marks this model Fast-capable. */
132
+ supportsModel(model: FastModel | undefined): boolean {
133
+ if (!model || model.provider !== this.providerId()) return false;
134
+ const path = join(this.agentDir, MODELS_CACHE_FILE_NAME);
135
+ let mtimeMs: number;
136
+ try {
137
+ mtimeMs = statSync(path).mtimeMs;
138
+ } catch {
139
+ this.modelsCache = undefined;
140
+ return false;
141
+ }
142
+ if (this.modelsCache?.mtimeMs !== mtimeMs) {
143
+ const ids = readJsonObject(path)?.fastModelIds;
144
+ this.modelsCache = {
145
+ mtimeMs,
146
+ ids: new Set(
147
+ Array.isArray(ids)
148
+ ? ids.filter((id): id is string => typeof id === "string")
149
+ : [],
150
+ ),
151
+ };
152
+ }
153
+ return this.modelsCache.ids.has(model.id);
154
+ }
155
+
156
+ /**
157
+ * The replacement payload for pi's `before_provider_request`, or
158
+ * `undefined` to keep it. Adds `service_tier` when Fast is on for a
159
+ * capable model of this provider, and strips a priority tier the
160
+ * provider's stale in-memory flag injected when Fast is off, so a global
161
+ * toggle takes effect on every running session's next request.
162
+ */
163
+ rewritePayload(payload: unknown, model: FastModel | undefined): unknown {
164
+ if (!model || model.provider !== this.providerId()) return undefined;
165
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
166
+ return undefined;
167
+ }
168
+ const record = payload as JsonObject;
169
+ const effective = this.sessionEnabled || this.isGlobalEnabled();
170
+ if (effective && this.supportsModel(model)) {
171
+ if (record.service_tier === PRIORITY_TIER) return undefined;
172
+ return { ...record, service_tier: PRIORITY_TIER };
173
+ }
174
+ if (!effective && record.service_tier === PRIORITY_TIER) {
175
+ const { service_tier: _dropped, ...rest } = record;
176
+ return rest;
177
+ }
178
+ return undefined;
179
+ }
180
+ }
181
+
182
+ /** User-facing toggle feedback shared by `/fast` and `/fast-global`. */
183
+ export function fastToggleNotice(options: {
184
+ scope: "session" | "global";
185
+ enabled: boolean;
186
+ otherEnabled: boolean;
187
+ modelSupported: boolean;
188
+ }): FastNotice {
189
+ const { scope, enabled, otherEnabled, modelSupported } = options;
190
+ const where =
191
+ scope === "session" ? "for this session" : "globally for all sessions";
192
+ if (!enabled) {
193
+ const residual = otherEnabled
194
+ ? scope === "session"
195
+ ? " Global Fast mode is still on."
196
+ : " This session's Fast mode is still on."
197
+ : "";
198
+ return {
199
+ message: `Fast mode disabled ${where}.${residual}`,
200
+ level: "info",
201
+ };
202
+ }
203
+ if (!modelSupported) {
204
+ return {
205
+ message: `Fast mode enabled ${where}, but the current model does not support it.`,
206
+ level: "warning",
207
+ };
208
+ }
209
+ return { message: `Fast mode enabled ${where}.`, level: "info" };
210
+ }
@@ -502,7 +502,11 @@ export function installImagePreview(
502
502
  target.render = (width: number) => {
503
503
  const lines = render.call(target, width);
504
504
  sync(target.getText?.() ?? "");
505
- margin.bottom = lines.length + rowsBelow(tui, target, width);
505
+ // rowsBelow re-renders every component below the editor, so frames
506
+ // without a visible preview skip the measurement entirely.
507
+ if (isVisible()) {
508
+ margin.bottom = lines.length + rowsBelow(tui, target, width);
509
+ }
506
510
  return lines;
507
511
  };
508
512
  target[INSTALLED] = controller;
@@ -136,9 +136,10 @@ function isPromptRow(line: string): boolean {
136
136
  * above the first prompt reports position zero, so one down click always
137
137
  * advances the reading by one.
138
138
  */
139
- function promptCount(view: Scroller): string | undefined {
140
- const lines = contentLines(view) ?? [];
141
- const top = view.viewportTop;
139
+ function promptCount(
140
+ lines: readonly string[],
141
+ top: number,
142
+ ): string | undefined {
142
143
  let current = 0;
143
144
  let total = 0;
144
145
  for (let row = 0; row < lines.length; row++) {
@@ -194,6 +195,14 @@ export function installPromptJump(
194
195
  target[INSTALLED]?.();
195
196
 
196
197
  let hit: Hit | undefined;
198
+ // The prompt scan walks every transcript line and runs once per frame
199
+ // while the viewport is scrolled up, so it is cached on the pair that
200
+ // changes when the reading can change.
201
+ // ponytail: keyed on (line count, scroll top) — an in-place rewrite that
202
+ // keeps the length can show a stale reading until either key moves.
203
+ let countCache:
204
+ | { length: number; top: number; value: string | undefined }
205
+ | undefined;
197
206
  const chipWidth = visibleWidth(UP) + visibleWidth(DOWN);
198
207
  const hadOwnMethod = Object.hasOwn(view, "compositeFlashes");
199
208
  const flashes = view.compositeFlashes;
@@ -218,7 +227,23 @@ export function installPromptJump(
218
227
  );
219
228
  // The reading only answers "where am I", so it stays out of the way while
220
229
  // the viewport is already following the newest output.
221
- const count = view.isFollowingOutput ? undefined : promptCount(view);
230
+ let count: string | undefined;
231
+ if (!view.isFollowingOutput) {
232
+ const lines = contentLines(view) ?? [];
233
+ const top = view.viewportTop;
234
+ if (
235
+ !countCache ||
236
+ countCache.length !== lines.length ||
237
+ countCache.top !== top
238
+ ) {
239
+ countCache = {
240
+ length: lines.length,
241
+ top,
242
+ value: promptCount(lines, top),
243
+ };
244
+ }
245
+ count = countCache.value;
246
+ }
222
247
  if (count) {
223
248
  const countWidth = visibleWidth(count);
224
249
  // Centred on the chips rather than the screen edge: the chips carry a
package/src/recorder.ts CHANGED
@@ -25,11 +25,16 @@ const INSTALLED = Symbol.for("pi-proper-history.recorder");
25
25
  * pi's submit path cannot cost a history entry. Returns false if the editor
26
26
  * already has a recorder, which keeps repeated `session_start` passes from
27
27
  * stacking them.
28
+ *
29
+ * `consume` runs first and may swallow a submission entirely: pi checks
30
+ * extension commands before the `input` event, so this is the only place an
31
+ * extension can take over a command name another extension registered.
28
32
  */
29
33
  export function installRecorder(
30
34
  editor: SubmittableEditor,
31
35
  record: (text: string, sourceText: string) => void,
32
36
  prepare: (text: string) => string = (text) => text,
37
+ consume?: (text: string) => boolean,
33
38
  ): boolean {
34
39
  const marked = editor as SubmittableEditor & { [INSTALLED]?: boolean };
35
40
  if (marked[INSTALLED]) return false;
@@ -37,6 +42,7 @@ export function installRecorder(
37
42
  let handler = editor.onSubmit;
38
43
  const wrap =
39
44
  (next: ((text: string) => void) | undefined) => (text: string) => {
45
+ if (consume?.(text)) return;
40
46
  const prepared = prepare(text);
41
47
  record(prepared, text);
42
48
  next?.(prepared);
@@ -0,0 +1,102 @@
1
+ import {
2
+ isKeyRelease,
3
+ parseKey,
4
+ type TUI,
5
+ type TuiInputListener,
6
+ } from "@earendil-works/pi-tui";
7
+
8
+ const INSTALLED = Symbol.for("pi-proper-base.selection-dismiss");
9
+ const PASTE_START = "\x1b[200~";
10
+
11
+ /**
12
+ * Alternate-screen renderer surface holding the mouse-selection state. Every
13
+ * field is TypeScript-private upstream, so the shape is duck-typed here and a
14
+ * rename disables the dismissal rather than breaking selection itself.
15
+ */
16
+ type SelectionHost = TUI & {
17
+ getSelectionBounds?(): unknown;
18
+ stopSelectionAutoScroll?(): void;
19
+ selectionPressActive?: boolean;
20
+ selectionDragged?: boolean;
21
+ selectionAnchor?: unknown;
22
+ selectionFocus?: unknown;
23
+ selectionGranularity?: string;
24
+ selectionInitialRange?: unknown;
25
+ [INSTALLED]?: () => void;
26
+ };
27
+
28
+ /**
29
+ * Whether terminal input is a keystroke or paste headed for the focused
30
+ * component, as opposed to a terminal report such as a cell-size response.
31
+ * Mouse, wheel, viewport-key, and focus input never reaches the listener at
32
+ * all: the renderer's own earlier listener consumes it.
33
+ */
34
+ export function isTypingInput(data: string): boolean {
35
+ if (data.length === 0) return false;
36
+ // Printable text, Enter, Backspace, control chars, non-ASCII graphemes,
37
+ // and multi-character bursts all arrive without an escape prefix.
38
+ if (!data.startsWith("\x1b")) return true;
39
+ if (data.startsWith(PASTE_START)) return true;
40
+ // Kitty release events repeat the press encoding and must not re-dismiss.
41
+ if (isKeyRelease(data)) return false;
42
+ return parseKey(data) !== undefined;
43
+ }
44
+
45
+ /**
46
+ * Dismiss the fullscreen mouse selection when typing reaches the editor.
47
+ *
48
+ * Pi's alternate-screen renderer clears its selection on focus loss and on
49
+ * the next mouse press, but never on keyboard input, so a highlight survives
50
+ * typing and keeps painting whatever new content lands on its rows. The copy
51
+ * already happened on mouse release, so dropping the highlight loses nothing.
52
+ *
53
+ * The listener registers after the renderer's own constructor-installed
54
+ * listener, so it only sees input the viewport declined: scroll keys and
55
+ * mouse gestures keep the selection, matching terminal convention. It resets
56
+ * the same private fields the renderer's focus-loss branch resets and never
57
+ * consumes the input, so the keystroke still reaches the editor.
58
+ *
59
+ * Renderers without the selection surface, including regular mode, install
60
+ * nothing. The renderer outlives an extension reload, so installation takes
61
+ * over a previous instance's listener and disposal is identity-guarded.
62
+ *
63
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Selection dismissal]]
64
+ */
65
+ export function installSelectionDismiss(tui: TUI): (() => void) | undefined {
66
+ const host = tui as SelectionHost;
67
+ if (
68
+ typeof host.getSelectionBounds !== "function" ||
69
+ typeof host.stopSelectionAutoScroll !== "function"
70
+ ) {
71
+ return undefined;
72
+ }
73
+ // A reload runs the new instance's editor factory before the outgoing
74
+ // instance shuts down, so take over any listener it left on the renderer.
75
+ host[INSTALLED]?.();
76
+
77
+ const listener: TuiInputListener = (data) => {
78
+ // A drag in progress owns the selection it is building.
79
+ if (host.selectionPressActive) return undefined;
80
+ if (host.getSelectionBounds?.() === undefined) return undefined;
81
+ if (!isTypingInput(data)) return undefined;
82
+ host.stopSelectionAutoScroll?.();
83
+ host.selectionAnchor = undefined;
84
+ host.selectionFocus = undefined;
85
+ host.selectionGranularity = "character";
86
+ host.selectionInitialRange = undefined;
87
+ host.selectionDragged = false;
88
+ host.requestRender();
89
+ return undefined;
90
+ };
91
+ const unsubscribe = tui.addInputListener(listener);
92
+
93
+ // A disposer left over from a previous extension instance must not remove
94
+ // the listener that replaced it.
95
+ const dispose = () => {
96
+ if (host[INSTALLED] !== dispose) return;
97
+ unsubscribe();
98
+ delete host[INSTALLED];
99
+ };
100
+ host[INSTALLED] = dispose;
101
+ return dispose;
102
+ }
@@ -0,0 +1,497 @@
1
+ /**
2
+ * Fast session metadata for the `/resume` picker.
3
+ *
4
+ * Pi's `SessionManager.list` builds each `SessionInfo` by streaming every line
5
+ * of every session file, `JSON.parse`-ing it, and concatenating every message's
6
+ * text into `allMessagesText`. Only the picker's search reads that field, so a
7
+ * project with hundreds of megabytes of transcripts waits seconds before the
8
+ * first row is drawn.
9
+ *
10
+ * These readers replace that with two cheap passes. Session entries are one
11
+ * JSON object per line, so a byte-prefix test classifies a line without
12
+ * decoding it: the head is read until the first user message, then the file is
13
+ * scanned as raw bytes to count messages and locate the newest rename.
14
+ * `allMessagesText` starts empty and is refilled by a detached backfill, so
15
+ * search recovers on its own instead of blocking the picker.
16
+ */
17
+
18
+ import { createReadStream } from "node:fs";
19
+ import { open, readdir, stat } from "node:fs/promises";
20
+ import { join, resolve } from "node:path";
21
+ import { createInterface } from "node:readline";
22
+
23
+ import { projectKey } from "./store.ts";
24
+
25
+ /** Structurally compatible with pi's `SessionInfo`. */
26
+ export type SessionInfo = {
27
+ path: string;
28
+ id: string;
29
+ cwd: string;
30
+ name?: string | undefined;
31
+ parentSessionPath?: string | undefined;
32
+ created: Date;
33
+ modified: Date;
34
+ messageCount: number;
35
+ firstMessage: string;
36
+ allMessagesText: string;
37
+ };
38
+
39
+ export type ProgressCallback = (loaded: number, total: number) => void;
40
+
41
+ const SESSION_PREFIX = '{"type":"session"';
42
+ const MESSAGE_PREFIX = '{"type":"message"';
43
+ const NAME_PREFIX = '{"type":"session_info"';
44
+ const MESSAGE_BYTES = Buffer.from(`\n${MESSAGE_PREFIX}`);
45
+ const NAME_BYTES = Buffer.from(`\n${NAME_PREFIX}`);
46
+ const CHUNK_BYTES = 1 << 20;
47
+
48
+ /**
49
+ * Bytes of an entry inspected for its role and write time.
50
+ *
51
+ * Both sit before the message body: `{"type":"message","id":…,"parentId":…,
52
+ * "timestamp":…,"message":{"role":…`.
53
+ */
54
+ const ENTRY_HEAD_BYTES = 256;
55
+
56
+ /** Matches pi's own concurrency, so disk access patterns do not change. */
57
+ const MAX_CONCURRENT_READS = 10;
58
+
59
+ /**
60
+ * Bytes read while looking for the first user message.
61
+ *
62
+ * The first thing a user typed precedes every response it caused, so this only
63
+ * bounds files that never received one.
64
+ */
65
+ const MAX_HEAD_BYTES = 4 << 20;
66
+
67
+ /** Upper bound for re-reading one rename entry, which holds a short name. */
68
+ const NAME_ENTRY_BYTES = 8192;
69
+
70
+ type JsonRecord = Record<string, unknown>;
71
+
72
+ function parseLine(line: string): JsonRecord | undefined {
73
+ try {
74
+ const parsed: unknown = JSON.parse(line);
75
+ return parsed && typeof parsed === "object"
76
+ ? (parsed as JsonRecord)
77
+ : undefined;
78
+ } catch {
79
+ return undefined;
80
+ }
81
+ }
82
+
83
+ function messageOf(entry: JsonRecord): JsonRecord | undefined {
84
+ const message = entry.message;
85
+ return message && typeof message === "object"
86
+ ? (message as JsonRecord)
87
+ : undefined;
88
+ }
89
+
90
+ /** Pi joins text blocks with a space and passes string content through. */
91
+ export function extractText(message: JsonRecord): string {
92
+ const content = message.content;
93
+ if (typeof content === "string") return content;
94
+ if (!Array.isArray(content)) return "";
95
+ const texts: string[] = [];
96
+ for (const block of content) {
97
+ if (!block || typeof block !== "object") continue;
98
+ const part = block as JsonRecord;
99
+ if (part.type === "text" && typeof part.text === "string")
100
+ texts.push(part.text);
101
+ }
102
+ return texts.join(" ");
103
+ }
104
+
105
+ type Head = { header: JsonRecord; firstMessage: string };
106
+
107
+ /**
108
+ * Read the session header and the first user message.
109
+ *
110
+ * Stops as soon as both are known, so the cost is the head of the file rather
111
+ * than its length.
112
+ */
113
+ async function readHead(filePath: string): Promise<Head | undefined> {
114
+ // Closing the interface leaves its input open, and this returns early for
115
+ // almost every file, so the stream itself has to be destroyed.
116
+ const input = createReadStream(filePath, { encoding: "utf8" });
117
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
118
+ try {
119
+ let header: JsonRecord | undefined;
120
+ let read = 0;
121
+ for await (const line of lines) {
122
+ if (!line) continue;
123
+ if (!header) {
124
+ // A first line that is not a session header means this is not a
125
+ // session file, and pi drops those from the list.
126
+ if (!line.startsWith(SESSION_PREFIX)) return undefined;
127
+ header = parseLine(line);
128
+ if (!header) return undefined;
129
+ continue;
130
+ }
131
+ read += line.length;
132
+ if (read > MAX_HEAD_BYTES) break;
133
+ if (!line.startsWith(MESSAGE_PREFIX)) continue;
134
+ const message = messageOf(parseLine(line) ?? {});
135
+ if (message?.role !== "user") continue;
136
+ const text = extractText(message);
137
+ if (text) return { header, firstMessage: text };
138
+ }
139
+ return header ? { header, firstMessage: "" } : undefined;
140
+ } finally {
141
+ lines.close();
142
+ input.destroy();
143
+ }
144
+ }
145
+
146
+ type Scan = {
147
+ messageCount: number;
148
+ lastNameOffset: number;
149
+ lastActivity: number | undefined;
150
+ };
151
+
152
+ /**
153
+ * Read one entry's write time, if it is a message pi counts as activity.
154
+ *
155
+ * `head` is the start of an entry; the body beyond it is not needed. Pi prefers
156
+ * the message's own start time, which sits after the content and would cost a
157
+ * full-line read, so this uses the entry's write time instead — later by the
158
+ * duration of the response, which is seconds.
159
+ */
160
+ function entryActivityTime(head: string): number | undefined {
161
+ const roleAt = head.indexOf('"role":"');
162
+ if (roleAt < 0) return undefined;
163
+ const role = head.slice(roleAt + 8, head.indexOf('"', roleAt + 8));
164
+ if (role !== "user" && role !== "assistant") return undefined;
165
+ const timeAt = head.indexOf('"timestamp":"');
166
+ if (timeAt < 0 || timeAt > roleAt) return undefined;
167
+ const parsed = new Date(
168
+ head.slice(timeAt + 13, head.indexOf('"', timeAt + 13)),
169
+ ).getTime();
170
+ return Number.isNaN(parsed) ? undefined : parsed;
171
+ }
172
+
173
+ /**
174
+ * Count message entries, locate the newest rename, and track last activity.
175
+ *
176
+ * Nothing is decoded and no line is assembled: single entries reach tens of
177
+ * megabytes, so buffering one would cost more than the scan it serves. Every
178
+ * needle includes the preceding newline, which anchors it to a line start and
179
+ * keeps it from matching text inside a JSON string.
180
+ */
181
+ async function scanFile(filePath: string): Promise<Scan> {
182
+ let messageCount = 0;
183
+ let lastNameOffset = -1;
184
+ let lastActivity: number | undefined;
185
+ let offset = 0;
186
+ let carry = Buffer.alloc(0);
187
+
188
+ // Consecutive buffers overlap by one entry head, so an entry whose head is
189
+ // cut short here is left for the next buffer, where it is whole. Because
190
+ // `limit` stops one byte before the overlap begins, no entry is taken twice.
191
+ const take = (buffer: Buffer, base: number, limit: number): void => {
192
+ for (let at = 0; at <= limit; ) {
193
+ const found = buffer.indexOf(MESSAGE_BYTES, at);
194
+ if (found < 0 || found > limit) break;
195
+ at = found + MESSAGE_BYTES.length;
196
+ messageCount++;
197
+ const time = entryActivityTime(
198
+ buffer.toString("utf8", found, found + ENTRY_HEAD_BYTES),
199
+ );
200
+ if (time !== undefined && time > (lastActivity ?? 0)) lastActivity = time;
201
+ }
202
+ // Renames are re-read from the file by offset, so a short head is fine.
203
+ for (let at = 0; ; ) {
204
+ const found = buffer.indexOf(NAME_BYTES, at);
205
+ if (found < 0) break;
206
+ lastNameOffset = base + found + 1;
207
+ at = found + NAME_BYTES.length;
208
+ }
209
+ };
210
+
211
+ for await (const chunk of createReadStream(filePath, {
212
+ highWaterMark: CHUNK_BYTES,
213
+ }) as AsyncIterable<Buffer>) {
214
+ const buffer = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
215
+ const base = offset - carry.length;
216
+ take(buffer, base, buffer.length - ENTRY_HEAD_BYTES - 1);
217
+ offset += chunk.length;
218
+ // Only the overlap carries, so a single huge entry never accumulates.
219
+ carry = Buffer.from(
220
+ buffer.subarray(Math.max(0, buffer.length - ENTRY_HEAD_BYTES)),
221
+ );
222
+ }
223
+ // At end of file a short head is all there is.
224
+ take(carry, offset - carry.length, carry.length);
225
+ return { messageCount, lastNameOffset, lastActivity };
226
+ }
227
+
228
+ /** Re-read one rename entry. Renames are rare, so this costs one small read. */
229
+ async function readName(
230
+ filePath: string,
231
+ offset: number,
232
+ ): Promise<string | undefined> {
233
+ const handle = await open(filePath, "r");
234
+ try {
235
+ const buffer = Buffer.alloc(NAME_ENTRY_BYTES);
236
+ const { bytesRead } = await handle.read(
237
+ buffer,
238
+ 0,
239
+ NAME_ENTRY_BYTES,
240
+ offset,
241
+ );
242
+ const text = buffer.subarray(0, bytesRead).toString("utf8");
243
+ const end = text.indexOf("\n");
244
+ const entry = parseLine(end < 0 ? text : text.slice(0, end));
245
+ if (typeof entry?.name !== "string") return undefined;
246
+ return entry.name.trim() || undefined;
247
+ } finally {
248
+ await handle.close();
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Read one session file's picker metadata.
254
+ *
255
+ * Returns `null` for anything without a session header, matching how pi drops
256
+ * those files from the list.
257
+ */
258
+ export async function readSessionInfo(
259
+ filePath: string,
260
+ ): Promise<SessionInfo | null> {
261
+ try {
262
+ const [stats, head] = await Promise.all([
263
+ stat(filePath),
264
+ readHead(filePath),
265
+ ]);
266
+ if (!head) return null;
267
+ const { header } = head;
268
+ const scan = await scanFile(filePath);
269
+ const name =
270
+ scan.lastNameOffset >= 0
271
+ ? await readName(filePath, scan.lastNameOffset)
272
+ : undefined;
273
+
274
+ const created =
275
+ typeof header.timestamp === "string"
276
+ ? new Date(header.timestamp)
277
+ : stats.mtime;
278
+ // The file's own mtime is not a substitute: branching from a session
279
+ // appends to it hours after its last message.
280
+ const modified =
281
+ scan.lastActivity !== undefined && scan.lastActivity > 0
282
+ ? new Date(scan.lastActivity)
283
+ : Number.isNaN(created.getTime())
284
+ ? stats.mtime
285
+ : created;
286
+
287
+ return {
288
+ path: filePath,
289
+ id: typeof header.id === "string" ? header.id : "",
290
+ cwd: typeof header.cwd === "string" ? header.cwd : "",
291
+ name,
292
+ parentSessionPath:
293
+ typeof header.parentSession === "string"
294
+ ? header.parentSession
295
+ : undefined,
296
+ created,
297
+ modified,
298
+ messageCount: scan.messageCount,
299
+ firstMessage: head.firstMessage || "(no messages)",
300
+ allMessagesText: "",
301
+ };
302
+ } catch {
303
+ return null;
304
+ }
305
+ }
306
+
307
+ /** Concatenated message text, matching what pi's picker search expects. */
308
+ export async function readSearchText(filePath: string): Promise<string> {
309
+ const parts: string[] = [];
310
+ const input = createReadStream(filePath, { encoding: "utf8" });
311
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
312
+ try {
313
+ for await (const line of lines) {
314
+ if (!line.startsWith(MESSAGE_PREFIX)) continue;
315
+ const message = messageOf(parseLine(line) ?? {});
316
+ if (!message) continue;
317
+ if (message.role !== "user" && message.role !== "assistant") continue;
318
+ const text = extractText(message);
319
+ if (text) parts.push(text);
320
+ }
321
+ } catch {
322
+ // A partial read still beats the empty placeholder for search.
323
+ } finally {
324
+ lines.close();
325
+ input.destroy();
326
+ }
327
+ return parts.join(" ");
328
+ }
329
+
330
+ /** Run `task` over `items` with pi's bounded concurrency. */
331
+ async function mapConcurrent<T>(
332
+ items: string[],
333
+ task: (item: string) => Promise<T>,
334
+ onDone?: () => void,
335
+ ): Promise<T[]> {
336
+ const results = new Array<T>(items.length);
337
+ let next = 0;
338
+ const worker = async (): Promise<void> => {
339
+ for (;;) {
340
+ const index = next++;
341
+ const item = items[index];
342
+ if (item === undefined) return;
343
+ results[index] = await task(item);
344
+ onDone?.();
345
+ }
346
+ };
347
+ await Promise.all(
348
+ Array.from(
349
+ { length: Math.min(MAX_CONCURRENT_READS, items.length) },
350
+ worker,
351
+ ),
352
+ );
353
+ return results;
354
+ }
355
+
356
+ async function sessionFiles(dir: string): Promise<string[]> {
357
+ try {
358
+ return (await readdir(dir))
359
+ .filter((file) => file.endsWith(".jsonl"))
360
+ .map((file) => join(dir, file));
361
+ } catch {
362
+ return [];
363
+ }
364
+ }
365
+
366
+ function byNewest(a: SessionInfo, b: SessionInfo): number {
367
+ return b.modified.getTime() - a.modified.getTime();
368
+ }
369
+
370
+ async function collect(
371
+ files: string[],
372
+ onProgress?: ProgressCallback,
373
+ ): Promise<SessionInfo[]> {
374
+ let loaded = 0;
375
+ const results = await mapConcurrent(files, readSessionInfo, () => {
376
+ loaded++;
377
+ onProgress?.(loaded, files.length);
378
+ });
379
+ return results.filter((info): info is SessionInfo => info !== null);
380
+ }
381
+
382
+ /** Pi's session directory for a working directory. Pi resolves the cwd first. */
383
+ export function projectSessionDir(agentDir: string, cwd: string): string {
384
+ return join(resolve(agentDir), "sessions", projectKey(resolve(cwd)));
385
+ }
386
+
387
+ /** Drop-in replacements for `SessionManager.list` and `SessionManager.listAll`. */
388
+ export function createSessionListers(agentDir: string) {
389
+ const list = async (
390
+ cwd: string,
391
+ sessionDir?: string,
392
+ onProgress?: ProgressCallback,
393
+ ): Promise<SessionInfo[]> => {
394
+ const defaultDir = projectSessionDir(agentDir, cwd);
395
+ const dir = sessionDir ? resolve(sessionDir) : defaultDir;
396
+ // A custom session directory can hold sessions from other projects.
397
+ const filterCwd = sessionDir !== undefined && dir !== defaultDir;
398
+ const resolvedCwd = resolve(cwd);
399
+ const sessions = await collect(await sessionFiles(dir), onProgress);
400
+ return sessions
401
+ .filter(
402
+ (session) =>
403
+ !filterCwd || (!!session.cwd && resolve(session.cwd) === resolvedCwd),
404
+ )
405
+ .sort(byNewest);
406
+ };
407
+
408
+ const listAll = async (
409
+ sessionDirOrProgress?: string | ProgressCallback,
410
+ maybeProgress?: ProgressCallback,
411
+ ): Promise<SessionInfo[]> => {
412
+ const customDir =
413
+ typeof sessionDirOrProgress === "string"
414
+ ? sessionDirOrProgress
415
+ : undefined;
416
+ const onProgress =
417
+ typeof sessionDirOrProgress === "function"
418
+ ? sessionDirOrProgress
419
+ : maybeProgress;
420
+ if (customDir) {
421
+ const sessions = await collect(
422
+ await sessionFiles(resolve(customDir)),
423
+ onProgress,
424
+ );
425
+ return sessions.sort(byNewest);
426
+ }
427
+ const root = join(resolve(agentDir), "sessions");
428
+ let projects: string[];
429
+ try {
430
+ projects = (await readdir(root, { withFileTypes: true }))
431
+ .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
432
+ .map((entry) => join(root, entry.name));
433
+ } catch {
434
+ return [];
435
+ }
436
+ const files = (await Promise.all(projects.map(sessionFiles))).flat();
437
+ const sessions = await collect(files, onProgress);
438
+ return sessions.sort(byNewest);
439
+ };
440
+
441
+ return { list, listAll };
442
+ }
443
+
444
+ /**
445
+ * Refill `allMessagesText` on sessions the picker already holds.
446
+ *
447
+ * The picker reads that field on every keystroke, so mutating the objects it
448
+ * was handed restores full-text search without the loader ever waiting for it.
449
+ * Sessions arrive newest-first, which is the order the picker shows them in.
450
+ */
451
+ export function backfillSearchText(sessions: SessionInfo[]): () => void {
452
+ let cancelled = false;
453
+ void (async () => {
454
+ for (const session of sessions) {
455
+ if (cancelled) return;
456
+ session.allMessagesText = await readSearchText(session.path);
457
+ }
458
+ })();
459
+ return () => {
460
+ cancelled = true;
461
+ };
462
+ }
463
+
464
+ type Listers = { list: unknown; listAll: unknown };
465
+
466
+ const FAST_SESSION_LIST = Symbol.for("pi-proper-base.fast-session-list");
467
+
468
+ /**
469
+ * Point pi's session listing at the fast readers.
470
+ *
471
+ * Pi's `SessionManager` is a module singleton reached through static property
472
+ * lookups, so replacing the two listing methods covers `/resume` without
473
+ * touching the picker. Installation is idempotent: the class outlives every
474
+ * session, so a reload must not stack wrappers.
475
+ */
476
+ export function installFastSessionList(target: object, agentDir: string): void {
477
+ const tagged = target as Listers & { [FAST_SESSION_LIST]?: true };
478
+ if (tagged[FAST_SESSION_LIST]) return;
479
+ const fast = createSessionListers(agentDir);
480
+ let cancelBackfill: (() => void) | undefined;
481
+ const served = (sessions: SessionInfo[]): SessionInfo[] => {
482
+ // Only the newest listing is worth completing; a rescan replaces it.
483
+ cancelBackfill?.();
484
+ cancelBackfill = backfillSearchText(sessions);
485
+ return sessions;
486
+ };
487
+ tagged.list = (
488
+ cwd: string,
489
+ sessionDir?: string,
490
+ onProgress?: ProgressCallback,
491
+ ) => fast.list(cwd, sessionDir, onProgress).then(served);
492
+ tagged.listAll = (
493
+ sessionDirOrProgress?: string | ProgressCallback,
494
+ onProgress?: ProgressCallback,
495
+ ) => fast.listAll(sessionDirOrProgress, onProgress).then(served);
496
+ tagged[FAST_SESSION_LIST] = true;
497
+ }
@@ -267,7 +267,7 @@ function renderCollapsed(
267
267
  ) {
268
268
  group.push(child);
269
269
  } else {
270
- lines.push(...child.render(width));
270
+ lines.push(...renderExpandable(child, width, state));
271
271
  }
272
272
  }
273
273
  flush();
@@ -364,10 +364,36 @@ function renderGroup(
364
364
  continue;
365
365
  }
366
366
  if (!state.owned.has(child)) {
367
- lines.push(...child.render(width));
367
+ lines.push(...renderExpandable(child, width, state));
368
368
  continue;
369
369
  }
370
- lines.push(...withVerticalSpacing(child.render(width)));
370
+ lines.push(...withVerticalSpacing(renderExpandable(child, width, state)));
371
+ }
372
+ return lines;
373
+ }
374
+
375
+ /**
376
+ * Extension entry renderers draw their own disclosure marker from Pi's global
377
+ * tool-expansion state, so without a hit row the marker is decoration that only
378
+ * `app.tools.expand` moves. Drive the same per-item state the tool summaries use
379
+ * and register the header row, so one entry opens on click.
380
+ */
381
+ function renderExpandable(
382
+ child: Component,
383
+ width: number,
384
+ state: State,
385
+ ): string[] {
386
+ const expandable = child as ToolComponent;
387
+ if (typeof expandable.setExpanded !== "function") return child.render(width);
388
+ expandable.setExpanded(state.expanded.get(child) ?? state.globalExpanded);
389
+ const lines = child.render(width);
390
+ const header = lines.find((line) => stripTerminalSequences(line).trim());
391
+ if (header) {
392
+ state.pendingHits.push({
393
+ owner: child,
394
+ line: header,
395
+ end: visibleWidth(stripTerminalSequences(header).trimEnd()),
396
+ });
371
397
  }
372
398
  return lines;
373
399
  }