@luxass/pi-session-search 0.0.0-stage → 0.1.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,544 @@
1
+ /**
2
+ * What Enter does in the picker: switch session and branch when needed, with
3
+ * confirmation, through pi's public command APIs, then bring the message into
4
+ * view when pi allows it.
5
+ */
6
+
7
+ import type {
8
+ ExtensionCommandContext,
9
+ ExtensionContext,
10
+ ExtensionUIContext,
11
+ } from "@earendil-works/pi-coding-agent";
12
+ import type { TUI } from "@earendil-works/pi-tui";
13
+
14
+ import { cleanForDisplay, kindLabel } from "./display-text.ts";
15
+ import type { SearchHit } from "./hits.ts";
16
+ import { bestMatchIndex, parseQuery, termPatterns } from "./query.ts";
17
+ import { extractSearchableItems } from "./searchable-text.ts";
18
+ import {
19
+ countOccurrences,
20
+ expandHiddenToolOutput,
21
+ normalizeForComparison,
22
+ type RevealTarget,
23
+ revealInTranscript,
24
+ type TranscriptIdentity,
25
+ type TranscriptNeedle,
26
+ } from "./transcript-scroll.ts";
27
+
28
+ /** Longest text used to find a message in the rendered transcript. */
29
+ const NEEDLE_CHARS = 48;
30
+
31
+ interface EntryLink {
32
+ id: string;
33
+ parentId: string | null;
34
+ }
35
+
36
+ function asEntryLink(entry: unknown): EntryLink | undefined {
37
+ if (typeof entry !== "object" || entry === null) {
38
+ return undefined;
39
+ }
40
+ const record = entry as Record<string, unknown>;
41
+ if (typeof record.id !== "string") {
42
+ return undefined;
43
+ }
44
+ return { id: record.id, parentId: typeof record.parentId === "string" ? record.parentId : null };
45
+ }
46
+
47
+ /**
48
+ * The leaf of the most recently active branch below an entry. At each step it
49
+ * follows the child whose subtree holds the latest-written entry. Navigating
50
+ * there opens the branch that holds the entry, as it was last used.
51
+ */
52
+ export function branchTipOf(entries: readonly unknown[], entryId: string): string {
53
+ const links: EntryLink[] = [];
54
+ for (const entry of entries) {
55
+ const link = asEntryLink(entry);
56
+ if (link !== undefined) {
57
+ links.push(link);
58
+ }
59
+ }
60
+ // Entries are append-only, so a child is always written after its parent.
61
+ // Walking backwards gives every subtree its latest write position.
62
+ const latestInSubtree = new Map<string, number>();
63
+ for (let position = links.length - 1; position >= 0; position -= 1) {
64
+ const link = links[position] as EntryLink;
65
+ const latest = Math.max(latestInSubtree.get(link.id) ?? position, position);
66
+ latestInSubtree.set(link.id, latest);
67
+ if (link.parentId !== null) {
68
+ latestInSubtree.set(
69
+ link.parentId,
70
+ Math.max(latestInSubtree.get(link.parentId) ?? -1, latest),
71
+ );
72
+ }
73
+ }
74
+ const children = new Map<string, string[]>();
75
+ for (const link of links) {
76
+ if (link.parentId !== null) {
77
+ const siblings = children.get(link.parentId) ?? [];
78
+ siblings.push(link.id);
79
+ children.set(link.parentId, siblings);
80
+ }
81
+ }
82
+
83
+ let tip = entryId;
84
+ const seen = new Set<string>([tip]);
85
+ for (;;) {
86
+ let next: string | undefined;
87
+ let nextLatest = -1;
88
+ for (const child of children.get(tip) ?? []) {
89
+ const latest = latestInSubtree.get(child) ?? -1;
90
+ if (latest > nextLatest) {
91
+ next = child;
92
+ nextLatest = latest;
93
+ }
94
+ }
95
+ if (next === undefined || seen.has(next)) {
96
+ return tip;
97
+ }
98
+ seen.add(next);
99
+ tip = next;
100
+ }
101
+ }
102
+
103
+ /** First line of text, cut to a length that rarely wraps in the transcript. */
104
+ function leadingText(text: string): string {
105
+ const firstLine = text.split("\n").find((line) => line.trim() !== "") ?? "";
106
+ return cutAtWord(firstLine.trim(), NEEDLE_CHARS);
107
+ }
108
+
109
+ function cutAtWord(text: string, limit: number): string {
110
+ if (text.length <= limit) {
111
+ return text;
112
+ }
113
+ const space = text.lastIndexOf(" ", limit);
114
+ return text.slice(0, space > limit / 2 ? space : limit);
115
+ }
116
+
117
+ /** A needle and where it starts in the message text it was cut from. */
118
+ interface AnchoredNeedle {
119
+ text: string;
120
+ /** Index in the cleaned message text where this needle's own occurrence starts. */
121
+ anchor: number;
122
+ /** See TranscriptNeedle.pinpoints. */
123
+ pinpoints: boolean;
124
+ }
125
+
126
+ /**
127
+ * Needles cut from `cleaned`, best first: the words at the match, the primary
128
+ * argument of a tool call, then the start of the message. Each keeps its
129
+ * position so occurrences before it can be counted.
130
+ */
131
+ function anchoredNeedles(
132
+ cleaned: string,
133
+ hit: Pick<SearchHit, "kind" | "fuzzy">,
134
+ includeStart: boolean,
135
+ queryText: string,
136
+ ): AnchoredNeedle[] {
137
+ const needles: AnchoredNeedle[] = [];
138
+ const patterns = termPatterns(parseQuery(queryText));
139
+ if (patterns.length > 0 && !hit.fuzzy) {
140
+ const at = bestMatchIndex(cleaned, patterns);
141
+ const lineEnd = cleaned.indexOf("\n", at);
142
+ const rest = cleaned.slice(at, lineEnd < 0 ? undefined : lineEnd);
143
+ needles.push({ text: cutAtWord(rest.trim(), NEEDLE_CHARS), anchor: at, pinpoints: true });
144
+ }
145
+ if (hit.kind === "toolCall") {
146
+ // Tool calls render their primary argument, not the tool name we prefix.
147
+ const firstLine = cleaned.split("\n")[0] ?? "";
148
+ const space = firstLine.indexOf(" ");
149
+ if (space > 0) {
150
+ needles.push({
151
+ text: cutAtWord(firstLine.slice(space + 1).trim(), NEEDLE_CHARS),
152
+ anchor: space + 1,
153
+ pinpoints: true,
154
+ });
155
+ }
156
+ }
157
+ if (includeStart) {
158
+ needles.push({ text: leadingText(cleaned), anchor: 0, pinpoints: false });
159
+ }
160
+ const seen = new Set<string>();
161
+ return needles.filter((needle) => {
162
+ if (normalizeForComparison(needle.text).length < 3 || seen.has(needle.text)) {
163
+ return false;
164
+ }
165
+ seen.add(needle.text);
166
+ return true;
167
+ });
168
+ }
169
+
170
+ /**
171
+ * Texts that identify the message in the rendered transcript, best first:
172
+ * the words at the match, then the start of the message.
173
+ */
174
+ export function transcriptNeedles(hit: SearchHit, queryText: string): string[] {
175
+ return anchoredNeedles(cleanForDisplay(hit.text), hit, !hit.clippedStart, queryText).map(
176
+ (needle) => needle.text,
177
+ );
178
+ }
179
+
180
+ function isRecord(value: unknown): value is Record<string, unknown> {
181
+ return typeof value === "object" && value !== null;
182
+ }
183
+
184
+ /**
185
+ * How pi's transcript identifies the component that renders a hit: message
186
+ * components carry the entry id, tool components carry the tool call id.
187
+ * Shell commands have no identity in the transcript.
188
+ */
189
+ export function transcriptIdentity(
190
+ entry: unknown,
191
+ hit: Pick<SearchHit, "entryId" | "kind" | "part">,
192
+ ): TranscriptIdentity | undefined {
193
+ if (!isRecord(entry) || !isRecord(entry.message)) {
194
+ return undefined;
195
+ }
196
+ const message = entry.message;
197
+ switch (hit.kind) {
198
+ case "user":
199
+ case "assistant":
200
+ return { messageId: hit.entryId };
201
+ case "toolResult":
202
+ return typeof message.toolCallId === "string"
203
+ ? { toolCallId: message.toolCallId }
204
+ : undefined;
205
+ case "toolCall": {
206
+ // The hit's part counts the text part too; tool call items keep the order of the call blocks.
207
+ const callIndex = extractSearchableItems(entry).filter(
208
+ (item) => item.kind === "toolCall" && item.part < hit.part,
209
+ ).length;
210
+ const calls = Array.isArray(message.content)
211
+ ? message.content.filter(
212
+ (block): block is Record<string, unknown> =>
213
+ isRecord(block) && block.type === "toolCall" && typeof block.name === "string",
214
+ )
215
+ : [];
216
+ const id = calls[callIndex]?.id;
217
+ return typeof id === "string" ? { toolCallId: id } : undefined;
218
+ }
219
+ case "shell":
220
+ return undefined;
221
+ default:
222
+ return hit.kind satisfies never;
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Builds the reveal target for a hit, given the entries pi renders on the
228
+ * open branch. Every needle gets its own occurrence count: the times it
229
+ * appears in earlier messages and earlier parts of the same message, plus the
230
+ * times it appears in the hit's own text before the matched spot.
231
+ * Returns undefined when the entry is not rendered, for example when a
232
+ * compaction summary replaced it.
233
+ */
234
+ export function buildRevealTarget(
235
+ contextEntries: readonly unknown[],
236
+ hit: SearchHit,
237
+ queryText: string,
238
+ ): RevealTarget | undefined {
239
+ const position = contextEntries.findIndex((entry) => isRecord(entry) && entry.id === hit.entryId);
240
+ if (position < 0) {
241
+ return undefined;
242
+ }
243
+ const entry = contextEntries[position];
244
+ const entryItems = extractSearchableItems(entry);
245
+ const item = entryItems.find((candidate) => candidate.part === hit.part);
246
+ // The full item text, so occurrences before a clipped preview window are counted too.
247
+ const fullText = cleanForDisplay(item?.text ?? hit.text);
248
+ const includeStart = item !== undefined || !hit.clippedStart;
249
+ const anchored = anchoredNeedles(fullText, hit, includeStart, queryText);
250
+
251
+ const earlierTexts: string[] = [];
252
+ for (const earlier of contextEntries.slice(0, position)) {
253
+ for (const earlierItem of extractSearchableItems(earlier)) {
254
+ earlierTexts.push(normalizeForComparison(earlierItem.text));
255
+ }
256
+ }
257
+ for (const sibling of entryItems) {
258
+ if (sibling.part < hit.part) {
259
+ earlierTexts.push(normalizeForComparison(sibling.text));
260
+ }
261
+ }
262
+
263
+ const needles: TranscriptNeedle[] = anchored.map((needle) => {
264
+ const normalized = normalizeForComparison(needle.text);
265
+ const occurrenceInMessage = countOccurrences(
266
+ normalizeForComparison(fullText.slice(0, needle.anchor)),
267
+ normalized,
268
+ );
269
+ let before = 0;
270
+ for (const text of earlierTexts) {
271
+ before += countOccurrences(text, normalized);
272
+ }
273
+ return {
274
+ text: needle.text,
275
+ occurrence: before + occurrenceInMessage,
276
+ occurrenceInMessage,
277
+ pinpoints: needle.pinpoints,
278
+ };
279
+ });
280
+ const identity = transcriptIdentity(entry, hit);
281
+ return identity === undefined ? { needles } : { identity, needles };
282
+ }
283
+
284
+ function revealTarget(
285
+ sessionManager: ExtensionContext["sessionManager"],
286
+ hit: SearchHit,
287
+ queryText: string,
288
+ ): RevealTarget | undefined {
289
+ return buildRevealTarget(sessionManager.buildContextEntries(), hit, queryText);
290
+ }
291
+
292
+ /** Context methods used after a session switch; the replacement context provides them too. */
293
+ type OpeningContext = Pick<
294
+ ExtensionCommandContext,
295
+ "ui" | "sessionManager" | "navigateTree" | "isIdle"
296
+ >;
297
+
298
+ /**
299
+ * The UI methods a reveal uses. Tool expansion is optional because older pi
300
+ * versions may not have it.
301
+ */
302
+ export type RevealUi = Pick<ExtensionUIContext, "notify"> &
303
+ Partial<Pick<ExtensionUIContext, "getToolsExpanded" | "setToolsExpanded" | "setStatus">>;
304
+
305
+ /** Footer status key for notices about a reveal. */
306
+ const REVEAL_STATUS_KEY = "session-search";
307
+ /** How long a reveal notice stays in the footer. */
308
+ export const REVEAL_STATUS_MS = 10_000;
309
+ /** Identifies the latest footer notice, so an older timer does not clear a newer one. */
310
+ let revealStatusToken = 0;
311
+
312
+ /**
313
+ * Reports a notice after the transcript was scrolled away from its end. Pi
314
+ * appends notices to the end of the transcript, out of view after a scroll,
315
+ * so the notice also shows in the footer for a while. Never throws.
316
+ */
317
+ function notifyAfterScroll(ui: RevealUi, message: string): void {
318
+ try {
319
+ ui.notify(message, "info");
320
+ } catch {
321
+ // Nowhere else to report.
322
+ }
323
+ if (ui.setStatus === undefined) {
324
+ return;
325
+ }
326
+ revealStatusToken += 1;
327
+ const token = revealStatusToken;
328
+ try {
329
+ ui.setStatus(REVEAL_STATUS_KEY, message);
330
+ } catch {
331
+ return;
332
+ }
333
+ setTimeout(() => {
334
+ if (token !== revealStatusToken) {
335
+ return;
336
+ }
337
+ try {
338
+ ui.setStatus?.(REVEAL_STATUS_KEY, undefined);
339
+ } catch {
340
+ // The context is gone after a session switch, and its footer with it.
341
+ }
342
+ }, REVEAL_STATUS_MS).unref?.();
343
+ }
344
+
345
+ /**
346
+ * Pi's default key for `app.tools.expand`, from its keybindings docs. Users
347
+ * can rebind it, so notices name the action too.
348
+ */
349
+ const TOOLS_EXPAND_HINT = "app.tools.expand (ctrl+o by default)";
350
+
351
+ /** Expands all tool output through pi's public API. Returns false when that cannot help. */
352
+ function expandAllToolOutput(ui: RevealUi): boolean {
353
+ if (ui.setToolsExpanded === undefined) {
354
+ return false;
355
+ }
356
+ try {
357
+ if (ui.getToolsExpanded?.() === true) {
358
+ return false;
359
+ }
360
+ ui.setToolsExpanded(true);
361
+ return true;
362
+ } catch {
363
+ return false;
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Scrolls to a target and reports what happened. When the match is hidden in
369
+ * collapsed tool output, expands that tool's output, or else all tool output,
370
+ * and scrolls to the matched line.
371
+ */
372
+ export async function revealTargetAndReport(
373
+ ui: RevealUi,
374
+ tui: TUI | undefined,
375
+ target: RevealTarget,
376
+ afterSwitch: boolean,
377
+ ): Promise<void> {
378
+ let outcome = await revealInTranscript(tui, target, afterSwitch);
379
+ let expandedNotice: string | undefined;
380
+ if (outcome === "collapsed") {
381
+ if (expandHiddenToolOutput(tui, target)) {
382
+ expandedNotice = `Expanded that tool output to show the match. ${TOOLS_EXPAND_HINT} toggles all tool output.`;
383
+ } else if (expandAllToolOutput(ui)) {
384
+ expandedNotice = `Expanded tool output to show the match. Use ${TOOLS_EXPAND_HINT} to collapse it.`;
385
+ }
386
+ if (expandedNotice !== undefined) {
387
+ outcome = await revealInTranscript(tui, target, false, { afterExpand: true });
388
+ }
389
+ }
390
+ switch (outcome) {
391
+ case "revealed":
392
+ if (expandedNotice !== undefined) {
393
+ notifyAfterScroll(ui, expandedNotice);
394
+ }
395
+ return;
396
+ case "unsupported":
397
+ ui.notify(
398
+ "Scroll up to find the message. Jumping to it needs fullscreen mode (tuiMode).",
399
+ "info",
400
+ );
401
+ return;
402
+ case "collapsed":
403
+ notifyAfterScroll(
404
+ ui,
405
+ expandedNotice === undefined
406
+ ? "Could not expand the tool output that holds the match. The transcript shows that tool call."
407
+ : "Expanded tool output, but could not find the match in it. The transcript shows that tool call.",
408
+ );
409
+ return;
410
+ case "not-found":
411
+ ui.notify(
412
+ "Could not find the message on screen. It may be inside collapsed tool output.",
413
+ "info",
414
+ );
415
+ return;
416
+ default:
417
+ outcome satisfies never;
418
+ }
419
+ }
420
+
421
+ async function revealAndReport(
422
+ ctx: OpeningContext,
423
+ tui: TUI | undefined,
424
+ hit: SearchHit,
425
+ queryText: string,
426
+ afterSwitch: boolean,
427
+ ): Promise<void> {
428
+ const target = revealTarget(ctx.sessionManager, hit, queryText);
429
+ if (target === undefined) {
430
+ ctx.ui.notify(
431
+ "That message is folded into a compaction summary, so it is not in the transcript.",
432
+ "info",
433
+ );
434
+ return;
435
+ }
436
+ await revealTargetAndReport(ctx.ui, tui, target, afterSwitch);
437
+ }
438
+
439
+ /** Moves to the branch that holds the hit, after asking. Returns false when the user declines or pi is busy. */
440
+ async function switchBranch(ctx: OpeningContext, hit: SearchHit): Promise<boolean> {
441
+ const confirmed = await ctx.ui.confirm(
442
+ "Open this branch?",
443
+ `This ${kindLabel(hit)} message is not on the branch you are on. Move to its branch? Pi does not summarize the branch you leave.`,
444
+ );
445
+ if (!confirmed) {
446
+ return false;
447
+ }
448
+ if (!ctx.isIdle()) {
449
+ ctx.ui.notify("Wait for pi to finish, then open the match again.", "warning");
450
+ return false;
451
+ }
452
+ const tip = branchTipOf(ctx.sessionManager.getEntries(), hit.entryId);
453
+ try {
454
+ const result = await ctx.navigateTree(tip, { summarize: false });
455
+ return !result.cancelled;
456
+ } catch (error) {
457
+ ctx.ui.notify(
458
+ `Could not switch branch: ${error instanceof Error ? error.message : String(error)}`,
459
+ "error",
460
+ );
461
+ return false;
462
+ }
463
+ }
464
+
465
+ /** Notifies through a context that may be stale after a session switch. */
466
+ function notifySafely(
467
+ ctx: Pick<ExtensionCommandContext, "ui">,
468
+ message: string,
469
+ type: "info" | "warning" | "error",
470
+ ): void {
471
+ try {
472
+ ctx.ui.notify(message, type);
473
+ } catch {
474
+ // The old session's context is gone; there is nowhere left to report.
475
+ }
476
+ }
477
+
478
+ /** Handles Enter on a hit. Never throws: problems become notifications. */
479
+ export async function openHit(
480
+ ctx: ExtensionCommandContext,
481
+ tui: TUI | undefined,
482
+ hit: SearchHit,
483
+ queryText: string,
484
+ ): Promise<void> {
485
+ const currentFile = ctx.sessionManager.getSessionFile();
486
+ const inCurrentSession = hit.sessionFile === undefined || hit.sessionFile === currentFile;
487
+
488
+ if (inCurrentSession) {
489
+ if (ctx.sessionManager.getEntry(hit.entryId) === undefined) {
490
+ ctx.ui.notify("That message is no longer in this session.", "warning");
491
+ return;
492
+ }
493
+ const onBranch = ctx.sessionManager.getBranch().some((entry) => entry.id === hit.entryId);
494
+ if (!onBranch) {
495
+ if (!(await switchBranch(ctx, hit))) {
496
+ return;
497
+ }
498
+ }
499
+ await revealAndReport(ctx, tui, hit, queryText, !onBranch);
500
+ return;
501
+ }
502
+
503
+ const sessionFile = hit.sessionFile;
504
+ if (sessionFile === undefined) {
505
+ return;
506
+ }
507
+ const where = hit.sessionName ?? hit.cwd;
508
+ const confirmed = await ctx.ui.confirm(
509
+ "Open this session?",
510
+ `This match is in ${where}. Leave the current session and open that one?`,
511
+ );
512
+ if (!confirmed) {
513
+ return;
514
+ }
515
+ if (!ctx.isIdle()) {
516
+ ctx.ui.notify("Wait for pi to finish, then open the match again.", "warning");
517
+ return;
518
+ }
519
+ try {
520
+ const result = await ctx.switchSession(sessionFile, {
521
+ // Runs with the replacement session's context. Only plain data is captured.
522
+ withSession: async (next) => {
523
+ if (next.sessionManager.getEntry(hit.entryId) === undefined) {
524
+ next.ui.notify("The message was not found in that session.", "warning");
525
+ return;
526
+ }
527
+ const onBranch = next.sessionManager.getBranch().some((entry) => entry.id === hit.entryId);
528
+ if (!onBranch && !(await switchBranch(next, hit))) {
529
+ return;
530
+ }
531
+ await revealAndReport(next, tui, hit, queryText, true);
532
+ },
533
+ });
534
+ if (result.cancelled) {
535
+ notifySafely(ctx, "Session switch was cancelled.", "info");
536
+ }
537
+ } catch (error) {
538
+ notifySafely(
539
+ ctx,
540
+ `Could not open that session: ${error instanceof Error ? error.message : String(error)}`,
541
+ "error",
542
+ );
543
+ }
544
+ }