@evandu/super-pi 0.1.222 → 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 (57) hide show
  1. package/dist/client/.super-pi-client-sources.json +12 -8
  2. package/dist/client/assets/{CodeMirrorEditor-IWcAz6oz.js → CodeMirrorEditor-CophJ9Eb.js} +2 -2
  3. package/dist/client/assets/{dist-D73UQVEK.js → dist-BGVYvXYo.js} +1 -1
  4. package/dist/client/assets/{dist-Bx-zvsek.js → dist-BYjXg164.js} +1 -1
  5. package/dist/client/assets/{dist-DglikBo1.js → dist-BxcN7lnR.js} +1 -1
  6. package/dist/client/assets/{dist-Cd2jBngi.js → dist-C0s45hG8.js} +1 -1
  7. package/dist/client/assets/{dist-DZFnjuKR.js → dist-C3BgT3PU.js} +1 -1
  8. package/dist/client/assets/{dist-B4YZqIKX.js → dist-C3amppza.js} +1 -1
  9. package/dist/client/assets/{dist-ChJliyoT.js → dist-C8FqYuNv.js} +1 -1
  10. package/dist/client/assets/{dist-Brmqe6G6.js → dist-CEbbDGoy.js} +1 -1
  11. package/dist/client/assets/{dist-DgRXONWV.js → dist-CFMeFXLU.js} +1 -1
  12. package/dist/client/assets/{dist-KddcFuL2.js → dist-CMPtWQjx.js} +1 -1
  13. package/dist/client/assets/{dist-DR-NR2sl.js → dist-Ch4dVwk4.js} +1 -1
  14. package/dist/client/assets/{dist-B2WzMUqb.js → dist-Clk6Knpv.js} +1 -1
  15. package/dist/client/assets/{dist-CRfBzL2s.js → dist-CxeSxC9m.js} +1 -1
  16. package/dist/client/assets/{dist-B41_P-GB.js → dist-D-s1GEbP.js} +1 -1
  17. package/dist/client/assets/{dist-fzY9qpWd.js → dist-D7On6h3N.js} +1 -1
  18. package/dist/client/assets/{dist-C-CsTWFq.js → dist-DBdR1Wph.js} +1 -1
  19. package/dist/client/assets/{dist-ByhQMTZz.js → dist-TcwefdPn.js} +1 -1
  20. package/dist/client/assets/{dist-BPhtg6ss.js → dist-ZuNGtw_8.js} +1 -1
  21. package/dist/client/assets/{dist-DftBUe3J.js → dist-i8fMtdTP.js} +1 -1
  22. package/dist/client/assets/{dist-CLfjxR6r.js → dist-nSNA_ze3.js} +1 -1
  23. package/dist/client/assets/{dist-0tDquiIc.js → dist-pVo8vQ15.js} +1 -1
  24. package/dist/client/assets/{dist-JFHBsRN8.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/conversation-service.d.ts +15 -0
  29. package/dist/server/application/conversation-service.js +28 -0
  30. package/dist/server/application/project-service.d.ts +7 -1
  31. package/dist/server/application/project-service.js +29 -9
  32. package/dist/server/application/run-service.js +44 -17
  33. package/dist/server/file-index.d.ts +13 -1
  34. package/dist/server/file-index.js +108 -12
  35. package/dist/server/file-name-index.d.ts +8 -0
  36. package/dist/server/file-name-index.js +58 -11
  37. package/dist/server/files.js +4 -0
  38. package/dist/server/http-server.js +143 -17
  39. package/dist/server/session-cwd.d.ts +2 -0
  40. package/dist/server/session-cwd.js +16 -1
  41. package/dist/server/store.js +7 -0
  42. package/dist/server/types.d.ts +21 -0
  43. package/dist/server/workspace-file-indexes.d.ts +2 -0
  44. package/dist/server/workspace-file-indexes.js +61 -0
  45. package/dist/server/workspace-file-operations.d.ts +36 -0
  46. package/dist/server/workspace-file-operations.js +281 -0
  47. package/dist/server/workspace-file-response.d.ts +3 -0
  48. package/dist/server/workspace-file-response.js +79 -0
  49. package/dist/shared/archive-decisions.d.ts +37 -0
  50. package/dist/shared/archive-decisions.js +86 -0
  51. package/dist/shared/project-overview.d.ts +35 -0
  52. package/dist/shared/project-overview.js +39 -1
  53. package/dist/shared/workspace-file-preview.d.ts +4 -0
  54. package/dist/shared/workspace-file-preview.js +28 -0
  55. package/package.json +4 -1
  56. package/dist/client/assets/index-DbtNmSyS.js +0 -103
  57. package/dist/client/assets/index-OmaD3l6r.css +0 -1
@@ -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")
@@ -8,7 +8,7 @@ import { gzip } from "node:zlib";
8
8
  import { promisify } from "node:util";
9
9
  import { homedir, networkInterfaces } from "node:os";
10
10
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
11
- import { describe as describeFilesError, fileMeta, listDirectory, MAX_FILE_BYTES, readWorkspaceFile, resolveInsideRoot, toRelative, writeWorkspaceFile, } from "./files.js";
11
+ import { describe as describeFilesError, FilesError, fileMeta, listDirectory, MAX_FILE_BYTES, readWorkspaceFile, resolveInsideRoot, toRelative, writeWorkspaceFile, } from "./files.js";
12
12
  import { findUploadFile, MAX_UPLOAD_BODY_BYTES, saveUpload } from "./upload.js";
13
13
  import { describeThrown } from "./failure-text.js";
14
14
  import { checkDiskVersion } from "./version.js";
@@ -24,9 +24,12 @@ import { MAX_FEISHU_REQUEST_BYTES } from "./application/feishu-service.js";
24
24
  import { MAX_WEB_REQUEST_BYTES } from "./web.js";
25
25
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
26
26
  import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateArgs, recordUpdateOutcome, releaseUpdateSlot, shellArgs } from "./update.js";
