diff --git a/README.md b/README.md
index 1a78e881..5e1b102c 100644
--- a/README.md
+++ b/README.md
@@ -91,6 +91,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques
| [本机大盘 · Local Market Board](plugins/jzlikewei/kurumi-monitor/) | Watch your own machine as a stock terminal: CPU, GPU, temperature, memory, disk, network and every running process become listed stocks with live candlesticks, moving averages, a watchlist, a leaderboard and a trade tape, on macOS and Windows. Requires minimax Code 3.1.2 or later | [jzlikewei](https://github.com/jzlikewei) |
| [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) |
| [Site QA](plugins/lonelyguy-se1/site-qa/) | Check local HTML/robots/sitemap for SEO and accessibility gaps, then ask the agent to fix them (Mini App + skill/CLI). Requires MiniMax Code 3.1.6 or later | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) |
+| [Learn Workbench](plugins/meisijiya/learn-workbench/) | A teach-method learning workbench: mission, curriculum, per-lesson branch sessions, annotations, notes and a code-link panel; lesson file links open the matching lines in an in-app panel | [meisijiya](https://github.com/meisijiya) |
| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/) | Turn one sentence into verified 4K images: it plans the shot list, searches for reference images, generates, reviews each image by looking at it, corrects colour cast, runs a bounded fix loop and delivers the result with an acceptance report; multi-image runs generate a character sheet first so the same subject stays the same subject. Needs an H3-Image endpoint and key you configure yourself. Requires MiniMax Code 3.1.6 or later | [liddalidd](https://github.com/liddalidd) |
| [Express Media](plugins/andre-1998/express-media/) | Compress a video to the size each platform accepts and report whether it fits; the bundled limits table shows where every number comes from | [Andre-1998](https://github.com/Andre-1998) |
| [FactScribe Paper Workbench](plugins/unclemoc/factscribe/) | A local workbench for writing papers: open your manuscript projects, read the check report, the fact ledger and the knowledge base, and let the assistant propose edits you approve before anything reaches the file. 17 MCP tools, read-mostly by design; every write is gated by your confirmation. Requires MiniMax Code 3.1.2 or later | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 19c1ac99..4e930985 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -91,6 +91,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求
| [本机大盘](plugins/jzlikewei/kurumi-monitor/README.zh-CN.md) | 把本机当成行情终端来看:CPU、GPU、温度、内存、磁盘、网络与每个运行中的进程都是一只个股,实时 K 线、均线、自选行情、主力动向与逐笔成交,支持 macOS 与 Windows。需要 minimax Code 3.1.2 或更高版本 | [jzlikewei](https://github.com/jzlikewei) |
| [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) |
| [Site QA](plugins/lonelyguy-se1/site-qa/) | 检查本地 HTML/robots/sitemap 的 SEO / 无障碍问题,再让 Agent 修复(Mini App + skill/CLI)。需要 MiniMax Code 3.1.6 或更高版本(说明文档为英文) | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) |
+| [学习工作台](plugins/meisijiya/learn-workbench/README.zh-CN.md) | 按 teach 方法管理学习目录:使命、课纲、每课独立分支会话、划词批注与笔记提炼;课程里的文件链接会在应用内打开对应行 | [meisijiya](https://github.com/meisijiya) |
| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/README.zh-CN.md) | 把一句话需求跑成经过校验的 4K 图片:规划分镜、检索参考图、生成、看图评审、色偏校正、有限次修正,最后交付图片和验收报告;多图任务会先生成角色设定图锁定主体外观。需要自备 H3-Image 接口地址和 Key。需要 MiniMax Code 3.1.6 或更高版本 | [liddalidd](https://github.com/liddalidd) |
| [急件 · 视频投递](plugins/andre-1998/express-media/README.zh-CN.md) | 把视频压到各平台能收的体积,并如实告诉你发不发得出去;内置上限表标明每个数字的来源 | [Andre-1998](https://github.com/Andre-1998) |
| [FactScribe 论文工作台](plugins/unclemoc/factscribe/README.zh-CN.md) | 写论文的本地工作台:打开你的稿盘,看检查报告、事实账与知识库,助手给的改动先成提议单,你在页面上点采纳才落盘。17 个 MCP 工具以只读为主,写盘一律由你确认。需要 MiniMax Code 3.1.2 或更高版本 | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) |
diff --git a/plugins/meisijiya/learn-workbench/.minimax-plugin/plugin.json b/plugins/meisijiya/learn-workbench/.minimax-plugin/plugin.json
new file mode 100644
index 00000000..3ee34fdb
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/.minimax-plugin/plugin.json
@@ -0,0 +1,18 @@
+{
+ "schemaVersion": 1,
+ "name": "learn-workbench",
+ "displayName": "学习工作台",
+ "version": "1.0.0",
+ "description": "A teach-method learning workbench: mission, curriculum, per-lesson branch sessions, annotations, notes and a code-link panel.",
+ "author": "meisijiya",
+ "icon": "icon.png",
+ "category": "Education",
+ "exampleQueries": [
+ "打开学习工作台,继续第 3 课",
+ "为这个主题生成课纲,每节课开一个独立会话",
+ "把第 1–3 课结合我的批注提炼成笔记"
+ ],
+ "apps": [],
+ "mcpServers": [],
+ "skills": []
+}
diff --git a/plugins/meisijiya/learn-workbench/LICENSE b/plugins/meisijiya/learn-workbench/LICENSE
new file mode 100644
index 00000000..32a54759
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 meisijiya
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/meisijiya/learn-workbench/README.md b/plugins/meisijiya/learn-workbench/README.md
new file mode 100644
index 00000000..2f3993d9
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/README.md
@@ -0,0 +1,51 @@
+# Learn Workbench
+
+A teach-method learning workbench for MiniMax Code. You pick a learning folder; the workbench keeps its mission, curriculum, lessons, references, learning records and notes, and gives every lesson its own branch conversation with the Agent.
+
+The page is in Chinese, like the learning method it follows (Matt Pocock's teach approach).
+
+## What it does
+
+- **Setup**: a setup conversation interviews you and writes `MISSION.md`, `RESOURCES.md`, `GLOSSARY.md` and `NOTES.md` into the folder you chose.
+- **Curriculum**: the main conversation writes a 3–6 module curriculum into `.workbench/curriculum.json` plus a human-readable `CURRICULUM.md`. Regenerating it keeps existing lesson titles, claimed files and statuses.
+- **Lessons**: each lesson has a branch conversation that writes one self-contained HTML lesson into `lessons/`. Every lesson is required to stand alone: when it needs earlier knowledge, it recaps it in one or two sentences and links back.
+- **Annotations and notes**: select text in a lesson to annotate it; a note conversation distils chosen lessons and annotations into Markdown under `notes/`.
+- **Code links**: a file link inside a lesson (`main.py:608`, `main.py:46–48`) opens a floating code panel at that line, without leaving the app.
+- **Workspace management**: create or import learning folders, regenerate a lesson, clean generated artifacts, and switch models.
+
+## Install
+
+- **From Git (MiniMax Code 3.1.11 or later)**: in the plugin marketplace choose **Create → Mini App → Import from Git repository**, then enter `https://github.com/meisijiya/learn-workbench-miniapp`.
+- **Manual copy**: copy this folder to `~/.minimax/plugins/learn-workbench/` (`%USERPROFILE%\.minimax\plugins\learn-workbench\` on Windows), restart MiniMax Code, and make sure the plugin is enabled.
+
+The package declares `agentAccess`, `agentConcurrency` and `surface.window`, whose minimum client is MiniMax Code 3.1.2.
+
+## Use
+
+1. Open 学习工作台 from the plugin list.
+2. Choose or create a learning folder.
+3. Finish the setup conversation, then generate the curriculum from the main conversation.
+4. Open a lesson; its branch conversation writes and revises that lesson.
+5. Annotate the text you care about, and distil notes when you want them.
+
+## Tested environment
+
+- MiniMax Code 3.1.19 on Windows 11 (10.0.26200), using the Node runtime provided by the app.
+- Tested: setup; curriculum generation and regeneration; lesson generation, rewrite and clean-then-regenerate; annotations and highlights; note extraction; the code-link panel; workspace create, import and remove.
+- Not tested: macOS, Linux, clients older than 3.1.19, and very long conversations.
+
+## Data & access
+
+- **Files read and written**: only the learning folder you choose. The app creates and edits `MISSION.md`, `RESOURCES.md`, `GLOSSARY.md`, `NOTES.md`, `CURRICULUM.md`, `lessons/*.html`, `reference/*.html`, `learning-records/*.md`, `notes/*.md`, `assets/course.css`, and the `.workbench/` state folder (`workspace.json`, `curriculum.json`, `curriculum.backup.json`, `sessions.json`, `annotations.json`, `notes.json`, `rules/teach.md`, `context/`).
+- **Where state is stored**: the workspace folder above, plus a workspace registry (`registry.json`) in the Host-provided `context.dataDir`.
+- **Network**: the Mini App makes no external network requests. The page talks only to its own local Node service on the Host-assigned port. Agent turns it starts may use the Host's own tools and network under the Host's permissions.
+- **Agent turns**: it starts Agent sessions for setup, the main conversation (curriculum), each lesson branch, and note extraction. It reads and writes only its own session records inside the selected folder; it does not read other conversations.
+- **Tools**: no MCP endpoints; it declares `agentAccess: ["session.run"]`.
+- **Processes**: it does not spawn processes beyond the Host starting its own Node entry.
+- **Microphone, camera, notifications**: not used.
+- **Host navigation read**: no. It does not read which MiniMax Code page you are on.
+- **Code files**: clicking a file link reads a text or code file inside the learning folder (no `..`, 512 KB limit) and shows it in a panel.
+
+## License
+
+MIT — see `LICENSE`.
diff --git a/plugins/meisijiya/learn-workbench/README.zh-CN.md b/plugins/meisijiya/learn-workbench/README.zh-CN.md
new file mode 100644
index 00000000..56d90108
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/README.zh-CN.md
@@ -0,0 +1,49 @@
+# 学习工作台
+
+给 MiniMax Code 用的 teach 方法学习工作台。你选一个学习目录;工作台在这里维护使命、课纲、课程、速查、学习记录与笔记,并给每节课一个独立的分支会话。
+
+## 它能做什么
+
+- **前置配置**:配置会话采访你,把 `MISSION.md`、`RESOURCES.md`、`GLOSSARY.md`、`NOTES.md` 写进你选的目录。
+- **课纲**:主会话写 3–6 个模块的课纲到 `.workbench/curriculum.json`,同时写人类可读的 `CURRICULUM.md`。重新生成会保留已有课程标题、已认领文件与状态。
+- **课程**:每节课有自己的分支会话,写出一份自包含的 HTML 到 `lessons/`。每节课都要求能单独阅读;需要前置知识时,用一两句话回顾并链接回那一课。
+- **批注与笔记**:在课程里划词添加批注;提炼会话把选中的课程与批注整理成 `notes/` 下的 Markdown。
+- **代码链接**:课程里的文件链接(`main.py:608`、`main.py:46–48`)会在应用内弹出代码面板并定位到对应行。
+- **工作台管理**:新建/导入学习目录、逐课重新生成、清理产物、切换模型。
+
+## 安装
+
+- **从 Git 导入(MiniMax Code 3.1.11 起)**:插件市场 →「创建」→「Mini App」→「从 Git 仓库导入」,填 `https://github.com/meisijiya/learn-workbench-miniapp`。
+- **手动复制**:把本目录复制到 `~/.minimax/plugins/learn-workbench/`(Windows 为 `%USERPROFILE%\.minimax\plugins\learn-workbench\`),重启 MiniMax Code,确认插件已启用。
+
+包声明了 `agentAccess`、`agentConcurrency` 与 `surface.window`,最低客户端为 MiniMax Code 3.1.2。
+
+## 使用
+
+1. 从插件列表打开「学习工作台」。
+2. 选择或新建一个学习目录。
+3. 完成配置会话,再从主会话生成课纲。
+4. 打开一节课,让它的分支会话写课、改课。
+5. 划词批注,需要时提炼笔记。
+
+## 测试环境
+
+- MiniMax Code 3.1.19,Windows 11(10.0.26200),使用应用自带的 Node 运行时。
+- 已验证:配置;课纲生成与重新生成;课程生成、整节重写、清理后重新生成;批注与高亮;笔记提炼;代码链接面板;工作台新建、导入与移除。
+- 未验证:macOS、Linux、3.1.19 之前的客户端、超长会话。
+
+## 数据与访问
+
+- **读写文件**:只读写你选择的学习目录。应用会创建/修改 `MISSION.md`、`RESOURCES.md`、`GLOSSARY.md`、`NOTES.md`、`CURRICULUM.md`、`lessons/*.html`、`reference/*.html`、`learning-records/*.md`、`notes/*.md`、`assets/course.css`,以及 `.workbench/` 状态目录(`workspace.json`、`curriculum.json`、`curriculum.backup.json`、`sessions.json`、`annotations.json`、`notes.json`、`rules/teach.md`、`context/`)。
+- **状态存放**:上述学习目录,以及宿主提供的 `context.dataDir` 里的工作台注册表(`registry.json`)。
+- **网络**:Mini App 不发起外部网络请求;页面只访问宿主分配端口上的本地 Node 服务。它启动的 Agent 轮次可能按宿主权限使用宿主自己的工具与网络。
+- **Agent 轮次**:会为配置、主会话(课纲)、每节课的分支、笔记提炼启动 Agent 会话;只读写所选目录里自己的会话记录,不读取其他对话。
+- **工具**:没有 MCP endpoint;声明 `agentAccess: ["session.run"]`。
+- **进程**:除宿主启动自己的 Node 入口外,不额外启动进程。
+- **麦克风、摄像头、通知**:不使用。
+- **读取宿主页面**:不读取你当前在 MiniMax Code 的哪个页面。
+- **代码文件**:点击课程里的文件链接时,读取学习目录内的文本/代码文件(禁止 `..`,上限 512 KB)并在面板里显示。
+
+## 许可证
+
+MIT,见 `LICENSE`。
diff --git a/plugins/meisijiya/learn-workbench/icon.png b/plugins/meisijiya/learn-workbench/icon.png
new file mode 100644
index 00000000..fc6c09d1
Binary files /dev/null and b/plugins/meisijiya/learn-workbench/icon.png differ
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/app.css b/plugins/meisijiya/learn-workbench/miniapp/client/app.css
new file mode 100644
index 00000000..e8e8d225
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/app.css
@@ -0,0 +1,1353 @@
+:root,
+[data-theme='light'] {
+ --mcode-bg: #ffffff;
+ --mcode-bg-secondary: #f5f5f5;
+ --mcode-surface: #ffffff;
+ --mcode-surface-muted: #fafafa;
+ --mcode-text: #171717;
+ --mcode-text-muted: #666666;
+ --mcode-text-subtle: #a3a3a3;
+ --mcode-border: #0a0a0a14;
+ --mcode-border-strong: #0a0a0a2e;
+ --mcode-accent: #0094fc;
+ --mcode-accent-soft: #0094fc14;
+ --mcode-success: #04b54b;
+ --mcode-warning: #f56811;
+ --mcode-danger: #f73646;
+ --mcode-primary-action-bg: #171717;
+ --mcode-primary-action-text: #ffffff;
+ --paper: #fbfaf7;
+ --ink: #1c1b19;
+ --shadow: 0 0 20px rgb(10 10 10 / 8%);
+ --overlay: rgb(10 10 10 / 28%);
+}
+[data-theme='dark'] {
+ --mcode-bg: #171717;
+ --mcode-bg-secondary: #1c1c1c;
+ --mcode-surface: #262626;
+ --mcode-surface-muted: #202020;
+ --mcode-text: #ededed;
+ --mcode-text-muted: #949494;
+ --mcode-text-subtle: #6b6b6b;
+ --mcode-border: #ffffff14;
+ --mcode-border-strong: #ffffff2e;
+ --mcode-accent: #5eb0ff;
+ --mcode-accent-soft: #5eb0ff1a;
+ --mcode-success: #22c55e;
+ --mcode-warning: #f59e0b;
+ --mcode-danger: #f87171;
+ --mcode-primary-action-bg: #ffffff;
+ --mcode-primary-action-text: #171717;
+ --paper: #1e1d1b;
+ --ink: #ece9e2;
+ --shadow: 0 0 24px rgb(0 0 0 / 45%);
+ --overlay: rgb(0 0 0 / 55%);
+}
+
+* { box-sizing: border-box; }
+html, body { height: 100%; }
+body {
+ margin: 0;
+ background: var(--mcode-bg);
+ color: var(--mcode-text);
+ font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', 'PingFang SC',
+ 'Microsoft YaHei', Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ line-height: 1.55;
+ -webkit-font-smoothing: antialiased;
+}
+button, input, textarea, select { font: inherit; color: inherit; }
+button { cursor: pointer; background: none; border: 0; padding: 0; }
+a { color: var(--mcode-accent); text-decoration: none; }
+a:hover { text-decoration: underline; }
+::-webkit-scrollbar { width: 10px; height: 10px; }
+::-webkit-scrollbar-thumb {
+ background: var(--mcode-border-strong);
+ border-radius: 999px;
+ border: 3px solid transparent;
+ background-clip: content-box;
+}
+.mono {
+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.92em;
+}
+.muted { color: var(--mcode-text-muted); }
+.subtle { color: var(--mcode-text-subtle); }
+.label {
+ font-size: 11px;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--mcode-text-subtle);
+}
+.hidden { display: none !important; }
+.grow { flex: 1; }
+.row { display: flex; align-items: center; gap: 8px; }
+.stack { display: flex; flex-direction: column; gap: 8px; }
+
+.icon {
+ width: 15px;
+ height: 15px;
+ stroke: currentColor;
+ fill: none;
+ stroke-width: 1.6;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ flex: none;
+}
+
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 20px;
+ padding: 0 7px;
+ border-radius: 999px;
+ font-size: 11px;
+ line-height: 1;
+ border: 1px solid var(--mcode-border);
+ color: var(--mcode-text-muted);
+ background: var(--mcode-surface-muted);
+ white-space: nowrap;
+}
+.chip.ok {
+ color: var(--mcode-success);
+ background: color-mix(in srgb, var(--mcode-success) 10%, transparent);
+ border-color: transparent;
+}
+.chip.live {
+ color: var(--mcode-warning);
+ background: color-mix(in srgb, var(--mcode-warning) 12%, transparent);
+ border-color: transparent;
+}
+.chip.todo { color: var(--mcode-text-subtle); }
+
+.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ height: 32px;
+ padding: 0 12px;
+ border-radius: 8px;
+ border: 1px solid var(--mcode-border);
+ background: var(--mcode-surface);
+ color: var(--mcode-text);
+ font-size: 13px;
+ white-space: nowrap;
+ transition: background 150ms ease-out, border-color 150ms ease-out, opacity 150ms ease-out;
+}
+.btn:hover { background: var(--mcode-surface-muted); }
+.btn:focus-visible { outline: 2px solid var(--mcode-accent); outline-offset: 2px; }
+.btn[disabled] { opacity: 0.5; cursor: default; }
+.btn.primary {
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ border-color: transparent;
+}
+.btn.primary:hover { opacity: 0.88; background: var(--mcode-primary-action-bg); }
+.btn.ghost { border-color: transparent; background: transparent; color: var(--mcode-text-muted); }
+.btn.ghost:hover { background: var(--mcode-surface-muted); color: var(--mcode-text); }
+.btn.danger { color: var(--mcode-danger); }
+.btn.sm { height: 26px; padding: 0 9px; font-size: 12px; }
+.btn.icon { width: 30px; height: 30px; padding: 0; }
+
+.field {
+ width: 100%;
+ min-height: 34px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ background: var(--mcode-surface);
+ padding: 7px 10px;
+ font-size: 13px;
+ resize: vertical;
+ outline: none;
+}
+.field:focus {
+ border-color: var(--mcode-border-strong);
+ box-shadow: 0 0 0 3px var(--mcode-accent-soft);
+}
+.field::placeholder { color: var(--mcode-text-subtle); }
+select.field { height: 32px; min-height: 32px; padding: 0 8px; }
+
+.progressbar {
+ height: 4px;
+ border-radius: 999px;
+ background: var(--mcode-border);
+ overflow: hidden;
+}
+.progressbar > i {
+ display: block;
+ height: 100%;
+ background: var(--mcode-success);
+ border-radius: 999px;
+ transition: width 300ms ease-out;
+}
+
+/* ------------------------------------------------------------------ app */
+
+.app {
+ --rail-w: 248px;
+ --talk-w: 372px;
+ height: 100vh;
+ display: grid;
+ grid-template-columns: var(--rail-w) minmax(0, 1fr) var(--talk-w);
+ grid-template-rows: 52px minmax(0, 1fr);
+ grid-template-areas:
+ 'top top top'
+ 'rail center talk';
+}
+.app.no-talk { grid-template-columns: var(--rail-w) minmax(0, 1fr) 0; }
+.app.no-talk .talk { display: none; }
+.app.rail-collapsed { grid-template-columns: 0 minmax(0, 1fr) var(--talk-w); }
+.app.rail-collapsed.no-talk { grid-template-columns: 0 minmax(0, 1fr) 0; }
+.app.rail-collapsed .rail { display: none; }
+.app.rail-collapsed .rail-handle { display: none; }
+
+/* Drag handles sit on the two column borders, not inside either column. */
+.resizer {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 7px;
+ margin-left: -3px;
+ cursor: col-resize;
+ z-index: 35;
+ touch-action: none;
+ outline: none;
+}
+.resizer::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 3px;
+ width: 1px;
+ background: transparent;
+ transition: background 120ms ease-out;
+}
+.resizer:hover::after,
+.resizer:focus-visible::after,
+.resizing .resizer::after { background: var(--mcode-border-strong); }
+.resizing, .resizing * { cursor: col-resize !important; user-select: none; }
+.resizing iframe { pointer-events: none; }
+
+.top {
+ grid-area: top;
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 12px;
+ border-bottom: 1px solid var(--mcode-border);
+ min-width: 0;
+}
+.menu-wrap { position: relative; display: flex; align-items: center; }
+.menu-pop {
+ position: absolute;
+ top: 34px;
+ right: 0;
+ z-index: 55;
+ min-width: 196px;
+ max-width: min(280px, calc(100vw - 24px));
+ padding: 5px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ background: var(--mcode-bg);
+ box-shadow: 0 12px 36px rgb(10 10 10 / 16%);
+}
+.menu-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 7px 9px;
+ border-radius: 7px;
+ color: var(--mcode-text);
+ font-size: 12.5px;
+ text-align: left;
+}
+.menu-item:hover { background: var(--mcode-surface-muted); }
+.menu-item.on { background: var(--mcode-accent-soft); }
+.menu-item .icon { width: 14px; height: 14px; color: var(--mcode-text-subtle); }
+.menu-count { margin-left: auto; font-size: 10.5px; color: var(--mcode-text-subtle); }
+.menu-sep { height: 1px; margin: 4px 3px; background: var(--mcode-border); }
+.menu-label {
+ padding: 5px 8px 3px;
+ font-size: 10px;
+ letter-spacing: 0.06em;
+ color: var(--mcode-text-subtle);
+}
+.menu-select { width: 100%; height: 30px; min-height: 30px; margin: 0 0 2px; }
+.font-wrap { position: relative; display: flex; align-items: center; }
+.font-btn { font-weight: 600; letter-spacing: -0.02em; }
+.font-menu { top: 34px; right: 0; min-width: 190px; }
+.font-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ padding: 6px 4px;
+}
+.font-row .btn { min-width: 44px; height: 28px; padding: 0 8px; }
+.font-value {
+ min-width: 44px;
+ text-align: center;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: var(--mcode-text-muted);
+}
+.ws-mark {
+ width: 26px;
+ height: 26px;
+ border-radius: 7px;
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ display: grid;
+ place-items: center;
+ font-size: 11px;
+ font-weight: 600;
+ flex: none;
+}
+.ws-name {
+ font-size: 13.5px;
+ font-weight: 600;
+ line-height: 1.2;
+ max-width: 220px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ws-path {
+ font-size: 11px;
+ color: var(--mcode-text-subtle);
+ max-width: 300px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ws-switch {
+ height: 30px;
+ max-width: 190px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ background: var(--mcode-surface);
+ font-size: 12px;
+ padding: 0 6px;
+}
+
+.rail {
+ grid-area: rail;
+ border-right: 1px solid var(--mcode-border);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+.rail-head { padding: 12px 14px 8px; display: flex; flex-direction: column; gap: 8px; }
+.rail-head .progress-line { display: flex; align-items: center; gap: 8px; font-size: 11.5px; color: var(--mcode-text-muted); }
+.tree { flex: 1; overflow-y: auto; padding: 2px 8px 16px; }
+.mod {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 10px 6px 4px;
+}
+.mod .mname { font-size: 12px; font-weight: 600; }
+.mod .mcount { font-size: 10.5px; color: var(--mcode-text-subtle); }
+.lesson-row {
+ display: grid;
+ grid-template-columns: 22px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ text-align: left;
+ padding: 7px 8px;
+ border-radius: 8px;
+ color: var(--mcode-text-muted);
+ border: 1px solid transparent;
+}
+.lesson-row:hover { background: var(--mcode-surface-muted); }
+.lesson-row.active {
+ background: var(--mcode-accent-soft);
+ border-color: color-mix(in srgb, var(--mcode-accent) 24%, transparent);
+ color: var(--mcode-text);
+}
+.lesson-row .no { font-size: 11px; color: var(--mcode-text-subtle); font-variant-numeric: tabular-nums; }
+.lesson-row .nm { font-size: 12.5px; line-height: 1.35; overflow: hidden; text-overflow: ellipsis; }
+.lesson-row.active .nm { font-weight: 600; color: var(--mcode-text); }
+.lesson-row .marks { display: flex; align-items: center; gap: 5px; }
+.dotstate { width: 6px; height: 6px; border-radius: 999px; background: var(--mcode-border-strong); }
+.dotstate.done { background: var(--mcode-success); }
+.dotstate.active { background: var(--mcode-warning); }
+.annocount { font-size: 10px; color: var(--mcode-text-subtle); }
+.unread { width: 5px; height: 5px; border-radius: 999px; background: var(--mcode-accent); }
+.rail-foot { border-top: 1px solid var(--mcode-border); padding: 8px; display: flex; flex-direction: column; gap: 2px; }
+.rail-foot button {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 7px 8px;
+ border-radius: 7px;
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ text-align: left;
+}
+.rail-foot button:hover { background: var(--mcode-surface-muted); color: var(--mcode-text); }
+.rail-foot .count { margin-left: auto; font-size: 11px; color: var(--mcode-text-subtle); }
+
+.center { grid-area: center; position: relative; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
+.center-head { padding: 12px 20px 0; }
+.center-head .row1 { display: flex; align-items: center; flex-wrap: wrap; row-gap: 6px; gap: 10px; min-width: 0; }
+.center-head h2 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ letter-spacing: -0.005em;
+ white-space: nowrap;
+}
+.center-head .objective {
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ margin-top: 3px;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ line-height: 1.5;
+ white-space: normal;
+}
+.tabs { display: flex; gap: 18px; margin-top: 8px; }
+.tabs button {
+ padding: 0 0 9px;
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ border-bottom: 2px solid transparent;
+ margin-bottom: -1px;
+}
+.tabs button.on { color: var(--mcode-text); border-color: var(--mcode-text); }
+.center-body { flex: 1; overflow-y: auto; min-height: 0; }
+.center-body.flush { overflow: hidden; }
+.frame-wrap { height: 100%; background: #fff; }
+.frame-wrap iframe { width: 100%; height: 100%; border: 0; display: block; background: #fff; }
+
+.empty {
+ max-width: 460px;
+ margin: 48px auto;
+ text-align: center;
+ color: var(--mcode-text-muted);
+ font-size: 13px;
+ line-height: 1.7;
+}
+.empty h3 { margin: 10px 0 4px; font-size: 14px; color: var(--mcode-text); font-weight: 600; }
+.empty .icon { width: 22px; height: 22px; color: var(--mcode-text-subtle); }
+.empty .actions { margin-top: 14px; display: flex; gap: 8px; justify-content: center; }
+
+/* overview */
+.pane { padding: 20px 22px 60px; max-width: 760px; }
+.card {
+ border: 1px solid var(--mcode-border);
+ border-radius: 12px;
+ background: var(--mcode-surface);
+ padding: 14px 16px;
+}
+.card + .card { margin-top: 12px; }
+.card h3 { margin: 0 0 6px; font-size: 13px; font-weight: 600; }
+.card .card-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
+.card .card-head h3 { margin: 0; }
+.prose {
+ font-size: 13px;
+ line-height: 1.75;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+.prose.long { max-height: 220px; overflow: auto; }
+.stat-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
+.stat {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ padding: 11px 13px;
+ background: var(--mcode-surface);
+}
+.stat .k { font-size: 11px; color: var(--mcode-text-subtle); }
+.stat .v { font-size: 22px; font-weight: 600; letter-spacing: -0.01em; margin-top: 2px; line-height: 1.2; }
+.stat .v small { font-size: 12px; font-weight: 400; color: var(--mcode-text-muted); }
+.list-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 7px 0;
+ font-size: 12.5px;
+ line-height: 1.5;
+}
+.list-row + .list-row { border-top: 1px solid var(--mcode-border); }
+.list-row .t { color: var(--mcode-text); }
+.list-row .m { color: var(--mcode-text-subtle); font-size: 11px; }
+
+/* annotations */
+.anno-pane { padding: 18px 22px 60px; }
+.anno {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ padding: 10px 12px;
+ background: var(--mcode-surface);
+}
+.anno + .anno { margin-top: 8px; }
+.anno.flash { border-color: var(--mcode-accent); box-shadow: 0 0 0 3px var(--mcode-accent-soft); }
+.anno .quote {
+ font-family: ui-serif, Georgia, 'Songti SC', serif;
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ border-left: 2px solid var(--mcode-warning);
+ padding-left: 8px;
+ margin-bottom: 6px;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.anno .note { font-size: 13px; line-height: 1.6; white-space: pre-wrap; }
+.anno .meta { display: flex; align-items: center; gap: 8px; margin-top: 6px; font-size: 11px; color: var(--mcode-text-subtle); }
+.anno .meta .grow { flex: 1; }
+
+/* notes */
+.note-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ width: 100%;
+ padding: 10px 12px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ background: var(--mcode-surface);
+}
+.note-row + .note-row { margin-top: 8px; }
+.note-row:hover { border-color: var(--mcode-border-strong); }
+.note-open {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ flex: 1;
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+}
+.note-row .nt { font-size: 13px; font-weight: 600; }
+.note-row .nm { font-size: 11.5px; color: var(--mcode-text-subtle); margin-top: 2px; }
+.note-actions { display: flex; align-items: center; gap: 2px; opacity: 0.55; transition: opacity 120ms; }
+.note-row:hover .note-actions, .note-actions:focus-within { opacity: 1; }
+.note-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
+.tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 1px 7px;
+ border-radius: 999px;
+ background: var(--mcode-surface-muted);
+ color: var(--mcode-text-muted);
+ font-size: 10.5px;
+ line-height: 1.7;
+}
+.tag.more { color: var(--mcode-text-subtle); }
+.tag-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-bottom: 12px; }
+.tag-x {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 13px;
+ height: 13px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: none;
+ color: var(--mcode-text-subtle);
+ cursor: pointer;
+}
+.tag-x:hover { color: var(--mcode-text); background: var(--mcode-surface); }
+.tag-x .icon { width: 9px; height: 9px; }
+.tag-add { display: flex; }
+.tag-input {
+ width: 132px;
+ height: 24px;
+ min-height: 24px;
+ padding: 0 8px;
+ font-size: 11.5px;
+}
+.md { font-size: 13.5px; line-height: 1.75; max-width: 720px; }
+.md h1 { font-size: 20px; margin: 0 0 0.5em; }
+.md h2 { font-size: 15px; margin: 1.6em 0 0.3em; }
+.md h3 { font-size: 13.5px; margin: 1.2em 0 0.2em; }
+.md p { margin: 0 0 0.8em; }
+.md ul, .md ol { padding-left: 1.3em; margin: 0 0 0.8em; }
+.md li { margin: 0.15em 0; }
+.md code {
+ font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace;
+ font-size: 0.88em;
+ background: var(--mcode-surface-muted);
+ border-radius: 4px;
+ padding: 0.1em 0.32em;
+}
+.md pre {
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ padding: 10px 12px;
+ overflow: auto;
+ font-size: 12.5px;
+}
+.md pre code { background: none; padding: 0; }
+.md blockquote {
+ margin: 0.8em 0;
+ padding-left: 12px;
+ border-left: 2px solid var(--mcode-border-strong);
+ color: var(--mcode-text-muted);
+}
+.md a { border-bottom: 1px solid currentColor; }
+.md hr { border: 0; border-top: 1px solid var(--mcode-border); margin: 1.4em 0; }
+.md table {
+ border-collapse: collapse;
+ font-size: 12.5px;
+ margin: 0.4em 0 1em;
+ display: block;
+ overflow-x: auto;
+ max-width: 100%;
+}
+.md th,
+.md td {
+ border: 1px solid var(--mcode-border);
+ padding: 6px 9px;
+ text-align: left;
+ vertical-align: top;
+}
+.md th {
+ background: var(--mcode-surface-muted);
+ font-weight: 600;
+ color: var(--mcode-text-muted);
+}
+
+/* A note is a recall index, not a lesson summary: one hero line, then tight rows. */
+.note-md { max-width: 640px; font-size: 13.5px; line-height: 1.7; }
+.note-md h1 { font-size: 18px; margin-bottom: 0.4em; }
+.note-md blockquote {
+ margin: 0 0 1.5em;
+ padding: 11px 14px;
+ border-left: 3px solid var(--mcode-accent);
+ border-radius: 0 8px 8px 0;
+ background: var(--mcode-accent-soft);
+ color: var(--mcode-text);
+ font-size: 15px;
+ line-height: 1.7;
+}
+.note-md h2 {
+ margin: 1.7em 0 0.5em;
+ padding-top: 13px;
+ border-top: 1px solid var(--mcode-border);
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ color: var(--mcode-text-subtle);
+}
+.note-md ul { list-style: none; padding: 0; margin: 0 0 1.2em; }
+.note-md ul li {
+ position: relative;
+ margin: 0;
+ padding: 5px 0 5px 15px;
+ line-height: 1.65;
+}
+.note-md ul li::before {
+ content: '';
+ position: absolute;
+ left: 2px;
+ top: 0.95em;
+ width: 5px;
+ height: 5px;
+ border-radius: 999px;
+ background: var(--mcode-accent);
+}
+.note-md li strong { font-weight: 600; }
+.note-md ol { padding-left: 1.35em; margin: 0 0 1.2em; }
+.note-md ol li { padding: 2px 0; line-height: 1.65; }
+.note-md table {
+ display: block;
+ width: 100%;
+ max-width: 100%;
+ overflow-x: auto;
+ border-collapse: collapse;
+ margin: 0 0 1.2em;
+ font-size: 12.5px;
+}
+.note-md th,
+.note-md td {
+ border-bottom: 1px solid var(--mcode-border);
+ padding: 6px 8px;
+ text-align: left;
+ vertical-align: top;
+}
+.note-md thead th {
+ font-size: 10.5px;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ color: var(--mcode-text-subtle);
+}
+.note-md tbody tr:nth-child(even) { background: var(--mcode-surface-muted); }
+
+/* teacher style card in the overview */
+.teacher-controls {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+}
+.teacher-controls select {
+ flex: 1 1 220px;
+ max-width: 320px;
+}
+.teacher-preview {
+ margin-top: 8px;
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+}
+.teacher-preview summary { cursor: pointer; }
+.teacher-preview pre {
+ margin: 6px 0 0;
+ max-height: 180px;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-size: 11px;
+ line-height: 1.6;
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ padding: 8px 10px;
+}
+
+/* chat */
+.talk {
+ grid-area: talk;
+ position: relative;
+ border-left: 1px solid var(--mcode-border);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+.talk-head {
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--mcode-border);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 50px;
+}
+.talk-head .t {
+ font-size: 12.5px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.talk-head .s { font-size: 11px; color: var(--mcode-text-subtle); }
+.chat-scroll {
+ flex: 1;
+ overflow-y: auto;
+ min-height: 0;
+ padding: 16px 14px 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.msg { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
+.msg .who {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 10.5px;
+ color: var(--mcode-text-subtle);
+}
+.msg .who .icon { width: 13px; height: 13px; }
+.msg .who .at {
+ margin-left: auto;
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ color: var(--mcode-text-subtle);
+ opacity: 0.8;
+}
+.msg .bubble {
+ font-size: 13px;
+ line-height: 1.7;
+ white-space: pre-wrap;
+ word-break: break-word;
+ overflow-wrap: anywhere;
+}
+.msg.user { align-items: flex-end; }
+.msg.user .who { justify-content: flex-end; }
+.msg.user .who .at { margin-left: 6px; }
+.msg.user .bubble {
+ max-width: 88%;
+ background: var(--mcode-accent-soft);
+ border: 1px solid color-mix(in srgb, var(--mcode-accent) 22%, transparent);
+ border-radius: 12px 12px 4px 12px;
+ padding: 8px 10px;
+ color: var(--mcode-text);
+}
+.msg.user .bubble.prompt-seed {
+ font-size: 12px;
+ color: var(--mcode-text-muted);
+}
+.msg.assistant .bubble {
+ padding: 0 0 0 10px;
+ border-left: 2px solid var(--mcode-border);
+ white-space: normal;
+}
+.msg.assistant.live .bubble {
+ border-left-color: color-mix(in srgb, var(--mcode-accent) 55%, transparent);
+}
+.msg.assistant .bubble > :first-child { margin-top: 0; }
+.msg.assistant .bubble > :last-child { margin-bottom: 0; }
+.msg.assistant .bubble h1 { font-size: 15px; margin: 0 0 0.45em; }
+.msg.assistant .bubble h2 { font-size: 13.5px; margin: 1.15em 0 0.35em; }
+.msg.assistant .bubble h3 { font-size: 13px; margin: 1em 0 0.25em; }
+.msg.assistant .bubble p { margin: 0 0 0.7em; }
+.msg.assistant .bubble ul,
+.msg.assistant .bubble ol { margin: 0 0 0.7em; padding-left: 1.25em; }
+.msg.assistant .bubble li + li { margin-top: 0.2em; }
+.msg.assistant .bubble li::marker { color: var(--mcode-text-subtle); }
+.msg.assistant .bubble strong { color: var(--mcode-text); font-weight: 600; }
+.msg.assistant .bubble code {
+ font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace;
+ font-size: 0.88em;
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 5px;
+ padding: 0.08em 0.3em;
+ white-space: pre-wrap;
+}
+.msg.assistant .bubble pre {
+ position: relative;
+ margin: 0.6em 0 0.8em;
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 9px;
+ padding: 10px 11px;
+ overflow: auto;
+ max-width: 100%;
+ font-size: 11.5px;
+ line-height: 1.6;
+}
+.msg.assistant .bubble pre[data-lang] { padding-top: 22px; }
+.msg.assistant .bubble pre[data-lang]::before {
+ content: attr(data-lang);
+ position: absolute;
+ top: 5px;
+ left: 11px;
+ font-size: 9.5px;
+ letter-spacing: 0.06em;
+ color: var(--mcode-text-subtle);
+}
+.msg.assistant .bubble pre code {
+ background: none;
+ border: 0;
+ padding: 0;
+ white-space: pre;
+}
+.msg.assistant .bubble blockquote {
+ margin: 0.7em 0;
+ padding: 6px 10px;
+ border-left: 2px solid var(--mcode-border-strong);
+ border-radius: 0 6px 6px 0;
+ background: var(--mcode-surface-muted);
+ color: var(--mcode-text-muted);
+}
+.msg.assistant .bubble hr {
+ border: 0;
+ border-top: 1px solid var(--mcode-border);
+ margin: 1em 0;
+}
+.msg.assistant .bubble table {
+ display: block;
+ max-width: 100%;
+ overflow-x: auto;
+ border-collapse: collapse;
+ font-size: 12px;
+ margin: 0.6em 0 0.8em;
+ white-space: normal;
+}
+.msg.assistant .bubble th,
+.msg.assistant .bubble td {
+ border-bottom: 1px solid var(--mcode-border);
+ padding: 5px 7px;
+ text-align: left;
+ vertical-align: top;
+}
+.msg.assistant .bubble thead th {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--mcode-text-subtle);
+}
+.msg .bubble a {
+ color: var(--mcode-accent);
+ border-bottom: 1px solid color-mix(in srgb, var(--mcode-accent) 45%, transparent);
+ overflow-wrap: anywhere;
+}
+.msg.system .bubble {
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+ background: var(--mcode-surface-muted);
+ border-radius: 8px;
+ padding: 6px 9px;
+}
+.msg.system.error .bubble { color: var(--mcode-danger); }
+.msg.system.handoff .bubble {
+ padding: 0;
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-left: 2px solid var(--mcode-accent);
+ border-radius: 10px;
+ overflow: hidden;
+ white-space: normal;
+}
+.msg.system.handoff summary {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 8px 10px;
+ cursor: pointer;
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+ list-style: none;
+}
+.msg.system.handoff summary::-webkit-details-marker { display: none; }
+.msg.system.handoff .handoff-label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.msg.system.handoff .chev {
+ margin-left: auto;
+ color: var(--mcode-text-subtle);
+ transition: transform 120ms ease-out;
+}
+.msg.system.handoff details[open] .chev { transform: rotate(90deg); }
+.msg.system.handoff .handoff-pre {
+ margin: 0;
+ padding: 9px 10px;
+ border-top: 1px solid var(--mcode-border);
+ background: var(--mcode-surface);
+ max-height: 240px;
+ overflow: auto;
+ white-space: pre-wrap;
+ font-size: 10.5px;
+ line-height: 1.55;
+ color: var(--mcode-text-muted);
+}
+.msg .bubble .pending-dots::after {
+ content: '···';
+ letter-spacing: 0.1em;
+ color: var(--mcode-text-subtle);
+ animation: wb-pulse 1.4s ease-in-out infinite;
+}
+.msg .live-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--mcode-accent);
+ animation: wb-pulse 1.2s ease-in-out infinite;
+}
+@keyframes wb-pulse {
+ 0%, 100% { opacity: 0.25; }
+ 50% { opacity: 1; }
+}
+.tool-stack {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ background: var(--mcode-surface-muted);
+ padding: 5px;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+.tool-stack-head {
+ font-size: 9.5px;
+ letter-spacing: 0.08em;
+ color: var(--mcode-text-subtle);
+ padding: 1px 3px 2px;
+}
+.tool-line {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ min-width: 0;
+ padding: 5px 7px;
+ border-radius: 6px;
+ background: var(--mcode-surface);
+ font-size: 11px;
+ color: var(--mcode-text-muted);
+}
+.tool-line .icon { width: 12px; height: 12px; flex: none; }
+.tool-line .tool-name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--mcode-text);
+}
+.tool-line .tool-phase { flex: none; font-size: 10px; color: var(--mcode-text-subtle); }
+.tool-line.start .icon { color: var(--mcode-warning); }
+.tool-line.ok .icon { color: var(--mcode-success); }
+.tool-line.fail .icon { color: var(--mcode-danger); }
+.composer { border-top: 1px solid var(--mcode-border); padding: 8px 10px 10px; }
+.composer .box {
+ border: 1px solid var(--mcode-border-strong);
+ border-radius: 14px;
+ padding: 8px 10px 6px;
+ background: var(--mcode-surface);
+}
+.composer .box:focus-within { border-color: var(--mcode-border-strong); box-shadow: 0 0 0 3px var(--mcode-accent-soft); }
+.composer textarea {
+ width: 100%;
+ border: 0;
+ background: none;
+ outline: none;
+ resize: none;
+ font-size: 13px;
+ line-height: 1.5;
+ min-height: 38px;
+ max-height: 120px;
+}
+.composer .row { display: flex; align-items: center; gap: 6px; margin-top: 2px; }
+.composer .tools { display: flex; align-items: center; gap: 2px; min-width: 0; flex: 1; }
+.composer .actions { display: flex; align-items: center; gap: 4px; flex: none; }
+.composer select.pick {
+ min-width: 0;
+ max-width: 190px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--mcode-text);
+ font-size: 11.5px;
+ line-height: 1;
+ padding: 4px;
+}
+.composer select.pick:hover { background: var(--mcode-surface-muted); }
+.composer select.pick:disabled { opacity: 0.5; }
+.composer select.pick.effort {
+ max-width: 74px;
+ color: var(--mcode-text-muted);
+ border: 1px solid var(--mcode-border);
+ padding: 3px;
+}
+.composer .send {
+ width: 30px;
+ height: 30px;
+ border-radius: 999px;
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ display: grid;
+ place-items: center;
+ flex: none;
+}
+.composer .send.continue {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: auto;
+ min-width: 30px;
+ padding: 0 10px;
+ gap: 5px;
+ border-radius: 999px;
+ font-size: 11.5px;
+ font-weight: 500;
+}
+.composer .send.continue .icon { width: 13px; height: 13px; }
+.composer .send:hover { opacity: 0.88; }
+.composer .send[disabled] { opacity: 0.35; cursor: default; }
+.composer .send .icon { width: 15px; height: 15px; }
+
+/* interaction cards */
+.card-interact {
+ border: 1px solid var(--mcode-border-strong);
+ border-radius: 10px;
+ background: var(--mcode-surface);
+ padding: 10px 11px;
+ font-size: 12.5px;
+}
+.card-interact h4 { margin: 0 0 4px; font-size: 12px; font-weight: 600; }
+.card-interact p { margin: 0 0 8px; color: var(--mcode-text-muted); line-height: 1.55; }
+.card-interact .opts { display: flex; flex-direction: column; gap: 5px; margin-bottom: 8px; }
+.card-interact .opt {
+ display: flex;
+ gap: 7px;
+ align-items: flex-start;
+ border: 1px solid var(--mcode-border);
+ border-radius: 7px;
+ padding: 6px 8px;
+ cursor: pointer;
+ background: var(--mcode-surface-muted);
+ font-size: 12.5px;
+ line-height: 1.45;
+}
+.card-interact .opt input { margin-top: 2px; flex: none; }
+.card-interact .opt .d { display: block; color: var(--mcode-text-muted); font-size: 11.5px; }
+.card-interact .step + .step { margin-top: 10px; }
+.card-interact .step-q { font-weight: 600; margin-bottom: 5px; }
+.card-interact .plan {
+ background: var(--mcode-surface-muted);
+ border-radius: 8px;
+ padding: 9px 10px;
+ max-height: 260px;
+ overflow: auto;
+ white-space: pre-wrap;
+ font-size: 12px;
+ margin-bottom: 8px;
+}
+
+/* modal */
+.modal-backdrop {
+ position: fixed;
+ inset: 0;
+ background: var(--overlay);
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ z-index: 60;
+}
+.modal {
+ width: min(560px, 100%);
+ max-height: min(760px, calc(100vh - 48px));
+ background: var(--mcode-bg);
+ border: 1px solid var(--mcode-border);
+ border-radius: 12px;
+ box-shadow: 0 18px 60px rgb(0 0 0 / 22%);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+.modal.wide { width: min(720px, 100%); }
+.modal-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 13px 16px;
+ border-bottom: 1px solid var(--mcode-border);
+}
+.modal-head h3 { margin: 0; font-size: 14px; font-weight: 600; }
+.modal-body { padding: 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; }
+.modal-foot {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 16px;
+ border-top: 1px solid var(--mcode-border);
+}
+.modal-foot .left { margin-right: auto; }
+
+/* directory picker */
+.crumbs {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+ overflow: hidden;
+}
+.crumbs .path {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ direction: rtl;
+ text-align: left;
+ flex: 1;
+}
+.dir-list {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ max-height: 250px;
+ overflow-y: auto;
+ padding: 4px;
+ background: var(--mcode-surface);
+}
+.dir {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ text-align: left;
+ padding: 6px 8px;
+ border-radius: 7px;
+ font-size: 12.5px;
+}
+.dir:hover { background: var(--mcode-surface-muted); }
+.dir .n { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dir.hidden-dir { opacity: 0.55; }
+.dir .badge {
+ margin-left: auto;
+ font-size: 10px;
+ color: var(--mcode-success);
+ border: 1px solid color-mix(in srgb, var(--mcode-success) 40%, transparent);
+ border-radius: 999px;
+ padding: 0 6px;
+}
+.checkline { display: flex; align-items: center; gap: 7px; font-size: 12.5px; color: var(--mcode-text-muted); }
+.checkline input { margin: 0; }
+.form-label { font-size: 11.5px; color: var(--mcode-text-muted); margin-bottom: 4px; display: block; }
+.hint-line { font-size: 11.5px; color: var(--mcode-text-subtle); line-height: 1.6; }
+.hint-line.warn { color: var(--mcode-warning); }
+
+/* lesson file panel: a code window opened from a link inside a lesson */
+.modal.wide:has(.file-view) { width: min(1000px, 100%); }
+.modal-body:has(.file-view) { padding: 0; }
+.ref-frame { height: min(70vh, 680px); }
+.ref-frame iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ display: block;
+ background: #fff;
+ border-radius: 8px;
+}
+
+.file-view {
+ max-height: min(62vh, 640px);
+ overflow: auto;
+ font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+}
+.file-row { display: flex; gap: 12px; padding: 0 14px; white-space: pre; }
+.file-row .ln { flex: 0 0 52px; text-align: right; color: var(--mcode-text-subtle); user-select: none; }
+.file-row .lc { flex: 1 0 auto; white-space: pre; }
+.file-row.hit { background: color-mix(in srgb, var(--mcode-warning) 15%, transparent); }
+
+/* notes picker */
+.pick-group + .pick-group { margin-top: 10px; }
+.pick-group .g-title { font-size: 11.5px; font-weight: 600; color: var(--mcode-text-muted); margin-bottom: 4px; }
+.pick-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 7px;
+ border-radius: 7px;
+ font-size: 12.5px;
+}
+.pick-row:hover { background: var(--mcode-surface-muted); }
+.pick-row input { margin: 0; }
+.pick-row .t { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.pick-row .c { font-size: 10.5px; color: var(--mcode-text-subtle); }
+.manage-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 2px;
+ border-top: 1px solid var(--mcode-border);
+}
+.manage-row:first-child { border-top: 0; }
+.manage-row .nt { font-size: 13px; font-weight: 600; }
+.manage-row .nm { font-size: 11px; color: var(--mcode-text-subtle); word-break: break-all; }
+.clean-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ font-size: 12.5px;
+ line-height: 1.55;
+ padding: 3px 0;
+ cursor: pointer;
+}
+.clean-row input { margin: 3px 0 0; flex: none; }
+
+/* landing */
+.landing {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 40px 24px;
+ background: var(--mcode-bg);
+}
+.landing-inner { width: min(680px, 100%); }
+.landing h1 { font-size: 22px; font-weight: 600; letter-spacing: -0.01em; margin: 0 0 4px; }
+.landing .sub { color: var(--mcode-text-muted); font-size: 13px; margin-bottom: 22px; }
+.landing .actions { display: flex; gap: 8px; margin-bottom: 26px; }
+.recent { border-top: 1px solid var(--mcode-border); padding-top: 14px; }
+.recent h2 { font-size: 12px; color: var(--mcode-text-subtle); font-weight: 500; margin: 0 0 8px; }
+.recent-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ text-align: left;
+ padding: 9px 10px;
+ border-radius: 9px;
+ border: 1px solid transparent;
+}
+.recent-row:hover { background: var(--mcode-surface-muted); border-color: var(--mcode-border); }
+.recent-row .nm { font-size: 13px; font-weight: 600; }
+.recent-row .pt { font-size: 11px; color: var(--mcode-text-subtle); }
+
+/* toast */
+.toast {
+ position: fixed;
+ left: 50%;
+ bottom: 22px;
+ transform: translateX(-50%);
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ border-radius: 999px;
+ padding: 7px 14px;
+ font-size: 12.5px;
+ box-shadow: 0 8px 24px rgb(0 0 0 / 20%);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 180ms ease-out, transform 180ms ease-out;
+ z-index: 80;
+ max-width: 80vw;
+}
+.toast.show { opacity: 1; transform: translateX(-50%) translateY(-2px); }
+.toast.error { background: var(--mcode-danger); color: #fff; }
+
+/* annotation modal */
+.quote-box {
+ border-left: 2px solid var(--mcode-warning);
+ background: var(--mcode-surface-muted);
+ border-radius: 0 8px 8px 0;
+ padding: 9px 11px;
+ font-family: ui-serif, Georgia, 'Songti SC', serif;
+ font-size: 13px;
+ line-height: 1.7;
+ max-height: 130px;
+ overflow: auto;
+}
+.note-input { min-height: 96px; }
+
+@media (max-width: 1120px) {
+ .app { grid-template-columns: var(--rail-w) minmax(0, 1fr); grid-template-areas: 'top top' 'rail center'; }
+ .app.rail-collapsed { grid-template-columns: 0 minmax(0, 1fr); }
+ .talk {
+ position: fixed;
+ right: 0;
+ top: 52px;
+ bottom: 0;
+ width: min(var(--talk-w), 88vw);
+ background: var(--mcode-bg);
+ box-shadow: -14px 0 40px rgb(10 10 10 / 12%);
+ z-index: 30;
+ }
+ .app.no-talk .talk { display: none; }
+}
+@media (max-width: 760px) {
+ .app { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'center'; }
+ .app.rail-collapsed { grid-template-columns: minmax(0, 1fr); }
+ .rail { display: none; }
+ .rail-handle { display: none; }
+ .rail-toggle { display: none; }
+ .top { gap: 6px; }
+ .ws-path { display: none; }
+ .stat-grid { grid-template-columns: 1fr 1fr; }
+ .center-head { padding: 10px 14px 0; }
+ .pane, .anno-pane { padding: 16px 14px 60px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ * { transition: none !important; animation: none !important; }
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/app.js b/plugins/meisijiya/learn-workbench/miniapp/client/app.js
new file mode 100644
index 00000000..f5bcbd86
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/app.js
@@ -0,0 +1,3458 @@
+(function () {
+ 'use strict';
+
+ /* ------------------------------------------------------------- helpers */
+
+ const $ = (selector, root = document) => root.querySelector(selector);
+ const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector));
+
+ const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
+ const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ESCAPES[char]);
+
+ const ICONS = {
+ book: '',
+ chat: '',
+ note: '',
+ play: '',
+ check: '',
+ plus: '',
+ x: '',
+ dots: '',
+ send: '',
+ open: '',
+ folder: '',
+ spark: '',
+ up: '',
+ left: '',
+ stop: '',
+ pause: '',
+ menu: '',
+ panel: '',
+ refresh: '',
+ trash: '',
+ pencil: '',
+ };
+ const icon = (name) => ``;
+
+ const ERROR_TEXT = {
+ BUSY: '这一轮还在进行,等它结束再发。',
+ ANSWER_PENDING: '先回答右侧会话里待回答的问题,再重新生成这一课。',
+ NOT_PERMITTED: '这个能力在插件设置里被关掉了,打开后再试。',
+ NO_QUESTION: '这个问题已经结束,刷新一下会话。',
+ NO_PERMISSION: '这次授权请求已经结束。',
+ NOT_FOUND: '对象不存在,可能已被移动或删除。',
+ note_not_found: '这份笔记已经不在了,刷新一下列表。',
+ empty_title: '标题不能为空。',
+ invalid_action: '这个笔记操作不认识,刷新后重试。',
+ TARGET_NOT_EMPTY: '目标文件夹不是空的,换一个名字或目录。',
+ NOT_A_WORKSPACE: '这个目录里没有学习工作台(缺少 .workbench/workspace.json)。',
+ SETUP_REQUIRED: '先完成前置配置,再生成课纲。',
+ PARENT_NOT_FOUND: '目录不存在。',
+ HOME_NOT_ALLOWED: '别把工作台建在用户主目录,请选一个具体项目文件夹。',
+ DRIVE_ROOT_NOT_ALLOWED: '别把工作台建在磁盘根目录,请选一个项目文件夹。',
+ not_a_directory: '这个路径不是一个文件夹。',
+ path_must_be_absolute: '要填完整路径,例如 D:\\代码\\项目名。',
+ path_not_allowed: '只能在工作台目录、用户主目录或磁盘根目录里选。',
+ NO_LESSONS: '选中的课程还没有生成文件,先生成课程。',
+ INVALID_TEMPLATE: '模板名称和提示词都要填。',
+ TEMPLATE_LIMIT: '自定义模板最多 12 个,先删一个。',
+ TEMPLATE_NOT_FOUND: '这个模板不存在,刷新后重试。',
+ INVALID_ACTION: '未知的模板操作。',
+ SESSION_CREATE_FAILED: '无法创建会话,检查插件权限后重试。',
+ internal_error: '内部错误,看一下插件诊断。',
+ };
+
+ function errorText(error) {
+ const code = error && error.code;
+ return ERROR_TEXT[code] || (error && error.message) || '操作失败';
+ }
+
+ async function api(path, options) {
+ const opts = options || {};
+ const response = await fetch(path, {
+ method: opts.method || 'GET',
+ headers: opts.body ? { 'content-type': 'application/json' } : undefined,
+ body: opts.body ? JSON.stringify(opts.body) : undefined,
+ });
+ const text = await response.text();
+ let data = null;
+ try {
+ data = text ? JSON.parse(text) : null;
+ } catch {
+ data = null;
+ }
+ if (!response.ok) {
+ const error = new Error((data && (data.message || data.error)) || `HTTP ${response.status}`);
+ error.code = (data && data.error) || 'http_error';
+ error.status = response.status;
+ throw error;
+ }
+ return data;
+ }
+
+ let toastTimer = 0;
+ function toast(message, kind) {
+ const node = $('#toast');
+ if (!node) return;
+ node.textContent = message;
+ node.className = `toast show${kind === 'error' ? ' error' : ''}`;
+ window.clearTimeout(toastTimer);
+ toastTimer = window.setTimeout(() => {
+ node.className = 'toast';
+ }, 2800);
+ }
+
+ function clockLabel(ms) {
+ if (!ms) return '';
+ const date = new Date(ms);
+ const pad = (n) => String(n).padStart(2, '0');
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
+ }
+
+ function timeLabel(ms) {
+ if (!ms) return '';
+ const date = new Date(ms);
+ const pad = (n) => String(n).padStart(2, '0');
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
+ }
+
+ /* --------------------------------------------------------- mini markdown */
+
+ function md(text) {
+ const source = esc(String(text ?? '')).replace(/\r\n/g, '\n');
+ const lines = source.split('\n');
+ const out = [];
+ let index = 0;
+
+ const inline = (value) =>
+ value
+ .replace(/`([^`]+)`/g, '$1')
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
+ .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '$1')
+ .replace(/(^|[\s(])(https?:\/\/[^\s<)]+)/g, '$1$2');
+
+ while (index < lines.length) {
+ const line = lines[index];
+
+ if (/^```/.test(line)) {
+ const lang = line.slice(3).trim();
+ const buffer = [];
+ index += 1;
+ while (index < lines.length && !/^```/.test(lines[index])) {
+ buffer.push(lines[index]);
+ index += 1;
+ }
+ index += 1;
+ out.push(
+ `
${buffer.join('\n')}
`,
+ );
+ continue;
+ }
+
+ if (!line.trim()) {
+ index += 1;
+ continue;
+ }
+
+ const heading = line.match(/^(#{1,4})\s+(.*)$/);
+ if (heading) {
+ const level = Math.min(3, heading[1].length);
+ out.push(`${inline(heading[2])}`);
+ index += 1;
+ continue;
+ }
+
+ if (/^(\s*)(---|\*\*\*|___)\s*$/.test(line)) {
+ out.push('
');
+ index += 1;
+ continue;
+ }
+
+ if (/^\s*\|/.test(line) && /^\s*\|?[\s:-]+\|/.test(lines[index + 1] || '')) {
+ const header = line.split('|').map((cell) => cell.trim()).filter(Boolean);
+ index += 2;
+ const rows = [];
+ while (index < lines.length && /^\s*\|/.test(lines[index])) {
+ const cells = lines[index].split('|').map((cell) => cell.trim());
+ if (cells.length && cells[0] === '') cells.shift();
+ if (cells.length && cells[cells.length - 1] === '') cells.pop();
+ rows.push(cells);
+ index += 1;
+ }
+ out.push(
+ `${header.map((cell) => `| ${inline(cell)} | `).join('')}
${rows
+ .map((cells) => `${cells.map((cell) => `| ${inline(cell)} | `).join('')}
`)
+ .join('')}
`,
+ );
+ continue;
+ }
+
+ if (/^\s*(?:>|>)\s?/.test(line)) {
+ const buffer = [];
+ while (index < lines.length && /^\s*(?:>|>)\s?/.test(lines[index])) {
+ buffer.push(lines[index].replace(/^\s*(?:>|>)\s?/, ''));
+ index += 1;
+ }
+ out.push(`${buffer.map(inline).join('
')}
`);
+ continue;
+ }
+
+ if (/^\s*([-*]|\d+\.)\s+/.test(line)) {
+ const ordered = /^\s*\d+\./.test(line);
+ const buffer = [];
+ while (index < lines.length && /^\s*([-*]|\d+\.)\s+/.test(lines[index])) {
+ buffer.push(lines[index].replace(/^\s*([-*]|\d+\.)\s+/, ''));
+ index += 1;
+ }
+ const tag = ordered ? 'ol' : 'ul';
+ out.push(`<${tag}>${buffer.map((item) => `${inline(item)}`).join('')}${tag}>`);
+ continue;
+ }
+
+ const buffer = [];
+ while (
+ index < lines.length &&
+ lines[index].trim() &&
+ !/^```/.test(lines[index]) &&
+ !/^(#{1,4})\s+/.test(lines[index]) &&
+ !/^\s*([-*]|\d+\.)\s+/.test(lines[index]) &&
+ !/^\s*(?:>|>)\s?/.test(lines[index]) &&
+ !/^(\s*)(---|\*\*\*|___)\s*$/.test(lines[index]) &&
+ !/^\s*\|/.test(lines[index])
+ ) {
+ buffer.push(lines[index]);
+ index += 1;
+ }
+ out.push(`${buffer.map(inline).join('
')}
`);
+ }
+
+ return out.join('\n');
+ }
+
+ /* ---------------------------------------------------------------- state */
+
+ const S = {
+ boot: null,
+ wsId: null,
+ snap: null,
+ lessonId: null,
+ sessionId: null,
+ center: 'lesson',
+ tab: 'lesson',
+ noteId: null,
+ noteText: '',
+ noteTagDraft: '',
+ transcripts: new Map(),
+ drafts: new Map(),
+ live: new Map(),
+ tools: new Map(),
+ loads: new Map(),
+ unread: new Set(),
+ talkOpen: true,
+ railOpen: true,
+ topMenu: false,
+ fontMenu: false,
+ layout: null,
+ toolsSig: '',
+ centerSig: '',
+ railSig: '',
+ topSig: '',
+ snapKey: '',
+ sending: false,
+ talkError: '',
+ pendingQuote: '',
+ pendingAnnoId: '',
+ picker: null,
+ es: null,
+ };
+
+ /** Every derived view reads this key; nothing hand-picks snapshot fields. */
+ function setSnapshot(next) {
+ S.snap = next;
+ S.snapKey = next ? JSON.stringify(next) : '';
+ }
+
+ const lessonsOf = () =>
+ S.snap ? S.snap.curriculum.modules.flatMap((module) => module.lessons) : [];
+ const findLesson = (id) => lessonsOf().find((lesson) => lesson.id === id) || null;
+ const lessonByFile = (rel) =>
+ lessonsOf().find((lesson) => lesson.file && lesson.file === rel) || null;
+ const currentLesson = () => findLesson(S.lessonId);
+ const lessonHasFile = (lesson) =>
+ Boolean(lesson && lesson.file && S.snap && S.snap.lessonFiles.includes(lesson.file));
+ const annotationsOf = (lessonId) =>
+ S.snap ? S.snap.annotations.filter((item) => item.lessonId === lessonId) : [];
+ const currentSession = () => (S.sessionId ? S.transcripts.get(S.sessionId) : null);
+
+ /* ------------------------------------------------------- template catalogs */
+
+ const teacherPresets = () =>
+ S.boot && Array.isArray(S.boot.teacherPresets) ? S.boot.teacherPresets : [];
+ const teacherCustom = () =>
+ S.snap && S.snap.teacher && Array.isArray(S.snap.teacher.custom) ? S.snap.teacher.custom : [];
+ const teacherEntries = () => [
+ ...teacherPresets().map((item) => ({ ...item, kind: 'preset' })),
+ ...teacherCustom().map((item) => ({ ...item, kind: 'custom', summary: '自定义风格' })),
+ ];
+ const activeTeacher = () => {
+ const selected = S.snap && S.snap.teacher ? S.snap.teacher.selected : '';
+ const entries = teacherEntries();
+ return entries.find((item) => item.id === selected) || entries[0] || null;
+ };
+ const noteTemplates = () =>
+ S.boot && Array.isArray(S.boot.noteTemplates) ? S.boot.noteTemplates : [];
+ const noteTemplateName = (id) => {
+ const found = noteTemplates().find((item) => item.id === id);
+ return found ? found.name : '';
+ };
+ const teacherOptionsHtml = () => {
+ const selected = S.snap && S.snap.teacher ? S.snap.teacher.selected : '';
+ const options = (items) =>
+ items
+ .map(
+ (item) =>
+ ``,
+ )
+ .join('');
+ const presets = teacherPresets();
+ const custom = teacherCustom();
+ return `${presets.length ? `` : ''}${
+ custom.length ? `` : ''
+ }`;
+ };
+
+ function pickLesson() {
+ const all = lessonsOf();
+ if (!all.length) return null;
+ const stored = localStorage.getItem(`wb.lesson.${S.wsId}`);
+ if (stored && all.some((lesson) => lesson.id === stored)) return stored;
+ const active = all.find((lesson) => lesson.status === 'active');
+ const planned = all.find((lesson) => lesson.status === 'planned');
+ return (active || planned || all[0]).id;
+ }
+
+ function lessonNumberList(ids) {
+ const numbers = ids
+ .map((id) => findLesson(id))
+ .filter(Boolean)
+ .map((lesson) => lesson.no)
+ .sort((a, b) => a - b);
+ if (!numbers.length) return '';
+ if (numbers.length === 1) return `第 ${numbers[0]} 课`;
+ const contiguous = numbers.every((n, i) => i === 0 || n === numbers[i - 1] + 1);
+ return contiguous ? `第 ${numbers[0]}–${numbers[numbers.length - 1]} 课` : `第 ${numbers.join('、')} 课`;
+ }
+
+ /* ----------------------------------------------------------------- theme */
+
+ function applyTheme(theme) {
+ document.documentElement.dataset.theme = theme === 'dark' ? 'dark' : 'light';
+ const frame = $('#lesson-frame');
+ if (frame && frame.contentWindow) {
+ frame.contentWindow.postMessage(
+ { source: 'host', type: 'theme', theme: theme === 'dark' ? 'dark' : 'light' },
+ '*',
+ );
+ }
+ }
+
+ function initTheme() {
+ const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ applyTheme(prefersDark ? 'dark' : 'light');
+ const host = window.mcode && window.mcode.miniapp && window.mcode.miniapp.host;
+ if (host && host.ui && host.ui.subscribe) {
+ try {
+ const subscription = host.ui.subscribe(
+ (state) => applyTheme(state.theme),
+ { onError: () => undefined },
+ );
+ window.addEventListener(
+ 'pagehide',
+ () => {
+ if (subscription && subscription.dispose) subscription.dispose();
+ },
+ { once: true },
+ );
+ } catch {
+ /* keep the system theme */
+ }
+ }
+ }
+
+ /* --------------------------------------------------------------- landing */
+
+ function renderLanding() {
+ const host = $('#app');
+ const list = (S.boot && S.boot.workspaces) || [];
+ host.innerHTML = `
+
+
+
学习工作台
+
按 teach 方法管理学习目录与课纲;每节课有独立的分支会话,批注和笔记跟着课程走。
+
+
+
+ ${list.length ? `` : ''}
+
+ ${
+ list.length
+ ? `
+
最近
+ ${list
+ .map(
+ (workspace) => `
`,
+ )
+ .join('')}
+
`
+ : `
还没有工作台
选一个目录,工作台会在里面创建 MISSION.md、lessons/、reference/ 等 teach 结构。
`
+ }
+
+
`;
+ connectEvents();
+ }
+
+ /* ------------------------------------------------------------ workspace */
+
+ async function openWorkspace(id) {
+ S.wsId = id;
+ S.transcripts.clear();
+ S.drafts.clear();
+ S.live.clear();
+ S.tools.clear();
+ S.unread.clear();
+ S.sessionId = null;
+ S.noteId = null;
+ S.centerSig = '';
+ S.railSig = '';
+ try {
+ setSnapshot(await api(`/api/ws/${encodeURIComponent(id)}`));
+ } catch (error) {
+ toast(errorText(error), 'error');
+ localStorage.removeItem('wb.last');
+ S.boot = await api('/api/bootstrap').catch(() => S.boot);
+ S.wsId = null;
+ renderLanding();
+ return;
+ }
+ localStorage.setItem('wb.last', id);
+ S.lessonId = pickLesson();
+ const setupPending = S.snap.workspace.configured === false;
+ S.center = setupPending || !S.snap.curriculum.modules.length ? 'overview' : 'lesson';
+ renderShell(true);
+ connectEvents();
+ if (setupPending) {
+ S.talkOpen = true;
+ renderShell(false);
+ await openSetupSession();
+ return;
+ }
+ if (S.lessonId) {
+ await selectLesson(S.lessonId, { seed: false, silent: true });
+ } else {
+ const recent = (S.snap.sessions || []).find((session) => session.kind === 'main') || (S.snap.sessions || [])[0];
+ if (recent) await openSession(recent.id);
+ else updateTalk();
+ }
+ }
+
+ async function openSetupSession() {
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/setup/open`, {
+ method: 'POST',
+ body: {},
+ });
+ S.talkOpen = true;
+ renderShell(false);
+ if (result && result.sessionId) await openSession(result.sessionId);
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function preferredTalkOpen() {
+ return localStorage.getItem('wb.talkOpen') === '1';
+ }
+
+ function clampLayout(layout) {
+ const rail = Math.min(420, Math.max(200, Math.round(layout.rail)));
+ const overlay = window.innerWidth <= 1120;
+ const maxTalk = overlay
+ ? Math.max(300, Math.min(600, Math.round(window.innerWidth * 0.88)))
+ : Math.max(300, Math.min(600, window.innerWidth - rail - 380));
+ const talk = Math.min(maxTalk, Math.max(300, Math.round(layout.talk)));
+ return { rail, talk };
+ }
+
+ function readLayout() {
+ let saved = null;
+ try {
+ saved = JSON.parse(localStorage.getItem('wb.layout') || 'null');
+ } catch {
+ saved = null;
+ }
+ return clampLayout({
+ rail: (saved && saved.rail) || 248,
+ talk: (saved && saved.talk) || 372,
+ });
+ }
+
+ function applyLayout() {
+ const app = $('#app .app');
+ if (!app || !S.layout) return;
+ app.style.setProperty('--rail-w', S.layout.rail + 'px');
+ app.style.setProperty('--talk-w', S.layout.talk + 'px');
+ }
+
+ function setTalkOpen(open) {
+ S.talkOpen = Boolean(open);
+ localStorage.setItem('wb.talkOpen', S.talkOpen ? '1' : '0');
+ renderShell(false);
+ }
+
+ function setRailOpen(open) {
+ S.railOpen = Boolean(open);
+ S.topMenu = false;
+ localStorage.setItem('wb.railOpen', S.railOpen ? '1' : '0');
+ renderShell(false);
+ }
+
+ function setTopMenu(open) {
+ S.topMenu = Boolean(open);
+ updateTop();
+ }
+
+ function currentFontScale() {
+ const raw = Number(localStorage.getItem('wb.fontScale'));
+ return Number.isFinite(raw) && raw >= 0.85 && raw <= 1.3 ? Math.round(raw * 100) / 100 : 1;
+ }
+
+ function applyFontScale(scale = currentFontScale()) {
+ const frame = $('#lesson-frame');
+ if (!frame || !frame.contentWindow) return;
+ try {
+ // The lesson frame is a sandboxed opaque origin: zoom goes over postMessage.
+ frame.contentWindow.postMessage({ source: 'host', type: 'font', scale }, '*');
+ } catch {
+ /* The frame may be navigating; the load handler sends it again. */
+ }
+ }
+
+ /** The lesson frame is a sandboxed opaque origin, so it gets markup, not a URL. */
+ let frameToken = 0;
+ async function loadLessonFrame(url) {
+ const token = ++frameToken;
+ try {
+ const response = await fetch(url, { cache: 'no-store' });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const html = await response.text();
+ if (token !== frameToken) return;
+ const frame = $('#lesson-frame');
+ if (frame) frame.srcdoc = html;
+ } catch (error) {
+ if (token !== frameToken) return;
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function loadSrcdoc(frame, url) {
+ if (!frame) return;
+ try {
+ const response = await fetch(url, { cache: 'no-store' });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ frame.srcdoc = await response.text();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function fontMenuHtml() {
+ const scale = currentFontScale();
+ return ``;
+ }
+
+ function renderFontMenu() {
+ const root = $('#font-menu');
+ const button = $('#font-toggle');
+ if (button) button.setAttribute('aria-expanded', String(S.fontMenu));
+ if (root) root.innerHTML = S.fontMenu ? fontMenuHtml() : '';
+ }
+
+ function setFontScale(next) {
+ const scale = Math.min(1.3, Math.max(0.85, Math.round(next * 100) / 100));
+ localStorage.setItem('wb.fontScale', String(scale));
+ applyFontScale(scale);
+ renderFontMenu();
+ }
+
+ function stepFontScale(delta) {
+ setFontScale(currentFontScale() + delta);
+ }
+
+ function sendModeInterrupted(session) {
+ return Boolean(
+ session &&
+ session.interrupted &&
+ !session.running &&
+ !session.pending &&
+ !(session.permissions || []).length,
+ );
+ }
+
+ function applySendMode(continueMode) {
+ const send = $('#talk-send');
+ if (!send) return;
+ send.classList.toggle('continue', continueMode);
+ if (continueMode) {
+ send.innerHTML = `${icon('play')}继续`;
+ send.title = '继续上次暂停的任务';
+ send.setAttribute('aria-label', '继续上次暂停的任务');
+ } else {
+ send.innerHTML = icon('send');
+ send.title = '发送(Enter)';
+ send.setAttribute('aria-label', '发送');
+ }
+ }
+
+ function syncSendMode() {
+ const session = currentSession();
+ const input = $('#talk-input');
+ if (!session || !input || input.disabled || S.sending) return;
+ if (session.running || session.pending || (session.permissions || []).length) return;
+ applySendMode(sendModeInterrupted(session) && !input.value.trim());
+ }
+
+ function bindResizers() {
+ $$('.resizer').forEach((handle) => {
+ handle.addEventListener('pointerdown', (event) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ const kind = handle.dataset.resize;
+ const startX = event.clientX;
+ const start = { ...S.layout };
+ document.body.classList.add('resizing');
+ const move = (moveEvent) => {
+ const delta = moveEvent.clientX - startX;
+ S.layout = clampLayout({
+ rail: kind === 'rail' ? start.rail + delta : start.rail,
+ talk: kind === 'talk' ? start.talk - delta : start.talk,
+ });
+ applyLayout();
+ };
+ const stop = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', stop);
+ document.body.classList.remove('resizing');
+ localStorage.setItem('wb.layout', JSON.stringify(S.layout));
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', stop, { once: true });
+ });
+ handle.addEventListener('keydown', (event) => {
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
+ const kind = handle.dataset.resize;
+ const step = event.shiftKey ? 48 : 16;
+ const delta = event.key === 'ArrowLeft' ? -step : step;
+ event.preventDefault();
+ S.layout = clampLayout({
+ ...S.layout,
+ [kind]: S.layout[kind] + (kind === 'talk' ? -delta : delta),
+ });
+ applyLayout();
+ localStorage.setItem('wb.layout', JSON.stringify(S.layout));
+ });
+ });
+ }
+
+ function shellHtml() {
+ return `
+ `;
+ }
+
+ function renderShell(force) {
+ const host = $('#app');
+ const existing = $('#app .app');
+ if (!force && existing && existing.dataset.ws === S.wsId) {
+ existing.classList.toggle('no-talk', !S.talkOpen);
+ existing.classList.toggle('rail-collapsed', !S.railOpen);
+ updateTop();
+ updateRail();
+ updateCenter();
+ updateTalk();
+ return;
+ }
+ host.innerHTML = shellHtml();
+ bindComposer();
+ applyLayout();
+ bindResizers();
+ updateTop();
+ updateRail();
+ updateCenter();
+ updateTalk();
+ }
+
+ function bindComposer() {
+ const form = $('#talk-form');
+ const input = $('#talk-input');
+ if (!form || !input) return;
+ form.addEventListener('submit', (event) => {
+ event.preventDefault();
+ void sendCurrent();
+ });
+ input.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
+ event.preventDefault();
+ void sendCurrent();
+ }
+ });
+ input.addEventListener('input', () => {
+ if (S.sessionId) S.drafts.set(S.sessionId, input.value);
+ autoSize(input);
+ syncSendMode();
+ });
+ }
+
+ function autoSize(input) {
+ input.style.height = 'auto';
+ input.style.height = `${Math.min(120, input.scrollHeight)}px`;
+ }
+
+ /* ------------------------------------------------------------------- top */
+
+ function updateTop() {
+ const node = $('#top');
+ if (!node || !S.snap) return;
+ const summary = S.snap.summary;
+ const workspaces = (S.boot && S.boot.workspaces) || [];
+ const sig = [
+ S.wsId,
+ S.snapKey,
+ S.talkOpen ? 'talk' : '',
+ S.railOpen ? 'rail' : '',
+ S.topMenu ? 'menu' : '',
+ S.center,
+ workspaces.map((workspace) => workspace.id + ':' + workspace.name).join(','),
+ ].join('|');
+ if (sig === S.topSig) return;
+ S.topSig = sig;
+ const workspaceOptions = workspaces
+ .map(
+ (workspace) =>
+ ``,
+ )
+ .join('');
+ const menu = S.topMenu
+ ? ``
+ : '';
+ node.innerHTML = `
+
+ 学
+
+
${esc(S.snap.workspace.name)}
+
${esc(S.snap.workspace.root)}
+
+
+ 已学 ${summary.done}/${summary.total} 课
+
+
+ `;
+ const select = $('#ws-switch');
+ if (select) {
+ select.addEventListener('change', () => {
+ S.topMenu = false;
+ S.talkOpen = preferredTalkOpen();
+ void openWorkspace(select.value);
+ });
+ }
+ }
+
+ /* ------------------------------------------------------------------ rail */
+
+ function updateRail() {
+ const node = $('#rail');
+ if (!node || !S.snap) return;
+ const lessons = lessonsOf();
+ const sig = JSON.stringify([S.snapKey, S.lessonId, Array.from(S.unread).sort()]);
+ if (sig === S.railSig) return;
+ S.railSig = sig;
+ const total = lessons.length || 0;
+ const done = S.snap.summary.done;
+ node.innerHTML = `
+
+
+ ${
+ total
+ ? S.snap.curriculum.modules
+ .map(
+ (module) => `
+
${esc(module.title)}${module.lessons.length} 课
+ ${module.lessons
+ .map((lesson) => {
+ const count = annotationsOf(lesson.id).length;
+ return `
`;
+ })
+ .join('')}`,
+ )
+ .join('')
+ : `
还没有课纲。先在概览里让主会话写一份。
`
+ }
+
`;
+ }
+
+ /* ---------------------------------------------------------------- center */
+
+ function centerSignature() {
+ return JSON.stringify([S.snapKey, S.center, S.lessonId, S.tab, S.noteId]);
+ }
+
+ function updateCenter() {
+ const head = $('#center-head');
+ const body = $('#center-body');
+ if (!head || !body || !S.snap) return;
+ const sig = centerSignature();
+ if (sig === S.centerSig) return;
+ S.centerSig = sig;
+ body.classList.toggle('flush', S.center === 'lesson' && lessonHasFile(currentLesson()));
+
+ if (S.center === 'overview') {
+ head.innerHTML = `
+ 使命、课纲与资源都在这个目录里,随时可以改。
`;
+ body.innerHTML = overviewHtml();
+ const teacherPick = $('#teacher-select', body);
+ if (teacherPick) {
+ teacherPick.addEventListener('change', () => void selectTeacher(teacherPick.value));
+ }
+ return;
+ }
+
+ if (S.center === 'notes' || S.center === 'note') {
+ head.innerHTML = `
+ 按你选的课程范围,结合课程内容与批注,交给她在独立会话里完成。
`;
+ body.innerHTML = S.center === 'note' ? noteHtml() : notesHtml();
+ if (S.center === 'note') bindNoteTags(body);
+ return;
+ }
+
+ const lesson = currentLesson();
+ if (!lesson) {
+ head.innerHTML = `课程
`;
+ body.innerHTML = `${icon('book')}
还没有课程
先在概览里生成课纲。
+
`;
+ return;
+ }
+
+ const annoCount = annotationsOf(lesson.id).length;
+ head.innerHTML = `
+
+
第 ${String(lesson.no).padStart(2, '0')} 课
+
${
+ lesson.status === 'done' ? '已完成' : lesson.status === 'active' ? '进行中' : '未开始'
+ }
+
约 ${lesson.minutes} 分钟
+
+
+
+
+
+ ${
+ lessonHasFile(lesson)
+ ? `
`
+ : ''
+ }
+
+
+ ${esc(lesson.objective || lesson.title)}
+
+
+
+
`;
+
+ if (S.tab === 'anno') {
+ body.classList.remove('flush');
+ body.innerHTML = annotationPaneHtml(lesson);
+ return;
+ }
+
+ if (!lessonHasFile(lesson)) {
+ body.classList.remove('flush');
+ body.innerHTML = `${icon('spark')}
这一课还没有生成
+
打开这一课不会自动开写。点下面的按钮,课程分支会话才会读使命、课纲和前几课的学习记录,再写这节课的 HTML。
+
+
+
+
`;
+ return;
+ }
+
+ body.innerHTML = ``;
+ const frame = $('#lesson-frame');
+ if (frame) frame.addEventListener('load', () => applyFontScale());
+ void loadLessonFrame(
+ `/w/${encodeURIComponent(S.wsId)}/${lesson.file
+ .split('/')
+ .map(encodeURIComponent)
+ .join('/')}?v=${S.snap.curriculum.updatedAt}`,
+ );
+ }
+
+ function overviewHtml() {
+ const summary = S.snap.summary;
+ const issues = S.snap.curriculum.issues || [];
+ const hasLessons = summary.total > 0;
+ const setupPending = S.snap.workspace.configured === false;
+ const titleMissing = !setupPending && !S.snap.missionTitle;
+ const teacher = activeTeacher();
+ return `
+
+
已掌握
${summary.done} / ${summary.total} 课
+
+
+
+
+
+
前置配置
+
${setupPending ? '进行中' : '已就绪'}
+
+ ${
+ setupPending
+ ? `
`
+ : `
`
+ }
+
+ ${
+ setupPending
+ ? `
配置会话会在右侧问你几个问题,然后把使命、来源与规则写进这个目录。这一步只搭前置环境,不产出课程和课纲。
`
+ : `
${esc((S.snap.missionExcerpt || '').slice(0, 600) || '使命已写入 MISSION.md。')}
`
+ }
+ ${
+ titleMissing
+ ? `
+ MISSION.md 的第一行不是「# Mission: 主题」,工作台名字仍按目录名显示。改成这个格式后点「重新读取」,就会按标题命名。
+
+
`
+ : ''
+ }
+
+
+
+
老师风格
+ ${
+ teacher
+ ? `
${teacher.kind === 'custom' ? '自定义' : '预设'}`
+ : ''
+ }
+
+
+
+ ${
+ teacher
+ ? `
+
+ ${
+ teacher.kind === 'custom'
+ ? ''
+ : ''
+ }
+
+
${esc(teacher.summary || '')}
+
查看生效提示词
${esc(teacher.prompt || '')}
+
影响新会话与下一轮的讲解、排版和对话语气;已生成的课件要重新生成才会换风格。
`
+ : '
风格模板尚未加载,刷新后重试。
'
+ }
+
+
+
+
课纲
+
${hasLessons ? `${summary.total} 课` : '未生成'}
+
+
+
+ ${
+ hasLessons
+ ? `
${esc(
+ S.snap.curriculum.modules
+ .map(
+ (module) =>
+ `${module.title}:${module.lessons
+ .map((lesson) => `${String(lesson.no).padStart(2, '0')} ${lesson.title}`)
+ .join(' · ')}`,
+ )
+ .join('\n'),
+ )}
`
+ : setupPending
+ ? `
前置配置完成后,主会话才能按使命写课纲。
`
+ : `
主会话会按使命写 3–6 个模块,每节课 15–25 分钟。生成过程在右侧会话里可见。
`
+ }
+ ${issues.length ? `
${esc(issues.join(';'))}
` : ''}
+ ${
+ S.snap.curriculumError
+ ? `
+ 课纲文件无法解析(${esc(S.snap.curriculumError)})。让主会话修复格式,或点「重新读取」。
+
+
`
+ : ''
+ }
+
+
+
+
+ ${
+ S.snap.records.length
+ ? S.snap.records
+ .map(
+ (record) =>
+ `
${icon('check')}
${esc(record.title)}
${esc(record.rel)}
`,
+ )
+ .join('')
+ : `
还没有学习记录。老师说清一个概念、你做出一次正确判断之后,才会写一条。
`
+ }
+
+
+
+
目录与规则
+ ${(S.snap.referenceFiles || []).includes('reference/视觉组件速查.html') ? `
` : ''}
+
+
+
${esc(S.snap.workspace.root)}
+
规则文件:.workbench/rules/teach.md · 课纲:.workbench/curriculum.json · 课件:lessons/
+
+
`;
+ }
+
+ function annotationPaneHtml(lesson) {
+ const items = annotationsOf(lesson.id);
+ return `
+
+
本课批注
+
+
+
+ ${
+ items.length
+ ? items
+ .map(
+ (item) => `
+ ${item.quote ? `
${esc(item.quote)}
` : ''}
+
${esc(item.note)}
+
+
`,
+ )
+ .join('')
+ : `
在左侧课程里选中一句话,点浮动按钮就能批注;也可以点上面的「整节批注」。
`
+ }
+
`;
+ }
+
+ function noteTagsHtml(note, limit) {
+ const tags = Array.isArray(note.tags) ? note.tags : [];
+ if (!tags.length) return '';
+ const shown = limit ? tags.slice(0, limit) : tags;
+ const rest = tags.length - shown.length;
+ return `${shown
+ .map((tag) => `${esc(tag)}`)
+ .join('')}${rest > 0 ? `+${rest}` : ''}
`;
+ }
+
+ function noteStatusChip(note) {
+ return note.status === 'ready'
+ ? '已生成'
+ : note.status === 'running'
+ ? '生成中'
+ : '未完成';
+ }
+
+ function notesHtml() {
+ const items = S.snap.notes;
+ if (!items.length) {
+ return `${icon('note')}
还没有笔记
+
选几节课,她会在独立会话里把课程内容和你写在课上的批注一起提炼成 Markdown。
+
`;
+ }
+ return `
+ ${items
+ .map((note) => {
+ const scope = lessonNumberList(note.lessonIds);
+ const template = noteTemplateName(note.templateId);
+ const busy = note.status === 'running';
+ return `
+
+ ${noteStatusChip(note)}
+
+
+
+
+
+
`;
+ })
+ .join('')}
+
笔记写入 notes/*.md,可以继续编辑;重新生成会覆盖同一份文件,标签由这次生成重写。
+
`;
+ }
+
+ function noteHtml() {
+ const note = S.snap.notes.find((item) => item.id === S.noteId);
+ if (!note) {
+ return `${icon('note')}
笔记不存在
`;
+ }
+ const tags = Array.isArray(note.tags) ? note.tags : [];
+ const busy = note.status === 'running';
+ return `
+
+
+ ${
+ noteTemplateName(note.templateId)
+ ? `
${esc(noteTemplateName(note.templateId))}`
+ : ''
+ }
+ ${noteStatusChip(note)}
+
+
${esc(note.path)}
+
+
+
+
+
+ ${tags
+ .map(
+ (tag) =>
+ `${esc(tag)}`,
+ )
+ .join('')}
+
+
+
${md(S.noteText)}
+
`;
+ }
+
+ /* ------------------------------------------------------------------ talk */
+
+ const modelCatalog = () =>
+ S.boot && S.boot.models && Array.isArray(S.boot.models.models) ? S.boot.models.models : [];
+ const modelLabel = (item) =>
+ String((item && (item.displayName || item.modelId)) || '').split(' · ')[0];
+ const EFFORT_LABELS = {
+ default: '默认',
+ low: '低',
+ medium: '中',
+ high: '高',
+ xhigh: '极高',
+ max: '最高',
+ };
+ const fmtChars = (value) => (value >= 10000 ? (value / 1000).toFixed(1) + 'k' : String(value));
+ const countTurns = (session) =>
+ session && Array.isArray(session.messages)
+ ? session.messages.filter((message) => message.role === 'assistant').length
+ : 0;
+ const countChars = (session) =>
+ session && Array.isArray(session.messages)
+ ? session.messages.reduce((sum, message) => sum + String(message.text ?? '').length, 0)
+ : 0;
+
+ function selectionFor(item, level) {
+ if (!item) return null;
+ const selection = { providerId: item.providerId, modelId: item.modelId };
+ const current = currentSession() && currentSession().model;
+ const same = current && current.providerId === item.providerId && current.modelId === item.modelId;
+ const thinkingOnly =
+ (item.variants || []).includes('thinking') ||
+ Boolean(item.thinking && Array.isArray(item.thinking.efforts));
+ const variant = (same && current.variant) || (thinkingOnly ? 'thinking' : '');
+ if (variant) selection.variant = variant;
+ const efforts = item.thinking && Array.isArray(item.thinking.efforts) ? item.thinking.efforts : [];
+ const chosen = efforts.includes(level) ? level : item.thinking && item.thinking.default;
+ if (chosen && efforts.includes(chosen)) selection.thinking = { effort: chosen };
+ return selection;
+ }
+
+ async function switchModel(selection) {
+ if (!S.sessionId) return;
+ const url =
+ '/api/ws/' +
+ encodeURIComponent(S.wsId) +
+ '/sessions/' +
+ encodeURIComponent(S.sessionId) +
+ '/model';
+ try {
+ const result = await api(url, { method: 'POST', body: { model: selection } });
+ const known = S.transcripts.get(S.sessionId);
+ if (known && result && result.session) {
+ known.model = result.session.model;
+ known.turns = result.session.turns;
+ known.chars = result.session.chars;
+ }
+ updateTalk();
+ const option = modelCatalog().find(
+ (item) =>
+ item.providerId === selection.providerId && item.modelId === selection.modelId,
+ );
+ toast('已切到 ' + ((option && option.displayName) || selection.modelId) + ',下一轮生效');
+ } catch (error) {
+ S.toolsSig = '';
+ toast(errorText(error), 'error');
+ updateTalk();
+ }
+ }
+
+ function updateTalk() {
+ const head = $('#talk-head');
+ const body = $('#talk-body');
+ const input = $('#talk-input');
+ const form = $('#talk-form');
+ if (!head || !body || !input) return;
+
+ if (!S.sessionId) {
+ head.innerHTML = ``;
+ body.innerHTML = `${icon('chat')}
还没有会话
点左侧任意一节课开始阅读;需要备课时,在课程页点「开始这一课」。
`;
+ input.disabled = true;
+ input.placeholder = '先选一节课';
+ const tools = $('#talk-tools');
+ if (tools) tools.innerHTML = '';
+ S.toolsSig = '';
+ const send = $('#talk-send');
+ send.disabled = true;
+ send.title = '先选一节课';
+ return;
+ }
+
+ const session = S.transcripts.get(S.sessionId);
+ const lesson = currentLesson();
+ const isMain = session && session.kind === 'main';
+ const isNote = session && session.kind === 'note';
+ const isSetup = session && session.kind === 'setup';
+ const title = session ? session.title : '会话';
+ const running = session && (session.running || S.live.get(S.sessionId));
+ const catalog = modelCatalog();
+ const currentModel = (session && session.model) || (S.boot.models && S.boot.models.default) || null;
+ const currentItem = currentModel
+ ? catalog.find(
+ (entry) =>
+ entry.providerId === currentModel.providerId && entry.modelId === currentModel.modelId,
+ ) || null
+ : null;
+ const efforts =
+ currentItem && currentItem.thinking && Array.isArray(currentItem.thinking.efforts)
+ ? currentItem.thinking.efforts
+ : [];
+ const savedEffort = currentModel && currentModel.thinking && currentModel.thinking.effort;
+ const effort = efforts.includes(savedEffort)
+ ? savedEffort
+ : (currentItem && currentItem.thinking && currentItem.thinking.default) || efforts[0] || '';
+ const modelOptions =
+ catalog.length && currentModel
+ ? catalog
+ .map((item) => {
+ const value = item.providerId + '|' + item.modelId;
+ const selected =
+ currentModel.providerId === item.providerId && currentModel.modelId === item.modelId;
+ return '';
+ })
+ .join('')
+ : '';
+ const effortOptions = efforts
+ .map(
+ (level) =>
+ '',
+ )
+ .join('');
+ const turns = session && typeof session.turns === 'number' ? session.turns : countTurns(session);
+ const chars = session && typeof session.chars === 'number' ? session.chars : countChars(session);
+ head.innerHTML = `
+
+
${esc(title)}
+
${
+ isSetup
+ ? '前置配置 · 只搭环境,不产出课程与课纲'
+ : isMain
+ ? '使命、课纲与全局配置'
+ : isNote
+ ? '独立提炼会话 · 只读课程与批注'
+ : '分支会话 · 只改这一课'
+ }${running ? ' · 正在生成' : ''}${turns ? ' · ' + turns + ' 轮' : ''}
+
`;
+ const tools = $('#talk-tools');
+ const toolsSig = [
+ session.id,
+ currentModel ? currentModel.providerId + '|' + currentModel.modelId : '',
+ effort,
+ running ? '1' : '0',
+ isSetup ? 's' : isMain ? 'm' : isNote ? 'n' : 'l',
+ ].join('~');
+ if (tools && toolsSig !== S.toolsSig) {
+ S.toolsSig = toolsSig;
+ tools.innerHTML =
+ (!isSetup && !isMain && !isNote
+ ? ''
+ : '') +
+ (modelOptions
+ ? ''
+ : '') +
+ (effortOptions
+ ? ''
+ : '');
+ const modelPick = tools.querySelector('#model-pick');
+ if (modelPick) {
+ modelPick.addEventListener('change', () => {
+ const parts = modelPick.value.split('|');
+ const nextItem = catalog.find(
+ (entry) => entry.providerId === parts[0] && entry.modelId === parts[1],
+ );
+ const selection = selectionFor(nextItem, effort);
+ if (selection) void switchModel(selection);
+ });
+ }
+ const effortPick = tools.querySelector('#effort-pick');
+ if (effortPick) {
+ effortPick.addEventListener('change', () => {
+ const selection = selectionFor(currentItem, effortPick.value);
+ if (selection) void switchModel(selection);
+ });
+ }
+ }
+
+ const draft = S.drafts.get(S.sessionId);
+ if (document.activeElement !== input) {
+ input.value = draft || '';
+ autoSize(input);
+ }
+ const hasPending = Boolean(
+ session && (session.pending || (session.permissions || []).length),
+ );
+ const notStarted = Boolean(session && !(session.messages || []).length && !session.running);
+ const interrupted = sendModeInterrupted(session);
+ input.disabled = !session || notStarted;
+ input.placeholder = notStarted
+ ? '先让老师开始'
+ : hasPending
+ ? '先回答上面的问题…'
+ : interrupted
+ ? '这一轮已暂停,点「继续」接着做,或输入新的要求…'
+ : isSetup
+ ? '和老师讨论你想从这个目录学到什么…'
+ : isMain
+ ? '和主会话讨论使命、课纲或全局设置…'
+ : isNote
+ ? '补充提炼要求,或追问这份笔记…'
+ : lesson
+ ? `追问第 ${lesson.no} 课…`
+ : '追问…';
+ const send = $('#talk-send');
+ send.disabled = !session || notStarted || S.sending || Boolean(session.running) || hasPending;
+ send.title = S.sending
+ ? '正在发送…'
+ : notStarted
+ ? '这一课还没有开始'
+ : session.running
+ ? '正在生成 · 可随时停止'
+ : hasPending
+ ? '先回答上面的问题'
+ : '发送(Enter)';
+ send.setAttribute('aria-label', send.title);
+ const idle = Boolean(session && !session.running && !notStarted && !hasPending && !S.sending);
+ if (idle) {
+ applySendMode(interrupted && !input.value.trim());
+ } else {
+ send.classList.remove('continue');
+ send.innerHTML = icon('send');
+ send.setAttribute('aria-label', send.title);
+ }
+ $('#talk-stop').classList.toggle('hidden', !running);
+
+ if (!session) {
+ body.innerHTML = `${icon('chat')}
正在建立会话
稍等一下。
`;
+ return;
+ }
+
+ const stick = body.scrollHeight - body.scrollTop - body.clientHeight < 90;
+ const hadPending = Boolean(body.querySelector('.card-interact'));
+ renderTalkBody(body, session);
+ if (hadPending !== Boolean(body.querySelector('.card-interact')) && body.querySelector('.card-interact')) {
+ const card = body.querySelector('.card-interact');
+ if (card) {
+ const top = card.getBoundingClientRect().top - body.getBoundingClientRect().top + body.scrollTop;
+ body.scrollTop = Math.max(0, top - 10);
+ return;
+ }
+ }
+ if (stick) body.scrollTop = body.scrollHeight;
+ }
+
+ function renderTalkBody(body, session) {
+ const sid = session.id;
+ const parts = [];
+ const messages = session.messages || [];
+
+ if (!messages.length && !S.live.get(sid)) {
+ parts.push(emptyTalkHtml(session));
+ }
+
+ for (const message of messages) {
+ parts.push(messageHtml(message, session.kind));
+ }
+
+ const live = S.live.get(sid);
+ if (live) {
+ parts.push(`
+
${icon('spark')}老师
+
${md(live)}
+
`);
+ } else if (session.running) {
+ parts.push(`
+
${icon('spark')}老师
+
思考中
+
`);
+ }
+
+ const tools = (S.tools.get(sid) || []).slice(-3);
+ if (tools.length) {
+ parts.push(``);
+ }
+
+ for (const permission of session.permissions || []) {
+ parts.push(permissionHtml(permission));
+ }
+ if (session.pending) parts.push(pendingHtml(session.pending));
+
+ body.innerHTML = parts.join('');
+ }
+
+ function emptyTalkHtml(session) {
+ if (session.kind === 'setup') {
+ return `${icon('spark')}
还没开始配置
+
老师会看你选的目录,问你三个问题,然后把使命、来源和规则写好。这一轮不产出课程。
+
`;
+ }
+ if (session.kind === 'main') {
+ return `${icon('spark')}
主会话还没开始
+
她会先问你为什么学,再把使命写进 MISSION.md,然后才生成课纲。
+
`;
+ }
+ if (session.kind === 'note') {
+ return `${icon('note')}
准备提炼
+
她正在读课程与批注。完成后笔记会出现在「笔记」里。
`;
+ }
+ return `${icon('spark')}
这一课还没开始
+
点下面的按钮,她会先读使命、课纲和资源清单,再开始备课。
+
`;
+ }
+
+ function messageHtml(message, sessionKind) {
+ if (message.kind === 'seed' || message.kind === 'task' || message.kind === 'rewrite' || message.kind === 'continue') {
+ const label =
+ message.kind === 'task'
+ ? '已交给主会话:生成课纲'
+ : message.kind === 'rewrite'
+ ? '已让老师整节重写这一课'
+ : message.kind === 'continue'
+ ? '继续上次暂停的任务'
+ : sessionKind === 'setup'
+ ? '已把目录与规则交给配置会话'
+ : sessionKind === 'note'
+ ? '已把课程与批注交给提炼会话'
+ : sessionKind === 'main'
+ ? '已把工作台的规则与现状交给主会话'
+ : '已把这一课的上下文交给老师';
+ return `
+
+ ${label}›
+ ${esc(message.text)}
+
+
`;
+ }
+ const at = message.at
+ ? `${clockLabel(message.at)}`
+ : '';
+ if (message.role === 'system') {
+ return ``;
+ }
+ if (message.role === 'user') {
+ return `你${at}
${esc(message.text)}
`;
+ }
+ const clean = String(message.text || '')
+ .replace(/[\s\S]*?<\/deliver-assets>/gi, '')
+ .trim();
+ return `${icon('spark')}老师${at}
${md(
+ clean,
+ )}
`;
+ }
+
+ function permissionHtml(pending) {
+ return `
+
需要授权:${esc(pending.toolName)}
+
${esc(pending.reason || '这次工具调用超出自动授权范围。')}
+
+
+
+
+
`;
+ }
+
+ function pendingHtml(pending) {
+ const request = pending.request || { steps: [] };
+ const plan =
+ request.mode === 'plan' && request.modePayload
+ ? request.modePayload.markdown || request.modePayload.text || ''
+ : '';
+ return `
+
${esc(request.title || '需要你的回答')}
+ ${plan ? `
${esc(plan)}
` : ''}
+ ${(request.steps || [])
+ .map(
+ (step) => `
+
${esc(step.question)}
+
+ ${(step.options || [])
+ .map(
+ (option) => ``,
+ )
+ .join('')}
+
+
+
`,
+ )
+ .join('')}
+
+
+
+
+
`;
+ }
+
+ /* ------------------------------------------------------------- workspace */
+
+ async function selectLesson(lessonId, options) {
+ const opts = options || {};
+ S.lessonId = lessonId;
+ S.center = 'lesson';
+ S.tab = 'lesson';
+ S.centerSig = '';
+ S.fontMenu = false;
+ S.talkError = '';
+ localStorage.setItem(`wb.lesson.${S.wsId}`, lessonId);
+ updateCenter();
+ updateRail();
+ if (opts.silent && !S.talkOpen) return;
+ try {
+ const result = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/lessons/${encodeURIComponent(lessonId)}/open`,
+ { method: 'POST', body: { seed: Boolean(opts.seed) } },
+ );
+ if (result && result.sessionId) {
+ await openSession(result.sessionId);
+ } else {
+ updateTalk();
+ }
+ } catch (error) {
+ if (opts.seed && (error.code === 'ANSWER_PENDING' || error.code === 'BUSY')) {
+ // The lesson's session is waiting for an answer or still running: open it
+ // as it stands instead of starting a turn over it.
+ return selectLesson(lessonId, { seed: false });
+ }
+ S.talkError = errorText(error);
+ toast(errorText(error), 'error');
+ updateTalk();
+ }
+ }
+
+ async function openSession(sessionId) {
+ S.sessionId = sessionId;
+ S.unread.delete(sessionId);
+ await loadTranscript(sessionId);
+ updateTalk();
+ updateRail();
+ }
+
+ async function renewLesson() {
+ const lesson = currentLesson();
+ closeModal();
+ if (!lesson) return;
+ try {
+ const result = await api(
+ '/api/ws/' + encodeURIComponent(S.wsId) + '/lessons/' + encodeURIComponent(lesson.id) + '/renew',
+ { method: 'POST', body: {} },
+ );
+ S.boot = await api('/api/bootstrap');
+ S.centerSig = '';
+ await refreshSnapshot();
+ if (result && result.sessionId) {
+ setTalkOpen(true);
+ await openSession(result.sessionId);
+ }
+ toast('已新开追问,这一课的上下文重新带上');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function regenerateLesson() {
+ const lesson = currentLesson();
+ closeModal();
+ if (!lesson) return;
+ try {
+ const result = await api(
+ '/api/ws/' + encodeURIComponent(S.wsId) + '/lessons/' + encodeURIComponent(lesson.id) + '/regenerate',
+ { method: 'POST', body: {} },
+ );
+ S.centerSig = '';
+ setTalkOpen(true);
+ if (result && result.sessionId) await openSession(result.sessionId);
+ await refreshSnapshot();
+ toast('正在整节重写这一课');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function loadTranscript(sessionId) {
+ const token = (S.loads.get(sessionId) || 0) + 1;
+ S.loads.set(sessionId, token);
+ try {
+ const data = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(sessionId)}`,
+ );
+ if (S.loads.get(sessionId) !== token) return;
+ S.transcripts.set(sessionId, data);
+ if (!data.running) S.live.delete(sessionId);
+ } catch (error) {
+ if (S.loads.get(sessionId) !== token) return;
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function sendCurrent() {
+ const input = $('#talk-input');
+ if (!input || !S.sessionId || S.sending) return;
+ const text = input.value.trim();
+ const session = currentSession();
+ if (!text && sendModeInterrupted(session)) {
+ void continueTurn();
+ return;
+ }
+ if (!text) return;
+ const sid = S.sessionId;
+ S.sending = true;
+ const transcript = S.transcripts.get(sid);
+ if (transcript) {
+ transcript.messages = transcript.messages.concat({
+ id: `tmp_${Date.now()}`,
+ role: 'user',
+ text,
+ at: Date.now(),
+ });
+ }
+ S.drafts.delete(sid);
+ input.value = '';
+ autoSize(input);
+ S.live.delete(sid);
+ updateTalk();
+ $('#talk-send').disabled = true;
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(sid)}/send`, {
+ method: 'POST',
+ body: { text },
+ });
+ if (transcript) transcript.running = true;
+ } catch (error) {
+ toast(errorText(error), 'error');
+ S.drafts.set(sid, text);
+ input.value = text;
+ autoSize(input);
+ } finally {
+ S.sending = false;
+ updateTalk();
+ }
+ }
+
+ async function submitAnswers(skip) {
+ const session = currentSession();
+ if (!session || !session.pending || session.pending.kind !== 'question') return;
+ const pending = session.pending;
+ const body = $('#talk-body');
+ const steps = (pending.request && pending.request.steps) || [];
+ const answers = steps.map((step) => {
+ const inputs = $$(`[data-step="${cssEscape(step.id)}"]`, body).filter((node) => node.checked);
+ const other = $(`[data-other="${cssEscape(step.id)}"]`, body);
+ const otherText = other && other.value.trim();
+ return {
+ stepId: step.id,
+ selectedOptionIds: skip ? [] : inputs.map((node) => node.value),
+ selectedOther: Boolean(otherText),
+ otherText: otherText || undefined,
+ skipped: Boolean(skip),
+ };
+ });
+ try {
+ await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(session.id)}/answer`,
+ { method: 'POST', body: { requestId: pending.requestId, answers } },
+ );
+ session.pending = null;
+ updateTalk();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function cssEscape(value) {
+ return String(value).replace(/["\\]/g, '\\$&');
+ }
+
+ async function replyPermission(requestId, decision) {
+ const session = currentSession();
+ if (!session) return;
+ try {
+ await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(session.id)}/reply`,
+ { method: 'POST', body: { requestId, decision } },
+ );
+ session.permissions = (session.permissions || []).filter((item) => item.requestId !== requestId);
+ updateTalk();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function cancelTurn() {
+ const session = currentSession();
+ if (!session) return;
+ try {
+ await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(session.id)}/cancel`,
+ { method: 'POST', body: {} },
+ );
+ toast('已请求暂停这一轮,稍后可点「继续」');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function continueTurn() {
+ if (!S.sessionId || S.sending) return;
+ const sid = S.sessionId;
+ S.sending = true;
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(sid)}/continue`, {
+ method: 'POST',
+ body: {},
+ });
+ const known = S.transcripts.get(sid);
+ if (known) {
+ known.interrupted = false;
+ known.running = true;
+ }
+ S.live.delete(sid);
+ updateTalk();
+ toast('已继续上次暂停的任务');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ } finally {
+ S.sending = false;
+ updateTalk();
+ }
+ }
+
+ async function openMain(options) {
+ void options;
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/main/open`, {
+ method: 'POST',
+ body: {},
+ });
+ if (result && result.sessionId) {
+ setTalkOpen(true);
+ await openSession(result.sessionId);
+ toast('已打开主会话(右侧栏)');
+ }
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function generateCurriculum() {
+ if (S.snap.workspace.configured === false) {
+ toast('先完成前置配置,再生成课纲');
+ await openSetupSession();
+ return;
+ }
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/curriculum`, {
+ method: 'POST',
+ body: {},
+ });
+ setTalkOpen(true);
+ if (result && result.sessionId) await openSession(result.sessionId);
+ toast('主会话正在写课纲,完成后课纲会自动出现');
+ } catch (error) {
+ if (error && error.code === 'SETUP_REQUIRED') {
+ toast('先完成前置配置,再生成课纲');
+ await openSetupSession();
+ return;
+ }
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function refreshSnapshot() {
+ if (!S.wsId) return;
+ try {
+ setSnapshot(await api(`/api/ws/${encodeURIComponent(S.wsId)}`));
+ } catch {
+ return;
+ }
+ const bootEntry = ((S.boot && S.boot.workspaces) || []).find((workspace) => workspace.id === S.wsId);
+ if (bootEntry && bootEntry.name !== S.snap.workspace.name) bootEntry.name = S.snap.workspace.name;
+ if (S.lessonId && !findLesson(S.lessonId)) S.lessonId = pickLesson();
+ if ((S.center === 'note' || S.center === 'notes') && !S.snap.notes.length) S.center = 'overview';
+ if (S.center === 'note' && S.noteId && !S.snap.notes.some((note) => note.id === S.noteId)) {
+ S.center = 'notes';
+ }
+ S.centerSig = '';
+ updateTop();
+ updateRail();
+ updateCenter();
+ updateTalk();
+ }
+
+ async function reloadTeacherView() {
+ setSnapshot(await api(`/api/ws/${encodeURIComponent(S.wsId)}`));
+ S.centerSig = '';
+ updateCenter();
+ updateTop();
+ updateRail();
+ }
+
+ async function selectTeacher(id) {
+ if (!id) return;
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/teacher`, {
+ method: 'POST',
+ body: { action: 'select', id },
+ });
+ await reloadTeacherView();
+ toast('老师风格已切换,下一轮生效');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function teacherEditor(entry) {
+ const custom = Boolean(entry && entry.kind === 'custom');
+ const base = entry || activeTeacher();
+ const name = custom ? entry.name : '我的风格';
+ const prompt = base && base.prompt ? base.prompt : '';
+ openModal({
+ title: custom ? '编辑老师风格' : '新建老师风格',
+ wide: true,
+ body: `模板名称
+
+ 风格提示词
+
+ 只影响讲解、排版与对话语气,不会改教学契约、会话边界和写权限。与契约冲突时以契约为准。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function saveTeacher(button) {
+ const name = $('#teacher-name') ? $('#teacher-name').value.trim() : '';
+ const prompt = $('#teacher-prompt') ? $('#teacher-prompt').value.trim() : '';
+ if (!name || !prompt) {
+ toast('模板名称和提示词都要填', 'error');
+ return;
+ }
+ const id = button && button.dataset ? button.dataset.id : '';
+ const label = id ? '保存' : '创建并启用';
+ if (button) {
+ button.disabled = true;
+ button.textContent = '保存中…';
+ }
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/teacher`, {
+ method: 'POST',
+ body: id ? { action: 'update', id, name, prompt } : { action: 'create', name, prompt },
+ });
+ closeModal();
+ await reloadTeacherView();
+ toast(id ? '老师风格已更新' : '新模板已创建并启用');
+ } catch (error) {
+ if (button) {
+ button.disabled = false;
+ button.textContent = label;
+ }
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function confirmTeacherDelete() {
+ const entry = activeTeacher();
+ if (!entry || entry.kind !== 'custom') return;
+ openModal({
+ title: '删除老师风格',
+ body: `删除自定义模板「${esc(entry.name)}」。如果它正在生效,会回到「平衡讲解」。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function deleteTeacher(id) {
+ if (!id) return;
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/teacher`, {
+ method: 'POST',
+ body: { action: 'delete', id },
+ });
+ closeModal();
+ await reloadTeacherView();
+ toast('已删除自定义风格');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function markLesson(status) {
+ if (!S.lessonId) return;
+ try {
+ const result = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/lessons/${encodeURIComponent(S.lessonId)}/status`,
+ { method: 'POST', body: { status } },
+ );
+ if (result && result.snapshot) setSnapshot(result.snapshot);
+ S.centerSig = '';
+ updateRail();
+ updateCenter();
+ toast(status === 'done' ? '已标记完成' : '已标记未完成');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function openNote(noteId) {
+ const note = S.snap.notes.find((item) => item.id === noteId);
+ if (!note) return;
+ if (note.status !== 'ready') {
+ if (note.sessionId) {
+ S.center = 'notes';
+ S.centerSig = '';
+ updateCenter();
+ setTalkOpen(true);
+ await openSession(note.sessionId);
+ toast(note.status === 'running' ? '这份笔记还在生成,下面是提炼会话' : '这份笔记没写成功,可以在会话里追问');
+ }
+ return;
+ }
+ try {
+ const result = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/file?rel=${encodeURIComponent(note.path)}`,
+ );
+ S.noteId = noteId;
+ S.noteText = result.text || '';
+ S.center = 'note';
+ S.centerSig = '';
+ updateCenter();
+ if (note.sessionId) await openSession(note.sessionId);
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function bindNoteTags(root) {
+ const form = $('#note-tag-form', root);
+ if (!form) return;
+ const box = $('#note-tag-input', root);
+ if (box) {
+ box.addEventListener('input', () => {
+ // Kept on S so an SSE refresh does not wipe half-typed tags.
+ S.noteTagDraft = box.value;
+ });
+ }
+ form.addEventListener('submit', (event) => {
+ event.preventDefault();
+ const input = $('#note-tag-input', root);
+ void addNoteTag(input ? input.value : '');
+ });
+ }
+
+ const noteEndpoint = (noteId) =>
+ `/api/ws/${encodeURIComponent(S.wsId)}/notes/${encodeURIComponent(noteId)}`;
+
+ async function saveNoteTags(tags) {
+ const note = S.snap.notes.find((item) => item.id === S.noteId);
+ if (!note) return;
+ try {
+ await api(noteEndpoint(note.id), { method: 'POST', body: { action: 'tags', tags } });
+ await refreshSnapshot();
+ toast('标签已更新');
+ return true;
+ } catch (error) {
+ toast(errorText(error), 'error');
+ return false;
+ }
+ }
+
+ async function addNoteTag(value) {
+ const note = S.snap.notes.find((item) => item.id === S.noteId);
+ if (!note) return;
+ const tag = String(value ?? '')
+ .trim()
+ .replace(/^#+/, '')
+ .trim()
+ .slice(0, 24);
+ if (!tag) return;
+ const tags = Array.isArray(note.tags) ? note.tags.slice() : [];
+ if (tags.includes(tag)) {
+ toast('这个标签已经有了');
+ return;
+ }
+ if (tags.length >= 6) {
+ toast('标签最多 6 个,先删一个');
+ return;
+ }
+ tags.push(tag);
+ if (await saveNoteTags(tags)) S.noteTagDraft = '';
+ }
+
+ async function removeNoteTag(tag) {
+ const note = S.snap.notes.find((item) => item.id === S.noteId);
+ if (!note) return;
+ void saveNoteTags((note.tags || []).filter((item) => item !== tag));
+ }
+
+ function renameNote(noteId) {
+ const note = S.snap.notes.find((item) => item.id === noteId);
+ if (!note) return;
+ openModal({
+ title: '重命名笔记',
+ body: `标题
+
+ 只改标题和正文里的第一个标题,文件名 ${esc(
+ note.path,
+ )} 不动。
`,
+ footer: `
+ `,
+ onMount: (root) => {
+ const input = $('#rename-title', root);
+ if (input) {
+ input.focus();
+ input.select();
+ }
+ },
+ });
+ }
+
+ async function renameNoteConfirm(noteId) {
+ const input = $('#rename-title');
+ const title = input ? input.value.trim() : '';
+ if (!title) {
+ toast('标题不能为空', 'error');
+ return;
+ }
+ try {
+ await api(noteEndpoint(noteId), { method: 'POST', body: { action: 'rename', title } });
+ closeModal();
+ const keep = S.center === 'note' && S.noteId === noteId;
+ await refreshSnapshot();
+ if (keep) await openNote(noteId);
+ toast('标题已更新');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function regenNote(noteId) {
+ const note = S.snap.notes.find((item) => item.id === noteId);
+ if (!note) return;
+ openModal({
+ title: '重新生成笔记',
+ body: `用同样的范围(${esc(lessonNumberList(note.lessonIds))})和同样的模板重跑一遍,覆盖 ${esc(
+ note.path,
+ )}。标签会由这次生成重写。
+ 这次想改什么(可选)
+
+ 不填就按原模板重写一遍。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function regenNoteConfirm(noteId) {
+ const input = $('#regen-request');
+ const request = input ? input.value.trim() : '';
+ try {
+ const result = await api(noteEndpoint(noteId), {
+ method: 'POST',
+ body: { action: 'regenerate', request },
+ });
+ closeModal();
+ S.center = 'notes';
+ S.noteId = null;
+ S.centerSig = '';
+ setTalkOpen(true);
+ await refreshSnapshot();
+ if (result && result.sessionId) await openSession(result.sessionId);
+ toast('已开始重新生成,完成后点开这份笔记');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function deleteNote(noteId) {
+ const note = S.snap.notes.find((item) => item.id === noteId);
+ if (!note) return;
+ openModal({
+ title: '删除笔记',
+ body: `删除「${esc(note.title)}」,同时删掉文件 ${esc(
+ note.path,
+ )}。课程、批注与会话记录不动,删掉后不能恢复。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function deleteNoteConfirm(noteId) {
+ try {
+ const result = await api(noteEndpoint(noteId), { method: 'POST', body: { action: 'delete' } });
+ closeModal();
+ S.noteId = null;
+ S.center = 'notes';
+ S.centerSig = '';
+ if (result && result.snapshot) setSnapshot(result.snapshot);
+ updateRail();
+ updateCenter();
+ toast('已删除笔记');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* --------------------------------------------------------------- modals */
+
+ function openModal(config) {
+ const root = $('#modal-root');
+ root.innerHTML = `
+
+
${esc(config.title)}
+
+
+
${config.body || ''}
+ ${config.footer ? `` : ''}
+
+
`;
+ if (config.onMount) config.onMount(root);
+ window.setTimeout(() => {
+ const focusable = root.querySelector('input, textarea, button.primary');
+ if (focusable) focusable.focus();
+ }, 40);
+ }
+
+ function closeModal() {
+ $('#modal-root').innerHTML = '';
+ S.picker = null;
+ }
+
+ /* -------------------------------------------------------- directory picker */
+
+ async function openPicker(mode) {
+ const start = (S.boot && S.boot.home) || '';
+ S.picker = {
+ mode,
+ path: start,
+ input: start,
+ error: '',
+ parent: null,
+ entries: [],
+ loading: true,
+ busy: false,
+ };
+ await loadDir(S.picker.path);
+ }
+
+ /** Accept what people actually paste: quotes, file://, trailing slash, spaces. */
+ function normalizePathInput(value) {
+ let text = String(value ?? '').trim();
+ text = text.replace(/^["'`]+/, '').replace(/["'`]+$/, '').trim();
+ text = text.replace(/^file:\/\/\/?/i, '');
+ text = text.replace(/[\\/]+$/, '');
+ if (/^[a-zA-Z]:$/.test(text)) text += '\\';
+ return text;
+ }
+
+ function isAbsolutePath(value) {
+ return /^[a-zA-Z]:[\\/]/.test(value) || /^\\\\/.test(value);
+ }
+
+ async function loadDir(target) {
+ const picker = S.picker;
+ if (!picker) return false;
+ const next = normalizePathInput(target);
+ picker.input = String(target ?? '');
+ if (!isAbsolutePath(next)) {
+ picker.error = '要填完整路径,例如 D:\\代码\\项目名';
+ picker.loading = false;
+ renderPicker();
+ return false;
+ }
+ picker.loading = true;
+ picker.error = '';
+ renderPicker();
+ try {
+ const data = await api(`/api/fs/list?path=${encodeURIComponent(next)}`);
+ picker.path = data.path;
+ picker.parent = data.parent;
+ picker.entries = data.entries;
+ picker.input = data.path;
+ picker.error = '';
+ return true;
+ } catch (error) {
+ // Keep the typed value so a bad paste never silently falls back to the
+ // previously browsed directory.
+ picker.input = String(target ?? '');
+ picker.error =
+ error.code === 'not_a_directory' || error.code === 'path_must_be_absolute'
+ ? '读不到这个目录:确认路径存在、且是一个文件夹'
+ : errorText(error);
+ return false;
+ } finally {
+ picker.loading = false;
+ renderPicker();
+ }
+ }
+
+ function renderPicker() {
+ const picker = S.picker;
+ if (!picker) return;
+ const isCreate = picker.mode === 'create';
+ const typed = normalizePathInput(picker.input || picker.path);
+ const body = `
+
+
+
+
+
+ ${picker.error ? `${esc(picker.error)}
` : ''}
+
+ ${
+ picker.loading
+ ? `
读取中…
`
+ : picker.entries.length
+ ? picker.entries
+ .map(
+ (entry) => `
`,
+ )
+ .join('')
+ : `
这个目录里没有子目录。
`
+ }
+
+ ${
+ isCreate
+ ? `
+
+ 将在
+ ${esc(
+ typed || '(还没选)',
+ )}
+
+
会在这里生成 MISSION.md、RESOURCES.md、GLOSSARY.md、lessons/、reference/、.workbench/ 等结构;已有同名文件不会覆盖。
+
主题、使命和规则不在这里填——创建工作台后会开一个配置会话,老师先问清楚再写,这一轮不产出课程和课纲。
+
`
+ : `选择已经用学习工作台创建过的目录(里面有 .workbench/workspace.json)。
`
+ }`;
+ const footer = isCreate
+ ? `
+ `
+ : `
+ `;
+ openModal({
+ title: isCreate ? '新建学习工作台' : '导入已有学习工作台',
+ body,
+ footer,
+ wide: true,
+ onMount: (root) => {
+ const pathInput = $('#pick-path', root);
+ if (!pathInput) return;
+ pathInput.addEventListener('input', () => {
+ picker.input = pathInput.value;
+ picker.error = '';
+ const line = root.querySelector('.stack .mono');
+ if (line) line.textContent = normalizePathInput(pathInput.value) || '(还没选)';
+ });
+ pathInput.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void loadDir(pathInput.value);
+ }
+ });
+ },
+ });
+ window.setTimeout(() => {
+ const input = $('#pick-path');
+ if (input && document.activeElement !== input) {
+ input.focus();
+ input.setSelectionRange(input.value.length, input.value.length);
+ }
+ }, 30);
+ }
+
+ /** Verify the typed path, then create — never reuse a stale browsed path. */
+ async function resolveTargetPath() {
+ const picker = S.picker;
+ if (!picker) return null;
+ const input = $('#pick-path');
+ const raw = input ? input.value : picker.input;
+ const target = normalizePathInput(raw);
+ if (!isAbsolutePath(target)) {
+ picker.input = String(raw ?? '');
+ picker.error = '要填完整路径,例如 D:\\代码\\项目名';
+ renderPicker();
+ return null;
+ }
+ picker.input = String(raw ?? '');
+ const listing = await api(`/api/fs/list?path=${encodeURIComponent(target)}`);
+ return listing.path;
+ }
+
+ async function submitCreate() {
+ const picker = S.picker;
+ if (!picker) return;
+ picker.busy = true;
+ renderPicker();
+ try {
+ const target = await resolveTargetPath();
+ if (!target) {
+ picker.busy = false;
+ renderPicker();
+ return;
+ }
+ picker.path = target;
+ picker.input = target;
+ const result = await api('/api/workspaces/create', {
+ method: 'POST',
+ body: { parentPath: target },
+ });
+ closeModal();
+ S.boot = await api('/api/bootstrap');
+ S.talkOpen = preferredTalkOpen();
+ await openWorkspace(result.workspace.id);
+ toast(result.existing ? '这个目录已经是学习工作台' : '工作台已创建,老师开始配置');
+ } catch (error) {
+ picker.busy = false;
+ picker.error = errorText(error);
+ renderPicker();
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function submitImport() {
+ const picker = S.picker;
+ if (!picker) return;
+ picker.busy = true;
+ renderPicker();
+ try {
+ const target = await resolveTargetPath();
+ if (!target) {
+ picker.busy = false;
+ renderPicker();
+ return;
+ }
+ picker.path = target;
+ picker.input = target;
+ const result = await api('/api/workspaces/import', {
+ method: 'POST',
+ body: { root: target },
+ });
+ closeModal();
+ S.boot = await api('/api/bootstrap');
+ S.talkOpen = preferredTalkOpen();
+ await openWorkspace(result.workspace.id);
+ toast('已导入');
+ } catch (error) {
+ picker.busy = false;
+ picker.error = errorText(error);
+ renderPicker();
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* -------------------------------------------------------------- manage */
+
+ const cleanList = () => (S.boot && Array.isArray(S.boot.cleanTargets) ? S.boot.cleanTargets : []);
+ const defaultCleanTargets = () =>
+ new Set(cleanList().filter((row) => row.default).map((row) => row.key));
+
+ function openManage(view, id) {
+ S.manage = {
+ view: view || 'list',
+ id: id || '',
+ targets: defaultCleanTargets(),
+ };
+ renderManage();
+ }
+
+ function renderManage() {
+ const manage = S.manage;
+ if (!manage) return;
+ const workspaces = (S.boot && S.boot.workspaces) || [];
+
+ if (manage.view === 'clean') {
+ const workspace = workspaces.find((item) => item.id === manage.id);
+ if (!workspace) {
+ openManage('list');
+ return;
+ }
+ const rows = cleanList();
+ openModal({
+ title: '清理产物',
+ wide: true,
+ body: `只删下面勾选的路径;目录里的其他文件(源码、docs、datasets 等)不会动。
+ ${esc(workspace.root)}
+
+ ${rows
+ .map(
+ (row) => ``,
+ )
+ .join('')}
+
`,
+ footer: `
+ `,
+ onMount: (root) => {
+ root.querySelectorAll('input[data-clean]').forEach((input) => {
+ input.addEventListener('change', () => {
+ if (input.checked) manage.targets.add(input.dataset.clean);
+ else manage.targets.delete(input.dataset.clean);
+ });
+ });
+ },
+ });
+ return;
+ }
+
+ openModal({
+ title: '工作台管理',
+ wide: true,
+ body: `新增、移除,或清理某个工作台按 teach 规约生成的文件。
+ ${
+ workspaces.length
+ ? workspaces
+ .map(
+ (workspace) => `
+
+
${esc(workspace.name)}${
+ workspace.id === S.wsId ? ' 当前' : ''
+ }
+
${esc(workspace.root)}
+
+ ${
+ workspace.id === S.wsId
+ ? ''
+ : `
`
+ }
+
+
+
`,
+ )
+ .join('')
+ : '还没有工作台。
'
+ }`,
+ footer: `
+
+ `,
+ });
+ }
+
+ async function confirmClean() {
+ const manage = S.manage;
+ if (!manage) return;
+ const targets = Array.from(manage.targets);
+ if (!targets.length) {
+ toast('先勾选要清理的内容');
+ return;
+ }
+ // The clean stops running turns before it deletes, so show the wait.
+ const button = $('[data-act="manage-clean-confirm"]');
+ const label = button ? button.textContent : '';
+ if (button) {
+ button.disabled = true;
+ button.textContent = '清理中…';
+ }
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(manage.id)}/clean`, {
+ method: 'POST',
+ body: { targets },
+ });
+ const wasCurrent = manage.id === S.wsId;
+ S.boot = await api('/api/bootstrap');
+ const count = result.removed ? result.removed.length : 0;
+ const effects = result.effects || {};
+ const notes = effects.notesPruned ? `,笔记索引移除 ${effects.notesPruned} 条` : '';
+ toast(`已清理 ${count} 项${notes}`);
+ if (result.workspaceGone) {
+ closeModal();
+ if (wasCurrent) {
+ const next = (S.boot.workspaces || [])[0];
+ if (next) {
+ await openWorkspace(next.id);
+ } else {
+ S.wsId = null;
+ setSnapshot(null);
+ renderLanding();
+ }
+ }
+ return;
+ }
+ if (wasCurrent) {
+ S.centerSig = '';
+ await refreshSnapshot();
+ }
+ openManage('list');
+ } catch (error) {
+ if (button) {
+ button.disabled = false;
+ button.textContent = label;
+ }
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function confirmRemove(id) {
+ const workspace = ((S.boot && S.boot.workspaces) || []).find((item) => item.id === id);
+ if (!workspace) return;
+ openModal({
+ title: '移除工作台',
+ body: `把「${esc(workspace.name)}」从列表移除。磁盘上的文件不会删除,之后可以再导入。
+ ${esc(workspace.root)}
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function doRemove(id) {
+ try {
+ await api('/api/workspaces/forget', { method: 'POST', body: { id } });
+ closeModal();
+ S.boot = await api('/api/bootstrap');
+ if (id === S.wsId) {
+ const next = (S.boot.workspaces || [])[0];
+ if (next) {
+ await openWorkspace(next.id);
+ } else {
+ S.wsId = null;
+ setSnapshot(null);
+ renderLanding();
+ }
+ } else {
+ toast('已从列表移除');
+ }
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ------------------------------------------------------------- annotate */
+
+ function openAnnotate(options) {
+ const opts = options || {};
+ S.pendingQuote = opts.quote || '';
+ S.pendingAnnoId = opts.id || '';
+ const existing = opts.id ? S.snap.annotations.find((item) => item.id === opts.id) : null;
+ openModal({
+ title: existing ? '编辑批注' : '添加批注',
+ body: `
+ ${opts.quote ? `${esc(opts.quote)}
` : ''}
+
+ ${
+ opts.quote ? '批注会挂在这句话上,并在这节课里高亮。' : '整节批注会挂在这一课上。'
+ } 提炼笔记时会被一起带上。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function saveAnnotation() {
+ const input = $('#anno-note');
+ const note = input ? input.value.trim() : '';
+ if (!note) {
+ toast('写点什么再保存');
+ return;
+ }
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/annotations`, {
+ method: 'POST',
+ body: {
+ action: S.pendingAnnoId ? 'update' : 'create',
+ id: S.pendingAnnoId || undefined,
+ lessonId: S.lessonId,
+ quote: S.pendingQuote,
+ note,
+ },
+ });
+ closeModal();
+ await refreshSnapshot();
+ S.tab = 'anno';
+ S.centerSig = '';
+ updateCenter();
+ toast('已保存批注');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function deleteAnnotation(id) {
+ openModal({
+ title: '删除批注',
+ body: `删除后无法恢复。这节课的笔记如果已经生成,不受影响。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function confirmDeleteAnnotation(id) {
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/annotations`, {
+ method: 'POST',
+ body: { action: 'delete', id },
+ });
+ closeModal();
+ await refreshSnapshot();
+ S.centerSig = '';
+ updateCenter();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ---------------------------------------------------------------- notes */
+
+ function openNotesPicker() {
+ const lessons = lessonsOf().filter((lesson) => lessonHasFile(lesson));
+ if (!lessons.length) {
+ toast('还没有生成任何课程文件');
+ return;
+ }
+ const state = {
+ selected: new Set(lessons.map((lesson) => lesson.id)),
+ title: '',
+ titleTouched: false,
+ template: (noteTemplates()[0] && noteTemplates()[0].id) || 'essence',
+ request: '',
+ };
+ const render = () => {
+ const selectedLessons = lessons.filter((lesson) => state.selected.has(lesson.id));
+ const annotationCount = S.snap.annotations.filter((item) => state.selected.has(item.lessonId)).length;
+ if (!state.titleTouched) {
+ state.title = `${lessonNumberList(Array.from(state.selected))}笔记`;
+ }
+ const currentTemplate =
+ noteTemplates().find((item) => item.id === state.template) || noteTemplates()[0];
+ const body = `
+ 范围
+ ${
+ S.snap.curriculum.modules
+ .map((module) => {
+ const rows = module.lessons.filter((lesson) => lessonHasFile(lesson));
+ if (!rows.length) return '';
+ return `
+
${esc(module.title)}
+ ${rows
+ .map((lesson) => {
+ const count = annotationsOf(lesson.id).length;
+ return `
`;
+ })
+ .join('')}
+
`;
+ })
+ .join('')
+ }
+ ${
+ noteTemplates().length
+ ? `笔记模板
+
+ ${esc(currentTemplate ? currentTemplate.summary : '')}
`
+ : ''
+ }
+ 笔记标题
+
+ 微调提示(可选)
+
+ 会带上你选中的 ${
+ selectedLessons.length
+ } 节课的课程内容与 ${annotationCount} 条批注,在独立会话里写成 notes/*.md。
`;
+ openModal({
+ title: '提炼笔记',
+ body,
+ footer: `
+ `,
+ wide: true,
+ onMount: (root) => {
+ root.querySelectorAll('input[data-lesson]').forEach((input) => {
+ input.addEventListener('change', () => {
+ if (input.checked) state.selected.add(input.dataset.lesson);
+ else state.selected.delete(input.dataset.lesson);
+ render();
+ });
+ });
+ const templatePick = $('#note-template', root);
+ if (templatePick) {
+ templatePick.addEventListener('change', () => {
+ state.template = templatePick.value;
+ const hint = $('#note-template-hint', root);
+ const found = noteTemplates().find((item) => item.id === state.template);
+ if (hint) hint.textContent = found ? found.summary : '';
+ });
+ }
+ const title = $('#note-title', root);
+ if (title) {
+ title.addEventListener('input', () => {
+ state.title = title.value;
+ state.titleTouched = true;
+ });
+ }
+ const request = $('#note-request', root);
+ if (request) {
+ request.addEventListener('input', () => {
+ state.request = request.value;
+ });
+ }
+ },
+ });
+ S.notePick = state;
+ };
+ render();
+ }
+
+ async function startNote() {
+ const state = S.notePick;
+ if (!state) return;
+ const lessonIds = Array.from(state.selected);
+ if (!lessonIds.length) return;
+ const title = (state.title || '').trim() || `${lessonNumberList(lessonIds)}笔记`;
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/notes`, {
+ method: 'POST',
+ body: { lessonIds, title, templateId: state.template, request: state.request || '' },
+ });
+ closeModal();
+ S.center = 'notes';
+ S.centerSig = '';
+ setTalkOpen(true);
+ await refreshSnapshot();
+ if (result && result.sessionId) await openSession(result.sessionId);
+ toast('已开一个独立会话提炼笔记');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ---------------------------------------------------------------- rules */
+
+ async function showRules() {
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/rules`);
+ openModal({
+ title: '教学规则 · teach.md',
+ wide: true,
+ body: `${esc(result.path || '')}
+ ${esc(
+ result.text || '',
+ )}`,
+ footer: ``,
+ });
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ---------------------------------------------------------------- events */
+
+ function handleEvent(event) {
+ let message = null;
+ try {
+ message = JSON.parse(event.data);
+ } catch {
+ return;
+ }
+ if (!message || (message.wsId && message.wsId !== S.wsId)) return;
+
+ if (message.t === 'delta') {
+ const sid = message.sessionId;
+ const next = (S.live.get(sid) || '') + (message.text || '');
+ S.live.set(sid, next);
+ if (sid === S.sessionId) {
+ const body = $('#talk-body');
+ const live = $('#live-text');
+ if (body && live) {
+ const stick = body.scrollHeight - body.scrollTop - body.clientHeight < 90;
+ live.innerHTML = md(next);
+ if (stick) body.scrollTop = body.scrollHeight;
+ } else {
+ updateTalk();
+ }
+ }
+ return;
+ }
+
+ if (message.t === 'session') {
+ const sid = message.sessionId;
+ const session = message.session;
+ if (!session) return;
+ if (!session.running) {
+ S.live.delete(sid);
+ }
+ const known = S.transcripts.get(sid);
+ if (known) {
+ known.running = session.running;
+ known.pending = session.pending;
+ known.permissions = session.permissions || [];
+ known.title = session.title;
+ }
+ if (sid === S.sessionId) {
+ void loadTranscript(sid).then(() => {
+ S.tools.delete(sid);
+ updateTalk();
+ });
+ } else if (session.messageCount > ((known && known.messages.length) || 0)) {
+ S.unread.add(sid);
+ updateRail();
+ }
+ return;
+ }
+
+ if (message.t === 'tool') {
+ if (message.phase !== 'end') return;
+ const sid = message.sessionId;
+ const list = S.tools.get(sid) || [];
+ list.push({ name: message.name, phase: message.phase, ok: message.ok });
+ S.tools.set(sid, list.slice(-6));
+ if (sid === S.sessionId) {
+ const body = $('#talk-body');
+ if (body) {
+ const stick = body.scrollHeight - body.scrollTop - body.clientHeight < 90;
+ renderTalkBody(body, S.transcripts.get(sid) || { id: sid, messages: [] });
+ if (stick) body.scrollTop = body.scrollHeight;
+ }
+ }
+ return;
+ }
+
+ if (message.t === 'state' || message.t === 'annotations') {
+ window.clearTimeout(handleEvent.timer);
+ handleEvent.timer = window.setTimeout(() => {
+ void refreshSnapshot();
+ }, 250);
+ }
+ }
+
+ let reconnectCount = 0;
+ function connectEvents() {
+ if (S.es) {
+ S.es.close();
+ S.es = null;
+ }
+ if (!S.wsId) return;
+ try {
+ const es = new EventSource('/api/events');
+ es.onmessage = handleEvent;
+ es.onopen = () => {
+ reconnectCount += 1;
+ if (reconnectCount > 1) void refreshSnapshot();
+ };
+ es.onerror = () => {
+ /* EventSource reconnects on its own */
+ };
+ S.es = es;
+ } catch {
+ /* ignore */
+ }
+ }
+
+ /* --------------------------------------------------------------- bridge */
+
+ /** Resolve a lesson link against the lesson's own path; '' when it leaves the workspace. */
+ function resolveDocRel(lessonRel, href) {
+ const raw = String(href || '').trim();
+ if (!raw || raw.startsWith('#') || raw.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(raw)) return '';
+ const clean = raw.split('#')[0].split('?')[0];
+ if (!clean) return '';
+ let decoded = clean;
+ try {
+ decoded = decodeURIComponent(clean);
+ } catch {
+ /* keep the raw value */
+ }
+ const out = [];
+ for (const part of String(lessonRel || '').split('/').slice(0, -1).concat(decoded.split('/'))) {
+ if (!part || part === '.') continue;
+ if (part === '..') {
+ if (!out.length) return '';
+ out.pop();
+ continue;
+ }
+ out.push(part);
+ }
+ return out.join('/');
+ }
+
+ /** "main.py:46–48" → {line:46,end:48}; ":1807" → {line:1807,end:1807}. */
+ function parseLineRef(text) {
+ const match = String(text || '').match(/:(\d+)(?:\s*[–—-]\s*(\d+))?/);
+ if (!match) return { line: 0, end: 0 };
+ const line = Number(match[1]) || 0;
+ const end = Number(match[2]) || line;
+ return { line, end: Math.max(line, end) };
+ }
+
+ function openWorkspacePage(rel) {
+ if (!$('#lesson-frame')) return;
+ void loadLessonFrame(
+ `/w/${encodeURIComponent(S.wsId)}/${rel.split('/').map(encodeURIComponent).join('/')}`,
+ );
+ }
+
+ async function openCodePanel(data) {
+ const lessonRel = data.rel || (currentLesson() || {}).file || '';
+ const rel = resolveDocRel(lessonRel, data.href);
+ if (!rel) {
+ toast('这个链接不在工作台里,暂时打不开');
+ return;
+ }
+ // A link to another lesson or a reference page is page navigation, not a
+ // code view: switch lessons for a lesson page, otherwise load the page into
+ // the lesson frame.
+ const target = lessonByFile(rel);
+ if (target) {
+ await selectLesson(target.id, { seed: false });
+ return;
+ }
+ if ((S.snap.lessonFiles || []).includes(rel) || (S.snap.referenceFiles || []).includes(rel)) {
+ openWorkspacePage(rel);
+ return;
+ }
+ const range = parseLineRef(data.text);
+ let payload;
+ try {
+ payload = await api(`/api/ws/${encodeURIComponent(S.wsId)}/file?rel=${encodeURIComponent(rel)}`);
+ } catch (error) {
+ toast(errorText(error), 'error');
+ return;
+ }
+ const lines = String(payload.text || '').replace(/\r\n/g, '\n').split('\n');
+ const start = range.line ? Math.min(range.line, lines.length) : 0;
+ const end = start ? Math.min(range.end || start, lines.length) : 0;
+ const rows = lines
+ .map((code, index) => {
+ const no = index + 1;
+ const hit = start && no >= start && no <= end ? ' hit' : '';
+ return `${no}${esc(code) || ' '}
`;
+ })
+ .join('');
+ const label = start ? `${rel}:${start}${end > start ? `–${end}` : ''}` : rel;
+ openModal({
+ title: label,
+ wide: true,
+ body: `${rows}
`,
+ footer: `共 ${lines.length} 行
`,
+ onMount: (root) => {
+ const view = root.querySelector('.file-view');
+ const hit = view ? view.querySelector('.file-row.hit') : null;
+ if (view && hit) view.scrollTop = Math.max(0, hit.offsetTop - view.clientHeight / 3);
+ },
+ });
+ }
+
+ window.addEventListener('message', (event) => {
+ const frame = $('#lesson-frame');
+ if (!frame || event.source !== frame.contentWindow) return;
+ const data = event.data;
+ if (!data || data.source !== 'wb') return;
+ if (data.type === 'external' && typeof data.href === 'string' && /^https?:/i.test(data.href)) {
+ window.open(data.href, '_blank', 'noopener');
+ return;
+ }
+ if (data.type === 'file' && data.href) {
+ void openCodePanel(data);
+ return;
+ }
+ if (data.type === 'annotate' && data.quote) {
+ openAnnotate({ quote: data.quote });
+ }
+ if (data.type === 'ask' && data.quote) {
+ const quote = String(data.quote).slice(0, 300);
+ const prefix = '关于「' + quote + '」:';
+ const apply = () => {
+ if (!S.sessionId) return;
+ setTalkOpen(true);
+ S.drafts.set(S.sessionId, prefix);
+ const input = $('#talk-input');
+ if (!input) return;
+ input.value = prefix;
+ input.focus();
+ input.setSelectionRange(prefix.length, prefix.length);
+ autoSize(input);
+ };
+ if (S.sessionId) {
+ apply();
+ return;
+ }
+ // Reading a lesson without its branch session open: open it, then prefill.
+ const lessonId = pickLesson();
+ if (!lessonId) return;
+ void selectLesson(lessonId, { seed: false }).then(apply).catch(() => {});
+ }
+ if (data.type === 'open' && data.id) {
+ S.tab = 'anno';
+ S.centerSig = '';
+ updateCenter();
+ window.setTimeout(() => {
+ const node = $(`#anno-${CSS.escape(data.id)}`);
+ if (node) {
+ node.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ node.classList.add('flash');
+ window.setTimeout(() => node.classList.remove('flash'), 1800);
+ }
+ }, 60);
+ }
+ if (data.type === 'ready') {
+ frame.contentWindow.postMessage(
+ {
+ source: 'host',
+ type: 'theme',
+ theme: document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light',
+ },
+ '*',
+ );
+ applyFontScale();
+ }
+ });
+
+ /* -------------------------------------------------------------- handlers */
+
+ const ACTIONS = {
+ 'close-modal': () => closeModal(),
+ 'modal-backdrop': (node, event) => {
+ if (event.target === node) closeModal();
+ },
+ 'open-picker': (node) => openPicker(node.dataset.mode || 'create'),
+ 'picker-up': () => {
+ if (S.picker && S.picker.parent) void loadDir(S.picker.parent);
+ },
+ 'picker-enter': (node) => {
+ if (node.dataset.path) void loadDir(node.dataset.path);
+ },
+ 'picker-go': () => {
+ const input = $('#pick-path');
+ void loadDir(input ? input.value : S.picker && S.picker.input);
+ },
+ 'create-ws': () => void submitCreate(),
+ 'import-ws': () => void submitImport(),
+ 'open-ws': (node) => void openWorkspace(node.dataset.id),
+ 'manage-ws': () => openManage('list'),
+ 'manage-open': (node) => {
+ closeModal();
+ S.talkOpen = preferredTalkOpen();
+ void openWorkspace(node.dataset.id);
+ },
+ 'manage-clean': (node) => {
+ S.manage.view = 'clean';
+ S.manage.id = node.dataset.id;
+ S.manage.targets = defaultCleanTargets();
+ renderManage();
+ },
+ 'manage-back': () => {
+ S.manage.view = 'list';
+ renderManage();
+ },
+ 'manage-clean-confirm': () => void confirmClean(),
+ 'manage-remove': (node) => confirmRemove(node.dataset.id),
+ 'manage-remove-confirm': (node) => void doRemove(node.dataset.id),
+ 'open-lesson': (node) => void selectLesson(node.dataset.id, { seed: false }),
+ 'renew-lesson': () => {
+ const lesson = currentLesson();
+ if (!lesson) return;
+ openModal({
+ title: '新开追问',
+ body: '会为「第 ' + lesson.no + ' 课」新建一个分支会话:带上这一课的上下文与上一轮的结论。旧会话记录保留,课件不会被改写。
',
+ footer: '' +
+ '',
+ });
+ },
+ 'renew-lesson-confirm': () => void renewLesson(),
+ 'regenerate-lesson': () => {
+ const lesson = currentLesson();
+ if (!lesson) return;
+ openModal({
+ title: '重新生成这一课',
+ body:
+ '会按课纲把「第 ' +
+ lesson.no +
+ ' 课」整节重写,覆盖 ' +
+ esc(lesson.file || '本课文件') +
+ '。课件内容会被替换,批注、笔记与学习记录保留。
',
+ footer:
+ '' +
+ '',
+ });
+ },
+ 'regenerate-lesson-confirm': () => void regenerateLesson(),
+ 'open-main': () => void openMain(),
+ 'open-setup': () => void openSetupSession(),
+ 'open-overview': () => {
+ S.center = 'overview';
+ S.centerSig = '';
+ S.fontMenu = false;
+ updateTop();
+ updateCenter();
+ },
+ 'open-notes': () => {
+ S.center = 'notes';
+ S.noteId = null;
+ S.centerSig = '';
+ S.fontMenu = false;
+ updateTop();
+ updateCenter();
+ },
+ 'open-note': (node) => void openNote(node.dataset.id),
+ tab: (node) => {
+ S.tab = node.dataset.tab === 'anno' ? 'anno' : 'lesson';
+ S.centerSig = '';
+ updateCenter();
+ },
+ 'toggle-talk': () => {
+ const open = !S.talkOpen;
+ setTalkOpen(open);
+ if (open && !S.sessionId && S.center === 'lesson' && S.lessonId) {
+ void selectLesson(S.lessonId, { seed: false });
+ }
+ },
+ 'toggle-rail': () => setRailOpen(!S.railOpen),
+ 'toggle-top-menu': () => {
+ S.fontMenu = false;
+ renderFontMenu();
+ setTopMenu(!S.topMenu);
+ },
+ 'toggle-font-menu': () => {
+ S.topMenu = false;
+ S.fontMenu = !S.fontMenu;
+ updateTop();
+ renderFontMenu();
+ },
+ 'font-step': (node) => stepFontScale(Number(node.dataset.step) || 0),
+ 'font-reset': () => setFontScale(1),
+ 'mark-lesson': (node) => void markLesson(node.dataset.status),
+ 'start-lesson': () => {
+ if (!S.lessonId) return;
+ setTalkOpen(true);
+ void selectLesson(S.lessonId, { seed: true });
+ },
+ 'start-main': () => void openMain({ seed: true }),
+ 'generate-curriculum': () => void generateCurriculum(),
+ 'teacher-new': () => teacherEditor(null),
+ 'teacher-edit': () => teacherEditor(activeTeacher()),
+ 'teacher-delete': () => confirmTeacherDelete(),
+ 'teacher-delete-confirm': (node) => void deleteTeacher(node.dataset.id),
+ 'teacher-save': (node) => void saveTeacher(node),
+ 'refresh-ws': () => {
+ void (async () => {
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/refresh`, {
+ method: 'POST',
+ body: {},
+ });
+ if (result && result.snapshot) setSnapshot(result.snapshot);
+ S.centerSig = '';
+ updateTop();
+ updateRail();
+ updateCenter();
+ toast(result && result.error ? `课纲解析失败:${result.error}` : '已重新读取');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ })();
+ },
+ 'annotate-lesson': () => openAnnotate({ quote: '' }),
+ 'edit-anno': (node) => {
+ const item = S.snap.annotations.find((entry) => entry.id === node.dataset.id);
+ if (item) openAnnotate({ quote: item.quote, id: item.id });
+ },
+ 'delete-anno': (node) => void deleteAnnotation(node.dataset.id),
+ 'confirm-delete-anno': (node) => void confirmDeleteAnnotation(node.dataset.id),
+ 'save-anno': () => void saveAnnotation(),
+ 'permission-allow': (node) => void replyPermission(node.dataset.request, 'allowOnce'),
+ 'permission-deny': (node) => void replyPermission(node.dataset.request, 'deny'),
+ 'answer-question': () => void submitAnswers(false),
+ 'skip-question': () => void submitAnswers(true),
+ 'cancel-turn': () => void cancelTurn(),
+ 'open-notes-picker': () => openNotesPicker(),
+ 'start-note': () => void startNote(),
+ 'rename-note': (node) => renameNote(node.dataset.id),
+ 'rename-note-confirm': (node) => void renameNoteConfirm(node.dataset.id),
+ 'regen-note': (node) => regenNote(node.dataset.id),
+ 'regen-note-confirm': (node) => void regenNoteConfirm(node.dataset.id),
+ 'delete-note': (node) => deleteNote(node.dataset.id),
+ 'delete-note-confirm': (node) => void deleteNoteConfirm(node.dataset.id),
+ 'del-note-tag': (node) => void removeNoteTag(node.dataset.tag),
+ 'show-rules': () => void showRules(),
+ 'show-components': () => {
+ const rel = 'reference/视觉组件速查.html';
+ if (!S.snap || !(S.snap.referenceFiles || []).includes(rel)) return;
+ const src = `/w/${encodeURIComponent(S.wsId)}/${rel.split('/').map(encodeURIComponent).join('/')}`;
+ openModal({
+ title: '视觉组件速查',
+ wide: true,
+ body: ``,
+ footer: '',
+ onMount: (root) => {
+ void loadSrcdoc($('#ref-frame', root), src);
+ },
+ });
+ },
+ 'show-mission': () =>
+ openModal({
+ title: '使命 · MISSION.md',
+ wide: true,
+ body: `${md((S.snap && S.snap.mission) || '')}
`,
+ footer: ``,
+ }),
+ 'copy-path': () => {
+ const root = S.snap && S.snap.workspace.root;
+ if (!root) return;
+ navigator.clipboard
+ .writeText(root)
+ .then(() => toast('路径已复制'))
+ .catch(() => toast('复制失败', 'error'));
+ },
+ };
+
+ document.addEventListener('click', (event) => {
+ const node = event.target.closest ? event.target.closest('[data-act]') : null;
+ if (!node) return;
+ // The modal backdrop is an ancestor of everything in the dialog. Clicks on
+ // inputs, checkboxes and links inside it must keep their default behaviour.
+ if (node.dataset.act === 'modal-backdrop' && event.target !== node) return;
+ const action = ACTIONS[node.dataset.act];
+ if (!action) return;
+ event.preventDefault();
+ action(node, event);
+ if (node.dataset.act !== 'toggle-top-menu' && S.topMenu) {
+ S.topMenu = false;
+ updateTop();
+ }
+ });
+
+ document.addEventListener('click', (event) => {
+ // composedPath survives the re-render a menu action does: the clicked node is
+ // already detached here, so closest() would no longer find its wrapper.
+ const path = event.composedPath ? event.composedPath() : [event.target];
+ if (S.fontMenu && !path.some((node) => node.classList && node.classList.contains('font-wrap'))) {
+ S.fontMenu = false;
+ renderFontMenu();
+ }
+ if (!S.topMenu) return;
+ if (path.some((node) => node.classList && node.classList.contains('menu-wrap'))) return;
+ S.topMenu = false;
+ updateTop();
+ });
+
+ document.addEventListener('keydown', (event) => {
+ if (event.key !== 'Escape') return;
+ if ($('#modal-root').children.length) closeModal();
+ else if (S.topMenu) {
+ S.topMenu = false;
+ updateTop();
+ } else if (S.fontMenu) {
+ S.fontMenu = false;
+ renderFontMenu();
+ }
+ });
+
+ /* ------------------------------------------------------------------ boot */
+
+ async function boot() {
+ initTheme();
+ S.layout = readLayout();
+ S.railOpen = localStorage.getItem('wb.railOpen') !== '0';
+ try {
+ S.boot = await api('/api/bootstrap');
+ } catch (error) {
+ $('#app').innerHTML = `
+
无法连接学习工作台
+
${esc(errorText(error))}
+
+
`;
+ return;
+ }
+ // A path-vocabulary drift is a code problem: say it here instead of leaving
+ // the startup check in a log nobody reads.
+ const pathIssues = (S.boot && S.boot.diagnostics && S.boot.diagnostics.pathVocabulary) || [];
+ if (pathIssues.length) {
+ console.warn('[check-paths]', pathIssues);
+ toast(`路径检查发现 ${pathIssues.length} 处问题,详见控制台`, 'error');
+ }
+ S.talkOpen = preferredTalkOpen();
+ const list = S.boot.workspaces || [];
+ if (!list.length) {
+ renderLanding();
+ return;
+ }
+ const last = localStorage.getItem('wb.last');
+ const target = list.find((workspace) => workspace.id === last) || list[0];
+ await openWorkspace(target.id);
+ }
+
+ window.addEventListener('resize', () => {
+ if (!S.layout) return;
+ const next = clampLayout(S.layout);
+ if (next.rail === S.layout.rail && next.talk === S.layout.talk) return;
+ S.layout = next;
+ applyLayout();
+ localStorage.setItem('wb.layout', JSON.stringify(S.layout));
+ });
+
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') {
+ const input = $('#talk-input');
+ if (input && S.sessionId) S.drafts.set(S.sessionId, input.value);
+ }
+ if (document.visibilityState === 'visible' && S.wsId) {
+ void refreshSnapshot();
+ }
+ });
+
+ void boot();
+})();
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/index.html b/plugins/meisijiya/learn-workbench/miniapp/client/index.html
new file mode 100644
index 00000000..11baf5ad
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/index.html
@@ -0,0 +1,15 @@
+
+
+
+
+
+ 学习工作台
+
+
+
+
+
+
+
+
+
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/lesson-bridge.js b/plugins/meisijiya/learn-workbench/miniapp/client/lesson-bridge.js
new file mode 100644
index 00000000..38fe0a96
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/lesson-bridge.js
@@ -0,0 +1,408 @@
+(function () {
+ 'use strict';
+
+ const cfg = window.__WB__ || { annotations: [] };
+ const source = 'wb';
+
+ /* ------------------------------------------------------------ highlight */
+
+ const style = document.createElement('style');
+ style.textContent = `
+ mark.wb-hl {
+ background: color-mix(in srgb, #f59e0b 26%, transparent);
+ border-bottom: 1px solid color-mix(in srgb, #f59e0b 70%, transparent);
+ border-radius: 2px;
+ padding: 0 1px;
+ cursor: pointer;
+ color: inherit;
+ }
+ mark.wb-hl:hover { background: color-mix(in srgb, #f59e0b 40%, transparent); }
+ `;
+ document.head.appendChild(style);
+
+ function normalize(value) {
+ return String(value || '').replace(/\s+/g, ' ').trim();
+ }
+
+ // Quotes may cross / inside one block, so highlight per block
+ // instead of per text node.
+ const BLOCK_SELECTOR =
+ 'p, li, h1, h2, h3, h4, h5, h6, blockquote, td, th, dd, dt, figcaption, caption, pre';
+
+ function textNodesIn(root) {
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
+ acceptNode(node) {
+ const parent = node.parentElement;
+ if (!parent) return NodeFilter.FILTER_REJECT;
+ const tag = parent.tagName;
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'MARK' || tag === 'NOSCRIPT') {
+ return NodeFilter.FILTER_REJECT;
+ }
+ if (!node.nodeValue || !node.nodeValue.trim()) return NodeFilter.FILTER_REJECT;
+ return NodeFilter.FILTER_ACCEPT;
+ },
+ });
+ const nodes = [];
+ let current = walker.nextNode();
+ while (current) {
+ nodes.push(current);
+ current = walker.nextNode();
+ }
+ return nodes;
+ }
+
+ /** Concatenate a block's text and remember where each character came from. */
+ function buildIndex(nodes) {
+ let text = '';
+ const map = [];
+ for (const node of nodes) {
+ const value = node.nodeValue;
+ for (let i = 0; i < value.length; i += 1) {
+ const char = value[i];
+ if (/\s/.test(char)) {
+ if (text.endsWith(' ')) continue;
+ map.push({ node, offset: i });
+ text += ' ';
+ } else {
+ map.push({ node, offset: i });
+ text += char;
+ }
+ }
+ }
+ return { text, map };
+ }
+
+ function markFor(annotation) {
+ const mark = document.createElement('mark');
+ mark.className = 'wb-hl';
+ mark.dataset.wb = annotation.id;
+ mark.title = annotation.note ? String(annotation.note).slice(0, 200) : '查看批注';
+ return mark;
+ }
+
+ function wrapNode(node, start, end, annotation) {
+ if (start >= end) return false;
+ try {
+ const range = document.createRange();
+ range.setStart(node, start);
+ range.setEnd(node, end);
+ range.surroundContents(markFor(annotation));
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ function locate(index, target) {
+ if (target.length < 2) return null;
+ let at = index.text.indexOf(target);
+ let length = target.length;
+ if (at < 0 && target.length > 12) {
+ const head = target.slice(0, 12);
+ at = index.text.indexOf(head);
+ length = head.length;
+ }
+ if (at < 0) return null;
+ const start = index.map[at];
+ const end = index.map[Math.min(index.map.length - 1, at + length - 1)];
+ if (!start || !end) return null;
+ return { start, end, at, length };
+ }
+
+ function highlightIn(block, quote, annotation) {
+ const nodes = textNodesIn(block);
+ if (!nodes.length) return false;
+ const found = locate(buildIndex(nodes), normalize(quote));
+ if (!found) return false;
+ const { start, end } = found;
+
+ const range = document.createRange();
+ range.setStart(start.node, start.offset);
+ range.setEnd(end.node, end.offset + 1);
+ try {
+ range.surroundContents(markFor(annotation));
+ return true;
+ } catch {
+ /* The range crosses element boundaries; wrap each covered text node. */
+ }
+
+ const from = nodes.indexOf(start.node);
+ const to = nodes.indexOf(end.node);
+ if (from < 0 || to < from) return false;
+ let touched = false;
+ for (let i = from; i <= to; i += 1) {
+ const node = nodes[i];
+ const startOffset = node === start.node ? start.offset : 0;
+ const endOffset = node === end.node ? end.offset + 1 : node.nodeValue.length;
+ touched = wrapNode(node, startOffset, endOffset, annotation) || touched;
+ }
+ return touched;
+ }
+
+ /** Plain text inside a block-less container: only wrap within one text node. */
+ function highlightSingleNode(quote, annotation) {
+ const target = normalize(quote);
+ if (target.length < 2) return false;
+ for (const node of textNodesIn(document.body)) {
+ const flat = normalize(node.nodeValue);
+ if (flat.length < target.length) continue;
+ let at = flat.indexOf(target);
+ let length = target.length;
+ if (at < 0 && target.length > 12) {
+ at = flat.indexOf(target.slice(0, 12));
+ length = Math.min(12, target.length);
+ }
+ if (at < 0) continue;
+ // Map the normalized index back onto this node's raw text.
+ let rawStart = -1;
+ let seen = 0;
+ let cursor = 0;
+ while (cursor < node.nodeValue.length) {
+ const char = node.nodeValue[cursor];
+ if (/\s/.test(char)) {
+ if (seen > 0) {
+ let lookahead = cursor;
+ while (lookahead < node.nodeValue.length && /\s/.test(node.nodeValue[lookahead])) lookahead += 1;
+ if (lookahead < node.nodeValue.length && seen === at) {
+ rawStart = lookahead;
+ break;
+ }
+ cursor = lookahead;
+ continue;
+ }
+ cursor += 1;
+ continue;
+ }
+ if (seen === at) {
+ rawStart = cursor;
+ break;
+ }
+ seen += 1;
+ cursor += 1;
+ }
+ if (rawStart < 0) return false;
+ let rawEnd = rawStart;
+ let counted = 0;
+ while (rawEnd < node.nodeValue.length && counted < length) {
+ const char = node.nodeValue[rawEnd];
+ if (!/\s/.test(char) || !/\s/.test(node.nodeValue[rawEnd - 1] || '')) counted += 1;
+ rawEnd += 1;
+ }
+ return wrapNode(node, rawStart, rawEnd, annotation);
+ }
+ return false;
+ }
+
+ function applyHighlights() {
+ for (const annotation of cfg.annotations || []) {
+ if (document.querySelector(`mark.wb-hl[data-wb="${annotation.id}"]`)) continue;
+ let done = false;
+ for (const block of document.body.querySelectorAll(BLOCK_SELECTOR)) {
+ if (highlightIn(block, annotation.quote, annotation)) {
+ done = true;
+ break;
+ }
+ }
+ if (!done) highlightSingleNode(annotation.quote, annotation);
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', applyHighlights, { once: true });
+ } else {
+ applyHighlights();
+ }
+
+ /* --------------------------------------------------------------- bubble */
+
+ const host = document.createElement('div');
+ host.style.cssText = 'position:fixed;z-index:2147483647;top:0;left:0;';
+ document.body.appendChild(host);
+ const shadow = host.attachShadow({ mode: 'open' });
+ shadow.innerHTML = `
+
+
+ 添加批注
+
+
+
+ `;
+ const bubble = shadow.querySelector('.bubble');
+ const bubbleText = shadow.querySelector('.txt');
+ let pendingQuote = '';
+
+ function hideBubble() {
+ bubble.classList.remove('show');
+ pendingQuote = '';
+ }
+
+ function showBubble(quote, rect) {
+ pendingQuote = quote;
+ bubbleText.textContent = quote.length > 18 ? `${quote.slice(0, 18)}…` : quote;
+ bubble.style.left = `${Math.max(80, Math.min(window.innerWidth - 80, rect.left + rect.width / 2))}px`;
+ bubble.style.top = `${Math.max(40, rect.top - 6)}px`;
+ bubble.classList.add('show');
+ }
+
+ shadow.querySelectorAll('button').forEach((button) => {
+ button.addEventListener('click', (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!pendingQuote) return;
+ const kind = button.dataset.act === 'ask' ? 'ask' : 'annotate';
+ parent.postMessage({ source, type: kind, quote: pendingQuote }, '*');
+ hideBubble();
+ const selection = window.getSelection();
+ if (selection) selection.removeAllRanges();
+ });
+ });
+
+ document.addEventListener('mouseup', (event) => {
+ if (event.target && event.target.closest && event.target.closest('mark.wb-hl')) return;
+ window.setTimeout(() => {
+ const selection = window.getSelection();
+ const quote = selection ? normalize(selection.toString()) : '';
+ if (!quote || quote.length < 2) {
+ hideBubble();
+ return;
+ }
+ const range = selection.getRangeAt(0);
+ const rect = range.getBoundingClientRect();
+ if (!rect || (!rect.width && !rect.height)) return;
+ showBubble(quote.slice(0, 400), rect);
+ }, 10);
+ });
+
+ document.addEventListener('mousedown', (event) => {
+ // The bubble lives in a shadow root, so event.target arrives retargeted to
+ // the host. composedPath() is the only reliable way to tell a click on the
+ // bubble from a click on the lesson text; getting this wrong clears the
+ // pending quote before the button's click handler reads it.
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
+ if (path.includes(bubble) || path.includes(host) || bubble.contains(event.target)) return;
+ hideBubble();
+ });
+
+ document.addEventListener('scroll', hideBubble, true);
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') hideBubble();
+ });
+
+ document.addEventListener(
+ 'click',
+ (event) => {
+ const link = event.target && event.target.closest ? event.target.closest('a[href]') : null;
+ if (!link) return;
+ const href = link.getAttribute('href') || '';
+ if (!href || href.startsWith('#')) return;
+ // This frame cannot navigate anywhere (opaque origin), so even an external
+ // link is handed to the host to open in a real tab.
+ if (/^https?:/i.test(href)) {
+ event.preventDefault();
+ parent.postMessage({ source, type: 'external', href }, '*');
+ return;
+ }
+ if (href.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(href)) return;
+ // The lesson page cannot reach the workspace API (connect-src 'none'); the
+ // host opens the file panel on the lesson's behalf.
+ event.preventDefault();
+ parent.postMessage(
+ { source, type: 'file', href, text: normalize(link.textContent || ''), rel: cfg.rel || '' },
+ '*',
+ );
+ },
+ true,
+ );
+
+ document.addEventListener('click', (event) => {
+ const mark = event.target && event.target.closest ? event.target.closest('mark.wb-hl') : null;
+ if (!mark) return;
+ event.preventDefault();
+ parent.postMessage({ source, type: 'open', id: mark.dataset.wb }, '*');
+ });
+
+ /* ------------------------------------------------------------- lifecycle */
+
+ parent.postMessage({ source, type: 'ready', rel: cfg.rel || '' }, '*');
+
+ /* ------------------------------------------------------------- theme sync */
+
+ const LIGHT_VARS =
+ ':root{--ink:#1c1b19;--muted:#6b6a66;--line:#0a0a0a14;--paper:#fbfaf7;--surface:#ffffff;' +
+ '--accent:#0b6bcb;--ok:#0f7a3d;--bad:#b42318;--warn:#b45309;--code:#f2f0eb}' +
+ 'html{background:#fbfaf7;color-scheme:light}';
+ const DARK_VARS =
+ ':root{--ink:#ece9e2;--muted:#a09d95;--line:#ffffff1f;--paper:#1e1d1b;--surface:#26251f;' +
+ '--accent:#7db4ff;--ok:#6ee7a8;--bad:#ff9a8f;--warn:#ffc46b;--code:#2b2a24}' +
+ 'html{background:#1e1d1b;color-scheme:dark}';
+
+ let themeStyle = null;
+ function applyHostTheme(theme) {
+ const systemDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ const wantDark = theme === 'dark';
+ const needsOverride = wantDark !== Boolean(systemDark);
+ if (!themeStyle) {
+ themeStyle = document.createElement('style');
+ themeStyle.id = 'wb-theme';
+ document.head.appendChild(themeStyle);
+ }
+ themeStyle.textContent = needsOverride ? (wantDark ? DARK_VARS : LIGHT_VARS) : '';
+ document.documentElement.dataset.wbTheme = wantDark ? 'dark' : 'light';
+ }
+
+ window.addEventListener('message', (event) => {
+ const data = event.data;
+ if (!data || data.source !== 'host') return;
+ if (data.type === 'theme') {
+ applyHostTheme(data.theme);
+ return;
+ }
+ if (data.type === 'font') {
+ const scale = Number(data.scale);
+ document.documentElement.style.zoom = Number.isFinite(scale) && scale !== 1 ? String(scale) : '';
+ return;
+ }
+ if (data.type === 'focus') {
+ const mark = document.querySelector(`mark.wb-hl[data-wb="${data.id}"]`);
+ if (mark) {
+ mark.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ mark.style.outline = '2px solid #f59e0b';
+ window.setTimeout(() => {
+ mark.style.outline = '';
+ }, 1600);
+ }
+ }
+ });
+})();
diff --git a/plugins/meisijiya/learn-workbench/miniapp/miniapp.json b/plugins/meisijiya/learn-workbench/miniapp/miniapp.json
new file mode 100644
index 00000000..80efd86e
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/miniapp.json
@@ -0,0 +1,32 @@
+{
+ "schemaVersion": 1,
+ "artifacts": {
+ "client": [
+ "./miniapp/client"
+ ],
+ "node": [
+ "./miniapp/node"
+ ]
+ },
+ "runtime": {
+ "kind": "process",
+ "entry": "./miniapp/node/server.mjs",
+ "lifecycle": "on-demand"
+ },
+ "surface": {
+ "path": "/workbench",
+ "window": {
+ "width": 1320,
+ "height": 880,
+ "minWidth": 900,
+ "minHeight": 560,
+ "resizable": true,
+ "frame": true
+ }
+ },
+ "agentAccess": [
+ "session.run"
+ ],
+ "agentConcurrency": 4,
+ "mcpEndpoints": []
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/agent.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/agent.mjs
new file mode 100644
index 00000000..09c2955f
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/agent.mjs
@@ -0,0 +1,1350 @@
+import { randomUUID } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { readFile, readdir, stat } from 'node:fs/promises';
+import path from 'node:path';
+
+import {
+ backupCurriculum,
+ cleanCursor,
+ cleanSince,
+ findLesson,
+ getSession,
+ importCurriculum,
+ loadSnapshot,
+ makeMessage,
+ mutateCurriculum,
+ mutateNotes,
+ nodeWriteCursor,
+ normalizeTags,
+ nodeWritesAfter,
+ readCurriculumBackup,
+ readMeta,
+ readMission,
+ readTeacher,
+ reconcileWorkspaceFiles,
+ registerWorkspace,
+ saveSession,
+ sessionSummary,
+ writeContextFile,
+ writeMeta,
+} from './store.mjs';
+import { readText, resolveInside, writeText } from './fsx.mjs';
+import {
+ canWrite,
+ classify,
+ denyMessage,
+ protectedSpecs,
+ rulesPath as contractPath,
+ toPosixRel,
+ underAny,
+} from './policy.mjs';
+import { TEACHER_STYLE_GUARD, resolveTeacher } from './teacher-presets.mjs';
+import { noteTemplateById } from './note-templates.mjs';
+import {
+ buildContextPacket,
+ curriculumPrompt,
+ lessonFileName,
+ lessonRewritePrompt,
+ lessonSeedPrompt,
+ mainSeedPrompt,
+ noteFileName,
+ notePrompt,
+ setupPrompt,
+} from './prompts.mjs';
+
+const ASK_TIMEOUT_MS = 5 * 60 * 1000;
+/** Fixed resume prompt; the original task is already in the session context. */
+const CONTINUE_PROMPT =
+ '继续上一条用户消息对应的任务,从断点接着做。不要回到更早的任务,也不要重做已经完成的部分;涉及文件时先检查当前文件,再补上缺失内容;完成后按原要求自检。';
+
+function continuePromptFor(session) {
+ const last = [...(session.messages || [])]
+ .reverse()
+ .find((message) => message.role === 'user' && message.kind !== 'continue');
+ const task = last && last.text ? String(last.text).slice(0, 1200) : '';
+ return task ? `${CONTINUE_PROMPT}\n\n上一条用户消息:\n${task}` : CONTINUE_PROMPT;
+}
+/** How long a clean waits for an aborted turn to write its last word. */
+const CANCEL_WAIT_MS = 4000;
+
+/** Said once per turn while a ready mission has no readable title line. */
+const MISSION_TITLE_NOTE =
+ 'MISSION.md 的第一行不是「# Mission: 主题」格式,工作台名字没有更新。把它改成这个格式,再重新读取一次就会按标题命名。';
+
+/**
+ * The style is an instruction layer, not a replacement for the contract. It is
+ * prepended to the host prompt but not to the transcript, so the user sees the
+ * same message they sent (or the original seed prompt).
+ */
+async function withTeacherStyle(ws, session, prompt) {
+ if (!prompt || session.kind === 'note') return prompt;
+ try {
+ const active = resolveTeacher(await readTeacher(ws.root));
+ if (!active.prompt) return prompt;
+ return `【老师风格:${active.name}】${active.prompt}\n${TEACHER_STYLE_GUARD}\n\n${prompt}`;
+ } catch {
+ return prompt;
+ }
+}
+
+const READ_TOOLS = new Set([
+ 'read',
+ 'read_file',
+ 'readfile',
+ 'view',
+ 'open_file',
+ 'glob',
+ 'grep',
+ 'rg',
+ 'ls',
+ 'list',
+ 'list_dir',
+ 'list_files',
+ 'listdirectory',
+ 'webfetch',
+ 'web_fetch',
+ 'fetch',
+ 'web_search',
+ 'websearch',
+ 'search',
+ 'todo_write',
+ 'todo',
+ 'todos',
+ 'skill',
+ 'update_plan',
+ 'think',
+]);
+const WRITE_TOOLS = new Set([
+ 'write',
+ 'write_file',
+ 'writefile',
+ 'edit',
+ 'edit_file',
+ 'editfile',
+ 'multiedit',
+ 'multi_edit',
+ 'apply_patch',
+ 'applypatch',
+ 'create_file',
+ 'str_replace_editor',
+ 'str_replace',
+ 'notebook_edit',
+ 'notebookedit',
+ 'patch',
+ 'delete_file',
+ 'mkdir',
+]);
+const SHELL_TOOLS = new Set(['bash', 'shell', 'powershell', 'run_command', 'exec', 'terminal']);
+const DELEGATE_TOOLS = new Set(['task', 'agent', 'spawn_agent', 'launch_agent']);
+
+function toolKey(name) {
+ const raw = String(name ?? '').toLowerCase();
+ const tail = raw.includes('__') ? raw.split('__').pop() : raw;
+ return tail.replace(/[^a-z_]/g, '') || raw;
+}
+
+function collectPaths(input, key = '', out = []) {
+ if (typeof input === 'string') {
+ if (/^(file_?path|path|paths?|target|target_file|filename|file|notebook_path)$/i.test(key)) {
+ out.push(input);
+ }
+ if (/patch|diff/i.test(key) || input.includes('*** Begin Patch')) {
+ for (const match of input.matchAll(/\*\*\* (?:Add|Update|Delete) File: (.+)/g)) {
+ out.push(match[1].trim());
+ }
+ for (const match of input.matchAll(/^\+\+\+ (?:b\/)?(.+)$/gm)) {
+ out.push(match[1].trim());
+ }
+ }
+ return out;
+ }
+ if (Array.isArray(input)) {
+ input.forEach((item) => collectPaths(item, key, out));
+ return out;
+ }
+ if (input && typeof input === 'object') {
+ for (const [childKey, value] of Object.entries(input)) collectPaths(value, childKey, out);
+ }
+ return out;
+}
+
+export function createAgentService({ context, emit, onCurriculumImported }) {
+ const runs = new Map();
+ const ensuring = new Map();
+
+ const keyOf = (wsId, sessionId) => `${wsId}:${sessionId}`;
+
+ const summary = sessionSummary;
+
+ function newRecord({ id, kind, targetId, title }) {
+ const now = Date.now();
+ return {
+ id,
+ kind,
+ targetId,
+ title,
+ createdAt: now,
+ updatedAt: now,
+ messages: [],
+ pending: null,
+ permissions: [],
+ running: null,
+ seeded: false,
+ model: null,
+ };
+ }
+
+ /**
+ * Snapshot every artifact this kind must not write, so a turn that writes one
+ * anyway can be corrected. The cursor lets the restore skip files node itself
+ * touched during the same turn (curriculum, indexes, the session store).
+ */
+ async function snapshotProtected(ws, session) {
+ const files = new Map();
+ const take = async (rel) => {
+ try {
+ const abs = resolveInside(ws.root, rel);
+ const info = await stat(abs);
+ if (!info.isFile() || info.size > 400_000) return;
+ files.set(toPosixRel(rel), await readFile(abs, 'utf8'));
+ } catch {
+ /* missing files are not part of the snapshot */
+ }
+ };
+
+ const specs = protectedSpecs(session.kind);
+ for (const rel of specs.files) await take(rel);
+ for (const entry of specs.dirs) {
+ const dir = path.join(ws.root, entry.dir);
+ const names = await readdir(dir).catch(() => []);
+ const own =
+ entry.own && session.kind === 'lesson' ? toPosixRel(session.targetFile || '').split('/').pop() : '';
+ for (const name of names) {
+ if (name === own) continue;
+ if (entry.exts && !entry.exts.some((ext) => name.toLowerCase().endsWith(ext))) continue;
+ await take(`${entry.dir}/${name}`);
+ }
+ }
+ return { files, cursor: nodeWriteCursor() };
+ }
+
+ async function restoreProtected(ws, snapshot, session, cleanedPaths = []) {
+ if (!snapshot || !snapshot.files || !snapshot.files.size) return [];
+ const touched = nodeWritesAfter(ws.root, snapshot.cursor);
+ const restored = [];
+ for (const [rel, text] of snapshot.files) {
+ if (touched.has(rel)) continue;
+ // Deleted by a clean that started mid-turn: the clean wins over the copy.
+ if (underAny(rel, cleanedPaths)) continue;
+ const abs = resolveInside(ws.root, rel);
+ const current = await readFile(abs, 'utf8').catch(() => null);
+ if (current === text) continue;
+ await writeText(abs, text);
+ restored.push(rel);
+ }
+ if (restored.length) {
+ const hint =
+ {
+ lesson: '这一课只能改自己的课程文件',
+ note: '提炼会话只能写笔记与速查文档',
+ setup: '配置会话只能改 MISSION / RESOURCES / GLOSSARY / NOTES',
+ main: '主会话不直接改课程文件与学习记录',
+ }[session.kind] ?? '这一轮只能改自己负责的文件';
+ session.messages.push(
+ makeMessage('system', `已还原越界修改:${restored.join('、')}。${hint}。`, {
+ kind: 'policy',
+ }),
+ );
+ }
+ return restored;
+ }
+
+ function makeEventHandlers({ ws, session, record }) {
+ return (event) => {
+ if (!event || typeof event !== 'object') return;
+ if (event.type === 'text.delta') {
+ emit(ws.id, { t: 'delta', sessionId: session.id, text: event.text ?? '' });
+ return;
+ }
+ if (event.type === 'tool.started' || event.type === 'tool.finished') {
+ emit(ws.id, {
+ t: 'tool',
+ sessionId: session.id,
+ phase: event.type === 'tool.started' ? 'start' : 'end',
+ name: event.name ?? '',
+ ok: event.ok !== false,
+ });
+ return;
+ }
+ if (event.type === 'permission.requested') {
+ void handlePermission({ ws, session, event, record });
+ return;
+ }
+ if (event.type === 'turn.started') {
+ // The Host is the source of truth for which model actually ran.
+ if (event.model) session.model = event.model;
+ emit(ws.id, { t: 'turn', sessionId: session.id, phase: 'started', model: event.model ?? '' });
+ }
+ };
+ }
+
+ async function createHostSession() {
+ const created = await context.agent.create({});
+ if (!created?.sessionId) {
+ const error = new Error('session_create_failed');
+ error.code = 'SESSION_CREATE_FAILED';
+ throw error;
+ }
+ return created.sessionId;
+ }
+
+ /* ------------------------------------------------------------- deciding */
+
+ function decidePermission(session, event) {
+ const tool = toolKey(event.toolName);
+ const kind = session.kind;
+
+ if (READ_TOOLS.has(tool)) return { decision: 'allowOnce' };
+ if (WRITE_TOOLS.has(tool)) {
+ const targets = collectPaths(event.toolInput ?? {});
+ if (!targets.length) {
+ return { decision: 'ask', reason: '无法判断这次写入的目标路径' };
+ }
+ const relative = targets.filter((target) => !path.isAbsolute(target));
+ if (relative.length) {
+ return {
+ decision: 'deny',
+ note: `已阻止相对路径写入(${relative[0]}):本工作台要求对工作区文件使用绝对路径。`,
+ };
+ }
+ for (const target of targets) {
+ const resolved = path.resolve(target);
+ const rel = path.relative(session.root, resolved);
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
+ return { decision: 'ask', reason: `写入工作区之外的文件:${target}` };
+ }
+ if (!canWrite(kind, rel, session)) {
+ return { decision: 'deny', note: denyMessage(kind, rel, session) };
+ }
+ if (classify(rel).id === 'other') {
+ // Files the workspace does not own may belong to the user's existing
+ // project, so they are never written without an explicit allow.
+ return { decision: 'ask', reason: `这次会写工作台不管理的文件:${rel}` };
+ }
+ }
+ return { decision: 'allowOnce' };
+ }
+ if (SHELL_TOOLS.has(tool) || DELEGATE_TOOLS.has(tool)) {
+ if (kind === 'main') return { decision: 'ask', reason: `主会话请求 ${tool}` };
+ return {
+ decision: 'deny',
+ note: `已阻止 ${tool}:${kind === 'lesson' ? '课程' : '提炼'}会话不执行 shell,也不委派子任务。`,
+ };
+ }
+ return { decision: 'ask', reason: `工具 ${event.toolName} 需要确认` };
+ }
+
+ async function replyPermission(session, event, decision) {
+ try {
+ await context.agent.reply({
+ sessionId: event.sessionId,
+ requestId: event.requestId,
+ decision,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ /* ---------------------------------------------------------------- turns */
+
+ /**
+ * The only entry that starts a turn. A fresh turn pushes the user message and
+ * calls run; a resume keeps the transcript, clears the questionnaire and calls
+ * answer. Everything else — busy check, running marker, snapshot, record,
+ * finalize — happens exactly once here.
+ */
+ async function runTurn({ ws, session, prompt, promptKind, resume, hostPrompt: hostText }) {
+ // Read before anything is written: a clean that lands after this point owns
+ // the files, and this turn must not write them back when it finalizes.
+ const turnFrom = cleanCursor();
+ const key = keyOf(ws.id, session.id);
+ if (runs.has(key)) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+
+ // The merge after the turn needs the curriculum as it was before the agent
+ // rewrites it: lesson files, statuses and session bindings live there. A
+ // backup taken at generation time is too old to carry them between turns.
+ if (session.kind === 'main') await backupCurriculum(ws.root);
+
+ const requestId = randomUUID();
+ if (!resume) {
+ const isSeed = (session.messages?.length ?? 0) === 0;
+ const kind = isSeed ? 'seed' : promptKind || '';
+ session.messages.push(makeMessage('user', prompt, kind ? { kind } : {}));
+ }
+ session.running = { requestId, startedAt: Date.now() };
+ session.interrupted = false;
+ session.pending = null;
+ session.updatedAt = Date.now();
+ session.root = ws.root;
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+
+ const controller = new AbortController();
+ let settle = () => {};
+ const done = new Promise((resolve) => {
+ settle = resolve;
+ });
+ const record = {
+ controller,
+ startedAt: Date.now(),
+ permissionTimers: new Map(),
+ protected: null,
+ cleanCursor: turnFrom,
+ done,
+ };
+ // Visible to cancelAll from the start; a failed snapshot only means there is
+ // nothing to restore later.
+ runs.set(key, record);
+ record.protected = await snapshotProtected(ws, session).catch(() => null);
+
+ const onEvent = makeEventHandlers({ ws, session, record });
+
+ void (async () => {
+ let result = null;
+ let failure = null;
+ try {
+ if (resume) {
+ result = await context.agent.answer(
+ {
+ sessionId: session.id,
+ requestId: resume.requestId,
+ answers: resume.answers,
+ ...(session.model ? { model: session.model } : {}),
+ },
+ { signal: controller.signal, onEvent },
+ );
+ } else {
+ const textForHost = await withTeacherStyle(ws, session, hostText || prompt);
+ result = await context.agent.run(
+ { text: textForHost, sessionId: session.id, ...(session.model ? { model: session.model } : {}) },
+ { signal: controller.signal, onEvent },
+ );
+ }
+ } catch (error) {
+ failure = error;
+ }
+ // A questionnaire that never reached the Host can be answered again.
+ const retryable =
+ failure && (failure.code === 'AGENT_UNAVAILABLE' || failure.code === 'REQUEST_CANCELLED');
+ try {
+ await finalizeTurn({
+ ws,
+ session,
+ result,
+ failure,
+ record,
+ preservedPending: resume && retryable ? resume.pending : null,
+ });
+ } finally {
+ // Stay in runs until the last write is done: cancelAll waits on done.
+ runs.delete(key);
+ settle();
+ }
+ })();
+
+ return { requestId };
+ }
+
+ async function handlePermission({ ws, session, event, record }) {
+ const decision = decidePermission(session, event);
+
+ if (decision.decision !== 'ask') {
+ const settled = await replyPermission(session, event, decision.decision);
+ if (!settled) {
+ // The automatic reply failed, so the run would wait forever. Surface
+ // the request as a manual card instead of dropping it.
+ const pending = {
+ requestId: event.requestId,
+ agentSessionId: event.sessionId,
+ toolName: event.toolName,
+ reason: '自动处理失败,请手动决定',
+ at: Date.now(),
+ };
+ session.permissions = [...(session.permissions || []), pending];
+ session.messages.push(
+ makeMessage('system', `自动授权失败:${event.toolName}。请在会话里手动允许或拒绝。`, {
+ kind: 'policy',
+ }),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ return;
+ }
+ if (decision.note) {
+ session.messages.push(makeMessage('system', decision.note, { kind: 'policy' }));
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ }
+ emit(ws.id, {
+ t: 'permission',
+ sessionId: session.id,
+ toolName: event.toolName,
+ auto: decision.decision,
+ note: decision.note ?? '',
+ });
+ return;
+ }
+
+ const pending = {
+ requestId: event.requestId,
+ agentSessionId: event.sessionId,
+ toolName: event.toolName,
+ reason: decision.reason ?? event.reason ?? '',
+ at: Date.now(),
+ };
+ // Several tools can ask at once; every request keeps its own card and timer.
+ session.permissions = [
+ ...(session.permissions || []).filter((item) => item.requestId !== event.requestId),
+ pending,
+ ];
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+
+ const timer = setTimeout(() => {
+ void (async () => {
+ const still = (session.permissions || []).find((item) => item.requestId === event.requestId);
+ if (!still) return;
+ await replyPermission(session, event, 'deny');
+ session.permissions = (session.permissions || []).filter(
+ (item) => item.requestId !== event.requestId,
+ );
+ session.messages.push(
+ makeMessage('system', '这次工具调用等待了 5 分钟无人处理,已自动拒绝。', { kind: 'policy' }),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ })();
+ }, ASK_TIMEOUT_MS);
+ if (timer.unref) timer.unref();
+ record.permissionTimers.set(event.requestId, timer);
+ }
+
+ async function finalizeTurn({ ws, session, result, failure, record, preservedPending }) {
+ const status = result?.status ?? (failure ? 'error' : 'finished');
+ const reply = result?.text ?? '';
+
+ for (const timer of record?.permissionTimers?.values?.() ?? []) clearTimeout(timer);
+ record?.permissionTimers?.clear?.();
+
+ // 「清理产物」 that started after this turn did owns the files. A deleted
+ // state directory must not be written back, and a deleted artifact must not
+ // be restored from the protected snapshot.
+ const cleans = cleanSince(ws.root, record?.cleanCursor ?? 0);
+ const cleanedPaths = cleans.flatMap((entry) => entry.paths);
+ if (cleans.some((entry) => entry.keys.includes('state'))) {
+ // The workspace's state is gone: saving the transcript would recreate it
+ // and bring the cleaned workspace back. An out-of-scope write is still
+ // reverted (that file is not under the cleaned paths), but nothing is
+ // persisted and no post-turn bookkeeping runs.
+ if (record?.protected) {
+ try {
+ await restoreProtected(ws, record.protected, session, cleanedPaths);
+ } catch {
+ /* A restore failure is reported, never fatal. */
+ }
+ }
+ return;
+ }
+
+ if (reply.trim()) {
+ session.messages.push(makeMessage('assistant', reply, { status }));
+ }
+ if (failure) {
+ const code = failure?.code ?? failure?.message ?? 'unknown';
+ session.messages.push(
+ makeMessage(
+ 'system',
+ /cancel|abort/i.test(String(code))
+ ? '这一轮已暂停。点「继续」从断点接着做。'
+ : `这一轮没有跑完(${code})。点「继续」重试,或直接输入新的要求。`,
+ { kind: /cancel|abort/i.test(String(code)) ? 'policy' : 'error' },
+ ),
+ );
+ } else if (status === 'error') {
+ session.messages.push(
+ makeMessage('system', `这一轮以错误结束${result?.error ? `:${result.error}` : ''}。可以点「继续」重试。`, {
+ kind: 'error',
+ }),
+ );
+ } else if (status === 'aborted') {
+ session.messages.push(makeMessage('system', '这一轮已暂停。可以点「继续」从断点接着做。', { kind: 'policy' }));
+ }
+
+ const pendingQuestion = Boolean(result?.pendingQuestion);
+ const interrupted =
+ !pendingQuestion &&
+ !preservedPending &&
+ (status === 'aborted' || status === 'error' || Boolean(failure));
+ session.pending = result?.pendingQuestion
+ ? {
+ kind: 'question',
+ requestId: result.pendingQuestion.requestId,
+ request: result.pendingQuestion.request,
+ at: Date.now(),
+ }
+ : preservedPending ?? null;
+ if (preservedPending) {
+ session.messages.push(
+ makeMessage('system', '这次回答没有送达,可以重新提交一次。', { kind: 'policy' }),
+ );
+ }
+ session.permissions = [];
+ session.running = null;
+ session.interrupted = interrupted;
+ session.updatedAt = Date.now();
+
+ if (record?.protected) {
+ try {
+ await restoreProtected(ws, record.protected, session, cleanedPaths);
+ } catch {
+ /* A restore failure is reported, never fatal. */
+ }
+ }
+
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+
+ try {
+ await afterTurn({
+ ws,
+ session,
+ result,
+ failure,
+ cleanedKeys: new Set(cleans.flatMap((entry) => entry.keys)),
+ });
+ } catch {
+ /* A refresh failure never invalidates the stored turn. */
+ }
+ emit(ws.id, { t: 'state' });
+ }
+
+ /**
+ * Keep the workspace name in step with the mission title. Setup and main are the
+ * two kinds that may rewrite MISSION.md. A ready mission without a readable
+ * title line is reported once instead of silently keeping the directory name.
+ */
+ async function syncWorkspaceName({ ws, session }) {
+ const mission = readMission(await readText(path.join(ws.root, 'MISSION.md'), ''));
+ if (!mission.ready) return;
+ if (mission.title) {
+ await registerWorkspace(ws.root, { name: mission.title, touch: false });
+ return;
+ }
+ const said = session.messages.some(
+ (message) => message.role === 'system' && message.text === MISSION_TITLE_NOTE,
+ );
+ if (said) return;
+ session.messages.push(makeMessage('system', MISSION_TITLE_NOTE, { kind: 'policy' }));
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ }
+
+ async function afterTurn({ ws, session, result, cleanedKeys = new Set() }) {
+ const meta = await readMeta(ws.root);
+ if (session.kind === 'setup') {
+ await syncWorkspaceName({ ws, session });
+ return;
+ }
+ if (session.kind === 'main') {
+ // The Agent rewrites curriculum.json from scratch; merge it onto the
+ // pre-turn snapshot so lesson sessions, files and status survive.
+ const backup = await readCurriculumBackup(ws.root);
+ const imported = await importCurriculum(ws.root, meta, backup ? { previous: backup } : {});
+ if (imported.curriculum.modules.length && onCurriculumImported) {
+ onCurriculumImported(ws);
+ }
+ // The merge carries lesson files over from the pre-turn backup; a clean
+ // that deleted them mid-turn must not get those paths back.
+ if (cleanedKeys.has('lessons')) {
+ await reconcileWorkspaceFiles(ws.root, { lessons: true });
+ }
+ await syncWorkspaceName({ ws, session });
+ return;
+ }
+ if (session.kind === 'lesson') {
+ const snap = await loadSnapshot(ws);
+ const lesson = findLesson(snap.curriculum, session.targetId);
+ if (!lesson) return;
+ // The target is fixed before the turn. A file under another name is not
+ // this lesson's result, so it is never adopted.
+ const target = session.targetFile || lesson.file;
+ if (!target || !existsSync(resolveInside(ws.root, target))) {
+ session.messages.push(
+ makeMessage(
+ 'system',
+ cleanedKeys.has('lessons')
+ ? '「清理产物」删除了课程 HTML,这一轮生成的内容没有保留。可以再问一次重新生成。'
+ : `这一轮没有写成本课文件${target ? `(期望 ${target})` : ''}。可以再问一次,或检查它是否写到了别的文件名。`,
+ { kind: 'policy' },
+ ),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ return;
+ }
+ await mutateCurriculum(ws.root, meta, (curriculum) => {
+ const current = findLesson(curriculum, session.targetId);
+ if (!current) return null;
+ current.file = target;
+ current.sessionId = session.id;
+ if (current.status === 'planned') current.status = 'active';
+ return curriculum;
+ });
+ return;
+ }
+ if (session.kind === 'note') {
+ const target = session.targetFile || '';
+ const found = Boolean(target && existsSync(resolveInside(ws.root, target)));
+ const tags = found ? await takeNoteTags(ws.root, target) : null;
+ await mutateNotes(ws.root, (notes) => {
+ const item = notes.items.find((entry) => entry.id === session.targetId);
+ if (!item) return null;
+ item.status = found ? 'ready' : 'failed';
+ if (found) item.path = target;
+ if (tags) item.tags = tags;
+ item.updatedAt = Date.now();
+ return notes;
+ });
+ }
+ }
+
+ /* ------------------------------------------------------------- opening */
+
+ async function ensureMainSession(ws) {
+ const meta = await readMeta(ws.root);
+ if (meta?.mainSessionId) {
+ const existing = await getSession(ws.root, meta.mainSessionId);
+ if (existing) return { session: existing, meta };
+ }
+ const sessionKey = `main:${ws.id}`;
+ if (ensuring.has(sessionKey)) return ensuring.get(sessionKey);
+ const task = (async () => {
+ const sid = await createHostSession();
+ const session = newRecord({ id: sid, kind: 'main', targetId: '', title: '主会话' });
+ await saveSession(ws.root, session);
+ const freshMeta = (await readMeta(ws.root)) ?? {};
+ await writeMeta(ws.root, { ...freshMeta, id: ws.id, mainSessionId: sid });
+ return { session, meta: { ...freshMeta, mainSessionId: sid } };
+ })();
+ ensuring.set(sessionKey, task);
+ try {
+ return await task;
+ } finally {
+ ensuring.delete(sessionKey);
+ }
+ }
+
+ async function ensureSetupSession(ws) {
+ const meta = await readMeta(ws.root);
+ if (meta?.setupSessionId) {
+ const existing = await getSession(ws.root, meta.setupSessionId);
+ if (existing) return { session: existing, meta };
+ }
+ const sessionKey = `setup:${ws.id}`;
+ if (ensuring.has(sessionKey)) return ensuring.get(sessionKey);
+ const task = (async () => {
+ const sid = await createHostSession();
+ const session = newRecord({ id: sid, kind: 'setup', targetId: '', title: '配置 · 学习工作台' });
+ await saveSession(ws.root, session);
+ const freshMeta = (await readMeta(ws.root)) ?? {};
+ await writeMeta(ws.root, { ...freshMeta, id: ws.id, setupSessionId: sid });
+ return { session, meta: { ...freshMeta, setupSessionId: sid } };
+ })();
+ ensuring.set(sessionKey, task);
+ try {
+ return await task;
+ } finally {
+ ensuring.delete(sessionKey);
+ }
+ }
+
+ /** Start the front-matter configuration conversation (once). */
+ async function seedSetup(ws) {
+ const { session } = await ensureSetupSession(ws);
+ if (session.seeded || (session.messages?.length ?? 0) > 0) {
+ return { sessionId: session.id, started: false };
+ }
+ const rulesPath = contractPath(ws.root);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: setupPrompt({ workspace: { ...ws, name: ws.name || path.basename(ws.root) }, rulesPath }),
+ });
+ return { sessionId: session.id, started: true };
+ }
+
+ async function openSetup(ws) {
+ const result = await seedSetup(ws);
+ const session = await getSession(ws.root, result.sessionId);
+ return {
+ sessionId: result.sessionId,
+ started: Boolean(result.started),
+ session: session ? summary(session) : null,
+ };
+ }
+
+ async function ensureLessonSession(ws, lessonId) {
+ const sessionKey = `lesson:${ws.id}:${lessonId}`;
+ if (ensuring.has(sessionKey)) return ensuring.get(sessionKey);
+ const task = (async () => {
+ const snap = await loadSnapshot(ws);
+ const lesson = findLesson(snap.curriculum, lessonId);
+ if (!lesson) {
+ const error = new Error('lesson_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ if (lesson.sessionId) {
+ const existing = await getSession(ws.root, lesson.sessionId);
+ if (existing) return { session: existing, lesson };
+ }
+ const sid = await createHostSession();
+ const target = lesson.file || lessonFileName(lesson);
+ const session = newRecord({
+ id: sid,
+ kind: 'lesson',
+ targetId: lesson.id,
+ title: `第 ${lesson.no} 课 · ${lesson.title}`,
+ });
+ session.targetFile = target;
+ await saveSession(ws.root, session);
+ const meta = await readMeta(ws.root);
+ await mutateCurriculum(ws.root, meta, (curriculum) => {
+ const current = findLesson(curriculum, lessonId);
+ if (!current) return null;
+ current.sessionId = sid;
+ return curriculum;
+ });
+ return { session, lesson: { ...lesson, sessionId: sid } };
+ })();
+ ensuring.set(sessionKey, task);
+ try {
+ return await task;
+ } finally {
+ ensuring.delete(sessionKey);
+ }
+ }
+
+ async function seedMain(ws) {
+ const { session, meta } = await ensureMainSession(ws);
+ if (session.seeded || (session.messages?.length ?? 0) > 0) {
+ return { sessionId: session.id, started: false };
+ }
+ const snap = await loadSnapshot(ws);
+ const hasMission = Boolean(snap.workspace.configured);
+ const rulesPath = contractPath(ws.root);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: mainSeedPrompt({ workspace: { ...ws, root: ws.root }, rulesPath, hasMission }),
+ });
+ return { sessionId: session.id, started: true };
+ }
+
+ async function seedLesson(ws, lessonId) {
+ const { session, lesson } = await ensureLessonSession(ws, lessonId);
+ // A lesson whose file the curriculum already claims is read, not generated:
+ // 「重新生成」 owns that case. A missing file — cleaned, or deleted by hand —
+ // is the one state where the same session may be seeded again, so the button
+ // that starts a lesson keeps working after 「清理产物」.
+ if (lesson.file && existsSync(resolveInside(ws.root, lesson.file))) {
+ return { sessionId: session.id, started: false };
+ }
+ // No file yet, but the session is already busy or waiting for an answer:
+ // seeding would start a second turn and clear the questionnaire. Refuse it;
+ // the caller opens the session as it stands instead.
+ if (session.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ if (session.pending) {
+ const error = new Error('answer_pending');
+ error.code = 'ANSWER_PENDING';
+ throw error;
+ }
+ const snap = await loadSnapshot(ws);
+ const main = snap.workspace.mainSessionId ? await getSession(ws.root, snap.workspace.mainSessionId) : null;
+ const target = session.targetFile || lesson.file || lessonFileName(lesson);
+ const rulesPath = contractPath(ws.root);
+ const packet = buildContextPacket({
+ workspace: { name: ws.name, root: ws.root, mission: snap.mission },
+ curriculum: snap.curriculum,
+ lesson,
+ records: snap.records,
+ mainSession: main,
+ });
+ await writeContextFile(ws.root, `lesson-${String(lesson.no).padStart(4, '0')}`, packet);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: lessonSeedPrompt({
+ workspace: { ...ws, name: ws.name },
+ rulesPath,
+ lesson,
+ target,
+ contextPacket: packet,
+ }),
+ promptKind: 'seed',
+ });
+ return { sessionId: session.id, started: true };
+ }
+
+ async function openLesson(ws, lessonId, { seed = true } = {}) {
+ let sessionId = '';
+ let started = false;
+ if (seed) {
+ const result = await seedLesson(ws, lessonId);
+ sessionId = result.sessionId;
+ started = Boolean(result.started);
+ } else {
+ const result = await ensureLessonSession(ws, lessonId);
+ sessionId = result.session.id;
+ }
+ const session = await getSession(ws.root, sessionId);
+ return {
+ sessionId,
+ started,
+ session: session ? summary(session) : null,
+ };
+ }
+
+ /**
+ * Rewrite one lesson in place: the same branch session and the same target
+ * file. Unlike a follow-up this asks for the whole lesson, and unlike seeding
+ * it runs even when the session already has a transcript.
+ */
+ async function regenerateLesson(ws, lessonId) {
+ const { session, lesson } = await ensureLessonSession(ws, lessonId);
+ if (session.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ if (session.pending) {
+ const error = new Error('answer_pending');
+ error.code = 'ANSWER_PENDING';
+ throw error;
+ }
+ const snap = await loadSnapshot(ws);
+ const main = snap.workspace.mainSessionId ? await getSession(ws.root, snap.workspace.mainSessionId) : null;
+ const target = session.targetFile || lesson.file || lessonFileName(lesson);
+ session.targetFile = target;
+ const rulesPath = contractPath(ws.root);
+ const packet = buildContextPacket({
+ workspace: { name: ws.name, root: ws.root, mission: snap.mission },
+ curriculum: snap.curriculum,
+ lesson,
+ records: snap.records,
+ mainSession: main,
+ });
+ await writeContextFile(ws.root, `lesson-${String(lesson.no).padStart(4, '0')}`, packet);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: lessonRewritePrompt({
+ workspace: { ...ws, name: ws.name },
+ rulesPath,
+ lesson,
+ target,
+ contextPacket: packet,
+ }),
+ promptKind: 'rewrite',
+ });
+ return { sessionId: session.id, started: true, target };
+ }
+ /**
+ * Start a follow-up branch for a lesson with a fresh Host session.
+ * The old session record stays on disk; the lesson points at the new one, so a
+ * long chain of questions never runs on an unbounded context.
+ */
+ async function renewLesson(ws, lessonId) {
+ const snap = await loadSnapshot(ws);
+ const lesson = findLesson(snap.curriculum, lessonId);
+ if (!lesson) {
+ const error = new Error('lesson_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ const previous = lesson.sessionId ? await getSession(ws.root, lesson.sessionId) : null;
+ if (previous?.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ const previousTurns = (previous?.messages ?? []).filter((message) => message.role === 'assistant').length;
+ const lastReply =
+ (previous?.messages ?? []).filter((message) => message.role === 'assistant').slice(-1)[0]?.text ?? '';
+ const main = snap.workspace.mainSessionId ? await getSession(ws.root, snap.workspace.mainSessionId) : null;
+ const target = lesson.file || lessonFileName(lesson);
+ const packet = buildContextPacket({
+ workspace: { name: ws.name, root: ws.root, mission: snap.mission },
+ curriculum: snap.curriculum,
+ lesson,
+ records: snap.records,
+ mainSession: main,
+ });
+ const sessionId = await createHostSession();
+ const session = newRecord({
+ id: sessionId,
+ kind: 'lesson',
+ targetId: lessonId,
+ title: `第 ${lesson.no} 课 · 续 ${previousTurns + 1}`,
+ });
+ session.targetFile = target;
+ session.seeded = true;
+ session.model = previous?.model ?? null;
+ await saveSession(ws.root, session);
+ await mutateCurriculum(ws.root, {}, (curriculum) => {
+ const current = findLesson(curriculum, lessonId);
+ if (!current) return null;
+ current.sessionId = sessionId;
+ return curriculum;
+ });
+ const prompt = [
+ `你是第 ${lesson.no} 课的追问续接会话(${session.title})。`,
+ `工作台:${ws.root}`,
+ `规则(先读):${contractPath(ws.root)}`,
+ `本课文件:${path.join(ws.root, target)}(已存在,不要重写整节课,只回答追问。)`,
+ lastReply ? `上一次会话的结论摘要:\n${lastReply.slice(0, 1500)}` : '',
+ packet ? `— 本课上下文 —\n${packet}\n— 上下文结束 —` : '',
+ '用户即将继续追问这一课。先用一句话确认你已接手这一课的上下文(不超过 40 字),不要重复课程内容,也不要生成新课件。',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+ await runTurn({ ws, session, prompt });
+ return { sessionId, started: true, session: summary(session) };
+ }
+
+ /* ------------------------------------------------------------ messaging */
+
+ async function send(ws, sessionId, text) {
+ const session = await getSession(ws.root, sessionId);
+ if (!session) {
+ const error = new Error('session_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ session.root = ws.root;
+ return runTurn({ ws, session, prompt: String(text ?? '').trim() });
+ }
+
+ async function answer(ws, sessionId, requestId, answers) {
+ const session = await getSession(ws.root, sessionId);
+ if (!session) {
+ const error = new Error('session_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ const pending = session.pending;
+ if (!pending || pending.kind !== 'question' || (requestId && pending.requestId !== requestId)) {
+ const error = new Error('no_pending_question');
+ error.code = 'NO_QUESTION';
+ throw error;
+ }
+ await runTurn({
+ ws,
+ session,
+ resume: { requestId: pending.requestId, answers, pending },
+ });
+ return { started: true };
+ }
+
+ async function reply(ws, sessionId, requestId, decision) {
+ const session = await getSession(ws.root, sessionId);
+ const pending = (session?.permissions || []).find((item) => item.requestId === requestId);
+ if (!session || !pending) {
+ const error = new Error('no_pending_permission');
+ error.code = 'NO_PERMISSION';
+ throw error;
+ }
+ try {
+ await context.agent.reply({
+ sessionId: pending.agentSessionId ?? session.id,
+ requestId,
+ decision,
+ });
+ } catch (error) {
+ const failed = new Error(error?.code ?? 'reply_failed');
+ failed.code = error?.code ?? 'REPLY_FAILED';
+ throw failed;
+ }
+ const record = runs.get(keyOf(ws.id, session.id));
+ const timer = record?.permissionTimers?.get(requestId);
+ if (timer) {
+ clearTimeout(timer);
+ record.permissionTimers.delete(requestId);
+ }
+ session.permissions = (session.permissions || []).filter((item) => item.requestId !== requestId);
+ session.messages.push(
+ makeMessage('system', decision === 'allowOnce' ? '已允许这次工具调用。' : '已拒绝这次工具调用。', {
+ kind: 'policy',
+ }),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ return { ok: true };
+ }
+
+ async function continueTurn(ws, sessionId) {
+ const session = await getSession(ws.root, sessionId);
+ if (!session) {
+ const error = new Error('session_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ if (session.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ if (session.pending) {
+ const error = new Error('answer_pending');
+ error.code = 'ANSWER_PENDING';
+ throw error;
+ }
+ const last = [...(session.messages || [])]
+ .reverse()
+ .find((message) => message.role === 'user' && message.kind !== 'continue');
+ const isTask = Boolean(last && ['seed', 'task', 'rewrite'].includes(last.kind));
+ // A chat question is resumed as itself, not as a meta "continue the task"
+ // instruction: the latter makes a lesson session go back and edit its file.
+ if (last && last.text && !isTask) {
+ session.messages.push(
+ makeMessage(
+ 'system',
+ '这是一次聊天追问的继续,不是课程生成任务。只回答最后一条用户消息;除非它明确要求,否则不要修改任何课程文件。',
+ { kind: 'policy' },
+ ),
+ );
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: last.text,
+ hostPrompt: last.text,
+ promptKind: 'continue',
+ });
+ } else {
+ await runTurn({ ws, session, prompt: continuePromptFor(session), promptKind: 'continue' });
+ }
+ return { sessionId: session.id, started: true };
+ }
+
+ function cancel(ws, sessionId) {
+ const record = runs.get(keyOf(ws.id, sessionId));
+ if (!record) return false;
+ record.controller.abort();
+ return true;
+ }
+
+ /**
+ * Stop every running turn of one workspace and wait for their finalize.
+ * A caller that deletes workspace files must await this before it touches disk.
+ */
+ async function cancelAll(ws) {
+ const prefix = `${ws.id}:`;
+ const records = [];
+ for (const [key, record] of runs) {
+ if (!key.startsWith(prefix)) continue;
+ records.push(record);
+ record.controller.abort();
+ }
+ if (!records.length) return 0;
+ // A host that ignores the abort must not block the clean forever; whatever
+ // lands late is caught by the finalize gate.
+ await Promise.race([
+ Promise.all(records.map((record) => record.done)),
+ new Promise((resolve) => {
+ const timer = setTimeout(resolve, CANCEL_WAIT_MS);
+ if (timer.unref) timer.unref();
+ }),
+ ]);
+ return records.length;
+ }
+
+ /* -------------------------------------------------------------- notes */
+
+ const NOTE_TAGS_LINE = /^(?:\uFEFF)?[ \t\r\n]*`?[ \t]*[ \t]*`?[ \t]*\r?\n?/i;
+
+ /** The note prompt writes one tag line first; move it into the index and drop it. */
+ async function takeNoteTags(root, rel) {
+ const file = resolveInside(root, rel);
+ const raw = await readText(file, '');
+ const match = raw.match(NOTE_TAGS_LINE);
+ if (!match) return null;
+ const tags = normalizeTags(match[1].split(/[,,、]/));
+ await writeText(file, raw.slice(match[0].length).replace(/^\s*\n/, ''));
+ return tags.length ? tags : null;
+ }
+
+ async function startNoteJob(ws, { lessonIds, title, templateId, noteId, request }) {
+ const snap = await loadSnapshot(ws);
+ const existing = noteId ? (snap.notes || []).find((item) => item.id === noteId) : null;
+ if (noteId && !existing) {
+ const error = new Error('note_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ // Regenerating keeps the note's own scope and target file; a new note takes
+ // whatever the picker sent.
+ const scope = existing ? existing.lessonIds : lessonIds;
+ const lessons = scope
+ .map((id) => findLesson(snap.curriculum, id))
+ .filter((lesson) => lesson && lesson.file);
+ if (!lessons.length) {
+ const error = new Error('no_lessons_with_files');
+ error.code = 'NO_LESSONS';
+ throw error;
+ }
+ const template = noteTemplateById(existing ? existing.templateId : templateId);
+ const scoped = snap.annotations.filter((item) => lessons.some((lesson) => lesson.id === item.lessonId));
+ const safeTitle =
+ (existing ? existing.title : String(title ?? '').trim()) ||
+ `第 ${lessons.map((l) => l.no).join('、')} 课笔记`;
+ if (existing && existing.sessionId) {
+ const previous = await getSession(ws.root, existing.sessionId);
+ if (previous && previous.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ }
+ let target = existing ? existing.path : '';
+ if (!target) {
+ // A running note has no file yet, so also avoid paths already claimed by a note record.
+ const taken = new Set((snap.notes || []).map((item) => item.path));
+ target = noteFileName(safeTitle);
+ let suffix = 2;
+ while (taken.has(target) || existsSync(resolveInside(ws.root, target))) {
+ target = noteFileName(safeTitle).replace(/\.md$/, `-${suffix}.md`);
+ suffix += 1;
+ }
+ }
+ const id = existing ? existing.id : `n_${randomUUID().slice(0, 8)}`;
+ const sid = await createHostSession();
+ const session = newRecord({
+ id: sid,
+ kind: 'note',
+ targetId: id,
+ title: `${existing ? '重写' : '提炼'} · ${safeTitle}`,
+ });
+ session.targetFile = target;
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await mutateNotes(ws.root, (notes) => {
+ const item = notes.items.find((entry) => entry.id === id);
+ if (item) {
+ item.status = 'running';
+ item.sessionId = sid;
+ item.path = target;
+ item.updatedAt = Date.now();
+ return notes;
+ }
+ notes.items.unshift({
+ id,
+ title: safeTitle,
+ path: target,
+ lessonIds: lessons.map((lesson) => lesson.id),
+ sessionId: sid,
+ status: 'running',
+ templateId: template.id,
+ tags: [],
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ return notes;
+ });
+ const rulesPath = contractPath(ws.root);
+ await runTurn({
+ ws,
+ session,
+ prompt: notePrompt({
+ workspace: ws,
+ rulesPath,
+ title: safeTitle,
+ target,
+ lessons,
+ annotations: scoped,
+ template,
+ request: String(request ?? '').trim().slice(0, 600),
+ }),
+ });
+ return { noteId: id, sessionId: sid, path: target };
+ }
+
+ async function curriculumTurn(ws) {
+ const snap = await loadSnapshot(ws);
+ if (!snap.workspace.configured) {
+ const error = new Error('setup_required');
+ error.code = 'SETUP_REQUIRED';
+ throw error;
+ }
+ const { session } = await ensureMainSession(ws);
+ const rulesPath = contractPath(ws.root);
+ // runTurn backs the curriculum up before the rewrite; importCurriculum merges
+ // lesson state back from it after the turn.
+ await runTurn({
+ ws,
+ session,
+ prompt: curriculumPrompt({ workspace: ws, rulesPath }),
+ promptKind: 'task',
+ });
+ return { sessionId: session.id };
+ }
+
+ function abortAll() {
+ for (const record of runs.values()) {
+ for (const timer of record.permissionTimers?.values?.() ?? []) clearTimeout(timer);
+ record.permissionTimers?.clear?.();
+ try {
+ record.controller.abort();
+ } catch {
+ /* ignore */
+ }
+ }
+ runs.clear();
+ }
+
+ return {
+ openLesson,
+ regenerateLesson,
+ renewLesson,
+ openSetup,
+ seedMain,
+ ensureMainSession,
+ send,
+ answer,
+ reply,
+ cancel,
+ continueTurn,
+ cancelAll,
+ startNoteJob,
+ curriculumTurn,
+ abortAll,
+ };
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/check-paths.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/check-paths.mjs
new file mode 100644
index 00000000..d2264581
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/check-paths.mjs
@@ -0,0 +1,60 @@
+/**
+ * Path vocabulary guard.
+ *
+ * node check-paths.mjs → the manual check, with an exit code
+ * import { checkPaths } → the runtime's startup self-check
+ *
+ * It fails when a module keeps its own copy of a workspace path, or when the
+ * declared layout no longer matches what the app builds. Importing this module
+ * has no side effect, so the server can run it without taking the app down.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import { artifactPaths, rulesPath, workbenchPaths } from './policy.mjs';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const skip = new Set(['policy.mjs', 'check-paths.mjs']);
+const forbidden = [/\.workbench/, /lessons\//, /notes\//, /reference\//, /learning-records\//, /assets\//, /teach\.md/];
+
+export function checkPaths() {
+ const failures = [];
+ for (const file of fs.readdirSync(here).filter((name) => name.endsWith('.mjs') && !skip.has(name))) {
+ const lines = fs.readFileSync(path.join(here, file), 'utf8').split(/\r?\n/);
+ lines.forEach((line, index) => {
+ if (forbidden.some((pattern) => pattern.test(line))) {
+ failures.push(`${file}:${index + 1} ${line.trim()}`);
+ }
+ });
+ }
+
+ const expected = {
+ lesson: 'lessons',
+ notes: 'notes',
+ reference: 'reference',
+ records: 'learning-records',
+ assets: 'assets',
+ };
+ for (const [id, dir] of Object.entries(expected)) {
+ const actual = artifactPaths(id)[0];
+ if (actual !== dir) failures.push(`artifactPaths(${id}) = ${actual}, expected ${dir}`);
+ }
+
+ const root = path.resolve('/tmp/workspace-check');
+ const paths = workbenchPaths(root);
+ if (paths.rules !== rulesPath(root)) failures.push('rules path mismatch');
+ if (!paths.curriculum.endsWith('curriculum.json')) failures.push('curriculum path mismatch');
+
+ return { ok: failures.length === 0, failures };
+}
+
+const entry = process.argv[1] ? pathToFileURL(process.argv[1]).href : '';
+if (entry === import.meta.url) {
+ const { ok, failures } = checkPaths();
+ if (!ok) {
+ console.error(failures.join('\n'));
+ process.exit(1);
+ }
+ process.stderr.write('path vocabulary OK\n');
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/clean.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/clean.mjs
new file mode 100644
index 00000000..725623b3
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/clean.mjs
@@ -0,0 +1,97 @@
+import { existsSync } from 'node:fs';
+import { rm } from 'node:fs/promises';
+
+import { resolveInside } from './fsx.mjs';
+import { artifactPaths, WORKBENCH_DIR } from './policy.mjs';
+import { forgetWorkspace, markClean, reconcileWorkspaceFiles, workspaceId } from './store.mjs';
+
+/**
+ * What 「清理产物」 offers, and what each key deletes.
+ *
+ * Paths come from the artifact table — the clean view owns only the clean
+ * semantics: which artifacts form one key, which keys start selected, and which
+ * side effects follow a deletion. Callers (the route, the client, the tests)
+ * ask this module instead of keeping their own copy of the list.
+ */
+const dirLabel = (id) => artifactPaths(id)[0] + '/';
+
+const ROWS = [
+ { key: 'lessons', ids: ['lesson'], label: dirLabel('lesson'), hint: '课程 HTML', default: true },
+ { key: 'reference', ids: ['reference'], label: dirLabel('reference'), hint: '速查文档', default: true },
+ { key: 'records', ids: ['records'], label: dirLabel('records'), hint: '学习记录', default: true },
+ { key: 'notes', ids: ['notes'], label: dirLabel('notes'), hint: '提炼出的笔记', default: true },
+ { key: 'assets', ids: ['assets'], label: dirLabel('assets'), hint: '共享样式 course.css', default: true },
+ {
+ key: 'docs',
+ ids: ['mission', 'resources', 'glossary', 'preferences', 'curriculumDoc'],
+ label: 'MISSION / RESOURCES / GLOSSARY / NOTES / CURRICULUM',
+ hint: '前置文档',
+ default: false,
+ },
+ {
+ key: 'state',
+ ids: null,
+ label: WORKBENCH_DIR + '/',
+ hint: '会话、批注、课纲状态(清理后会从列表移除)',
+ default: false,
+ },
+];
+
+/** The list the client renders and the route validates against. */
+export function cleanTargets() {
+ return ROWS.map((row) => ({
+ key: row.key,
+ label: row.label,
+ hint: row.hint,
+ default: row.default,
+ paths: row.ids ? row.ids.flatMap((id) => artifactPaths(id)) : [WORKBENCH_DIR],
+ }));
+}
+
+/** Unknown keys are dropped, so a stale client cannot delete something else. */
+export function cleanKeys(value) {
+ const known = new Set(ROWS.map((row) => row.key));
+ return Array.isArray(value) ? value.filter((key) => known.has(key)) : [];
+}
+
+/**
+ * Delete the selected keys and repair what pointed at them.
+ * Removing the state directory also removes the workspace from the registry; the
+ * caller stops and awaits its running turns first.
+ */
+export async function cleanWorkspace(root, keys) {
+ const wanted = cleanKeys(keys);
+ const rows = cleanTargets().filter((item) => wanted.includes(item.key));
+ // Claim the paths before the first rm: a turn that is still winding down must
+ // not restore them or write the state directory back.
+ markClean(root, { keys: wanted, paths: rows.flatMap((row) => row.paths) });
+ const removed = [];
+ for (const row of rows) {
+ for (const rel of row.paths) {
+ const absolute = resolveInside(root, rel);
+ if (!existsSync(absolute)) continue;
+ await rm(absolute, { recursive: true, force: true });
+ removed.push(rel);
+ }
+ }
+
+ const workspaceGone = wanted.includes('state');
+ const effects = { notesPruned: 0, lessonsReset: 0 };
+
+ if (workspaceGone) {
+ await forgetWorkspace(workspaceId(root));
+ // Sweep once more: a turn that outlived the abort may have written the state
+ // directory back between the delete and the forget.
+ await rm(resolveInside(root, WORKBENCH_DIR), { recursive: true, force: true });
+ return { removed, workspaceGone, effects };
+ }
+
+ const reconciled = await reconcileWorkspaceFiles(root, {
+ lessons: wanted.includes('lessons'),
+ notes: wanted.includes('notes'),
+ });
+ effects.notesPruned = reconciled.notesPruned;
+ effects.lessonsReset = reconciled.lessonsReset;
+
+ return { removed, workspaceGone, effects };
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/fsx.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/fsx.mjs
new file mode 100644
index 00000000..7c7b999c
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/fsx.mjs
@@ -0,0 +1,198 @@
+import { mkdir, readFile, rename, readdir, stat, writeFile } from 'node:fs/promises';
+import { existsSync, realpathSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { WORKBENCH_DIR } from './policy.mjs';
+
+/** Read JSON; `fallback` on missing or (unless strict) unparsable files. */
+export async function readJson(file, fallback, { strict = false } = {}) {
+ let raw;
+ try {
+ raw = await readFile(file, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return fallback;
+ throw error;
+ }
+ if (!raw.trim()) return fallback;
+ try {
+ return JSON.parse(raw);
+ } catch (error) {
+ if (strict) throw new Error(`invalid_json:${path.basename(file)}`);
+ return fallback;
+ }
+}
+
+/** Read JSON and report parse failure without throwing. */
+export async function readJsonChecked(file, fallback) {
+ let raw;
+ try {
+ raw = await readFile(file, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return { value: fallback, missing: true, error: null };
+ return { value: fallback, missing: false, error: 'read_failed' };
+ }
+ if (!raw.trim()) return { value: fallback, missing: false, error: null };
+ try {
+ return { value: JSON.parse(raw), missing: false, error: null };
+ } catch {
+ return { value: fallback, missing: false, error: 'invalid_json' };
+ }
+}
+
+export async function readText(file, fallback = '') {
+ try {
+ return await readFile(file, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return fallback;
+ throw error;
+ }
+}
+
+export async function writeText(file, text) {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, text, 'utf8');
+}
+
+/** Atomic JSON write: temp file in the same directory, then rename over the target. */
+export async function writeJsonAtomic(file, value) {
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
+ await rename(tmp, file);
+}
+
+/** Write a text file only when it does not exist yet. */
+export async function writeTextOnce(file, text) {
+ if (existsSync(file)) return false;
+ await writeText(file, text);
+ return true;
+}
+
+function escapeError() {
+ const error = new Error('path_outside_workspace');
+ error.code = 'PATH_OUTSIDE';
+ return error;
+}
+
+/**
+ * A lexically safe path can still leave the workspace through a symlink, so the
+ * nearest existing ancestor is resolved for real and checked as well.
+ */
+function assertInsideReal(root, target) {
+ let base;
+ try {
+ base = realpathSync.native(path.resolve(root));
+ } catch {
+ return;
+ }
+ let cursor = target;
+ for (;;) {
+ let real = null;
+ try {
+ real = realpathSync.native(cursor);
+ } catch {
+ real = null;
+ }
+ if (real) {
+ if (!isInside(base, real)) throw escapeError();
+ return;
+ }
+ const parent = path.dirname(cursor);
+ if (parent === cursor) return;
+ cursor = parent;
+ }
+}
+
+export function resolveInside(root, relative) {
+ const clean = String(relative ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
+ const target = path.resolve(root, clean);
+ const rel = path.relative(root, target);
+ if (rel.startsWith('..') || path.isAbsolute(rel)) throw escapeError();
+ assertInsideReal(root, target);
+ return target;
+}
+
+export function isInside(root, candidate) {
+ const rel = path.relative(path.resolve(root), path.resolve(candidate));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
+export function toPosix(value) {
+ return String(value).replace(/\\/g, '/');
+}
+
+export async function listFiles(dir, { extensions = null, max = 400 } = {}) {
+ const out = [];
+ async function walk(current, prefix) {
+ if (out.length >= max) return;
+ let entries;
+ try {
+ entries = await readdir(current, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (out.length >= max) return;
+ if (entry.name.startsWith('.') && entry.name !== WORKBENCH_DIR) continue;
+ const abs = path.join(current, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules') continue;
+ await walk(abs, `${prefix}${entry.name}/`);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (extensions && !extensions.includes(path.extname(entry.name).toLowerCase())) continue;
+ out.push(`${prefix}${entry.name}`);
+ }
+ }
+ await walk(dir, '');
+ return out;
+}
+
+export async function fileMeta(root, relative) {
+ try {
+ const info = await stat(resolveInside(root, relative));
+ if (!info.isFile()) return null;
+ return { rel: toPosix(relative), size: info.size, mtime: info.mtimeMs };
+ } catch {
+ return null;
+ }
+}
+
+export function platformRoots() {
+ const roots = [];
+ if (process.platform === 'win32') {
+ for (let code = 65; code <= 90; code += 1) {
+ const drive = `${String.fromCharCode(code)}:\\`;
+ if (existsSync(drive)) roots.push(drive);
+ }
+ } else {
+ roots.push('/');
+ }
+ return roots;
+}
+
+export function homeDir() {
+ try {
+ return os.homedir();
+ } catch {
+ return process.platform === 'win32' ? 'C:\\' : '/';
+ }
+}
+
+export function parentOf(target) {
+ const parent = path.dirname(path.resolve(target));
+ if (parent === path.resolve(target)) return null;
+ return parent;
+}
+
+export function slugify(value, fallback = 'study') {
+ const stripped = String(value ?? '')
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 48);
+ return stripped || fallback;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/note-templates.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/note-templates.mjs
new file mode 100644
index 00000000..6e28602d
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/note-templates.mjs
@@ -0,0 +1,60 @@
+/**
+ * Built-in note templates. The template changes the note's structure and
+ * layout; the note session still only reads the scoped lessons and writes one
+ * note file.
+ */
+
+export const DEFAULT_NOTE_TEMPLATE = 'essence';
+
+export const NOTE_TEMPLATES = [
+ {
+ id: 'essence',
+ name: '精华索引',
+ summary: '一句话 + 6–8 条必记 + ≤3 条易错 + 批注;适合快速回忆。',
+ prompt:
+ '全文 400–600 字(不含来源),一眼能扫完。结构固定,不要加别的章节:\n## 必记\n- 6–8 条;每条以 **2–6 字标签** 开头,后面只放一个事实或动作,不超过 45 字。\n## 易错\n- 0–3 条;每条写「会怎么错 → 正确做法」,不超过 45 字。\n## 我的批注\n- 用户原话或要点,按课次标注;没有批注就写「(本范围没有批注)」。\n## 来源\n- 一行:课程编号 + 文件名。',
+ },
+ {
+ id: 'cornell',
+ name: '康奈尔笔记',
+ summary: '线索问题 / 笔记答案两栏表 + 总结;适合复习和自问自答。',
+ prompt:
+ '全文 350–600 字。结构:\n## 线索\n- 3–5 个只写问题、不写答案的问题。\n## 笔记\n| 线索 | 笔记 |\n| --- | --- |\n| 问题 | 1–2 句答案,保留术语与数字 |\n(每个问题一行,共 3–5 行)\n## 总结\n- 不超过 3 条,压成能背诵的句子。\n## 我的批注\n- 用户原话;没有就写「(本范围没有批注)」。\n## 来源\n- 一行:课程编号 + 文件名。',
+ },
+ {
+ id: 'flashcards',
+ name: '问答卡',
+ summary: '问题 / 答案两列表 + 易错;适合遮住答案自测。',
+ prompt:
+ '全文 350–550 字。结构:\n## 问答卡\n| 问题 | 答案 |\n| --- | --- |\n| 具体问题 | 不超过 40 字的答案 |\n(6–8 行,答案不要放提示词)\n## 易错\n- 不超过 3 条,每条「会怎么错 → 正确做法」。\n## 我的批注\n- 用户原话;没有就写「(本范围没有批注)」。\n## 来源\n- 一行:课程编号 + 文件名。',
+ },
+ {
+ id: 'compare',
+ name: '对比表',
+ summary: '按维度对比两个概念/方案 + 结论;适合易混点和选型。',
+ prompt:
+ '全文 350–600 字。先找出课程里最容易混淆的两个概念或两种方案(没有明显两个对象时,选两个相邻概念)。结构:\n## 对比\n| 维度 | 对象 A | 对象 B |\n| --- | --- | --- |\n| 3–5 个真正能区分它们的维度 | ... | ... |\n## 结论\n- 3 条以内:什么时候用 A / B,以及最常见的误用。\n## 我的批注\n- 用户原话;没有就写「(本范围没有批注)」。\n## 来源\n- 一行:课程编号 + 文件名。',
+ },
+ {
+ id: 'checklist',
+ name: '考点清单',
+ summary: '必会动作 + 易错 + 自测问题;适合考试/上手前检查。',
+ prompt:
+ '全文 350–550 字。结构:\n## 必会\n- 6–8 条,动词开头,每条一个可检查的动作。\n## 易错\n- 不超过 3 条,每条「会怎么错 → 正确做法」。\n## 自测\n- 3 个问题,只问不答;问题要能在一分钟内回答。\n## 我的批注\n- 用户原话;没有就写「(本范围没有批注)」。\n## 来源\n- 一行:课程编号 + 文件名。',
+ },
+ {
+ id: 'story',
+ name: '主线故事',
+ summary: '6–8 步主线 + 转折 + 记忆锚点;适合流程和多阶段内容。',
+ prompt:
+ '全文 350–600 字。结构:\n## 主线\n1. 6–8 步,每步不超过 30 字,按真实发生顺序写。\n## 转折\n- 2–3 条:哪一步最容易误判,为什么。\n## 记忆锚点\n- 3 条:一句口诀、一个数字或一个反例。\n## 我的批注\n- 用户原话;没有就写「(本范围没有批注)」。\n## 来源\n- 一行:课程编号 + 文件名。',
+ },
+];
+
+export function noteTemplateById(id) {
+ return NOTE_TEMPLATES.find((item) => item.id === id) || NOTE_TEMPLATES[0];
+}
+
+export function noteTemplatesPublic() {
+ return NOTE_TEMPLATES.map(({ id, name, summary }) => ({ id, name, summary }));
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/policy.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/policy.mjs
new file mode 100644
index 00000000..8282226f
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/policy.mjs
@@ -0,0 +1,201 @@
+/**
+ * One declaration of every workspace artifact and who may write it.
+ *
+ * This module is the single source for four things that used to drift apart:
+ * 1. which session kind may write a path (the seam decision),
+ * 2. the explanation shown when a write is refused,
+ * 3. the contract text in .workbench/rules/teach.md and the prompts,
+ * 4. which files a turn snapshots so an out-of-scope write can be restored.
+ *
+ * Pure on purpose: no fs access, no session state beyond the lesson's own
+ * target file. Every function here is a table lookup, so the whole policy is
+ * testable as a matrix of (kind, rel) pairs.
+ */
+
+import path from 'node:path';
+
+/** Every directory and file name a workspace uses, declared once. */
+export const WORKBENCH_DIR = '.workbench';
+export const RULES_DIR = `${WORKBENCH_DIR}/rules`;
+export const COURSE_CSS_REL = 'assets/course.css';
+
+/** Workspace-relative state paths. */
+export const STATE_RELS = {
+ meta: `${WORKBENCH_DIR}/workspace.json`,
+ sessions: `${WORKBENCH_DIR}/sessions.json`,
+ annotations: `${WORKBENCH_DIR}/annotations.json`,
+ notes: `${WORKBENCH_DIR}/notes.json`,
+ curriculum: `${WORKBENCH_DIR}/curriculum.json`,
+ curriculumBackup: `${WORKBENCH_DIR}/curriculum.backup.json`,
+ rules: `${RULES_DIR}/teach.md`,
+ context: `${WORKBENCH_DIR}/context`,
+ teacher: `${WORKBENCH_DIR}/teacher.json`,
+};
+
+/** Absolute paths for one workspace root; the only builder callers use. */
+export function workbenchPaths(root) {
+ return {
+ base: path.join(root, WORKBENCH_DIR),
+ meta: path.join(root, STATE_RELS.meta),
+ curriculum: path.join(root, STATE_RELS.curriculum),
+ curriculumBackup: path.join(root, STATE_RELS.curriculumBackup),
+ annotations: path.join(root, STATE_RELS.annotations),
+ notes: path.join(root, STATE_RELS.notes),
+ sessions: path.join(root, STATE_RELS.sessions),
+ context: path.join(root, STATE_RELS.context),
+ rules: path.join(root, STATE_RELS.rules),
+ teacher: path.join(root, STATE_RELS.teacher),
+ };
+}
+
+export function rulesPath(root) {
+ return path.join(root, STATE_RELS.rules);
+}
+
+export const SESSION_KINDS = ['main', 'setup', 'lesson', 'note'];
+
+export const KIND_LABEL = {
+ main: '主会话',
+ setup: '配置会话',
+ lesson: '课程分支会话',
+ note: '提炼会话',
+};
+
+/**
+ * Ordered: the first spec whose files/dirs match owns the path.
+ * "other" is the fallback for everything the workspace does not own.
+ */
+export const ARTIFACTS = [
+ { id: 'mission', label: '使命', mention: '`MISSION.md`', files: ['MISSION.md'], writers: ['main', 'setup'] },
+ { id: 'resources', label: '来源清单', mention: '`RESOURCES.md`', files: ['RESOURCES.md'], writers: ['main', 'setup'] },
+ { id: 'glossary', label: '术语表', mention: '`GLOSSARY.md`', files: ['GLOSSARY.md'], writers: ['main', 'setup'] },
+ { id: 'preferences', label: '教学偏好', mention: '`NOTES.md`', files: ['NOTES.md'], writers: ['main', 'setup'] },
+ { id: 'curriculumDoc', label: '课纲文档', mention: '`CURRICULUM.md`', files: ['CURRICULUM.md'], writers: ['main'] },
+ { id: 'curriculumState', label: '课纲状态', mention: '`.workbench/curriculum.json`', files: [STATE_RELS.curriculum], writers: ['main'] },
+ { id: 'contextPacket', label: '上下文包', mention: '`.workbench/context/`', dirs: [{ dir: STATE_RELS.context }], writers: ['main'] },
+ {
+ id: 'appState',
+ label: '应用状态',
+ mention: '`.workbench/` 下的会话、批注、笔记索引',
+ files: [
+ STATE_RELS.meta,
+ STATE_RELS.sessions,
+ STATE_RELS.annotations,
+ STATE_RELS.notes,
+ STATE_RELS.curriculumBackup,
+ STATE_RELS.teacher,
+ ],
+ writers: [],
+ },
+ { id: 'lesson', label: '课程', mention: '`lessons/*.html`', dirs: [{ dir: 'lessons', exts: ['.html'], own: true }], writers: ['lesson'] },
+ { id: 'reference', label: '速查文档', mention: '`reference/`', dirs: [{ dir: 'reference' }], writers: ['main', 'lesson', 'note'] },
+ { id: 'records', label: '学习记录', mention: '`learning-records/`', dirs: [{ dir: 'learning-records' }], writers: ['lesson'] },
+ { id: 'notes', label: '提炼笔记', mention: '`notes/`', dirs: [{ dir: 'notes' }], writers: ['note'] },
+ { id: 'assets', label: '共享样式', mention: '`assets/`', dirs: [{ dir: 'assets' }], writers: ['main', 'lesson'] },
+ { id: 'other', label: '其他文件', mention: '工作区里的其他文件', writers: ['main'], neverProtect: true },
+];
+
+const OTHER = ARTIFACTS[ARTIFACTS.length - 1];
+
+export function toPosixRel(rel) {
+ return String(rel ?? '')
+ .replace(/\\/g, '/')
+ .replace(/^\.\//, '')
+ .replace(/^\/+/, '');
+}
+
+/**
+ * True when `rel` is one of `paths` or lives inside one of those directories.
+ * Cleaned roots are declared without a trailing slash (lessons), so a plain
+ * prefix test would also match a sibling such as lessons-old.
+ */
+export function underAny(rel, paths) {
+ const posix = toPosixRel(rel);
+ return (paths ?? []).some((item) => {
+ const root = toPosixRel(item);
+ return Boolean(root) && (posix === root || posix.startsWith(`${root}/`));
+ });
+}
+
+function matches(spec, posix) {
+ if (spec.files) return spec.files.includes(posix);
+ if (spec.dirs) {
+ return spec.dirs.some((entry) => posix === entry.dir || posix.startsWith(`${entry.dir}/`));
+ }
+ return false;
+}
+
+export function classify(rel) {
+ const posix = toPosixRel(rel);
+ return ARTIFACTS.find((spec) => matches(spec, posix)) ?? OTHER;
+}
+
+/** Relative paths that belong to one artifact: its files and directory roots. */
+export function artifactPaths(id) {
+ const spec = ARTIFACTS.find((item) => item.id === id);
+ if (!spec) return [];
+ const out = [];
+ if (spec.files) out.push(...spec.files);
+ if (spec.dirs) for (const entry of spec.dirs) out.push(entry.dir);
+ return out;
+}
+
+/** The one place that decides whether a session may write a path. */
+export function canWrite(kind, rel, session = {}) {
+ const posix = toPosixRel(rel);
+ const spec = classify(posix);
+ if (!spec.writers.includes(kind)) return false;
+ if (spec.id === 'lesson' && kind === 'lesson') return posix === toPosixRel(session.targetFile);
+ return true;
+}
+
+/** The one place that explains a refusal. */
+export function denyMessage(kind, rel, session = {}) {
+ const posix = toPosixRel(rel);
+ const spec = classify(posix);
+ const who = KIND_LABEL[kind] ?? '这个会话';
+ if (spec.id === 'lesson' && kind === 'lesson') {
+ return `已阻止修改其他课程(${posix}):课程会话只能写自己的 ${session.targetFile || '本课文件'}。`;
+ }
+ const owners = spec.writers.map((item) => KIND_LABEL[item]).join(' 或 ');
+ return owners
+ ? `已阻止${who}写 ${posix}:${spec.label}只能由${owners}维护。`
+ : `已阻止${who}写 ${posix}:${spec.label}由应用维护,会话不写。`;
+}
+
+/** Artifacts this kind must not write, so a turn snapshots them for restore. */
+export function protectedSpecs(kind) {
+ const files = [];
+ const dirs = [];
+ for (const spec of ARTIFACTS) {
+ if (spec.neverProtect) continue;
+ // A kind that owns one file inside a shared directory (the lesson's own
+ // HTML) still needs the rest of that directory snapshotted.
+ const ownsOne = Boolean(spec.dirs && spec.dirs.some((entry) => entry.own));
+ if (spec.writers.includes(kind) && !ownsOne) continue;
+ if (spec.files) files.push(...spec.files);
+ if (spec.dirs) for (const entry of spec.dirs) dirs.push({ ...entry });
+ }
+ return { files, dirs };
+}
+
+function mentionFor(kind, spec) {
+ if (spec.id === 'lesson' && kind === 'lesson') return '`lessons/<本课文件>`';
+ return spec.mention;
+}
+
+/** Hard-boundary bullets for .workbench/rules/teach.md. */
+export function boundaryLines() {
+ return SESSION_KINDS.map((kind) => {
+ const can = ARTIFACTS.filter((spec) => spec.writers.includes(kind)).map((spec) => mentionFor(kind, spec));
+ const cannot = ARTIFACTS.filter((spec) => !spec.writers.includes(kind)).map((spec) => spec.mention);
+ return `- **${KIND_LABEL[kind]}**:可写 ${can.join('、') || '无'};不可写 ${cannot.join('、')}。`;
+ }).join('\n');
+}
+
+/** Short scope lines for prompts: what this turn may touch, and what it may not. */
+export function scopeLines(kind) {
+ const can = ARTIFACTS.filter((spec) => spec.writers.includes(kind)).map((spec) => mentionFor(kind, spec));
+ const cannot = ARTIFACTS.filter((spec) => !spec.writers.includes(kind)).map((spec) => spec.mention);
+ return `可以写:${can.join('、') || '无'}。\n禁止改动:${cannot.join('、')}。`;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/prompts.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/prompts.mjs
new file mode 100644
index 00000000..6b42388e
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/prompts.mjs
@@ -0,0 +1,256 @@
+import { allLessons } from './store.mjs';
+import { noteTemplateById } from './note-templates.mjs';
+import { artifactPaths, COURSE_CSS_REL, scopeLines, STATE_RELS, workbenchPaths } from './policy.mjs';
+
+function clip(value, max) {
+ const text = String(value ?? '').trim();
+ if (text.length <= max) return text;
+ return `${text.slice(0, max)}…`;
+}
+
+export function lessonFileName(lesson) {
+ const no = String(lesson.no).padStart(4, '0');
+ const slug =
+ String(lesson.title)
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 50) || 'lesson';
+ const dir = artifactPaths('lesson')[0];
+ return `${dir}/${no}-${slug}.html`;
+}
+
+export function noteFileName(title, date = new Date()) {
+ const stamp = [
+ date.getFullYear(),
+ String(date.getMonth() + 1).padStart(2, '0'),
+ String(date.getDate()).padStart(2, '0'),
+ ].join('-');
+ const clock = `${String(date.getHours()).padStart(2, '0')}${String(date.getMinutes()).padStart(2, '0')}`;
+ const slug =
+ String(title)
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 36) || 'note';
+ const dir = artifactPaths('notes')[0];
+ return `${dir}/${stamp}-${slug}-${clock}.md`;
+}
+
+export function buildContextPacket({ workspace, curriculum, lesson, records, mainSession }) {
+ const lessons = allLessons(curriculum);
+ const outline = curriculum.modules
+ .map((module) => {
+ const items = module.lessons
+ .map((item) => `${String(item.no).padStart(2, '0')} ${item.title}${item.status === 'done' ? '(已完成)' : item.status === 'active' ? '(进行中)' : ''}`)
+ .join(' · ');
+ return `${module.title}:${items}`;
+ })
+ .join('\n');
+
+ const doneRecords = records
+ .slice(0, 6)
+ .map((record) => {
+ const summary = clip(record.excerpt ?? '', 160).replace(/\s+/g, ' ');
+ return `- ${record.title}${summary ? `:${summary}` : ''}`;
+ })
+ .join('\n');
+
+ const decisions = (mainSession?.messages ?? [])
+ .filter((message) => message.role === 'assistant')
+ .slice(-2)
+ .map((message) => `- ${clip(message.text, 360).replace(/\s+/g, ' ')}`)
+ .join('\n');
+
+ const position = `第 ${lesson.no} 课 / 共 ${lessons.length} 课`;
+
+ return [
+ `【工作台】${workspace.name}(${workspace.root})`,
+ `【本课位置】${position}`,
+ `【使命】${clip(
+ (workspace.mission ?? '').replace(//g, '').replace(/^#.*$/gm, '').trim(),
+ 700,
+ )}`,
+ `【课纲】\n${clip(outline, 1200)}`,
+ doneRecords ? `【已完成课程的学习记录】\n${clip(doneRecords, 900)}` : '',
+ decisions ? `【主会话最近结论】\n${clip(decisions, 700)}` : '',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+}
+
+export function setupPrompt({ workspace, rulesPath }) {
+ return `你是这个学习工作台的配置会话。工作台目录:${workspace.root}
+
+这一步只搭前置环境:确定学习者是谁、想从这个目录里学到什么、有哪些约束。不要产出课程,也不要写课纲。
+
+先做三件事(都用绝对路径):
+1. 读 ${rulesPath};
+2. 读 ${workspace.root}\\MISSION.md(现在是模板);
+3. 看一眼这个目录:列出根目录,读 README、docs/ 里能说明它在做什么的文件,判断用户为什么把这个目录选来学习。
+
+然后用 ask_user 采访用户:一次问完,最多 3 个问题,围绕「你想从这个项目/目录里学到什么、为什么现在要学、时间与已有基础」。每题给 3–4 个具体选项,选项要基于你在目录里看到的东西来设计,不要问空泛的问题。
+
+拿到答案后:
+- 把 ${workspace.root}\\MISSION.md 写完整(严格按契约里的模板;首行是 # Mission: <一句话主题>)。
+- 更新 ${workspace.root}\\RESOURCES.md:挑 2–4 个可信来源,每条一句话说明用途。
+- 在 ${workspace.root}\\NOTES.md 记下用户的偏好,以及你在目录里看到、后面设计课程会用到的结构(比如已有的 tasks/、docs/)。
+
+边界(硬性):这一轮只做前置配置,不生成课纲,也不写任何课程文件。
+${scopeLines('setup')}
+
+完成标准:MISSION.md 的 Why 和 Success looks like 都写实了,不是模板占位。
+写完后回复不超过 100 字:一句话主题 + 你记下的关键约束 + 一句「前置环境已就绪,可以生成课纲」。
+停在这里,不要继续生成课纲或课程。`;
+}
+
+export function mainSeedPrompt({ workspace, rulesPath, hasMission }) {
+ return `你是这个学习工作台的主会话(teacher of record)。工作台根目录:${workspace.root}
+
+先读这两个文件,再动手(所有文件操作都用绝对路径):
+1. ${rulesPath} —— 教学契约,必须遵守
+2. ${workspace.root}\\MISSION.md —— 当前使命${hasMission ? '(已填写)' : '(还是模板)'}
+如果 \`mattpocock-skills:teach\` 这个 Skill 可用,也读一遍;它与上面的契约冲突时,以契约里的会话边界为准。
+
+你的职责:确定使命、维护 RESOURCES.md 与 GLOSSARY.md、生成和调整课纲、处理全局配置。
+你不写具体课程内容:课程文件由每节课的分支会话负责。
+
+流程:
+- 如果使命仍未确定,用 ask_user 采访用户:一次问完,最多 3 个问题,围绕「为什么学、想做成什么、时间与已有基础」。每题给 3–4 个具体选项,不要开放式空问。
+- 拿到答案后,把 ${workspace.root}\\MISSION.md 写完整(严格按契约里的模板),并在 NOTES.md 记下用户的偏好。
+- 然后回复不超过 120 字的小结:一句话使命 + 建议的模块数量 + 下一步。
+- 除非用户明确要求,这一轮不要生成课纲。`;
+}
+
+export function curriculumPrompt({ workspace, rulesPath }) {
+ return `任务:为这个学习工作台生成课纲。
+
+先读:${rulesPath}、${workspace.root}\\MISSION.md、${workspace.root}\\RESOURCES.md。
+
+要求:
+- 3–6 个模块,每模块 2–5 节课,总课数 6–18;顺序从用户当前水平推到使命终点(最近发展区)。
+- 每节课单点、预算 15–25 分钟、有可验证的产出,直接服务使命。
+- 每节课必须能单独阅读:不假设读者记得上一课;需要前置知识时,用课内回顾补上(在 objective 里点明),拆不开的两课合并成一课。
+- 课程标题用中文、动词开头(例:「用 clap 建立子命令」),不要用「第一讲」这类编号标题。
+- objective 用一句话说清这节课结束时用户能做什么(可观察)。
+- **保留已有课程的原标题**:工作台按标题把每节课绑到它自己的分支会话;改标题等于换一门课。
+- 这一轮只写课纲,不要创建课程文件,不要写 HTML。
+
+写入 ${workbenchPaths(workspace.root).curriculum},严格是下面这个结构(不要注释、不要多余字段):
+{"schemaVersion":1,"modules":[{"title":"模块名","goal":"这一模块解决什么","lessons":[{"title":"课程标题","objective":"结束时能做什么","minutes":20}]}]}
+
+同时把人类可读版写入 ${workspace.root}\\CURRICULUM.md:每个模块一节,列出课号、标题、目标。
+
+完成后只回复:模块数、课程数、一句「课纲已写入」。`;
+}
+
+const LESSON_WRITING_RULES = `写作要求:
+- 一个自包含 HTML:用 复用共享样式,必要时少量内联样式。
+- 只教一个点,用户 20 分钟内能读完并做完练习。
+- 自包含:不假设读者读过上一课;需要前置知识时,用 1–2 句回顾并链接到对应课程。
+- 先给知识(来源以 RESOURCES.md 为准,不够就用 web 搜索补,并保持可信),再给互动练习。
+- 至少 2 个检索练习:单选、四个选项长度尽量一致、点选后立即显示对错与原因(原生 JS 即可)。
+- 每个事实性论断附近给来源链接;结尾列「主要来源」。
+- 视觉组件:见 ${STATE_RELS.rules} 的「视觉组件」;每课按内容选 3–5 种(callout/cards/steps/compare/flow/layers/matrix/tree/timeline/sheet/slide/doc/kpis/bars/formula/checklist/diagram)。宽表放 sheet-wrap,SVG 放 diagram;窄屏优先纵向。
+- 结尾提醒:可以在这个分支会话里继续追问。
+- 不要引用远程脚本或 CDN。`;
+
+export function lessonSeedPrompt({ workspace, rulesPath, lesson, target, contextPacket }) {
+ return `你是第 ${lesson.no} 课的课程分支会话。这节课的上下文已经由主会话打包给你,你只负责这一课。
+
+工作台:${workspace.root}
+规则(先读):${rulesPath}
+如果 \`mattpocock-skills:teach\` 这个 Skill 可用,也读一遍;与规则冲突时以规则里的会话边界为准。
+本课:${lesson.title}
+目标:${lesson.objective || '(课纲未写目标,按标题把握)'}
+预算:${lesson.minutes} 分钟
+本课文件(唯一要写的课程文件):${workspace.root}\\${target}
+
+本课文件是唯一要写的课程文件;越界写入会被拒绝或还原。
+${scopeLines('lesson')}
+
+— 继承的上下文 —
+${contextPacket}
+— 上下文结束 —
+
+${LESSON_WRITING_RULES}
+
+第一步(不要跳过):先读规则、MISSION.md 与共享样式,然后回复 3 句——本课要拿到的一个具体成果、你打算怎么讲、需要用户准备什么。之后再写文件。
+写完回复:文件路径 + 一句自检(是否包含练习与来源)。`;
+}
+
+export function lessonRewritePrompt({ workspace, rulesPath, lesson, target, contextPacket }) {
+ return `这是第 ${lesson.no} 课的整节重做:用户看过现有课程,要求把这一课重新写一遍。
+
+工作台:${workspace.root}
+规则(先读):${rulesPath}
+本课:${lesson.title}
+目标:${lesson.objective || '(课纲未写目标,按标题把握)'}
+预算:${lesson.minutes} 分钟
+本课文件(唯一要写的课程文件,整份覆盖):${workspace.root}\\${target}
+
+本课文件是唯一要写的课程文件;越界写入会被拒绝或还原。
+${scopeLines('lesson')}
+
+— 继承的上下文 —
+${contextPacket}
+— 上下文结束 —
+
+这是重做,不是追问:
+- 覆盖同一个文件,不要新建第二个课程文件,也不要改其他课程。
+- 先读本课现有文件与 MISSION.md:保留值得留的部分,改进讲法、练习与来源。
+- 标题、目标、预算以课纲为准,不要改课纲。
+- 不要先复述计划,直接写。
+
+${LESSON_WRITING_RULES}
+
+写完回复:文件路径 + 一句自检(哪里比上一版好,是否包含练习与来源)。`;
+}
+
+export function notePrompt({ workspace, rulesPath, title, target, lessons, annotations, template, request }) {
+ const active = template && template.prompt ? template : noteTemplateById('');
+ const shape = active.prompt;
+ const lessonLines = lessons
+ .map((lesson) => `- 第 ${lesson.no} 课《${lesson.title}》:${workspace.root}\\${lesson.file}`)
+ .join('\n');
+ const annotationLines = annotations.length
+ ? annotations
+ .map((item) => {
+ const lesson = lessons.find((entry) => entry.id === item.lessonId);
+ const label = lesson ? `第 ${lesson.no} 课` : '相关课程';
+ const quote = item.quote ? `引用「${clip(item.quote, 120)}」→ ` : '';
+ return `- [${label}] ${quote}${clip(item.note, 300)}`;
+ })
+ .join('\n')
+ : '(这个范围内没有批注)';
+
+ return `笔记提炼任务(独立会话,只读课程与批注)。
+
+工作台:${workspace.root}
+规则:${rulesPath}(先读,尤其是文档格式与「不要编造」)
+笔记标题:${title}
+
+范围课程:
+${lessonLines}
+
+用户批注(用户自己的想法,必须被吸收,保留他们的用词):
+${annotationLines}
+
+要求:
+- 读上面列出的课程 HTML,提炼而不是照抄。
+- 写入 ${workspace.root}\\${target},结构固定,不要加别的章节。
+- 这是一个独立模板(${active.name}),必须严格遵守下面的结构与长度。
+- 第一行固定写 \`\`:2–4 个中文短词,每个不超过 6 字,用逗号分隔,不加 #。这一行只给应用读,正文里不要再提它。
+- 第二行起用 \`# ${title}\`;紧接着一段 \`> 一句话:…\`(不超过 60 字)。
+${shape}
+${request ? `- 用户这次的额外要求(优先满足,但不得违反上面的结构、长度与「不编造」):\n ${request}\n` : ''}
+- 表格里的示例行只说明列的含义;必须换成真实内容,不要保留示例行或省略号。
+- 保留专有名词、函数名、文件名与数字;不复述课程目录,不写「下一步练习」。
+- 课程与批注冲突时保留冲突并指出,不要自行调和;不确定的内容宁可不写,不要编造。
+- 只写这一个笔记文件,不改课程、不改其他文件。
+- 写前先删:任何不能帮未来的自己在一分钟内回忆起来的内容,都不写。
+
+完成后回复:文件路径 + 一句话摘要。`;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/scaffold.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/scaffold.mjs
new file mode 100644
index 00000000..d10fcf25
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/scaffold.mjs
@@ -0,0 +1,847 @@
+import { mkdir } from 'node:fs/promises';
+import path from 'node:path';
+
+import { readText, writeText, writeTextOnce } from './fsx.mjs';
+import { artifactPaths, boundaryLines, COURSE_CSS_REL, RULES_DIR, STATE_RELS, WORKBENCH_DIR } from './policy.mjs';
+
+export const TEACH_RULES = `# 教学契约(学习工作台)
+
+本工作区遵循 Matt Pocock 的 teach 方法(改编自 \`mattpocock-skills:teach\`)。任何在这个目录里工作的会话都必须遵守本文件。
+这是「为什么这样教」的唯一依据:课程结构、练习形式、文档格式都以它为准。
+
+## 目录约定
+
+- \`MISSION.md\`:使命。为什么学、学成什么样。所有教学决策都要能回溯到这里。
+- \`CURRICULUM.md\`:人类可读的课纲。机器可读版在 \`${STATE_RELS.curriculum}\`。
+- \`${artifactPaths('lesson')[0]}/0001-.html\`:课程。一课一个自包含 HTML 文件,编号递增。
+- \`${artifactPaths('assets')[0]}/\`:课程共享的组件与样式(\`course.css\` 是默认样式表)。复用优先,不要复制粘贴。
+- \`${artifactPaths('reference')[0]}/*.html\`:速查文档。可打印、排版干净,供反复查阅。
+- \`${artifactPaths('records')[0]}/0001-.md\`:学习记录。记录非显然的理解、先前知识、被纠正的误解。
+- \`GLOSSARY.md\`:术语表。只收录用户已经理解的术语。
+- \`RESOURCES.md\`:可信来源清单,分 Knowledge / Wisdom 两组,每条都要有用途说明。
+- \`NOTES.md\`:教学偏好与临时笔记。
+- \`${artifactPaths('notes')[0]}/*.md\`:从课程与批注提炼出的笔记(由提炼会话写入)。
+- \`${WORKBENCH_DIR}/\`:学习工作台的机器状态,由应用维护;会话的写权限见「会话职责」。
+
+## 会话职责(硬边界)
+
+${boundaryLines()}
+
+## 教学原则
+
+学习需要三样东西:知识(来自高质量来源)、技能(通过有反馈的练习获得)、智慧(真实世界的交流)。
+不要相信自己的记忆:所有事实性陈述都要能指向 RESOURCES.md 里的来源。
+
+- **区分流畅度与存储强度**。看懂了不等于记住了。设计课程时用检索练习、间隔、交错,制造「合意的困难」。
+- **最近发展区**。每节课只比用户当前水平难一点点;读学习记录判断当前水平。
+- **知识先行,技能随后**。先用最少的知识把概念讲清,然后立刻用互动练习把它变成技能。
+- **反馈回路要短**。练习要立即给出对错与原因,不要让用户自己猜。
+- **一课一个收获**。工作记忆很小;宁可少讲,也要让用户拿到一个可以马上用出去的东西。
+- **每节课自包含**。读者只读这一课也能听懂;不假设他记得上一课的讲解。需要前置知识时,课内用 1–2 句回顾并链接到那一课;拆不开的两课合并成一课,不要拆成必须连着读的两课。
+
+## 课程(lesson)要求
+
+1. 一个自包含 HTML 文件,直接打开就能读。默认引用 \`../${COURSE_CSS_REL}\` 获得排版,
+ 需要时再加少量内联样式。
+2. 15–25 分钟内可完成。开头用一句话说清「这节课结束时你能做什么」。
+3. 结构:知识(带来源链接)→ 示例/演示 → 检索练习(至少 2 个)→ 这一课的收获 → 可以继续追问。
+4. 检索练习题:单选,四个选项长度尽量一致(不要用格式泄露答案),点选后立即出现对错与原因。
+5. 每个事实性论断附近给出链接;结尾列出「主要来源」。
+6. 用原生 HTML/CSS/JS。不要引用远程脚本或 CDN。
+7. 课程之间用相对链接互链;首次出现的术语链接到 \`${artifactPaths('reference')[0]}/\` 或 \`GLOSSARY.md\`。
+8. 结尾必须有一句提醒:可以在这个工作台的分支会话里继续追问。
+9. 打印友好:\`@media print\` 下不要出现交互控件。
+10. 内容自包含:不依赖上一课的讲解才能看懂;需要前置知识时,用 1–2 句在课内回顾,并链接到对应课程。拆不开的内容合并成一课。
+11. 视觉块服务于理解:见下方「视觉组件」,每课按内容选 3–5 种;不要为了装饰堆块。
+
+## 视觉组件(${COURSE_CSS_REL})
+
+按内容选 3–5 种,先图后文;图块必须服务理解。常用结构(类名必须一致):
+
+- 提示:(也可 warn / tip)
+- 卡片:
+- 步骤:- 第一步说明
+- 对比:
+- 流程:
+- 分层:
+- 2×2 矩阵:
+- 决策树:
+- 时间线:- 09:00事件
+- Excel 表:
+- PPT 页:
+- 文档卡:
+- 指标卡:
+- 条形图:
+- 公式:P(A|B) = P(B|A)P(A)/P(B)
+- 清单:
+- SVG 图示:图注
+
+宽表放进 sheet-wrap,SVG 放进 diagram;窄屏优先纵向排列。不要把两个宽块并排塞进 .grid-2。
+
+## 文档格式
+
+### MISSION.md
+
+\`\`\`md
+# Mission: {Topic}
+
+## Why
+{1-3 sentences. The concrete real-world goal.}
+
+## Success looks like
+- {A specific, observable thing the user will be able to do}
+
+## Constraints
+- {Time, budget, prior commitments, learning preferences}
+
+## Out of scope
+- {Adjacent topics deliberately not chased now}
+\`\`\`
+
+保持一屏以内。使命需要变化时,先和用户确认,再更新这份文件,并补一条 learning-record 说明为什么变——
+不要自己悄悄改掉方向,也不要留一份过时的使命指挥后面的课。
+
+### RESOURCES.md
+
+\`\`\`md
+# {Topic} Resources
+
+## Knowledge
+
+- [Book: _Title_ by Author](https://example.com)
+ 一句话说明它覆盖什么、什么时候该查它。
+
+## Wisdom (Communities)
+
+- [r/example](https://example.com)
+ 高信噪比社区,用来:方案点评、瓶颈排错。
+
+## Gaps
+- {还没有找到好来源的方向}
+\`\`\`
+
+只收高可信来源;每条都要有用途说明;宁可五个锋利的来源,不要三十个平庸的。
+
+### ${artifactPaths('records')[0]}/0001-.md
+
+\`\`\`md
+# {Short title}
+
+{1-3 sentences: 学到了什么(或确认了什么先前知识),为什么它会影响后面的课。}
+\`\`\`
+
+只在有**证据**时写:用户演示了真正的理解、说明了已知、纠正了误解、或使命发生变化。
+单纯的「讲过」不算学习,不要写。
+
+### GLOSSARY.md
+
+\`\`\`md
+# {Topic} Glossary
+
+## Terms
+
+**术语**:
+一到两句话,定义它是什么(不是怎么用)。
+_Avoid_: 同义的模糊说法
+\`\`\`
+
+术语只有等用户能正确使用之后才收录。定义里优先使用表里已有的术语。
+`;
+
+const MISSION_TEMPLATE = (topic) => `# Mission: ${topic}
+
+## Why
+_待主会话与你确认:一句话说清为什么学、想做成什么。_
+
+## Success looks like
+- _待填写:一个具体、可观察的结果_
+
+## Constraints
+- _待填写:时间、预算、已有基础、学习偏好_
+
+## Out of scope
+- _待填写:这次明确不追的相邻主题_
+`;
+
+const RESOURCES_TEMPLATE = (topic) => `# ${topic} Resources
+
+## Knowledge
+
+- _待主会话补充:可信来源,每条一句话说明用途_
+
+## Wisdom (Communities)
+
+- _待补充:可以验证技能的真实社区_
+
+## Gaps
+- _还没有找到好来源的方向_
+`;
+
+const GLOSSARY_TEMPLATE = (topic) => `# ${topic} Glossary
+
+只在你能正确使用一个术语之后,它才应该出现在这里。
+
+## Terms
+
+`;
+
+const NOTES_TEMPLATE = `# 教学笔记
+
+这里记录教学偏好、临时想法、以及主会话需要注意的事。
+
+- 界面语言:中文
+`;
+
+const CURRICULUM_TEMPLATE = `# 课纲
+
+尚未生成。在学习工作台的「概览」里点「生成课纲」,主会话会按使命写出模块与课程。
+`;
+
+const COURSE_CSS_MARKER = '/* 学习工作台组件库 v1 */';
+
+export const COURSE_CSS = `/* 学习工作台共享课程样式:所有课程页默认引用它。 */
+:root {
+ --ink: #1c1b19;
+ --muted: #6b6a66;
+ --line: #0a0a0a14;
+ --paper: #fbfaf7;
+ --surface: #ffffff;
+ --accent: #0b6bcb;
+ --ok: #0f7a3d;
+ --bad: #b42318;
+ --warn: #b45309;
+ --code: #f2f0eb;
+ color-scheme: light dark;
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --ink: #ece9e2;
+ --muted: #a09d95;
+ --line: #ffffff1f;
+ --paper: #1e1d1b;
+ --surface: #26251f;
+ --accent: #7db4ff;
+ --ok: #6ee7a8;
+ --bad: #ff9a8f;
+ --warn: #ffc46b;
+ --code: #2b2a24;
+ }
+}
+* { box-sizing: border-box; }
+html { -webkit-text-size-adjust: 100%; }
+body {
+ margin: 0;
+ background: var(--paper);
+ color: var(--ink);
+ font-family: ui-serif, Georgia, "Songti SC", "Source Han Serif SC", "Noto Serif CJK SC", serif;
+ font-size: 17.5px;
+ line-height: 1.85;
+}
+.lesson {
+ max-width: 680px;
+ margin: 0 auto;
+ padding: 48px 28px 96px;
+}
+.kicker {
+ font-family: ui-sans-serif, -apple-system, system-ui, "PingFang SC", sans-serif;
+ font-size: 11px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--muted);
+ margin-bottom: 1.6em;
+}
+h1, h2, h3 {
+ font-family: ui-sans-serif, -apple-system, system-ui, "PingFang SC", sans-serif;
+ line-height: 1.35;
+ letter-spacing: -0.01em;
+}
+h1 { font-size: 30px; font-weight: 600; margin: 0 0 0.4em; }
+h2 { font-size: 18px; font-weight: 600; margin: 2em 0 0.3em; }
+h3 { font-size: 15px; font-weight: 600; margin: 1.4em 0 0.2em; }
+p { margin: 0 0 1em; }
+a { color: var(--accent); text-decoration: none; border-bottom: 1px solid currentColor; }
+a:hover { opacity: 0.8; }
+code {
+ font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.85em;
+ background: var(--code);
+ border-radius: 4px;
+ padding: 0.1em 0.34em;
+}
+pre {
+ background: var(--code);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 14px 16px;
+ overflow: auto;
+ font-size: 13px;
+ line-height: 1.7;
+}
+pre code { background: none; padding: 0; font-size: inherit; }
+blockquote {
+ margin: 1.4em 0;
+ padding: 2px 0 2px 16px;
+ border-left: 2px solid var(--line);
+ color: var(--muted);
+ font-style: italic;
+}
+ul, ol { padding-left: 1.3em; margin: 0 0 1em; }
+li + li { margin-top: 0.3em; }
+mark { background: #b4530922; border-radius: 2px; padding: 0 2px; color: inherit; }
+.lede { font-size: 1.05em; color: var(--muted); }
+.note {
+ border: 1px solid var(--line);
+ border-left: 3px solid var(--warn);
+ border-radius: 8px;
+ background: var(--surface);
+ padding: 12px 14px;
+ margin: 1.4em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.7;
+}
+.quiz {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 16px 18px;
+ margin: 1.8em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.65;
+}
+.quiz h3 { margin: 0 0 2px; font-size: 14px; }
+.quiz .prompt { margin: 0 0 12px; color: var(--muted); font-size: 13px; }
+.quiz button {
+ display: flex;
+ gap: 9px;
+ width: 100%;
+ text-align: left;
+ align-items: flex-start;
+ padding: 9px 11px;
+ margin-bottom: 6px;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+}
+.quiz button:hover { border-color: var(--muted); }
+.quiz button b { width: 18px; flex: none; color: var(--muted); font-weight: 500; }
+.quiz button.right { border-color: var(--ok); background: color-mix(in srgb, var(--ok) 10%, transparent); }
+.quiz button.wrong { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 8%, transparent); }
+.quiz .feedback { color: var(--muted); font-size: 13px; margin-top: 8px; }
+.quiz .feedback[hidden] { display: none; }
+.takeaway {
+ border-top: 1px solid var(--line);
+ margin-top: 2.4em;
+ padding-top: 16px;
+}
+.takeaway h2 { margin-top: 0; }
+.sources {
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 13px;
+ color: var(--muted);
+ border-top: 1px solid var(--line);
+ margin-top: 2.4em;
+ padding-top: 12px;
+}
+.ask-teacher {
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 13px;
+ color: var(--muted);
+ background: var(--code);
+ border-radius: 8px;
+ padding: 10px 12px;
+ margin-top: 1.6em;
+}
+mark.wb-hl {
+ background: color-mix(in srgb, #f59e0b 26%, transparent);
+ border-bottom: 1px solid color-mix(in srgb, #f59e0b 70%, transparent);
+ cursor: pointer;
+}
+/* 学习工作台组件库 v1 */
+.callout {
+ border: 1px solid var(--line);
+ border-left: 3px solid var(--accent);
+ border-radius: 10px;
+ background: var(--surface);
+ padding: 12px 15px;
+ margin: 1.5em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.7;
+}
+.callout.warn { border-left-color: var(--warn); }
+.callout.key { border-left-color: var(--ink); }
+.callout .t {
+ display: block;
+ font-size: 11px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--muted);
+ margin-bottom: 3px;
+}
+.callout p:last-child { margin-bottom: 0; }
+.cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
+ gap: 12px;
+ margin: 1.6em 0;
+}
+.card {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 13px 15px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.65;
+}
+.card h3 { margin: 0 0 0.35em; font-size: 14px; }
+.card p:last-child { margin-bottom: 0; }
+.steps {
+ list-style: none;
+ counter-reset: step;
+ padding: 0;
+ margin: 1.7em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+}
+.steps li {
+ counter-increment: step;
+ position: relative;
+ margin: 0 0 0 13px;
+ padding: 0 0 1.2em 30px;
+ border-left: 1px solid var(--line);
+ line-height: 1.65;
+}
+.steps li:last-child { border-left-color: transparent; padding-bottom: 0; }
+.steps li::before {
+ content: counter(step);
+ position: absolute;
+ left: -13px;
+ top: -2px;
+ width: 25px;
+ height: 25px;
+ border-radius: 999px;
+ border: 1px solid var(--line);
+ background: var(--surface);
+ display: grid;
+ place-items: center;
+ font-size: 12px;
+ color: var(--muted);
+}
+.steps li b { display: block; color: var(--ink); }
+.compare {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+ margin: 1.6em 0;
+}
+.compare > div {
+ border: 1px solid var(--line);
+ border-top: 3px solid var(--accent);
+ border-radius: 10px;
+ background: var(--surface);
+ padding: 12px 14px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.65;
+}
+.compare > div + div { border-top-color: var(--warn); }
+.compare h3 { margin: 0 0 0.3em; font-size: 14px; }
+.flow {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ margin: 1.6em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 13px;
+}
+.flow .node {
+ flex: 1 1 120px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--surface);
+ padding: 9px 11px;
+ line-height: 1.5;
+}
+.flow .node b {
+ display: block;
+ font-size: 11px;
+ color: var(--muted);
+ font-weight: 500;
+ letter-spacing: 0.06em;
+}
+.flow .arrow { color: var(--muted); flex: none; }
+.figure { margin: 1.8em 0; }
+.figure svg,
+.figure img { display: block; max-width: 100%; height: auto; border-radius: 10px; }
+.figure figcaption {
+ margin-top: 7px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 12.5px;
+ color: var(--muted);
+ text-align: center;
+}
+.flash {
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--surface);
+ margin: 10px 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.65;
+}
+.flash summary { padding: 10px 14px; cursor: pointer; font-weight: 600; list-style: none; }
+.flash summary::-webkit-details-marker { display: none; }
+.flash summary::before {
+ content: '?';
+ display: inline-grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ margin-right: 8px;
+ border-radius: 999px;
+ border: 1px solid var(--line);
+ font-size: 11px;
+ color: var(--muted);
+}
+.flash[open] summary { border-bottom: 1px solid var(--line); }
+.flash .a { padding: 11px 14px; color: var(--muted); }
+.tag {
+ display: inline-block;
+ margin: 0 6px 4px 0;
+ padding: 1px 8px;
+ border: 1px solid var(--line);
+ border-radius: 999px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 11px;
+ color: var(--muted);
+}
+.meter {
+ height: 6px;
+ border-radius: 999px;
+ background: var(--line);
+ overflow: hidden;
+ margin: 0.6em 0 1em;
+}
+.meter > i { display: block; height: 100%; background: var(--accent); border-radius: 999px; }
+.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 1.4em 0; }
+.lesson table {
+ width: 100%;
+ border-collapse: collapse;
+ margin: 1.4em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+}
+.lesson th,
+.lesson td {
+ border-bottom: 1px solid var(--line);
+ padding: 8px 10px;
+ text-align: left;
+ vertical-align: top;
+}
+.lesson thead th {
+ font-size: 11px;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--muted);
+ font-weight: 600;
+}
+/* --- richer lesson blocks: structure over decoration --- */
+.callout.tip { border-left-color: var(--ok); }
+.kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: 10px;
+ margin: 1.6em 0;
+}
+.kpi {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 12px 13px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+}
+.kpi b { display: block; font-size: 22px; line-height: 1.2; letter-spacing: -0.01em; }
+.kpi span { display: block; margin-top: 2px; font-size: 11px; color: var(--muted); }
+.matrix {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+ margin: 1.6em 0;
+}
+.matrix .quad {
+ min-width: 0;
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 13px 14px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.65;
+}
+.matrix .quad h3 { margin: 0 0 0.3em; font-size: 13px; }
+.matrix .quad:nth-child(1) { border-top: 3px solid var(--ok); }
+.matrix .quad:nth-child(2) { border-top: 3px solid var(--warn); }
+.matrix .quad:nth-child(3) { border-top: 3px solid var(--accent); }
+.matrix .quad:nth-child(4) { border-top: 3px solid var(--bad); }
+.layers {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin: 1.6em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+}
+.layers .layer {
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--surface);
+ padding: 10px 13px;
+ font-size: 14px;
+ line-height: 1.6;
+}
+.layers .layer b { display: block; font-size: 11px; color: var(--muted); letter-spacing: 0.06em; }
+.layers .arrow, .flow .arrow { align-self: center; color: var(--muted); flex: none; line-height: 1; }
+.layers .arrow { text-align: center; }
+.tree, .tree ul { list-style: none; margin: 0; padding-left: 0; }
+.tree ul { margin-left: 0.45em; padding-left: 1.05em; border-left: 1px solid var(--line); }
+.tree li {
+ position: relative;
+ padding: 3px 0 3px 13px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.6;
+}
+.tree li::before {
+ content: '';
+ position: absolute;
+ left: -1px;
+ top: 1em;
+ width: 9px;
+ border-top: 1px solid var(--line);
+}
+.tree > li { padding-left: 0; }
+.tree > li::before { display: none; }
+.timeline {
+ list-style: none;
+ padding: 0;
+ margin: 1.6em 0 1.6em 8px;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+}
+.timeline li {
+ position: relative;
+ margin: 0;
+ padding: 0 0 1.1em 22px;
+ border-left: 2px solid var(--line);
+ font-size: 14px;
+ line-height: 1.65;
+}
+.timeline li:last-child { border-left-color: transparent; padding-bottom: 0; }
+.timeline li::before {
+ content: '';
+ position: absolute;
+ left: -6px;
+ top: 0.35em;
+ width: 10px;
+ height: 10px;
+ border-radius: 999px;
+ background: var(--surface);
+ border: 2px solid var(--accent);
+}
+.timeline li b { display: block; font-size: 11px; color: var(--muted); letter-spacing: 0.04em; }
+.sheet-wrap {
+ max-width: 100%;
+ overflow-x: auto;
+ margin: 1.5em 0;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+}
+.sheet {
+ width: 100%;
+ min-width: 480px;
+ border-collapse: collapse;
+ background: var(--surface);
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 13px;
+}
+.sheet caption {
+ caption-side: top;
+ text-align: left;
+ padding: 9px 11px;
+ color: var(--muted);
+ font-size: 11.5px;
+ border-bottom: 1px solid var(--line);
+}
+.sheet th, .sheet td {
+ border-bottom: 1px solid var(--line);
+ border-right: 1px solid var(--line);
+ padding: 7px 9px;
+ text-align: left;
+ vertical-align: top;
+}
+.sheet th:last-child, .sheet td:last-child { border-right: 0; }
+.sheet thead th { background: var(--code); font-size: 11px; color: var(--muted); font-weight: 600; }
+.sheet tbody tr:nth-child(even) { background: color-mix(in srgb, var(--code) 55%, transparent); }
+.sheet td.num, .sheet th.num { text-align: right; font-variant-numeric: tabular-nums; }
+.slide {
+ display: flex;
+ flex-direction: column;
+ aspect-ratio: 16 / 9;
+ min-height: 240px;
+ overflow: auto;
+ border: 1px solid var(--line);
+ border-radius: 14px;
+ background: var(--surface);
+ padding: 22px 24px;
+ margin: 1.8em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ box-shadow: 0 6px 20px rgb(10 10 10 / 5%);
+}
+.slide-title { margin: 0 0 0.5em; font-size: 22px; line-height: 1.3; font-weight: 600; letter-spacing: -0.01em; }
+.slide-body { flex: 1; min-height: 0; font-size: 14.5px; line-height: 1.7; }
+.slide-body ul { margin: 0.3em 0 0; padding-left: 1.2em; }
+.slide-foot { margin-top: auto; padding-top: 10px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11px; }
+.doc {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 18px 20px;
+ margin: 1.8em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+}
+.doc-head { border-bottom: 1px solid var(--line); padding-bottom: 8px; margin-bottom: 10px; }
+.doc-head .kicker { margin: 0 0 4px; }
+.doc-head h2 { margin: 0; font-size: 18px; }
+.doc-body { font-size: 14.5px; line-height: 1.75; }
+.bars { margin: 1.6em 0; font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif; font-size: 13px; }
+.bar-row {
+ display: grid;
+ grid-template-columns: minmax(64px, auto) minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 9px;
+ padding: 3px 0;
+}
+.bar-label { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.bar-track { height: 10px; border-radius: 999px; background: var(--code); overflow: hidden; }
+.bar-track > i { display: block; height: 100%; width: var(--v, 0%); background: var(--accent); border-radius: 999px; }
+.bar-value { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 12px; }
+.formula {
+ margin: 1.5em 0;
+ padding: 12px 14px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--surface);
+ text-align: center;
+ font-family: ui-serif, Georgia, "Songti SC", serif;
+ font-size: 17px;
+ overflow-x: auto;
+}
+.checklist { list-style: none; padding: 0; margin: 1.4em 0; font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif; }
+.checklist li { position: relative; padding: 4px 0 4px 24px; font-size: 14px; line-height: 1.65; }
+.checklist li::before {
+ content: '';
+ position: absolute;
+ left: 0;
+ top: 0.55em;
+ width: 12px;
+ height: 12px;
+ border: 1px solid var(--line);
+ border-radius: 3px;
+ background: var(--surface);
+}
+.diagram {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 12px;
+ overflow-x: auto;
+ margin: 1.8em 0;
+}
+.diagram svg { display: block; max-width: 100%; min-width: 420px; height: auto; margin: 0 auto; }
+.diagram text { font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif; fill: var(--ink); }
+.diagram .box { fill: var(--surface); stroke: var(--line); }
+.diagram .muted { fill: var(--muted); }
+.diagram .line { stroke: var(--muted); fill: none; }
+@media (max-width: 640px) {
+ .compare,
+ .grid-2,
+ .matrix { grid-template-columns: 1fr; }
+ .flow { flex-direction: column; align-items: stretch; }
+ .flow .node { flex: 0 0 auto; }
+ .flow .arrow { align-self: center; transform: rotate(90deg); }
+ .slide { aspect-ratio: auto; min-height: 0; padding: 16px 18px; }
+ .slide-title { font-size: 19px; }
+ .sheet { min-width: 420px; }
+}
+@media print {
+ body { background: #fff; color: #000; font-size: 12pt; }
+ .quiz button, .ask-teacher { display: none; }
+ .flash .a { display: block; }
+ a { color: #000; }
+}
+`;
+
+/** The managed block: refreshed in place so existing workspaces get new components. */
+const COURSE_BLOCKS = COURSE_CSS.slice(COURSE_CSS.indexOf(COURSE_CSS_MARKER));
+
+/**
+ * The contract text is generated from the write policy, so it is refreshed in
+ * place: a workspace created by an older build must not keep a stale boundary.
+ */
+export async function refreshRules(root) {
+ const rel = STATE_RELS.rules;
+ const abs = path.join(root, rel);
+ await mkdir(path.dirname(abs), { recursive: true });
+ await writeText(abs, TEACH_RULES);
+ return rel;
+}
+
+/**
+ * Existing workspaces were scaffolded with an older course.css. Replace only the
+ * managed block below the marker, so a session's own additions above it survive.
+ */
+export async function refreshCourseCss(root) {
+ const abs = path.join(root, COURSE_CSS_REL);
+ const current = await readText(abs);
+ if (!current.trim()) {
+ await writeText(abs, COURSE_CSS);
+ return COURSE_CSS_REL;
+ }
+ const at = current.indexOf(COURSE_CSS_MARKER);
+ if (at >= 0 && current.slice(at) === COURSE_BLOCKS) return COURSE_CSS_REL;
+ const head = at >= 0 ? current.slice(0, at) : `${current.trimEnd()}\n\n`;
+ await writeText(abs, head + COURSE_BLOCKS);
+ return COURSE_CSS_REL;
+}
+
+/** Create the teach workspace structure. Existing files are never overwritten. */
+export async function ensureScaffold(root, { topic }) {
+ const dirs = [
+ ...['lesson', 'reference', 'records', 'assets', 'notes'].map((id) => artifactPaths(id)[0]),
+ RULES_DIR,
+ STATE_RELS.context,
+ ];
+ for (const dir of dirs) {
+ await mkdir(path.join(root, dir), { recursive: true });
+ }
+
+ const files = [
+ ['MISSION.md', MISSION_TEMPLATE(topic)],
+ ['RESOURCES.md', RESOURCES_TEMPLATE(topic)],
+ ['GLOSSARY.md', GLOSSARY_TEMPLATE(topic)],
+ ['NOTES.md', NOTES_TEMPLATE],
+ ['CURRICULUM.md', CURRICULUM_TEMPLATE],
+ [COURSE_CSS_REL, COURSE_CSS],
+ [STATE_RELS.rules, TEACH_RULES],
+ ];
+ const created = [];
+ for (const [rel, text] of files) {
+ if (await writeTextOnce(path.join(root, rel), text)) created.push(rel);
+ }
+ return created;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/server.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/server.mjs
new file mode 100644
index 00000000..cf0e4a11
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/server.mjs
@@ -0,0 +1,1147 @@
+import { createReadStream, existsSync } from 'node:fs';
+import { access, readFile, readdir, rm, stat } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import path from 'node:path';
+
+import { createAgentService } from './agent.mjs';
+import { checkPaths } from './check-paths.mjs';
+import { cleanKeys, cleanTargets, cleanWorkspace } from './clean.mjs';
+import { classify, rulesPath, STATE_RELS, WORKBENCH_DIR } from './policy.mjs';
+import { refreshCourseCss, refreshRules } from './scaffold.mjs';
+import { DEFAULT_TEACHER_ID, newTeacherId, presetById, teacherPresetsPublic } from './teacher-presets.mjs';
+import { noteTemplatesPublic } from './note-templates.mjs';
+import {
+ createWorkspace,
+ findLesson,
+ forgetWorkspace,
+ getSession,
+ getWorkspace,
+ importCurriculum,
+ importWorkspace,
+ initStore,
+ listWorkspaces,
+ loadSnapshot,
+ mutateAnnotations,
+ mutateCurriculum,
+ mutateNotes,
+ normalizeTags,
+ readAnnotations,
+ readCurriculum,
+ readMeta,
+ readNotes,
+ readMission,
+ readRules,
+ reconcileRunningSessions,
+ registerWorkspace,
+ saveSession,
+ sessionSummary,
+ mutateTeacher,
+} from './store.mjs';
+import {
+ homeDir,
+ isInside,
+ parentOf,
+ platformRoots,
+ readText,
+ resolveInside,
+ toPosix,
+ writeText,
+} from './fsx.mjs';
+
+const SURFACE = '/workbench';
+
+/** Accept only a selection the Host can dispatch: provider, model, optional variant, optional effort. */
+function normalizeModelSelection(value) {
+ if (!value || typeof value !== 'object') return null;
+ const providerId = typeof value.providerId === 'string' ? value.providerId.trim() : '';
+ const modelId = typeof value.modelId === 'string' ? value.modelId.trim() : '';
+ if (!providerId || !modelId) return null;
+ const selection = { providerId, modelId };
+ if (typeof value.variant === 'string') selection.variant = value.variant;
+ if (value.thinking && typeof value.thinking === 'object' && typeof value.thinking.effort === 'string') {
+ selection.thinking = { effort: value.thinking.effort };
+ }
+ return selection;
+}
+
+const MIME = {
+ '.html': 'text/html; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.mjs': 'text/javascript; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.md': 'text/plain; charset=utf-8',
+ '.txt': 'text/plain; charset=utf-8',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.ico': 'image/x-icon',
+ '.woff2': 'font/woff2',
+ '.woff': 'font/woff',
+ '.ttf': 'font/ttf',
+ '.otf': 'font/otf',
+ '.pdf': 'application/pdf',
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+};
+
+const TEXT_EXT = new Set(['.html', '.css', '.js', '.mjs', '.json', '.md', '.txt', '.svg']);
+// What the lesson file panel may read: the workspace's own text files plus the
+// code a lesson links to. Serving over /w/ stays on TEXT_EXT above.
+const READABLE_EXT = new Set([
+ ...TEXT_EXT,
+ '.py', '.pyi', '.ts', '.tsx', '.jsx', '.java', '.kt', '.go', '.rs', '.rb', '.php',
+ '.c', '.h', '.cc', '.cpp', '.hpp', '.cs', '.swift', '.sh', '.bash', '.ps1',
+ '.yml', '.yaml', '.toml', '.ini', '.cfg', '.conf', '.sql', '.log',
+]);
+
+/**
+ * Lesson pages are generated from web research and run their own scripts, so
+ * they get a CSP that keeps rendering and quizzes working but forbids any
+ * network call back into this app's API (or anywhere else).
+ */
+const LESSON_CSP = [
+ "default-src 'none'",
+ "script-src 'self' 'unsafe-inline'",
+ "style-src 'self' 'unsafe-inline' https:",
+ "img-src 'self' data: https:",
+ "font-src 'self' data: https:",
+ "media-src 'self' data: https:",
+ "connect-src 'none'",
+ "form-action 'none'",
+ "base-uri 'none'",
+ "frame-ancestors 'self'",
+].join('; ');
+
+/**
+ * The same page injected into a sandboxed srcdoc frame has an opaque origin, so
+ * 'self' matches nothing there. This policy names this server instead, drops
+ * base-uri (the injected must apply), and keeps network access closed.
+ */
+const LESSON_CSP_SRCDOC = [
+ // The stylesheet and the bridge are inlined, so inline is the only source the
+ // page needs: a host-source list here would silently disable 'unsafe-inline'.
+ "default-src 'none'",
+ "style-src 'unsafe-inline'",
+ "script-src 'unsafe-inline'",
+ "img-src http: https: data:",
+ "font-src http: https: data:",
+ "media-src http: https: data:",
+ "connect-src 'none'",
+ "form-action 'none'",
+].join('; ');
+
+function json(response, status, body) {
+ const payload = JSON.stringify(body);
+ response.writeHead(status, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'content-length': Buffer.byteLength(payload),
+ });
+ response.end(payload);
+}
+
+function fail(response, status, code, message) {
+ json(response, status, { error: code, message: message ?? code });
+}
+
+function decodeParam(value) {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ const error = new Error('invalid_path');
+ error.code = 'INVALID_PATH';
+ throw error;
+ }
+}
+
+async function readBody(request, limit = 2_000_000) {
+ const chunks = [];
+ let size = 0;
+ for await (const chunk of request) {
+ size += chunk.length;
+ if (size > limit) {
+ const error = new Error('payload_too_large');
+ error.code = 'PAYLOAD_TOO_LARGE';
+ throw error;
+ }
+ chunks.push(chunk);
+ }
+ if (!chunks.length) return {};
+ try {
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ } catch {
+ const error = new Error('invalid_json');
+ error.code = 'INVALID_JSON';
+ throw error;
+ }
+}
+
+function errorStatus(error) {
+ switch (error?.code) {
+ case 'NOT_FOUND':
+ return 404;
+ case 'SETUP_REQUIRED':
+ case 'BUSY':
+ case 'ANSWER_PENDING':
+ case 'NO_QUESTION':
+ case 'NO_PERMISSION':
+ case 'TARGET_NOT_EMPTY':
+ return 409;
+ case 'PARENT_NOT_FOUND':
+ case 'NOT_A_WORKSPACE':
+ case 'TOPIC_REQUIRED':
+ case 'INVALID_JSON':
+ case 'HOME_NOT_ALLOWED':
+ case 'DRIVE_ROOT_NOT_ALLOWED':
+ case 'NO_LESSONS':
+ case 'PATH_OUTSIDE':
+ case 'INVALID_PATH':
+ case 'PAYLOAD_TOO_LARGE':
+ case 'INVALID_TEMPLATE':
+ case 'TEMPLATE_LIMIT':
+ case 'INVALID_ACTION':
+ return 400;
+ case 'TEMPLATE_NOT_FOUND':
+ return 404;
+ case 'SESSION_CREATE_FAILED':
+ return 502;
+ default:
+ return 500;
+ }
+}
+
+export async function start(context) {
+ initStore(context.dataDir);
+ // The vocabulary guard runs on every start, so a module that grows its own
+ // copy of a workspace path does not wait for someone to remember the CLI.
+ let pathCheck = { ok: true, failures: [] };
+ try {
+ pathCheck = checkPaths();
+ } catch (error) {
+ pathCheck = { ok: false, failures: [`check-paths 无法运行:${error?.message ?? error}`] };
+ }
+ if (!pathCheck.ok) console.error(`[check-paths]\n${pathCheck.failures.join('\n')}`);
+ for (const workspace of await listWorkspaces()) {
+ await refreshRules(workspace.root).catch(() => {});
+ await refreshCourseCss(workspace.root).catch(() => {});
+ await reconcileRunningSessions(workspace.root).catch(() => {});
+ }
+ const clientRoot = path.join(context.pluginRoot, 'miniapp', 'client');
+ const surfaceHtml = await readFile(path.join(clientRoot, 'index.html'), 'utf8');
+
+ /** @type {Set} */
+ const clients = new Set();
+
+ const emit = (wsId, payload) => {
+ const frame = `data: ${JSON.stringify({ wsId, ...payload })}\n\n`;
+ for (const response of clients) {
+ try {
+ response.write(frame);
+ } catch {
+ clients.delete(response);
+ }
+ }
+ };
+
+ const warming = new Set();
+ let disposing = false;
+
+ const agent = createAgentService({
+ context,
+ emit,
+ onCurriculumImported: (ws) => {
+ void warmLessonSessions(ws);
+ },
+ });
+
+ async function warmLessonSessions(ws) {
+ const key = `warm:${ws.id}`;
+ if (warming.has(key) || disposing) return;
+ warming.add(key);
+ try {
+ const snap = await loadSnapshot(ws);
+ const pending = snap.curriculum.modules
+ .flatMap((module) => module.lessons)
+ .filter((lesson) => !lesson.sessionId);
+ for (let index = 0; index < pending.length; index += 3) {
+ if (disposing) break;
+ const batch = pending.slice(index, index + 3);
+ await Promise.all(
+ batch.map((lesson) =>
+ agent.openLesson(ws, lesson.id, { seed: false }).catch(() => undefined),
+ ),
+ );
+ }
+ if (!disposing) emit(ws.id, { t: 'state' });
+ } catch {
+ /* warming is best effort; a lesson session is created when it is opened */
+ } finally {
+ warming.delete(key);
+ }
+ }
+
+ async function requireWorkspace(id) {
+ const ws = await getWorkspace(id);
+ if (!ws) {
+ const error = new Error('workspace_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ return ws;
+ }
+
+ async function serveClient(response, pathname) {
+ if (pathname === SURFACE || pathname === '/' || pathname === '/index.html') {
+ response.writeHead(200, {
+ 'content-type': 'text/html; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ response.end(surfaceHtml);
+ return true;
+ }
+ const name = pathname.slice(1);
+ if (!['app.css', 'app.js', 'lesson-bridge.js'].includes(name)) return false;
+ try {
+ const body = await readFile(path.join(clientRoot, name));
+ const type = MIME[path.extname(name)] ?? 'application/octet-stream';
+ response.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' });
+ response.end(body);
+ return true;
+ } catch {
+ fail(response, 404, 'client_asset_missing', name);
+ return true;
+ }
+ }
+
+ /** Resolve one relative reference of a workspace file to its text. */
+ async function readLocalAsset(root, docRel, href) {
+ if (!href || href.startsWith('#') || href.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(href)) {
+ return null;
+ }
+ let decoded = href.split('#')[0].split('?')[0];
+ try {
+ decoded = decodeURIComponent(decoded);
+ } catch {
+ /* keep the raw value */
+ }
+ const dir = docRel.includes('/') ? docRel.slice(0, docRel.lastIndexOf('/')) : '';
+ const parts = [];
+ for (const segment of (dir ? dir.split('/') : []).concat(decoded.split('/'))) {
+ if (!segment || segment === '.') continue;
+ if (segment === '..') {
+ if (!parts.length) return null;
+ parts.pop();
+ continue;
+ }
+ parts.push(segment);
+ }
+ try {
+ return await readText(resolveInside(root, parts.join('/')), '');
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * A srcdoc page has an opaque origin, and Chrome does not apply a stylesheet
+ * it loads from another origin there. Local stylesheets are inlined instead,
+ * so the lesson keeps its own look without a cross-origin fetch.
+ */
+ async function inlineLocalStyles(html, root, docRel) {
+ let out = html;
+ for (const match of [...html.matchAll(/]*>/gi)]) {
+ const tag = match[0];
+ if (!/rel\s*=\s*["']?stylesheet/i.test(tag)) continue;
+ const href = /href\s*=\s*"([^"]*)"/i.exec(tag);
+ const css = href ? await readLocalAsset(root, docRel, href[1]) : null;
+ if (!css) continue;
+ out = out.replace(tag, ``);
+ }
+ return out;
+ }
+
+ async function injectBridge(html, { root, wsId, rel, lessonId, annotations }) {
+ const payload = JSON.stringify({
+ wsId,
+ rel,
+ lessonId,
+ annotations: annotations.map((item) => ({ id: item.id, quote: item.quote, note: item.note })),
+ }).replace(/ goes first, before any URL attribute.
+ const segments = String(rel || '')
+ .split('/')
+ .slice(0, -1)
+ .filter(Boolean)
+ .map(encodeURIComponent);
+ const baseHref = `/w/${encodeURIComponent(wsId)}/${segments.length ? `${segments.join('/')}/` : ''}`;
+ const head = ``;
+ const styled = await inlineLocalStyles(html, root, rel);
+ const withHead = /]*)>/i.test(styled)
+ ? styled.replace(/]*)>/i, `${head}`)
+ : `${head}${styled}`;
+ // The bridge is inlined too: a cross-origin script would be a second
+ // dependency the sandboxed frame cannot be relied on to fetch.
+ const bridge = (await readFile(path.join(clientRoot, 'lesson-bridge.js'), 'utf8')).replace(
+ /<\/script/gi,
+ '<\\/script',
+ );
+ const snippet = ``;
+ if (/<\/body>/i.test(withHead)) return withHead.replace(/<\/body>/i, `${snippet}\n`);
+ return `${withHead}\n${snippet}`;
+ }
+
+ async function serveWorkspaceFile(response, ws, relative) {
+ const rel = toPosix(relative);
+ if (!rel || rel.includes('..') || rel.includes('\0')) {
+ fail(response, 400, 'invalid_path');
+ return;
+ }
+ if (rel.startsWith(WORKBENCH_DIR + '/')) {
+ fail(response, 403, 'reserved_path');
+ return;
+ }
+ const ext = path.extname(rel).toLowerCase();
+ if (!MIME[ext]) {
+ fail(response, 415, 'unsupported_type');
+ return;
+ }
+ let absolute;
+ try {
+ absolute = resolveInside(ws.root, rel);
+ } catch {
+ fail(response, 400, 'invalid_path');
+ return;
+ }
+ const info = await stat(absolute).catch(() => null);
+ if (!info?.isFile()) {
+ fail(response, 404, 'file_not_found', rel);
+ return;
+ }
+
+ if (ext === '.html') {
+ const curriculum = await readCurriculum(ws.root, { topic: ws.name }).then(
+ (result) => result.curriculum,
+ () => null,
+ );
+ const lesson = curriculum
+ ? curriculum.modules
+ .flatMap((module) => module.lessons)
+ .find((entry) => entry.file === rel)
+ : null;
+ const annotations = lesson
+ ? (await readAnnotations(ws.root)).items.filter((item) => item.lessonId === lesson.id)
+ : [];
+ const html = await readFile(absolute, 'utf8');
+ response.writeHead(200, {
+ 'content-type': MIME[ext],
+ 'cache-control': 'no-store',
+ 'x-content-type-options': 'nosniff',
+ 'content-security-policy': LESSON_CSP,
+ });
+ response.end(
+ await injectBridge(html, { root: ws.root, wsId: ws.id, rel, lessonId: lesson?.id ?? '', annotations }),
+ );
+ return;
+ }
+
+ if (TEXT_EXT.has(ext)) {
+ const body = await readFile(absolute, 'utf8');
+ response.writeHead(200, {
+ 'content-type': MIME[ext],
+ 'cache-control': 'no-store',
+ 'x-content-type-options': 'nosniff',
+ });
+ response.end(body);
+ return;
+ }
+
+ response.writeHead(200, {
+ 'content-type': MIME[ext],
+ 'cache-control': 'no-store',
+ 'content-length': info.size,
+ 'x-content-type-options': 'nosniff',
+ });
+ createReadStream(absolute).pipe(response);
+ }
+
+ async function handleApi(request, response, url) {
+ const { pathname } = url;
+
+ if (pathname === '/api/models' && request.method === 'GET') {
+ if (typeof context.agent?.models !== 'function') {
+ fail(response, 501, 'models_unavailable');
+ return true;
+ }
+ const catalog = await context.agent.models().catch(() => null);
+ if (!catalog) {
+ fail(response, 502, 'models_unavailable');
+ return true;
+ }
+ json(response, 200, catalog);
+ return true;
+ }
+
+ if (pathname === '/api/bootstrap' && request.method === 'GET') {
+ const workspaces = await listWorkspaces();
+ let models = null;
+ if (typeof context.agent?.models === 'function') {
+ models = await context.agent.models().catch((error) => ({ error: String(error?.message ?? error) }));
+ }
+ // The catalog is what the composer offers; null when this host build has no models().
+ json(response, 200, {
+ surface: SURFACE,
+ platform: process.platform,
+ home: homeDir(),
+ drives: platformRoots(),
+ workspaces,
+ cleanTargets: cleanTargets(),
+ models,
+ teacherPresets: teacherPresetsPublic(),
+ noteTemplates: noteTemplatesPublic(),
+ diagnostics: { pathVocabulary: pathCheck.failures },
+ });
+ return true;
+ }
+
+ if (pathname === '/api/fs/list' && request.method === 'GET') {
+ const requested = url.searchParams.get('path') || homeDir();
+ if (!path.isAbsolute(requested)) {
+ fail(response, 400, 'path_must_be_absolute');
+ return true;
+ }
+ const target = path.resolve(requested);
+ // The folder picker browses whole drives, so any path on a local drive is
+ // allowed; UNC and other non-local paths are refused.
+ const allowed =
+ isInside(homeDir(), target) || platformRoots().some((root) => isInside(root, target));
+ if (!allowed) {
+ fail(response, 403, 'path_not_allowed');
+ return true;
+ }
+ const info = await stat(target).catch(() => null);
+ if (!info || !info.isDirectory()) {
+ fail(response, 400, 'not_a_directory');
+ return true;
+ }
+ const entries = await readdir(target, { withFileTypes: true }).catch(() => []);
+ const dirs = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '$RECYCLE.BIN') continue;
+ const child = path.join(target, entry.name);
+ const isWorkspace = await access(path.join(child, STATE_RELS.meta)).then(
+ () => true,
+ () => false,
+ );
+ dirs.push({
+ name: entry.name,
+ path: child,
+ hidden: entry.name.startsWith('.') || entry.name.startsWith('$'),
+ isWorkspace,
+ });
+ }
+ dirs.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
+ json(response, 200, {
+ path: target,
+ parent: parentOf(target),
+ entries: dirs.slice(0, 400),
+ });
+ return true;
+ }
+
+ if (pathname === '/api/workspaces/create' && request.method === 'POST') {
+ const body = await readBody(request);
+ if (!body?.parentPath) {
+ fail(response, 400, 'parent_required');
+ return true;
+ }
+ const created = await createWorkspace({ parentPath: body.parentPath });
+ json(response, 200, { workspace: created.workspace, existing: Boolean(created.existing) });
+ return true;
+ }
+
+ if (pathname === '/api/workspaces/import' && request.method === 'POST') {
+ const body = await readBody(request);
+ const imported = await importWorkspace({ root: body.root });
+ void warmLessonSessions(imported.workspace);
+ json(response, 200, { workspace: imported.workspace });
+ return true;
+ }
+
+ if (pathname === '/api/workspaces/forget' && request.method === 'POST') {
+ const body = await readBody(request);
+ await forgetWorkspace(String(body.id ?? ''));
+ json(response, 200, { ok: true });
+ return true;
+ }
+
+ const wsMatch = pathname.match(/^\/api\/ws\/([^/]+)(\/(.*))?$/);
+ if (wsMatch) {
+ const ws = await requireWorkspace(decodeURIComponent(wsMatch[1]));
+ const rest = wsMatch[3] ?? '';
+
+ if (rest === '' && request.method === 'GET') {
+ json(response, 200, await loadSnapshot(ws));
+ return true;
+ }
+
+ if (rest === 'rules' && request.method === 'GET') {
+ json(response, 200, {
+ text: await readRules(ws.root),
+ path: rulesPath(ws.root),
+ });
+ return true;
+ }
+
+ if (rest === 'refresh' && request.method === 'POST') {
+ const meta = await readMeta(ws.root);
+ const imported = await importCurriculum(ws.root, meta ?? {});
+ // Re-reading the directory re-reads the mission too: a fixed title is the
+ // workspace's name, and this is the button the overview offers.
+ const mission = readMission(await readText(path.join(ws.root, 'MISSION.md'), ''));
+ if (mission.title) await registerWorkspace(ws.root, { name: mission.title, touch: false });
+ if (imported.curriculum.modules.length) void warmLessonSessions(ws);
+ json(response, 200, {
+ snapshot: await loadSnapshot(ws),
+ error: imported.error ?? null,
+ });
+ return true;
+ }
+
+ if (rest === 'teacher' && request.method === 'POST') {
+ const body = await readBody(request);
+ const action = String(body.action ?? 'select');
+ const name = String(body.name ?? '').replace(/\r\n/g, '\n').trim().slice(0, 24);
+ const prompt = String(body.prompt ?? '').replace(/\r\n/g, '\n').trim().slice(0, 2000);
+ const id = String(body.id ?? '').trim();
+ let failure = '';
+ const teacher = await mutateTeacher(ws.root, (current) => {
+ if (action === 'select') {
+ if (!presetById(id) && !current.custom.some((item) => item.id === id)) {
+ failure = 'TEMPLATE_NOT_FOUND';
+ return null;
+ }
+ current.selected = id;
+ return current;
+ }
+ if (action === 'create') {
+ if (!name || !prompt) {
+ failure = 'INVALID_TEMPLATE';
+ return null;
+ }
+ if (current.custom.length >= 12) {
+ failure = 'TEMPLATE_LIMIT';
+ return null;
+ }
+ const nextId = newTeacherId();
+ current.custom.unshift({
+ id: nextId,
+ name,
+ prompt,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ current.selected = nextId;
+ return current;
+ }
+ if (action === 'update') {
+ const item = current.custom.find((entry) => entry.id === id);
+ if (!item) {
+ failure = 'TEMPLATE_NOT_FOUND';
+ return null;
+ }
+ if (!name || !prompt) {
+ failure = 'INVALID_TEMPLATE';
+ return null;
+ }
+ item.name = name;
+ item.prompt = prompt;
+ item.updatedAt = Date.now();
+ return current;
+ }
+ if (action === 'delete') {
+ const item = current.custom.find((entry) => entry.id === id);
+ if (!item) {
+ failure = 'TEMPLATE_NOT_FOUND';
+ return null;
+ }
+ current.custom = current.custom.filter((entry) => entry.id !== id);
+ if (current.selected === id) current.selected = DEFAULT_TEACHER_ID;
+ return current;
+ }
+ failure = 'INVALID_ACTION';
+ return null;
+ });
+ if (failure) {
+ fail(response, failure === 'TEMPLATE_NOT_FOUND' ? 404 : 400, failure);
+ return true;
+ }
+ emit(ws.id, { t: 'state' });
+ json(response, 200, { ok: true, teacher });
+ return true;
+ }
+
+ if (rest === 'clean' && request.method === 'POST') {
+ const body = await readBody(request);
+ const wanted = cleanKeys(body.targets);
+ if (!wanted.length) {
+ fail(response, 400, 'nothing_selected');
+ return true;
+ }
+ // Running turns would write the state directory back and restore the
+ // files this clean deletes, so they are stopped and awaited first.
+ await agent.cancelAll(ws);
+ const result = await cleanWorkspace(ws.root, wanted);
+ emit(ws.id, { t: 'state' });
+ json(response, 200, result);
+ return true;
+ }
+
+ if (rest === 'setup/open' && request.method === 'POST') {
+ const result = await agent.openSetup(ws);
+ json(response, 200, result);
+ return true;
+ }
+
+ if (rest === 'main/open' && request.method === 'POST') {
+ const result = await agent.seedMain(ws);
+ json(response, 200, result);
+ return true;
+ }
+
+ if (rest === 'curriculum' && request.method === 'POST') {
+ const result = await agent.curriculumTurn(ws);
+ json(response, 200, result);
+ return true;
+ }
+
+ const lessonMatch = rest.match(/^lessons\/([^/]+)\/(open|status|renew|regenerate)$/);
+ if (lessonMatch) {
+ const lessonId = decodeParam(lessonMatch[1]);
+ if (lessonMatch[2] === 'open' && request.method === 'POST') {
+ const body = await readBody(request).catch(() => ({}));
+ const result = await agent.openLesson(ws, lessonId, { seed: body?.seed !== false });
+ json(response, 200, result);
+ return true;
+ }
+ if (lessonMatch[2] === 'regenerate' && request.method === 'POST') {
+ const result = await agent.regenerateLesson(ws, lessonId);
+ json(response, 200, result);
+ return true;
+ }
+ if (lessonMatch[2] === 'renew' && request.method === 'POST') {
+ const result = await agent.renewLesson(ws, lessonId);
+ json(response, 200, result);
+ return true;
+ }
+ if (lessonMatch[2] === 'status' && request.method === 'POST') {
+ const body = await readBody(request);
+ const status = ['planned', 'active', 'done'].includes(body.status) ? body.status : null;
+ if (!status) {
+ fail(response, 400, 'invalid_status');
+ return true;
+ }
+ const meta = await readMeta(ws.root);
+ const updated = await mutateCurriculum(ws.root, meta ?? {}, (curriculum) => {
+ const lesson = findLesson(curriculum, lessonId);
+ if (!lesson) return null;
+ lesson.status = status;
+ return curriculum;
+ });
+ if (!updated) {
+ fail(response, 404, 'lesson_not_found', lessonId);
+ return true;
+ }
+ emit(ws.id, { t: 'state' });
+ json(response, 200, { ok: true, snapshot: await loadSnapshot(ws) });
+ return true;
+ }
+ }
+
+ const sessionMatch = rest.match(/^sessions\/([^/]+)(?:\/(send|reply|answer|cancel|continue|model))?$/);
+ if (sessionMatch) {
+ const sessionId = decodeParam(sessionMatch[1]);
+ const action = sessionMatch[2] ?? '';
+ if (!action && request.method === 'GET') {
+ const session = await getSession(ws.root, sessionId);
+ if (!session) {
+ fail(response, 404, 'session_not_found');
+ return true;
+ }
+ json(response, 200, session);
+ return true;
+ }
+ if (action === 'send' && request.method === 'POST') {
+ const body = await readBody(request);
+ const text = String(body.text ?? '').trim();
+ if (!text) {
+ fail(response, 400, 'empty_text');
+ return true;
+ }
+ const result = await agent.send(ws, sessionId, text);
+ json(response, 200, { ok: true, ...result });
+ return true;
+ }
+ if (action === 'reply' && request.method === 'POST') {
+ const body = await readBody(request);
+ const decision = body.decision === 'allowOnce' ? 'allowOnce' : 'deny';
+ const result = await agent.reply(ws, sessionId, String(body.requestId ?? ''), decision);
+ json(response, 200, result);
+ return true;
+ }
+ if (action === 'answer' && request.method === 'POST') {
+ const body = await readBody(request);
+ const answers = Array.isArray(body.answers) ? body.answers : [];
+ const result = await agent.answer(ws, sessionId, String(body.requestId ?? ''), answers);
+ json(response, 200, result);
+ return true;
+ }
+ if (action === 'cancel' && request.method === 'POST') {
+ json(response, 200, { ok: agent.cancel(ws, sessionId) });
+ return true;
+ }
+ if (action === 'continue' && request.method === 'POST') {
+ json(response, 200, await agent.continueTurn(ws, sessionId));
+ return true;
+ }
+ if (action === 'model' && request.method === 'POST') {
+ const body = await readBody(request);
+ const selection = normalizeModelSelection(body.model);
+ const record = await getSession(ws.root, sessionId);
+ if (!record) {
+ fail(response, 404, 'session_not_found');
+ return true;
+ }
+ if (record.running) {
+ fail(response, 409, 'session_busy');
+ return true;
+ }
+ const catalog =
+ typeof context.agent?.models === 'function' ? await context.agent.models().catch(() => null) : null;
+ const known = Boolean(
+ selection &&
+ catalog &&
+ catalog.models.some(
+ (item) => item.providerId === selection.providerId && item.modelId === selection.modelId,
+ ),
+ );
+ if (!known) {
+ fail(response, 400, 'unknown_model');
+ return true;
+ }
+ record.model = selection;
+ record.updatedAt = Date.now();
+ await saveSession(ws.root, record);
+ emit(ws.id, { t: 'session', sessionId, session: sessionSummary(record) });
+ json(response, 200, { session: sessionSummary(record) });
+ return true;
+ }
+ }
+
+ if (rest === 'annotations' && request.method === 'POST') {
+ const body = await readBody(request);
+ const action = String(body.action ?? 'create');
+ const note = String(body.note ?? '').trim();
+ if (action !== 'delete' && !note) {
+ fail(response, 400, 'empty_note');
+ return true;
+ }
+ let missing = false;
+ const next = await mutateAnnotations(ws.root, (current) => {
+ if (action === 'create') {
+ const lessonId = String(body.lessonId ?? '');
+ const quote = String(body.quote ?? '').trim().slice(0, 600);
+ if (!lessonId) {
+ missing = true;
+ return null;
+ }
+ current.items.unshift({
+ id: `an_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`,
+ lessonId,
+ quote,
+ note: note.slice(0, 4000),
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ return current;
+ }
+ const item = current.items.find((entry) => entry.id === String(body.id ?? ''));
+ if (!item) {
+ missing = true;
+ return null;
+ }
+ if (action === 'update') {
+ item.note = note.slice(0, 4000);
+ item.updatedAt = Date.now();
+ return current;
+ }
+ current.items = current.items.filter((entry) => entry.id !== item.id);
+ return current;
+ });
+ if (missing || !next) {
+ fail(response, 404, 'annotation_not_found');
+ return true;
+ }
+ emit(ws.id, { t: 'annotations' });
+ json(response, 200, { annotations: next.items });
+ return true;
+ }
+
+ if (rest === 'notes' && request.method === 'POST') {
+ const body = await readBody(request);
+ const lessonIds = Array.isArray(body.lessonIds)
+ ? body.lessonIds.filter((id) => typeof id === 'string')
+ : [];
+ if (!lessonIds.length) {
+ fail(response, 400, 'no_lessons');
+ return true;
+ }
+ const result = await agent.startNoteJob(ws, {
+ lessonIds,
+ title: String(body.title ?? '').trim(),
+ templateId: String(body.templateId ?? '').trim(),
+ request: String(body.request ?? ''),
+ });
+ emit(ws.id, { t: 'state' });
+ json(response, 200, result);
+ return true;
+ }
+
+ const noteMatch = rest.match(/^notes\/([^/]+)$/);
+ if (noteMatch && request.method === 'POST') {
+ const noteId = decodeParam(noteMatch[1]);
+ const body = await readBody(request);
+ const action = String(body.action ?? '');
+ if (action === 'regenerate') {
+ const result = await agent.startNoteJob(ws, {
+ noteId,
+ request: String(body.request ?? ''),
+ });
+ emit(ws.id, { t: 'state' });
+ json(response, 200, result);
+ return true;
+ }
+ if (action === 'rename') {
+ const title = String(body.title ?? '').trim().slice(0, 80);
+ if (!title) {
+ fail(response, 400, 'empty_title');
+ return true;
+ }
+ const current = await readNotes(ws.root);
+ const item = current.items.find((entry) => entry.id === noteId);
+ if (!item) {
+ fail(response, 404, 'note_not_found');
+ return true;
+ }
+ const previous = item.title;
+ await mutateNotes(ws.root, (notes) => {
+ const entry = notes.items.find((row) => row.id === noteId);
+ if (!entry) return null;
+ entry.title = title;
+ entry.updatedAt = Date.now();
+ return notes;
+ });
+ // The file name stays put; only the document's own heading follows the title.
+ if (item.path && classify(item.path).id === 'notes') {
+ const absolute = resolveInside(ws.root, item.path);
+ const raw = await readText(absolute, '');
+ const first = raw.split('\n', 1)[0] || '';
+ if (previous && first.trim() === `# ${previous}`) {
+ await writeText(absolute, `# ${title}${raw.slice(first.length)}`);
+ }
+ }
+ emit(ws.id, { t: 'state' });
+ json(response, 200, { ok: true, title, snapshot: await loadSnapshot(ws) });
+ return true;
+ }
+ if (action === 'tags') {
+ const tags = normalizeTags(body.tags);
+ let found = false;
+ await mutateNotes(ws.root, (notes) => {
+ const item = notes.items.find((entry) => entry.id === noteId);
+ if (!item) return null;
+ found = true;
+ item.tags = tags;
+ item.updatedAt = Date.now();
+ return notes;
+ });
+ if (!found) {
+ fail(response, 404, 'note_not_found');
+ return true;
+ }
+ emit(ws.id, { t: 'state' });
+ json(response, 200, { ok: true, tags });
+ return true;
+ }
+ if (action === 'delete') {
+ const current = await readNotes(ws.root);
+ const item = current.items.find((entry) => entry.id === noteId);
+ if (!item) {
+ fail(response, 404, 'note_not_found');
+ return true;
+ }
+ // Only a note's own markdown file is removed; anything else is left alone.
+ if (item.path && classify(item.path).id === 'notes') {
+ await rm(resolveInside(ws.root, item.path), { force: true });
+ }
+ await mutateNotes(ws.root, (notes) => {
+ notes.items = notes.items.filter((entry) => entry.id !== noteId);
+ return notes;
+ });
+ emit(ws.id, { t: 'state' });
+ json(response, 200, { ok: true, snapshot: await loadSnapshot(ws) });
+ return true;
+ }
+ fail(response, 400, 'invalid_action');
+ return true;
+ }
+
+ if (rest === 'file' && request.method === 'GET') {
+ const rel = toPosix(url.searchParams.get('rel') ?? '');
+ const ext = path.extname(rel).toLowerCase();
+ if (!rel || rel.includes('..') || rel.startsWith(WORKBENCH_DIR + '/') || !READABLE_EXT.has(ext)) {
+ fail(response, 400, 'invalid_path');
+ return true;
+ }
+ const absolute = resolveInside(ws.root, rel);
+ const info = await stat(absolute).catch(() => null);
+ if (!info?.isFile()) {
+ fail(response, 404, 'file_not_found', rel);
+ return true;
+ }
+ if (info.size > 512 * 1024) {
+ fail(response, 413, 'file_too_large');
+ return true;
+ }
+ const body = await readText(absolute, '');
+ json(response, 200, { rel, text: body });
+ return true;
+ }
+
+ fail(response, 404, 'not_found', rest);
+ return true;
+ }
+
+ if (pathname === '/api/events' && request.method === 'GET') {
+ response.writeHead(200, {
+ 'content-type': 'text/event-stream; charset=utf-8',
+ 'cache-control': 'no-cache, no-transform',
+ connection: 'keep-alive',
+ 'x-accel-buffering': 'no',
+ });
+ response.write(': ok\n\n');
+ clients.add(response);
+ const ping = setInterval(() => {
+ try {
+ response.write(': ping\n\n');
+ } catch {
+ /* ignore */
+ }
+ }, 30_000);
+ if (ping.unref) ping.unref();
+ const close = () => {
+ clearInterval(ping);
+ clients.delete(response);
+ };
+ request.on('close', close);
+ request.on('aborted', close);
+ return true;
+ }
+
+ return false;
+ }
+
+ const server = createServer((request, response) => {
+ void (async () => {
+ const url = new URL(request.url ?? '/', 'http://miniapp.local');
+ try {
+ if (request.method === 'GET' || request.method === 'HEAD') {
+ if (await serveClient(response, url.pathname)) return;
+ }
+
+ const workspaceFile = url.pathname.match(/^\/w\/([^/]+)\/(.+)$/);
+ if (workspaceFile && request.method === 'GET') {
+ const ws = await requireWorkspace(decodeParam(workspaceFile[1]));
+ await serveWorkspaceFile(response, ws, decodeParam(workspaceFile[2]));
+ return;
+ }
+
+ if (await handleApi(request, response, url)) return;
+
+ fail(response, 404, 'not_found', url.pathname);
+ } catch (error) {
+ const code = error?.code ?? 'internal_error';
+ if (response.headersSent) {
+ try {
+ response.end();
+ } catch {
+ /* ignore */
+ }
+ return;
+ }
+ if (response.writableEnded) return;
+ if (code === 'internal_error') {
+ context.logger?.error?.('request_failed', {
+ path: url.pathname,
+ message: String(error?.message ?? error).slice(0, 300),
+ });
+ }
+ fail(response, errorStatus(error), code, error?.message);
+ }
+ })();
+ });
+
+ await new Promise((resolve, reject) => {
+ const onError = (error) => reject(error);
+ server.once('error', onError);
+ server.listen(context.listen.port, context.listen.host, () => {
+ server.off('error', onError);
+ resolve();
+ });
+ });
+
+ let disposal;
+ const dispose = () => {
+ if (disposal) return disposal;
+ disposing = true;
+ context.signal.removeEventListener('abort', onAbort);
+ disposal = new Promise((resolve) => {
+ agent.abortAll();
+ for (const client of clients) {
+ try {
+ client.end();
+ } catch {
+ /* ignore */
+ }
+ }
+ clients.clear();
+ // The Host gives 2 s; never let a lingering connection hold the exit.
+ const timer = setTimeout(() => {
+ try {
+ server.closeAllConnections?.();
+ } catch {
+ /* ignore */
+ }
+ resolve();
+ }, 1500);
+ if (timer.unref) timer.unref();
+ server.close(() => {
+ clearTimeout(timer);
+ resolve();
+ });
+ });
+ return disposal;
+ };
+ const onAbort = () => {
+ void dispose().catch(() => undefined);
+ };
+ context.signal.addEventListener('abort', onAbort, { once: true });
+ if (context.signal.aborted) await dispose();
+
+ return { dispose };
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/store.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/store.mjs
new file mode 100644
index 00000000..ad628a22
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/store.mjs
@@ -0,0 +1,831 @@
+import { createHash } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { mkdir, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import {
+ fileMeta,
+ listFiles,
+ readJson,
+ readJsonChecked,
+ readText,
+ resolveInside,
+ slugify,
+ toPosix,
+ writeJsonAtomic,
+ writeText,
+} from './fsx.mjs';
+import { classify, STATE_RELS, workbenchPaths } from './policy.mjs';
+import { ensureScaffold } from './scaffold.mjs';
+import { normalizeTeacher } from './teacher-presets.mjs';
+
+export const EMPTY_CURRICULUM = {
+ schemaVersion: 1,
+ topic: '',
+ updatedAt: 0,
+ modules: [],
+};
+
+const EMPTY_ANNOTATIONS = { schemaVersion: 1, items: [] };
+const EMPTY_NOTES = { schemaVersion: 1, items: [] };
+const EMPTY_SESSIONS = { schemaVersion: 1, sessions: {} };
+
+let DATA_DIR = '';
+
+/**
+ * Files written by the app itself during a turn, per workspace root.
+ * A restore must leave those alone: only an out-of-scope session write is
+ * reverted, and node's own bookkeeping (curriculum, indexes) is not a
+ * violation even when it lands inside the same time window.
+ */
+let writeSeq = 0;
+const nodeWrites = new Map();
+const rootKey = (root) => path.resolve(root).toLowerCase();
+
+function markNodeWrite(root, rel) {
+ const key = rootKey(root);
+ let marks = nodeWrites.get(key);
+ if (!marks) {
+ marks = new Map();
+ nodeWrites.set(key, marks);
+ }
+ marks.set(rel, ++writeSeq);
+}
+
+export function nodeWriteCursor() {
+ return writeSeq;
+}
+
+export function nodeWritesAfter(root, cursor) {
+ const marks = nodeWrites.get(rootKey(root));
+ const out = new Set();
+ if (!marks) return out;
+ for (const [rel, seq] of marks) {
+ if (seq > cursor) out.add(rel);
+ }
+ return out;
+}
+
+/**
+ * Cleans that already started, per workspace root.
+ *
+ * A turn that was running when 「清理产物」 began must not write its state back or
+ * restore what the clean deleted. The clean claims its paths before the first
+ * rm; a turn compares the cursor it took when it started.
+ */
+let cleanSeq = 0;
+const cleanLog = new Map();
+
+export function cleanCursor() {
+ return cleanSeq;
+}
+
+export function cleanSince(root, cursor) {
+ const list = cleanLog.get(rootKey(root)) ?? [];
+ return list.filter((entry) => entry.seq > (cursor ?? 0));
+}
+
+export function markClean(root, { keys = [], paths = [] } = {}) {
+ const key = rootKey(root);
+ const entry = { seq: ++cleanSeq, keys: [...keys], paths: [...paths], at: Date.now() };
+ // Keep the log short: only turns that started before the newest clean matter.
+ cleanLog.set(key, [...(cleanLog.get(key) ?? []).slice(-7), entry]);
+ return entry.seq;
+}
+
+export function initStore(dataDir) {
+ DATA_DIR = dataDir;
+ return dataDir;
+}
+
+export function workspaceId(root) {
+ const key = path.resolve(root).toLowerCase();
+ return `ws_${createHash('sha1').update(key).digest('hex').slice(0, 10)}`;
+}
+
+/* ------------------------------------------------------------------ locks */
+
+const chains = new Map();
+
+export function withLock(key, fn) {
+ const prev = chains.get(key) ?? Promise.resolve();
+ const next = prev.then(fn, fn);
+ chains.set(
+ key,
+ next.then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ return next;
+}
+
+/* --------------------------------------------------------------- registry */
+
+function registryPath() {
+ return path.join(DATA_DIR, 'registry.json');
+}
+
+async function readRegistry() {
+ const raw = await readJson(registryPath(), { schemaVersion: 1, workspaces: [] });
+ const list = Array.isArray(raw.workspaces) ? raw.workspaces : [];
+ return {
+ schemaVersion: 1,
+ workspaces: list.filter((item) => item && typeof item.root === 'string'),
+ };
+}
+
+export async function listWorkspaces() {
+ const registry = await readRegistry();
+ const out = [];
+ for (const item of registry.workspaces) {
+ if (!existsSync(item.root)) continue;
+ out.push({
+ ...item,
+ name: item.name || path.basename(item.root),
+ exists: true,
+ });
+ }
+ out.sort((a, b) => (b.lastOpenedAt ?? 0) - (a.lastOpenedAt ?? 0));
+ return out;
+}
+
+export async function getWorkspace(id) {
+ const registry = await readRegistry();
+ const found = registry.workspaces.find((item) => item.id === id);
+ if (!found) return null;
+ if (!existsSync(found.root)) return null;
+ return found;
+}
+
+async function saveRegistry(registry) {
+ await writeJsonAtomic(registryPath(), registry);
+}
+
+export async function registerWorkspace(root, { name, touch = true } = {}) {
+ return withLock('registry', async () => {
+ const registry = await readRegistry();
+ const id = workspaceId(root);
+ const now = Date.now();
+ const existing = registry.workspaces.find((item) => item.id === id);
+ if (existing) {
+ existing.root = root;
+ if (name) existing.name = name;
+ if (touch) existing.lastOpenedAt = now;
+ } else {
+ registry.workspaces.push({
+ id,
+ root,
+ name: name || path.basename(root),
+ createdAt: now,
+ lastOpenedAt: now,
+ });
+ }
+ await saveRegistry(registry);
+ return registry.workspaces.find((item) => item.id === id);
+ });
+}
+
+export async function forgetWorkspace(id) {
+ return withLock('registry', async () => {
+ const registry = await readRegistry();
+ registry.workspaces = registry.workspaces.filter((item) => item.id !== id);
+ await saveRegistry(registry);
+ });
+}
+
+/* -------------------------------------------------------------- workspace */
+
+export async function readMeta(root) {
+ return readJson(workbenchPaths(root).meta, null);
+}
+
+export async function writeMeta(root, meta) {
+ await writeJsonAtomic(workbenchPaths(root).meta, { schemaVersion: 1, ...meta });
+ markNodeWrite(root, STATE_RELS.meta);
+}
+
+export async function readTeacher(root) {
+ const raw = await readJson(workbenchPaths(root).teacher, null);
+ return normalizeTeacher(raw);
+}
+
+export async function mutateTeacher(root, mutator) {
+ return withLock(`teacher:${root}`, async () => {
+ const current = await readTeacher(root);
+ const next = mutator(structuredClone(current));
+ if (!next) return current;
+ const saved = normalizeTeacher(next);
+ await writeJsonAtomic(workbenchPaths(root).teacher, saved);
+ markNodeWrite(root, STATE_RELS.teacher);
+ return saved;
+ });
+}
+
+async function initStateFiles(root) {
+ const p = workbenchPaths(root);
+ if (!existsSync(p.curriculum)) await writeJsonAtomic(p.curriculum, EMPTY_CURRICULUM);
+ if (!existsSync(p.annotations)) await writeJsonAtomic(p.annotations, EMPTY_ANNOTATIONS);
+ if (!existsSync(p.notes)) await writeJsonAtomic(p.notes, EMPTY_NOTES);
+ if (!existsSync(p.sessions)) await writeJsonAtomic(p.sessions, EMPTY_SESSIONS);
+ if (!existsSync(p.teacher)) await writeJsonAtomic(p.teacher, normalizeTeacher(null));
+}
+
+export async function createWorkspace({ parentPath }) {
+ const root = path.resolve(parentPath);
+ const info = await stat(root).catch(() => null);
+ if (!info || !info.isDirectory()) {
+ const error = new Error('parent_not_found');
+ error.code = 'PARENT_NOT_FOUND';
+ throw error;
+ }
+ // Scaffolding the home directory or a drive root is always a mistake; it
+ // normally means the dialog fell back to a stale path.
+ if (root.toLowerCase() === path.resolve(os.homedir()).toLowerCase()) {
+ const error = new Error('home_not_allowed');
+ error.code = 'HOME_NOT_ALLOWED';
+ throw error;
+ }
+ if (path.dirname(root) === root) {
+ const error = new Error('drive_root_not_allowed');
+ error.code = 'DRIVE_ROOT_NOT_ALLOWED';
+ throw error;
+ }
+
+ const existing = await readMeta(root);
+ const label = existing?.topic || path.basename(root);
+ await ensureScaffold(root, { topic: label });
+ const now = Date.now();
+ const id = workspaceId(root);
+ await writeMeta(root, {
+ id,
+ topic: existing?.topic ?? '',
+ createdAt: existing?.createdAt ?? now,
+ updatedAt: now,
+ mainSessionId: existing?.mainSessionId ?? null,
+ mainSeededAt: existing?.mainSeededAt ?? null,
+ setupSessionId: existing?.setupSessionId ?? null,
+ });
+ await initStateFiles(root);
+ const registered = await registerWorkspace(root, { name: existing?.topic || path.basename(root) });
+ return { root, workspace: registered, existing: Boolean(existing) };
+}
+
+export async function importWorkspace({ root: rawRoot }) {
+ const root = path.resolve(rawRoot);
+ const meta = await readMeta(root);
+ if (!meta) {
+ const error = new Error('not_a_workspace');
+ error.code = 'NOT_A_WORKSPACE';
+ throw error;
+ }
+ await ensureScaffold(root, { topic: meta.topic || path.basename(root) });
+ await initStateFiles(root);
+ if (!meta.id || meta.id !== workspaceId(root)) {
+ await writeMeta(root, { ...meta, id: workspaceId(root) });
+ }
+ const mission = await readText(path.join(root, 'MISSION.md'), '');
+ const label = readMission(mission).title || meta.topic || path.basename(root);
+ const registered = await registerWorkspace(root, { name: label });
+ return { root, workspace: registered };
+}
+
+/* ------------------------------------------------------------- curriculum */
+
+function asArray(value) {
+ return Array.isArray(value) ? value : [];
+}
+
+function text(value, fallback = '') {
+ if (typeof value === 'string') return value.trim();
+ if (typeof value === 'number') return String(value);
+ return fallback;
+}
+
+function toMinutes(value) {
+ const n = Number(value);
+ if (!Number.isFinite(n)) return 20;
+ return Math.min(60, Math.max(10, Math.round(n)));
+}
+
+/**
+ * Normalize whatever the Agent wrote into the canonical curriculum, keeping
+ * per-lesson state (session binding, generated file, status) across regenerations.
+ */
+export function normalizeCurriculum(raw, previous = EMPTY_CURRICULUM, topic = '') {
+ const source = raw && typeof raw === 'object' ? raw : {};
+ const modulesRaw = asArray(source.modules ?? source.curriculum ?? source.syllabus);
+ const prevLessons = [];
+ for (const module of asArray(previous?.modules)) {
+ for (const lesson of asArray(module.lessons)) prevLessons.push(lesson);
+ }
+ const prevById = new Map(prevLessons.map((lesson) => [lesson.id, lesson]));
+ const prevByTitle = new Map(prevLessons.map((lesson) => [lesson.title, lesson]));
+ const issues = [];
+ let no = 0;
+ const modules = [];
+
+ modulesRaw.forEach((module, moduleIndex) => {
+ if (!module || typeof module !== 'object') return;
+ const lessonsRaw = asArray(module.lessons ?? module.items);
+ const lessons = [];
+ lessonsRaw.forEach((lesson) => {
+ if (!lesson || typeof lesson !== 'object') return;
+ const title = text(lesson.title ?? lesson.name);
+ if (!title) {
+ issues.push(`模块 ${moduleIndex + 1} 有一节课缺少 title`);
+ return;
+ }
+ no += 1;
+ const previousMatch =
+ (lesson.id && prevById.get(lesson.id)) || prevByTitle.get(title) || null;
+ const id = text(lesson.id) || previousMatch?.id || `l${no}`;
+ const prev = prevById.get(id) || previousMatch;
+ const status = ['planned', 'active', 'done'].includes(lesson.status)
+ ? lesson.status
+ : (prev?.status ?? 'planned');
+ lessons.push({
+ id,
+ no,
+ title,
+ objective: text(lesson.objective ?? lesson.goal),
+ minutes: toMinutes(lesson.minutes ?? lesson.estimateMinutes),
+ status,
+ file: text(lesson.file) || prev?.file || '',
+ sessionId: text(lesson.sessionId) || prev?.sessionId || '',
+ notes: text(lesson.notes),
+ });
+ });
+ if (!lessons.length) return;
+ modules.push({
+ id: text(module.id) || `m${moduleIndex + 1}`,
+ title: text(module.title ?? module.name) || `模块 ${moduleIndex + 1}`,
+ goal: text(module.goal ?? module.description),
+ lessons,
+ });
+ });
+
+ return {
+ value: {
+ schemaVersion: 1,
+ topic: text(source.topic) || topic,
+ updatedAt: Number(source.updatedAt) || Date.now(),
+ modules,
+ },
+ issues,
+ };
+}
+
+export async function readCurriculum(root, meta) {
+ const p = workbenchPaths(root);
+ const checked = await readJsonChecked(p.curriculum, null);
+ if (!checked.value) {
+ return {
+ curriculum: { ...EMPTY_CURRICULUM, topic: meta?.topic ?? '' },
+ error: checked.error,
+ mtime: 0,
+ };
+ }
+ const previous = checked.value;
+ const { value, issues } = normalizeCurriculum(previous, previous, meta?.topic ?? '');
+ const info = await fileMeta(root, STATE_RELS.curriculum);
+ return {
+ curriculum: { ...value, issues },
+ error: checked.error,
+ mtime: info?.mtime ?? 0,
+ };
+}
+
+export async function writeCurriculum(root, curriculum) {
+ const out = {
+ schemaVersion: 1,
+ topic: curriculum.topic,
+ updatedAt: Date.now(),
+ modules: curriculum.modules.map((module) => ({
+ id: module.id,
+ title: module.title,
+ goal: module.goal,
+ lessons: module.lessons.map((lesson) => ({
+ id: lesson.id,
+ no: lesson.no,
+ title: lesson.title,
+ objective: lesson.objective,
+ minutes: lesson.minutes,
+ status: lesson.status,
+ file: lesson.file,
+ sessionId: lesson.sessionId,
+ notes: lesson.notes,
+ })),
+ })),
+ };
+ await writeJsonAtomic(workbenchPaths(root).curriculum, out);
+ markNodeWrite(root, STATE_RELS.curriculum);
+ return out;
+}
+
+export async function mutateCurriculum(root, meta, mutator) {
+ return withLock(`ws:${root}`, async () => {
+ const { curriculum } = await readCurriculum(root, meta);
+ const next = mutator(structuredClone(curriculum));
+ if (!next) return null;
+ const saved = await writeCurriculum(root, next);
+ return { ...saved, issues: [] };
+ });
+}
+
+/** Copy the current curriculum aside so a rewrite cannot lose per-lesson state. */
+export async function backupCurriculum(root) {
+ const current = await readJson(workbenchPaths(root).curriculum, null);
+ if (current) {
+ await writeJsonAtomic(workbenchPaths(root).curriculumBackup, current);
+ markNodeWrite(root, STATE_RELS.curriculumBackup);
+ }
+ return current;
+}
+
+export async function readCurriculumBackup(root) {
+ return readJson(workbenchPaths(root).curriculumBackup, null);
+}
+
+/**
+ * Import the curriculum the Agent wrote to disk. `options.previous` supplies the
+ * pre-rewrite snapshot so lesson sessions, files and status survive regeneration.
+ */
+export async function importCurriculum(root, meta, options = {}) {
+ return withLock(`ws:${root}`, async () => {
+ const p = workbenchPaths(root);
+ const checked = await readJsonChecked(p.curriculum, null);
+ if (!checked.value) {
+ return { curriculum: { ...EMPTY_CURRICULUM, topic: meta?.topic ?? '' }, error: checked.error ?? 'missing' };
+ }
+ const previous =
+ options.previous ?? (await readJson(p.curriculum, EMPTY_CURRICULUM));
+ const { value, issues } = normalizeCurriculum(checked.value, previous, meta?.topic ?? '');
+ if (!value.modules.length) {
+ return { curriculum: { ...previous, issues }, error: checked.error ?? 'no_modules' };
+ }
+ const saved = await writeCurriculum(root, value);
+ return { curriculum: { ...saved, issues }, error: checked.error };
+ });
+}
+
+export function allLessons(curriculum) {
+ const out = [];
+ for (const module of asArray(curriculum?.modules)) {
+ for (const lesson of asArray(module.lessons)) out.push(lesson);
+ }
+ return out;
+}
+
+export function findLesson(curriculum, lessonId) {
+ return allLessons(curriculum).find((lesson) => lesson.id === lessonId) ?? null;
+}
+
+/* ------------------------------------------------------------ annotations */
+
+export async function readAnnotations(root) {
+ const raw = await readJson(workbenchPaths(root).annotations, EMPTY_ANNOTATIONS);
+ const items = asArray(raw.items)
+ .filter((item) => item && typeof item.id === 'string' && typeof item.lessonId === 'string')
+ .map((item) => ({
+ id: item.id,
+ lessonId: item.lessonId,
+ quote: text(item.quote),
+ note: text(item.note),
+ createdAt: Number(item.createdAt) || 0,
+ updatedAt: Number(item.updatedAt) || 0,
+ }));
+ return { schemaVersion: 1, items };
+}
+
+export async function mutateAnnotations(root, mutator) {
+ return withLock(`ws:${root}`, async () => {
+ const current = await readAnnotations(root);
+ const next = mutator(structuredClone(current));
+ if (!next) return current;
+ await writeJsonAtomic(workbenchPaths(root).annotations, next);
+ markNodeWrite(root, STATE_RELS.annotations);
+ return next;
+ });
+}
+
+/* ------------------------------------------------------------------ notes */
+
+export const NOTE_TAG_LIMIT = 6;
+const NOTE_TAG_CHARS = 24;
+
+/** One normaliser for both the AI-written tag line and the manual tag box. */
+export function normalizeTags(input) {
+ const out = [];
+ for (const raw of asArray(input)) {
+ const tag = text(raw).replace(/^#+/, '').trim().slice(0, NOTE_TAG_CHARS);
+ if (tag && !out.includes(tag)) out.push(tag);
+ if (out.length >= NOTE_TAG_LIMIT) break;
+ }
+ return out;
+}
+
+export async function readNotes(root) {
+ const raw = await readJson(workbenchPaths(root).notes, EMPTY_NOTES);
+ const items = asArray(raw.items)
+ .filter((item) => item && typeof item.id === 'string')
+ .map((item) => ({
+ id: item.id,
+ title: text(item.title),
+ path: text(item.path),
+ lessonIds: asArray(item.lessonIds).filter((id) => typeof id === 'string'),
+ sessionId: text(item.sessionId),
+ status: ['running', 'ready', 'failed'].includes(item.status) ? item.status : 'running',
+ templateId: text(item.templateId),
+ tags: normalizeTags(item.tags),
+ createdAt: Number(item.createdAt) || 0,
+ updatedAt: Number(item.updatedAt) || 0,
+ }));
+ return { schemaVersion: 1, items };
+}
+
+export async function mutateNotes(root, mutator) {
+ return withLock(`ws:${root}`, async () => {
+ const current = await readNotes(root);
+ const next = mutator(structuredClone(current));
+ if (!next) return current;
+ await writeJsonAtomic(workbenchPaths(root).notes, next);
+ markNodeWrite(root, STATE_RELS.notes);
+ return next;
+ });
+}
+
+/**
+ * Drop index entries whose files no longer exist.
+ * 「清理产物」deletes lesson HTML and note files, so the indexes must forget those
+ * entries instead of handing the UI paths that 404.
+ */
+export async function reconcileWorkspaceFiles(root, { lessons = false, notes = false } = {}) {
+ let notesPruned = 0;
+ let lessonsReset = 0;
+
+ if (notes) {
+ await mutateNotes(root, (current) => {
+ const kept = current.items.filter((item) => {
+ if (!item.path) return item.status === 'running';
+ const alive = existsSync(resolveInside(root, item.path));
+ if (!alive) notesPruned += 1;
+ return alive;
+ });
+ return kept.length === current.items.length ? null : { ...current, items: kept };
+ });
+ }
+
+ if (lessons) {
+ await mutateCurriculum(root, {}, (current) => {
+ let changed = false;
+ for (const module of current.modules) {
+ for (const lesson of module.lessons) {
+ if (!lesson.file || existsSync(resolveInside(root, lesson.file))) continue;
+ lesson.file = '';
+ if (lesson.status !== 'planned') lesson.status = 'planned';
+ changed = true;
+ lessonsReset += 1;
+ }
+ }
+ return changed ? current : null;
+ });
+ }
+
+ return { notesPruned, lessonsReset };
+}
+
+/* --------------------------------------------------------------- sessions */
+
+export async function readSessions(root) {
+ const raw = await readJson(workbenchPaths(root).sessions, EMPTY_SESSIONS);
+ const all = raw && typeof raw.sessions === 'object' && raw.sessions ? raw.sessions : {};
+ const sessions = {};
+ for (const [id, session] of Object.entries(all)) {
+ if (!session || typeof session !== 'object') continue;
+ // A session names the workspace whose turn wrote it. A record whose root is
+ // gone can only be a leftover of a deleted or copied workspace, so it must
+ // not surface in this workspace's list.
+ if (session.root && !existsSync(session.root)) continue;
+ sessions[id] = session;
+ }
+ return { schemaVersion: 1, sessions };
+}
+
+export async function getSession(root, sessionId) {
+ const store = await readSessions(root);
+ return store.sessions[sessionId] ?? null;
+}
+
+export async function saveSession(root, session) {
+ return withLock(`ws:${root}`, async () => {
+ const store = await readSessions(root);
+ store.sessions[session.id] = session;
+ // Keep transcripts bounded so the state file stays readable.
+ if (Array.isArray(session.messages) && session.messages.length > 600) {
+ session.messages = session.messages.slice(-600);
+ }
+ await writeJsonAtomic(workbenchPaths(root).sessions, store);
+ markNodeWrite(root, STATE_RELS.sessions);
+ return session;
+ });
+}
+
+/**
+ * A turn cannot survive a runtime restart: the host run is gone, so its running
+ * flag would keep the composer stuck forever. Mark those sessions interrupted
+ * and leave a visible line that points at 「继续」.
+ */
+export async function reconcileRunningSessions(root) {
+ const store = await readSessions(root);
+ let changed = 0;
+ for (const session of Object.values(store.sessions)) {
+ if (!session) continue;
+ const waiting =
+ Boolean(session.pending) || (Array.isArray(session.permissions) && session.permissions.length > 0);
+ if (!session.running && !waiting) continue;
+ const wasRunning = Boolean(session.running);
+ session.running = null;
+ session.pending = null;
+ session.permissions = [];
+ session.interrupted = true;
+ session.updatedAt = Date.now();
+ session.messages = Array.isArray(session.messages) ? session.messages : [];
+ session.messages.push(
+ makeMessage(
+ 'system',
+ wasRunning
+ ? '这一轮因工作台重启中断。可以点「继续」接着做。'
+ : '上次等待回答的问题因工作台重启失效。可以点「继续」重新开始。',
+ { kind: 'policy' },
+ ),
+ );
+ await saveSession(root, session);
+ changed += 1;
+ }
+ return changed;
+}
+
+/** Shared session shape for every API response and SSE event. */
+export function sessionSummary(session) {
+ const messages = Array.isArray(session.messages) ? session.messages : [];
+ return {
+ id: session.id,
+ kind: session.kind,
+ targetId: session.targetId ?? '',
+ title: session.title ?? '',
+ updatedAt: session.updatedAt ?? 0,
+ messageCount: messages.length,
+ running: Boolean(session.running),
+ interrupted: Boolean(session.interrupted),
+ pending: session.pending ?? null,
+ permissions: Array.isArray(session.permissions) ? session.permissions : [],
+ seeded: Boolean(session.seeded),
+ model: session.model ?? null,
+ // Record size only: the Host keeps the real context and its own compaction.
+ turns: messages.filter((message) => message.role === 'assistant').length,
+ chars: messages.reduce((sum, message) => sum + String(message.text ?? '').length, 0),
+ };
+}
+
+export function makeMessage(role, messageText, extra = {}) {
+ return {
+ id: `msg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ role,
+ text: String(messageText ?? ''),
+ at: Date.now(),
+ ...extra,
+ };
+}
+
+/* --------------------------------------------------------------- snapshot */
+
+async function listRecords(root) {
+ const files = await listFiles(root, { extensions: ['.md'], max: 200 });
+ const records = files.filter((rel) => classify(rel).id === 'records');
+ const out = [];
+ for (const rel of records.slice(0, 40)) {
+ const body = await readText(resolveInside(root, rel), '');
+ const firstLine = body.split('\n').find((line) => line.startsWith('# '));
+ const title = firstLine?.slice(2).trim() || path.basename(rel, '.md');
+ const excerpt = body
+ .split('\n')
+ .filter((line) => line.trim() && !line.startsWith('#'))
+ .join(' ')
+ .slice(0, 220);
+ out.push({ rel, title, excerpt });
+ }
+ return out;
+}
+
+/**
+ * The only reader of MISSION.md. Everything else consumes this shape: the
+ * workspace name, the configured flag, and the overview excerpt.
+ */
+export function readMission(mission) {
+ const text = String(mission ?? '').replace(/\r\n/g, '\n');
+ const line = text.split('\n').find((entry) => /^#\s*Mission\s*[::]/i.test(entry.trim()));
+ const title = line
+ ? line
+ .trim()
+ .replace(/^#\s*Mission\s*[::]\s*/i, '')
+ .replace(/(待配置)/g, '')
+ .trim()
+ : '';
+ const why = (text.match(/##[ \t]*Why[ \t]*\n([\s\S]*?)(?=\n##|$)/i) || [])[1] || '';
+ const body = why
+ .replace(/^#.*$/gm, '')
+ .replace(//g, '')
+ .trim();
+ const ready = Boolean(body) && !/_待主会话与你确认/.test(why);
+ return {
+ title,
+ why: why.trim(),
+ ready,
+ // A placeholder is not a mission: never hand it out as the excerpt.
+ excerpt: ready ? body : '',
+ };
+}
+
+export async function loadSnapshot(ws) {
+ const root = ws.root;
+ const [meta, curriculumRead, annotations, notes, sessions, teacher] = await Promise.all([
+ readMeta(root),
+ readCurriculum(root, { topic: ws.name }),
+ readAnnotations(root),
+ readNotes(root),
+ readSessions(root),
+ readTeacher(root),
+ ]);
+ const [mission, resources, lessonFiles, noteFiles, records] = await Promise.all([
+ readText(path.join(root, 'MISSION.md'), ''),
+ readText(path.join(root, 'RESOURCES.md'), ''),
+ listFiles(root, { extensions: ['.html'], max: 400 }),
+ listFiles(root, { extensions: ['.md'], max: 200 }),
+ listRecords(root),
+ ]);
+
+ const curriculum = curriculumRead.curriculum;
+ const lessons = allLessons(curriculum);
+ // A finished note whose file was deleted must not stay in the list.
+ const noteItems = notes.items.filter(
+ (item) => item.status !== 'ready' || !item.path || existsSync(resolveInside(root, item.path)),
+ );
+ const sessionList = Object.values(sessions.sessions)
+ .map((session) => sessionSummary(session))
+ .sort((a, b) => b.updatedAt - a.updatedAt);
+ const missionInfo = readMission(mission);
+ const displayName = meta?.topic || missionInfo.title || path.basename(root);
+
+ return {
+ workspace: {
+ id: ws.id,
+ name: displayName,
+ root,
+ createdAt: ws.createdAt ?? 0,
+ mainSessionId: meta?.mainSessionId ?? '',
+ mainSeededAt: meta?.mainSeededAt ?? 0,
+ setupSessionId: meta?.setupSessionId ?? '',
+ configured: missionInfo.ready,
+ },
+ curriculum: {
+ modules: curriculum.modules,
+ updatedAt: curriculum.updatedAt,
+ topic: curriculum.topic,
+ issues: curriculum.issues ?? [],
+ },
+ curriculumError: curriculumRead.error ?? null,
+ annotations: annotations.items,
+ notes: noteItems,
+ sessions: sessionList,
+ teacher,
+ mission,
+ missionTitle: missionInfo.title,
+ missionExcerpt: missionInfo.excerpt,
+ resources,
+ lessonFiles: lessonFiles.filter((rel) => classify(rel).id === 'lesson'),
+ noteFiles: noteFiles.filter((rel) => classify(rel).id === 'notes'),
+ referenceFiles: lessonFiles.filter((rel) => classify(rel).id === 'reference'),
+ records,
+ summary: {
+ done: lessons.filter((lesson) => lesson.status === 'done').length,
+ total: lessons.length,
+ annotations: annotations.items.length,
+ notes: noteItems.length,
+ },
+ };
+}
+
+export async function readRules(root) {
+ return readText(workbenchPaths(root).rules, '');
+}
+
+export async function writeContextFile(root, name, body) {
+ const file = path.join(workbenchPaths(root).context, `${slugify(name, 'context')}.md`);
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeText(file, body);
+ const rel = toPosix(path.relative(root, file));
+ markNodeWrite(root, rel);
+ return rel;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/teacher-presets.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/teacher-presets.mjs
new file mode 100644
index 00000000..5a38ca35
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/teacher-presets.mjs
@@ -0,0 +1,118 @@
+/**
+ * Teacher style templates. A style changes explanation, layout and tone; it
+ * never changes the teaching contract, session boundaries or write scope.
+ */
+
+export const DEFAULT_TEACHER_ID = 'balanced';
+
+export const TEACHER_STYLE_GUARD =
+ '只影响讲解方式、版式与对话语气;不得改变教学契约、会话职责、写入范围与安全规则。与契约冲突时,以契约为准。';
+
+export const TEACHER_PRESETS = [
+ {
+ id: 'balanced',
+ name: '平衡讲解',
+ summary: '概念讲清 + 一个可运行例子;课程用 2–4 种视觉块;对话直接、简洁。',
+ prompt:
+ '先讲清一个概念,再给一个可运行或可观察的例子;避免堆术语。课程按内容使用 2–4 种视觉块,版式干净、层级清楚。对话用短段落,先回答关键点,再补原因;发现前提有误时直接指出。',
+ },
+ {
+ id: 'textbook',
+ name: '严谨教材',
+ summary: '定义 → 原理 → 推导 → 例题;术语精确,来源齐全,少装饰。',
+ prompt:
+ '按教材的顺序组织:定义、原理、推导、例题、练习。术语首次出现时给准确定义,事实性陈述尽量带来源;不要为了好看牺牲严谨。课程以长段落、公式、表格为主,视觉块克制(2–3 种)。对话先校正概念与前提,再回答问题。',
+ },
+ {
+ id: 'engineer',
+ name: '现场工程师',
+ summary: '先跑通,再拆链路,最后排错;多命令、日志、表格和检查清单。',
+ prompt:
+ '先让读者跑通最小可用路径,再拆开链路解释每一层,最后给排错与验证方法。多用命令、代码、日志、表格、检查清单和流程图;每个结论尽量给可观察的证据。对话直接给操作步骤、预期输出和失败时的下一步。',
+ },
+ {
+ id: 'coach',
+ name: '苏格拉底教练',
+ summary: '多问少答;先让读者预测和解释,再补充;用问题链推进。',
+ prompt:
+ '不要一上来给完整答案:先用 1–2 个具体问题让读者预测、解释或做选择,再根据常见误区补充。课程用问题链、对照实验和自测推进,视觉块服务于对比与选择。对话以反问和提示推进,只有读者明确卡住时才给完整解法。',
+ },
+ {
+ id: 'visual',
+ name: '视觉讲师',
+ summary: '先图后文;每课 3–5 种图块,优先流程、分层、矩阵、时间线、表与 PPT 页。',
+ prompt:
+ '先给一张能看懂全局的图或表,再用短段落解释;每课至少使用 3 种、最多 5 种视觉块,优先选择流程、分层、2×2 矩阵、决策树、时间线、Excel 表、PPT 页、指标卡和条形图。图块必须服务理解,不为装饰堆叠;窄屏优先纵向排列,宽表放进可横向滚动的容器。对话用短段落、小标题和列表,让结构一眼可见。',
+ },
+ {
+ id: 'feynman',
+ name: '费曼式',
+ summary: '日常比喻 → 回到术语 → 让读者复述;口语化,少术语堆叠。',
+ prompt:
+ '先用日常比喻或生活场景解释,再回到准确术语,并指出比喻在哪里不成立。每节都要求读者用自己的话复述一次;用对比、例子和小测检查理解。对话口语化、少术语;读者说得含糊时,请他换一种说法或举个反例。',
+ },
+];
+
+const presetIds = new Set(TEACHER_PRESETS.map((item) => item.id));
+
+const cleanText = (value, max) =>
+ String(value ?? '')
+ .replace(/\r\n/g, '\n')
+ .trim()
+ .slice(0, max);
+
+export function newTeacherId() {
+ return `c_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
+}
+
+export function presetById(id) {
+ return TEACHER_PRESETS.find((item) => item.id === id) || null;
+}
+
+export function normalizeTeacher(raw) {
+ const seen = new Set();
+ const custom = [];
+ for (const entry of Array.isArray(raw && raw.custom) ? raw.custom : []) {
+ if (!entry || typeof entry !== 'object') continue;
+ const prompt = cleanText(entry.prompt, 2000);
+ if (!prompt) continue;
+ let id = cleanText(entry.id, 40);
+ if (!/^c_[a-z0-9]+$/.test(id) || seen.has(id) || presetIds.has(id)) id = newTeacherId();
+ while (seen.has(id)) id = newTeacherId();
+ seen.add(id);
+ custom.push({
+ id,
+ name: cleanText(entry.name, 24) || '自定义风格',
+ prompt,
+ createdAt: Number(entry.createdAt) || Date.now(),
+ updatedAt: Number(entry.updatedAt) || Date.now(),
+ });
+ if (custom.length >= 12) break;
+ }
+ const all = new Set([...presetIds, ...custom.map((item) => item.id)]);
+ const selected = all.has(raw && raw.selected) ? raw.selected : DEFAULT_TEACHER_ID;
+ return { schemaVersion: 1, selected, custom };
+}
+
+export function resolveTeacher(teacher) {
+ const state = normalizeTeacher(teacher);
+ const preset = presetById(state.selected);
+ if (preset) return { ...preset, kind: 'preset' };
+ const custom = state.custom.find((item) => item.id === state.selected);
+ if (custom) {
+ return {
+ id: custom.id,
+ name: custom.name,
+ summary: '自定义风格',
+ prompt: custom.prompt,
+ kind: 'custom',
+ };
+ }
+ const fallback = presetById(DEFAULT_TEACHER_ID);
+ return { ...fallback, kind: 'preset' };
+}
+
+/** What the overview needs for a preview; no workspace-specific state here. */
+export function teacherPresetsPublic() {
+ return TEACHER_PRESETS.map(({ id, name, summary, prompt }) => ({ id, name, summary, prompt }));
+}
diff --git a/plugins/meisijiya/learn-workbench/package.json b/plugins/meisijiya/learn-workbench/package.json
new file mode 100644
index 00000000..1d55c1df
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/package.json
@@ -0,0 +1,11 @@
+{
+ "name": "learn-workbench",
+ "private": true,
+ "scripts": {
+ "test": "node test/selftest.mjs"
+ },
+ "mcode": {
+ "schemaVersion": 2,
+ "miniApp": "./miniapp/miniapp.json"
+ }
+}
diff --git a/plugins/meisijiya/learn-workbench/test/selftest.mjs b/plugins/meisijiya/learn-workbench/test/selftest.mjs
new file mode 100644
index 00000000..265e3834
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/test/selftest.mjs
@@ -0,0 +1,66 @@
+import assert from 'node:assert/strict';
+
+import { normalizeTags } from '../miniapp/node/store.mjs';
+import { resolveInside } from '../miniapp/node/fsx.mjs';
+import { classify, canWrite, STATE_RELS } from '../miniapp/node/policy.mjs';
+import { noteFileName } from '../miniapp/node/prompts.mjs';
+import { noteTemplateById, NOTE_TEMPLATES } from '../miniapp/node/note-templates.mjs';
+
+let checks = 0;
+const check = (label, fn) => {
+ fn();
+ checks += 1;
+ process.stdout.write(`ok ${label}\n`);
+};
+
+check('tags: 去掉 #、去重、trim', () => {
+ assert.deepEqual(normalizeTags(['#路由 ', '路由', '', ' x ']), ['路由', 'x']);
+});
+
+check('tags: 截断到 24 字、最多 6 个', () => {
+ assert.equal(normalizeTags(['a'.repeat(40)])[0].length, 24);
+ assert.equal(normalizeTags(Array.from({ length: 9 }, (_, i) => `t${i}`)).length, 6);
+});
+
+check('tags: 非数组得到空列表', () => {
+ assert.deepEqual(normalizeTags('nope'), []);
+});
+
+check('classify: 笔记、课程、状态、其他', () => {
+ assert.equal(classify('notes/a.md').id, 'notes');
+ assert.equal(classify('lessons/a.html').id, 'lesson');
+ assert.equal(classify(STATE_RELS.notes).id, 'appState');
+ assert.equal(classify('random/file.txt').id, 'other');
+});
+
+check('canWrite: 提炼会话只写笔记', () => {
+ assert.equal(canWrite('note', 'notes/a.md'), true);
+ assert.equal(canWrite('note', 'lessons/a.html', { targetFile: 'lessons/a.html' }), false);
+});
+
+check('canWrite: 课程会话只写自己那一课', () => {
+ assert.equal(canWrite('lesson', 'lessons/a.html', { targetFile: 'lessons/a.html' }), true);
+ assert.equal(canWrite('lesson', 'lessons/b.html', { targetFile: 'lessons/a.html' }), false);
+});
+
+check('resolveInside: 词法越界被拒绝', () => {
+ assert.throws(() => resolveInside('.', '../outside.txt'), /path_outside_workspace/);
+});
+
+check('resolveInside: 不存在的新文件仍被允许', () => {
+ const resolved = resolveInside('.', 'node/.selftest-missing.txt');
+ assert.match(resolved, /selftest-missing\.txt$/);
+});
+
+check('noteFileName: 生成 .md 并去掉非法字符', () => {
+ const name = noteFileName('第 3 课 · 问答卡');
+ assert.match(name, /^notes\/.+\.md$/);
+ assert.ok(!/[:*?"<>|]/.test(name));
+});
+
+check('noteTemplateById: 未知模板回落到默认', () => {
+ assert.equal(noteTemplateById('nope').id, NOTE_TEMPLATES[0].id);
+ assert.equal(noteTemplateById(NOTE_TEMPLATES[1].id).id, NOTE_TEMPLATES[1].id);
+});
+
+process.stdout.write(`\n${checks} checks passed\n`);