@evandu/super-pi 0.1.223 → 0.1.224

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.
Files changed (48) hide show
  1. package/dist/client/.super-pi-client-sources.json +10 -7
  2. package/dist/client/assets/{CodeMirrorEditor-Due3YL4A.js → CodeMirrorEditor-CophJ9Eb.js} +2 -2
  3. package/dist/client/assets/{dist-B3qtMidG.js → dist-BGVYvXYo.js} +1 -1
  4. package/dist/client/assets/{dist-Po3GdueN.js → dist-BYjXg164.js} +1 -1
  5. package/dist/client/assets/{dist-CQIMZ_7M.js → dist-BxcN7lnR.js} +1 -1
  6. package/dist/client/assets/{dist-DCVXoyno.js → dist-C0s45hG8.js} +1 -1
  7. package/dist/client/assets/{dist-Cw21UX77.js → dist-C3BgT3PU.js} +1 -1
  8. package/dist/client/assets/{dist-CMws1R9h.js → dist-C3amppza.js} +1 -1
  9. package/dist/client/assets/{dist-BJ_pU8qp.js → dist-C8FqYuNv.js} +1 -1
  10. package/dist/client/assets/{dist-1hXEE44f.js → dist-CEbbDGoy.js} +1 -1
  11. package/dist/client/assets/{dist-BJ5mZEGq.js → dist-CFMeFXLU.js} +1 -1
  12. package/dist/client/assets/{dist-BaUqm3zx.js → dist-CMPtWQjx.js} +1 -1
  13. package/dist/client/assets/{dist-JSFnHR0P.js → dist-Ch4dVwk4.js} +1 -1
  14. package/dist/client/assets/{dist-CRrYz-2t.js → dist-Clk6Knpv.js} +1 -1
  15. package/dist/client/assets/{dist-D2n9-vIx.js → dist-CxeSxC9m.js} +1 -1
  16. package/dist/client/assets/{dist-DSCSHwdP.js → dist-D-s1GEbP.js} +1 -1
  17. package/dist/client/assets/{dist-CA52X7jm.js → dist-D7On6h3N.js} +1 -1
  18. package/dist/client/assets/{dist-2kMlRtqo.js → dist-DBdR1Wph.js} +1 -1
  19. package/dist/client/assets/{dist-BvUexO6W.js → dist-TcwefdPn.js} +1 -1
  20. package/dist/client/assets/{dist-DOJKt6Px.js → dist-ZuNGtw_8.js} +1 -1
  21. package/dist/client/assets/{dist-BHlGN5Cp.js → dist-i8fMtdTP.js} +1 -1
  22. package/dist/client/assets/{dist-B2XX-bBx.js → dist-nSNA_ze3.js} +1 -1
  23. package/dist/client/assets/{dist-BXTbngmK.js → dist-pVo8vQ15.js} +1 -1
  24. package/dist/client/assets/{dist-BZGq856v.js → dist-ukIdoKjd.js} +1 -1
  25. package/dist/client/assets/index-CoJT13t0.js +105 -0
  26. package/dist/client/assets/index-DK_mME9e.css +1 -0
  27. package/dist/client/index.html +2 -2
  28. package/dist/server/application/run-service.js +44 -17
  29. package/dist/server/file-index.d.ts +13 -1
  30. package/dist/server/file-index.js +108 -12
  31. package/dist/server/file-name-index.d.ts +8 -0
  32. package/dist/server/file-name-index.js +58 -11
  33. package/dist/server/files.js +4 -0
  34. package/dist/server/http-server.js +142 -16
  35. package/dist/server/session-cwd.d.ts +2 -0
  36. package/dist/server/session-cwd.js +16 -1
  37. package/dist/server/types.d.ts +4 -0
  38. package/dist/server/workspace-file-indexes.d.ts +2 -0
  39. package/dist/server/workspace-file-indexes.js +61 -0
  40. package/dist/server/workspace-file-operations.d.ts +36 -0
  41. package/dist/server/workspace-file-operations.js +281 -0
  42. package/dist/server/workspace-file-response.d.ts +3 -0
  43. package/dist/server/workspace-file-response.js +79 -0
  44. package/dist/shared/workspace-file-preview.d.ts +4 -0
  45. package/dist/shared/workspace-file-preview.js +28 -0
  46. package/package.json +2 -1
  47. package/dist/client/assets/index-DHdzZ1mf.js +0 -103
  48. package/dist/client/assets/index-OmaD3l6r.css +0 -1