27
- import { FileIndex } from "./file-index.js";
27
+ import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
28
28
  import { ensureNameIndex, recordWorkspacePath } from "./file-name-index.js";
29
- import { resolveSessionCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
29
+ import { resolveFileCwd, resolveSessionCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
30
+ import { explorerInternalPath, explorerPath, inspectWorkspaceUpload, listWorkspaceTrash, MAX_WORKSPACE_UPLOAD_BYTES, mutateWorkspaceTree, serializeWorkspaceWrite, uploadWorkspaceFile } from "./workspace-file-operations.js";
31
+ import { readWorkspaceDocumentPreview, respondWithWorkspaceFile } from "./workspace-file-response.js";
32
+ import { updateExplorerIndexes } from "./workspace-file-indexes.js";
30
33
  import { readMessageMedia } from "./message-media.js";
31
34
  import { MESSAGE_FRAME_CSP, MESSAGE_HTML_CSP } from "../shared/message-media.js";
32
35
  import { verifyDirectChildScope, verifyListParentScope, verifyReportTargetScope, verifySpawnParentScope } from "./session-tree-scope.js";
@@ -47,6 +50,19 @@ function nameIndexFor(context, workspaceId, root, cwd = "") {
47
50
  context.nameIndexes = indexes;
48
51
  return ensureNameIndex(indexes, workspaceId, root, cwd);
49
52
  }
53
+ async function readWorkspaceUpload(request) {
54
+ const chunks = [];
55
+ let length = 0;
56
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
57
+ length += chunk.length;
58
+ if (length > MAX_WORKSPACE_UPLOAD_BYTES) {
59
+ request.resume();
60
+ throw new FilesError(413, "单个文件不能超过 32 MB。", "too_large");
61
+ }
62
+ chunks.push(chunk);
63
+ }
64
+ return Buffer.concat(chunks, length);
65
+ }
50
66
  const MIME_TYPES = {
51
67
  ".css": "text/css; charset=utf-8",
52
68
  ".html": "text/html; charset=utf-8",
@@ -1683,7 +1699,7 @@ export function createHttpServer(options) {
1683
1699
  return;
1684
1700
  }
1685
1701
  if (!projectId) {
1686
- json(200, { projects: service.list(requestedWorkspaceId) });
1702
+ json(200, { projects: service.list(requestedWorkspaceId, url.searchParams.get("view") === "history" ? "history" : "current") });
1687
1703
  return;
1688
1704
  }
1689
1705
  const project = service.get(projectId, requestedWorkspaceId);
@@ -2415,6 +2431,83 @@ export function createHttpServer(options) {
2415
2431
  }
2416
2432
  return;
2417
2433
  }
2434
+ const explorerRoute = /^\/api\/files\/(tree|upload|upload-check|asset|document)$/.exec(url.pathname)?.[1];
2435
+ if (explorerRoute) {
2436
+ try {
2437
+ const workspaceId = url.searchParams.get("workspaceId")?.trim();
2438
+ const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
2439
+ if (!workspaceId || !workspace)
2440
+ throw new FilesError(404, "请先选择有效工作区。", "no_workspace");
2441
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2442
+ const path = url.searchParams.get("path") ?? "";
2443
+ if (request.method === "GET" || request.method === "HEAD") {
2444
+ if (explorerRoute === "asset") {
2445
+ await respondWithWorkspaceFile(request, response, await explorerPath(workspace.path, root, path), url.searchParams.has("download"));
2446
+ return;
2447
+ }
2448
+ if (request.method === "GET" && explorerRoute === "document") {
2449
+ json(200, await readWorkspaceDocumentPreview(await explorerPath(workspace.path, root, path)));
2450
+ return;
2451
+ }
2452
+ if (request.method === "GET" && explorerRoute === "tree") {
2453
+ json(200, { entries: await listWorkspaceTrash(workspace.path, root) });
2454
+ return;
2455
+ }
2456
+ if (request.method === "GET" && explorerRoute === "upload-check") {
2457
+ json(200, await inspectWorkspaceUpload(workspace.path, root, path, url.searchParams.get("name") ?? ""));
2458
+ return;
2459
+ }
2460
+ }
2461
+ if (request.method !== "POST" || (explorerRoute !== "tree" && explorerRoute !== "upload")) {
2462
+ json(405, { error: "不支持此文件操作。", code: "method" });
2463
+ return;
2464
+ }
2465
+ const origin = request.headers.origin;
2466
+ const fetchSite = request.headers["sec-fetch-site"];
2467
+ if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
2468
+ throw new FilesError(403, "文件操作需要来自同源的本机或局域网请求。", "denied");
2469
+ }
2470
+ let mutate;
2471
+ if (explorerRoute === "upload") {
2472
+ const bytes = await readWorkspaceUpload(request);
2473
+ mutate = () => uploadWorkspaceFile(workspace.path, root, path, url.searchParams.get("name") ?? "", bytes, request.headers["if-match"]);
2474
+ }
2475
+ else {
2476
+ const result = await readRequestText(request, 16 * 1024);
2477
+ if (result.tooLarge)
2478
+ throw new FilesError(413, "文件操作请求过大。", "too_large");
2479
+ let body;
2480
+ try {
2481
+ body = JSON.parse(result.text);
2482
+ }
2483
+ catch {
2484
+ throw new FilesError(400, "需要有效的文件操作请求。", "bad_request");
2485
+ }
2486
+ if (!body || typeof body !== "object" || Array.isArray(body))
2487
+ throw new FilesError(400, "需要有效的文件操作请求。", "bad_request");
2488
+ mutate = () => mutateWorkspaceTree(workspace.path, root, body);
2489
+ }
2490
+ const outcome = await serializeWorkspaceWrite(workspace.path, async () => {
2491
+ const result = await mutate();
2492
+ const oldPath = result.previousPath && toRelative(workspace.path, resolve(root, result.previousPath));
2493
+ const newPath = toRelative(workspace.path, resolve(root, result.path));
2494
+ await updateExplorerIndexes(context, workspaceId, workspace.path, newPath, result.removed ? newPath : oldPath, !!result.directory, !!result.removed)
2495
+ .catch((error) => console.warn("Super Pi: file operation completed, but the file indexes could not be updated", error));
2496
+ broadcaster.broadcast({ type: "files.invalidated", workspaceId, paths: oldPath ? [oldPath, newPath] : [newPath] });
2497
+ return result;
2498
+ });
2499
+ json(200, outcome);
2500
+ }
2501
+ catch (error) {
2502
+ if (response.headersSent) {
2503
+ response.destroy();
2504
+ return;
2505
+ }
2506
+ const described = describeFilesError(error);
2507
+ json(described.status, described.body);
2508
+ }
2509
+ return;
2510
+ }
2418
2511
  if (url.pathname === "/api/files/diff") {
2419
2512
  const json = (status, body) => {
2420
2513
  response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body));
