proper-base 0.2.8 → 0.4.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 +2 -2
- package/index.ts +129 -9
- package/package.json +3 -3
- package/src/autocomplete-details.ts +21 -5
- package/src/clipboard-guard.ts +181 -0
- package/src/fast-mode.ts +210 -0
- package/src/image-preview.ts +15 -4
- package/src/osc8-link-ids.ts +90 -0
- package/src/prompt-jump.ts +29 -4
- package/src/recorder.ts +6 -0
- package/src/selection-dismiss.ts +110 -0
- package/src/session-list.ts +497 -0
- package/src/transcript-cleanup.ts +29 -3
- package/src/wheel-scroll.ts +46 -0
|
@@ -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
|
|
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
|
|
367
|
+
lines.push(...renderExpandable(child, width, state));
|
|
368
368
|
continue;
|
|
369
369
|
}
|
|
370
|
-
lines.push(...withVerticalSpacing(child
|
|
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
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi's fullscreen renderer scrolls its transcript exactly one line per
|
|
3
|
+
* mouse-wheel report: the renderer's `wheelScrollLines` option defaults to 1
|
|
4
|
+
* and pi passes no override and exposes no setting. Terminals natively
|
|
5
|
+
* multiply a wheel notch to about three lines, so fullscreen scrolling feels
|
|
6
|
+
* slower than every other terminal surface.
|
|
7
|
+
*
|
|
8
|
+
* No escape sequence lets an application query the terminal's own wheel
|
|
9
|
+
* configuration, so the step defaults to the 3-line application convention
|
|
10
|
+
* (vim, less) and honors a per-terminal `PROPER_WHEEL_SCROLL_LINES`
|
|
11
|
+
* environment override that each terminal's profile can export.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const DEFAULT_WHEEL_SCROLL_LINES = 3;
|
|
15
|
+
|
|
16
|
+
/** Renderer surface carrying the per-wheel-event line count. */
|
|
17
|
+
type WheelHost = { wheelScrollLines?: unknown };
|
|
18
|
+
|
|
19
|
+
/** Lines per wheel event: a positive integer override, else the 3-line convention. */
|
|
20
|
+
export function resolveWheelScrollLines(
|
|
21
|
+
env: Record<string, string | undefined> = process.env,
|
|
22
|
+
): number {
|
|
23
|
+
const parsed = Number.parseInt(env.PROPER_WHEEL_SCROLL_LINES ?? "", 10);
|
|
24
|
+
return parsed >= 1 ? parsed : DEFAULT_WHEEL_SCROLL_LINES;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Raise the fullscreen renderer's wheel step. Only a renderer that already
|
|
29
|
+
* exposes a numeric `wheelScrollLines` is touched, so regular mode — where
|
|
30
|
+
* the terminal scrolls natively — and a renamed upstream field fail open to
|
|
31
|
+
* pi's own behavior.
|
|
32
|
+
*
|
|
33
|
+
* ponytail: SGR wheel reports cannot distinguish a discrete mouse notch from
|
|
34
|
+
* one line of a high-rate trackpad stream, so a terminal emitting one report
|
|
35
|
+
* per native line scrolls proportionally faster; exporting
|
|
36
|
+
* PROPER_WHEEL_SCROLL_LINES=1 there restores pi's original pace.
|
|
37
|
+
*/
|
|
38
|
+
export function installWheelScrollLines(
|
|
39
|
+
tui: unknown,
|
|
40
|
+
lines: number = resolveWheelScrollLines(),
|
|
41
|
+
): boolean {
|
|
42
|
+
const host = tui as WheelHost;
|
|
43
|
+
if (typeof host.wheelScrollLines !== "number") return false;
|
|
44
|
+
host.wheelScrollLines = Math.floor(lines);
|
|
45
|
+
return true;
|
|
46
|
+
}
|