@evandu/super-pi 0.1.302 → 0.1.304
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/agents/super-pi-managed-model/index.ts +2 -0
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +23 -18
- package/dist/client/assets/CodeMirrorEditor-BgCUmuUG.js +2 -0
- package/dist/client/assets/GitDiffEditor-BT1PriQU.js +29 -0
- package/dist/client/assets/index-2PIw_FRw.css +1 -0
- package/dist/client/assets/index-BklBoCmG.js +355 -0
- package/dist/client/index.html +2 -2
- package/dist/server/application/catalog-service.js +2 -8
- package/dist/server/application/group-chat-service.js +13 -3
- package/dist/server/application/rsi-repairs.js +2 -2
- package/dist/server/application/rsi-service.js +13 -13
- package/dist/server/application/run-service.js +2 -0
- package/dist/server/explicit-file-open.d.ts +2 -0
- package/dist/server/explicit-file-open.js +3 -2
- package/dist/server/files.d.ts +4 -1
- package/dist/server/files.js +24 -8
- package/dist/server/http-server.js +5 -5
- package/dist/server/index.js +8 -2
- package/dist/server/managed-helper-model.d.ts +11 -0
- package/dist/server/managed-helper-model.js +58 -0
- package/dist/server/managed-model-adapter.js +4 -1
- package/dist/server/model-filter.d.ts +15 -0
- package/dist/server/model-filter.js +24 -0
- package/dist/server/pi-session.js +1 -1
- package/dist/server/rsi-http.js +11 -1
- package/dist/server/runtime.d.ts +1 -0
- package/dist/server/runtime.js +48 -4
- package/dist/server/store.d.ts +1 -0
- package/dist/server/store.js +7 -0
- package/dist/server/types.d.ts +1 -0
- package/dist/shared/rsi.d.ts +7 -2
- package/package.json +4 -1
- package/dist/client/assets/CodeMirrorEditor-BeVgHVpR.js +0 -2
- package/dist/client/assets/GitDiffEditor-D3hvVjdf.js +0 -29
- package/dist/client/assets/index-BAq4p4ug.js +0 -354
- package/dist/client/assets/index-BzYJAyfI.css +0 -1
package/dist/server/runtime.js
CHANGED
|
@@ -45,6 +45,9 @@ const traceLatency = (conversationId, phase, startedAt, extra = "") => {
|
|
|
45
45
|
return;
|
|
46
46
|
console.warn(`[super-pi latency] conversation=${conversationId} phase=${phase} elapsedMs=${Math.round(performance.now() - startedAt)}${extra ? ` ${extra}` : ""}`);
|
|
47
47
|
};
|
|
48
|
+
// Let the managed startup hook see an explicit helper selection before RPC commands are accepted.
|
|
49
|
+
const managedHelperArgs = (model) => process.env.SUPER_PI_MANAGED_CONFIG && model?.provider && model.modelId
|
|
50
|
+
? ["--provider", model.provider, "--model", model.modelId] : [];
|
|
48
51
|
/** A steer that provably never reached Pi; the caller may safely use the next turn instead. */
|
|
49
52
|
export class SteerUnavailableError extends Error {
|
|
50
53
|
}
|
|
@@ -2732,7 +2735,7 @@ export class PiRpcRuntime {
|
|
|
2732
2735
|
// The selected model is carried over, but the current conversation transcript and its live cache are
|
|
2733
2736
|
// deliberately not: title generation is an isolated, bounded one-shot request.
|
|
2734
2737
|
const selectedModel = conversation.model;
|
|
2735
|
-
const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--extension", shellQuote(modelPolicyExtensionPath())], {
|
|
2738
|
+
const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--extension", shellQuote(modelPolicyExtensionPath()), ...managedHelperArgs(selectedModel).map(arg => shellQuote(arg))], {
|
|
2736
2739
|
cwd: resolve(cwd),
|
|
2737
2740
|
env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir(), selectedModel?.provider) },
|
|
2738
2741
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -2768,6 +2771,7 @@ export class PiRpcRuntime {
|
|
|
2768
2771
|
if (modelResponse.success !== true)
|
|
2769
2772
|
throw new Error(modelResponse.error || `Pi 无法使用当前会话模型 ${selectedModel.provider}/${selectedModel.modelId}`);
|
|
2770
2773
|
}
|
|
2774
|
+
await this.confirmManagedHelperModel(channel, deadline, signal);
|
|
2771
2775
|
// Reasoning adds latency without improving a short session label. Keep this one-shot call fast
|
|
2772
2776
|
// even when the user's normal default thinking level is high.
|
|
2773
2777
|
const thinkingResponse = await channel.request({ id: "autotitle_thinking", type: "set_thinking_level", level: "off" }, Math.max(1, Math.min(30_000, deadline - Date.now())));
|
|
@@ -2784,7 +2788,10 @@ export class PiRpcRuntime {
|
|
|
2784
2788
|
transcript,
|
|
2785
2789
|
].join("\n"),
|
|
2786
2790
|
});
|
|
2787
|
-
let settled = false, text = "";
|
|
2791
|
+
let settled = false, text = "", failure;
|
|
2792
|
+
const noteTitleOutcome = (message, reason) => {
|
|
2793
|
+
failure = ["error", "aborted", "length"].includes(message?.stopReason ?? reason ?? "") ? message?.errorMessage || "模型未完成标题生成" : undefined;
|
|
2794
|
+
};
|
|
2788
2795
|
while (!settled && Date.now() < deadline) {
|
|
2789
2796
|
if (signal?.aborted)
|
|
2790
2797
|
throw new Error("已取消");
|
|
@@ -2793,6 +2800,11 @@ export class PiRpcRuntime {
|
|
|
2793
2800
|
continue;
|
|
2794
2801
|
if (record.type === "message_update" && record.assistantMessageEvent?.type === "text_delta")
|
|
2795
2802
|
text += record.assistantMessageEvent.delta ?? "";
|
|
2803
|
+
if (record.type === "message_update" && ["done", "error"].includes(record.assistantMessageEvent?.type ?? "")) {
|
|
2804
|
+
noteTitleOutcome(record.assistantMessageEvent?.message, record.assistantMessageEvent?.type === "error" ? "error" : record.assistantMessageEvent?.reason);
|
|
2805
|
+
}
|
|
2806
|
+
if (record.type === "agent_end" && !record.willRetry && record.messages)
|
|
2807
|
+
noteTitleOutcome([...record.messages].reverse().find(message => message.role === "assistant"));
|
|
2796
2808
|
if (record.type === "agent_settled")
|
|
2797
2809
|
settled = true;
|
|
2798
2810
|
if (record.type === "response" && record.id === "autotitle_prompt" && record.success === false)
|
|
@@ -2802,6 +2814,8 @@ export class PiRpcRuntime {
|
|
|
2802
2814
|
}
|
|
2803
2815
|
if (!settled)
|
|
2804
2816
|
throw new Error(`模型在 ${TIMEOUT_MS / 1000} 秒内没有返回标题`);
|
|
2817
|
+
if (failure)
|
|
2818
|
+
throw new Error(failure);
|
|
2805
2819
|
// A model asked for "only the title" still wraps it now and then. Stripping the wrappers is not
|
|
2806
2820
|
// cosmetic: without it a leading quote or a `Title:` prefix becomes the first characters of every
|
|
2807
2821
|
// title in the sidebar.
|
|
@@ -2849,11 +2863,40 @@ export class PiRpcRuntime {
|
|
|
2849
2863
|
await this.groupLifecycle?.forget(workspaceId, roomId);
|
|
2850
2864
|
await (this.memberSessions ??= new GroupMemberSessions(join(this.sessionDir, "group-members"))).removeRoom(workspaceId, roomId);
|
|
2851
2865
|
}
|
|
2866
|
+
async confirmManagedHelperModel(channel, deadline, signal) {
|
|
2867
|
+
if (!process.env.SUPER_PI_MANAGED_CONFIG)
|
|
2868
|
+
return;
|
|
2869
|
+
signal?.throwIfAborted();
|
|
2870
|
+
const remaining = deadline - Date.now();
|
|
2871
|
+
if (remaining <= 0)
|
|
2872
|
+
throw new Error("托管辅助请求在模型初始化完成前超时,请重试。");
|
|
2873
|
+
const request = channel.request({ id: "managed_helper_state", type: "get_state" }, Math.min(30_000, remaining));
|
|
2874
|
+
let abort;
|
|
2875
|
+
let response;
|
|
2876
|
+
try {
|
|
2877
|
+
response = signal ? await Promise.race([request, new Promise((_resolve, reject) => {
|
|
2878
|
+
abort = () => reject(signal.reason ?? new Error("已取消"));
|
|
2879
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
2880
|
+
if (signal.aborted)
|
|
2881
|
+
abort();
|
|
2882
|
+
})]) : await request;
|
|
2883
|
+
}
|
|
2884
|
+
finally {
|
|
2885
|
+
if (abort)
|
|
2886
|
+
signal?.removeEventListener("abort", abort);
|
|
2887
|
+
}
|
|
2888
|
+
signal?.throwIfAborted();
|
|
2889
|
+
if (response.success !== true)
|
|
2890
|
+
throw new Error(response.error || "无法确认托管辅助请求的模型状态。");
|
|
2891
|
+
if (!describeModel(response.data?.model)) {
|
|
2892
|
+
throw new Error("托管 Pi 尚未选定有效模型,请检查历史模型、默认模型与模型目录初始化状态后重试。此错误不表示入口缺少 API Key。");
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2852
2895
|
async completeOnce(input, sessionFile) {
|
|
2853
2896
|
if (!this.pi.found)
|
|
2854
2897
|
throw new Error(this.pi.reason);
|
|
2855
2898
|
const executable = Boolean(input.agent && input.onToolStart);
|
|
2856
|
-
const args = ["--mode", "rpc", ...(sessionFile ? ["--session", sessionFile] : ["--no-session"]), "--no-mcp"];
|
|
2899
|
+
const args = ["--mode", "rpc", ...(sessionFile ? ["--session", sessionFile] : ["--no-session"]), "--no-mcp", ...managedHelperArgs(input.model)];
|
|
2857
2900
|
if (executable)
|
|
2858
2901
|
args.push(...superPiExtensionPaths(repositoryRootFrom()).flatMap(path => ["--extension", path]));
|
|
2859
2902
|
else
|
|
@@ -2888,6 +2931,7 @@ export class PiRpcRuntime {
|
|
|
2888
2931
|
if (response.success !== true)
|
|
2889
2932
|
throw new Error(response.error || "Pi 无法选择指定模型");
|
|
2890
2933
|
}
|
|
2934
|
+
await this.confirmManagedHelperModel(channel, deadline, input.signal);
|
|
2891
2935
|
if (input.onModel) {
|
|
2892
2936
|
let selected = input.model;
|
|
2893
2937
|
try {
|
|
@@ -3534,7 +3578,7 @@ export function describeModel(value) {
|
|
|
3534
3578
|
if (!value || typeof value !== "object")
|
|
3535
3579
|
return undefined;
|
|
3536
3580
|
const model = value;
|
|
3537
|
-
if (typeof model.provider !== "string" || model.provider === "" || typeof model.id !== "string" || model.id === "")
|
|
3581
|
+
if (typeof model.provider !== "string" || model.provider === "" || typeof model.id !== "string" || model.id === "" || model.provider === "unknown" && model.id === "unknown")
|
|
3538
3582
|
return undefined;
|
|
3539
3583
|
const label = typeof model.name === "string" && model.name !== "" ? model.name : model.id;
|
|
3540
3584
|
// Anything that is not an array of strings is treated as absent rather than searched with
|
package/dist/server/store.d.ts
CHANGED
|
@@ -588,6 +588,7 @@ export declare class Store {
|
|
|
588
588
|
setThinkingActiveLive(conversationId: string, messageId: string, active: boolean): void;
|
|
589
589
|
appendThinkingDelta(conversationId: string, messageId: string, delta: string): Promise<void>;
|
|
590
590
|
/** Persists the message exactly as it stands now, including any live text, thinking and tool updates. */
|
|
591
|
+
recordMessageModel(conversationId: string, messageId: string, model: ModelSelection): Promise<void>;
|
|
591
592
|
checkpointMessage(conversationId: string, messageId: string): Promise<void>;
|
|
592
593
|
/**
|
|
593
594
|
* Appends one tool call to the message it belongs to, and returns the message's whole `toolCalls`
|
package/dist/server/store.js
CHANGED
|
@@ -2286,6 +2286,13 @@ export class Store {
|
|
|
2286
2286
|
await this.checkpointMessage(conversationId, messageId);
|
|
2287
2287
|
}
|
|
2288
2288
|
/** Persists the message exactly as it stands now, including any live text, thinking and tool updates. */
|
|
2289
|
+
async recordMessageModel(conversationId, messageId, model) {
|
|
2290
|
+
const message = this.requireConversation(conversationId).messages.find(item => item.id === messageId);
|
|
2291
|
+
if (!message || message.role !== "assistant")
|
|
2292
|
+
throw new Error("找不到对应的助手消息。");
|
|
2293
|
+
message.actualModel = { provider: model.provider, modelId: model.modelId, label: model.label };
|
|
2294
|
+
await this.checkpointMessage(conversationId, messageId);
|
|
2295
|
+
}
|
|
2289
2296
|
async checkpointMessage(conversationId, messageId) {
|
|
2290
2297
|
const conversation = this.requireConversation(conversationId);
|
|
2291
2298
|
const message = conversation.messages.find((item) => item.id === messageId);
|
package/dist/server/types.d.ts
CHANGED
|
@@ -114,6 +114,7 @@ export type ToolCallQuestion = {
|
|
|
114
114
|
answers?: QuestionAnswer[];
|
|
115
115
|
};
|
|
116
116
|
export type Message = {
|
|
117
|
+
actualModel?: ModelSelection;
|
|
117
118
|
backgroundBatch?: Pick<Message, "id" | "content" | "createdAt" | "backgroundTask">[];
|
|
118
119
|
batchedInto?: string;
|
|
119
120
|
backgroundTask?: BackgroundTaskSummary;
|
package/dist/shared/rsi.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { GroupRsi, GroupRsiFinding } from "./group-chat.js";
|
|
1
|
+
import type { GroupModel, GroupRsi, GroupRsiFinding } from "./group-chat.js";
|
|
2
2
|
export type RsiSource = {
|
|
3
3
|
kind: "session" | "group";
|
|
4
4
|
id: string;
|
|
@@ -29,6 +29,7 @@ export type RsiRepair = {
|
|
|
29
29
|
}[];
|
|
30
30
|
};
|
|
31
31
|
export type RsiRepairView = RsiRepair & {
|
|
32
|
+
model?: GroupModel;
|
|
32
33
|
busy: boolean;
|
|
33
34
|
revision?: string;
|
|
34
35
|
proposedPlan?: string;
|
|
@@ -36,6 +37,7 @@ export type RsiRepairView = RsiRepair & {
|
|
|
36
37
|
id: string;
|
|
37
38
|
role: "user" | "assistant";
|
|
38
39
|
content: string;
|
|
40
|
+
actualModel?: GroupModel;
|
|
39
41
|
}[];
|
|
40
42
|
};
|
|
41
43
|
export type RsiImprovement = {
|
|
@@ -60,7 +62,10 @@ export type RsiImprovement = {
|
|
|
60
62
|
export type RsiSnapshot = {
|
|
61
63
|
state: GroupRsi;
|
|
62
64
|
repairs?: RsiRepairView[];
|
|
63
|
-
improvements: RsiImprovement
|
|
65
|
+
improvements: (RsiImprovement & {
|
|
66
|
+
model?: GroupModel;
|
|
67
|
+
actualModel?: GroupModel;
|
|
68
|
+
})[];
|
|
64
69
|
capabilities: {
|
|
65
70
|
slug: string;
|
|
66
71
|
name: string;
|
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.304",
|
|
7
7
|
"description": "Web control plane and companion for Pi",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"type": "module",
|
|
@@ -83,6 +83,7 @@
|
|
|
83
83
|
"scripts/desktop-runtime.test.mjs",
|
|
84
84
|
"scripts/managed-ssh.test.mjs",
|
|
85
85
|
"scripts/managed-model.test.mjs",
|
|
86
|
+
"scripts/managed-helper-default.test.mjs",
|
|
86
87
|
"scripts/managed-model-flow.test.mjs",
|
|
87
88
|
"scripts/managed-offline-recovery.test.mjs",
|
|
88
89
|
"scripts/multi-server.test.mjs",
|
|
@@ -227,6 +228,7 @@
|
|
|
227
228
|
"scripts/files-api.test.mjs",
|
|
228
229
|
"scripts/http-body-utf8-chunking.test.mjs",
|
|
229
230
|
"scripts/files-eol-roundtrip.test.mjs",
|
|
231
|
+
"scripts/document-drafts.test.mjs",
|
|
230
232
|
"scripts/files-missing-path.test.mjs",
|
|
231
233
|
"scripts/file-changes.test.mjs",
|
|
232
234
|
"scripts/file-index.test.mjs",
|
|
@@ -343,6 +345,7 @@
|
|
|
343
345
|
"scripts/git-panel-upgrade-browser.test.mjs",
|
|
344
346
|
"scripts/welcome-workspace-git-browser.test.mjs",
|
|
345
347
|
"scripts/editor-search-design-browser.test.mjs",
|
|
348
|
+
"scripts/workbench-document-drafts-browser.test.mjs",
|
|
346
349
|
"scripts/terminal-activity-focus-browser.test.mjs",
|
|
347
350
|
"scripts/context-meter-browser.test.mjs",
|
|
348
351
|
"scripts/rsi-sidebar-browser.test.mjs",
|
|
@@ -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{_ as t,c as n,g as r,h as i,i as a,l as o,o as s,r as c,s as l,u,v as d,y as f}from"./index-BAq4p4ug.js";var p=e(f(),1);function m(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,s=e=>{n&&(e===`expanded`?(a=!a,l()):n.querySelector(`input[name="${e===`caseSensitive`?`case`:e===`wholeWord`?`word`:`re`}"]`)?.click())},c=e=>{let t=o(e);t&&(e.preventDefault(),e.stopPropagation(),s(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)}},d=()=>{let o=r.querySelector(`.cm-panel.cm-search`);if(o===n)return;if(n?.removeEventListener(`keydown`,c,!0),i?.destroy(),n=o,!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 d=document.createElement(`span`);d.dataset.findControls=``,n.prepend(d);let f=t.getSearchQuery(e.state);a=!1,i=u(d,{...f,expanded:a},s),n.addEventListener(`keydown`,c,!0),l()},f=new MutationObserver(d);return f.observe(r,{childList:!0,subtree:!0}),d(),{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 h(e,t,r,i,a){let o=new e.Compartment,c=()=>{let n=s();return[e.EditorState.tabSize.of(n.tabSize),r.indentUnit.of(n.indent===`tabs`?` `:` `.repeat(n.tabSize)),n.wrap?t.EditorView.lineWrapping:[],n.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(),r.bracketMatching(),r.indentOnInput(),r.foldGutter(),i.closeBrackets(),e.Prec.highest(t.keymap.of([...i.closeBracketsKeymap,...r.foldKeymap,{key:`Alt-z`,run:()=>(l({wrap:!s().wrap}),!0)},{key:`Mod-Shift-z`,run:a.redo},{key:`Mod-y`,run:a.redo}])),o.of(c()),t.ViewPlugin.define(e=>({destroy:n(()=>{e.dispatch({effects:o.reconfigure(c())})})}))]}var g=new Map;function ee(e){let t=g.get(e);return t&&(g.delete(e),g.set(e,t)),t}function _(e,t){g.delete(e),g.set(e,t);let n=[...g.values()].reduce((e,t)=>e+t.state.doc.length,0);for(;g.size>32||n>16777216;){let e=g.keys().next().value;n-=g.get(e).state.doc.length,g.delete(e)}}var v=d(),te=262144,y=131072;function b(e){return e.split(`.`).pop()?.toLowerCase()??``}function x(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 S({path:e,value:n,onChange:o,jumpToLine:s,onSave:l,workspaceId:u,cwd:d=``,blame:f,onPosition:g,onView:S,readOnly:C=!1,languageOverride:w}){let T=(0,p.useRef)(null),E=(0,p.useRef)(null),D=(0,p.useRef)(null),ne=(0,p.useRef)(null),O=JSON.stringify([u,d,e]),k=(0,p.useRef)(void 0),A=(0,p.useRef)(null),j=(0,p.useRef)(null),re=(0,p.useRef)(null),M=(0,p.useRef)(null),N=(0,p.useRef)(null),P=(0,p.useRef)(null),F=(0,p.useRef)(o),ie=(0,p.useRef)(l),I=(0,p.useRef)(!1),L=(0,p.useRef)(S);L.current=S,F.current=o,ie.current=l;let[R,ae]=(0,p.useState)(!1),[z,B]=(0,p.useState)(!1),[V,H]=(0,p.useState)(`0,0`),[U,oe]=(0,p.useState)(0),[W,G]=(0,p.useState)(1);(0,p.useEffect)(()=>{let i=!1,o,s,c,l,u;return(async()=>{try{let d=w??b(e),f=r(d),[p,g,_,v,y,S,R,z,V]=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])),f?f().catch(e=>(console.warn(`[CodeMirror] Failed to load language for .${d}:`,e),null)):Promise.resolve(null),a().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||!T.current||!E.current)return;ne.current=g.EditorView,l=y,u=S,j.current=p.Annotation.define(),re.current=p.Transaction.addToHistory;let U=n.length<=te&&R!==null;s=new p.Compartment;let W=[g.lineNumbers(),g.highlightActiveLine(),g.drawSelection(),_.history(),g.keymap.of([_.indentWithTab,..._.defaultKeymap,..._.historyKeymap,...v.searchKeymap,{key:`Mod-s`,run:()=>(ie.current(),!0)}]),g.EditorView.updateListener.of(e=>{e.docChanged&&!(j.current&&e.transactions.some(e=>e.annotation(j.current)===!0))&&F.current(e.state.doc.toString()),e.selectionSet&&H(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),g.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(W.push(g.EditorView.updateListener.of(e=>{e.selectionSet&&G(e.state.selection.ranges.length),e.docChanged?I.current=!1:e.selectionSet&&(I.current=e.transactions.some(e=>e.isUserEvent(`select.search`)||e.isUserEvent(`select.pointer`)))}),m(p,v,g,E.current),h(p,g,y,V,_)),C&&W.push(p.EditorState.readOnly.of(!0),g.EditorView.editable.of(!1),g.EditorView.contentAttributes.of({tabindex:`0`})),z&&!C&&(c=new p.Compartment,W.splice(1,0,c.of([])),W.push(z.base)),R)try{W.push(R)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${d}:`,e),U=!1}if(U&&s&&l&&u)try{W.push(s.of(l.syntaxHighlighting(x(l,u))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${d}:`,e),U=!1}let K=ee(O),q=K&&K.state.doc.toString()===n,J=q?K.state.update({effects:p.StateEffect.reconfigure.of(W)}).state:p.EditorState.create({doc:n,extensions:W});if(o=new g.EditorView({state:J,parent:T.current}),k.current=q?K.jump:void 0,G(o.state.selection.ranges.length),H(`${o.state.selection.main.from},${o.state.selection.main.to}`),q&&(o.scrollDOM.scrollTop=K.top,o.scrollDOM.scrollLeft=K.left,k.current=K.jump),i){o.destroy();return}D.current=o,L.current?.(o),ae(U),B(!0),M.current=z,N.current=c??null,P.current=null,oe(e=>e+1);let Y=new MutationObserver(()=>{let e=D.current;if(e&&U&&s&&l&&u)try{e.dispatch({effects:s.reconfigure(l.syntaxHighlighting(x(l,u)))})}catch{}});A.current=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),i||B(!0)}})(),()=>{i=!0,A.current?.disconnect(),A.current=null,o&&_(O,{state:o.state,top:o.scrollDOM.scrollTop,left:o.scrollDOM.scrollLeft,jump:k.current}),o?.destroy(),D.current=null,L.current?.(),B(!1),T.current&&(T.current.textContent=``)}},[O,C,w]),(0,p.useEffect)(()=>{let e=D.current;if(!e)return;let t=e.state.doc.toString();t!==n&&e.dispatch({changes:{from:0,to:t.length,insert:n},annotations:j.current?j.current.of(!0):void 0})},[n]),(0,p.useEffect)(()=>{let e=D.current;if(!e||!s||k.current===s.request)return;k.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:ne.current?.scrollIntoView(n,{y:`start`,yMargin:Math.round(e.scrollDOM.clientHeight/3)})}),e.focus()},[s,z]);let K=!!(f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===u);(0,p.useEffect)(()=>{let t=D.current,n=M.current,r=N.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?c(i):null;P.current!==a&&(P.current=a,t.dispatch({effects:[n.setBlame.of(a),r.reconfigure(a?n.gutter:[])]}))},[f?.state,f?.response,f?.path,f?.workspaceId,e,u,U]);let q=D.current?.state.doc.toString()??n,J=q.length<=y?q:q.slice(0,y),Y=w??b(e),X=i(Y),Z=D.current?.state,Q=Z?.selection.main.head,$=Q===void 0?void 0:Z?.doc.lineAt(Q),se=$?.number,ce=Q!==void 0&&$?Q-$.from+1:void 0;return(0,p.useEffect)(()=>{let e=D.current;if(z&&e&&(!s||k.current===s.request)){let t=e.state.selection.main.head,n=e.state.doc.lineAt(t);g?.({line:n.number,column:t-n.from+1,language:R&&X||`纯文本`,highlight:R?Y:`plain`,navigation:I.current,selections:e.state.selection.ranges.length})}},[z,se,ce,R,X,Y,g,W,s?.request]),(0,p.useEffect)(()=>()=>g?.(),[g]),(0,v.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":J,"data-file-content-truncated":q.length>y?`1`:`0`,"data-file-selection":V,"data-editor-selection-count":W,"data-file-editor-ready":z?`1`:`0`,"data-file-blame-gutter":K?`1`:void 0,onMouseDown:e=>{e.target.closest(`.cm-panels`)||D.current?.focus()},children:[(0,v.jsx)(`div`,{className:`file-cm`,ref:T,"aria-label":`${C?`查看`:`编辑`} ${e}`}),(0,v.jsx)(`div`,{className:`workbench-editor-search`,ref:E,"data-editor-find-host":`file`}),(!z||!g)&&(0,v.jsxs)(`div`,{className:`file-editor-status`,children:[!z&&(0,v.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),z&&Q!==void 0&&$&&(0,v.jsxs)(`span`,{children:[`第 `,$.number,` 行,第 `,Q-$.from+1,` 列`]}),z&&!R&&(0,v.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),z&&R&&X&&(0,v.jsx)(`span`,{"data-file-highlight-status":Y,children:X})]})]})}export{S as CodeMirrorEditor,m as n,h as t,x as themeHighlightStyle};
|