@@ -8,8 +8,8 @@
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-DHdzZ1mf.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-OmaD3l6r.css">
11
+ <script type="module" crossorigin src="/assets/index-CoJT13t0.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DK_mME9e.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -9,12 +9,15 @@ import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
9
9
  import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
10
10
  import { describeThrownWithStack } from "../failure-text.js";
11
11
  import { toWorkspaceRelative } from "../files.js";
12
- import { refreshWorkspaceIndex } from "../file-index.js";
12
+ import { inScope, refreshWorkspaceIndex } from "../file-index.js";
13
13
  import { resolveSessionCwd } from "../session-cwd.js";
14
14
  import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
15
15
  import { execFile } from "node:child_process";
16
16
  import { promisify } from "node:util";
17
17
  import { randomUUID } from "node:crypto";
18
+ import { isAbsolute, resolve } from "node:path";
19
+ import { lstat } from "node:fs/promises";
20
+ import { explorerPath, serializeWorkspaceWrite } from "../workspace-file-operations.js";
18
21
  const execFileAsync = promisify(execFile);
19
22
  /**
20
23
  * Validates a caller-supplied delivery mode without silently falling back on bogus values.
@@ -1392,6 +1395,7 @@ export class RunService {
1392
1395
  * back as a path with one space.
1393
1396
  */
1394
1397
  const fileWritePaths = new Map();
1398
+ let runCwd = workspace.path;
1395
1399
  const onFileWrite = (path, _toolName, toolCallId) => {
1396
1400
  if (!acceptsEvent("file.write"))
1397
1401
  return;
@@ -1410,17 +1414,16 @@ export class RunService {
1410
1414
  // it right, while the name index stored the absolute path with its leading slash stripped
1411
1415
  // (`home/me/project/src/a.ts`) - an entry that matched by name and then pointed at a file that
1412
1416
  // does not exist.
1413
- const relative = toWorkspaceRelative(workspace.path, path);
1414
- tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
1415
- refreshWorkspaceIndex(this.fileIndexes, workspace.id, relative, workspace.path);
1416
- // The name index learns about the write as well, so the file the agent just created is
1417
- // findable by name straight away rather than after the next background scan. It goes through
1418
- // the SAME `ensureNameIndex` the HTTP layer uses, so there is one index per workspace rather
1419
- // than one per layer.
1420
- if (this.nameIndexes) {
1421
- ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1422
- recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, relative);
1417
+ let relative;
1418
+ try {
1419
+ relative = toWorkspaceRelative(workspace.path, isAbsolute(path) ? path : resolve(runCwd, path));
1420
+ }
1421
+ catch {
1422
+ return;
1423
1423
  }
1424
+ if (!relative)
1425
+ return;
1426
+ tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
1424
1427
  if (toolCallId)
1425
1428
  fileWritePaths.set(toolCallId, relative);
1426
1429
  this.broadcastFileChanges(workspace.id);
@@ -1524,14 +1527,37 @@ export class RunService {
1524
1527
  const writtenPath = call.id ? fileWritePaths.get(call.id) : undefined;
1525
1528
  if (writtenPath) {
1526
1529
  this.fileChanges?.confirm(workspace.id, writtenPath, workspace.path);
1527
- refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
1528
- if (this.nameIndexes) {
1529
- ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1530
- recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
1531
- }
1532
1530
  if (call.id)
1533
1531
  fileWritePaths.delete(call.id);
1534
1532
  this.broadcastFileChanges(workspace.id);
1533
+ void serializeWorkspaceWrite(workspace.path, async () => {
1534
+ const target = await explorerPath(workspace.path, workspace.path, writtenPath);
1535
+ const info = await lstat(target).catch((error) => {
1536
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR")
1537
+ throw error;
1538
+ });
1539
+ refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
1540
+ if (this.nameIndexes && info?.isFile()) {
1541
+ ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1542
+ recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
1543
+ }
1544
+ else if (!info)
1545
+ for (const index of this.nameIndexes?.values() ?? []) {
1546
+ if (index.workspaceId !== workspace.id)
1547
+ continue;
1548
+ const target = inScope(workspace.path, index.cwd, writtenPath);
1549
+ if (target)
1550
+ index.removeTree(target);
1551
+ }
1552
+ this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id, paths: [writtenPath] });
1553
+ }).catch((error) => {
1554
+ if (error && typeof error === "object" && "status" in error && error.status === 403)
1555
+ return;
1556
+ console.warn("Super Pi: could not update the workspace file tree", error);
1557
+ });
1558
+ }
1559
+ else if (/^(bash|powershell|shell|command|apply_patch|write|edit)$/i.test(call.name)) {
1560
+ this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id });
1535
1561
  }