@@ -2431,7 +2524,8 @@ export function createHttpServer(options) {
2431
2524
  json(400, { error: "需要 path 参数", code: "bad_request" });
2432
2525
  return;
2433
2526
  }
2434
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2527
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2528
+ await explorerPath(workspace.path, root, path);
2435
2529
  const workspaceRelativePath = await workspacePathFromSession(workspace.path, root, path);
2436
2530
  const requested = url.searchParams.get("base")?.trim();
2437
2531
  const preferred = requested === "git" || requested === "agent" ? requested : "auto";
@@ -2468,7 +2562,8 @@ export function createHttpServer(options) {
2468
2562
  json(404, { error: "找不到这个工作区——它可能已经被删除。", code: "no_workspace" });
2469
2563
  return;
2470
2564
  }
2471
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2565
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2566
+ await explorerPath(workspace.path, root, "", true);
2472
2567
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2473
2568
  const indexKey = sessionScopeKey(workspaceId, cwd);
2474
2569
  if (query.length > 256 || /[\r\n]/.test(query)) {
@@ -2519,7 +2614,8 @@ export function createHttpServer(options) {
2519
2614
  json(400, { error: "搜索内容过长。" });
2520
2615
  return;
2521
2616
  }
2522
- const root = await resolveInsideRoot(workspace.path, url.searchParams.get("cwd") ?? "");
2617
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2618
+ await explorerPath(workspace.path, root, "", true);
2523
2619
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2524
2620
  const index = nameIndexFor(context, workspaceId, root, cwd);
2525
2621
  await index.waitUntilIndexed(4000);
@@ -2563,7 +2659,8 @@ export function createHttpServer(options) {
2563
2659
  json(404, { error: `找不到工作区「${workspaceId ?? "未指定"}」——它可能已经被删除。`, code: "no_workspace" });
2564
2660
  return;
2565
2661
  }
2566
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2662
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2663
+ await explorerPath(workspace.path, root, "", true);
2567
2664
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2568
2665
  const indexKey = sessionScopeKey(workspaceId, cwd);
2569
2666
  const indexes = context.fileIndexes ?? new Map();
@@ -2599,7 +2696,8 @@ export function createHttpServer(options) {
2599
2696
  json(404, { error: `找不到工作区「${workspaceId ?? "未指定"}」——它可能已经被删除。`, code: "no_workspace" });
2600
2697
  return;
2601
2698
  }
2602
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2699
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2700
+ await explorerPath(workspace.path, root, "", true);
2603
2701
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2604
2702
  const indexKey = sessionScopeKey(workspaceId, cwd);
2605
2703
  if (url.pathname === "/api/files") {
@@ -2647,12 +2745,34 @@ export function createHttpServer(options) {
2647
2745
  });
2648
2746
  return;
2649
2747
  }
