@evandu/super-pi 0.1.236 → 0.1.238

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.
@@ -8,9 +8,9 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-Dg6iMr6l.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-D9r0K1_Y.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-CPZJ8qsj.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-sDaqj666.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -28,7 +28,7 @@ export type IndexProgress = {
28
28
  /** The answer to one question: which paths contain this needle. */
29
29
  export type NameSearchResult = {
30
30
  hits: NameEntry[];
31
- /** The exact number of matches. Equal to `hits.length` when nothing was withheld. */
31
+ /** Total matches before the result page is applied. */
32
32
  total: number;
33
33
  /** Whether the index has finished its first pass. `false` means "more may still arrive". */
34
34
  indexed: boolean;
@@ -36,6 +36,7 @@ export type NameSearchResult = {
36
36
  /** Set when the scan hit a limit. Its presence is the reason the answer is not the whole tree. */
37
37
  incomplete: boolean;
38
38
  };
39
+ export declare const QUICK_OPEN_PAGE_SIZE = 60;
39
40
  /**
40
41
  * The result ordering, and why it is not the path dictionary order.
41
42
  *
@@ -43,10 +44,10 @@ export type NameSearchResult = {
43
44
  * a whole string. In a list of two hundred that is actively hostile: the file whose name STARTS
44
45
  * with what you typed is the one you meant, and it is somewhere in the middle. So the order is:
45
46
  *
46
- * 1. the hit position inside the file name - a name that starts with the needle beats one that
47
- * merely contains it, whatever the directory;
48
- * 2. shallower directories first - `notes.md` beats `src/deep/nested/notes.md`;
49
- * 3. the path dictionary order, as the final tie-break, so the order is stable.
47
+ * 1. exact filenames;
48
+ * 2. the hit position inside the file name, so prefixes rank ahead of other substrings;
49
+ * 3. shallower directories first;
50
+ * 4. path order as the final tie-break.
50
51
  */
51
52
  export declare function compareNameHits(a: NameEntry, b: NameEntry, needle: string): number;
52
53
  /**
@@ -74,6 +75,8 @@ export declare class FileNameIndex {
74
75
  private incomplete;
75
76
  private needsScan;
76
77
  private generation;
78
+ private unread;
79
+ private hasScanned;
77
80
  private readonly removedDuringScan;
78
81
  private readonly directoriesReadDuringScan;
79
82
  constructor(workspaceId: string, cwd?: string);
@@ -88,9 +91,12 @@ export declare class FileNameIndex {
88
91
  * A scan that FAILED has not finished either - it never will be, and `failure` says why.
89
92
  */
90
93
  get indexed(): boolean;
94
+ get hasSnapshot(): boolean;
91
95
  get progress(): IndexProgress;
92
96
  /** Begin the background scan. Safe to call more than once; the second call is a no-op. */
93
97
  start(root: string): void;
98
+ /** Keep the preceding results usable while checking files written outside Super Pi. */
99
+ revalidate(root: string): void;
94
100
  markStale(): void;
95
101
  /**
96
102
  * WHY THE SCAN'S FAILURE IS RECORDED RATHER THAN THROWN.
@@ -109,8 +115,6 @@ export declare class FileNameIndex {
109
115
  get broken(): unknown;
110
116
  /** Rethrow the scan's failure, so the route can turn it into the status it deserves. */
111
117
  throwIfBroken(): void;
112
- /** Rebuild from scratch. The ↻ button. */
113
- reset(root: string): void;
114
118
  /** Record a path that appeared or changed. Used for agent writes and user saves. */
115
119
  upsert(relativePath: string, kind?: "file" | "directory", openLink?: true): void;
116
120
  /** Forget a path that is gone. */
@@ -125,6 +129,7 @@ export declare class FileNameIndex {
125
129
  * `app` return every file in `application/` as well - a result set nobody can read.
126
130
  */
127
131
  search(needle: string, linksOnly?: boolean): NameSearchResult;
132
+ searchQuickOpen(query: string, offset: number): NameSearchResult;
128
133
  /**
129
134
  * Wait until the first scan has finished, or until the deadline passes.
130
135
  *
@@ -33,6 +33,8 @@
33
33
  */
34
34
  import { readdir, stat } from "node:fs/promises";
35
35
  import { resolve } from "node:path";
36
+ import Fuse from "fuse.js";
37
+ import { matchPathMentions, rankPathMatches } from "../shared/file-mentions.js";
36
38
  import { createRootGuard, toRelative } from "./files.js";
37
39
  import { belowPath, blockedBy, inScope, matchesDirectoryReads } from "./file-index.js";
38
40
  import { explorerInternalPath } from "./workspace-file-operations.js";
@@ -66,8 +68,10 @@ export function recordWorkspacePath(indexes, workspaceId, workspaceRoot, path) {
66
68
  index.upsert(scoped);
67
69
  }
68
70
  }
71
+ export const QUICK_OPEN_PAGE_SIZE = 60;
69
72
  const MAX_DIRECTORIES = 20000;
70
- const MAX_FILES = 200000;
73
+ const MAX_ENTRIES = 200000;
74
+ const DIRECTORY_BATCH = 12;
71
75
  /**
72
76
  * The result ordering, and why it is not the path dictionary order.
73
77
  *
@@ -75,12 +79,15 @@ const MAX_FILES = 200000;
75
79
  * a whole string. In a list of two hundred that is actively hostile: the file whose name STARTS
76
80
  * with what you typed is the one you meant, and it is somewhere in the middle. So the order is:
77
81
  *
78
- * 1. the hit position inside the file name - a name that starts with the needle beats one that
79
- * merely contains it, whatever the directory;
80
- * 2. shallower directories first - `notes.md` beats `src/deep/nested/notes.md`;
81
- * 3. the path dictionary order, as the final tie-break, so the order is stable.
82
+ * 1. exact filenames;
83
+ * 2. the hit position inside the file name, so prefixes rank ahead of other substrings;
84
+ * 3. shallower directories first;
85
+ * 4. path order as the final tie-break.
82
86
  */
83
87
  export function compareNameHits(a, b, needle) {
88
+ const exact = Number(b.name.toLowerCase() === needle) - Number(a.name.toLowerCase() === needle);
89
+ if (exact !== 0)
90
+ return exact;
84
91
  const position = hitPosition(a, needle) - hitPosition(b, needle);
85
92
  if (position !== 0)
86
93
  return position;
@@ -119,6 +126,8 @@ export class FileNameIndex {
119
126
  incomplete = false;
120
127
  needsScan = false;
121
128
  generation = 0;
129
+ unread = new Set();
130
+ hasScanned = false;
122
131
  removedDuringScan = new Set();
123
132
  directoriesReadDuringScan = new Map();
124
133
  constructor(workspaceId, cwd = "") {
@@ -138,6 +147,7 @@ export class FileNameIndex {
138
147
  get indexed() {
139
148
  return !this.building && this.failure === undefined;
140
149
  }
150
+ get hasSnapshot() { return this.hasScanned; }
141
151
  get progress() {
142
152
  // The percentage is deliberately not a promise about the whole tree: the total is unknown
143
153
  // until the scan ends, so it is derived from the directory budget instead, and the UI shows
@@ -150,17 +160,28 @@ export class FileNameIndex {
150
160
  // The guard is "has a scan been started", NOT "are there any entries". An EMPTY workspace
151
161
  // finishes its scan with zero entries, and an emptiness test would restart the scan on every
152
162
  // request - so the answer to every query would be "still building" forever.
163
+ if (!this.started || this.needsScan)
164
+ this.revalidate(root);
165
+ }
166
+ /** Keep the preceding results usable while checking files written outside Super Pi. */
167
+ revalidate(root) {
153
168
  if (this.building)
154
169
  return;
155
- if (this.started) {
156
- if (this.needsScan)
157
- this.reset(root);
158
- return;
170
+ if (this.root && this.root !== root) {
171
+ this.entries.clear();
172
+ this.hasScanned = false;
159
173
  }
174
+ this.unread = new Set(this.entries.keys());
175
+ this.removedDuringScan.clear();
176
+ this.directoriesReadDuringScan.clear();
177
+ this.root = root;
160
178
  this.needsScan = false;
161
179
  this.started = true;
162
- this.root = root;
163
180
  this.building = true;
181
+ this.failure = undefined;
182
+ this.incomplete = false;
183
+ this.stopped = false;
184
+ this.scanned = 0;
164
185
  void this.scan(++this.generation);
165
186
  }
166
187
  markStale() { if (this.started)
@@ -188,19 +209,6 @@ export class FileNameIndex {
188
209
  return;
189
210
  throw this.failure;
190
211
  }
191
- /** Rebuild from scratch. The ↻ button. */
192
- reset(root) {
193
- this.entries.clear();
194
- this.removedDuringScan.clear();
195
- this.directoriesReadDuringScan.clear();
196
- this.scanned = 0;
197
- this.incomplete = false;
198
- this.stopped = false;
199
- this.building = false;
200
- this.started = false;
201
- this.failure = undefined;
202
- this.start(root);
203
- }
204
212
  /** Record a path that appeared or changed. Used for agent writes and user saves. */
205
213
  upsert(relativePath, kind = "file", openLink) {
206
214
  const path = relativePath.replace(/\\/g, "/").replace(/^\/+/, "");
@@ -209,6 +217,7 @@ export class FileNameIndex {
209
217
  const cut = path.lastIndexOf("/");
210
218
  const name = cut < 0 ? path : path.slice(cut + 1);
211
219
  const directory = cut < 0 ? "" : path.slice(0, cut);
220
+ this.unread.delete(path);
212
221
  this.entries.set(path, { path, name, directory, kind, ...(openLink ? { openLink } : {}) });
213
222
  }
214
223
  /** Forget a path that is gone. */
@@ -247,21 +256,44 @@ export class FileNameIndex {
247
256
  * `app` return every file in `application/` as well - a result set nobody can read.
248
257
  */
249
258
  search(needle, linksOnly = false) {
250
- const query = needle.trim().toLowerCase();
259
+ const normalized = needle.trim().replaceAll("\\", "/").replace(/^\.\//u, "");
260
+ const query = normalized.toLowerCase();
251
261
  if (!query) {
252
262
  return { hits: [], total: 0, indexed: this.indexed, progress: this.progress, incomplete: this.incomplete };
253
263
  }
254
264
  const hits = [];
265
+ const withDirectory = query.includes("/");
255
266
  for (const entry of this.entries.values()) {
256
267
  if (entry.kind !== "file" || linksOnly && !entry.openLink)
257
268
  continue;
258
- if (entry.name.toLowerCase().includes(query))
269
+ if (linksOnly || (withDirectory ? entry.path : entry.name).toLowerCase().includes(query))
259
270
  hits.push(entry);
260
271
  }
261
- hits.sort((a, b) => compareNameHits(a, b, query));
272
+ if (withDirectory && !linksOnly) {
273
+ hits.sort((a, b) => Number(b.path === normalized) - Number(a.path === normalized)
274
+ || Number(b.path.toLowerCase() === query) - Number(a.path.toLowerCase() === query) || compareNameHits(a, b, query));
275
+ }
276
+ else if (!linksOnly)
277
+ hits.sort((a, b) => compareNameHits(a, b, query));
278
+ const results = linksOnly ? matchPathMentions(hits, query, 100) : hits;
262
279
  return {
263
- hits,
264
- total: hits.length,
280
+ hits: results,
281
+ total: results.length,
282
+ indexed: this.indexed,
283
+ progress: this.progress,
284
+ incomplete: this.incomplete,
285
+ };
286
+ }
287
+ searchQuickOpen(query, offset) {
288
+ const files = [...this.entries.values()].filter(entry => entry.kind === "file");
289
+ const ranked = query ? rankPathMatches(files, query) : files;
290
+ if (query && !ranked.length && this.indexed) {
291
+ const approximate = new Fuse(files, { keys: ["path"], threshold: 0.38, ignoreLocation: true });
292
+ ranked.push(...approximate.search(query, { limit: QUICK_OPEN_PAGE_SIZE }).map(match => match.item));
293
+ }
294
+ return {
295
+ hits: ranked.slice(offset, offset + (query ? QUICK_OPEN_PAGE_SIZE : 20)),
296
+ total: ranked.length,
265
297
  indexed: this.indexed,
266
298
  progress: this.progress,
267
299
  incomplete: this.incomplete,
@@ -302,78 +334,66 @@ export class FileNameIndex {
302
334
  * Link names can be found, and linked directories never enter this traversal's queue.
303
335
  */
304
336
  async scan(generation) {
305
- const started = Date.now();
306
337
  const guard = createRootGuard(this.root);
307
338
  const queue = [""];
308
- while (queue.length) {
339
+ let count = 0;
340
+ scan: for (let next = 0; next < queue.length;) {
309
341
  if (this.stopped || generation !== this.generation)
310
342
  return;
311
- const directory = queue.shift();
312
- if (this.scanned >= MAX_DIRECTORIES) {
343
+ const batch = queue.slice(next, Math.min(next + DIRECTORY_BATCH, MAX_DIRECTORIES));
344
+ if (!batch.length) {
313
345
  this.incomplete = true;
314
346
  break;
315
347
  }
316
- this.scanned += 1;
317
- let entries;
318
- try {
319
- entries = await readdir(await guard(directory), { withFileTypes: true });
320
- }
321
- catch (error) {
322
- if (generation !== this.generation || this.stopped)
323
- return;
324
- // THE ROOT IS NOT ONE OF THE SKIPPABLE DIRECTORIES.
325
- //
326
- // A workspace whose directory is gone must answer 404 `workspace_missing`, and the reason is
327
- // the one this file's own `incomplete` flag cannot express: "I searched and found nothing"
328
- // and "there was nothing to search" are DIFFERENT answers, and only one of them is true.
329
- // The old walk rethrew the root's failure and the route turned it into a 404; swallowing it
330
- // here would put that exact bug back - a 200 with an empty list, which is byte-for-byte the
331
- // response for "your search matched nothing".
332
- //
333
- // The failure is RECORDED, not thrown: see `failure` above for why throwing it here would
334
- // take the whole server down with it.
335
- //
336
- // A SUBDIRECTORY that cannot be read is skipped instead: one unreadable folder in a large
337
- // tree must not cost the reader every other match, and the scan says so through
338
- // `incomplete` rather than by pretending the folder was empty.
339
- if (directory === "") {
340
- this.failure = error;
341
- this.building = false;
342
- return;
343
- }
344
- this.incomplete = true;
345
- continue;
346
- }
347
- if (generation !== this.generation || this.stopped)
348
+ next += batch.length;
349
+ const listings = await Promise.allSettled(batch.map(async (directory) => readdir(await guard(directory), { withFileTypes: true })));
350
+ if (this.stopped || generation !== this.generation)
348
351
  return;
349
- for (const entry of entries) {
350
- const relative = directory ? `${directory}/${entry.name}` : entry.name;
351
- if (explorerInternalPath(this.cwd ? `${this.cwd}/${relative}` : relative) || blockedBy(relative, this.removedDuringScan)
352
- || !matchesDirectoryReads(relative, this.directoriesReadDuringScan))
353
- continue;
354
- if (entry.isDirectory()) {
355
- this.entries.set(relative, { path: relative, name: entry.name, directory, kind: "directory" });
356
- queue.push(relative);
352
+ for (const [index, listing] of listings.entries()) {
353
+ const directory = batch[index];
354
+ this.scanned += 1;
355
+ if (listing.status === "rejected") {
356
+ if (!directory) {
357
+ this.failure = listing.reason;
358
+ this.building = false;
359
+ this.unread.clear();
360
+ return;
361
+ }
362
+ this.incomplete = true;
357
363
  continue;
358
364
  }
359
- const openLink = entry.isSymbolicLink() && await stat(resolve(this.root, relative)).then(info => info.isFile(), () => false);
360
- if (generation !== this.generation || this.stopped)
361
- return;
362
- if (openLink && (blockedBy(relative, this.removedDuringScan) || !matchesDirectoryReads(relative, this.directoriesReadDuringScan)))
363
- continue;
364
- if (!entry.isFile() && !openLink)
365
- continue;
366
- if (this.entries.size >= MAX_FILES) {
367
- this.incomplete = true;
368
- break;
365
+ for (const entry of listing.value) {
366
+ const relative = directory ? `${directory}/${entry.name}` : entry.name;
367
+ if (explorerInternalPath(this.cwd ? `${this.cwd}/${relative}` : relative) || blockedBy(relative, this.removedDuringScan)
368
+ || !matchesDirectoryReads(relative, this.directoriesReadDuringScan))
369
+ continue;
370
+ const isDirectory = entry.isDirectory();
371
+ const openLink = entry.isSymbolicLink() && await stat(resolve(this.root, relative)).then(info => info.isFile(), () => false);
372
+ if (generation !== this.generation || this.stopped)
373
+ return;
374
+ if (openLink && (blockedBy(relative, this.removedDuringScan) || !matchesDirectoryReads(relative, this.directoriesReadDuringScan)))
375
+ continue;
376
+ if (!isDirectory && !entry.isFile() && !openLink)
377
+ continue;
378
+ if (count >= MAX_ENTRIES) {
379
+ this.incomplete = true;
380
+ break scan;
381
+ }
382
+ count++;
383
+ this.unread.delete(relative);
384
+ this.entries.set(relative, { path: relative, name: entry.name, directory, kind: isDirectory ? "directory" : "file",
385
+ ...(openLink ? { openLink: true } : {}) });
386
+ if (isDirectory)
387
+ queue.push(relative);
369
388
  }
370
- this.entries.set(relative, { path: relative, name: entry.name, directory, kind: "file", ...(openLink ? { openLink: true } : {}) });
371
389
  }
372
- // Yield between directories so a large tree does not monopolise the event loop and starve
373
- // the WebSocket heartbeat. `setTimeout(0)` is the cheapest yield that still lets timers run.
374
- if (Date.now() - started > 0 && queue.length)
375
- await new Promise((resolve) => setTimeout(resolve, 0));
376
390
  }
391
+ if (!this.incomplete) {
392
+ for (const path of this.unread)
393
+ this.entries.delete(path);
394
+ }
395
+ this.unread.clear();
396
+ this.hasScanned = true;
377
397
  this.building = false;
378
398
  this.removedDuringScan.clear();
379
399
  this.directoriesReadDuringScan.clear();
@@ -1,5 +1,5 @@
1
1
  import type { GitCommitDetail } from "../shared/git-commit.js";
2
- import type { GitGraphPage } from "../shared/git-graph.js";
2
+ import type { GitGraphResponse } from "../shared/git-graph.js";
3
3
  export type GitWorkspace = {
4
4
  branch: string | null;
5
5
  detached: boolean;
@@ -26,7 +26,7 @@ export declare function gitLog(root: string, limit: number, cwd?: string, query?
26
26
  }[];
27
27
  truncated: boolean;
28
28
  }>;
29
- export declare function gitGraph(root: string, limit: number, offset: number, snapshot: string, after: string): Promise<GitGraphPage>;
29
+ export declare function gitGraph(root: string, limit: number, offset: number, snapshot: string, after: string, knownSnapshot?: string): Promise<GitGraphResponse>;
30
30
  export declare function gitCommit(root: string, cwd: string, hash: string): Promise<GitCommitDetail>;
31
31
  export declare function gitCommitDiff(root: string, cwd: string, hash: string, path: string, fullContext?: boolean): Promise<{
32
32
  path: string;
@@ -83,7 +83,7 @@ function parseGitCommits(raw) {
83
83
  return commits;
84
84
  }
85
85
  const COMMIT_HASH = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
86
- export async function gitGraph(root, limit, offset, snapshot, after) {
86
+ export async function gitGraph(root, limit, offset, snapshot, after, knownSnapshot = "") {
87
87
  const size = pageNumber(limit, 50, 1, 100);
88
88
  const start = pageNumber(offset, 0, 0, 2_147_483_647);
89
89
  const repo = await worktreeRoot(root);
@@ -97,6 +97,8 @@ export async function gitGraph(root, limit, offset, snapshot, after) {
97
97
  const changed = () => gitFailure("提交图已变化,请刷新后继续查看。", "graph_changed");
98
98
  if (start && snapshot !== version)
99
99
  throw changed();
100
+ if (!start && knownSnapshot === version)
101
+ return { unchanged: true, snapshot: version };
100
102
  const labels = new Map();
101
103
  const mark = (hash, label) => {
102
104
  const list = labels.get(hash) ?? [];
@@ -26,7 +26,7 @@ import { MAX_WEB_REQUEST_BYTES } from "./web.js";
26
26
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
27
27
  import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateArgs, recordUpdateOutcome, releaseUpdateSlot, shellArgs } from "./update.js";
28
28
  import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
29
- import { ensureNameIndex, recordWorkspacePath } from "./file-name-index.js";
29
+ import { ensureNameIndex, QUICK_OPEN_PAGE_SIZE, recordWorkspacePath } from "./file-name-index.js";
30
30
  import { resolveFileCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
31
31
  import { explorerInternalPath, explorerPath, inspectWorkspaceUpload, listWorkspaceTrash, MAX_WORKSPACE_UPLOAD_BYTES, mutateWorkspaceTree, serializeWorkspaceWrite, uploadWorkspaceFile } from "./workspace-file-operations.js";
32
32
  import { readWorkspaceDocumentPreview, respondWithWorkspaceFile } from "./workspace-file-response.js";
@@ -1433,7 +1433,7 @@ export function createHttpServer(options) {
1433
1433
  if (op === "status")
1434
1434
  json(200, await gitStatus(workspace.path, cwd));
1435
1435
  else if (op === "graph") {
1436
- json(200, await gitGraph(workspace.path, Number(url.searchParams.get("limit") ?? 50), Number(url.searchParams.get("offset") ?? 0), url.searchParams.get("snapshot") ?? "", url.searchParams.get("after") ?? ""));
1436
+ json(200, await gitGraph(workspace.path, Number(url.searchParams.get("limit") ?? 50), Number(url.searchParams.get("offset") ?? 0), url.searchParams.get("snapshot") ?? "", url.searchParams.get("after") ?? "", url.searchParams.get("knownSnapshot") ?? ""));
1437
1437
  }
1438
1438
  else if (op === "log" || op === "branches" || op === "stash") {
1439
1439
  const query = url.searchParams.get("q") ?? "";
@@ -2797,6 +2797,25 @@ export function createHttpServer(options) {
2797
2797
  }
2798
2798
  return;
2799
2799
  }
2800
+ if (url.pathname === "/api/session-search") {
2801
+ if (request.method !== "GET") {
2802
+ json(405, { error: "会话搜索需要 GET 请求。" });
2803
+ return;
2804
+ }
2805
+ const workspaceId = url.searchParams.get("workspaceId")?.trim();
2806
+ const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
2807
+ if (!workspaceId || !workspace || workspace.closedAt) {
2808
+ json(404, { error: "请先选择有效工作区。" });
2809
+ return;
2810
+ }
2811
+ const query = url.searchParams.get("q")?.trim() ?? "";
2812
+ if (query.length > 256 || /[\r\n]/.test(query)) {
2813
+ json(400, { error: "搜索词只能是一行,且不超过 256 个字符。" });
2814
+ return;
2815
+ }
2816
+ json(200, query ? store.searchConversationMessages(workspaceId, query) : { hits: [], truncated: false });
2817
+ return;
2818
+ }
2800
2819
  if (url.pathname === "/api/files/search") {
2801
2820
  const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body)); };
2802
2821
  try {
@@ -2954,41 +2973,34 @@ export function createHttpServer(options) {
2954
2973
  json(405, { error: "目录列表需要 GET 请求。", code: "method" });
2955
2974
  return;
2956
2975
  }
2957
- const query = url.searchParams.get("q");
2958
- if (query !== null && query.trim() !== "") {
2959
- // THE SEARCH IS AN INDEX QUERY, not a walk.
2960
- //
2961
- // The old path re-walked the entire tree on every keystroke and then reported its own
2962
- // limits ("已跳过 N 个目录", "结果不完整"). The index answers from memory - no filesystem
2963
- // access at all - and covers every directory in the workspace, so there is nothing to
2964
- // report a limit about. `truncated` and `skipped` stay in the response so the protocol
2965
- // shape does not change under the client, but they are now constants that say the
2966
- // opposite of what they used to.
2976
+ const query = url.searchParams.get("q")?.trim();
2977
+ const quick = url.searchParams.get("quick") === "1";
2978
+ if (query !== undefined && (query || quick)) {
2979
+ const page = Number(url.searchParams.get("page") ?? 0);
2980
+ if (quick && (query.length > 8192 || !Number.isSafeInteger(page) || page < 0 || page > Math.floor(Number.MAX_SAFE_INTEGER / QUICK_OPEN_PAGE_SIZE))) {
2981
+ json(400, { error: "文件查找请求无效。", code: "bad_query" });
2982
+ return;
2983
+ }
2967
2984
  const index = nameIndexFor(context, workspaceId, root, cwd);
2968
- // THE WORKSPACE MUST EXIST, AND THE INDEX IS WHAT KNOWS.
2969
- //
2970
- // The background scan records a root it could not read rather than throwing it - a scan
2971
- // has no caller to receive a rejection, and an unhandled one terminates the process. So
2972
- // the route asks the index what happened and turns the answer into the status it
2973
- // deserves. Without this a workspace whose directory is gone would answer 200 with an
2974
- // empty list, which is byte-for-byte the response for "your search matched nothing" -
2975
- // the exact confusion this endpoint is supposed to avoid.
2976
- await index.waitUntilIndexed(4000);
2985
+ const refresh = url.searchParams.get("refresh") === "1";
2986
+ if (refresh)
2987
+ index.revalidate(root);
2988
+ // A warm picker can use known results while refresh works through the remaining paths.
2989
+ if (!quick)
2990
+ await index.waitUntilIndexed(4000);
2991
+ else if (!refresh && !index.hasSnapshot)
2992
+ await index.waitUntilIndexed(800);
2977
2993
  index.throwIfBroken();
2978
- // WAIT FOR THE INDEX, briefly. A search answered from a half-built map would say "no
2979
- // matches" for files that are on disk - which is precisely the "搜不出他想搜的东西"
2980
- // failure this work exists to remove. Past the deadline the answer is still returned, with
2981
- // `indexed: false` so the UI can say the index is still building rather than pretending
2982
- // the tree is empty.
2983
2994
  const linksOnly = url.searchParams.get("links") === "1";
2984
- const result = index.search(query, linksOnly);
2985
- const hits = linksOnly ? result.hits.slice(0, 20) : result.hits;
2995
+ const offset = page * QUICK_OPEN_PAGE_SIZE;
2996
+ const result = quick ? index.searchQuickOpen(query, offset) : index.search(query, linksOnly);
2997
+ const hits = !quick && linksOnly ? result.hits.slice(0, 20) : result.hits;
2986
2998
  json(200, {
2987
2999
  mode: "search",
2988
3000
  query: query.trim(),
2989
3001
  hits: hits.map(({ path, name, directory, openLink }) => ({ path, name, directory, ...(openLink ? { openLink } : {}) })),
2990
3002
  total: result.total,
2991
- truncated: hits.length < result.total,
3003
+ truncated: (quick ? offset : 0) + hits.length < result.total,
2992
3004
  skipped: [],
2993
3005
  indexed: result.indexed,
2994
3006
  progress: result.progress,
@@ -1,3 +1,4 @@
1
+ import { type SessionSearchResult } from "../shared/session-search.js";
1
2
  import type { AppStateRepository } from "./persistence/app-state-repository.js";
2
3
  import { defaultJsonStatePath } from "./persistence/json-state-repository.js";
3
4
  import type { ScheduledTask } from "./scheduled-tasks.js";
@@ -182,6 +183,7 @@ export declare class Store {
182
183
  snapshot(): AppState;
183
184
  /** Cheap scalar/entity reads for hot paths. Never expose the live mutable state object. */
184
185
  hasWorkspace(workspaceId: string): boolean;
186
+ searchConversationMessages(workspaceId: string, query: string): SessionSearchResult;
185
187
  conversationStatus(conversationId: string): Conversation["status"] | undefined;
186
188
  question(conversationId: string, messageId: string, index: number): ToolCallQuestion | undefined;
187
189
  pendingQuestion(conversationId: string): {
@@ -1,3 +1,4 @@
1
+ import { SESSION_SEARCH_LIMIT } from "../shared/session-search.js";
1
2
  import { rename } from "node:fs/promises";
2
3
  import { JsonStateRepository, defaultJsonStatePath } from "./persistence/json-state-repository.js";
3
4
  import { normalizeTodos } from "./task-tool.js";
@@ -1078,6 +1079,35 @@ export class Store {
1078
1079
  hasWorkspace(workspaceId) {
1079
1080
  return this.state.workspaces.some((workspace) => workspace.id === workspaceId);
1080
1081
  }
1082
+ searchConversationMessages(workspaceId, query) {
1083
+ const literal = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu");
1084
+ const sessions = this.state.conversations
1085
+ .filter(item => item.workspaceId === workspaceId && !item.archivedAt && !item.warmSession)
1086
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
1087
+ const hits = [];
1088
+ for (const session of sessions) {
1089
+ for (let index = session.messages.length - 1; index >= 0; index--) {
1090
+ const { id, content, role, delivery } = session.messages[index];
1091
+ if (delivery || (role !== "user" && role !== "assistant"))
1092
+ continue;
1093
+ const match = literal.exec(content);
1094
+ if (!match)
1095
+ continue;
1096
+ if (hits.length === SESSION_SEARCH_LIMIT)
1097
+ return { hits, truncated: true };
1098
+ const start = Math.max(0, match.index - 72);
1099
+ const endOfMatch = match.index + match[0].length;
1100
+ const end = Math.min(content.length, endOfMatch + 96);
1101
+ hits.push({
1102
+ conversationId: session.id, title: session.title, messageId: id, role,
1103
+ before: (start ? "…" : "") + content.slice(start, match.index),
1104
+ match: match[0],
1105
+ after: content.slice(endOfMatch, end) + (end < content.length ? "…" : ""),
1106
+ });
1107
+ }
1108
+ }
1109
+ return { hits, truncated: false };
1110
+ }
1081
1111
  conversationStatus(conversationId) {
1082
1112
  return this.state.conversations.find((conversation) => conversation.id === conversationId)?.status;
1083
1113
  }
@@ -9,7 +9,8 @@ export interface MentionToken {
9
9
  }
10
10
  /** Only a standalone @ token opens completion; email addresses and escaped @ stay literal. */
11
11
  export declare function findMentionToken(text: string, caret: number, selectionEnd?: number): MentionToken | undefined;
12
- export declare function matchPathMentions(entries: Iterable<PathMentionEntry>, query: string, limit?: number): PathMentionEntry[];
12
+ export declare function rankPathMatches<T extends PathMentionEntry>(entries: Iterable<T>, query: string): T[];
13
+ export declare function matchPathMentions<T extends PathMentionEntry>(entries: Iterable<T>, query: string, limit?: number): T[];
13
14
  export declare function insertPathMention(text: string, token: MentionToken, entry: PathMentionEntry): {
14
15
  text: string;
15
16
  caret: number;
@@ -13,6 +13,8 @@ export function findMentionToken(text, caret, selectionEnd = caret) {
13
13
  /** Ordered-character matching supports abbreviations such as sct -> src/client/theme.tsx. */
14
14
  function fuzzyScore(path, query) {
15
15
  const name = path.slice(path.lastIndexOf("/") + 1);
16
+ if (path === query)
17
+ return -1;
16
18
  if (name === query)
17
19
  return 0;
18
20
  if (name.startsWith(query))
@@ -31,19 +33,23 @@ function fuzzyScore(path, query) {
31
33
  }
32
34
  return 50 + gaps / Math.max(1, path.length);
33
35
  }
34
- export function matchPathMentions(entries, query, limit = 30) {
35
- const needle = query.trim().replaceAll("\\", "/").toLowerCase();
36
+ export function rankPathMatches(entries, query) {
37
+ const normalized = query.trim().replaceAll("\\", "/");
38
+ const needle = normalized.toLowerCase();
36
39
  const matches = [];
37
40
  for (const entry of entries) {
38
41
  if (!entry.path || entry.path.startsWith("/") || /^[a-z]:/iu.test(entry.path) || entry.path.split("/").includes(".."))
39
42
  continue;
40
43
  const path = entry.path.toLowerCase();
41
- const score = needle ? fuzzyScore(path, needle) : 0;
44
+ const score = needle ? entry.path === normalized ? -2 : fuzzyScore(path, needle) : 0;
42
45
  if (score !== undefined)
43
46
  matches.push({ entry, score, depth: entry.path.split("/").length });
44
47
  }
45
48
  matches.sort((a, b) => a.score - b.score || a.depth - b.depth || Number(b.entry.kind === "directory") - Number(a.entry.kind === "directory") || (a.entry.path < b.entry.path ? -1 : a.entry.path > b.entry.path ? 1 : 0));
46
- return matches.slice(0, Math.max(0, Math.min(100, limit))).map(item => item.entry);
49
+ return matches.map(item => item.entry);
50
+ }
51
+ export function matchPathMentions(entries, query, limit = 30) {
52
+ return rankPathMatches(entries, query).slice(0, Math.max(0, Math.min(100, limit)));
47
53
  }
48
54
  export function insertPathMention(text, token, entry) {
49
55
  const path = entry.path + (entry.kind === "directory" && !entry.path.endsWith("/") ? "/" : "");
@@ -12,6 +12,10 @@ export type GitGraphCommit = {
12
12
  date: string;
13
13
  refs: GitGraphRef[];
14
14
  };
15
+ export type GitGraphResponse = GitGraphPage | {
16
+ unchanged: true;
17
+ snapshot: string;
18
+ };
15
19
  export type GitGraphPage = {
16
20
  commits: GitGraphCommit[];
17
21
  snapshot: string;