femo-plugin 1.0.0

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 (166) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +627 -0
  3. package/femo2host/__init__.py +4 -0
  4. package/femo2host/femoToolcall/chronica.py +156 -0
  5. package/femo2host/femoToolcall/femo-chat.mjs +69 -0
  6. package/femo2host/femoToolcall/femo_debugger.py +1515 -0
  7. package/femo2host/femo_api.py +437 -0
  8. package/femo2host/femo_gen_api.jsx +77 -0
  9. package/femoBridges/ContextExample.py +555 -0
  10. package/femoBridges/MemoryExample.py +163 -0
  11. package/femoBridges/__init__.py +1 -0
  12. package/femoBridges/getDir/get_dir.py +56 -0
  13. package/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
  14. package/femoBridges/llmBridge.py +247 -0
  15. package/femoBridges/llmProviders.py +308 -0
  16. package/femoCompiler/FEMO_CLIrenderer.py +198 -0
  17. package/femoCompiler/FEMO_config.py +35 -0
  18. package/femoCompiler/FEMO_errors.py +278 -0
  19. package/femoCompiler/FEMO_interpreter.py +163 -0
  20. package/femoCompiler/FEMO_normalizer.py +396 -0
  21. package/femoCompiler/FEMO_parser.py +2468 -0
  22. package/femoCompiler/FEMO_runtime.py +3630 -0
  23. package/femoCompiler/FEMO_scope_resolver.py +209 -0
  24. package/femoCompiler/__init__.py +1 -0
  25. package/femoCompiler/actor_resolver.py +86 -0
  26. package/femoCompiler/block_collector.py +441 -0
  27. package/femoCompiler/db_utils.py +485 -0
  28. package/femoCompiler/femoAsync.py +401 -0
  29. package/femoCompiler/host_manifest.py +68 -0
  30. package/femoCompiler/job_manager.py +767 -0
  31. package/femoCompiler/protocol.py +126 -0
  32. package/femoCompiler/save_dialog.py +402 -0
  33. package/femoCompiler/task_world.py +544 -0
  34. package/femoCompiler/vars/__init__.py +19 -0
  35. package/femoCompiler/vars/checkpoint.py +113 -0
  36. package/femoCompiler/vars/env.py +686 -0
  37. package/femoCompiler/vars/evaluator.py +567 -0
  38. package/femoCompiler/vars/join.py +303 -0
  39. package/femoCompiler/vars/merge.py +157 -0
  40. package/femoCompiler/vars/model.py +245 -0
  41. package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
  42. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
  43. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
  44. package/femoExamples/LuxFiat/luxfiat.femo +38 -0
  45. package/femoExamples/LuxFiat/wait.py +29 -0
  46. package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
  47. package/femoExamples/discussion.femo +70 -0
  48. package/femoExamples/goal-mode.femo +23 -0
  49. package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
  50. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
  51. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
  52. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
  53. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
  54. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
  55. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
  56. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +392 -0
  57. package/femoGen/document_ch.html +2352 -0
  58. package/femoGen/document_en.html +2279 -0
  59. package/femoGen/index.html +19 -0
  60. package/femoGen/intro_ch.html +942 -0
  61. package/femoGen/intro_en.html +932 -0
  62. package/femoGen/package-lock.json +1698 -0
  63. package/femoGen/package.json +19 -0
  64. package/femoGen/public/character_need.ttf +0 -0
  65. package/femoGen/public/favicon.ico +0 -0
  66. package/femoGen/public/femo-logo-slogan.svg +83 -0
  67. package/femoGen/public/femo-logo.svg +55 -0
  68. package/femoGen/public/logo-fullsize.ico +0 -0
  69. package/femoGen/src/FemoWorAuto.jsx +5444 -0
  70. package/femoGen/src/actionModal.jsx +358 -0
  71. package/femoGen/src/bubbleOverlay.jsx +701 -0
  72. package/femoGen/src/canvasNodes.jsx +608 -0
  73. package/femoGen/src/common.jsx +715 -0
  74. package/femoGen/src/debugPanel.jsx +530 -0
  75. package/femoGen/src/faIcons.jsx +84 -0
  76. package/femoGen/src/femoDiagnostics.js +122 -0
  77. package/femoGen/src/femoFileList.jsx +357 -0
  78. package/femoGen/src/femoGenerator.jsx +1198 -0
  79. package/femoGen/src/femoLog.js +107 -0
  80. package/femoGen/src/femoParser.jsx +2255 -0
  81. package/femoGen/src/femoPreview.jsx +297 -0
  82. package/femoGen/src/graphBuilder.jsx +358 -0
  83. package/femoGen/src/libPanel.jsx +519 -0
  84. package/femoGen/src/main.jsx +22 -0
  85. package/femoGen/src/mobileView.jsx +2796 -0
  86. package/femoGen/src/projectPanel.jsx +529 -0
  87. package/femoGen/src/soulModal.jsx +162 -0
  88. package/femoGen/src/styles/font.css +10 -0
  89. package/femoGen/src/themes.js +465 -0
  90. package/femoGen/src/useCanvasInteraction.jsx +319 -0
  91. package/femoGen/vite.config.js +28 -0
  92. package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
  93. package/hostAdapter/dshAdapter/README.md +68 -0
  94. package/hostAdapter/dshAdapter/build.mjs +75 -0
  95. package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
  96. package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
  97. package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
  98. package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
  99. package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
  100. package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
  101. package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
  102. package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
  103. package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
  104. package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
  105. package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
  106. package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
  107. package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
  108. package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
  109. package/hostAdapter/dshAdapter/client/client.tsx +518 -0
  110. package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
  111. package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
  112. package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
  113. package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
  114. package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
  115. package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
  116. package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
  117. package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
  118. package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
  119. package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
  120. package/hostAdapter/dshAdapter/host/config.ts +124 -0
  121. package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
  122. package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
  123. package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
  124. package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
  125. package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
  126. package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
  127. package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
  128. package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
  129. package/hostAdapter/dshAdapter/host/http.ts +66 -0
  130. package/hostAdapter/dshAdapter/host/index.ts +633 -0
  131. package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
  132. package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
  133. package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
  134. package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
  135. package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
  136. package/hostAdapter/dshAdapter/host/persona.ts +146 -0
  137. package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
  138. package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
  139. package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
  140. package/hostAdapter/dshAdapter/host/projection.ts +742 -0
  141. package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
  142. package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
  143. package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
  144. package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
  145. package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
  146. package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
  147. package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
  148. package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
  149. package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
  150. package/hostAdapter/dshAdapter/host/tools.ts +486 -0
  151. package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
  152. package/hostAdapter/dshAdapter/host.manifest.json +6 -0
  153. package/hostAdapter/dshAdapter/lib/client.js +19161 -0
  154. package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
  155. package/hostAdapter/dshAdapter/lib/index.js +8173 -0
  156. package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
  157. package/hostAdapter/dshAdapter/package-lock.json +500 -0
  158. package/hostAdapter/dshAdapter/package.json +55 -0
  159. package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
  160. package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
  161. package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
  162. package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
  163. package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
  164. package/hostAdapter/dshAdapter/tsconfig.json +21 -0
  165. package/package.json +40 -0
  166. package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
