@lune_99/pi-lune-extensions-core 0.2.0 → 0.2.1

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,303 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
+ import { INDEX_BUDGET_MB, megabytes, SESSION_TEXT_LIMIT } from "./budget.js";
6
+ import { SOURCE_NAMES } from "./session.js";
7
+ /** Raise when the stored shape or what a reader takes from a session file changes. */
8
+ const FORMAT = 3;
9
+ /**
10
+ * The default budget; Core settings let the user change it. The newest sessions whose entries
11
+ * fit are indexed and listed; older ones are neither read nor listed.
12
+ */
13
+ export const INDEX_BUDGET_BYTES = megabytes(INDEX_BUDGET_MB);
14
+ const STRING_FIELDS = ["path", "id", "cwd", "firstMessage", "allMessagesText"];
15
+ const OPTIONAL_STRING_FIELDS = ["name", "parentSessionPath"];
16
+ const DATE_FIELDS = ["created", "modified"];
17
+ export function sessionIndexFile(agentDir = getAgentDir()) {
18
+ return join(agentDir, "lune-cache", "session-index.json");
19
+ }
20
+ /** A file with the same inode, size and modification time reads the same. */
21
+ export function fileVersion(stats) {
22
+ return `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
23
+ }
24
+ /**
25
+ * What the catalog read from each session file, saved so that a new Pi session or process
26
+ * reads only the files that changed since. Listing reads every file in full, and the session
27
+ * stores reach gigabytes because of tool output the list never uses.
28
+ *
29
+ * Every load and every changed scan reads or writes the whole index, so it holds only the
30
+ * newest sessions that fit its budget, with their text clipped to the configured limit.
31
+ *
32
+ * Several Pi processes share the file. Each writes a complete index and renames it into
33
+ * place, so readers always see a whole index and the last writer wins.
34
+ */
35
+ export class SessionIndex {
36
+ file;
37
+ /**
38
+ * Bytes the entries of a scan may take. A smaller budget drops the oldest entries at the
39
+ * next scan; a larger one reads the files the last scan left out.
40
+ */
41
+ budget;
42
+ textLimit;
43
+ entries = new Map();
44
+ indexedTextLimit;
45
+ loaded = false;
46
+ changed = false;
47
+ constructor(file, budget = INDEX_BUDGET_BYTES, textLimit = SESSION_TEXT_LIMIT) {
48
+ this.file = file;
49
+ this.budget = budget;
50
+ this.textLimit = textLimit;
51
+ }
52
+ /**
53
+ * Reads the saved index once. A missing file or another format starts empty; an invalid
54
+ * one is reported and replaced by the next save.
55
+ */
56
+ async load(signal) {
57
+ if (this.loaded)
58
+ return;
59
+ this.loaded = true;
60
+ let content;
61
+ try {
62
+ content = await readFile(this.file, { encoding: "utf8", signal });
63
+ }
64
+ catch (error) {
65
+ if (error.code === "ENOENT")
66
+ return;
67
+ throw error;
68
+ }
69
+ try {
70
+ const stored = parseIndex(content);
71
+ if (stored) {
72
+ this.entries = stored.entries;
73
+ this.indexedTextLimit = stored.textLimit;
74
+ }
75
+ else {
76
+ this.changed = true;
77
+ }
78
+ }
79
+ catch (error) {
80
+ this.changed = true;
81
+ const reason = error instanceof Error ? error.message : String(error);
82
+ throw new Error(`${this.file}: unreadable session index, rebuilding it: ${reason}`, {
83
+ cause: error,
84
+ });
85
+ }
86
+ }
87
+ /**
88
+ * Lists the sessions of the newest files, by modification time, until the next one does
89
+ * not fit the budget. Files the index lacks are read one at a time, which bounds memory
90
+ * for large rollouts and keeps the order. Entries for every other file are dropped.
91
+ */
92
+ async scan(files, signal) {
93
+ signal.throwIfAborted();
94
+ if (this.indexedTextLimit !== this.textLimit) {
95
+ // A larger limit needs text that the saved entries no longer contain.
96
+ this.changed ||= this.indexedTextLimit !== undefined;
97
+ this.entries.clear();
98
+ this.indexedTextLimit = this.textLimit;
99
+ }
100
+ const sessions = new Array(files.length);
101
+ const errors = [];
102
+ const kept = new Map();
103
+ const newestFirst = files
104
+ .map((_, position) => position)
105
+ .sort((left, right) => files[right].stats.mtimeMs - files[left].stats.mtimeMs);
106
+ let used = Buffer.byteLength(serializeIndex(new Map(), this.textLimit));
107
+ for (const position of newestFirst) {
108
+ signal.throwIfAborted();
109
+ const file = files[position];
110
+ const version = fileVersion(file.stats);
111
+ const stored = this.entries.get(file.path);
112
+ let entry = stored?.version === version ? stored : undefined;
113
+ if (!entry ||
114
+ (entry.omitted &&
115
+ (used + entry.bytes - Number(kept.size === 0) <= this.budget ||
116
+ entry.currentVersion !== file.currentVersion))) {
117
+ let session;
118
+ try {
119
+ session = await file.read(signal);
120
+ }
121
+ catch (error) {
122
+ signal.throwIfAborted();
123
+ // Removed since the directory was listed.
124
+ if (error.code === "ENOENT")
125
+ continue;
126
+ const message = error instanceof Error ? error.message : String(error);
127
+ errors.push(new Error(`${file.label}: ${file.path}: ${message}`, { cause: error }));
128
+ continue;
129
+ }
130
+ entry = indexEntry(file.path, version, session && clipped(session, this.textLimit));
131
+ }
132
+ if (entry.session && file.current) {
133
+ const session = file.current(entry.session);
134
+ if (session !== entry.session)
135
+ entry = indexEntry(file.path, version, session);
136
+ }
137
+ const separator = Number(kept.size === 0);
138
+ if (used + entry.bytes - separator > this.budget) {
139
+ if (!entry.omitted) {
140
+ entry = {
141
+ version,
142
+ omitted: true,
143
+ bytes: entry.bytes,
144
+ currentVersion: file.currentVersion,
145
+ };
146
+ }
147
+ const markerBytes = serializedEntryBytes(file.path, {
148
+ version,
149
+ omittedBytes: entry.bytes,
150
+ currentVersion: entry.currentVersion,
151
+ });
152
+ // A boundary marker must not push the index beyond its configured size.
153
+ if (used + markerBytes - separator <= this.budget)
154
+ kept.set(file.path, entry);
155
+ break;
156
+ }
157
+ used += entry.bytes - separator;
158
+ kept.set(file.path, entry);
159
+ sessions[position] = entry.session;
160
+ }
161
+ if (kept.size !== this.entries.size ||
162
+ [...kept].some(([path, entry]) => this.entries.get(path) !== entry)) {
163
+ this.changed = true;
164
+ }
165
+ this.entries = kept;
166
+ return { sessions: sessions.filter((session) => session !== undefined), errors };
167
+ }
168
+ /** Writes the index if the last scan changed it. */
169
+ async save() {
170
+ if (!this.changed)
171
+ return;
172
+ const content = serializeIndex(this.entries, this.textLimit);
173
+ await mkdir(dirname(this.file), { recursive: true, mode: 0o700 });
174
+ const temporary = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
175
+ try {
176
+ // Owner-only: the index holds the message text of every listed session.
177
+ await writeFile(temporary, content, { encoding: "utf8", mode: 0o600 });
178
+ await rename(temporary, this.file);
179
+ }
180
+ catch (error) {
181
+ await rm(temporary, { force: true });
182
+ throw error;
183
+ }
184
+ this.changed = false;
185
+ }
186
+ }
187
+ function indexEntry(path, version, session) {
188
+ return session
189
+ ? { version, session, bytes: entryBytes(path, version, session) }
190
+ : { version, bytes: entryBytes(path, version) };
191
+ }
192
+ function entryBytes(path, version, session) {
193
+ return serializedEntryBytes(path, session ? { version, session: storedSession(session) } : { version });
194
+ }
195
+ function serializedEntryBytes(path, value) {
196
+ return Buffer.byteLength(JSON.stringify(path)) + Buffer.byteLength(JSON.stringify(value)) + 2;
197
+ }
198
+ function clipped(session, limit) {
199
+ const firstMessage = clip(session.firstMessage, limit);
200
+ const allMessagesText = clip(session.allMessagesText, limit);
201
+ return firstMessage === session.firstMessage && allMessagesText === session.allMessagesText
202
+ ? session
203
+ : { ...session, firstMessage, allMessagesText };
204
+ }
205
+ function clip(text, limit) {
206
+ if (text.length <= limit)
207
+ return text;
208
+ const last = text.charCodeAt(limit - 1);
209
+ // Never keep half of a surrogate pair.
210
+ return text.slice(0, last >= 0xd800 && last <= 0xdbff ? limit - 1 : limit);
211
+ }
212
+ function serializeIndex(entries, textLimit) {
213
+ const files = {};
214
+ for (const [path, { version, session, omitted, bytes, currentVersion }] of entries) {
215
+ files[path] = omitted
216
+ ? { version, omittedBytes: bytes, currentVersion }
217
+ : session
218
+ ? { version, session: storedSession(session) }
219
+ : { version };
220
+ }
221
+ return JSON.stringify({ format: FORMAT, textLimit, files });
222
+ }
223
+ // JSON drops undefined values, but the readers set `name` and `parentSessionPath` keys that
224
+ // may hold undefined. Null keeps the key, so a stored session equals a fresh read.
225
+ function storedSession(session) {
226
+ return Object.fromEntries(Object.entries(session).map(([key, value]) => [
227
+ key,
228
+ value instanceof Date ? value.getTime() : (value ?? null),
229
+ ]));
230
+ }
231
+ function parseIndex(content) {
232
+ const entries = new Map();
233
+ const stored = JSON.parse(content);
234
+ if (!isRecord(stored) || typeof stored["format"] !== "number") {
235
+ throw new Error("missing format");
236
+ }
237
+ if (stored["format"] !== FORMAT)
238
+ return undefined;
239
+ const textLimit = stored["textLimit"];
240
+ if (typeof textLimit !== "number" || !Number.isInteger(textLimit) || textLimit < 1) {
241
+ throw new Error("invalid textLimit");
242
+ }
243
+ const files = stored["files"];
244
+ if (!isRecord(files))
245
+ throw new Error("missing files");
246
+ for (const [path, value] of Object.entries(files)) {
247
+ if (!isRecord(value) || typeof value["version"] !== "string") {
248
+ throw new Error(`invalid entry for ${path}`);
249
+ }
250
+ const version = value["version"];
251
+ const omittedBytes = value["omittedBytes"];
252
+ if (omittedBytes !== undefined) {
253
+ if (typeof omittedBytes !== "number" || !(omittedBytes >= 0)) {
254
+ throw new Error(`invalid omittedBytes for ${path}`);
255
+ }
256
+ const currentVersion = value["currentVersion"];
257
+ if (currentVersion !== undefined && typeof currentVersion !== "string") {
258
+ throw new Error(`invalid currentVersion for ${path}`);
259
+ }
260
+ entries.set(path, { version, omitted: true, bytes: omittedBytes, currentVersion });
261
+ continue;
262
+ }
263
+ entries.set(path, indexEntry(path, version, value["session"] === undefined
264
+ ? undefined
265
+ : restoredSession(value["session"], path)));
266
+ }
267
+ return { entries, textLimit };
268
+ }
269
+ function restoredSession(value, path) {
270
+ const invalid = (field) => new Error(`invalid ${field} for ${path}`);
271
+ if (!isRecord(value))
272
+ throw invalid("session");
273
+ const session = { ...value };
274
+ for (const field of STRING_FIELDS) {
275
+ if (typeof value[field] !== "string")
276
+ throw invalid(field);
277
+ }
278
+ if (typeof value["messageCount"] !== "number")
279
+ throw invalid("messageCount");
280
+ const source = value["source"];
281
+ if (typeof source !== "string" || !Object.hasOwn(SOURCE_NAMES, source)) {
282
+ throw invalid("source");
283
+ }
284
+ for (const field of OPTIONAL_STRING_FIELDS) {
285
+ if (!Object.hasOwn(value, field))
286
+ continue;
287
+ const text = value[field];
288
+ if (text !== null && typeof text !== "string")
289
+ throw invalid(field);
290
+ session[field] = text ?? undefined;
291
+ }
292
+ for (const field of DATE_FIELDS) {
293
+ const time = value[field];
294
+ // An invalid date is stored as NaN, which JSON writes as null.
295
+ if (time !== null && typeof time !== "number")
296
+ throw invalid(field);
297
+ session[field] = new Date(time ?? Number.NaN);
298
+ }
299
+ return session;
300
+ }
301
+ function isRecord(value) {
302
+ return typeof value === "object" && value !== null && !Array.isArray(value);
303
+ }
@@ -687,11 +687,15 @@ class SettingsPanel {
687
687
  // Side-by-side preview needs room; below this width it is stacked under the list.
688
688
  const split = width >= 88 && !this.input && !!field?.preview;
689
689
  const bodyWidth = split ? Math.floor((width - 3) / 2) : width;
690
- let body = this.input
691
- ? this.input.render(bodyWidth)
692
- : this.customEditor
693
- ? this.renderCustomEditor(bodyWidth)
694
- : (this.choiceEditor?.renderBody(bodyWidth) ?? this.list?.render(bodyWidth) ?? []);
690
+ let body = [
691
+ ...(this.input
692
+ ? this.input.render(bodyWidth)
693
+ : this.customEditor
694
+ ? this.renderCustomEditor(bodyWidth)
695
+ : (this.choiceEditor?.renderBody(bodyWidth) ??
696
+ this.list?.render(bodyWidth) ??
697
+ [])),
698
+ ];
695
699
  if (!this.sections.length)
696
700
  body = [this.theme.fg("muted", "No extensions have registered settings.")];
697
701
  else if (this.section?.unavailable !== undefined)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lune_99/pi-lune-extensions-core",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Shared infrastructure for the Lune series of Pi extensions",
5
5
  "type": "module",
6
6
  "exports": {
@@ -102,9 +102,9 @@
102
102
  },
103
103
  "dependencies": {},
104
104
  "devDependencies": {
105
- "@earendil-works/pi-ai": "1.3.0",
106
- "@earendil-works/pi-coding-agent": "1.3.0",
107
- "@earendil-works/pi-tui": "1.3.0",
105
+ "@earendil-works/pi-ai": "1.6.0",
106
+ "@earendil-works/pi-coding-agent": "1.6.0",
107
+ "@earendil-works/pi-tui": "1.6.0",
108
108
  "@types/node": "^22.20.2",
109
109
  "typescript": "5.9.3"
110
110
  },
package/src/core/panel.ts CHANGED
@@ -1,7 +1,35 @@
1
1
  import { defineSettingsPanel } from "../panel/definition.ts";
2
- import { coreSettings } from "./settings.ts";
2
+ import { coreSettings, MENTION_CACHE_MAX_MB, MENTION_CACHE_MIN_MB } from "./settings.ts";
3
3
 
4
4
  export const corePanel = defineSettingsPanel(coreSettings, {
5
5
  id: "core",
6
6
  label: "Core",
7
+ fields: (field) => [
8
+ field(["mention", "cacheSizeMB"], {
9
+ label: "Session cache size",
10
+ description:
11
+ `The index on disk behind the @ and @@ session lists, ${MENTION_CACHE_MIN_MB} to ` +
12
+ `${MENTION_CACHE_MAX_MB} MB. Sessions older than what fits are not listed and ` +
13
+ `cannot be mentioned. Larger values retain more sessions and take longer to load.`,
14
+ inMenu: "mention",
15
+ formatValue: (value) => `${value} MB`,
16
+ }),
17
+ field(["mention", "textLimit"], {
18
+ label: "Session text limit",
19
+ description:
20
+ "Characters kept from each session's first message and searchable text. " +
21
+ "Use a positive integer; a change applies at the next load of the session list.",
22
+ inMenu: "mention",
23
+ formatValue: (value) => `${value} characters`,
24
+ }),
25
+ ],
26
+ menus: [
27
+ {
28
+ id: "mention",
29
+ label: "Mention",
30
+ description: "Settings for @ and @@ session mentions.",
31
+ summary: ({ values }) =>
32
+ `cache ${values.mention.cacheSizeMB} MB · text ${values.mention.textLimit} chars`,
33
+ },
34
+ ],
7
35
  });
@@ -1,8 +1,48 @@
1
1
  import { Type } from "typebox";
2
+ import { INDEX_BUDGET_MB, SESSION_TEXT_LIMIT } from "../mention/budget.ts";
2
3
  import { defineSettings } from "../settings/definition.ts";
3
4
 
4
- // Reserve Core's namespace without introducing settings solely for the placeholder.
5
+ /** Bounds of the session index size a user can choose, in megabytes. */
6
+ export const MENTION_CACHE_MIN_MB = 1;
7
+ export const MENTION_CACHE_MAX_MB = 64;
8
+
5
9
  export const coreSettings = defineSettings({
6
10
  id: "pi-lune-extensions-core",
7
- schema: Type.Object({}),
11
+ schema: Type.Object({
12
+ mention: Type.Object(
13
+ {
14
+ cacheSizeMB: Type.Integer({
15
+ minimum: MENTION_CACHE_MIN_MB,
16
+ maximum: MENTION_CACHE_MAX_MB,
17
+ default: INDEX_BUDGET_MB,
18
+ }),
19
+ textLimit: Type.Integer({ minimum: 1, default: SESSION_TEXT_LIMIT }),
20
+ },
21
+ {
22
+ additionalProperties: false,
23
+ default: { cacheSizeMB: INDEX_BUDGET_MB, textLimit: SESSION_TEXT_LIMIT },
24
+ },
25
+ ),
26
+ }),
27
+ migrations: [
28
+ (overrides) => {
29
+ const mention = overrides["mention"];
30
+ // Object overrides replace the whole value, so the new leaf needs a migration.
31
+ if (
32
+ typeof mention === "object" &&
33
+ mention !== null &&
34
+ !Array.isArray(mention) &&
35
+ !Object.hasOwn(mention, "textLimit")
36
+ ) {
37
+ return {
38
+ ...overrides,
39
+ mention: { ...mention, textLimit: SESSION_TEXT_LIMIT },
40
+ };
41
+ }
42
+ return overrides;
43
+ },
44
+ ],
45
+ // Every Pi process shares one index file. Projects with different sizes would make each
46
+ // process trim what the other read, so the file is read again on every load.
47
+ globalOnly: ["mention"],
8
48
  });
package/src/extension.ts CHANGED
@@ -13,6 +13,7 @@ import { registerSettingsPanel } from "./panel/registration.ts";
13
13
  import { openSettingsPanel } from "./panel/tui.ts";
14
14
  import { scopedExtension } from "./resources/scoped-extension.ts";
15
15
  import { installMentions } from "./mention/index.ts";
16
+ import { megabytes } from "./mention/budget.ts";
16
17
  import { bindSettings } from "./settings/binding.ts";
17
18
 
18
19
  /**
@@ -35,5 +36,9 @@ export default scopedExtension((pi, resources) => {
35
36
  await openSettingsPanel(ctx, { section: args.trim() || undefined });
36
37
  },
37
38
  });
38
- installMentions(pi, resources);
39
+ installMentions(pi, resources, {
40
+ indexBudget: async (ctx) =>
41
+ megabytes((await settings.view(ctx)).get("mention").cacheSizeMB),
42
+ indexTextLimit: async (ctx) => (await settings.view(ctx)).get("mention").textLimit,
43
+ });
39
44
  });
@@ -25,8 +25,10 @@ export interface MentionAutocompleteOptions {
25
25
  * `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
26
26
  * Everything that is not an `@` token goes to the provider underneath.
27
27
  *
28
- * Nothing here waits for the session list: the rows come from what the catalog has read. The
29
- * editor runs one request at a time, so a slow request would delay every later keystroke.
28
+ * A plain `@` never waits for the session list: its rows come from what the catalog has read,
29
+ * so file matches are not delayed. `@@` lists nothing but sessions, and the editor asks again
30
+ * only on a keystroke, so before the first load it waits for that load instead of answering
31
+ * empty. The editor aborts a pending request on the next keystroke, which ends the wait.
30
32
  */
31
33
  export function createMentionAutocomplete(
32
34
  current: AutocompleteProvider,
@@ -57,6 +59,8 @@ export function createMentionAutocomplete(
57
59
  const prefix = AT_WORD.exec((lines[cursorLine] ?? "").slice(0, cursorCol))?.[1];
58
60
  if (!prefix) return current.getSuggestions(lines, cursorLine, cursorCol, request);
59
61
  if (prefix.startsWith(SESSION_TRIGGER)) {
62
+ await options.catalog.whenLoaded(request.signal);
63
+ if (request.signal.aborted) return null;
60
64
  const query = prefix.slice(SESSION_TRIGGER.length);
61
65
  const items = sessionItems(query, SESSION_LIST_ROWS, true);
62
66
  return items.length > 0 ? { items, prefix } : null;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The default size of the session index. Kept free of runtime imports, because Core's settings
3
+ * declare it as their default and the settings screen loads them.
4
+ */
5
+ export const INDEX_BUDGET_MB = 4;
6
+ export const SESSION_TEXT_LIMIT = 8_000;
7
+
8
+ /** Megabytes (MiB) to bytes. */
9
+ export function megabytes(size: number): number {
10
+ return size * 1024 * 1024;
11
+ }
@@ -1,41 +1,50 @@
1
- import { dirname, join, resolve } from "node:path";
2
- import { getAgentDir, SessionManager } from "@earendil-works/pi-coding-agent";
1
+ import { SESSION_TEXT_LIMIT } from "./budget.ts";
3
2
  import { ExternalSessions } from "./external.ts";
3
+ import { PiSessions } from "./pi.ts";
4
+ import { INDEX_BUDGET_BYTES, SessionIndex, sessionIndexFile } from "./session-index.ts";
4
5
  import type { LocalSession } from "./session.ts";
5
6
 
6
7
  /** A list older than this is reloaded in the background on the next lookup. */
7
8
  const REFRESH_AFTER_MS = 60_000;
8
9
 
9
10
  /**
10
- * Local Pi, Codex and Claude Code main sessions, newest activity first.
11
+ * The newest local Pi, Codex and Claude Code main sessions that fit the index budget, newest
12
+ * activity first. Each load asks for the budget again, so a changed setting applies to the
13
+ * next load.
11
14
  *
12
- * Listing reads every session file (about a second for a few hundred sessions), so lookups
13
- * serve the cached list and reload it in the background. The owner disposes the catalog on
14
- * session shutdown; a load that finishes later is discarded.
15
+ * Every load checks each session file and reads only those that changed since the saved
16
+ * index. Lookups serve the cached list and reload it in the background. The owner disposes
17
+ * the catalog on session shutdown; a load that finishes later is discarded.
15
18
  */
16
19
  export class SessionCatalog {
17
- private readonly sessionDir: string;
18
20
  private readonly onBackgroundError: (error: unknown) => void;
21
+ private readonly budget: () => Promise<number>;
22
+ private readonly textLimit: () => Promise<number>;
19
23
  private readonly abort = new AbortController();
24
+ private readonly index = new SessionIndex(sessionIndexFile());
25
+ private readonly pi: PiSessions;
20
26
  private readonly external = new ExternalSessions();
21
27
  private sessions: readonly LocalSession[] = [];
22
28
  private loaded = false;
23
29
  private loadedAt = 0;
24
30
  private loading: Promise<readonly LocalSession[]> | undefined;
25
31
 
26
- constructor(sessionDir: string, onBackgroundError: (error: unknown) => void) {
27
- this.sessionDir = sessionDir;
32
+ /** `budget` gives the bytes the session index may keep. */
33
+ constructor(
34
+ sessionDir: string,
35
+ onBackgroundError: (error: unknown) => void,
36
+ budget: () => Promise<number> = async () => INDEX_BUDGET_BYTES,
37
+ textLimit: () => Promise<number> = async () => SESSION_TEXT_LIMIT,
38
+ ) {
39
+ this.pi = new PiSessions(sessionDir);
28
40
  this.onBackgroundError = onBackgroundError;
41
+ this.budget = budget;
42
+ this.textLimit = textLimit;
29
43
  }
30
44
 
31
45
  /** The cached list, empty before the first load. A stale list starts a background reload. */
32
46
  snapshot(): readonly LocalSession[] {
33
- const stale = Date.now() - this.loadedAt > REFRESH_AFTER_MS;
34
- if (stale && !this.loading && !this.abort.signal.aborted) {
35
- this.reload().catch((error: unknown) => {
36
- if (!this.abort.signal.aborted) this.onBackgroundError(error);
37
- });
38
- }
47
+ if (Date.now() - this.loadedAt > REFRESH_AFTER_MS) this.refreshInBackground();
39
48
  return this.sessions;
40
49
  }
41
50
 
@@ -44,26 +53,34 @@ export class SessionCatalog {
44
53
  return this.loaded ? this.snapshot() : this.reload();
45
54
  }
46
55
 
56
+ /**
57
+ * Settles when the first load does or when `signal` aborts. Whoever started the load
58
+ * handles its failure, so a waiting caller only reads snapshot() again.
59
+ *
60
+ * A failed first load is retried here. snapshot() only retries a stale list, and `@@`
61
+ * would otherwise stay empty for a minute after a transient read error.
62
+ */
63
+ async whenLoaded(signal: AbortSignal): Promise<void> {
64
+ if (this.loaded) return;
65
+ this.refreshInBackground();
66
+ const loading = this.loading;
67
+ if (!loading || signal.aborted) return;
68
+ await new Promise<void>((resolve) => {
69
+ const settle = () => {
70
+ signal.removeEventListener("abort", settle);
71
+ resolve();
72
+ };
73
+ signal.addEventListener("abort", settle, { once: true });
74
+ loading.then(settle, settle);
75
+ });
76
+ }
77
+
47
78
  /** Concurrent callers share one load. */
48
79
  reload(): Promise<readonly LocalSession[]> {
49
80
  this.loadedAt = Date.now();
50
- this.loading ??= Promise.all([
51
- listSessions(this.sessionDir, this.abort.signal),
52
- this.external.list(this.abort.signal, this.onBackgroundError),
53
- ])
54
- .then(([pi, external]) => {
55
- this.abort.signal.throwIfAborted();
56
- const sessions = [
57
- ...pi.map((session): LocalSession => ({ ...session, source: "pi" })),
58
- ...external,
59
- ].sort((left, right) => right.modified.getTime() - left.modified.getTime());
60
- this.sessions = sessions;
61
- this.loaded = true;
62
- return sessions;
63
- })
64
- .finally(() => {
65
- this.loading = undefined;
66
- });
81
+ this.loading ??= this.load().finally(() => {
82
+ this.loading = undefined;
83
+ });
67
84
  return this.loading;
68
85
  }
69
86
 
@@ -71,14 +88,46 @@ export class SessionCatalog {
71
88
  this.abort.abort();
72
89
  this.external.clear();
73
90
  }
74
- }
75
91
 
76
- function listSessions(sessionDir: string, signal: AbortSignal) {
77
- // Matches the "all" scope of /resume: the default store keeps one folder per project under
78
- // the agent's sessions root, and a custom session directory holds every session itself.
79
- const root = join(getAgentDir(), "sessions");
80
- const custom = sessionDir !== "" && resolve(dirname(sessionDir)) !== resolve(root);
81
- return custom
82
- ? SessionManager.listAll(sessionDir, undefined, signal)
83
- : SessionManager.listAll(undefined, signal);
92
+ private async load(): Promise<readonly LocalSession[]> {
93
+ const signal = this.abort.signal;
94
+ // A failed index only costs a full read; the scan below writes a new one.
95
+ await this.index.load(signal).catch((error: unknown) => this.report(error));
96
+ // Settings that cannot be read are reported where they are edited; the session list
97
+ // keeps working with the default size instead.
98
+ this.index.budget = await this.budget().catch(() => INDEX_BUDGET_BYTES);
99
+ this.index.textLimit = await this.textLimit().catch(() => SESSION_TEXT_LIMIT);
100
+ const [pi, external] = await Promise.all([
101
+ this.pi.list(signal),
102
+ this.external.list(signal, this.onBackgroundError),
103
+ ]);
104
+ // Pi first, so sessions with equal activity times keep listAll's order.
105
+ const { sessions: listed, errors } = await this.index.scan([...pi, ...external], signal);
106
+ signal.throwIfAborted();
107
+ if (errors.length > 0) {
108
+ this.report(
109
+ new AggregateError(errors, errors.map((error) => error.message).join("\n")),
110
+ );
111
+ }
112
+ await this.index.save().catch((error: unknown) => this.report(error));
113
+ signal.throwIfAborted();
114
+ const sessions = listed.sort(
115
+ (left, right) => right.modified.getTime() - left.modified.getTime(),
116
+ );
117
+ this.sessions = sessions;
118
+ this.loaded = true;
119
+ return sessions;
120
+ }
121
+
122
+ private refreshInBackground(): void {
123
+ if (this.loading || this.abort.signal.aborted) return;
124
+ this.reload().catch((error: unknown) => {
125
+ if (!this.abort.signal.aborted) this.onBackgroundError(error);
126
+ });
127
+ }
128
+
129
+ private report(error: unknown): void {
130
+ this.abort.signal.throwIfAborted();
131
+ this.onBackgroundError(error);
132
+ }
84
133
  }