@evandu/super-pi 0.1.293 → 0.1.295

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/.super-pi-check-inputs.json +4 -0
  2. package/dist/client/.super-pi-client-sources.json +21 -18
  3. package/dist/client/assets/CodeMirrorEditor--5LzaKEZ.css +1 -0
  4. package/dist/client/assets/CodeMirrorEditor-pPQNmfzu.js +2 -0
  5. package/dist/client/assets/{GitDiffEditor-WONJq3t4.js → GitDiffEditor-DIHJ24IL.js} +3 -3
  6. package/dist/client/assets/{GitDiffEditor-DP0DQ9Y5.css → GitDiffEditor-DUY8YwXS.css} +1 -1
  7. package/dist/client/assets/index-Ccibh1zo.css +1 -0
  8. package/dist/client/assets/index-DPQPznQh.js +354 -0
  9. package/dist/client/index.html +2 -2
  10. package/dist/server/application/group-chat-service.d.ts +7 -0
  11. package/dist/server/application/group-chat-service.js +34 -2
  12. package/dist/server/application/run-service.d.ts +2 -1
  13. package/dist/server/application/run-service.js +7 -5
  14. package/dist/server/content-replace-worker.d.ts +1 -0
  15. package/dist/server/content-replace-worker.js +83 -0
  16. package/dist/server/content-replace.d.ts +12 -0
  17. package/dist/server/content-replace.js +103 -0
  18. package/dist/server/content-search.d.ts +4 -0
  19. package/dist/server/content-search.js +44 -9
  20. package/dist/server/exec-service.js +27 -3
  21. package/dist/server/group-primary-executor.d.ts +1 -1
  22. package/dist/server/group-primary-executor.js +9 -2
  23. package/dist/server/http-server.js +60 -3
  24. package/dist/server/index.js +1 -1
  25. package/dist/server/runtime.d.ts +1 -0
  26. package/dist/server/runtime.js +1 -1
  27. package/dist/server/store.d.ts +4 -3
  28. package/dist/server/store.js +42 -5
  29. package/dist/server/types.d.ts +2 -0
  30. package/dist/shared/content-search.d.ts +19 -0
  31. package/dist/shared/group-chat.d.ts +6 -0
  32. package/package.json +1 -1
  33. package/dist/client/assets/CodeMirrorEditor-7EW-C8kx.css +0 -1
  34. package/dist/client/assets/CodeMirrorEditor-CRYNvn14.js +0 -2
  35. package/dist/client/assets/index-B2HH9caF.css +0 -1
  36. package/dist/client/assets/index-MxsSEfDh.js +0 -350
@@ -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.
@@ -557,6 +558,15 @@ export function createHttpServer(options) {
557
558
  return;
558
559
  }
559
560
  if (request.method === "POST") {
561
+ if (roomId && url.searchParams.get("upload") === "image") {
562
+ const input = await readRequestText(request, 8 * 1024 * 1024);
563
+ if (input.tooLarge) {
564
+ json(413, { error: "群聊图片过大" });
565
+ return;
566
+ }
567
+ json(200, await groups.uploadImage(workspaceId, roomId, JSON.parse(input.text)));
568
+ return;
569
+ }
560
570
  const input = await readRequestText(request, 128_000);
561
571
  if (input.tooLarge) {
562
572
  json(413, { error: "群聊请求内容过大。" });
@@ -3469,6 +3479,52 @@ export function createHttpServer(options) {
3469
3479
  json(200, query ? store.searchConversationMessages(workspaceId, query) : { hits: [], truncated: false });
3470
3480
  return;
3471
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
+ }
3472
3528
  if (url.pathname === "/api/files/search") {
3473
3529
  const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body)); };
3474
3530
  const controller = new AbortController();
@@ -3493,7 +3549,7 @@ export function createHttpServer(options) {
3493
3549
  return;
3494
3550
  }
3495
3551
  const workspaceId = url.searchParams.get("workspaceId")?.trim();
3496
- const query = url.searchParams.get("q")?.trim() ?? "";
3552
+ const query = url.searchParams.get("q") ?? "";
3497
3553
  const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