1536
1562
  const index = call.id ? rowByToolCallId.get(call.id) : undefined;
1537
1563
  if (index === undefined)
@@ -1605,11 +1631,12 @@ export class RunService {
1605
1631
  return pendingTools;
1606
1632
  };
1607
1633
  try {
1634
+ runCwd = await resolveSessionCwd(workspace.path, conversation.cwd);
1608
1635
  for await (const delta of this.runtime.answer({
1609
1636
  conversation,
1610
1637
  prompt,
1611
1638
  signal: controller.signal,
1612
- cwd: await resolveSessionCwd(workspace.path, conversation.cwd),
1639
+ cwd: runCwd,
1613
1640
  host: {
1614
1641
  notify: (request) => { if (acceptsEvent("ui.notify"))
1615
1642
  uiHost.notify(request); },
@@ -1,4 +1,8 @@
1
- import { type FileMeta } from "./files.js";
1
+ import { type DirEntry, type FileMeta } from "./files.js";
2
+ export declare function belowPath(path: string, parent: string): boolean;
3
+ export declare function inScope(workspaceRoot: string, cwd: string, path: string): string | undefined;
4
+ export declare function blockedBy(path: string, blocked: ReadonlySet<string>): boolean;
5
+ export declare function matchesDirectoryReads(path: string, snapshots: ReadonlyMap<string, ReadonlySet<string>>): boolean;
2
6
  export type IndexedFile = {
3
7
  path: string;
4
8
  kind: "file" | "directory";
@@ -40,12 +44,17 @@ export declare class FileIndex {
40
44
  private root;
41
45
  private queue;
42
46
  private building;
47
+ private needsScan;
43
48
  private skipped;
49
+ private readonly touched;
50
+ private readonly removedDuringScan;
51
+ private readonly directoriesReadDuringScan;
44
52
  version: number;
45
53
  builtAt: number;
46
54
  complete: boolean;
47
55
  constructor(workspaceId: string, broadcast: (event: FileIndexEvent) => void, cwd?: string);
48
56
  start(root: string): void;
57
+ markStale(): void;
49
58
  stop(): void;
50
59
  snapshot(since?: number): FileIndexSnapshot;
51
60
  /**
@@ -66,6 +75,9 @@ export declare class FileIndex {
66
75
  * caller's file API operation has already passed the sole containment guard and read this metadata. */
67
76
  recordFile(path: string, meta: FileMeta, mtimeMs?: number): void;
68
77
  remove(path: string): void;
78
+ removeTree(path: string): void;
79
+ recordEntries(entries: Pick<IndexedFile, "path" | "kind">[]): void;
80
+ reconcileDirectory(directory: string, entries: DirEntry[]): void;
69
81
  private scan;
70
82
  private publish;
71
83
  }
@@ -1,6 +1,34 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
- import { resolve } from "node:path";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { SEARCH_SKIP_DIRS, createRootGuard, fileMeta, isTextName, toRelative, toWorkspaceRelative } from "./files.js";
4
+ export function belowPath(path, parent) {
5
+ return !parent || path === parent || path.startsWith(`${parent}/`);
6
+ }
7
+ export function inScope(workspaceRoot, cwd, path) {
8
+ const local = relative(resolve(workspaceRoot, cwd), resolve(workspaceRoot, path));
9
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local))
10
+ return;
11
+ return local.split(sep).join("/");
12
+ }
13
+ export function blockedBy(path, blocked) {
14
+ if (blocked.has(""))
15
+ return true;
16
+ for (let prefix = path; prefix; prefix = prefix.slice(0, Math.max(0, prefix.lastIndexOf("/")))) {
17
+ if (blocked.has(prefix))
18
+ return true;
19
+ }
20
+ return false;
21
+ }
22
+ export function matchesDirectoryReads(path, snapshots) {
23
+ for (let entry = path; entry;) {
24
+ const parent = entry.slice(0, Math.max(0, entry.lastIndexOf("/")));
25
+ const present = snapshots.get(parent);
26
+ if (present && !present.has(entry))
27
+ return false;
28
+ entry = parent;
29
+ }
30
+ return true;
31
+ }
4
32
  const MAX_DIRECTORIES = 4000;
5
33
  const MAX_FILES = 30000;
6
34
  const MAX_MS = 4000;
@@ -19,7 +47,11 @@ export class FileIndex {
19
47
  root = "";
20
48
  queue = [];
21
49
  building = false;
50
+ needsScan = false;
22
51
  skipped = [];
52
+ touched = new Set();
53
+ removedDuringScan = new Set();
54
+ directoriesReadDuringScan = new Map();
23
55
  version = 0;
24
56
  builtAt = 0;
25
57
  complete = false;
@@ -29,20 +61,39 @@ export class FileIndex {
29
61
  this.cwd = cwd;
30
62
  }
31
63
  start(root) {
32
- if (this.building || this.builtAt)
64
+ if (this.building || (this.builtAt && !this.needsScan))
33
65
  return;
66
+ const replacing = !!this.builtAt;
67
+ this.needsScan = false;
34
68
  this.root = root;
35
69
  this.building = true;
70
+ this.complete = false;
71
+ this.skipped = [];
36
72
  this.queue = [""];
37
- void this.scan();
73
+ void this.scan(replacing);
38
74
  }
75
+ markStale() { if (this.root)
76
+ this.needsScan = true; }
39
77
  stop() { }
40
78
  snapshot(since) {
41
79
  const valid = Number.isFinite(since) && since !== undefined;
42
- const deltas = valid ? this.history.filter((item) => item.version > since) : [];
80
+ const changed = new Map();
81
+ const removed = new Set();
82
+ if (valid)
83
+ for (const item of this.history) {
84
+ if (item.version <= since)
85
+ continue;
86
+ for (const entry of item.changed) {
87
+ removed.delete(entry.path);
88
+ changed.set(entry.path, entry);
89
+ }
90
+ for (const path of item.removed) {
91
+ changed.delete(path);
92
+ removed.add(path);
93
+ }
94
+ }
43
95
  return { version: this.version, builtAt: this.builtAt, complete: this.complete, skipped: this.skipped,
44
- changed: valid ? deltas.flatMap((item) => item.changed) : [...this.entries.values()],
45
- removed: valid ? deltas.flatMap((item) => item.removed) : [] };
96
+ changed: valid ? [...changed.values()] : [...this.entries.values()], removed: [...removed] };
46
97
  }
47
98
  /**
48
99
  * ONE FILE, REFRESHED.
@@ -83,7 +134,7 @@ export class FileIndex {
83
134
  catch (error) {
84
135
  const code = error.code;
85
136
  if (code === "ENOENT" || code === "ENOTDIR")
86
- this.remove(key);
137
+ this.removeTree(key);
87
138
  else
88
139
  throw error;
89
140
  }
@@ -98,7 +149,39 @@ export class FileIndex {
98
149
  }
99
150
  remove(path) { if (this.entries.delete(path))
100
151
  this.publish([], [path]); }
101
- async scan() {
152
+ removeTree(path) {
153
+ if (this.building)
154
+ this.removedDuringScan.add(path);
155
+ const removed = [...this.entries.keys()].filter(key => belowPath(key, path));
156
+ for (const key of removed)
157
+ this.entries.delete(key);
158
+ this.publish([], removed);
159
+ }
160
+ recordEntries(entries) {
161
+ const changed = [];
162
+ for (const { path, kind } of entries) {
163
+ if (!path || path.split("/").some((segment, i, all) => SEARCH_SKIP_DIRS.has(segment) && (i < all.length - 1 || kind === "directory")))
164
+ continue;
165
+ if (this.entries.get(path)?.kind === kind)
166
+ continue;
167
+ changed.push({ path, kind, size: null, mtimeMs: null, etag: null, text: kind === "file" ? isTextName(path) : null });
168
+ }
169
+ this.publish(changed, []);
170
+ }
171
+ reconcileDirectory(directory, entries) {
172
+ const present = new Map(entries.map(entry => [entry.path, entry]));
173
+ if (this.building)
174
+ this.directoriesReadDuringScan.set(directory, new Set(entries.filter(entry => !entry.symlink && entry.kind !== "symlink").map(entry => entry.path)));
175
+ for (const [path, existing] of this.entries) {
176
+ if (path.slice(0, Math.max(0, path.lastIndexOf("/"))) !== directory)
177
+ continue;
178
+ const entry = present.get(path);
179
+ if (!entry || entry.symlink || entry.kind !== existing.kind)
180
+ this.removeTree(path);
181
+ }
182
+ this.recordEntries(entries.flatMap(entry => !entry.symlink && entry.kind !== "symlink" ? [{ path: entry.path, kind: entry.kind }] : []));
183
+ }
184
+ async scan(replacing) {
102
185
  const started = Date.now();
103
186
  let dirs = 0;
104
187
  let files = 0;
@@ -151,14 +234,25 @@ export class FileIndex {
151
234
  this.builtAt = Date.now();
152
235
  // Quick Open does not need per-directory progress. One final batch bounds WS traffic and keeps the
153
236
  // existing on-demand tree interactive throughout the scan (including dependency directories).
154
- this.publish(changed, [], true);
237
+ const scanned = changed.filter(entry => !this.touched.has(entry.path) && !blockedBy(entry.path, this.removedDuringScan)
238
+ && matchesDirectoryReads(entry.path, this.directoriesReadDuringScan));
239
+ const found = replacing && !incomplete ? new Set(scanned.map(entry => entry.path)) : undefined;
240
+ const removed = found ? [...this.entries.keys()].filter(path => !this.touched.has(path) && !found.has(path)) : [];
241
+ for (const path of removed)
242
+ this.entries.delete(path);
243
+ this.publish(scanned, removed, true, replacing);
244
+ this.touched.clear();
245
+ this.removedDuringScan.clear();
246
+ this.directoriesReadDuringScan.clear();
155
247
  }
156
- publish(changed, removed, force = false) {
248
+ publish(changed, removed, force = false, invalidateMetadata = false) {
157
249
  changed = changed.map((entry) => {
158
250
  // A targeted stat may race the cheap directory walk. Do not let the later readdir-only result erase
159
251
  // metadata that was already paid for and verified.
160
252
  const previous = this.entries.get(entry.path);
161
- const merged = previous?.kind === entry.kind && entry.size === null ? { ...entry, size: previous.size, mtimeMs: previous.mtimeMs, etag: previous.etag } : entry;
253
+ if (this.building)
254
+ this.touched.add(entry.path);
255
+ const merged = !invalidateMetadata && previous?.kind === entry.kind && entry.size === null ? { ...entry, size: previous.size, mtimeMs: previous.mtimeMs, etag: previous.etag } : entry;
162
256
  this.entries.set(entry.path, merged);
163
257
  return merged;
164
258
  });
@@ -192,7 +286,9 @@ export function refreshWorkspaceIndex(indexes, workspaceId, path, workspaceRoot)
192
286
  for (const index of indexes?.values() ?? []) {
193
287
  if (index.workspaceId !== workspaceId)
194
288
  continue;
195
- const target = workspaceRoot && index.cwd ? resolve(workspaceRoot, path) : path;
289
+ const target = workspaceRoot ? inScope(workspaceRoot, index.cwd, path) : path;
290
+ if (!target)
291
+ continue;
196
292
  void index.refresh(target).catch((error) => {
197
293
  console.warn(`Super Pi: the file index did not refresh ${path}: ${error instanceof Error ? error.message : "unknown error"}`);
198
294
  });
@@ -1,3 +1,4 @@
1
+ import { type DirEntry } from "./files.js";
1
2
  /**
2
3
  * THE INDEX FOR ONE WORKSPACE, created on demand and then kept.
3
4
  *
@@ -70,6 +71,10 @@ export declare class FileNameIndex {
70
71
  private scanned;
71
72
  private stopped;
72
73
  private incomplete;
74
+ private needsScan;
75
+ private generation;
76
+ private readonly removedDuringScan;
77
+ private readonly directoriesReadDuringScan;
73
78
  constructor(workspaceId: string, cwd?: string);
74
79
  /**
75
80
  * Whether the first pass has FINISHED.
@@ -85,6 +90,7 @@ export declare class FileNameIndex {
85
90
  get progress(): IndexProgress;
86
91
  /** Begin the background scan. Safe to call more than once; the second call is a no-op. */
87
92
  start(root: string): void;
93
+ markStale(): void;
88
94
  /**
89
95
  * WHY THE SCAN'S FAILURE IS RECORDED RATHER THAN THROWN.
90
96
  *
@@ -108,6 +114,8 @@ export declare class FileNameIndex {
108
114
  upsert(relativePath: string, kind?: "file" | "directory"): void;
109
115
  /** Forget a path that is gone. */
110
116
  remove(relativePath: string): void;
117
+ removeTree(path: string): void;
118
+ reconcileDirectory(directory: string, entries: DirEntry[]): void;
111
119
  /**
112
120
  * The query. A substring filter over an in-memory map - no filesystem access at all.
113
121
  *
@@ -32,8 +32,9 @@
32
32
  * replaces.
33
33
  */
34
34
  import { readdir } from "node:fs/promises";
35
- import { isAbsolute, relative, resolve, sep } from "node:path";
36
35
  import { createRootGuard, toRelative } from "./files.js";
36
+ import { belowPath, blockedBy, inScope, matchesDirectoryReads } from "./file-index.js";
37
+ import { explorerInternalPath } from "./workspace-file-operations.js";
37
38
  import { sessionScopeKey } from "./session-cwd.js";
38
39
  /**
39
40
  * THE INDEX FOR ONE WORKSPACE, created on demand and then kept.
@@ -54,14 +55,14 @@ export function ensureNameIndex(indexes, workspaceId, root, cwd = "") {
54
55
  }
55
56
  /** Keeps every root/subdirectory index for a workspace in step with one observed write. */
56
57
  export function recordWorkspacePath(indexes, workspaceId, workspaceRoot, path) {
57
- const absolute = resolve(workspaceRoot, path);
58
+ if (explorerInternalPath(path))
59
+ return;
58
60
  for (const index of indexes.values()) {
59
61
  if (index.workspaceId !== workspaceId)
60
62
  continue;
61
- const scoped = relative(resolve(workspaceRoot, index.cwd), absolute);
62
- if (!scoped || scoped === ".." || scoped.startsWith(`..${sep}`) || isAbsolute(scoped))
63
- continue;
64
- index.upsert(scoped.split(sep).join("/"));
63
+ const scoped = inScope(workspaceRoot, index.cwd, path);
64
+ if (scoped)
65
+ index.upsert(scoped);
65
66
  }
66
67
  }
67
68
  const MAX_DIRECTORIES = 20000;
@@ -115,6 +116,10 @@ export class FileNameIndex {
115
116
  scanned = 0;
116
117
  stopped = false;
117
118
  incomplete = false;
119
+ needsScan = false;
120
+ generation = 0;
121
+ removedDuringScan = new Set();
122
+ directoriesReadDuringScan = new Map();
118
123
  constructor(workspaceId, cwd = "") {
119
124
  this.workspaceId = workspaceId;
120
125
  this.cwd = cwd;
@@ -144,13 +149,21 @@ export class FileNameIndex {
144
149
  // The guard is "has a scan been started", NOT "are there any entries". An EMPTY workspace
145
150
  // finishes its scan with zero entries, and an emptiness test would restart the scan on every
146
151
  // request - so the answer to every query would be "still building" forever.
147
- if (this.started || this.building)
152
+ if (this.building)
153
+ return;
154
+ if (this.started) {
155
+ if (this.needsScan)
156
+ this.reset(root);
148
157
  return;
158
+ }
159
+ this.needsScan = false;
149
160
  this.started = true;
150
161
  this.root = root;
151
162
  this.building = true;
152
- void this.scan();
163
+ void this.scan(++this.generation);
153
164
  }
165
+ markStale() { if (this.started)
166
+ this.needsScan = true; }
154
167
  /**
155
168
  * WHY THE SCAN'S FAILURE IS RECORDED RATHER THAN THROWN.
156
169
  *
@@ -177,6 +190,8 @@ export class FileNameIndex {
177
190
  /** Rebuild from scratch. The ↻ button. */
178
191
  reset(root) {
179
192
  this.entries.clear();
193
+ this.removedDuringScan.clear();
194
+ this.directoriesReadDuringScan.clear();
180
195
  this.scanned = 0;
181
196
  this.incomplete = false;
182
197
  this.stopped = false;
@@ -201,6 +216,28 @@ export class FileNameIndex {
201
216
  this.entries.delete(path);
202
217
  // The directories that held it are still there; only the file itself is gone.
203
218
  }
219
+ removeTree(path) {
220
+ if (this.building)
221
+ this.removedDuringScan.add(path);
222
+ for (const key of this.entries.keys())
223
+ if (belowPath(key, path))
224
+ this.entries.delete(key);
225
+ }
226
+ reconcileDirectory(directory, entries) {
227
+ const present = new Map(entries.map(entry => [entry.path, entry]));
228
+ if (this.building)
229
+ this.directoriesReadDuringScan.set(directory, new Set(entries.filter(entry => !entry.symlink && entry.kind !== "symlink").map(entry => entry.path)));
230
+ for (const [path, existing] of this.entries) {
231
+ if (existing.directory !== directory)
232
+ continue;
233
+ const entry = present.get(path);
234
+ if (!entry || entry.symlink || entry.kind !== existing.kind)
235
+ this.removeTree(path);
236
+ }
237
+ for (const entry of entries)
238
+ if (!entry.symlink && entry.kind !== "symlink")
239
+ this.upsert(entry.path, entry.kind);
240
+ }
204
241
  /**
205
242
  * The query. A substring filter over an in-memory map - no filesystem access at all.
206
243
  *
@@ -264,13 +301,13 @@ export class FileNameIndex {
264
301
  * Symlinks are recorded but never followed - following one is how a scan becomes an infinite
265
302
  * walk, and a link inside the workspace is the one path the tree refuses to descend as well.
266
303
  */
267
- async scan() {
304
+ async scan(generation) {
268
305
  const started = Date.now();
269
306
  const guard = createRootGuard(this.root);
270
307
  const queue = [""];
271
308
  while (queue.length) {
272
- if (this.stopped)
273
- break;
309
+ if (this.stopped || generation !== this.generation)
310
+ return;
274
311
  const directory = queue.shift();
275
312
  if (this.scanned >= MAX_DIRECTORIES) {
276
313
  this.incomplete = true;
@@ -282,6 +319,8 @@ export class FileNameIndex {
282
319
  entries = await readdir(await guard(directory), { withFileTypes: true });
283
320
  }
284
321
  catch (error) {
322
+ if (generation !== this.generation || this.stopped)
323
+ return;
285
324
  // THE ROOT IS NOT ONE OF THE SKIPPABLE DIRECTORIES.
286
325
  //
287
326
  // A workspace whose directory is gone must answer 404 `workspace_missing`, and the reason is
@@ -305,10 +344,15 @@ export class FileNameIndex {
305
344
  this.incomplete = true;
306
345
  continue;
307
346
  }
347
+ if (generation !== this.generation || this.stopped)
348
+ return;
308
349
  for (const entry of entries) {
309
350
  if (entry.isSymbolicLink())
310
351
  continue;
311
352
  const relative = directory ? `${directory}/${entry.name}` : entry.name;
353
+ if (explorerInternalPath(this.cwd ? `${this.cwd}/${relative}` : relative) || blockedBy(relative, this.removedDuringScan)
354
+ || !matchesDirectoryReads(relative, this.directoriesReadDuringScan))
355
+ continue;
312
356
  if (entry.isDirectory()) {
313
357
  this.entries.set(relative, { path: relative, name: entry.name, directory, kind: "directory" });
314
358
  queue.push(relative);
@@ -328,9 +372,12 @@ export class FileNameIndex {
328
372
  await new Promise((resolve) => setTimeout(resolve, 0));
329
373
  }
330
374
  this.building = false;
375
+ this.removedDuringScan.clear();
376
+ this.directoriesReadDuringScan.clear();
331
377
  }
332
378
  /** Stop a running scan. Used when a workspace goes away. */
333
379
  stop() {
380
+ this.generation += 1;
334
381
  this.stopped = true;
335
382
  this.building = false;
336
383
  }
@@ -730,6 +730,10 @@ export function describe(error) {
730
730
  if (error instanceof FilesError)
731
731
  return { status: error.status, body: { error: error.message, code: error.code, ...(error.details ? { details: error.details } : {}) } };
732
732
  const code = error?.code;
733
+ if (code === "EEXIST" || code === "ENOTEMPTY")
734
+ return { status: 409, body: { error: "目标名称已存在。", code: "already_exists" } };
735
+ if (code === "EXDEV")
736
+ return { status: 409, body: { error: "这个位置位于另一文件系统,无法移动。", code: "different_filesystem" } };
733
737
  if (code === "EACCES" || code === "EPERM")
734
738
  return { status: 403, body: { error: "权限不足,无法访问该路径", code: "denied" } };
735
739
  if (code === "ELOOP")