@evandu/super-pi 0.1.294 → 0.1.296
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.
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +27 -17
- package/dist/client/assets/{CodeMirrorEditor-CxuPc1PQ.css → CodeMirrorEditor--5LzaKEZ.css} +1 -1
- package/dist/client/assets/CodeMirrorEditor-h1p8ZevT.js +2 -0
- package/dist/client/assets/GitDiffEditor-wJa0EI5q.js +29 -0
- package/dist/client/assets/{dist-Dc1MBGAG.js → dist-699T9mBC.js} +1 -1
- package/dist/client/assets/{dist-Dvb0SqcK.js → dist-B2l9cUU9.js} +2 -2
- package/dist/client/assets/dist-BJHpSQV1.js +1 -0
- package/dist/client/assets/{dist-Cx00EZKR.js → dist-BUY8ZNeZ.js} +9 -9
- package/dist/client/assets/{dist-D71y2EI1.js → dist-BX5MJasK.js} +1 -1
- package/dist/client/assets/{dist-QzbOCAU6.js → dist-BXqtlD7O.js} +1 -1
- package/dist/client/assets/{dist-AW5lyI3I.js → dist-BqSTJyq9.js} +1 -1
- package/dist/client/assets/{dist-DuvGReu-.js → dist-CAlPBcem.js} +1 -1
- package/dist/client/assets/{dist-BGxkyh6e.js → dist-CVPY8uK1.js} +1 -1
- package/dist/client/assets/{dist-CKF2Jksy.js → dist-DLNOWOmk.js} +1 -1
- package/dist/client/assets/dist-DP4hrTBF.js +3 -0
- package/dist/client/assets/{dist-B3-a6uF0.js → dist-DTIPfQj7.js} +5 -5
- package/dist/client/assets/{dist-Dds-qLxY.js → dist-Dfhu-vbV.js} +4 -4
- package/dist/client/assets/{dist-BV64A9Ji.js → dist-Jg3fJuzH.js} +1 -1
- package/dist/client/assets/{dist-scBkrwv-.js → dist-Qjm1p8SR.js} +2 -2
- package/dist/client/assets/{dist-CX_Hm4GS.js → dist-S5ntGzJB.js} +1 -1
- package/dist/client/assets/{dist-BRVQKlcp.js → dist-X4BHLQqs.js} +1 -1
- package/dist/client/assets/{dist-DeD9copn.js → dist-dybF9Ag8.js} +1 -1
- package/dist/client/assets/{dist-BJxfd7yb.js → dist-gDvn1xVj.js} +5 -5
- package/dist/client/assets/index-CPfz3vPM.css +1 -0
- package/dist/client/assets/index-RW-EQEae.js +354 -0
- package/dist/client/index.html +2 -2
- package/dist/server/application/run-service.d.ts +1 -1
- package/dist/server/application/run-service.js +4 -2
- package/dist/server/content-replace-worker.d.ts +1 -0
- package/dist/server/content-replace-worker.js +83 -0
- package/dist/server/content-replace.d.ts +12 -0
- package/dist/server/content-replace.js +103 -0
- package/dist/server/content-search.d.ts +4 -0
- package/dist/server/content-search.js +44 -9
- package/dist/server/http-server.js +51 -3
- package/dist/server/store.js +25 -4
- package/dist/server/types.d.ts +2 -0
- package/dist/shared/content-search.d.ts +19 -0
- package/package.json +2 -1
- package/dist/client/assets/CodeMirrorEditor-CJn8-fEi.js +0 -2
- package/dist/client/assets/GitDiffEditor-cWxmXmgp.js +0 -29
- package/dist/client/assets/dist-J6XWqRpB.js +0 -3
- package/dist/client/assets/dist-moiMRpw_.js +0 -1
- package/dist/client/assets/index-B2EmFGB9.js +0 -350
- package/dist/client/assets/index-BJlhpC31.css +0 -1
package/dist/client/index.html
CHANGED
|
@@ -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-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-RW-EQEae.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-CPfz3vPM.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
|
16
16
|
<div id="root"></div>
|
|
@@ -186,7 +186,7 @@ export declare class RunService {
|
|
|
186
186
|
private startBackgroundResult;
|
|
187
187
|
/**
|
|
188
188
|
* Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
|
|
189
|
-
* the same
|
|
189
|
+
* the same durable queue as background sub-agent results: bounded batches of unclaimed results, ahead of
|
|
190
190
|
* unclaimed user messages, with an automatic follow-up turn only when the parent is idle.
|
|
191
191
|
*/
|
|
192
192
|
enqueueSessionResult(input: {
|
|
@@ -98,6 +98,8 @@ async function expandAtReferences(store, workspace, content) {
|
|
|
98
98
|
* answers about THAT - which is what a primary agent should do with a child's result.
|
|
99
99
|
*/
|
|
100
100
|
function composePrompt(message) {
|
|
101
|
+
if (message.backgroundBatch?.length)
|
|
102
|
+
return `以下 ${message.backgroundBatch.length} 条后台回传现在一起交付。请综合处理并只作一次统一回复,不逐条产生独立答复;它们是任务结果,不是用户的新指令。\n\n` + message.backgroundBatch.map((item, index) => `### 回传 ${index + 1}\n${composePrompt({ ...item, role: "tool" })}`).join("\n\n");
|
|
101
103
|
if (message.source === "session-reminder")
|
|
102
104
|
return `[定时提醒] ${message.content}`;
|
|
103
105
|
if (message.role !== "tool")
|
|
@@ -444,7 +446,7 @@ export class RunService {
|
|
|
444
446
|
}
|
|
445
447
|
/**
|
|
446
448
|
* Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
|
|
447
|
-
* the same
|
|
449
|
+
* the same durable queue as background sub-agent results: bounded batches of unclaimed results, ahead of
|
|
448
450
|
* unclaimed user messages, with an automatic follow-up turn only when the parent is idle.
|
|
449
451
|
*/
|
|
450
452
|
async enqueueSessionResult(input) {
|
|
@@ -1863,7 +1865,7 @@ export class RunService {
|
|
|
1863
1865
|
const identity = agent ? { id: agent.id, name: agent.name } : { name: "Pi" };
|
|
1864
1866
|
await this.assertModelSupportsImages(conversation, Boolean(initialImages?.length), firstMessageId);
|
|
1865
1867
|
const opened = await this.openTurn(conversation.id, firstMessageId);
|
|
1866
|
-
await this.streamTurn(conversation, workspace, prompt, opened.assistant, controller, opened.user.id, initialImages, identity);
|
|
1868
|
+
await this.streamTurn(conversation, workspace, opened.user.backgroundBatch?.length ? composePrompt(opened.user) : prompt, opened.assistant, controller, opened.user.id, initialImages, identity);
|
|
1867
1869
|
for (;;) {
|
|
1868
1870
|
if (controller.signal.aborted)
|
|
1869
1871
|
break;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
// Keep user regular expressions outside the service event loop; the caller owns the time budget.
|
|
3
|
+
try {
|
|
4
|
+
const { content, query, replacement, regexp, wholeWord, caseSensitive, preserveCase } = workerData;
|
|
5
|
+
const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6
|
+
const expression = new RegExp(wholeWord ? `(?<![\\p{L}\\p{N}\\p{M}\\p{Pc}])(?:${regexp ? query : escaped})(?![\\p{L}\\p{N}\\p{M}\\p{Pc}])` : regexp ? query : escaped, "gmu" + (caseSensitive ? "" : "i"));
|
|
7
|
+
const matches = [];
|
|
8
|
+
let replacementBytes = 0;
|
|
9
|
+
const expand = (token, match) => {
|
|
10
|
+
if (token === "$$")
|
|
11
|
+
return "$";
|
|
12
|
+
if (token === "$&" || token === "$0")
|
|
13
|
+
return match[0];
|
|
14
|
+
if (token === "$`")
|
|
15
|
+
return content.slice(0, match.index);
|
|
16
|
+
if (token === "$'")
|
|
17
|
+
return content.slice(match.index + match[0].length);
|
|
18
|
+
if (token.startsWith("$<"))
|
|
19
|
+
return match.groups?.[token.slice(2, -1)] ?? token;
|
|
20
|
+
const index = Number(token.slice(1));
|
|
21
|
+
if (index > 0 && index < match.length)
|
|
22
|
+
return match[index] ?? "";
|
|
23
|
+
const first = Number(token[1]);
|
|
24
|
+
return token.length === 3 && first > 0 && first < match.length ? (match[first] ?? "") + token[2] : token;
|
|
25
|
+
};
|
|
26
|
+
const template = (text, match) => {
|
|
27
|
+
let result = "";
|
|
28
|
+
for (let i = 0; i < text.length;) {
|
|
29
|
+
const rest = text.slice(i);
|
|
30
|
+
const transformed = /^((?:\\[uUlL])+)(\$(?:\d{1,2}|<[^>]+>|&|0))/.exec(rest);
|
|
31
|
+
if (transformed) {
|
|
32
|
+
const characters = [...expand(transformed[2], match)];
|
|
33
|
+
let position = 0;
|
|
34
|
+
for (const modifier of transformed[1].matchAll(/\\([uUlL])/g)) {
|
|
35
|
+
const mode = modifier[1];
|
|
36
|
+
const end = mode === "U" || mode === "L" ? characters.length : Math.min(characters.length, position + 1);
|
|
37
|
+
for (let at = position; at < end; at++)
|
|
38
|
+
characters[at] = mode === "u" || mode === "U" ? characters[at].toUpperCase() : characters[at].toLowerCase();
|
|
39
|
+
if (mode === "u" || mode === "l")
|
|
40
|
+
position = end;
|
|
41
|
+
}
|
|
42
|
+
result += characters.join("");
|
|
43
|
+
i += transformed[0].length;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const token = /^(\$\$|\$&|\$`|\$'|\$<[^>]+>|\$\d{1,2})/.exec(rest);
|
|
47
|
+
if (token) {
|
|
48
|
+
result += expand(token[0], match);
|
|
49
|
+
i += token[0].length;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const escape = /^\\([ntr\\])/.exec(rest);
|
|
53
|
+
if (escape) {
|
|
54
|
+
result += { n: "\n", t: "\t", r: "\r", "\\": "\\" }[escape[1]];
|
|
55
|
+
i += 2;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
result += text[i++];
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
};
|
|
62
|
+
for (const match of content.matchAll(expression)) {
|
|
63
|
+
let after = regexp ? template(replacement, match) : replacement.replace(/\\([ntr\\])/g, (_, character) => ({ n: "\n", t: "\t", r: "\r", "\\": "\\" }[character]));
|
|
64
|
+
if (preserveCase && /\p{L}/u.test(match[0])) {
|
|
65
|
+
if (match[0] === match[0].toUpperCase())
|
|
66
|
+
after = after.toUpperCase();
|
|
67
|
+
else if (match[0] === match[0].toLowerCase())
|
|
68
|
+
after = after.toLowerCase();
|
|
69
|
+
else if (/^\p{Lu}\p{Ll}+$/u.test(match[0]))
|
|
70
|
+
after = after[0]?.toUpperCase() + after.slice(1).toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
replacementBytes += Buffer.byteLength(after, "utf8");
|
|
73
|
+
if (replacementBytes > 20 * 1024 * 1024)
|
|
74
|
+
throw new Error("替换后的内容过大,请缩小范围或简化替换表达式。");
|
|
75
|
+
matches.push({ from: match.index, to: match.index + match[0].length, after });
|
|
76
|
+
if (matches.length > 20000)
|
|
77
|
+
throw new Error("单个文件的替换次数超过上限,请缩小范围。");
|
|
78
|
+
}
|
|
79
|
+
parentPort.postMessage({ matches });
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
parentPort.postMessage({ error: error instanceof Error ? error.message : "替换表达式无效" });
|
|
83
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ContentSearchOptions } from "./content-search.js";
|
|
2
|
+
import type { ContentReplacePreview } from "../shared/content-search.js";
|
|
3
|
+
export declare function previewContentReplace(root: string, query: string, replacement: string, options: ContentSearchOptions & {
|
|
4
|
+
preserveCase?: boolean;
|
|
5
|
+
}): Promise<ContentReplacePreview>;
|
|
6
|
+
export declare function applyContentReplace(root: string, id: string, selected: string[]): Promise<{
|
|
7
|
+
applied: string[];
|
|
8
|
+
failed: {
|
|
9
|
+
path: string;
|
|
10
|
+
error: string;
|
|
11
|
+
}[];
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Worker } from "node:worker_threads";
|
|
3
|
+
import { FilesError, MAX_FILE_BYTES, readWorkspaceFile, writeWorkspaceFile } from "./files.js";
|
|
4
|
+
import { searchByContent } from "./content-search.js";
|
|
5
|
+
const previews = new Map();
|
|
6
|
+
async function replacementMatches(input) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const worker = new Worker(new URL("./content-replace-worker.js", import.meta.url), { workerData: input });
|
|
9
|
+
const timer = setTimeout(() => { void worker.terminate(); reject(new FilesError(400, "替换表达式执行超时,请简化表达式。", "regexp_timeout")); }, 3000);
|
|
10
|
+
worker.once("message", result => { clearTimeout(timer); void worker.terminate(); result.error ? reject(new FilesError(400, result.error, "bad_replace")) : resolve(result.matches); });
|
|
11
|
+
worker.once("error", error => { clearTimeout(timer); reject(error); });
|
|
12
|
+
worker.once("exit", code => { clearTimeout(timer); if (code)
|
|
13
|
+
reject(new FilesError(400, "替换表达式执行中断。", "replace_failed")); });
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export async function previewContentReplace(root, query, replacement, options) {
|
|
17
|
+
if (!query || query.length > 4096 || replacement.length > 8192 || query.includes("\0") || replacement.includes("\0"))
|
|
18
|
+
throw new FilesError(400, "搜索或替换文本无效。", "bad_replace");
|
|
19
|
+
const result = await searchByContent(root, query, { ...options, maxResults: 20000 });
|
|
20
|
+
if (!result.complete)
|
|
21
|
+
throw new FilesError(400, "搜索结果不完整,不能执行批量替换。请缩小范围并重新预览。", "partial_search");
|
|
22
|
+
const grouped = new Map();
|
|
23
|
+
for (const hit of result.hits) {
|
|
24
|
+
const rows = grouped.get(hit.path) ?? [];
|
|
25
|
+
rows.push(hit);
|
|
26
|
+
grouped.set(hit.path, rows);
|
|
27
|
+
}
|
|
28
|
+
if (grouped.size > 500)
|
|
29
|
+
throw new FilesError(400, "一次最多预览 500 个文件,请缩小范围。", "replace_limit");
|
|
30
|
+
const plan = { root, expires: Date.now() + 600000, files: [] };
|
|
31
|
+
const files = [];
|
|
32
|
+
let bytes = 0, outputBytes = 0, count = 0;
|
|
33
|
+
for (const [path, hits] of grouped) {
|
|
34
|
+
const file = await readWorkspaceFile(root, path);
|
|
35
|
+
bytes += file.meta.size;
|
|
36
|
+
if (bytes > 20 * 1024 * 1024)
|
|
37
|
+
throw new FilesError(400, "预览总量超过 20MB,请缩小范围。", "replace_limit");
|
|
38
|
+
const offsets = [0];
|
|
39
|
+
for (let i = 0; i < file.content.length; i++)
|
|
40
|
+
if (file.content[i] === "\n")
|
|
41
|
+
offsets.push(i + 1);
|
|
42
|
+
const expected = hits.flatMap(hit => (hit.ranges ?? []).map(range => ({ from: offsets[hit.line - 1] + range.from, to: offsets[hit.line - 1] + range.to })));
|
|
43
|
+
const matches = await replacementMatches({ content: file.content, query, replacement, regexp: !!options.regexp, wholeWord: !!options.wholeWord, caseSensitive: options.caseSensitive !== false, preserveCase: !!options.preserveCase });
|
|
44
|
+
if (matches.length !== expected.length || matches.some((match, index) => match.from !== expected[index].from || match.to !== expected[index].to))
|
|
45
|
+
throw new FilesError(409, `搜索与替换匹配不一致,文件可能已变化或表达式不兼容:${path}。请刷新搜索或简化表达式。`, "replace_mismatch");
|
|
46
|
+
const afterBytes = file.meta.size + matches.reduce((size, match) => size + Buffer.byteLength(match.after, "utf8") - Buffer.byteLength(file.content.slice(match.from, match.to), "utf8"), 0);
|
|
47
|
+
outputBytes += afterBytes;
|
|
48
|
+
if (afterBytes > MAX_FILE_BYTES || outputBytes > 20 * 1024 * 1024)
|
|
49
|
+
throw new FilesError(400, "替换后的文件或总量超过编辑器上限,请缩小范围。", "replace_limit");
|
|
50
|
+
const identified = matches.map((match, index) => ({ ...match, id: `${files.length}:${index}` }));
|
|
51
|
+
plan.files.push({ path, content: file.content, etag: file.meta.etag, matches: identified });
|
|
52
|
+
files.push({ path, matches: identified.map(match => {
|
|
53
|
+
let lo = 0, hi = offsets.length;
|
|
54
|
+
while (lo + 1 < hi) {
|
|
55
|
+
const middle = (lo + hi) >>> 1;
|
|
56
|
+
if (offsets[middle] <= match.from)
|
|
57
|
+
lo = middle;
|
|
58
|
+
else
|
|
59
|
+
hi = middle;
|
|
60
|
+
}
|
|
61
|
+
return { id: match.id, line: lo + 1, column: match.from - offsets[lo] + 1, before: file.content.slice(match.from, match.to).slice(0, 1000), after: match.after.slice(0, 1000) };
|
|
62
|
+
}) });
|
|
63
|
+
count += matches.length;
|
|
64
|
+
}
|
|
65
|
+
for (const [id, item] of previews)
|
|
66
|
+
if (item.expires < Date.now())
|
|
67
|
+
previews.delete(id);
|
|
68
|
+
if (previews.size >= 8)
|
|
69
|
+
previews.delete(previews.keys().next().value);
|
|
70
|
+
const id = randomUUID();
|
|
71
|
+
previews.set(id, plan);
|
|
72
|
+
return { id, files, count };
|
|
73
|
+
}
|
|
74
|
+
export async function applyContentReplace(root, id, selected) {
|
|
75
|
+
const plan = previews.get(id);
|
|
76
|
+
if (!plan || plan.root !== root || plan.expires < Date.now())
|
|
77
|
+
throw new FilesError(409, "替换预览已失效,请重新预览。", "stale_preview");
|
|
78
|
+
const selectedSet = new Set(selected);
|
|
79
|
+
const known = new Set(plan.files.flatMap(file => file.matches.map(match => match.id)));
|
|
80
|
+
if (!selectedSet.size || selectedSet.size > 20000 || [...selectedSet].some(id => !known.has(id)))
|
|
81
|
+
throw new FilesError(400, "请选择有效的替换项。", "bad_selection");
|
|
82
|
+
const chosen = plan.files.filter(file => file.matches.some(match => selectedSet.has(match.id)));
|
|
83
|
+
// Preflight all selected versions before the first write; every write validates again under its own lock.
|
|
84
|
+
for (const file of chosen)
|
|
85
|
+
if ((await readWorkspaceFile(root, file.path)).meta.etag !== file.etag)
|
|
86
|
+
throw new FilesError(409, `文件已变化,未应用替换:${file.path}。请重新预览。`, "stale");
|
|
87
|
+
const applied = [], failed = [];
|
|
88
|
+
for (const file of chosen) {
|
|
89
|
+
let content = file.content;
|
|
90
|
+
for (const match of [...file.matches].reverse())
|
|
91
|
+
if (selectedSet.has(match.id))
|
|
92
|
+
content = content.slice(0, match.from) + match.after + content.slice(match.to);
|
|
93
|
+
try {
|
|
94
|
+
await writeWorkspaceFile(root, file.path, content, file.etag);
|
|
95
|
+
applied.push(file.path);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
failed.push({ path: file.path, error: error instanceof Error ? error.message : "替换失败" });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
previews.delete(id);
|
|
102
|
+
return { applied, failed };
|
|
103
|
+
}
|
|
@@ -4,12 +4,16 @@ export type ContentSearchOptions = {
|
|
|
4
4
|
include?: string;
|
|
5
5
|
exclude?: string;
|
|
6
6
|
useIgnoreFiles?: boolean;
|
|
7
|
+
caseSensitive?: boolean;
|
|
8
|
+
wholeWord?: boolean;
|
|
9
|
+
regexp?: boolean;
|
|
7
10
|
signal?: AbortSignal;
|
|
8
11
|
maxResults?: number;
|
|
9
12
|
onHits?: (hits: ContentSearchHit[]) => Promise<void>;
|
|
10
13
|
resolveRipgrep?: () => Promise<string | undefined>;
|
|
11
14
|
};
|
|
12
15
|
export declare function isProtectedSearchPath(path: string): boolean;
|
|
16
|
+
export declare function searchGlobs(input?: string): string[];
|
|
13
17
|
export declare function searchByContent(root: string, query: string, options?: ContentSearchOptions): Promise<ContentSearchSummary & {
|
|
14
18
|
hits: ContentSearchHit[];
|
|
15
19
|
skipped: string[];
|
|
@@ -24,12 +24,41 @@ async function resolveSdkRipgrep() {
|
|
|
24
24
|
export function isProtectedSearchPath(path) {
|
|
25
25
|
return path.split("/").some((segment) => /^\.(?:git|super-pi)$/iu.test(segment));
|
|
26
26
|
}
|
|
27
|
-
function
|
|
28
|
-
const
|
|
27
|
+
export function searchGlobs(input) {
|
|
28
|
+
const patterns = [];
|
|
29
|
+
let depth = 0, start = 0;
|
|
30
|
+
for (let i = 0; i <= (input?.length ?? 0); i++) {
|
|
31
|
+
const character = input?.[i];
|
|
32
|
+
if (character === "{")
|
|
33
|
+
depth++;
|
|
34
|
+
if (character === "}")
|
|
35
|
+
depth--;
|
|
36
|
+
if (i === input?.length || character === "," && depth === 0) {
|
|
37
|
+
const pattern = input.slice(start, i).trim().replace(/^\.\//, "");
|
|
38
|
+
if (pattern)
|
|
39
|
+
patterns.push(pattern);
|
|
40
|
+
start = i + 1;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (depth !== 0)
|
|
44
|
+
throw new FilesError(400, "文件筛选规则中的花括号不匹配。", "bad_glob");
|
|
45
|
+
return patterns;
|
|
46
|
+
}
|
|
47
|
+
function ripgrepArgs(query, { exclude, useIgnoreFiles, caseSensitive = true, wholeWord, regexp }) {
|
|
48
|
+
const args = ["--no-config", "--json", "--hidden", "--no-follow", "--color=never", "--no-require-git", "--threads", "4"];
|
|
49
|
+
if (!regexp)
|
|
50
|
+
args.push("--fixed-strings");
|
|
51
|
+
else
|
|
52
|
+
args.push("--engine", "auto");
|
|
53
|
+
args.push(caseSensitive ? "--case-sensitive" : "--ignore-case");
|
|
54
|
+
if (wholeWord)
|
|
55
|
+
args.push("--word-regexp");
|
|
56
|
+
if (query.includes("\n") || regexp && query.includes("\\n"))
|
|
57
|
+
args.push("--multiline");
|
|
29
58
|
if (useIgnoreFiles === false)
|
|
30
59
|
args.push("--no-ignore");
|
|
31
|
-
|
|
32
|
-
args.push("--glob", "!" +
|
|
60
|
+
for (const pattern of searchGlobs(exclude))
|
|
61
|
+
args.push("--glob", "!" + pattern);
|
|
33
62
|
// The final exclusions cannot be overridden by an include glob.
|
|
34
63
|
for (const name of [".git", ".super-pi"])
|
|
35
64
|
args.push("--iglob", `!**/${name}`, "--iglob", `!**/${name}/**`);
|
|
@@ -67,19 +96,23 @@ function makeHit(path, event) {
|
|
|
67
96
|
const start = Math.max(0, column - Math.floor(PREVIEW_LENGTH / 3));
|
|
68
97
|
const excerpt = fullLine.slice(start, start + PREVIEW_LENGTH);
|
|
69
98
|
const text = (start ? "…" : "") + excerpt + (start + excerpt.length < fullLine.length ? "…" : "");
|
|
70
|
-
|
|
99
|
+
const bytes = Buffer.from(fullLine);
|
|
100
|
+
return { path, name: basename(path), line, column, text, ranges: submatches?.map(match => ({ from: bytes.subarray(0, match.start).toString("utf8").length, to: bytes.subarray(0, match.end).toString("utf8").length })) };
|
|
71
101
|
}
|
|
72
102
|
export async function searchByContent(root, query, options = {}) {
|
|
73
103
|
const hits = [];
|
|
74
104
|
const skipped = [];
|
|
75
105
|
const reasons = new Set();
|
|
76
106
|
const result = () => ({ hits, skipped, complete: reasons.size === 0, truncated: reasons.size > 0, reasons: [...reasons] });
|
|
77
|
-
if (!query.
|
|
107
|
+
if (!query.length)
|
|
78
108
|
return result();
|
|
79
109
|
const timeout = AbortSignal.timeout(MAX_SEARCH_MS);
|
|
80
110
|
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
81
111
|
const maxResults = options.maxResults ?? MAX_CONTENT_RESULTS;
|
|
82
|
-
const
|
|
112
|
+
const includes = searchGlobs(options.include).flatMap(pattern => {
|
|
113
|
+
const normalized = pattern.endsWith("/") ? pattern + "**" : pattern;
|
|
114
|
+
return [normalized, "**/" + normalized, normalized + "/**", "**/" + normalized + "/**"];
|
|
115
|
+
});
|
|
83
116
|
const guard = createRootGuard(root);
|
|
84
117
|
await guard("");
|
|
85
118
|
const canonicalRoot = await realpath(root);
|
|
@@ -167,7 +200,7 @@ export async function searchByContent(root, query, options = {}) {
|
|
|
167
200
|
if (path === ".." || path.startsWith("../") || isAbsolute(path) || isProtectedSearchPath(path))
|
|
168
201
|
path = "";
|
|
169
202
|
// A positive rg glob overrides ignore files. Match includes separately so users can combine both.
|
|
170
|
-
if (
|
|
203
|
+
if (includes.length && !includes.some(pattern => posix.matchesGlob(path, pattern)))
|
|
171
204
|
path = "";
|
|
172
205
|
}
|
|
173
206
|
else if (event.type === "match" && path) {
|
|
@@ -217,7 +250,9 @@ export async function searchByContent(root, query, options = {}) {
|
|
|
217
250
|
if (timeout.aborted)
|
|
218
251
|
reasons.add("time");
|
|
219
252
|
if (!signal.aborted && !reasons.has("results") && code !== 0 && code !== 1) {
|
|
220
|
-
if (
|
|
253
|
+
if (/regex|PCRE2|unclosed|repetition|look-around/i.test(diagnostic))
|
|
254
|
+
throw new FilesError(400, "正则表达式无效或当前搜索引擎不支持该表达式。", "bad_regexp");
|
|
255
|
+
if (/glob|error parsing|invalid definition/imu.test(diagnostic))
|
|
221
256
|
throw new FilesError(400, "文件筛选规则无效。", "bad_glob");
|
|
222
257
|
if (!diagnostic.startsWith("rg: No files were searched"))
|
|
223
258
|
reasons.add("unreadable");
|
|
@@ -49,6 +49,7 @@ import { MESSAGE_FRAME_CSP, MESSAGE_HTML_CSP } from "../shared/message-media.js"
|
|
|
49
49
|
import { verifyDirectChildScope, verifyListParentScope, verifyReportTargetScope, verifySpawnParentScope } from "./session-tree-scope.js";
|
|
50
50
|
import { CHILD_SESSION_LOCK_REASON } from "../shared/child-session-lock.js";
|
|
51
51
|
import { isProtectedSearchPath, MAX_CONTENT_RESULTS, searchByContent } from "./content-search.js";
|
|
52
|
+
import { applyContentReplace, previewContentReplace } from "./content-replace.js";
|
|
52
53
|
import { getAvailableSkills, readSkill } from "./skills.js";
|
|
53
54
|
/**
|
|
54
55
|
* THE NAME INDEX FOR ONE WORKSPACE, created on first use and then kept.
|
|
@@ -3478,6 +3479,52 @@ export function createHttpServer(options) {
|
|
|
3478
3479
|
json(200, query ? store.searchConversationMessages(workspaceId, query) : { hits: [], truncated: false });
|
|
3479
3480
|
return;
|
|
3480
3481
|
}
|
|
3482
|
+
if (url.pathname === "/api/files/replace") {
|
|
3483
|
+
const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body)); };
|
|
3484
|
+
try {
|
|
3485
|
+
if (request.method !== "POST") {
|
|
3486
|
+
json(405, { error: "替换需要 POST 请求。" });
|
|
3487
|
+
return;
|
|
3488
|
+
}
|
|
3489
|
+
const workspaceId = url.searchParams.get("workspaceId")?.trim();
|
|
3490
|
+
const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
|
|
3491
|
+
if (!workspace || workspace.closedAt) {
|
|
3492
|
+
json(404, { error: "找不到这个工作区。" });
|
|
3493
|
+
return;
|
|
3494
|
+
}
|
|
3495
|
+
const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
|
|
3496
|
+
await explorerPath(workspace.path, root, "", true);
|
|
3497
|
+
const input = await readRequestText(request, 512000);
|
|
3498
|
+
if (input.tooLarge) {
|
|
3499
|
+
json(413, { error: "替换请求过大。" });
|
|
3500
|
+
return;
|
|
3501
|
+
}
|
|
3502
|
+
const body = JSON.parse(input.text);
|
|
3503
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
3504
|
+
throw new FilesError(400, "替换请求需要一个对象。", "bad_replace");
|
|
3505
|
+
if (body.action === "preview") {
|
|
3506
|
+
if (typeof body.query !== "string" || typeof body.replacement !== "string" || [body.include, body.exclude].some(value => value !== undefined && (typeof value !== "string" || value.length > 512 || /[\0\r\n]/.test(value) || /^!/.test(value))))
|
|
3507
|
+
throw new FilesError(400, "搜索和替换参数无效。", "bad_replace");
|
|
3508
|
+
json(200, await previewContentReplace(root, body.query, body.replacement, { include: body.include, exclude: body.exclude, useIgnoreFiles: body.ignore !== false, caseSensitive: body.caseSensitive !== false, wholeWord: body.wholeWord === true, regexp: body.regexp === true, preserveCase: body.preserveCase === true }));
|
|
3509
|
+
}
|
|
3510
|
+
else if (body.action === "apply" && typeof body.id === "string" && Array.isArray(body.selected) && body.selected.every((id) => typeof id === "string")) {
|
|
3511
|
+
const result = await serializeWorkspaceWrite(workspace.path, () => applyContentReplace(root, body.id, body.selected));
|
|
3512
|
+
const paths = await Promise.all(result.applied.map(path => workspacePathFromSession(workspace.path, root, path)));
|
|
3513
|
+
for (const path of paths)
|
|
3514
|
+
refreshWorkspaceIndex(context.fileIndexes, workspace.id, path, workspace.path);
|
|
3515
|
+
if (paths.length)
|
|
3516
|
+
broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id, paths });
|
|
3517
|
+
json(200, result);
|
|
3518
|
+
}
|
|
3519
|
+
else
|
|
3520
|
+
throw new FilesError(400, "替换操作无效。", "bad_replace");
|
|
3521
|
+
}
|
|
3522
|
+
catch (error) {
|
|
3523
|
+
const described = describeFilesError(error);
|
|
3524
|
+
json(described.status, described.body);
|
|
3525
|
+
}
|
|
3526
|
+
return;
|
|
3527
|
+
}
|
|
3481
3528
|
if (url.pathname === "/api/files/search") {
|
|
3482
3529
|
const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body)); };
|
|
3483
3530
|
const controller = new AbortController();
|
|
@@ -3502,7 +3549,7 @@ export function createHttpServer(options) {
|
|
|
3502
3549
|
return;
|
|
3503
3550
|
}
|
|
3504
3551
|
const workspaceId = url.searchParams.get("workspaceId")?.trim();
|
|
3505
|
-
const query = url.searchParams.get("q")
|
|
3552
|
+
const query = url.searchParams.get("q") ?? "";
|
|
3506
3553
|
const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
|
|
3507
3554
|
if (!workspaceId || !workspace || workspace.closedAt) {
|
|
3508
3555
|
json(404, { error: "找不到这个工作区——它可能已经被关闭或删除。", code: "no_workspace" });
|
|
@@ -3514,8 +3561,8 @@ export function createHttpServer(options) {
|
|
|
3514
3561
|
const canonicalCwd = toRelative(await realpath(workspace.path), await realpath(root));
|
|
3515
3562
|
if (isProtectedSearchPath(cwd) || isProtectedSearchPath(canonicalCwd))
|
|
3516
3563
|
throw new FilesError(403, "不能搜索应用或 Git 内部目录。", "protected_path");
|
|
3517
|
-
if (query.length >
|
|
3518
|
-
json(400, { error: "
|
|
3564
|
+
if (query.length > 4096 || /\0/u.test(query)) {
|
|
3565
|
+
json(400, { error: "搜索词不能包含空字符,且不超过 4096 个字符。", code: "bad_query" });
|
|
3519
3566
|
return;
|
|
3520
3567
|
}
|
|
3521
3568
|
const include = url.searchParams.get("include")?.trim();
|
|
@@ -3532,6 +3579,7 @@ export function createHttpServer(options) {
|
|
|
3532
3579
|
}
|
|
3533
3580
|
const { hits, skipped, ...summary } = await searchByContent(root, query, {
|
|
3534
3581
|
include, exclude, useIgnoreFiles: url.searchParams.get("ignore") !== "0", signal: controller.signal,
|
|
3582
|
+
caseSensitive: url.searchParams.get("case") !== "0", wholeWord: url.searchParams.get("word") === "1", regexp: url.searchParams.get("regex") === "1",
|
|
3535
3583
|
onHits: stream ? (hits) => send({ type: "matches", hits }) : undefined,
|
|
3536
3584
|
});
|
|
3537
3585
|
if (controller.signal.aborted)
|
package/dist/server/store.js
CHANGED
|
@@ -2961,15 +2961,36 @@ export class Store {
|
|
|
2961
2961
|
if (index < 0)
|
|
2962
2962
|
throw new Error(`消息不存在或已被撤回:${messageId}`);
|
|
2963
2963
|
const user = conversation.messages[index];
|
|
2964
|
-
|
|
2964
|
+
const batch = [user];
|
|
2965
|
+
const isBackground = (message) => message.role === "tool" && !message.source && !message.images?.length && /<task id="[^"]+" state="[^"]+"/.test(message.content);
|
|
2966
|
+
if (isBackground(user) && user.delivery !== "sending") {
|
|
2967
|
+
const waiting = this.waitingMessages(conversation);
|
|
2968
|
+
const position = waiting.findIndex(message => message.id === user.id);
|
|
2969
|
+
let length = user.content.length;
|
|
2970
|
+
if (position >= 0)
|
|
2971
|
+
for (const message of waiting.slice(position + 1)) {
|
|
2972
|
+
if (message.delivery !== "waiting" || !isBackground(message) || batch.length >= 10 || length + message.content.length > 64000)
|
|
2973
|
+
break;
|
|
2974
|
+
batch.push(message);
|
|
2975
|
+
length += message.content.length;
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
if (batch.length > 1)
|
|
2979
|
+
user.backgroundBatch = batch.map(message => ({ id: message.id, content: message.content, createdAt: message.createdAt, backgroundTask: message.backgroundTask && structuredClone(message.backgroundTask) }));
|
|
2980
|
+
const batchedIds = new Set(batch.map(message => message.id));
|
|
2981
|
+
conversation.messages = conversation.messages.filter(message => !batchedIds.has(message.id));
|
|
2965
2982
|
let delivered = conversation.messages.length - 1;
|
|
2966
2983
|
while (delivered >= 0 && conversation.messages[delivered].delivery)
|
|
2967
2984
|
delivered--;
|
|
2968
2985
|
const deliveryIndex = delivered + 1;
|
|
2969
|
-
|
|
2970
|
-
|
|
2986
|
+
for (const message of batch) {
|
|
2987
|
+
delete message.delivery;
|
|
2988
|
+
if (message !== user)
|
|
2989
|
+
message.batchedInto = user.id;
|
|
2990
|
+
}
|
|
2991
|
+
conversation.messages.splice(deliveryIndex, 0, ...batch);
|
|
2971
2992
|
const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
|
|
2972
|
-
conversation.messages.splice(deliveryIndex +
|
|
2993
|
+
conversation.messages.splice(deliveryIndex + batch.length, 0, assistant);
|
|
2973
2994
|
const firstUser = conversation.messages.find((item) => item.role === "user");
|
|
2974
2995
|
const autoTitle = firstUser?.content.trim()
|
|
2975
2996
|
? firstUser.content.slice(0, 42)
|
package/dist/server/types.d.ts
CHANGED
|
@@ -114,6 +114,8 @@ export type ToolCallQuestion = {
|
|
|
114
114
|
answers?: QuestionAnswer[];
|
|
115
115
|
};
|
|
116
116
|
export type Message = {
|
|
117
|
+
backgroundBatch?: Pick<Message, "id" | "content" | "createdAt" | "backgroundTask">[];
|
|
118
|
+
batchedInto?: string;
|
|
117
119
|
backgroundTask?: BackgroundTaskSummary;
|
|
118
120
|
id: string;
|
|
119
121
|
role: MessageRole;
|
|
@@ -4,6 +4,25 @@ export type ContentSearchHit = {
|
|
|
4
4
|
line: number;
|
|
5
5
|
column: number;
|
|
6
6
|
text: string;
|
|
7
|
+
ranges?: {
|
|
8
|
+
from: number;
|
|
9
|
+
to: number;
|
|
10
|
+
}[];
|
|
11
|
+
};
|
|
12
|
+
export type ContentReplacement = {
|
|
13
|
+
id: string;
|
|
14
|
+
line: number;
|
|
15
|
+
column: number;
|
|
16
|
+
before: string;
|
|
17
|
+
after: string;
|
|
18
|
+
};
|
|
19
|
+
export type ContentReplacePreview = {
|
|
20
|
+
id: string;
|
|
21
|
+
files: {
|
|
22
|
+
path: string;
|
|
23
|
+
matches: ContentReplacement[];
|
|
24
|
+
}[];
|
|
25
|
+
count: number;
|
|
7
26
|
};
|
|
8
27
|
export type ContentSearchSummary = {
|
|
9
28
|
complete: boolean;
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"superPi": {
|
|
4
4
|
"managedDirectListener": true
|
|
5
5
|
},
|
|
6
|
-
"version": "0.1.
|
|
6
|
+
"version": "0.1.296",
|
|
7
7
|
"description": "Web control plane and companion for Pi",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"type": "module",
|
|
@@ -482,6 +482,7 @@
|
|
|
482
482
|
"scripts/session-row-escalation-browser.test.mjs"
|
|
483
483
|
],
|
|
484
484
|
"dependencies": {
|
|
485
|
+
"@codemirror/autocomplete": "6.20.4",
|
|
485
486
|
"@codemirror/commands": "^6.11.1",
|
|
486
487
|
"@codemirror/lang-cpp": "^6.0.3",
|
|
487
488
|
"@codemirror/lang-css": "^6.3.1",
|
|
@@ -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-B3-a6uF0.js","assets/dist-CX_Hm4GS.js","assets/dist-Cus6_oaF.js","assets/dist-J6XWqRpB.js","assets/dist-scBkrwv-.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{d as t,f as n,i as r,l as i,p as a,r as o,u as s}from"./index-B2EmFGB9.js";var c=e(a(),1);function l(e,t,n){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 t=()=>{let t=e.dom.querySelector(`.cm-panel.cm-search`);if(!t||t.querySelector(`[data-editor-search-options]`))return;let n=document.createElement(`button`);n.type=`button`,n.dataset.editorSearchOptions=``,n.textContent=`选项`,n.setAttribute(`aria-label`,`展开查找选项`),n.setAttribute(`aria-expanded`,`false`),n.onclick=()=>{let e=t.dataset.editorSearchExpanded!==`true`;t.dataset.editorSearchExpanded=String(e),n.setAttribute(`aria-expanded`,String(e)),n.setAttribute(`aria-label`,e?`收起查找选项`:`展开查找选项`)},t.append(n)},n=new MutationObserver(t);return n.observe(e.dom,{childList:!0,subtree:!0}),t(),{destroy(){n.disconnect()}}}),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":`所在行`})]}var u=n(),d=262144,f=131072;function p(e){return e.split(`.`).pop()?.toLowerCase()??``}function m(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 h({path:e,value:n,onChange:a,jumpToLine:h,onSave:g,workspaceId:_,blame:v,onPosition:y,readOnly:b=!1,languageOverride:x}){let S=(0,c.useRef)(null),C=(0,c.useRef)(null),w=(0,c.useRef)(null),T=(0,c.useRef)(void 0),E=(0,c.useRef)(null),D=(0,c.useRef)(null),O=(0,c.useRef)(null),k=(0,c.useRef)(null),A=(0,c.useRef)(null),j=(0,c.useRef)(null),M=(0,c.useRef)(a),N=(0,c.useRef)(g);M.current=a,N.current=g;let[P,F]=(0,c.useState)(!1),[I,L]=(0,c.useState)(!1),[R,z]=(0,c.useState)(`0,0`),[B,V]=(0,c.useState)(0);(0,c.useEffect)(()=>{let i=!1,a,o,c,u,f;return(async()=>{try{let h=x??p(e),g=s(h),[v,y,P,I,R,B,H,U]=await Promise.all([t(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([0,1])),t(()=>import(`./dist-B3-a6uF0.js`).then(e=>e.s),__vite__mapDeps([2,1,0])),t(()=>import(`./dist-CX_Hm4GS.js`),__vite__mapDeps([3,0,1,2,4,5])),t(()=>import(`./dist-scBkrwv-.js`),__vite__mapDeps([6,0,1,2])),t(()=>import(`./dist-J6XWqRpB.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])),g?g().catch(e=>(console.warn(`[CodeMirror] Failed to load language for .${h}:`,e),null)):Promise.resolve(null),r().catch(e=>(console.warn(`[CodeMirror] Failed to build the blame extension:`,e),null))]);if(i||!S.current)return;w.current=y.EditorView,u=R,f=B,D.current=v.Annotation.define(),O.current=v.Transaction.addToHistory;let W=n.length<=d&&H!==null;o=new v.Compartment;let G=[y.lineNumbers(),y.highlightActiveLine(),y.drawSelection(),P.history(),y.keymap.of([P.indentWithTab,...P.defaultKeymap,...P.historyKeymap,...I.searchKeymap,{key:`Mod-s`,run:()=>(N.current(),!0)}]),y.EditorView.updateListener.of(e=>{e.docChanged&&!(D.current&&e.transactions.some(e=>e.annotation(D.current)===!0))&&M.current(e.state.doc.toString()),e.selectionSet&&z(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),y.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(G.push(l(v,I,y)),b&&G.push(v.EditorState.readOnly.of(!0),y.EditorView.editable.of(!1),y.EditorView.contentAttributes.of({tabindex:`0`})),U&&!b&&(c=new v.Compartment,G.splice(1,0,c.of([])),G.push(U.base)),H)try{G.push(H)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${h}:`,e),W=!1}if(W&&o&&u&&f)try{G.push(o.of(u.syntaxHighlighting(m(u,f))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${h}:`,e),W=!1}let K=T.current,q=K?.scope===JSON.stringify([_,e])&&K.state.doc.toString()===n,J=q?K.state.update({effects:v.StateEffect.reconfigure.of(G)}).state:v.EditorState.create({doc:n,extensions:G});if(a=new y.EditorView({state:J,parent:S.current}),q&&(a.scrollDOM.scrollTop=K.top,a.scrollDOM.scrollLeft=K.left),i){a.destroy();return}C.current=a,F(W),L(!0),k.current=U,A.current=c??null,j.current=null,V(e=>e+1);let Y=new MutationObserver(()=>{let e=C.current;if(e&&W&&o&&u&&f)try{e.dispatch({effects:o.reconfigure(u.syntaxHighlighting(m(u,f)))})}catch{}});E.current=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),i||L(!0)}})(),()=>{i=!0,E.current?.disconnect(),E.current=null,a&&(T.current={scope:JSON.stringify([_,e]),state:a.state,top:a.scrollDOM.scrollTop,left:a.scrollDOM.scrollLeft}),a?.destroy(),C.current=null,L(!1),S.current&&(S.current.textContent=``)}},[e,b,x]),(0,c.useEffect)(()=>{let e=C.current;if(!e)return;let t=e.state.doc.toString();t!==n&&e.dispatch({changes:{from:0,to:t.length,insert:n},annotations:D.current?D.current.of(!0):void 0})},[n]),(0,c.useEffect)(()=>{let e=C.current;if(!e||!h)return;let t=e.state.doc.line(Math.min(Math.max(1,h.line),e.state.doc.lines)),n=Math.min(t.to,t.from+(h.column??1)-1);e.dispatch({selection:{anchor:t.to,head:n},effects:w.current?.scrollIntoView(n,{y:`start`,yMargin:Math.round(e.scrollDOM.clientHeight/3)})}),e.focus()},[h,I]);let H=!!(v&&v.state===`ready`&&v.response&&v.path===e&&v.workspaceId===_);(0,c.useEffect)(()=>{let t=C.current,n=k.current,r=A.current;if(!t||!n||!r)return;let i=v&&v.state===`ready`&&v.response&&v.path===e&&v.workspaceId===_?v.response:null,a=i?o(i):null;j.current!==a&&(j.current=a,t.dispatch({effects:[n.setBlame.of(a),r.reconfigure(a?n.gutter:[])]}))},[v?.state,v?.response,v?.path,v?.workspaceId,e,_,B]);let U=C.current?.state.doc.toString()??n,W=U.length<=f?U:U.slice(0,f),G=x??p(e),K=i(G),q=C.current?.state,J=q?.selection.main.head,Y=J===void 0?void 0:q?.doc.lineAt(J),X=Y?.number,Z=J!==void 0&&Y?J-Y.from+1:void 0;return(0,c.useEffect)(()=>{I&&X!==void 0&&Z!==void 0&&y?.({line:X,column:Z,language:P&&K||`纯文本`,highlight:P?G:`plain`})},[I,X,Z,P,K,G,y]),(0,c.useEffect)(()=>()=>y?.(),[y]),(0,u.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":W,"data-file-content-truncated":U.length>f?`1`:`0`,"data-file-selection":R,"data-file-editor-ready":I?`1`:`0`,"data-file-blame-gutter":H?`1`:void 0,onMouseDown:e=>{e.target.closest(`.cm-panels`)||C.current?.focus()},children:[(0,u.jsx)(`div`,{className:`file-cm`,ref:S,"aria-label":`${b?`查看`:`编辑`} ${e}`}),(!I||!y)&&(0,u.jsxs)(`div`,{className:`file-editor-status`,children:[!I&&(0,u.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),I&&J!==void 0&&Y&&(0,u.jsxs)(`span`,{children:[`第 `,Y.number,` 行,第 `,J-Y.from+1,` 列`]}),I&&!P&&(0,u.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),I&&P&&K&&(0,u.jsx)(`span`,{"data-file-highlight-status":G,children:K})]})]})}export{h as CodeMirrorEditor,l as t,m as themeHighlightStyle};
|