3498
3554
  if (!workspaceId || !workspace || workspace.closedAt) {
3499
3555
  json(404, { error: "找不到这个工作区——它可能已经被关闭或删除。", code: "no_workspace" });
@@ -3505,8 +3561,8 @@ export function createHttpServer(options) {
3505
3561
  const canonicalCwd = toRelative(await realpath(workspace.path), await realpath(root));
3506
3562
  if (isProtectedSearchPath(cwd) || isProtectedSearchPath(canonicalCwd))
3507
3563
  throw new FilesError(403, "不能搜索应用或 Git 内部目录。", "protected_path");
3508
- if (query.length > 256 || /[\0\r\n]/u.test(query)) {
3509
- json(400, { error: "搜索词只能是一行,且不超过 256 个字符。", code: "bad_query" });
3564
+ if (query.length > 4096 || /\0/u.test(query)) {
3565
+ json(400, { error: "搜索词不能包含空字符,且不超过 4096 个字符。", code: "bad_query" });
3510
3566
  return;
3511
3567
  }
3512
3568
  const include = url.searchParams.get("include")?.trim();
@@ -3523,6 +3579,7 @@ export function createHttpServer(options) {
3523
3579
  }
3524
3580
  const { hits, skipped, ...summary } = await searchByContent(root, query, {
3525
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",
3526
3583
  onHits: stream ? (hits) => send({ type: "matches", hits }) : undefined,
3527
3584
  });
3528
3585
  if (controller.signal.aborted)
@@ -363,7 +363,7 @@ void sessionOrchestratorService.restoreWatchdogs().catch((error) => {
363
363
  });
364
364
  const groupChatService = await GroupChatService.open(join(dataDir, "group-chats.json"), store, runtime, memory, update => broadcaster.broadcast({ type: "group.activity", ...update }));
365
365
  const { groupPrimaryExecutor, groupPrimaryLifecycle } = await import("./group-primary-executor.js");
366
- runtime.setGroupMemberExecutor?.(groupPrimaryExecutor(store, runService), groupPrimaryLifecycle(store, runService, id => runtime.disposeSessions?.(id) ?? Promise.resolve(), join(dataDir, "pi-sessions"), () => broadcaster.broadcastState()));
366
+ runtime.setGroupMemberExecutor?.(groupPrimaryExecutor(store, runService, uploadsDir), groupPrimaryLifecycle(store, runService, id => runtime.disposeSessions?.(id) ?? Promise.resolve(), join(dataDir, "pi-sessions"), () => broadcaster.broadcastState()));
367
367
  const userTools = await UserTools.open(join(dataDir, "user-capabilities"));
368
368
  async function queueRsiConversation(id, prompt) {
369
369
  await new Promise((resolve, reject) => {
@@ -275,6 +275,7 @@ export type GroupExecutionLifecycle = {
275
275
  forget(workspaceId: string, roomId: string): Promise<void>;
276
276
  };
277
277
  export type IsolatedCompletionInput = {
278
+ images?: import("./types.js").PiImageContent[];
278
279
  onConversation?(conversationId: string): Promise<void> | void;
279
280
  userToolContext?: {
280
281
  id: string;
@@ -2909,7 +2909,7 @@ export class PiRpcRuntime {
2909
2909
  catch { /* Older worker protocols can retain their default; the wall-clock deadline still applies. */ }
2910
2910
  }
2911
2911
  input.signal?.throwIfAborted();
2912
- channel.write({ id: "tool_llm", type: "prompt", message: input.prompt });
2912
+ channel.write({ id: "tool_llm", type: "prompt", message: input.prompt, ...(input.images?.length ? { images: input.images } : {}) });
2913
2913
  awaitingCompletion = true;
2914
2914
  let settled = false, text = "";
2915
2915
  let failure, finalText;
@@ -499,7 +499,7 @@ export declare class Store {
499
499
  * `composePrompt` in the run service). So the instruction reaches the model the same way, and the
500
500
  * reader sees who spoke.
501
501
  */
502
- addAgentMessage(conversationId: string, content: string, options?: Pick<Message, "delivery" | "source">): Promise<Message>;
502
+ addAgentMessage(conversationId: string, content: string, options?: Pick<Message, "delivery" | "source" | "images">): Promise<Message>;
503
503
  addUserMessage(conversationId: string, content: string, images?: MessageImage[], attachments?: import("./types.js").MessageAttachments, options?: {
504
504
  clientId?: string;
505
505
  delivery?: Message["delivery"];
@@ -875,8 +875,9 @@ export declare class Store {
875
875
  * THE INSERT POSITION IS THE WHOLE DESIGN. `push` was the old behaviour and it is only correct when the
876
876
  * message being answered is the last thing in the conversation. With two messages waiting, answering
877
877
  * the first by appending puts its reply BELOW the second one, so the reader sees the answer to a
878
- * question that is still waiting - a transcript lying about its own order. Splicing at
879
- * `indexOf(user) + 1` keeps every waiting message below the reply that belongs to the one above it.
878
+ * question that is still waiting - a transcript lying about its own order.
879
+ * Moving the delivered message past completed turns and then inserting its answer keeps waiting
880
+ * rows below actual answers, even when a later-created interrupt was answered first.
880
881
  *
881
882
  * The side effects - title, `updatedAt`, `status: "waiting"`, clearing a stale failure - all describe a
882
883
  * TURN rather than a message, which is why `addUserMessage` skips them for a message that is only
@@ -1982,6 +1982,8 @@ export class Store {
1982
1982
  const message = { id: id("message"), role: "tool", content, createdAt: now() };
1983
1983
  if (options?.source)
1984
1984
  message.source = options.source;
1985
+ if (options?.images?.length)
1986
+ message.images = structuredClone(options.images);
1985
1987
  if (options?.delivery)
1986
1988
  message.delivery = options.delivery;
1987
1989
  conversation.messages.push(message);
@@ -2923,9 +2925,16 @@ export class Store {
2923
2925
  const user = conversation.messages[index];
2924
2926
  if ((user.role !== "user" && user.role !== "tool") || user.delivery !== "sending")
2925
2927
  return undefined;
2928
+ // Delivery order owns transcript placement, regardless of when a waiting row was accepted.
2929
+ conversation.messages.splice(index, 1);
2930
+ let delivered = conversation.messages.length - 1;
2931
+ while (delivered >= 0 && conversation.messages[delivered].delivery)
2932
+ delivered--;
2933
+ const deliveryIndex = delivered + 1;
2934
+ conversation.messages.splice(deliveryIndex, 0, user);
2926
2935
  delete user.delivery;
2927
2936
  const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
2928
- conversation.messages.splice(index + 1, 0, assistant);
2937
+ conversation.messages.splice(deliveryIndex + 1, 0, assistant);
2929
2938
  await this.persistMessages(conversation);
2930
2939
  return { user: structuredClone(user), assistant: structuredClone(assistant) };
2931
2940
  }
@@ -2937,8 +2946,9 @@ export class Store {
2937
2946
  * THE INSERT POSITION IS THE WHOLE DESIGN. `push` was the old behaviour and it is only correct when the
2938
2947
  * message being answered is the last thing in the conversation. With two messages waiting, answering
2939
2948
  * the first by appending puts its reply BELOW the second one, so the reader sees the answer to a
2940
- * question that is still waiting - a transcript lying about its own order. Splicing at
2941
- * `indexOf(user) + 1` keeps every waiting message below the reply that belongs to the one above it.
2949
+ * question that is still waiting - a transcript lying about its own order.
2950
+ * Moving the delivered message past completed turns and then inserting its answer keeps waiting
2951
+ * rows below actual answers, even when a later-created interrupt was answered first.
2942
2952
  *
2943
2953
  * The side effects - title, `updatedAt`, `status: "waiting"`, clearing a stale failure - all describe a
2944
2954
  * TURN rather than a message, which is why `addUserMessage` skips them for a message that is only
@@ -2951,9 +2961,36 @@ export class Store {
2951
2961
  if (index < 0)
2952
2962
  throw new Error(`消息不存在或已被撤回:${messageId}`);
2953
2963
  const user = conversation.messages[index];
2954
- delete user.delivery;
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));
2982
+ let delivered = conversation.messages.length - 1;
2983
+ while (delivered >= 0 && conversation.messages[delivered].delivery)
2984
+ delivered--;
2985
+ const deliveryIndex = delivered + 1;
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);
2955
2992
  const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
2956
- conversation.messages.splice(index + 1, 0, assistant);
2993
+ conversation.messages.splice(deliveryIndex + batch.length, 0, assistant);
2957
2994
  const firstUser = conversation.messages.find((item) => item.role === "user");
2958
2995
  const autoTitle = firstUser?.content.trim()
2959
2996
  ? firstUser.content.slice(0, 42)
@@ -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;
@@ -144,6 +144,12 @@ export type GroupUserPost = GroupPost & {
144
144
  replyTo?: string;
145
145
  clientId: string;
146
146
  files?: GroupFileReference[];
147
+ images?: {
148
+ id: string;
149
+ name?: string;
150
+ mimeType: string;
151
+ bytes: number;
152
+ }[];
147
153
  memoryNotice?: string;
148
154
  };
149
155
  export type GroupReply = GroupPost & {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "superPi": {
4
4
  "managedDirectListener": true
5
5
  },
6
- "version": "0.1.293",
6
+ "version": "0.1.295",
7
7
  "description": "Web control plane and companion for Pi",
8
8
  "license": "MIT",
9
9
  "type": "module",
@@ -1 +0,0 @@
1
- .workbench-shell .cm-editor .cm-panels{background:var(--bg-panel);color:var(--text-primary)}.workbench-shell .cm-editor .cm-panels-top{border-bottom:1px solid var(--border-default)}.workbench-shell .cm-editor .cm-panel.cm-search{min-width:0;font-family:Manrope,system-ui,sans-serif;font-size:var(--type-control);line-height:var(--type-control-line);background:var(--bg-panel);color:var(--text-primary);flex-wrap:wrap;align-items:center;gap:6px 8px;padding:10px 46px 10px 12px;display:flex;position:relative}.workbench-shell .cm-editor .cm-search :is(input,button,label){font:inherit;margin:0}.workbench-shell .cm-editor .cm-search .cm-textfield{border:1px solid var(--border-default);width:220px;min-width:100px;max-width:340px;height:32px;color:var(--text-primary);background:var(--bg-input);box-shadow:none;border-radius:4px;flex:180px;padding:5px 8px}.workbench-shell .cm-editor .cm-search .cm-textfield::placeholder{color:var(--text-muted)}.workbench-shell .cm-editor .cm-search button{border:1px solid var(--border-default);min-height:32px;color:var(--text-primary);background:var(--bg-raised);box-shadow:none;cursor:pointer;background-image:none;border-radius:4px;flex:none;justify-content:center;align-items:center;padding:4px 8px;display:inline-flex}.workbench-shell .cm-editor .cm-search button:hover{background:var(--bg-hover)}.workbench-shell .cm-editor .cm-search label{white-space:nowrap;min-height:32px;color:var(--text-secondary);align-items:center;gap:5px;display:inline-flex}.workbench-shell .cm-editor .cm-search input[type=checkbox]{width:16px;height:16px;accent-color:var(--accent);cursor:pointer;margin:0}.workbench-shell .cm-editor .cm-search br{flex-basis:100%;height:0}.workbench-shell .cm-editor .cm-search button[name=close]{background:0 0;border-color:#0000;width:30px;height:32px;min-height:32px;padding:0;font-size:20px;line-height:1;position:absolute;top:10px;right:8px}.workbench-shell .cm-editor .cm-search button[name=close]:hover{background:var(--bg-hover)}.workbench-shell .cm-editor .cm-search :is(input,button):focus-visible{outline:2px solid var(--focus-ring);outline-offset:1px}.workbench-shell .cm-editor .cm-searchMatch{color:var(--editor-find-fg);background-color:var(--editor-find-bg);box-shadow:inset 0 0 0 1px var(--editor-find-border)}.workbench-shell .cm-editor .cm-searchMatch-selected{color:var(--editor-find-current-fg);background-color:var(--editor-find-current-bg);outline:1px solid var(--editor-find-current-border);box-shadow:inset 0 0 0 1px var(--editor-find-current-border)}.workbench-shell .cm-editor .cm-searchMatch span{color:inherit;background-color:#0000}@media (width<=700px){.workbench-shell .cm-editor .cm-panel.cm-search{padding-right:60px}.workbench-shell .cm-editor .cm-search :is(button,label){min-height:44px}.workbench-shell .cm-editor .cm-search .cm-textfield{height:44px}.workbench-shell .cm-editor .cm-search button[name=close]{width:44px;height:44px}}
@@ -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-MxsSEfDh.js";var c=e(a(),1);function l(e,t){return[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)),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:()=>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};