@@ -0,0 +1,726 @@
1
+ /**
2
+ * client-ui/editor-page.tsx — 「Femo 编辑器」单页常驻宿主(2026-08-26 架构 v3)。
3
+ *
4
+ * 用户拍板模型:内存里只有一个 femogen 网页(FEMOEditor 实例),内容跟随
5
+ * 「打开的 Session」加载——打开哪个 Session 就加载哪个;切 Session 内容重载。
6
+ * 网页挂在 body 级隐藏容器里(visibility:hidden 但保留视口尺寸,让编辑器
7
+ * 布局计算与可见时一致),**永不卸载**:
8
+ * - tab 切换(对话↔Femo 编辑器)不卸载 → 画布状态/连接全程存活;
9
+ * - 「Femo 编辑器」tab 激活 = 锚点注册 → 隐藏容器被**移动到锚点内**(同一个
10
+ * DOM 节点,React 状态零丢失;锚点注销再移回 body);
11
+ * - view-button 上报「当前打开的 femo 主会话」→ 页面内容跟随(打开哪个
12
+ * Session 加载哪个)。
13
+ *
14
+ * 单页(createRoot 于 body 级 div)——一万个 femo 会话也只占一份编辑器内存。
15
+ * (编辑器实例内的一切状态逻辑:session-state 加载、定稿落盘+409 冲突弹窗、
16
+ * 导出/导入、preflight、restore 报错横幅,全部从 editor-view.tsx 迁来——
17
+ * editor-view 只剩锚点。【Job 模型 §11.4】AI 触发 run 的 run_request/
18
+ * triggerRun/run-result 回传链已整体退役——AI 的 femo-run 直调 host
19
+ * job_start(B1 死于结构),前端只是纯显示者。)
20
+ */
21
+
22
+ import { useCallback, useEffect, useRef, useState } from 'react'
23
+ import { createPortal } from 'react-dom'
24
+ import { createRoot } from 'react-dom/client'
25
+ import { femoStreamAcquire, subscribeControlEvents } from './stream-store'
26
+ import FEMOEditor from '../../../../femo2host/femo_gen_api'
27
+
28
+ /** 编辑器页需要的注入能力(原 ScriptViewInjected 语义——宿主注入给页面)。 */
29
+ export interface EditorPageInjected {
30
+ listScripts(): Promise<string[]>
31
+ readScript(path: string): Promise<string>
32
+ /** sessionId 带上则 host 顺写会话记录 {path, text}(导出/覆盖保存统一格式)。 */
33
+ saveScript(name: string, content: string, sessionId?: string): Promise<string>
34
+ runScript(sessionId: string, scriptPath?: string): Promise<void>
35
+ /** 暂停本会话的活跃 Job(§8.4 B3:pause 归属解析——sessionId 必填,
36
+ * 只认本会话绑定,不再"停别家的戏")。jobId 可选显式指定(宿主按引擎
37
+ * 档案 host_ref 裁决)。resolve 值带回执:paused:false=该会话无活跃
38
+ * 剧本(前端据此复位运行按钮,2026-09-06 反馈断链修复);state=引擎侧
39
+ * Job 现态(paused:true 但 state 非 running=幂等无操作,前端知情提示)。
40
+ * 失败原样 throw(2026-09-07:不再吞成 undefined——femoGen 可见报错)。 */
41
+ pauseScript(sessionId: string, jobId?: number): Promise<{ paused?: boolean; state?: string } | undefined>
42
+ fetchErrors(sessionId: string): Promise<Array<{ ts: number; text: string }>>
43
+ /** 打开 dsh 侧边栏(手机版 femoGen 返回键回调)。 */
44
+ toggleSidebar(): void
45
+ }
46
+
47
+ /**
48
+ * 导入清单条目(导入过 / 导出过的 .femo)。
49
+ * 形状与 host 侧 src/femo-files.ts 的 FemoFileEntry 对齐——刻意不 import 那个
50
+ * 文件:它拉 node:path / node:fs,会把 node 内置模块拖进浏览器包。两处形状
51
+ * 靠这条注释绑定,改一处记得改另一处。
52
+ */
53
+ export interface FemoFileEntry {
54
+ /** 绝对路径(清单条目的主键,回传给 /open-femo-file)。 */
55
+ path: string
56
+ /** basename,列表主标题。 */
57
+ name: string
58
+ /** 最近一次来源:导入(系统对话框选的)或导出(保存出来的)。 */
59
+ source: 'import' | 'export'
60
+ firstSeenAt: number
61
+ lastUsedAt: number
62
+ /** host 列清单时现算:文件此刻是否还在盘上(false=变灰不可点)。 */
63
+ exists: boolean
64
+ size?: number
65
+ mtimeMs?: number
66
+ }
67
+
68
+ /**
69
+ * 读 JSON 响应体,把「响应体为空 / 不是 JSON」翻译成人话。
70
+ *
71
+ * 2026-09-11 实测踩坑:dsh 的 webServer 对**未注册的路由**回 `405 Method Not
72
+ * Allowed`,而且响应体是 0 字节——插件改了宿主侧代码但没重启 dsh 时,点导入
73
+ * 就是这个下场。裸 `resp.json()` 会抛 `Failed to execute 'json' on 'Response':
74
+ * Unexpected end of JSON input`,一句和导入八竿子打不着的 JS 报错,用户拿到
75
+ * 完全无从下手(连是网络问题还是代码问题都看不出来)。
76
+ * 这里统一改成「哪个动作 + HTTP 状态 + 最可能的原因」的口径。
77
+ */
78
+ async function readJsonOrThrow<T>(resp: Response, what: string): Promise<T> {
79
+ const text = await resp.text()
80
+ if (text.trim().length === 0) {
81
+ throw new Error(resp.status === 405
82
+ ? `${what}失败:HTTP 405(该接口未注册)——宿主侧改动需要重启 dsh 进程才生效`
83
+ : `${what}失败:HTTP ${resp.status},响应体为空`)
84
+ }
85
+ try {
86
+ return JSON.parse(text) as T
87
+ } catch {
88
+ throw new Error(`${what}失败:HTTP ${resp.status},响应不是 JSON:${text.slice(0, 200)}`)
89
+ }
90
+ }
91
+
92
+ // ── 单页 store(模块级:一个页面一个状态,跨组件共享)─────────────────────
93
+
94
+ interface EditorPageSlice {
95
+ /** 当前应加载内容的 femo 主会话 id(null=无 femo 会话打开)。 */
96
+ target: string | null
97
+ /** 当前激活的「Femo 编辑器」tab 锚点(会话 id + DOM 容器)。 */
98
+ anchor: { sid: string; el: HTMLElement } | null
99
+ }
100
+
101
+ const pageState: EditorPageSlice = { target: null, anchor: null }
102
+ const pageListeners = new Set<() => void>()
103
+ /** 会话 id → 打开中的会话数(view-button 上报;投影窗与主窗同 sids 合并计数)。 */
104
+ const sessionRefs = new Map<string, number>()
105
+
106
+ function pageNotify(): void {
107
+ for (const listener of [...pageListeners]) listener()
108
+ }
109
+
110
+ function pageSetTarget(sid: string | null): void {
111
+ if (pageState.target === sid) return
112
+ pageState.target = sid
113
+ pageNotify()
114
+ }
115
+
116
+ /** view-button 上报:某 femo 主会话的窗口打开了(主会话/投影窗都算)。 */
117
+ export function editorPageOpenSession(sid: string): void {
118
+ sessionRefs.set(sid, (sessionRefs.get(sid) ?? 0) + 1)
119
+ pageSetTarget(sid)
120
+ }
121
+
122
+ /** view-button 上报:某 femo 主会话的窗口关掉了;最后一个关掉的清空目标。 */
123
+ export function editorPageCloseSession(sid: string): void {
124
+ const n = (sessionRefs.get(sid) ?? 0) - 1
125
+ if (n > 0) {
126
+ sessionRefs.set(sid, n)
127
+ return
128
+ }
129
+ sessionRefs.delete(sid)
130
+ if (pageState.target === sid && pageState.anchor === null) pageSetTarget(null)
131
+ // 有锚点(编辑器 tab 还开着)时不清:锚点是当前内容的事实来源。
132
+ }
133
+
134
+ /** 「Femo 编辑器」tab 锚点注册(tab 激活 ⇔ 编辑器视图挂载)。 */
135
+ export function editorPageRegisterAnchor(sid: string, el: HTMLElement): void {
136
+ pageState.anchor = { sid, el }
137
+ pageSetTarget(sid)
138
+ pageNotify()
139
+ }
140
+
141
+ /** 锚点注销(tab 切走/会话切换/窗口关闭)。同名同元素才清,防多窗把新的误清。 */
142
+ export function editorPageUnregisterAnchor(sid: string, el: HTMLElement): void {
143
+ if (pageState.anchor?.sid !== sid || pageState.anchor.el !== el) return
144
+ pageState.anchor = null
145
+ pageNotify()
146
+ }
147
+
148
+ // ── 全局控制 SSE(页面级常驻,管 script_changed)────────────────────────
149
+
150
+ /** 已挂载页面的 script_changed 重载钩子。 */
151
+ let pageReloadRef: (() => void) | null = null
152
+
153
+ function handleControlEvent(msg: { type?: string; data?: Record<string, unknown> }): void {
154
+ const sid = typeof msg.data?.sessionId === 'string' ? msg.data.sessionId : ''
155
+ if (sid.length === 0) return
156
+ if (msg.type === 'script_changed') {
157
+ // mount/定稿落盘广播:页面内容跟随(当前无目标时采纳;已是目标则重载)。
158
+ console.log(`[femo-page] sse script_changed sid=${sid} target=${pageState.target} anchor=${pageState.anchor?.sid ?? 'none'}`)
159
+ if (pageState.target === null) pageSetTarget(sid)
160
+ if (pageState.target === sid) {
161
+ // eslint-disable-next-line no-console
162
+ console.log(`[femo-page] -> reload page (target match)`)
163
+ pageReloadRef?.()
164
+ }
165
+ return
166
+ }
167
+ }
168
+
169
+ // ── 页面根组件(createRoot 于 body 级隐藏容器)────────────────────────────
170
+
171
+ /** 页面根容器 DOM(body 级;锚点激活时被移动到锚点内)。 */
172
+ let pageRootEl: HTMLElement | null = null
173
+
174
+ /** 把页面根容器放到正确的位置:锚点内(激活)或 body 隐藏(未激活)。
175
+ * 移动的是同一个 DOM 节点——React 端口/状态零丢失(createRoot 容器如何
176
+ * 被挂接与 React 无关)。 */
177
+ function applyPagePlacement(): void {
178
+ const rootEl = pageRootEl
179
+ if (rootEl === null) return
180
+ const anchor = pageState.anchor
181
+ if (anchor !== null && anchor.el.isConnected) {
182
+ if (rootEl.parentNode !== anchor.el) anchor.el.appendChild(rootEl)
183
+ rootEl.style.visibility = 'visible'
184
+ rootEl.style.pointerEvents = 'auto'
185
+ rootEl.style.position = 'absolute'
186
+ rootEl.style.inset = '0'
187
+ // ★ 2026-08-26 「以为的屏幕」修正:隐藏态是 100vw×100vh(视口尺寸),
188
+ // 移入锚点时宽度/高度必须切回 100%(锚点尺寸)——否则编辑器布局始终按
189
+ // 视口算,内容右下超出实际容器(用户实拍「下方/右侧出框」真因)。
190
+ rootEl.style.width = '100%'
191
+ rootEl.style.height = '100%'
192
+ console.log(`[femo-page] placement -> anchor (sid=${anchor.sid})`)
193
+ } else {
194
+ if (rootEl.parentNode !== document.body) document.body.appendChild(rootEl)
195
+ rootEl.style.visibility = 'hidden'
196
+ rootEl.style.pointerEvents = 'none'
197
+ rootEl.style.position = 'fixed'
198
+ rootEl.style.inset = '0'
199
+ rootEl.style.width = '100vw'
200
+ rootEl.style.height = '100vh'
201
+ console.log('[femo-page] placement -> hidden')
202
+ }
203
+ }
204
+
205
+ /** 挂载单页根(client.tsx apply() 调用一次):body 级隐藏容器 + createRoot。 */
206
+ export function mountFemoEditorPage(createInjected: () => EditorPageInjected): void {
207
+ if (pageRootEl !== null) return
208
+ const el = document.createElement('div')
209
+ el.setAttribute('data-femo-editor-page', '')
210
+ el.style.cssText = 'position:fixed;left:0;top:0;width:100vw;height:100vh;visibility:hidden;pointer-events:none;z-index:0'
211
+ document.body.appendChild(el)
212
+ pageRootEl = el
213
+ createRoot(el).render(<EditorPageRoot injectedFactory={createInjected} />)
214
+ console.log('[femo-page] editor page root mounted (single-instance keep-alive)')
215
+ }
216
+
217
+ function EditorPageRoot({ injectedFactory }: { injectedFactory: () => EditorPageInjected }): JSX.Element {
218
+ const [, force] = useState(0)
219
+ // 渲染期读 target:target 变化经 pageNotify→force 重渲染,连接 effect 以它为
220
+ // dep 按需启停。
221
+ const target = pageState.target
222
+ useEffect(() => {
223
+ const listener = (): void => {
224
+ applyPagePlacement()
225
+ force(x => x + 1)
226
+ }
227
+ pageListeners.add(listener)
228
+ applyPagePlacement()
229
+ // target 变化(会话切换)后锚点可能仍挂着——内容跟随 target,重放位置。
230
+ return () => {
231
+ pageListeners.delete(listener)
232
+ }
233
+ }, [])
234
+ useEffect(() => {
235
+ // 控制事件搭全局 SSE 便车(stream-store 单例,不另开连接)。【2026-09-05
236
+ // 连接池修复】只在页面有 femo 编辑目标时连接:target=null 的纯聊天页不占
237
+ // 长连接。【2026-09-05 晚·Stage2】改走后台池(background: true):编辑器
238
+ // tab 打开即持有、不看页面可见性——AI 工具随时可能操作 femoGen(script_
239
+ // changed 实时响应是编辑器硬需求),页面切后台也不能断。
240
+ // target=null 期间 script_changed 的自动跟随不生效——AI 侧运行是 host
241
+ // 行为不受影响,femo 会话/编辑器打开时连接已在。
242
+ if (target === null) return
243
+ const release = femoStreamAcquire({ background: true })
244
+ const unsubscribe = subscribeControlEvents(handleControlEvent)
245
+ return () => {
246
+ unsubscribe()
247
+ release()
248
+ }
249
+ }, [target])
250
+ return (
251
+ <div style={{ width: '100%', height: '100%', background: 'transparent' }}>
252
+ {target !== null && (
253
+ <FemoEditorPage
254
+ key={target}
255
+ sessionId={target}
256
+ injected={injectedFactory()}
257
+ />
258
+ )}
259
+ </div>
260
+ )
261
+ }
262
+
263
+ // ── 编辑器页(单实例;key=sessionId 保证切 Session 全量重载)──────────────
264
+
265
+ type PageState = {
266
+ hasScript: boolean
267
+ script?: string
268
+ scriptPath?: string
269
+ rev?: number
270
+ checkpoint: Record<string, string>
271
+ running?: boolean
272
+ /** 当前 Job 索引(宿主会话记录的 currentJobId)——femoGen 暂停/继续显式
273
+ * 带号、断点覆盖层的数据源。 */
274
+ jobId?: number
275
+ /** 本会话激活过的全部 Job(历史场次回放/续跑候选)。 */
276
+ jobIds?: number[]
277
+ /** 草稿 vs 运行快照一致性(宿主比对):false=草稿已改动,resume 会被
278
+ * 引擎指纹关拒绝——femoGen 据此渲染"画布与运行快照不一致"横幅。 */
279
+ /** 引擎冷启动(§八.15):bridge 未就绪——前端"引擎启动中"加载态,
280
+ * 运行按钮禁用,不显示"断点丢失"。 */
281
+ pending?: boolean
282
+ /** 引擎等待人类输入快照(human_wait SET 期间存在):刷新页面后画布
283
+ * 据此恢复人类输入气泡(不依赖 SSE 重放环覆盖)。 */
284
+ waitingHuman?: {
285
+ waitKey: string
286
+ nodeName?: string
287
+ context?: string
288
+ memory?: string
289
+ showprompt?: string
290
+ prompt?: string
291
+ outVars?: string[]
292
+ }
293
+ /** 上一个 failed Job 的存档错误(宿主重启后 SSE 重放环清空,报错只能
294
+ * 从档案补)——恢复面只进调试窗日志,不拦画布、不弹横幅。 */
295
+ lastError?: string
296
+ } | null
297
+
298
+ const conflictBtnStyle = {
299
+ padding: '6px 14px',
300
+ borderRadius: 8,
301
+ cursor: 'pointer',
302
+ fontSize: 13,
303
+ background: 'var(--dsw-alias-bg-layer-3, #fff)',
304
+ border: '1px solid var(--dsw-alias-border-l2, #ddd)',
305
+ } as const
306
+
307
+ function FemoEditorPage({ sessionId, injected }: { sessionId: string; injected: EditorPageInjected }): JSX.Element {
308
+ const [state, setState] = useState<PageState>(null)
309
+ /** 409 冲突弹窗:localFemo=被拒的本地文本;remoteRev=裁决用的服务端当前 rev。 */
310
+ const [conflict, setConflict] = useState<{ localFemo: string; remoteRev: number } | null>(null)
311
+ /** 编辑器恢复/解析失败横幅:用户可见 + 上报 host 并入 errors(主模型经 femo-mount/run 工具结果可见)。 */
312
+ const [editorNotice, setEditorNotice] = useState<string | null>(null)
313
+ /** 已上报过的 restore 错误(消息级去重):同一条错误只报一次,避免多路
314
+ * 触发(挂载/script_changed/remount)累积 N 条相同 POST。新记录载入时
315
+ * 重置(剧本修复后再犯同错仍能重新上报)。 */
316
+ const lastRestoreErrorRef = useRef<string | null>(null)
317
+
318
+ const onRestoreError = useCallback((message: string): void => {
319
+ if (lastRestoreErrorRef.current === message) return
320
+ lastRestoreErrorRef.current = message
321
+ setEditorNotice(message)
322
+ void fetch('/femo-plugin/editor-error', {
323
+ method: 'POST',
324
+ headers: { 'content-type': 'application/json' },
325
+ body: JSON.stringify({ sessionId, message, source: 'restore' }),
326
+ }).catch((error: unknown) => { console.warn('[femo-plugin] editor-error 上报失败:', error) })
327
+ }, [sessionId])
328
+
329
+ /** 拉取 record 侧的原文:「放弃修改直接跑」时作为定稿覆盖前端两处。 */
330
+ const getRecordScript = useCallback(async (): Promise<string | undefined> => {
331
+ try {
332
+ const response = await fetch(`/femo-plugin/session-state?sessionId=${encodeURIComponent(sessionId)}`)
333
+ const data = await response.json() as { ok?: boolean; script?: string }
334
+ return data.ok === true ? data.script : undefined
335
+ } catch {
336
+ return undefined
337
+ }
338
+ }, [sessionId])
339
+
340
+ const loadSessionState = useCallback(async (): Promise<void> => {
341
+ console.log(`[femo-page] loadSessionState start sid=${sessionId}`)
342
+ const response = await fetch(`/femo-plugin/session-state?sessionId=${encodeURIComponent(sessionId)}`)
343
+ const data = await response.json() as { ok?: boolean; script?: string; scriptPath?: string; rev?: number; checkpoint?: Record<string, string>; running?: boolean; pending?: boolean; jobId?: number; jobIds?: number[]; lastError?: string; waitingHuman?: { waitKey: string; nodeName?: string; context?: string; memory?: string; showprompt?: string; prompt?: string; outVars?: string[] } }
344
+ if (data.ok === true) {
345
+ // 剧本载入新记录:上次的「恢复失败」横幅自动收起(若新剧本仍解析失败,
346
+ // restore effect 会再次 onRestoreError 重新上报弹出——时序上在本次 setState
347
+ // 之后,所以这里先清是安全的)。
348
+ setEditorNotice(null)
349
+ // 新记录载入=新的恢复上下文:清掉去重标记,剧本修复后再犯同错仍可上报。
350
+ lastRestoreErrorRef.current = null
351
+ setState(prev => {
352
+ // 引用复用:script/checkpoint 内容未变则沿用旧引用,避免 initialScript/
353
+ // initialCheckpoint prop 换新对象触发 restore effect 无谓重跑
354
+ // (每重跑一次坏剧本就多上报一次,是重复 editor_errors 的温床)。
355
+ const sameScript = prev !== null && data.script !== undefined && prev.script === data.script
356
+ const sameCheckpoint = prev !== null && prev.checkpoint !== undefined
357
+ && JSON.stringify(prev.checkpoint) === JSON.stringify(data.checkpoint ?? {})
358
+ return {
359
+ hasScript: data.script !== undefined,
360
+ script: sameScript ? prev.script : data.script,
361
+ scriptPath: data.scriptPath,
362
+ rev: data.rev ?? 0,
363
+ checkpoint: sameCheckpoint ? prev.checkpoint : (data.checkpoint ?? {}),
364
+ running: data.running === true,
365
+ jobId: data.jobId,
366
+ ...(data.jobIds !== undefined ? { jobIds: data.jobIds } : {}),
367
+ // 引擎冷启动(§八.15):pending=true → FEMOEditor enginePending
368
+ // → 运行按钮禁用+「引擎启动中」,不显示"断点丢失"。
369
+ pending: data.pending === true,
370
+ ...(data.waitingHuman !== undefined ? { waitingHuman: data.waitingHuman } : {}),
371
+ ...(data.lastError !== undefined ? { lastError: data.lastError } : {}),
372
+ }
373
+ })
374
+ console.log(`[femo-page] state loaded sid=${sessionId} script=${data.script === undefined ? 'undefined' : String(data.script.length) + 'ch'} rev=${String(data.rev ?? 0)} jobId=${String(data.jobId ?? '-')} pending=${data.pending === true}`)
375
+ }
376
+ }, [sessionId])
377
+
378
+ /** 切 Session / 新目标:清态 + 重载(key=sessionId 已保证编辑器重挂载)。 */
379
+ useEffect(() => {
380
+ setState(null)
381
+ setConflict(null)
382
+ setEditorNotice(null)
383
+ void loadSessionState().catch(() => { /* 编辑器仍可空白启动 */ })
384
+ pageReloadRef = loadSessionState
385
+ return () => { pageReloadRef = null }
386
+ }, [sessionId, loadSessionState])
387
+
388
+ // 断点位置:主流程分支优先,其次任一分支(画布按节点 label 匹配)。
389
+ const checkpointNode = state === null
390
+ ? undefined
391
+ : state.checkpoint['__main__'] ?? Object.values(state.checkpoint)[0]
392
+
393
+ const persistScript = (femo: string): void => {
394
+ void fetch('/femo-plugin/session-script', {
395
+ method: 'POST',
396
+ headers: { 'content-type': 'application/json' },
397
+ body: JSON.stringify({ sessionId, femo, ...(state?.rev === undefined ? {} : { baseRev: state.rev }) }),
398
+ })
399
+ .then(async (response) => {
400
+ if (response.status !== 409) return
401
+ const data = await response.json().catch(() => null) as { ok?: boolean; record?: { rev?: number } } | null
402
+ setConflict({ localFemo: femo, remoteRev: data?.record?.rev ?? 0 })
403
+ })
404
+ .catch((error: unknown) => {
405
+ console.warn('[femo-plugin] persist write failed:', error)
406
+ })
407
+ }
408
+
409
+ /** 冲突裁决·加载最新:丢弃本地文本,按服务端当前记录重载画布。 */
410
+ const resolveConflictByReload = (): void => {
411
+ setConflict(null)
412
+ void loadSessionState()
413
+ .catch((error: unknown) => { console.warn('[femo-plugin] conflict reload failed:', error) })
414
+ }
415
+
416
+ /** 冲突裁决·保留我的编辑:以服务端最新 rev 为基准强制重写本地文本。 */
417
+ const resolveConflictByOverride = (): void => {
418
+ if (conflict === null) return
419
+ const femo = conflict.localFemo
420
+ void fetch('/femo-plugin/session-script', {
421
+ method: 'POST',
422
+ headers: { 'content-type': 'application/json' },
423
+ body: JSON.stringify({ sessionId, femo, baseRev: conflict.remoteRev }),
424
+ })
425
+ .then(async (response) => {
426
+ if (response.ok) {
427
+ const data = await response.json().catch(() => null) as { ok?: boolean; rev?: number } | null
428
+ setState(prev => prev === null ? prev : { ...prev, rev: data?.rev ?? prev.rev })
429
+ setConflict(null)
430
+ return
431
+ }
432
+ if (response.status === 409) {
433
+ const data = await response.json().catch(() => null) as { record?: { rev?: number } } | null
434
+ setConflict({ localFemo: femo, remoteRev: data?.record?.rev ?? conflict.remoteRev })
435
+ }
436
+ })
437
+ .catch((error: unknown) => { console.warn('[femo-plugin] conflict override failed:', error) })
438
+ }
439
+
440
+ /** 预检:未保存(无剧本地址)时,剧本里的相对 file: 引用非法——只支持绝对地址。 */
441
+ const preflightCheck = (femo: string): string | null => {
442
+ if (state?.scriptPath !== undefined && state.scriptPath.length > 0) return null
443
+ const refs: string[] = []
444
+ const re = /(?:file|文件)[::]\s*["'“”]([^"'“”]+)["'“”]/g
445
+ let m: RegExpExecArray | null
446
+ while ((m = re.exec(femo)) !== null) refs.push(m[1])
447
+ const isAbs = (p: string): boolean => /^[a-zA-Z]:[\\/]/.test(p) || p.startsWith('/') || p.startsWith('\\\\')
448
+ const relative = refs.filter(p => !isAbs(p))
449
+ if (relative.length === 0) return null
450
+ return `剧本未保存:依赖文件只支持绝对地址。以下引用是相对路径:${relative.join('、')}。请先「导出 .FEMO」保存剧本(相对路径将基于剧本文件位置解析),或改用绝对路径。`
451
+ }
452
+
453
+ const onRun = async (femo: string, opts?: { reset?: boolean; jobId?: number }): Promise<void> => {
454
+ const problem = preflightCheck(femo)
455
+ if (problem !== null) throw new Error(problem)
456
+ const response = await fetch('/femo-plugin/run', {
457
+ method: 'POST',
458
+ headers: { 'content-type': 'application/json' },
459
+ body: JSON.stringify({
460
+ sessionId,
461
+ femo,
462
+ ...(opts?.reset === true ? { reset: true } : {}),
463
+ // 显式续跑目标 Job 号(femoGen「继续」按钮——续跑旧 Job 时不依赖
464
+ // 宿主 currentJobId 指针;fresh 会忽略它)。
465
+ ...(typeof opts?.jobId === 'number' && Number.isFinite(opts.jobId) ? { jobId: Math.trunc(opts.jobId) } : {}),
466
+ }),
467
+ })
468
+ let message = `run HTTP ${response.status}`
469
+ try {
470
+ const data = await response.json() as { ok?: boolean; error?: string }
471
+ if (data.ok === true) return
472
+ message = data.error ?? message
473
+ } catch {
474
+ // non-JSON body: keep the status message
475
+ }
476
+ throw new Error(message)
477
+ }
478
+ const onPause = async (jobId?: number): Promise<{ paused?: boolean; state?: string } | undefined> => {
479
+ // 回执透传(paused:false=无活跃剧本)——femoGen 据此复位运行按钮
480
+ // (2026-09-06 反馈断链修复:此前该结果被静默吞掉,按钮卡死在"暂停"态)。
481
+ // 【2026-09-07 214 事故收尾】失败不再吞成本函数 undefined(femoGen 零感知
482
+ // 的静默链终点)——原样上抛,由画布的暂停反馈条可见报错。
483
+ return await injected.pauseScript(sessionId, jobId)
484
+ }
485
+
486
+ /** 「未改动」提醒弹窗状态:onExport 挂起等待用户裁决(依然保存/另存为/返回画布)。 */
487
+ const [saveReminder, setSaveReminder] = useState<{
488
+ path: string
489
+ resolve: (choice: 'save' | 'saveas' | 'back') => void
490
+ } | null>(null)
491
+
492
+ /** 导出(2026-08-30 三态行为,猫猫拍板):
493
+ * 无 path → 系统「保存文件」对话框选位置+命名保存(首次导出,2026-09-06
494
+ * 起不再走选目录+前端拼名);
495
+ * 有 path 且文件内容与 Editor Text 一致 → 弹「未改动」提醒(依然保存/另存为/返回画布);
496
+ * 有 path 且不一致 → Editor Text 覆盖写入该文件 + 记录 {path, text} 同步更新
497
+ * (save-script 带 sessionId 一步完成文件+记录)。
498
+ * 比对基准=path 文件内容(CRLF 归一)——它是「上次保存版本」的权威载体,
499
+ * 对旧记录(纯 {path})与运行时比对逻辑剥离 text 的情况都正确。
500
+ * 返回 undefined = 用户选了「返回编辑画布」(未保存)。 */
501
+ const onExport = async (femo: string, name: string): Promise<string | undefined> => {
502
+ const norm = (s: string): string => s.replace(/\r\n/g, '\n')
503
+ const currentPath = state?.scriptPath
504
+ if (currentPath !== undefined && currentPath.length > 0) {
505
+ let fileText: string | undefined
506
+ try {
507
+ fileText = await injected.readScript(currentPath)
508
+ } catch {
509
+ fileText = undefined // 文件被外部删除:视为「有改动」→ 覆盖保存即重建该文件
510
+ }
511
+ if (fileText !== undefined && norm(fileText) === norm(femo)) {
512
+ const choice = await new Promise<'save' | 'saveas' | 'back'>((resolve) => {
513
+ setSaveReminder({ path: currentPath, resolve })
514
+ })
515
+ if (choice === 'back') return undefined
516
+ if (choice === 'save') {
517
+ // 依然保存:内容相同也覆盖写回原地址(会话记录 {path, text} 一并刷新)。
518
+ const saved = await injected.saveScript(currentPath, femo, sessionId)
519
+ setState(prev => prev === null ? prev : { ...prev, scriptPath: saved, script: femo })
520
+ return saved
521
+ }
522
+ // saveas → 落到下方另存为流程(新地址 + 记录跟随新地址)
523
+ } else {
524
+ const saved = await injected.saveScript(currentPath, femo, sessionId)
525
+ setState(prev => prev === null ? prev : { ...prev, scriptPath: saved, script: femo })
526
+ return saved
527
+ }
528
+ }
529
+ // 首次保存/另存为:host 弹系统「保存文件」对话框(默认文件名=项目名,
530
+ // 2026-09-06 起不再走「选目录+前端拼名」)。拿到完整路径后 saveScript
531
+ // 直写(绝对路径 path 直写语义)。用户取消返回 undefined(未保存,与
532
+ // 「返回画布」同口径——前端静默,不弹提示)。
533
+ const safe = name.replace(/[\\/:*?"<>|]/g, '_').replace(/\.femo$/i, '')
534
+ const pickResp = await fetch('/femo-plugin/pick-save-path', {
535
+ method: 'POST',
536
+ headers: { 'content-type': 'application/json' },
537
+ body: JSON.stringify({ name: safe }),
538
+ })
539
+ const pickData = await readJsonOrThrow<{ ok?: boolean; path?: string | null; error?: string }>(pickResp, '保存对话框')
540
+ if (pickData.ok !== true) {
541
+ throw new Error(pickData.error ?? '保存对话框失败')
542
+ }
543
+ if (typeof pickData.path !== 'string' || pickData.path.length === 0) {
544
+ return undefined
545
+ }
546
+ const saved = await injected.saveScript(pickData.path, femo, sessionId)
547
+ setState(prev => prev === null ? prev : { ...prev, scriptPath: saved, script: femo })
548
+ return saved
549
+ }
550
+
551
+ /** 打开一条剧本的收尾(引用式,2026-08-30 语义不变):写会话记录 {path, text}
552
+ * + 更新本地状态。**两条入口共用这一段**——系统对话框选中的、清单里挑的,
553
+ * 落点必须一模一样(画布、editor 文本、后台 scriptPath 全部跟上),否则
554
+ * 「从清单打开」会变成一种与「直接打开」不同的半吊子状态。
555
+ * 记录写 {path, text} 是 mount 同款并存格式,不再复制到 projects/。 */
556
+ const recordAndLoad = async (path: string, content: string): Promise<{ path: string; content: string }> => {
557
+ await fetch('/femo-plugin/session-script', {
558
+ method: 'POST',
559
+ headers: { 'content-type': 'application/json' },
560
+ body: JSON.stringify({ sessionId, scriptPath: path, femo: content }),
561
+ })
562
+ setState(prev => prev === null ? prev : { ...prev, scriptPath: path, script: content })
563
+ return { path, content }
564
+ }
565
+
566
+ /** 导入·第二级(电脑端专属):host 弹系统文件选择器(浏览器 FileReader 拿不到
567
+ * 完整路径,引用式导入必须由 host 侧选)。用户取消返回 null。 */
568
+ const onImport = async (): Promise<{ path: string; content: string } | null> => {
569
+ const resp = await fetch('/femo-plugin/pick-script', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
570
+ const data = await readJsonOrThrow<{ ok?: boolean; path?: string | null; content?: string; error?: string }>(resp, '导入(系统文件选择器)')
571
+ if (data.ok !== true) throw new Error(data.error ?? 'pick-script failed')
572
+ // 提取局部常量再守卫:属性窄化不保留进 setState 回调(TS2345 实测)。
573
+ const pickedPath = data.path
574
+ const pickedContent = data.content
575
+ if (typeof pickedPath !== 'string' || pickedPath.length === 0 || pickedContent === undefined) return null
576
+ return await recordAndLoad(pickedPath, pickedContent)
577
+ }
578
+
579
+ /** 导入·第一级:取「导入过 / 导出过」的历史清单(权威在 host 侧
580
+ * src/femo-files.ts 的账本)。手机端只有这一级——系统文件对话框开在电脑
581
+ * 上,手机够不着,给了也是死路。 */
582
+ const onListFemoFiles = async (): Promise<FemoFileEntry[]> => {
583
+ const resp = await fetch('/femo-plugin/femo-files', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
584
+ const data = await readJsonOrThrow<{ ok?: boolean; files?: FemoFileEntry[]; error?: string }>(resp, '读取导入清单')
585
+ if (data.ok !== true) throw new Error(data.error ?? '读取导入清单失败')
586
+ return data.files ?? []
587
+ }
588
+
589
+ /** 导入·从清单里选一条:host 读盘取正文 → 与「浏览选中」同一段收尾。 */
590
+ const onPickFemoFile = async (path: string): Promise<{ path: string; content: string }> => {
591
+ const resp = await fetch('/femo-plugin/open-femo-file', {
592
+ method: 'POST',
593
+ headers: { 'content-type': 'application/json' },
594
+ body: JSON.stringify({ path }),
595
+ })
596
+ const data = await readJsonOrThrow<{ ok?: boolean; path?: string; content?: string; error?: string }>(resp, '打开文件')
597
+ if (data.ok !== true) throw new Error(data.error ?? '打开失败')
598
+ const pickedPath = data.path
599
+ const pickedContent = data.content
600
+ if (typeof pickedPath !== 'string' || pickedPath.length === 0 || pickedContent === undefined) {
601
+ throw new Error('打开失败:host 返回的文件数据不完整')
602
+ }
603
+ return await recordAndLoad(pickedPath, pickedContent)
604
+ }
605
+
606
+ /** 导入·从清单移除一条(2026-09-13):只划 host 侧账本(femo-files.ts),
607
+ * 源文件零接触。路径不在账本里也 ok(幂等)。 */
608
+ const onForgetFemoFile = async (path: string): Promise<void> => {
609
+ const resp = await fetch('/femo-plugin/forget-femo-file', {
610
+ method: 'POST',
611
+ headers: { 'content-type': 'application/json' },
612
+ body: JSON.stringify({ path }),
613
+ })
614
+ const data = await readJsonOrThrow<{ ok?: boolean; error?: string }>(resp, '从清单移除')
615
+ if (data.ok !== true) throw new Error(data.error ?? '从清单移除失败')
616
+ }
617
+
618
+ return (
619
+ <div style={{ width: '100%', height: '100%' }}>
620
+ <FEMOEditor
621
+ plugin
622
+ sessionId={sessionId}
623
+ enginePending={state?.pending === true}
624
+ onRun={onRun}
625
+ onPause={onPause}
626
+ onPersistScript={persistScript}
627
+ getRecordScript={getRecordScript}
628
+ onExport={onExport}
629
+ onImport={onImport}
630
+ onListFemoFiles={onListFemoFiles}
631
+ onPickFemoFile={onPickFemoFile}
632
+ onForgetFemoFile={onForgetFemoFile}
633
+ onBackToShell={injected.toggleSidebar}
634
+ savedPath={state?.scriptPath}
635
+ initialScript={state?.script}
636
+ initialCheckpoint={checkpointNode}
637
+ initialRunning={state?.running === true}
638
+ initialJobId={state?.jobId}
639
+ jobIds={state?.jobIds}
640
+ initialWaitingHuman={state?.waitingHuman}
641
+ initialLastError={state?.lastError}
642
+ onRestoreError={onRestoreError}
643
+ />
644
+ {conflict !== null && createPortal(
645
+ <div style={{
646
+ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(0,0,0,0.35)',
647
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
648
+ }}>
649
+ <div style={{
650
+ maxWidth: 420, width: 'calc(100% - 48px)', padding: '18px 20px', borderRadius: 12,
651
+ background: 'color-mix(in srgb, var(--dsw-alias-bg-layer-2, #f5f5f5) 96%, transparent)',
652
+ border: '1px solid var(--dsw-alias-border-l2, #e0e0e0)', boxShadow: '0 8px 28px rgba(0,0,0,0.22)',
653
+ fontSize: 13, lineHeight: 1.6,
654
+ }}>
655
+ <div style={{ fontWeight: 700, marginBottom: 6 }}>⚔️ 剧本冲突</div>
656
+ <div style={{ color: 'var(--dsw-alias-label-secondary, #666)', marginBottom: 14 }}>
657
+ 本窗口的编辑和其他窗口/设备的保存冲突了(对方先写入)。以哪个为准?
658
+ </div>
659
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
660
+ <button onClick={resolveConflictByReload} style={conflictBtnStyle}>加载最新版本</button>
661
+ <button
662
+ onClick={resolveConflictByOverride}
663
+ style={{ ...conflictBtnStyle, color: '#fff', background: '#d96b2b', borderColor: '#d96b2b' }}
664
+ >保留我的编辑</button>
665
+ </div>
666
+ </div>
667
+ </div>,
668
+ document.body,
669
+ )}
670
+ {saveReminder !== null && createPortal(
671
+ <div style={{
672
+ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(0,0,0,0.35)',
673
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
674
+ }}>
675
+ <div style={{
676
+ maxWidth: 420, width: 'calc(100% - 48px)', padding: '18px 20px', borderRadius: 12,
677
+ background: 'color-mix(in srgb, var(--dsw-alias-bg-layer-2, #f5f5f5) 96%, transparent)',
678
+ border: '1px solid var(--dsw-alias-border-l2, #e0e0e0)', boxShadow: '0 8px 28px rgba(0,0,0,0.22)',
679
+ fontSize: 13, lineHeight: 1.6,
680
+ }}>
681
+ <div style={{ fontWeight: 700, marginBottom: 6 }}>📤 你并未改动文本</div>
682
+ <div style={{ color: 'var(--dsw-alias-label-secondary, #666)', marginBottom: 14, wordBreak: 'break-all' }}>
683
+ 当前编辑器文本和 {saveReminder.path} 里保存的版本一样。可以依然保存(覆盖写回原文件)、另存为新文件,或返回画布(若你是忘了先「图到文本」把画布改动应用过来)。
684
+ </div>
685
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
686
+ <button
687
+ onClick={() => { const r = saveReminder; setSaveReminder(null); r.resolve('back') }}
688
+ style={conflictBtnStyle}
689
+ >返回编辑画布</button>
690
+ <button
691
+ onClick={() => { const r = saveReminder; setSaveReminder(null); r.resolve('saveas') }}
692
+ style={conflictBtnStyle}
693
+ >另存为</button>
694
+ <button
695
+ onClick={() => { const r = saveReminder; setSaveReminder(null); r.resolve('save') }}
696
+ style={{ ...conflictBtnStyle, color: '#fff', background: '#d96b2b', borderColor: '#d96b2b' }}
697
+ >依然保存</button>
698
+ </div>
699
+ </div>
700
+ </div>,
701
+ document.body,
702
+ )}
703
+ {editorNotice !== null && createPortal(
704
+ <div style={{
705
+ position: 'fixed', left: 12, right: 12, bottom: 12, zIndex: 300,
706
+ display: 'flex', gap: 8, alignItems: 'flex-start',
707
+ padding: '10px 14px', borderRadius: 10, margin: '0 auto', maxWidth: 560,
708
+ background: 'color-mix(in srgb, #fdecea 92%, transparent)',
709
+ border: '1px solid #e5b3ad', boxShadow: '0 6px 20px rgba(0,0,0,0.18)',
710
+ fontSize: 12.5, lineHeight: 1.55,
711
+ }}>
712
+ <div style={{ flex: 1 }}>
713
+ <div style={{ fontWeight: 700, marginBottom: 2 }}>⚠️ 剧本恢复失败(已上报主模型)</div>
714
+ <div style={{ color: 'var(--dsw-alias-label-secondary, #666)', whiteSpace: 'pre-wrap' }}>{editorNotice}</div>
715
+ </div>
716
+ <button
717
+ onClick={() => setEditorNotice(null)}
718
+ style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 14, lineHeight: 1, padding: 2 }}
719
+ title="关闭"
720
+ >✕</button>
721
+ </div>,
722
+ document.body,
723
+ )}
724
+ </div>
725
+ )
726
+ }