@evandu/super-pi 0.1.321 → 0.1.323

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-D6OVl078.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-DLXLkcyw.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-Dj33YA2I.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-CjV5_OmA.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
17
17
 
@@ -38,7 +38,7 @@ type Frontmatter = Record<string, unknown>;
38
38
  */
39
39
  export declare const PI_TOOL_NAMES: readonly ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode", "tool_search", "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"];
40
40
  /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
- export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "agent_handbook", "user_tool", "user_tool_manage", "review_list", "review_reply", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
41
+ export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "agent_handbook", "user_tool", "user_tool_manage", "review_list", "review_reply", "review_create", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
42
42
  /**
43
43
  * Whether a name can be a real Pi tool. A name is real if it is one of `PI_TOOL_NAMES`, an MCP
44
44
  * server tool, or a PATTERN.
@@ -2,6 +2,7 @@ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import { orderAgentsForDisplay } from "../shared/agent-order.js";
5
+ import { FILE_REVIEW_TOOLS } from "../shared/file-review.js";
5
6
  /**
6
7
  * A guard rather than a cast: it is the only thing that lets `tools:` be checked once and then used as
7
8
  * a map everywhere without the compiler complaining. It narrows to the index-signature shape that
@@ -40,7 +41,7 @@ export const PI_TOOL_NAMES = [
40
41
  /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
42
  export const SUPER_PI_TOOL_NAMES = [
42
43
  "task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove",
43
- "memory", "skill_manage", "session_search", "agent_handbook", "user_tool", "user_tool_manage", "review_list", "review_reply",
44
+ "memory", "skill_manage", "session_search", "agent_handbook", "user_tool", "user_tool_manage", ...FILE_REVIEW_TOOLS,
44
45
  "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder",
45
46
  "knowledge_search", "knowledge_import",
46
47
  "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write",
@@ -1,4 +1,4 @@
1
- import { type ReviewThread } from "../shared/file-review.js";
1
+ import { type ReviewDiffReplay, type ReviewThread } from "../shared/file-review.js";
2
2
  type ScopedThread = ReviewThread & {
3
3
  workspaceId: string;
4
4
  cwd: string;
@@ -11,7 +11,15 @@ export declare class FileReviewThreads {
11
11
  private loaded;
12
12
  constructor(path: string);
13
13
  list(scope: Scope): ScopedThread[];
14
- create(scope: Scope, comments: unknown): ScopedThread[];
14
+ create(scope: Scope, comments: unknown, agentName?: string, diff?: unknown): ScopedThread[];
15
+ snapshot(scope: Scope, threadId: string): ReviewDiffReplay | undefined;
16
+ agentCreate(workspace: {
17
+ id: string;
18
+ path: string;
19
+ }, author: {
20
+ conversationId: string;
21
+ agentName?: string;
22
+ }, input: unknown, canWrite: () => boolean): Promise<ScopedThread>;
15
23
  update(scope: Scope, id: string, action: string, detail?: unknown, replyId?: string): ScopedThread | undefined;
16
24
  getForScope(scope: Scope, id: string): ScopedThread;
17
25
  agentReply(scopes: Scope[], author: {
@@ -23,5 +31,7 @@ export declare class FileReviewThreads {
23
31
  private get;
24
32
  private load;
25
33
  private save;
34
+ private snapshotPath;
35
+ private saveSnapshot;
26
36
  }
27
37
  export {};
@@ -1,6 +1,9 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
- import { workspaceReviewPath } from "../shared/file-review.js";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { stat } from "node:fs/promises";
4
+ import { join, posix } from "node:path";
5
+ import { reviewExcerpt, reviewTextVersions, workspaceReviewPath } from "../shared/file-review.js";
6
+ import { readWorkspaceFile, resolveInsideRoot } from "./files.js";
4
7
  function record(value) {
5
8
  if (!value || typeof value !== "object" || Array.isArray(value))
6
9
  throw new Error("批注参数无效。");
@@ -39,6 +42,44 @@ function anchorFrom(value, allowAdditional = true) {
39
42
  function sameScope(thread, scope) {
40
43
  return thread.workspaceId === scope.workspaceId;
41
44
  }
45
+ function diffVersion(value) {
46
+ const { kind, hash } = record(value);
47
+ if (kind === "missing" || kind === "unknown")
48
+ return { kind };
49
+ if ((kind === "commit" || kind === "blob") && typeof hash === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(hash)) {
50
+ return { kind, hash: hash.toLowerCase() };
51
+ }
52
+ throw new Error("差异版本标识无效。");
53
+ }
54
+ function diffSnapshot(value) {
55
+ const input = record(value);
56
+ const path = text(input.path, 4096);
57
+ const previousPath = text(input.previousPath, 4096, true);
58
+ const payloadText = (item) => item === null ? null : text(item, 8 * 1024 * 1024, true);
59
+ let content;
60
+ let versions;
61
+ if (input.mode === "patch" && (input.kind === "text" || input.kind === "binary" || input.kind === "untracked")) {
62
+ const patch = payloadText(input.diff);
63
+ if (patch === undefined)
64
+ throw new Error("缺少原差异内容。");
65
+ const sides = record(input.versions);
66
+ versions = { before: diffVersion(sides.before), after: diffVersion(sides.after) };
67
+ content = { mode: "patch", kind: input.kind, diff: patch, limited: input.limited === true, versions };
68
+ }
69
+ else if (input.mode === "text") {
70
+ const before = payloadText(input.before);
71
+ const after = payloadText(input.after);
72
+ if (before === undefined || after === undefined)
73
+ throw new Error("缺少原差异内容。");
74
+ const beforeUnknown = before === null && input.beforeUnknown === true;
75
+ versions = reviewTextVersions(before, after, beforeUnknown);
76
+ content = { mode: "text", before, after, ...(beforeUnknown ? { beforeUnknown } : {}) };
77
+ }
78
+ else
79
+ throw new Error("差异快照格式无效。");
80
+ const id = createHash("sha256").update(JSON.stringify([path, previousPath, content])).digest("hex");
81
+ return { ref: { id, path, ...(previousPath === undefined ? {} : { previousPath }), ...versions }, content };
82
+ }
42
83
  /** Review threads belong to one workspace checkout. Cwd records the origin of a relative anchor. */