2650
- const listing = await listDirectory(root, url.searchParams.get("path"));
2748
+ const requested = url.searchParams.get("path") ?? "";
2749
+ const listing = await serializeWorkspaceWrite(workspace.path, async () => {
2750
+ await explorerPath(workspace.path, root, requested, true);
2751
+ const listed = await listDirectory(root, requested);
2752
+ const allowed = await Promise.all(listed.entries.map(async (entry) => {
2753
+ if (explorerInternalPath(toRelative(workspace.path, resolve(root, entry.path))))
2754
+ return false;
2755
+ if (!entry.symlink || entry.outside)
2756
+ return true;
2757
+ return explorerPath(workspace.path, root, entry.path).then(() => true, () => false);
2758
+ }));
2759
+ listed.entries = listed.entries.filter((_, position) => allowed[position]);
2760
+ if (!listed.truncated) {
2761
+ context.fileIndexes?.get(indexKey)?.reconcileDirectory(listed.path, listed.entries);
2762
+ context.nameIndexes?.get(indexKey)?.reconcileDirectory(listed.path, listed.entries);
2763
+ }
2764
+ if (requested === "" && url.searchParams.get("revalidate") === "1") {
2765
+ context.fileIndexes?.get(indexKey)?.markStale();
2766
+ context.nameIndexes?.get(indexKey)?.markStale();
2767
+ }
2768
+ return listed;
2769
+ });
2651
2770
  json(200, { mode: "list", ...listing, maxEntries: 2000 });