43
84
  export class FileReviewThreads {
44
85
  path;
@@ -51,12 +92,14 @@ export class FileReviewThreads {
51
92
  this.load();
52
93
  return [...this.entries.values()].filter(thread => sameScope(thread, scope)).reverse();
53
94
  }
54
- create(scope, comments) {
95
+ create(scope, comments, agentName, diff) {
55
96
  this.load();
56
97
  if (!Array.isArray(comments) || !comments.length || comments.length > 25)
57
98
  throw new Error("请选择要保存的批注。");
58
99
  const next = new Map(this.entries);
59
100
  const created = [];
101
+ const snapshot = diff === undefined ? undefined : diffSnapshot(diff);
102
+ let added = false;
60
103
  for (const value of comments) {
61
104
  const item = record(value);
62
105
  const id = text(item.id, 128);
@@ -71,20 +114,69 @@ export class FileReviewThreads {
71
114
  }
72
115
  const entry = {
73
116
  ...scope, ...anchorFrom(item), id,
74
- text: text(item.text, 2_000), replies: [], createdAt: new Date().toISOString(),
117
+ text: text(item.text, 2_000), replies: [], createdAt: new Date().toISOString(), agentName, diffSnapshot: snapshot?.ref,
75
118
  };
119
+ if (snapshot && [entry, ...entry.additional ?? []].some(anchor => anchor.side === "file" || anchor.path !== (anchor.side === "before" ? snapshot.ref.previousPath ?? snapshot.ref.path : snapshot.ref.path))) {
120
+ throw new Error("批注位置与差异快照不匹配。");
121
+ }
76
122
  next.set(id, entry);
77
123
  created.push(entry);
124
+ added = true;
78
125
  }
126
+ if (snapshot && added)
127
+ this.saveSnapshot(snapshot);
79
128
  this.save(next);
80
129
  return created;
81
130
  }
131
+ snapshot(scope, threadId) {
132
+ const ref = this.getForScope(scope, threadId).diffSnapshot;
133
+ if (!ref)
134
+ return;
135
+ const path = this.snapshotPath(ref.id);
136
+ if (!existsSync(path))
137
+ return;
138
+ return { ref, content: JSON.parse(readFileSync(path, "utf8")) };
139
+ }
140
+ async agentCreate(workspace, author, input, canWrite) {
141
+ const item = record(input);
142
+ const id = "review-" + createHash("sha256").update(JSON.stringify([author.conversationId, text(item.requestId, 200)])).digest("hex");
143
+ const scope = { workspaceId: workspace.id, cwd: "" };
144
+ this.load();
145
+ if (this.entries.has(id))
146
+ return this.getForScope(scope, id);
147
+ const requested = workspaceReviewPath(text(item.path, 4096));
148
+ if (/(?:^|\/)\.\.(?:\/|$)/.test(requested))
149
+ throw new Error("批注路径须在当前工作区内。");
150
+ const path = posix.normalize(requested);
151
+ const target = await resolveInsideRoot(workspace.path, requested);
152
+ if (!(await stat(target)).isFile())
153
+ throw new Error("只能为文件创建批注。");
154
+ const anchor = anchorFrom({ side: "file", path, source: `file:${path}`, start: item.start, end: item.end ?? item.start });
155
+ if (anchor.start !== undefined && anchor.end !== undefined) {
156
+ const lines = (await readWorkspaceFile(workspace.path, requested)).content.split(/\r?\n/);
157
+ if (anchor.end > lines.length)
158
+ throw new Error("批注行号超出文件范围。");
159
+ anchor.excerpt = reviewExcerpt(lines.slice(anchor.start - 1, anchor.end));
160
+ }
161
+ if (!canWrite())
162
+ throw new Error("当前执行已经结束。");
163
+ return this.create(scope, [{ ...anchor, id, text: item.text }], author.agentName || "Agent")[0];
164
+ }
82
165
  update(scope, id, action, detail, replyId) {
83
166
  const thread = this.getForScope(scope, id);
84
167
  if (action === "delete") {
85
168
  const next = new Map(this.entries);
86
169
  next.delete(id);
87
170
  this.save(next);
171
+ const snapshotId = thread.diffSnapshot?.id;
172
+ if (snapshotId && ![...next.values()].some(entry => entry.diffSnapshot?.id === snapshotId)) {
173
+ try {
174
+ rmSync(this.snapshotPath(snapshotId), { force: true });
175
+ }
176
+ catch (error) {
177
+ console.warn("Could not remove unused review snapshot.", error);
178
+ }
179
+ }
88
180
  return;
89
181
  }
90
182
  if (action === "reply")
@@ -161,4 +253,18 @@ export class FileReviewThreads {
161
253
  renameSync(temporary, this.path);
162
254
  this.entries = next;
163
255
  }
256
+ snapshotPath(id) {
257
+ if (!/^[a-f0-9]{64}$/.test(id))
258
+ throw new Error("差异快照标识无效。");
259
+ return join(this.path + ".snapshots", id + ".json");
260
+ }
261
+ saveSnapshot(snapshot) {
262
+ const target = this.snapshotPath(snapshot.ref.id);
263
+ if (existsSync(target))
264
+ return;
265
+ mkdirSync(this.path + ".snapshots", { recursive: true, mode: 0o700 });
266
+ const temporary = target + ".tmp";
267
+ writeFileSync(temporary, JSON.stringify(snapshot.content), { mode: 0o600 });
268
+ renameSync(temporary, target);
269
+ }
164
270
  }
@@ -1,5 +1,6 @@
1
1
  import type { GitCommitDetail } from "../shared/git-commit.js";
2
2
  import type { GitGraphResponse } from "../shared/git-graph.js";
3
+ import type { ReviewVersions } from "../shared/file-review.js";
3
4
  export type GitWorkspace = {
4
5
  branch: string | null;
5
6
  detached: boolean;
@@ -33,6 +34,7 @@ export declare function gitCommitDiff(root: string, cwd: string, hash: string, p
33
34
  staged: boolean;
34
35
  kind: "binary" | "text";
35
36
  diff: string | null;
37
+ versions: ReviewVersions;
36
38
  }>;
37
39
  export type GitWorktree = {
38
40
  id: string;
@@ -89,13 +91,9 @@ export declare function inspectGitWorktree(path: string, base: GitWorktree | und
89
91
  export declare function gitWorktreeCommittedDiff(root: string, base: GitWorktree | undefined, path: string, fullContext?: boolean): Promise<{
90
92
  path: string;
91
93
  staged: boolean;
92
- kind: "text";
93
- diff: string;
94
- } | {
95
- path: string;
96
- staged: boolean;
97
- kind: "binary";
98
- diff: null;
94
+ kind: "binary" | "text";
95
+ diff: string | null;
96
+ versions: ReviewVersions;
99
97
  }>;
100
98
  export declare function gitBranches(root: string, cwd: string, query: string, offset: number, localOnly?: boolean): Promise<{
101
99
  branches: {
@@ -128,12 +126,14 @@ export declare function gitDiff(root: string, path: string, staged: boolean, ful
128
126
  diff: null;
129
127
  kind: "untracked";
130
128
  currentExists: boolean;
129
+ versions: ReviewVersions;
131
130
  } | {
132
131
  path: string;
133
132
  staged: boolean;
134
133
  diff: string;
135
134
  kind: "binary" | "text";
136
135
  currentExists: boolean;
136
+ versions: ReviewVersions;
137
137
  }>;
138
138
  /** Read the index version for the editable working-tree comparison. The path is resolved beneath the
139
139
  * workspace before it becomes a Git object expression, and the blob stays within the file editor's
@@ -162,6 +162,15 @@ const PATCH_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--submod
162
162
  const HISTORY_DIFF_OPTIONS = [...PATCH_OPTIONS, "--find-renames"];
163
163
  const FULL_DIFF_MAX_BYTES = 2 * 1024 * 1024;
164
164
  const FULL_DIFF_MAX_LINES = 12_000;
165
+ function comparedCommits(before, after) {
166
+ return { before: before ? { kind: "commit", hash: before } : { kind: "missing" }, after: { kind: "commit", hash: after } };
167
+ }
168
+ function comparedBlobs(patch) {
169
+ const index = /^index ([0-9a-f]{40}(?:[0-9a-f]{24})?)\.\.([0-9a-f]{40}(?:[0-9a-f]{24})?)(?: |$)/m.exec(patch);
170
+ const side = (hash) => !hash ? { kind: "unknown" }
171
+ : /^0+$/.test(hash) ? { kind: "missing" } : { kind: "blob", hash };
172
+ return { before: side(index?.[1]), after: side(index?.[2]) };
173
+ }
165
174
  function patchContext(fullContext) {
166
175
  // Any file that fits the full view limits fits within this unified context.
167
176
  return fullContext ? "--unified=1000000" : "--unified=3";
@@ -254,7 +263,8 @@ export async function gitCommitDiff(root, cwd, hash, path, fullContext = false)
254
263
  .map(name => scope ? `${scope}/${name}` : name);
255
264
  const patch = await diff(["--patch", patchContext(fullContext)], paths, true, fullContext);
256
265
  const binary = /^Binary files .* differ$/m.test(patch);
257
- return { path, staged: false, kind: binary ? "binary" : "text", diff: binary ? null : patch };
266
+ return { path, staged: false, kind: binary ? "binary" : "text", diff: binary ? null : patch,
267
+ versions: comparedCommits(detail.parents[0], detail.hash) };
258
268
  }
259
269
  const normalizedPath = (path) => process.platform === "win32" ? resolve(path).toLowerCase() : resolve(path);
260
270
  async function worktreeRoot(root) {
@@ -421,11 +431,11 @@ export async function gitWorktreeCommittedDiff(root, base, path, fullContext = f
421
431
  safePath(root, path);
422
432
  const reference = await worktreeComparisonBase(root, base);
423
433
  if (!reference)
424
- return { path, staged: false, kind: "text", diff: "" };
434
+ return { path, staged: false, kind: "text", diff: "", versions: comparedBlobs("") };
425
435
  const stdout = await readGitDiff(root, ["diff", ...PATCH_OPTIONS, patchContext(fullContext), reference.mergeBase, reference.target, "--", path], fullContext);
426
- if (/^Binary files .* differ$/m.test(stdout))
427
- return { path, staged: false, kind: "binary", diff: null };
428
- return { path, staged: false, kind: "text", diff: stdout };
436
+ const binary = /^Binary files .* differ$/m.test(stdout);
437
+ return { path, staged: false, kind: binary ? "binary" : "text", diff: binary ? null : stdout,
438
+ versions: comparedCommits(reference.mergeBase, reference.target) };
429
439
  }
430
440
  export async function gitBranches(root, cwd, query, offset, localOnly = false) {
431
441
  const canWrite = await canChangeWorktree(root, cwd);
@@ -511,9 +521,16 @@ export async function gitDiff(root, path, staged, fullContext = false) {
511
521
  if (!tracked && !currentExists)
512
522
  throw Object.assign(new Error("文件路径无效"), { code: "path" });
513
523
  if (!tracked)
514
- return { path, staged, diff: null, kind: "untracked", currentExists };
515
- const patch = await readGitDiff(root, ["diff", ...PATCH_OPTIONS, patchContext(fullContext), ...(staged ? ["--cached"] : []), "--", path], fullContext);
516
- return { path, staged, diff: patch, kind: /^Binary files .* differ$/m.test(patch) ? "binary" : "text", currentExists };
524
+ return { path, staged, diff: null, kind: "untracked", currentExists, versions: comparedBlobs("") };
525
+ // Pin HEAD before reading a staged patch so the stored base identifies what Git actually compared.
526
+ const head = staged ? await git(root, ["rev-parse", "--verify", "HEAD"]).then(result => result.stdout.trim()).catch(() => "") : "";
527
+ const patch = await readGitDiff(root, ["diff", ...PATCH_OPTIONS, patchContext(fullContext),
528
+ ...(staged ? ["--cached", ...(head ? [head] : [])] : []), "--", path], fullContext);
529
+ const versions = comparedBlobs(patch);
530
+ if (COMMIT_HASH.test(head))
531
+ versions.before = { kind: "commit", hash: head };
532
+ return { path, staged, diff: patch, kind: /^Binary files .* differ$/m.test(patch) ? "binary" : "text",
533
+ currentExists, versions };
517
534
  }
518
535
  /** Read the index version for the editable working-tree comparison. The path is resolved beneath the
519
536
  * workspace before it becomes a Git object expression, and the blob stays within the file editor's
@@ -25,7 +25,7 @@ import { computeFileDiff } from "./file-diff.js";
25
25
  import { verifyCapability } from "./capability.js";
26
26
  import { FileReviewThreads } from "./file-review-threads.js";
27
27
  import { toolSelection } from "./agents.js";
28
- import { workspaceReviewPath } from "../shared/file-review.js";
28
+ import { FILE_REVIEW_DISCUSSION_TOOLS, workspaceReviewPath } from "../shared/file-review.js";
29
29
  import { conversationWorkspace } from "./model-filter.js";
30
30
  import { describeSchedule } from "./scheduled-tasks.js";
31
31
  import { MAX_KNOWLEDGE_REQUEST_BYTES } from "./knowledge.js";
@@ -488,11 +488,11 @@ export function createHttpServer(options) {
488
488
  return;
489
489
  }
490
490
  const body = JSON.parse(payload.text);
491
- if (body.action !== undefined && body.action !== "list" && body.action !== "reply")
491
+ if (body.action !== undefined && body.action !== "list" && body.action !== "reply" && body.action !== "create")
492
492
  throw new Error("未知批注工具操作。");
493
- const tool = body.action === "list" ? "review_list" : "review_reply";
493
+ const tool = body.action === "create" ? "review_create" : body.action === "list" ? "review_list" : "review_reply";
494
494
  const agent = await context.runtime.agentFor?.(conversation);
495
- const selection = toolSelection(agent?.tools, { extraAllowedTools: ["review_list", "review_reply"] });
495
+ const selection = toolSelection(agent?.tools, { extraAllowedTools: FILE_REVIEW_DISCUSSION_TOOLS });
496
496
  if (conversation.agentId && context.runtime.agentFor && !agent || selection.excludeTools?.includes(tool) || selection.tools && !selection.tools.includes(tool)) {
497
497
  json(403, { error: "当前 Agent 没有此批注工具的权限。" });
498
498
  return;
@@ -501,6 +501,14 @@ export function createHttpServer(options) {
501
501
  json(403, { error: "当前执行已经结束。" });
502
502
  return;
503
503
  }
504
+ if (tool === "review_create") {
505
+ const workspace = conversation.workspaceId ? store.workspace(conversation.workspaceId) : undefined;
506
+ if (!workspace || workspace.closedAt)
507
+ throw new Error("当前执行没有有效工作区。");
508
+ const thread = await fileReviewThreads.agentCreate(workspace, { conversationId, agentName: agent?.name }, body, () => runService.isRunning(conversationId) && !store.conversation(conversationId)?.archivedAt && !!store.workspace(workspace.id) && !store.workspace(workspace.id)?.closedAt);
509
+ json(200, { id: thread.id, path: thread.path, start: thread.start, end: thread.end, created: true });
510
+ return;
511
+ }
504
512
  const workspaces = new Set([conversation.workspaceId, conversation.groupExecution?.workspaceId]);
505
513
  const scopes = [...workspaces].flatMap(workspaceId => {
506
514
  const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
@@ -523,8 +531,8 @@ export function createHttpServer(options) {
523
531
  const matches = entries.filter(thread => (body.includeResolved === true || !thread.resolvedAt)
524
532
  && (!path || [thread.path, thread.currentPath, ...thread.additional?.map(item => item.path) ?? []]
525
533
  .some(item => item && workspaceReviewPath(item, thread.cwd) === path)));
526
- const page = matches.slice(offset, offset + 20).map(({ id, path, currentPath, cwd, side, start, end, text, resolvedAt, replies, workspaceId }) => ({ id, workspaceId, path: workspaceReviewPath(path, cwd), currentPath: currentPath && workspaceReviewPath(currentPath, cwd),
527
- side, start, end, text, resolvedAt, replyCount: replies.length }));
534
+ const page = matches.slice(offset, offset + 20).map(({ id, path, currentPath, cwd, side, start, end, text, resolvedAt, replies, workspaceId, agentName, diffSnapshot }) => ({ id, workspaceId, path: workspaceReviewPath(path, cwd), currentPath: currentPath && workspaceReviewPath(currentPath, cwd),
535
+ side, start, end, text, resolvedAt, agentName, diffSnapshot, replyCount: replies.length }));
528
536
  json(200, { threads: page, nextOffset: matches.length > offset + page.length ? offset + page.length : undefined });
529
537
  return;
530
538
  }
@@ -534,7 +542,7 @@ export function createHttpServer(options) {
534
542
  json(200, { id: thread.id, replied: true });
535
543
  }
536
544
  catch (error) {
537
- json(400, { error: error instanceof Error ? error.message : "无法回复批注。" });
545
+ json(400, { error: error instanceof Error ? error.message : "无法处理批注工具请求。" });
538
546
  }
539
547
  return;
540
548
  }
@@ -549,10 +557,19 @@ export function createHttpServer(options) {
549
557
  const worktreeId = url.searchParams.get("worktreeId");
550
558
  const checkout = worktreeId ? await resolveGitWorktree(workspace.path, worktreeId) : undefined;
551
559
  let owner = checkout ? store.workspaces().find(item => !item.closedAt && !relative(resolve(item.path), resolve(checkout.path))) : workspace;
552
- const root = await resolveFileCwd(checkout?.path ?? workspace.path, checkout ? "" : url.searchParams.get("cwd"));
553
- const cwd = relative(resolve(checkout?.path ?? workspace.path), root).replaceAll("\\", "/");
554
560
  if (request.method === "GET") {
555
- json(200, { threads: owner ? fileReviewThreads.list({ workspaceId: owner.id, cwd }) : [] });
561
+ const scope = owner && { workspaceId: owner.id, cwd: "" };
562
+ const original = url.searchParams.get("snapshot");
563
+ if (original !== null) {
564
+ const saved = scope && fileReviewThreads.snapshot(scope, original);
565
+ if (!saved) {
566
+ json(404, { error: "原差异快照已不可用。批注中仍保留原代码摘录。" });
567
+ return;
568
+ }
569
+ json(200, saved);
570
+ }
571
+ else
572
+ json(200, { threads: scope ? fileReviewThreads.list(scope) : [] });
556
573
  return;
557
574
  }
558
575
  if (request.method !== "POST") {
@@ -564,7 +581,7 @@ export function createHttpServer(options) {
564
581
  json(403, { error: "批注操作需要同源访问。" });
565
582
  return;
566
583
  }
567
- const payload = await readRequestText(request, 2_500_000);
584
+ const payload = await readRequestText(request, 24_000_000);
568
585
  if (payload.tooLarge) {
569
586
  json(413, { error: "批注请求过大。" });
570
587
  return;
@@ -577,9 +594,12 @@ export function createHttpServer(options) {
577
594
  }
578
595
  if (!owner)
579
596
  throw new Error("找不到此工作树的批注。");
580
- const scope = { workspaceId: owner.id, cwd };
597
+ const scope = { workspaceId: owner.id, cwd: "" };
581
598
  if (body.action === "create") {
582
- json(200, { threads: fileReviewThreads.create(scope, body.comments) });
599
+ const base = checkout?.path ?? workspace.path;
600
+ const root = await resolveFileCwd(base, checkout ? "" : url.searchParams.get("cwd"));
601
+ scope.cwd = relative(resolve(base), root).replaceAll("\\", "/");
602
+ json(200, { threads: fileReviewThreads.create(scope, body.comments, undefined, body.diffSnapshot) });
583
603
  }
584
604
  else if (body.action === "reply") {
585
605
  if (typeof body.id !== "string" || typeof body.requestKey !== "string" || !/^[0-9a-f-]{36}$/.test(body.requestKey)) {
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { RpcChannel } from "./rpc-channel.js";
3
3
  export { RpcChannel } from "./rpc-channel.js";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { FILE_REVIEW_DISCUSSION_TOOLS } from "../shared/file-review.js";
5
6
  import { KNOWLEDGE_IMPORT_TOOL_NAME, KNOWLEDGE_TOOL_NAME } from "./knowledge.js";
6
7
  import { DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME } from "./documents.js";
7
8
  import { PRESENTATION_TOOL_NAMES } from "./presentations/service.js";
@@ -1543,7 +1544,7 @@ export class PiRpcRuntime {
1543
1544
  extensionToolNames() {
1544
1545
  const names = [TASK_TOOL_NAME, TODO_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register"];
1545
1546
  if (process.env.SUPER_PI_REVIEW_ENDPOINT)
1546
- names.push("review_list", "review_reply");
1547
+ names.push(...FILE_REVIEW_DISCUSSION_TOOLS);
1547
1548
  if (this.memory)
1548
1549
  names.push("memory", "skill_manage", "session_search", "agent_handbook");
1549
1550
  if (this.knowledge)
@@ -1787,7 +1788,7 @@ export class PiRpcRuntime {
1787
1788
  // allowlist and naming a tool Pi has not registered would change the spawn line for every other
1788
1789
  // mode. The prompt asks for a bare JSON array and nothing else; if the model spends a turn on a
1789
1790
  // tool call anyway the reranker times out and falls back to the lexical order.
1790
- const reviewTools = extensionArgs.length && process.env.SUPER_PI_REVIEW_ENDPOINT ? ["review_list", "review_reply"] : [];
1791
+ const reviewTools = extensionArgs.length && process.env.SUPER_PI_REVIEW_ENDPOINT ? FILE_REVIEW_DISCUSSION_TOOLS : [];
1791
1792
  const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: agent?.id === "rsi-discussion" ? [] : [...reviewTools, ...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", "tool_shortcut", "tool_remove", ...(this.options.orchestratorEndpoint ? [WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search", "agent_handbook"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME, ...PRESENTATION_TOOL_NAMES] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1792
1793
  // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
1793
1794
  // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
@@ -1,8 +1,45 @@
1
1
  export type ReviewSide = "file" | "before" | "after";
2
+ export declare const FILE_REVIEW_DISCUSSION_TOOLS: readonly ["review_list", "review_reply"];
3
+ export declare const FILE_REVIEW_TOOLS: readonly ["review_list", "review_reply", "review_create"];
2
4
  export type ReviewLine = {
3
5
  side: ReviewSide;
4
6
  number: number;
5
7
  };
8
+ export type ReviewVersion = {
9
+ kind: "commit" | "blob" | "content";
10
+ hash: string;
11
+ } | {
12
+ kind: "missing" | "unknown";
13
+ };
14
+ export type ReviewVersions = {
15
+ before: ReviewVersion;
16
+ after: ReviewVersion;
17
+ };
18
+ export type ReviewDiffRef = ReviewVersions & {
19
+ id: string;
20
+ path: string;
21
+ previousPath?: string;
22
+ };
23
+ export type ReviewDiffContent = {
24
+ mode: "patch";
25
+ diff: string | null;
26
+ kind: "text" | "binary" | "untracked";
27
+ limited?: boolean;
28
+ versions: ReviewVersions;
29
+ } | {
30
+ mode: "text";
31
+ before: string | null;
32
+ after: string | null;
33
+ beforeUnknown?: boolean;
34
+ };
35
+ export type ReviewDiffInput = ReviewDiffContent & {
36
+ path: string;
37
+ previousPath?: string;
38
+ };
39
+ export type ReviewDiffReplay = {
40
+ ref: ReviewDiffRef;
41
+ content: ReviewDiffContent;
42
+ };
6
43
  export type ReviewAnchor = {
7
44
  side: ReviewSide;
8
45
  start?: number;
@@ -36,6 +73,12 @@ export type ReviewThread = ReviewAnchor & {
36
73
  cwd: string;
37
74
  createdAt: string;
38
75
  resolvedAt?: string;
76
+ agentName?: string;
77
+ diffSnapshot?: ReviewDiffRef;
39
78
  replies: ReviewReply[];
40
79
  };
80
+ export declare function reviewContentHash(text: string): string;
81
+ export declare function reviewTextVersions(before: string | null, after: string | null, beforeUnknown?: boolean): ReviewVersions;
82
+ export declare function sameReviewVersions(a: ReviewVersions, b: ReviewVersions): boolean;
83
+ export declare function reviewExcerpt(lines: readonly string[]): string;
41
84
  export declare function workspaceReviewPath(path: string, cwd?: string): string;
@@ -1,3 +1,23 @@
1
+ import { sha256 } from "@noble/hashes/sha256";
2
+ import { bytesToHex } from "@noble/hashes/utils";
3
+ export const FILE_REVIEW_DISCUSSION_TOOLS = ["review_list", "review_reply"];
4
+ export const FILE_REVIEW_TOOLS = [...FILE_REVIEW_DISCUSSION_TOOLS, "review_create"];
5
+ export function reviewContentHash(text) { return bytesToHex(sha256(text)); }
6
+ export function reviewTextVersions(before, after, beforeUnknown = false) {
7
+ const version = (text) => text === null ? { kind: "missing" } : { kind: "content", hash: reviewContentHash(text) };
8
+ return { before: beforeUnknown ? { kind: "unknown" } : version(before), after: version(after) };
9
+ }
10
+ export function sameReviewVersions(a, b) {
11
+ return ["before", "after"].every(side => {
12
+ const left = a[side], right = b[side];
13
+ return left.kind !== "unknown" && left.kind === right.kind
14
+ && (!("hash" in left) || "hash" in right && left.hash === right.hash);
15
+ });
16
+ }
17
+ export function reviewExcerpt(lines) {
18
+ const text = lines.join("\n");
19
+ return text.length > 3000 ? text.slice(0, 3000) + "\n[…摘录截断]" : text;
20
+ }
1
21
  export function workspaceReviewPath(path, cwd = "") {
2
22
  const normalized = path.replaceAll("\\", "/").replace(/^\.\//, "");
3
23
  if (!cwd || /^(?:\/|[a-z]:)/i.test(normalized))
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "superPi": {
4
4
  "managedDirectListener": true
5
5
  },
6
- "version": "0.1.321",
6
+ "version": "0.1.323",
7
7
  "description": "Web control plane and companion for Pi",
8
8
  "license": "MIT",
9
9
  "type": "module",
@@ -516,6 +516,7 @@
516
516
  "@electron/get": "5.1.0",
517
517
  "@electron/packager": "20.3.0",
518
518
  "@git-diff-view/react": "^0.1.8",
519
+ "@noble/hashes": "1.8.0",
519
520
  "@types/diff": "^5.2.3",
520
521
  "@xterm/addon-fit": "^0.11.0",
521
522
  "@xterm/xterm": "^6.0.0",
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-D978o95T.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-DTIPfQj7.js","assets/dist-S5ntGzJB.js","assets/dist-Cus6_oaF.js","assets/dist-DP4hrTBF.js","assets/dist-Qjm1p8SR.js","assets/dist-BJHpSQV1.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{C as t,S as n,T as r,c as i,d as a,i as o,l as s,o as c,r as l,s as u,u as d,w as f,x as p}from"./index-D6OVl078.js";var m=e(r(),1);function ee(e,t,n,r){return[n.EditorView.decorations.compute([`selection`,`doc`],e=>n.Decoration.set(e.selection.ranges.filter(e=>!e.empty).map(e=>n.Decoration.mark({class:`cm-workbench-selectedText`}).range(e.from,e.to)),!0)),n.ViewPlugin.define(e=>{let n=null,i,a=!1,o=e=>{n&&(e===`expanded`?(a=!a,l()):n.querySelector(`input[name="${e===`caseSensitive`?`case`:e===`wholeWord`?`word`:`re`}"]`)?.click())},c=e=>{let t=s(e);t&&(e.preventDefault(),e.stopPropagation(),o(t))},l=()=>{if(!n||!i)return;let r=t.getSearchQuery(e.state);if(n.dataset.editorSearchExpanded=String(a),i.update({caseSensitive:r.caseSensitive,wholeWord:r.wholeWord,regexp:r.regexp,expanded:a}),n.querySelector(`[data-find-error]`)?.remove(),r.search&&!r.valid){let e=document.createElement(`output`);e.dataset.findError=``,e.setAttribute(`role`,`alert`),e.textContent=`正则表达式无效`,n.append(e)}},u=()=>{let s=r.querySelector(`.cm-panel.cm-search`);if(s===n)return;if(n?.removeEventListener(`keydown`,c,!0),i?.destroy(),n=s,!n){i=void 0;return}for(let[e,t,r]of[[`next`,`↓`,`下一处`],[`prev`,`↑`,`上一处`]]){let i=n.querySelector(`button[name="${e}"]`);i&&(i.textContent=t,i.setAttribute(`aria-label`,r),i.title=r)}let u=document.createElement(`span`);u.dataset.findControls=``,n.prepend(u);let f=t.getSearchQuery(e.state);a=!1,i=d(u,{...f,expanded:a},o),n.addEventListener(`keydown`,c,!0),l()},f=new MutationObserver(u);return f.observe(r,{childList:!0,subtree:!0}),u(),{update(){l()},destroy(){f.disconnect(),n?.removeEventListener(`keydown`,c,!0),i?.destroy()}}}),e.Prec.highest(n.keymap.of([{key:`Mod-Shift-l`,run:t.selectSelectionMatches},{key:`Mod-h`,scope:`editor search-panel`,run:e=>(t.searchPanelOpen(e.state)||t.openSearchPanel(e),requestAnimationFrame(()=>{e.dom.isConnected&&r.querySelector(`[data-editor-search-options][aria-expanded="false"]`)?.click()}),!0)},...[`c`,`w`,`r`].map(e=>({key:`Alt-${e}`,run:n=>{t.searchPanelOpen(n.state)||t.openSearchPanel(n);let r=t.getSearchQuery(n.state);return n.dispatch({effects:t.setSearchQuery.of(new t.SearchQuery({...r,...e===`c`?{caseSensitive:!r.caseSensitive}:e===`w`?{wholeWord:!r.wholeWord}:{regexp:!r.regexp}}))}),!0}}))])),n.panels({topContainer:r}),n.EditorView.scrollMargins.of(()=>({top:r.querySelector(`.cm-search`)?Math.min(r.getBoundingClientRect().height+8,Math.max(0,(r.parentElement?.clientHeight??0)-32)):0})),t.highlightSelectionMatches({wholeWords:!0,minSelectionLength:1,maxMatches:1e3}),t.search({top:!0}),e.EditorState.phrases.of({Find:`查找`,Replace:`替换为`,next:`下一处`,previous:`上一处`,all:`全部选中`,"match case":`区分大小写`,regexp:`正则表达式`,"by word":`全词匹配`,replace:`替换`,"replace all":`全部替换`,close:`关闭查找`,"current match":`当前匹配`,"on line":`所在行`})]}function te(e,t,n,r,a){let o=new e.Compartment,s=()=>{let r=c();return[e.EditorState.tabSize.of(r.tabSize),n.indentUnit.of(r.indent===`tabs`?` `:` `.repeat(r.tabSize)),r.wrap?t.EditorView.lineWrapping:[],r.whitespace?[t.highlightWhitespace(),t.highlightTrailingWhitespace()]:[]]};return[e.EditorState.allowMultipleSelections.of(!0),t.rectangularSelection(),t.crosshairCursor({key:`Alt`}),e.EditorState.phrases.of({"folded code":`已折叠代码`,unfold:`展开代码`,"Fold line":`折叠代码`,"Unfold line":`展开代码`}),t.highlightActiveLineGutter(),t.highlightSpecialChars(),t.dropCursor(),n.bracketMatching(),n.indentOnInput(),n.foldGutter(),r.closeBrackets(),e.Prec.highest(t.keymap.of([...r.closeBracketsKeymap,...n.foldKeymap,{key:`Alt-z`,run:()=>(u({wrap:!c().wrap}),!0)},{key:`Mod-Shift-z`,run:a.redo},{key:`Mod-y`,run:a.redo}])),o.of(s()),t.ViewPlugin.define(e=>({destroy:i(()=>{e.dispatch({effects:o.reconfigure(s())})})}))]}var h=new Map;function ne(e){let t=h.get(e);return t&&(h.delete(e),h.set(e,t)),t}function g(e,t){h.delete(e),h.set(e,t);let n=[...h.values()].reduce((e,t)=>e+t.state.doc.length,0);for(;h.size>32||n>16777216;){let e=h.keys().next().value;n-=h.get(e).state.doc.length,h.delete(e)}}var _=f(),re=262144,v=131072;function ie(e){return e.split(`.`).pop()?.toLowerCase()??``}function y(e,t,n=!1){let r=e=>n?`var(--git-diff-${e.slice(5)}, var(${e}))`:`var(${e})`;return e.HighlightStyle.define([{tag:t.tags.keyword,color:r(`--cm-keyword`)},{tag:t.tags.string,color:r(`--cm-string`)},{tag:t.tags.number,color:r(`--cm-number`)},{tag:t.tags.comment,color:r(`--cm-comment`),fontStyle:`italic`},{tag:t.tags.function(t.tags.variableName),color:r(`--cm-function`)},{tag:t.tags.typeName,color:r(`--cm-type`)},{tag:t.tags.className,color:r(`--cm-type`)},{tag:t.tags.propertyName,color:r(`--cm-property`)},{tag:t.tags.operator,color:r(`--cm-operator`)},{tag:t.tags.variableName,color:r(`--cm-variable`)}])}function b({path:e,value:r,onChange:i,jumpToLine:s,onSave:c,workspaceId:u,cwd:d=``,blame:f,onPosition:h,onView:b,readOnly:x=!1,languageOverride:S,onReviewLine:C}){let w=(0,m.useRef)(null),T=(0,m.useRef)(null),E=(0,m.useRef)(null),ae=(0,m.useRef)(null),D=JSON.stringify([u,d,e]),O=(0,m.useRef)(void 0),k=(0,m.useRef)(null),A=(0,m.useRef)(null),oe=(0,m.useRef)(null),j=(0,m.useRef)(null),M=(0,m.useRef)(null),N=(0,m.useRef)(null),P=(0,m.useRef)(i),F=(0,m.useRef)(c),I=(0,m.useRef)(r);I.current=r;let L=(0,m.useRef)(!1),R=(0,m.useRef)(b);R.current=b;let z=(0,m.useRef)(C);z.current=C;let B=!!C;P.current=i,F.current=c;let[V,se]=(0,m.useState)(!1),[H,U]=(0,m.useState)(!1),[W,ce]=(0,m.useState)(`0,0`),[G,le]=(0,m.useState)(0),[K,ue]=(0,m.useState)(1);(0,m.useEffect)(()=>{let i=!1,s,c,l,u,d;return(async()=>{try{let f=S??ie(e),p=n(f),[m,h,g,_,v,b,C,V,H]=await Promise.all([t(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([0,1])),t(()=>import(`./dist-DTIPfQj7.js`).then(e=>e.s),__vite__mapDeps([2,1,0])),t(()=>import(`./dist-S5ntGzJB.js`),__vite__mapDeps([3,0,1,2,4,5])),t(()=>import(`./dist-Qjm1p8SR.js`),__vite__mapDeps([6,0,1,2])),t(()=>import(`./dist-DP4hrTBF.js`).then(e=>e.d),__vite__mapDeps([5,1,0,2,4])),t(()=>import(`./dist-Cus6_oaF.js`).then(e=>e.n),__vite__mapDeps([4,1])),p?p().catch(e=>(console.warn(`[CodeMirror] Failed to load language for .${f}:`,e),null)):Promise.resolve(null),o().catch(e=>(console.warn(`[CodeMirror] Failed to build the blame extension:`,e),null)),t(()=>import(`./dist-BJHpSQV1.js`).then(e=>e.r),__vite__mapDeps([7,1,0,2,5,4]))]);if(i||!w.current||!T.current)return;ae.current=h.EditorView,u=v,d=b,A.current=m.Annotation.define(),oe.current=m.Transaction.addToHistory;let W=r.length<=re&&C!==null;c=new m.Compartment;let G=[h.lineNumbers(),h.highlightActiveLine(),h.drawSelection(),g.history(),h.keymap.of([g.indentWithTab,...g.defaultKeymap,...g.historyKeymap,..._.searchKeymap,{key:`Mod-s`,run:()=>(F.current(),!0)}]),h.EditorView.updateListener.of(e=>{e.docChanged&&!(A.current&&e.transactions.some(e=>e.annotation(A.current)===!0))&&P.current(e.state.doc.toString()),e.selectionSet&&ce(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),h.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(B&&G.push(a(h,e=>z.current?.(e),`file`)),G.push(h.EditorView.updateListener.of(e=>{e.selectionSet&&ue(e.state.selection.ranges.length),e.docChanged?L.current=!1:e.selectionSet&&(L.current=e.transactions.some(e=>e.isUserEvent(`select.search`)||e.isUserEvent(`select.pointer`)))}),ee(m,_,h,T.current),te(m,h,v,H,g)),x&&G.push(m.EditorState.readOnly.of(!0),h.EditorView.editable.of(!1),h.EditorView.contentAttributes.of({tabindex:`0`})),V&&!x&&(l=new m.Compartment,G.splice(1,0,l.of([])),G.push(V.base)),C)try{G.push(C)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${f}:`,e),W=!1}if(W&&c&&u&&d)try{G.push(c.of(u.syntaxHighlighting(y(u,d))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${f}:`,e),W=!1}let K=ne(D),q=K&&K.state.doc.toString()===I.current,J=q?K.state.update({effects:m.StateEffect.reconfigure.of(G)}).state:m.EditorState.create({doc:I.current,extensions:G});if(s=new h.EditorView({state:J,parent:w.current}),O.current=q?K.jump:void 0,ue(s.state.selection.ranges.length),ce(`${s.state.selection.main.from},${s.state.selection.main.to}`),q&&(s.scrollDOM.scrollTop=K.top,s.scrollDOM.scrollLeft=K.left,O.current=K.jump),i){s.destroy();return}E.current=s,R.current?.(s),se(W),U(!0),j.current=V,M.current=l??null,N.current=null,le(e=>e+1);let Y=new MutationObserver(()=>{let e=E.current;if(e&&W&&c&&u&&d)try{e.dispatch({effects:c.reconfigure(u.syntaxHighlighting(y(u,d)))})}catch{}});k.current=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),i||U(!0)}})(),()=>{i=!0,k.current?.disconnect(),k.current=null,s&&g(D,{state:s.state,top:s.scrollDOM.scrollTop,left:s.scrollDOM.scrollLeft,jump:O.current}),s?.destroy(),E.current=null,R.current?.(),U(!1),w.current&&(w.current.textContent=``)}},[D,x,S,B]),(0,m.useEffect)(()=>{let e=E.current;if(!e)return;let t=e.state.doc.toString();t!==r&&e.dispatch({changes:{from:0,to:t.length,insert:r},annotations:A.current?A.current.of(!0):void 0})},[r,H]),(0,m.useEffect)(()=>{let e=E.current;if(!e||!s||O.current===s.request)return;O.current=s.request;let t=e.state.doc.line(Math.min(Math.max(1,s.line),e.state.doc.lines)),n=Math.min(t.to,t.from+(s.column??1)-1);e.dispatch({selection:{anchor:t.to,head:n},effects:ae.current?.scrollIntoView(n,{y:`start`,yMargin:Math.round(e.scrollDOM.clientHeight/3)})}),e.focus()},[s,H]);let q=!!(f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===u);(0,m.useEffect)(()=>{let t=E.current,n=j.current,r=M.current;if(!t||!n||!r)return;let i=f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===u?f.response:null,a=i?l(i):null;N.current!==a&&(N.current=a,t.dispatch({effects:[n.setBlame.of(a),r.reconfigure(a?n.gutter:[])]}))},[f?.state,f?.response,f?.path,f?.workspaceId,e,u,G]);let J=E.current?.state.doc.toString()??r,Y=J.length<=v?J:J.slice(0,v),X=S??ie(e),Z=p(X),de=E.current?.state,Q=de?.selection.main.head,$=Q===void 0?void 0:de?.doc.lineAt(Q),fe=$?.number,pe=Q!==void 0&&$?Q-$.from+1:void 0;return(0,m.useEffect)(()=>{let e=E.current;if(H&&e&&(!s||O.current===s.request)){let t=e.state.selection.main.head,n=e.state.doc.lineAt(t);h?.({line:n.number,column:t-n.from+1,language:V&&Z||`纯文本`,highlight:V?X:`plain`,navigation:L.current,selections:e.state.selection.ranges.length})}},[H,fe,pe,V,Z,X,h,K,s?.request]),(0,m.useEffect)(()=>()=>h?.(),[h]),(0,_.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":Y,"data-file-content-truncated":J.length>v?`1`:`0`,"data-file-selection":W,"data-editor-selection-count":K,"data-file-editor-ready":H?`1`:`0`,"data-file-blame-gutter":q?`1`:void 0,onMouseDown:e=>{e.target.closest(`.cm-panels`)||E.current?.focus()},children:[(0,_.jsx)(`div`,{className:`file-cm`,ref:w,"aria-label":`${x?`查看`:`编辑`} ${e}`}),(0,_.jsx)(`div`,{className:`workbench-editor-search`,ref:T,"data-editor-find-host":`file`}),(!H||!h)&&(0,_.jsxs)(`div`,{className:`file-editor-status`,children:[!H&&(0,_.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),H&&Q!==void 0&&$&&(0,_.jsxs)(`span`,{children:[`第 `,$.number,` 行,第 `,Q-$.from+1,` 列`]}),H&&!V&&(0,_.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),H&&V&&Z&&(0,_.jsx)(`span`,{"data-file-highlight-status":X,children:Z})]})]})}export{b as CodeMirrorEditor,ee as n,te as t,y as themeHighlightStyle};