2652
2771
  return;
2653
2772
  }
2654
2773
  if (request.method === "GET") {
2655
2774
  const rel = url.searchParams.get("path") ?? "";
2775
+ await explorerPath(workspace.path, root, rel, true);
2656
2776
  if (url.searchParams.get("meta") === "1") {
2657
2777
  const resolved = await resolveInsideRoot(root, rel);
2658
2778
  const meta = await fileMeta(resolved);
@@ -2696,13 +2816,19 @@ export function createHttpServer(options) {
2696
2816
  json(400, { error: "写入需要 path 与 content 两个字符串字段", code: "bad_request" });
2697
2817
  return;
2698
2818
  }
2699
- const outcome = await writeWorkspaceFile(root, parsed.path, parsed.content, parsed.baseEtag);
2700
- context.fileIndexes?.get(indexKey)?.recordFile(outcome.path, outcome.meta);
2701
- // The name index learns about the save too. A file the user just saved must be findable
2702
- // by name immediately, and the index is the thing the search reads - so this is where the
2703
- // index stays true without anybody re-scanning the tree.
2704
- if (context.nameIndexes)
2705
- recordWorkspacePath(context.nameIndexes, workspaceId, workspace.path, await workspacePathFromSession(workspace.path, root, outcome.path));
2819
+ await explorerPath(workspace.path, root, parsed.path, true);
2820
+ const { path, content, baseEtag } = parsed;
2821
+ const outcome = await serializeWorkspaceWrite(workspace.path, async () => {
2822
+ await explorerPath(workspace.path, root, path, true);
2823
+ const saved = await writeWorkspaceFile(root, path, content, baseEtag);
2824
+ const changedPath = await workspacePathFromSession(workspace.path, root, saved.path);
2825
+ context.fileIndexes?.get(indexKey)?.recordFile(saved.path, saved.meta);
2826
+ refreshWorkspaceIndex(context.fileIndexes, workspaceId, changedPath, workspace.path);
2827
+ if (context.nameIndexes)
2828
+ recordWorkspacePath(context.nameIndexes, workspaceId, workspace.path, changedPath);
2829
+ broadcaster.broadcast({ type: "files.invalidated", workspaceId, paths: [changedPath] });
2830
+ return saved;
2831
+ });
2706
2832
  json(200, outcome);
2707
2833
  return;
2708
2834
  }
@@ -1,3 +1,5 @@
1
+ /** Explicit file scopes must still name an existing directory. */
2
+ export declare function resolveFileCwd(workspaceRoot: string, cwd?: string | null): Promise<string>;
1
3
  /**
2
4
  * Resolves a conversation's optional relative cwd without ever letting it leave the workspace.
3
5
  * An absent value preserves the workspace root; an invalid or escaping value is rejected back to
@@ -1,5 +1,20 @@
1
1
  import { relative, resolve, sep } from "node:path";
2
- import { resolveInsideRoot } from "./files.js";
2
+ import { stat } from "node:fs/promises";
3
+ import { FilesError, resolveInsideRoot } from "./files.js";
4
+ /** Explicit file scopes must still name an existing directory. */
5
+ export async function resolveFileCwd(workspaceRoot, cwd) {
6
+ const target = await resolveInsideRoot(workspaceRoot, cwd);
7
+ if (!cwd?.trim())
8
+ return target;
9
+ const info = await stat(target).catch((error) => {
10
+ if (error.code === "ENOENT" || error.code === "ENOTDIR")
11
+ throw new FilesError(404, "会话目录已不存在。", "cwd_missing");
12
+ throw error;
13
+ });
14
+ if (!info.isDirectory())
15
+ throw new FilesError(400, "会话路径必须是目录。", "cwd_not_directory");
16
+ return target;
17
+ }
3
18
  /**
4
19
  * Resolves a conversation's optional relative cwd without ever letting it leave the workspace.
5
20
  * An absent value preserves the workspace root; an invalid or escaping value is rejected back to
@@ -4,6 +4,7 @@ import { normalizeTodos } from "./task-tool.js";
4
4
  import { initializeMemoryTrees, memoryTreeId } from "./session-memory-scope.js";
5
5
  import { TOOL_ARG_CAP } from "./tool-calls.js";
6
6
  import { serverTimeZone } from "./time-zone.js";
7
+ import { pendingUserDecisionsByOwner } from "../shared/archive-decisions.js";
7
8
  function id(prefix) { return `${prefix}_${crypto.randomUUID()}`; }
8
9
  /** Mints the id a forked conversation will have, BEFORE its Pi transcript exists.
9
10
  *
@@ -1271,12 +1272,17 @@ export class Store {
1271
1272
  const presets = warmSessions.length ? { warmSessions } : {};
1272
1273
  const openEscalations = this.openEscalationAudiences();
1273
1274
  const pendingResults = this.pendingResultConversationIds();
1275
+ /* 项目本身不上广播,但归档提醒要知道「归档这棵树会作废几条决策」。服务端算这个数,
1276
+ 客户端只做加法 —— 判据在 `src/shared/archive-decisions.ts`,两边共用一份。 */
1277
+ const pendingDecisions = pendingUserDecisionsByOwner(this.state.projects ?? []);
1278
+ const pendingDecisionsField = Object.keys(pendingDecisions).length ? { pendingUserDecisionsByConversation: pendingDecisions } : {};
1274
1279
  // Legacy sockets still receive complete visible transcripts. Project before cloning so a closed
1275
1280
  // workspace's retained history is never copied just to discard it afterwards.
1276
1281
  if (scope === undefined) {
1277
1282
  return structuredClone({
1278
1283
  ...publicState,
1279
1284
  ...presets,
1285
+ ...pendingDecisionsField,
1280
1286
  workspaces,
1281
1287
  conversations: visible.map((c) => {
1282
1288
  const escalationAudience = openEscalations.get(c.id);
@@ -1308,6 +1314,7 @@ export class Store {
1308
1314
  return structuredClone({
1309
1315
  ...publicState,
1310
1316
  ...presets,
1317
+ ...pendingDecisionsField,
1311
1318
  workspaces,
1312
1319
  conversations,
1313
1320
  // THE CLOCK THE SERVER SCHEDULES BY, NAMED. The scheduled-task panel renders 「每天 09:00」 and
@@ -1139,6 +1139,11 @@ export type Project = {
1139
1139
  risk: ProjectRisk;
1140
1140
  status: ProjectStatus;
1141
1141
  ownerConversationId?: string;
1142
+ /** IS THE OWNER SESSION IN THE ARCHIVE? A project whose leader was archived has nobody left to
1143
+ * run it, so it is history with its records intact - not work in progress. The server computes
1144
+ * it (it is the one that knows what is archived) and the client re-applies the same rule, so
1145
+ * both ends agree on which view a project belongs to. */
1146
+ ownerArchived?: boolean;
1142
1147
  /** The session that created the project - the Boss's own conversation, which may register the
1143
1148
  * top-level tasks and is the one the project answers to. */
1144
1149
  initiatorConversationId?: string;
@@ -1172,6 +1177,7 @@ export type Project = {
1172
1177
  tokens: number;
1173
1178
  usageKnown: boolean;
1174
1179
  activeWorkers: number;
1180
+ ownerCwd?: string;
1175
1181
  memoryTreeId?: string;
1176
1182
  usage?: {
1177
1183
  input: number;
@@ -1264,6 +1270,17 @@ export type AppState = {
1264
1270
  cwd?: string;
1265
1271
  savedAt: string;
1266
1272
  }>;
1273
+ /**
1274
+ * 每个会话背着几条「用户还没拍板的决策」,by conversation id.
1275
+ *
1276
+ * 项目本身不上广播(`clientState` 把 projects 摘掉了),但归档提醒需要知道:**归档这棵会话树
1277
+ * 会作废几条决策**。这个数由服务端算 —— 判据在 `src/shared/archive-decisions.ts`,两边共用 ——
1278
+ * 客户端只负责把树里的会话加起来,然后写进那一次确认框。
1279
+ *
1280
+ * 键是**负责人会话**:一个项目上的未决决策记在它的负责人名下,因为那个会话就是项目的领导。
1281
+ * 没有这个数,客户端就只能对用户说「可能会作废一些东西」,而不是「还有 3 个」。
1282
+ */
1283
+ pendingUserDecisionsByConversation?: Record<string, number>;
1267
1284
  /**
1268
1285
  * THE CLOCK THIS SERVER SCHEDULES BY. A scheduled task's 「每天 09:00」 is the SERVER's wall clock,
1269
1286
  * and the panel has to say so, because browser rendering 「下次」 may be on a different clock
@@ -2019,6 +2036,10 @@ export type ServerEvent = {
2019
2036
  workspaceId: string;
2020
2037
  changes: ChangedFile[];
2021
2038
  dropped: number;
2039
+ } | {
2040
+ type: "files.invalidated";
2041
+ workspaceId: string;
2042
+ paths?: string[];
2022
2043
  } | {
2023
2044
  type: "files.index";
2024
2045
  workspaceId: string;
@@ -0,0 +1,2 @@
1
+ import type { ServerContext } from "./server-context.js";
2
+ export declare function updateExplorerIndexes(context: Pick<ServerContext, "fileIndexes" | "nameIndexes">, workspaceId: string, workspaceRoot: string, path: string, previousPath: string | undefined, directory: boolean, removed: boolean): Promise<void>;
@@ -0,0 +1,61 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { belowPath, inScope } from "./file-index.js";
3
+ import { createRootGuard } from "./files.js";
4
+ import { explorerInternalPath } from "./workspace-file-operations.js";
5
+ export async function updateExplorerIndexes(context, workspaceId, workspaceRoot, path, previousPath, directory, removed) {
6
+ const files = [...(context.fileIndexes?.values() ?? [])].filter(index => index.workspaceId === workspaceId);
7
+ const names = [...(context.nameIndexes?.values() ?? [])].filter(index => index.workspaceId === workspaceId);
8
+ if (!files.length && !names.length)
9
+ return;
10
+ if (previousPath !== undefined) {
11
+ for (const index of [...files, ...names]) {
12
+ const scoped = inScope(workspaceRoot, index.cwd, previousPath);
13
+ if (scoped !== undefined)
14
+ index.removeTree(scoped);
15
+ else if (belowPath(index.cwd, previousPath))
16
+ index.removeTree("");
17
+ }
18
+ }
19
+ if (removed)
20
+ return;
21
+ if (!directory) {
22
+ for (const index of names) {
23
+ const scoped = inScope(workspaceRoot, index.cwd, path);
24
+ if (scoped)
25
+ index.upsert(scoped);
26
+ }
27
+ await Promise.all(files.map(index => {
28
+ const scoped = inScope(workspaceRoot, index.cwd, path);
29
+ return scoped ? index.refresh(scoped) : undefined;
30
+ }));
31
+ return;
32
+ }
33
+ const guard = createRootGuard(workspaceRoot);
34
+ const folders = [path];
35
+ const entries = [{ path, kind: "directory" }];
36
+ for (let cursor = 0; cursor < folders.length && cursor < 4000 && entries.length < 30000; cursor += 1) {
37
+ const folder = folders[cursor];
38
+ const children = await guard(folder).then(absolute => readdir(absolute, { withFileTypes: true })).catch(() => []);
39
+ for (const child of children) {
40
+ const childPath = `${folder}/${child.name}`;
41
+ if (explorerInternalPath(childPath) || (!child.isDirectory() && !child.isFile()))
42
+ continue;
43
+ entries.push({ path: childPath, kind: child.isDirectory() ? "directory" : "file" });
44
+ if (child.isDirectory())
45
+ folders.push(childPath);
46
+ if (entries.length >= 30000)
47
+ break;
48
+ }
49
+ }
50
+ for (const index of names)
51
+ for (const entry of entries) {
52
+ const scoped = inScope(workspaceRoot, index.cwd, entry.path);
53
+ if (scoped)
54
+ index.upsert(scoped, entry.kind);
55
+ }
56
+ for (const index of files)
57
+ index.recordEntries(entries.flatMap(entry => {
58
+ const scoped = inScope(workspaceRoot, index.cwd, entry.path);
59
+ return scoped ? [{ ...entry, path: scoped }] : [];
60
+ }));
61
+ }
@@ -0,0 +1,36 @@
1
+ declare const MAX_INITIAL_CONTENT: number;
2
+ export declare function serializeWorkspaceWrite<T>(workspace: string, work: () => Promise<T>): Promise<T>;
3
+ export type FileTreeMutation = {
4
+ path: string;
5
+ previousPath?: string;
6
+ removed?: boolean;
7
+ directory?: boolean;
8
+ text?: boolean;
9
+ trashId?: string;
10
+ };
11
+ export declare function explorerInternalPath(path: string): boolean;
12
+ export declare function explorerPath(workspace: string, root: string, path: string, allowRoot?: boolean): Promise<string>;
13
+ export declare function listWorkspaceTrash(workspace: string, root: string): Promise<{
14
+ deletedAt: string;
15
+ directory: boolean;
16
+ id: string;
17
+ path: string;
18
+ }[]>;
19
+ export declare function mutateWorkspaceTree(workspace: string, root: string, body: Record<string, unknown>): Promise<FileTreeMutation>;
20
+ export declare function inspectWorkspaceUpload(workspace: string, root: string, parent: string, name: string): Promise<{
21
+ exists: boolean;
22
+ replaceable?: undefined;
23
+ meta?: undefined;
24
+ } | {
25
+ exists: boolean;
26
+ replaceable: boolean;
27
+ meta?: undefined;
28
+ } | {
29
+ exists: boolean;
30
+ replaceable: boolean;
31
+ meta: import("./files.js").FileMeta;
32
+ }>;
33
+ export declare function uploadWorkspaceFile(workspace: string, root: string, parent: string, name: string, bytes: Buffer, baseEtag?: string): Promise<{
34
+ path: string;
35
+ }>;
36
+ export { MAX_INITIAL_CONTENT as MAX_WORKSPACE_UPLOAD_BYTES };