dsh-mindmap 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,11 @@ All notable changes to this project are documented here. Release-specific notes
6
6
 
7
7
  ### Added
8
8
 
9
+ - Refresh current mindmap from disk in either panel mode, without replacing drafts or submitting an AI request; failed reads retain the current canvas and show an error.
10
+ - A reproducible `npm run bench:client` benchmark compares cached and full replay using fictional long-conversation data and verifies output equivalence before timing.
11
+
12
+ - Whole-map overview (全图): the canvas zoom bar gains a 全图 button beside 适配. It uses both viewport dimensions and can zoom below the readable floor, but stops at 25%; exceptionally large maps may still overflow and remain scrollable. Like a manual zoom it stops automatic re-fitting, so the observer cannot pull the view back to the readable floor; 适配 or switching documents resumes auto-fit.
13
+
9
14
  - Default mindmap inbox and naming (036): a request without a location ("创建一个脑图", "把刚才的讨论整理成脑图", "盘点一下这个问题") now files the document in `.mindmaps/` as `YYYYMMDD-HHmmss-中文描述.md` instead of dropping it on top of the session working directory root. `mindmap_create` takes `name` when the user named the mindmap and a short `description` otherwise — the host reads the clock, so the model never guesses a time. Descriptions are whitespace-collapsed, truncated to 24 characters, and rejected outright when they carry path separators or control characters. `.mindmaps/` is created on first use (a same-named ordinary file, a symlinked-out directory, and a missing session cwd all fail closed), is never added to `.gitignore`, and shows in the directory tree as 脑图收件箱(.mindmaps) with the root/blank-space context menu offering 在脑图收件箱新建脑图. An explicit `directory` is still honoured verbatim, and the approval hook now computes the final normalized path before the first write, so a fresh inbox creation still goes through the normal confirmation. The root node title keeps equaling the filename, so a default-created mindmap temporarily shows its timestamp as the root title; splitting filename from display title is left as a separate decision.
10
15
  - Approval and write now agree on one path (036 follow-up): the confirmation prompt resolves the first free `-2`/`-3` candidate before the user is asked, instead of naming a file a previous same-second capture had already taken and then silently writing a sibling. If another create claims the confirmed name during the deliberation window, the host steps to the next free suffix, the tool result reports that final path, and the session grant is recorded against it rather than the stale candidate — so an existing file is never overwritten and a confirmation never buys a write nobody was shown. Concurrent default creates are verified end to end: eight same-description creates launched in parallel produce eight distinct documents with no lost bytes.
11
16
 
@@ -20,10 +25,21 @@ All notable changes to this project are documented here. Release-specific notes
20
25
 
21
26
  ### Changed
22
27
 
28
+ - Share the document projection between the header and workspace, and cache tool-result JSON per session. Changed result text invalidates its entry; session switches discard the previous reducer.
29
+
30
+ - Node text size is now one constant (`NODE_FONT_SIZE = 13`) with no smaller overrides: code blocks, tables and inline code used to render at 12px, which broke the readable-floor promise — the whole canvas shares a single CSS zoom, so 12px text landed at ~11.1px at the 12/13 floor. Code keeps its monospace face and surface colour, so the hierarchy survives without the size step.
31
+
32
+ - Automatic fit and node focus now keep 13px node text at an effective size of at least 12px. Large maps or subtrees may extend beyond the viewport and remain accessible by scrolling/panning; manual zoom still supports 25%–300%. Focusing after a manual zoom below the readable floor restores readability in one step, even when that exceeds the usual ×2 jump limit.
23
33
  - `mindmap_create` without `directory` no longer writes to the root of the session working directory: the file goes into the `.mindmaps/` inbox (see above). Existing documents stay exactly where they are — only new creations move.
24
34
 
25
35
  ### Fixed
26
36
 
37
+ - Read draft text and attachment state from the host's `useInput` snapshot, including edits made while a file request is pending. Unknown state preserves input; old action-face getters remain supported. Inline references and attachment-only drafts block automatic submission too.
38
+ - Fresh disk reads no longer lose to older tool snapshots. A later tool event takes over normally; overlapping reads, closing, session switches, and newer open intents invalidate stale requests.
39
+ - Resolve all mindmap HTTP calls against the page base address, retaining reverse-proxy prefixes while refusing cross-origin base URLs.
40
+
41
+ - A pending mount-time auto-fit frame no longer overrides an early 全图 click or other manual zoom choice; the frame still runs when the user has not changed the view.
42
+ - Keep the readable zoom floor finite by deriving it from the same numeric font-size constant used by node boxes, rather than parsing a CSS style string at startup.
27
43
  - Restored host-side settings on 0.1.7+ hosts: the service no longer has `register`, so the 0.15.0 startup path never read live values or ran its `.imported` migration. The flat `Config` export remains the loader-discovered schema; host approval now reads the `mindmap` descriptor from `describe()` at execution time, and legacy settings are restored via revision-checked `update()` only when the profile has no saved user overrides. Older hosts retain their `register` path. The tests now mock the actual service surface without `register` and exercise live approval changes and one-time migration.
28
44
  - Extended the tooling peer range with `^0.2.0-alpha.0` for the 0.2.0 prerelease tuple. Hosts that enforce peer compatibility no longer skip the plugin solely because its previous range stopped at 0.1.7; the optional sidebar peer is unchanged.
29
45
  - 0.1.7 settings volatile mechanism: all seven Config fields (`requireApproval`, `approvalMode`, `defaultPanelWidth`, `lineStyle`, `cardStyle`, `colorTheme`, `growthAnimation`) are now marked `.extra('volatile', true)` on their schemastery schema nodes. Without `meta.volatile`, the 0.1.7 host's settings storage (`dsh-settings` `volatileForm`/`isVolatilePath`/`write`) rejects all reads and writes for the `mindmap` namespace — the settings panel (设置 → 思维脑图) displays stale or default values and saving a new choice is silently dropped. The `volatile` meta is transparent to older hosts (0.1.5 and below ignore it), so the dual-path behavior is unchanged. A one-time legacy migration was also added: on startup, when the settings value is all-defaults, the plugin reads `~/.dsh/settings.yaml.imported` (the host-renamed old `settings.yaml`), extracts the `mindmap:` section's scalar fields with a line-by-line parser (no YAML dependency), validates each value against its allowed set, and writes the result to the new settings store via `scope.update()`. The `.imported` file is never deleted (it is host-managed); failures are silently skipped so the plugin still loads and the user can configure manually.
package/README.md CHANGED
@@ -18,13 +18,17 @@ A DeepSeek Harness plugin that turns a plain Markdown file into a live mindmap.
18
18
  - **Four tools** (`mindmap_create` / `mindmap_open` / `mindmap_get` / `mindmap_update`) — plain Markdown files in the session working directory; the root node title is the filename and stays in sync both ways (`renameRoot` renames the file, collisions are rejected).
19
19
  - **Live panel with zero extra channels** — the panel consumes the session snapshot (`mindmap_*` tool results), so every AI edit re-renders immediately.
20
20
  - **Reliable open, recoverable loading state** — AI create/open results always expand the panel (a structural-fingerprint selector drives snapshot recomputation even when the host reuses the nodes array reference); clicking a `.md` first reads it through the local read-only route, while AI fallback loading still recovers from case-only path mismatches, inline tool errors, and a ~30s watchdog timeout with one-click retry.
21
+ - **Refresh from disk** — 刷新脑图 reloads the current file while preserving drafts and attachments, without submitting a model request. Fresh disk content stays visible until a later tool result arrives; overlapping reads, closing, and session changes cannot let an old request replace the new view. Failed refreshes retain the canvas and show a retryable error.
22
+ - **Draft protection** — uses the host's published input snapshot for text, references, and attachments. Pending or unreadable input is preserved; files still open through the read-only route and editing commands remain available for manual submission.
21
23
  - **Graceful parse failure** — if a document's Markdown ever breaks the parser, the panel never crashes: the mindmap area shows an explicit parse-failed state with the error, the original file is left untouched, and you can switch back to the directory tab or let the AI fix the content and reopen. Normal documents never reach this path.
22
24
  - **Floating right panel or native sidebar tab** — when `dsh-better-sidebar` is installed, the mindmap registers as a native single-instance tab (`dsh-mindmap:mindmap`) inside Better Sidebar, with a compact one-row toolbar (mindmap list, current mindmap, and export on the same line); the header 思维脑图 button opens or focuses that tab. When Better Sidebar is absent, the panel falls back to a standalone floating right panel toggled by the 思维脑图 button — drag-resizable (280px ~ 80% viewport), persisted, and pushing the chat left (layout-push) so the two never overlap. AI create/open/view intents always open or focus the panel/tab and switch to the target document, including when it is currently closed or the same document is opened again. The mode switch is fully reversible: if Better Sidebar is unloaded mid-session, the standalone panel and layout-push CSS are restored automatically.
23
25
  - **Directory tree tab** — a persistent tree of the session working directory (served by plugin-owned read-only routes), lazy-loaded per directory; right-click to create a mindmap in the inbox or inside a directory; left-click a `.md` renders it through the read-only route first, then hands it to the AI for editing when the draft is empty. Labeled 目录 in standalone mode and 脑图列表 in sidebar mode.
24
26
  - **Single-mindmap mode** — two tabs only: the tree/list tab and 脑图 (the current mindmap); opening another `.md` replaces the previous one.
25
27
  - **"What you see is what the AI edits"** — when the visible mindmap differs from the AI's working document, the panel automatically asks the AI to open it, keeping the chat focus in sync.
26
28
  - **MarkGrove-style mapping** — heading hierarchy, nested lists (empty items become placeholder nodes), code blocks as leaf nodes, paragraphs promoted to their own nodes (019 block concept), stable structural IDs, and orthogonal connector lines between nodes.
27
- - **Centered canvas with zoom and pan** — the mindmap opens centered in the canvas (scrollable without edge clipping when larger); a floating zoom bar at the canvas top-right (zoom out / percent / zoom in / fit) applies auto fit-to-view on open (small maps stay at 100%), steps through 25%–300% with a stable view center, and keeps re-fitting as the AI edits — until you zoom manually. Click any node to zoom in on it and its whole subtree, with the node pinned at the left-center of the canvas. The focus transition glides the node from its clicked position to the left-quarter anchor with no first-frame jump, animates the zoom over ≤250 ms (capped at ×2/÷2 per click, so a huge map drills down progressively instead of jumping 4× in one step), and writes frames directly to the canvas DOM layer without re-rendering the tree per frame; any new interaction interrupts it instantly. When an AI edit pushes the selected node fully out of view, the canvas performs a minimal scroll to bring it back to the edge without touching your chosen zoom. Narrow panels (sidebar mode) fit by height instead of width — the overflowing part is reachable by panning — and the scrollbar gutter is reserved, so the fit ratio no longer oscillates as scrollbars appear. The canvas also pans by drag: the **middle button** anywhere (even over a node), the **left button on blank canvas** (the Mac trackpad「click and drag」path), or **Space + left button** when the drag must start on a card. Panning works in both directions even when content does not overflow; content follows the pointer 1:1, blank space shows a grab hand, and a 4px threshold separates drag from click — so clicking blank space still clears the selection and clicking a node still focuses it, while a real drag never wipes the selection ring.
29
+ - **Centered canvas with zoom and pan** — the mindmap opens centered in the canvas; the top-right zoom bar (out / percent / in / 适配 / 全图) auto-fits on open without shrinking 13px node text below an effective 12px. Larger maps remain scrollable. 全图 instead tries to frame the entire tree, even below the readable floor, but stops at 25%: exceptionally large maps can still overflow. Manual zoom spans 25%–300%, and automatic re-fitting after AI edits pauses when you choose a zoom or 全图; 适配 restores it.
30
+ Clicking a node focuses it at a readable scale near the left-quarter anchor; large subtrees may extend beyond the viewport. The ≤250 ms transition has no first-frame jump, normally changes zoom by at most ×2/÷2 per click (except when restoring readability after manual zoom below 12px), and writes frames directly to the canvas DOM without re-rendering the tree. New interactions interrupt it; when an AI edit pushes a selected node completely out of view, the canvas minimally scrolls it back without changing your zoom.
31
+ Narrow panels fit by height instead of width and reserve a stable scrollbar gutter. Pan with the **middle button** anywhere, the **left button on blank canvas** (including Mac trackpad click-and-drag), or **Space + left button** on a card. Dragging follows the pointer even at scroll edges; a 4px threshold keeps clicks and the selection ring distinct from pans.
28
32
  - **Collapsible subtrees** — every node with children carries a small toggle on its connector: collapsing hides the whole subtree and reports how many nodes are hidden, so large maps stay navigable. It is view state only — the markdown file is untouched, image export still covers the full subtree, and switching documents expands everything again.
29
33
  - **PNG export** — one click on 导出图片 exports the current mindmap.
30
34
  - **Copy as markdown** — one click on 复制全文 (left of 导出图片) copies the current mindmap's raw markdown source to the system clipboard, so pasting into markdown-aware editors restores headings, nested lists, and tables, while plain-text targets keep the literal `#`/`-` source. The button shows 已复制 ✓ for about two seconds on success; failures reuse the export error slot.
@@ -57,6 +61,8 @@ When you ask for a mindmap without naming a location — "创建一个脑图", "
57
61
  | Node.js | 20.11 or newer |
58
62
  | DeepSeek Harness | tested against `0.1.1-rc.2`, `0.1.2-rc.1`, and `0.1.5-rc.1` |
59
63
 
64
+ Input, settings, and conversation contracts from `0.2.0-rc.2` / `0.2.1-alpha.1` have offline regression coverage; this does not certify every host workflow. API requests retain the page's base path for reverse-proxy deployments and enforce the page's origin.
65
+
60
66
  ## Installation
61
67
 
62
68
  Development (link install, live source):
@@ -71,6 +77,14 @@ Released tag:
71
77
  dsh plugin --profile <profile> add <pkg>#v<version>
72
78
  ```
73
79
 
80
+ Exact npm version:
81
+
82
+ ```bash
83
+ dsh plugin --profile <profile> add dsh-mindmap@<version>
84
+ ```
85
+
86
+ New-version cooldown policies can affect package selection shortly after publication. Check the actual installed version in plugin management; use an exact version when needed.
87
+
74
88
  ## Tools
75
89
 
76
90
  | Tool | Description |
@@ -85,11 +99,14 @@ dsh plugin --profile <profile> add <pkg>#v<version>
85
99
  ```bash
86
100
  npm run build:client # assemble the runtime client.js from src/client fragments
87
101
  npm run verify # rebuild + syntax check + node --test
102
+ npm run bench:client # pure-computation long-conversation replay benchmark
88
103
  npm pack --dry-run # inspect the files that will enter the npm package
89
104
  ```
90
105
 
91
106
  The browser implementation is maintained under `src/client/` and assembled into the single `client.js` entry required by DeepSeek Harness. Edit the source fragments, then run `npm run build:client`; do not hand-edit the generated entry.
92
107
 
108
+ Document replay shares a session-local parse cache, invalidates changed text, and starts fresh after session changes. The benchmark uses 3000 fictional conversation nodes and 200 mindmap results, verifies cached and full replay equivalence, then measures their time. It measures replay cost, not browser frame rates or overall UI performance.
109
+
93
110
  ## License
94
111
 
95
112
  MIT License. See [LICENSE](LICENSE) for details.
package/README.zh-CN.md CHANGED
@@ -18,20 +18,24 @@
18
18
  - **四个工具**(`mindmap_create` / `mindmap_open` / `mindmap_get` / `mindmap_update`)——会话工作目录里的普通 `.md` 文件;根节点标题 = 文件名,双向同步(`renameRoot` 触发文件重命名,撞名报错不覆盖)。
19
19
  - **零通道实时面板**——面板直接消费会话快照里的 `mindmap_*` 工具结果,AI 每改一步面板即渲染一次。
20
20
  - **打开必达 + 加载态可恢复**——AI create/open 结果落地,面板必展开(节点结构指纹驱动快照重算,不受宿主数组引用稳定性影响);点目录树 `.md` 会先走本地只读路由直接显示,AI fallback 加载态仍支持大小写路径自动匹配、工具错误提示、约 30 秒超时和一键重试。
21
+ - **磁盘刷新**——「刷新脑图」直接重读当前文件,保留聊天草稿和附件,不发送模型请求。直读的新内容保留到后续工具结果到来;连续打开、关闭或切换会话后,旧请求不能覆盖新视图。读取失败保留原画布并显示可重试的错误。
22
+ - **草稿保护**——从宿主正式输入快照读取当前文字、引用和附件;存在未发送内容或状态暂时不可读时,不替换输入、不自动发送。目录文件仍可直接打开,编辑指令可手动发送。
21
23
  - **解析失败显式成态**——文档 Markdown 万一让解析器崩掉,面板绝不整体炸:脑图区显示明确的解析失败态并带错误信息,原文件内容原样未动,可切回目录 tab 查看,或让 AI 修正后重新打开。正常文档永远走不到这里。
22
24
  - **原生侧栏 Tab 或右侧悬浮面板**——安装了 `dsh-better-sidebar` 时,脑图注册为 Better Sidebar 内的原生单实例 Tab(`dsh-mindmap:mindmap`),工具栏只有一行(脑图列表、当前脑图、导出图片在同一行);头部「思维脑图」按钮打开或聚焦该 Tab。未安装时回退为独立的右侧悬浮面板——会话头部按钮开合,宽度可拖(280px ~ 80% 视口)并持久化,打开时**聊天区向左让位**(布局推挤,互不遮挡)。AI 创建、打开或查看脑图时自动展开或聚焦面板/Tab 并切换到目标文档,即使当前收起或重复打开同一文档也能接续跟随。模式切换完全可逆:Better Sidebar 运行中卸载后,独立面板与布局推挤 CSS 自动恢复。
23
25
  - **常驻目录树 tab**——工作目录结构懒加载树(插件自建只读路由);空白处右键新建到脑图收件箱、目录右键新建到该目录;左键点 `.md` 先通过只读路由直接显示,再在草稿为空时交给 AI 对话编辑。独立面板模式标签为「目录」,侧栏模式标签为「脑图列表」。
24
26
  - **单脑图模式**——面板只有树/列表和「脑图」两个 tab,打开新脑图替换旧的那颗。
25
27
  - **「所见即所编」焦点同步**——可见脑图与 AI 工作文档不一致时,面板自动让 AI 打开它,聊天焦点始终跟随你的眼睛。
26
28
  - **MarkGrove 同款映射与连线**——标题层级挂树、列表缩进(空项 = 占位节点)、代码块叶节点、段落升格为独立节点(019 块概念)、稳定结构 ID、节点间直角折线。
27
- - **画布居中、缩放与平移**——脑图打开后居中呈现(超出画布时可滚动、无边缘裁剪);画布右上角浮动缩放条(缩小 / 比例 / 放大 / 适配),打开时自动适配合适比例(小图保持 100%),25%–300% 逐级缩放且视图中心不跳变,AI 编辑后持续自动再适配,直到你手动缩放。点击任意节点即可聚焦:节点从被点位置平滑滑向画布左侧居中锚位(无首帧突跳),视图平滑放大到它和整棵子树完整可见(上限 100%,且单次点击缩放变化不超过 2 倍,巨图上连点渐进深入);动画期间直接操作画布层、不逐帧重绘整棵树,聚焦动画可随时被拖拽、缩放或新点击打断。AI 编辑后若聚焦的节点被顶出视野,画布只做最小滚动把它带回边缘,不打乱你选定的缩放。窄面板(侧栏模式)下自动改按高度适配,宽出的部分靠平移浏览;滚动条槽位常驻,适配比例不再因滚动条出现而反复跳变。画布还能拖着走:**中键**随处拖(含节点上)、**空白处左键拖**(Mac 触控板「点按并拖移」)、或 **Space + 左键拖**(必须从节点上起手时);无论内容是否溢出都可横纵双向拖动,内容跟手 1:1,空白处呈抓手光标,4px 阈值把拖与点分开——点空白仍取消选中、点节点仍聚焦,真拖不会误清选中圈。
29
+ - **画布居中、缩放与平移**——脑图打开时自动「适配」:13px 的节点文字有效字号不低于 12px(代码块、表格、行内代码同为 13px 基准),放不下时由滚动和平移浏览。缩放条另有「全图」:允许缩到可读下限以下,尽量把整棵树放进视口,但最低仍是 25%,极大图仍可能溢出。手动缩放范围为 25%–300%;AI 编辑后会持续自动适配,直到你手动缩放或点击「全图」,点「适配」可恢复自动模式。
30
+ 点击节点会平滑聚焦到画布左侧约四分之一处,过大的子树可能超出视口;动画不逐帧重绘整棵树,通常单次缩放变化不超过 2 倍,若此前手动缩到可读下限以下则会直接恢复可读比例。AI 编辑后若选中节点完全离开视口,画布只做最小滚动把它拉回,不改变你的缩放。窄面板按高度适配,宽出的部分靠平移浏览;滚动条槽位常驻,避免适配值反复跳动。
31
+ 用**中键**随处拖动、在**空白处左键拖动**(包括 Mac 触控板点按并拖移),或按住 **Space + 左键**从节点上拖动。内容跟手移动,滚到边缘后仍可继续平移;4px 阈值区分拖与点,避免误清选中圈。
28
32
  - **子树折叠**——有子节点的节点在连线起点上带一个小开关:折叠后隐藏整棵子树并提示隐藏了多少节点,超大脑图也能逐层看。折叠只是视图状态,不改 markdown 文件,导出图片仍是完整子树;切换文档自动全部展开。
29
33
  - **PNG 导出**——面板右上角「导出图片」一键导出当前脑图。
30
34
  - **复制全文**——「导出图片」左侧一键把当前脑图的 Markdown 原文复制到系统剪贴板:粘到飞书文档 / Notion / Obsidian 等支持 Markdown 的目标会自动还原标题、嵌套列表和表格,粘到纯文本环境则是带 `#`、`-` 符号的源码,零信息损失。成功后按钮短暂显示「已复制 ✓」(约 2 秒),失败复用导出错误的红字提示位。
31
35
  - **节点搜索与快速定位**——⌘/Ctrl+F(或缩放条上的 🔍)在当前脑图中搜索文字,Enter / ↑ ↓ 逐个跳转匹配节点(双向环绕),并自动展开被折叠分支中的搜索结果;跳转保留当前缩放、只滚动视图。搜索只改视图状态,绝不动 Markdown。
32
36
  - **安全**——写入确认默认采用“本会话一次”:同一会话内同一脑图首次写入确认后,后续普通 `mindmap_update` 不再重复弹窗;也可切换为“每次确认”或“关闭普通确认”。重命名、删除和大范围重写仍需单独确认;当前脑图工作区会显示并可撤销本会话授权。受信自动化可显式设置 `requireApproval: false` 关闭普通确认,但高风险写入仍需确认。客户端**没有任何写文件通道**,一切编辑都经 AI 工具。
33
37
 
34
- 内嵌 Better Sidebar 时,脑图列表采用宿主的 14px 正文字体。Markdown 文件显示紧凑的 M 徽标,文件夹与其他文件使用 14px 线框图标;其他格式文件仅展示,没有悬停反馈、打开、拖拽或右键菜单,文件夹仍可展开。标签、操作按钮和提示采用宿主的 12px 字体角色。独立模式保留原有外观;脑图节点的字体层级、缩放和图片导出保持不变。
38
+ 内嵌 Better Sidebar 时,脑图列表采用宿主的 14px 正文字体。Markdown 文件显示紧凑的 M 徽标,文件夹与其他文件使用 14px 线框图标;其他格式文件仅展示,没有悬停反馈、打开、拖拽或右键菜单,文件夹仍可展开。标签、操作按钮和提示采用宿主的 12px 字体角色。独立模式保留原有外观;脑图节点的基础字体层级和图片导出保持不变。
35
39
 
36
40
  内嵌 M 徽标采用透明底、粗体字母与细描边,字母和边框跟随文件名的主题文字颜色;浅色、深色及自定义皮肤切换时同步适配,不依赖品牌色与底色的对比。
37
41
 
@@ -57,6 +61,8 @@
57
61
  | Node.js | 20.11 及以上 |
58
62
  | DeepSeek Harness | 实测于 `0.1.1-rc.2`、`0.1.2-rc.1` 与 `0.1.5-rc.1` |
59
63
 
64
+ 新版输入快照、设置与会话接口按 `0.2.0-rc.2` / `0.2.1-alpha.1` 契约补有离线回归覆盖;不等同于全部宿主版本的完整验收。带路径前缀的 Web 页面使用页面基础地址请求脑图 API,保留反向代理前缀并检查同源。
65
+
60
66
  ## 安装
61
67
 
62
68
  开发(link 安装,实时源码):
@@ -71,6 +77,14 @@ dsh plugin --profile web add link:/path/to/dsh-mindmap
71
77
  dsh plugin --profile <profile> add <pkg>#v<version>
72
78
  ```
73
79
 
80
+ npm 精确版本安装:
81
+
82
+ ```bash
83
+ dsh plugin --profile <profile> add dsh-mindmap@<version>
84
+ ```
85
+
86
+ 新发布版本可能受到安装器的新版本冷却策略影响;安装后核对插件管理页显示的实际版本,需要指定版本时使用上述精确版本写法。
87
+
74
88
  ## 工具
75
89
 
76
90
  | 工具 | 说明 |
@@ -85,11 +99,14 @@ dsh plugin --profile <profile> add <pkg>#v<version>
85
99
  ```bash
86
100
  npm run build:client # 从 src/client 片段组装运行时 client.js
87
101
  npm run verify # 重建 + 语法检查 + node --test
102
+ npm run bench:client # 虚构长会话的纯计算重放基准,不启动服务或浏览器
88
103
  npm pack --dry-run # 检查将进入 npm 包的文件
89
104
  ```
90
105
 
91
106
  浏览器端实现维护在 `src/client/` 下,构建后仍输出 DeepSeek Harness 要求的单一 `client.js` 入口。请修改源码片段后运行 `npm run build:client`,不要直接手改生成入口。
92
107
 
108
+ 文档重放共享会话内的解析缓存,文本变化时失效,切换会话后重新建立。基准脚本使用 3000 个虚构会话节点、200 个脑图工具结果,先核对缓存与完整重放的结果一致,再比较耗时;它衡量重放成本,不代表浏览器帧率或完整 UI 性能。
109
+
93
110
  ## License
94
111
 
95
112
  MIT License,详见 [LICENSE](LICENSE)。
package/client.js CHANGED
@@ -169,7 +169,8 @@ window.__ModuleLoader__.load({
169
169
  } else if (kind === "code") {
170
170
  style.background = resolveToken("color.surface.code", overrides);
171
171
  style.fontFamily = "Menlo, monospace";
172
- style.fontSize = "12px";
172
+ // 不再比正文小一号:整块画布共用一个 CSS zoom,任何小于基准字号的
173
+ // 节点文字都会把「有效字号 ≥12px」的适配下限承诺打破(12px 实际落在 ~11.1px)。
173
174
  } else if (kind === "quote") {
174
175
  style.background = resolveToken("color.surface.quote", overrides);
175
176
  style.border = `1px solid ${resolveToken("color.border.subtle", overrides)}`;
@@ -835,6 +836,24 @@ window.__ModuleLoader__.load({
835
836
  return raw || "mindmap tool failed";
836
837
  }
837
838
 
839
+ /** 缓存已完成工具结果的 JSON;仍逐事件重放,保留改名、错误和嵌套语义。 */
840
+ function parsedToolResult(node, cache) {
841
+ const texts = (node.content ?? []).filter((block) => block?.type === "text").map((block) => block.text);
842
+ const previous = cache?.get(node);
843
+ if (previous && previous.texts.length === texts.length && texts.every((text, i) => text === previous.texts[i])) return previous;
844
+ const text = texts.join("\n");
845
+ let parsed = null;
846
+ try { parsed = JSON.parse(text); } catch { /* 错误结果允许纯文本。 */ }
847
+ const result = { texts, text, parsed };
848
+ cache?.set(node, result);
849
+ return result;
850
+ }
851
+
852
+ function createDocumentReducer() {
853
+ const cache = new WeakMap();
854
+ return (nodes) => reduceDocuments(nodes, cache);
855
+ }
856
+
838
857
  /**
839
858
  * 重放会话快照里的 mindmap_* 工具结果,得到每个脑图文档的最新状态。
840
859
  * nodes: ConversationSnapshot.nodes(ToolResultNode 含 call.name 与渲染后的
@@ -843,7 +862,7 @@ window.__ModuleLoader__.load({
843
862
  * 顺序递归重放整棵调用树。
844
863
  * 返回文档集及最近一次 create/open 意图,用于驱动面板自动切换目标。
845
864
  */
846
- function reduceDocuments(nodes) {
865
+ function reduceDocuments(nodes, cache) {
847
866
  const byPath = Object.create(null);
848
867
  let order = [];
849
868
  let latestOpeningPath = null;
@@ -862,13 +881,7 @@ window.__ModuleLoader__.load({
862
881
  if (node.kind === "tool-result") {
863
882
  const name = node.call?.name;
864
883
  if (typeof name === "string" && TOOL_NAMES.has(name)) {
865
- const text = resultTextOfBlocks(node.content);
866
- let parsed;
867
- try {
868
- parsed = JSON.parse(text);
869
- } catch {
870
- parsed = null;
871
- }
884
+ const { text, parsed } = parsedToolResult(node, cache);
872
885
  // callId 是实际调用的事件身份;eventPath 是无 callId 时按会话
873
886
  // 遍历顺序生成的稳定兜底,避免重复 open 被合并成一个事件。
874
887
  const callId = node.callId != null && String(node.callId)
@@ -911,6 +924,7 @@ window.__ModuleLoader__.load({
911
924
  path: parsed.path,
912
925
  rootTitle: typeof parsed.rootTitle === "string" && parsed.rootTitle ? parsed.rootTitle : stemOf(parsed.path),
913
926
  content: typeof parsed.content === "string" ? parsed.content : "",
927
+ revision: typeof parsed.revision === "string" ? parsed.revision : null,
914
928
  op,
915
929
  callId,
916
930
  eventKey,
@@ -957,7 +971,7 @@ window.__ModuleLoader__.load({
957
971
 
958
972
  /**
959
973
  * 快照文档集(AI 工具结果)与本地直读文档集(read 路由即时打开)合并:
960
- * - 快照优先(同 path 覆盖本地占位);
974
+ * - 快照覆盖占位;直读成功后保留磁盘内容,直到读取开始后的新工具结果到达;
961
975
  * - 本地文档追加在快照 order 之后;
962
976
  * - 快照里有 renamedFrom 指向某本地路径时,丢弃该本地条目(文件已改名);
963
977
  * - 016 大小写 fallback(S5 成因):本地占位(op:"local")与快照文档仅
@@ -969,6 +983,11 @@ window.__ModuleLoader__.load({
969
983
  function mergeDocuments(snapshot, localDocs) {
970
984
  const snapByPath = (snapshot && snapshot.byPath) || {};
971
985
  const byPath = { ...localDocs, ...snapByPath };
986
+ for (const [path, local] of Object.entries(localDocs)) {
987
+ if (local?.op !== "local-read") continue;
988
+ const snapshotDoc = snapByPath[path];
989
+ if (!snapshotDoc || snapshotDoc.eventKey === local.snapshotEventKey) byPath[path] = local;
990
+ }
972
991
  const dropped = new Set();
973
992
  for (const doc of Object.values(snapByPath)) {
974
993
  if (typeof doc.renamedFrom === "string" && doc.renamedFrom && localDocs[doc.renamedFrom]) {
@@ -1127,20 +1146,27 @@ window.__ModuleLoader__.load({
1127
1146
  }
1128
1147
  //#endregion
1129
1148
 
1130
- //#region 025 草稿保护:能力探测(宿主是否让插件读到聊天草稿)
1149
+ //#region 025 草稿保护:正式输入快照优先,旧宿主动作面兜底
1150
+ function draftStateOf(inputActions, readInputState) {
1151
+ try {
1152
+ if (typeof readInputState === "function") return readInputState() ?? null;
1153
+ if (typeof inputActions?.getState === "function") return inputActions.getState() ?? null;
1154
+ } catch { return null; }
1155
+ return null;
1156
+ }
1157
+
1131
1158
  /**
1132
- * 读取当前聊天草稿。宿主契约只保证 setDraft/submit,读取面属可选能力:
1133
- * 逐个探测已知形态,读不到返回 null(= 不可知,不等于空草稿)。
1159
+ * 新宿主的 useInput 提供 draft/attachmentIds;动作对象不提供读取方法。
1160
+ * readInputState 在发送时读取最新快照,避免异步打开期间覆盖后来输入的内容。
1134
1161
  */
1135
- function readDraftText(inputActions) {
1136
- if (!inputActions) return null;
1162
+ function readDraftText(inputActions, readInputState) {
1163
+ const state = draftStateOf(inputActions, readInputState);
1164
+ if (typeof state?.draft === "string") return state.draft;
1165
+ // 正式快照存在但不可读时,不能把旧动作对象误当作空草稿。
1166
+ if (typeof readInputState === "function") return null;
1137
1167
  try {
1138
- if (typeof inputActions.getDraft === "function") return String(inputActions.getDraft() ?? "");
1139
- if (typeof inputActions.draft === "string") return inputActions.draft;
1140
- if (typeof inputActions.getState === "function") {
1141
- const state = inputActions.getState();
1142
- if (state && typeof state.draft === "string") return state.draft;
1143
- }
1168
+ if (typeof inputActions?.getDraft === "function") return String(inputActions.getDraft() ?? "");
1169
+ if (typeof inputActions?.draft === "string") return inputActions.draft;
1144
1170
  } catch {
1145
1171
  return null;
1146
1172
  }
@@ -1148,22 +1174,24 @@ window.__ModuleLoader__.load({
1148
1174
  }
1149
1175
 
1150
1176
  /**
1151
- * 是否因「已有未发送草稿」而放弃自动发送。只有确实读到非空草稿才拦截;
1152
- * 读不到时不拦——否则在不暴露草稿的宿主上,点目录文件会完全打不开。
1177
+ * 文字、引用和附件都属于未发送内容。未知状态同样保留输入;目录直读
1178
+ * 不依赖自动发送,旧宿主仍可打开文件,指令走剪贴板/手动发送。
1153
1179
  */
1154
- function draftBlocksAutoSend(inputActions) {
1155
- const draft = readDraftText(inputActions);
1156
- return typeof draft === "string" && draft.trim() !== "";
1180
+ function draftBlocksAutoSend(inputActions, readInputState) {
1181
+ const state = draftStateOf(inputActions, readInputState);
1182
+ const draft = readDraftText(inputActions, readInputState);
1183
+ const attachmentsUnknown = typeof readInputState === "function" && !Array.isArray(state?.attachmentIds);
1184
+ return draft === null || attachmentsUnknown || draft.trim() !== "" || (Array.isArray(state?.attachmentIds) && state.attachmentIds.length > 0);
1157
1185
  }
1158
1186
 
1159
1187
  /** 037 节点焦点消息:保护现有草稿后,原子地写入并提交到当前 DSH 对话。 */
1160
- function submitNodeFocusMessage(inputActions, text) {
1161
- if (draftBlocksAutoSend(inputActions)) {
1162
- throw new Error("当前聊天框已有未发送内容,请先处理后再围绕节点聊天");
1163
- }
1188
+ function submitNodeFocusMessage(inputActions, text, readInputState) {
1164
1189
  if (!inputActions || typeof inputActions.setDraft !== "function" || typeof inputActions.submit !== "function") {
1165
1190
  throw new Error("当前对话不支持自动发送节点焦点消息");
1166
1191
  }
1192
+ if (draftBlocksAutoSend(inputActions, readInputState)) {
1193
+ throw new Error("当前聊天框有未发送内容,或暂时无法读取草稿;请保留并处理后再围绕节点聊天");
1194
+ }
1167
1195
  inputActions.setDraft(String(text ?? ""));
1168
1196
  inputActions.submit();
1169
1197
  return true;
@@ -1285,6 +1313,8 @@ window.__ModuleLoader__.load({
1285
1313
  //#region PNG 导出(SVG 序列化 → canvas → 下载 / 剪贴板)
1286
1314
  // 019 可变盒高布局:盒高按内容估行数(全量换行的导出形态),表格节点加宽;
1287
1315
  // 布局契约不变——叶子自上而下占行、父节点垂直居中于其子块。
1316
+ // 导出拥有独立的 SVG 度量:13px 正文、12px 表格、18px 行高;不随画布
1317
+ // 的 NODE_FONT_SIZE 或 CSS zoom 改动,否则预估盒高与导出绘制会失配。
1288
1318
  const EXPORT = {
1289
1319
  nodeW: 220, padX: 12, padY: 8, hGap: 48, vGap: 12, pad: 20,
1290
1320
  fontSize: 13, lineHeight: 18,
@@ -1565,6 +1595,7 @@ window.__ModuleLoader__.load({
1565
1595
  //#endregion
1566
1596
 
1567
1597
  //#region React 组件
1598
+ const NODE_FONT_SIZE = 13;
1568
1599
  const S = {
1569
1600
  mButton: { display: "inline-flex", alignItems: "center", gap: "4px", padding: "0 8px", height: "22px", background: "var(--dsw-alias-fill-tsp-secondary)", color: "var(--dsw-alias-label-secondary)", border: "none", borderRadius: "6px", cursor: "pointer", font: "inherit", fontSize: "12px", whiteSpace: "nowrap" },
1570
1601
  // 014 overlay 外壳:右缘贴边全高悬浮面板,点击穿透层里自 opt-in pointer-events。
@@ -1655,7 +1686,7 @@ window.__ModuleLoader__.load({
1655
1686
  // 019 节点盒骨架(002 三层模型:骨架/血肉/皮肤):只留内距与换行契约,
1656
1687
  // 颜色/圆角/阴影由 resolveNodeStyle 生成。020 长度治理:320px 宽上限
1657
1688
  // 强制盒内折行(废除横条);长 URL 用 overflowWrap:anywhere 保证可折行不截断。
1658
- box: { padding: "6px 12px", flex: "0 0 auto", whiteSpace: "pre-wrap", overflowWrap: "anywhere", lineHeight: "20px", fontSize: "13px", boxSizing: "border-box", maxWidth: 320 },
1689
+ box: { padding: "6px 12px", flex: "0 0 auto", whiteSpace: "pre-wrap", overflowWrap: "anywhere", lineHeight: "20px", fontSize: `${NODE_FONT_SIZE}px`, boxSizing: "border-box", maxWidth: 320 },
1659
1690
  // 020 长度治理:散文类块(text/md/list/quote)折行后仍超 6 行即截断+
1660
1691
  // 省略号,全文走悬停浮层(复用代码浮层通道,缩减≠阉割)。仅散文类套用。
1661
1692
  // 行高必须整数像素(20px):小数行高会让 line-clamp 裁切边界与行盒
@@ -1672,13 +1703,13 @@ window.__ModuleLoader__.load({
1672
1703
  textPanelBody: { margin: "0", whiteSpace: "pre-wrap", overflowWrap: "anywhere" },
1673
1704
  // 019 表格块:完整网格(全量行列、单元格内换行、弱边框)。020:表格不
1674
1705
  // 参与截断,超宽时盒内横向滚动,网格与单元格完整保留。
1675
- tableWrap: { fontSize: "12px", lineHeight: 1.5, overflowX: "auto", maxWidth: "100%" },
1706
+ tableWrap: { fontSize: `${NODE_FONT_SIZE}px`, lineHeight: 1.5, overflowX: "auto", maxWidth: "100%" },
1676
1707
  tableGrid: { borderCollapse: "collapse" },
1677
1708
  tableCell: { border: "1px solid var(--dsw-alias-border-l2)", padding: "3px 8px", whiteSpace: "pre-wrap", overflowWrap: "anywhere", verticalAlign: "top", textAlign: "left", minWidth: "64px", maxWidth: "240px" },
1678
1709
  tableHeaderCell: { fontWeight: 600, background: "var(--dsw-alias-fill-tsp-secondary)" },
1679
1710
  // 019 大一统可点击链接:任何块里的任何 URL 完整呈现、永不缩减。
1680
1711
  inlineLink: { color: "var(--dsw-alias-state-business-primary)", textDecoration: "underline", textUnderlineOffset: "2px", overflowWrap: "anywhere", cursor: "pointer" },
1681
- inlineCode: { fontFamily: "Menlo, monospace", fontSize: "12px", background: "var(--dsw-alias-fill-tsp-secondary)", borderRadius: "4px", padding: "0 3px" },
1712
+ inlineCode: { fontFamily: "Menlo, monospace", fontSize: `${NODE_FONT_SIZE}px`, background: "var(--dsw-alias-fill-tsp-secondary)", borderRadius: "4px", padding: "0 3px" },
1682
1713
  // 016 脑图画布:滚动区 + 居中层 + 右上角浮动缩放控制条。
1683
1714
  canvasWrap: { flex: "1 1 auto", minHeight: 0, minWidth: 0, position: "relative", display: "flex", flexDirection: "column" },
1684
1715
  // 021 平移:空白处抓手光标(节点盒自带 pointer 覆盖);overscroll
@@ -2316,15 +2347,19 @@ window.__ModuleLoader__.load({
2316
2347
  //#endregion
2317
2348
 
2318
2349
  //#region 016 脑图画布:居中呈现 + 缩放控制(右上角)
2319
- // 缩放契约:范围 [0.25, 3],每级 ×1.2;适配计算四周留 48px 余量
2350
+ // 缩放契约:手动范围 [0.25, 3],每级 ×1.2;自动适配/聚焦时
2351
+ // 节点正文的有效字号至少 12px(「全图」是显式例外:用户可主动要求一屏看全)。
2352
+ // 适配计算四周留 48px 余量
2320
2353
  //(16px 视觉内距 + 经典滚动条占位,避免「适配→滚动条出现→视口变
2321
2354
  // 窄→再适配」的抖动循环)。
2322
- // 033 focusJump:点击聚焦单次跳变上限(相对当前比例最多 ×2 / ÷2),
2355
+ // 033 focusJump:点击聚焦通常最多 ×2 / ÷2;手动缩至不可读后
2356
+ // 点击聚焦会直接回到可读范围。
2323
2357
  // 巨图点叶子不再一步怼到 100%,连点渐进 drill。narrowView:视口宽
2324
2358
  // 低于该值(sidebar 最窄 280px)时改按高度适配——横向适配在窄面板
2325
2359
  // 永远占主导会把子树压得过小,宽度溢出交给平移(横向本就一等公民)。
2326
2360
  // animMs:033 平滑过渡时长上限(限长、可中断、熔断后退化瞬时)。
2327
- const ZOOM = { min: 0.25, max: 3, step: 1.2, padding: 48, focusMax: 1, focusJump: 2, narrowView: 400, animMs: 250 };
2361
+ const MIN_READABLE_FONT_SIZE = 12;
2362
+ const ZOOM = { min: 0.25, max: 3, step: 1.2, padding: 48, focusMax: 1, focusJump: 2, narrowView: 400, animMs: 250, readableFloor: MIN_READABLE_FONT_SIZE / NODE_FONT_SIZE };
2328
2363
  // 034 聚焦锚位(视口比例):树向右生长,节点压在左侧 1/4 处、
2329
2364
  // 垂直居中,右侧 3/4 视野铺开子级。动画从点击位置插值到此锚位。
2330
2365
  const FOCUS_ANCHOR = { x: 0.25, y: 0.5 };
@@ -2341,24 +2376,38 @@ window.__ModuleLoader__.load({
2341
2376
  return clampZoom(direction > 0 ? base * ZOOM.step : base / ZOOM.step);
2342
2377
  }
2343
2378
 
2344
- /** 适配比例:min((view-padding)/tree, 1) 再夹取——小图不放大、巨图夹下限;零/非法尺寸返回 1。 */
2379
+ /** 自动适配不会把 13px 节点文字缩到 12px 以下;手动缩放仍可低于此值。 */
2380
+ function readableZoom(value) {
2381
+ return Math.max(ZOOM.readableFloor, clampZoom(value));
2382
+ }
2383
+
2384
+ /** 适配比例:小图不放大;大图不低于可读下限,溢出部分交给滚动/平移。 */
2345
2385
  function fitZoom(treeW, treeH, viewW, viewH) {
2346
2386
  if (!(treeW > 0) || !(treeH > 0) || !(viewW > 0) || !(viewH > 0)) return 1;
2347
2387
  // 033 窄视口(sidebar):按高度适配,宽度溢出靠平移。
2348
- if (viewW < ZOOM.narrowView) return clampZoom(Math.min((viewH - ZOOM.padding) / treeH, 1));
2388
+ if (viewW < ZOOM.narrowView) return readableZoom(Math.min((viewH - ZOOM.padding) / treeH, 1));
2389
+ return readableZoom(Math.min((viewW - ZOOM.padding) / treeW, (viewH - ZOOM.padding) / treeH, 1));
2390
+ }
2391
+
2392
+ /**
2393
+ * 全图比例:与 fitZoom 同一公式,但不受可读下限约束;窄视口也按
2394
+ * 宽高同时计算。仍夹在 [min, max],极大图触到 25% 后可能继续溢出。
2395
+ */
2396
+ function fitAllZoom(treeW, treeH, viewW, viewH) {
2397
+ if (!(treeW > 0) || !(treeH > 0) || !(viewW > 0) || !(viewH > 0)) return 1;
2349
2398
  return clampZoom(Math.min((viewW - ZOOM.padding) / treeW, (viewH - ZOOM.padding) / treeH, 1));
2350
2399
  }
2351
2400
 
2352
2401
  /**
2353
2402
  * 子树聚焦比例:适配整棵子树(区别于全局适配,允许放大到 focusMax),
2354
- * 叶子/小子树不会怼脸、巨子树夹下限;零/非法尺寸返回 1。
2403
+ * 叶子/小子树不会怼脸、巨子树夹可读下限;零/非法尺寸返回 1。
2355
2404
  * 033 窄视口同 fitZoom:按高度适配(子树行通常宽而扁,窄面板里
2356
2405
  * 横向适配会把整行压到不可读)。
2357
2406
  */
2358
2407
  function focusZoom(treeW, treeH, viewW, viewH) {
2359
2408
  if (!(treeW > 0) || !(treeH > 0) || !(viewW > 0) || !(viewH > 0)) return 1;
2360
- if (viewW < ZOOM.narrowView) return clampZoom(Math.min((viewH - ZOOM.padding) / treeH, ZOOM.focusMax));
2361
- return clampZoom(Math.min((viewW - ZOOM.padding) / treeW, (viewH - ZOOM.padding) / treeH, ZOOM.focusMax));
2409
+ if (viewW < ZOOM.narrowView) return readableZoom(Math.min((viewH - ZOOM.padding) / treeH, ZOOM.focusMax));
2410
+ return readableZoom(Math.min((viewW - ZOOM.padding) / treeW, (viewH - ZOOM.padding) / treeH, ZOOM.focusMax));
2362
2411
  }
2363
2412
 
2364
2413
  /**
@@ -2472,7 +2521,7 @@ window.__ModuleLoader__.load({
2472
2521
  * 修正 scroll,视图不跳变(内容回到视口内时浏览器会自动钳制回 0)。
2473
2522
  */
2474
2523
  function MindmapCanvas(props) {
2475
- const { node, theme, fitKey, reveal, inputActions } = props;
2524
+ const { node, theme, fitKey, reveal, inputActions, readInputState } = props;
2476
2525
  const scrollRef = react.useRef(null);
2477
2526
  const contentRef = react.useRef(null);
2478
2527
  const zoomRef = react.useRef(1);
@@ -2649,7 +2698,8 @@ window.__ModuleLoader__.load({
2649
2698
  // 测量并适配:自然尺寸 = getBoundingClientRect ÷ 已提交 zoom(与
2650
2699
  // DOM 实际状态严格同步,无竞态)。值不变不动 state(bail-out),
2651
2700
  // 值变化才重置滚动到原点让树回到居中;同步记录自然尺寸供防抖。
2652
- function applyFit() {
2701
+ // wholeMap=true:「全图」——不受可读下限约束(见 fitAllZoom)。
2702
+ function applyFit(wholeMap) {
2653
2703
  const scroller = scrollRef.current;
2654
2704
  const content = contentRef.current;
2655
2705
  if (!scroller || !content) return;
@@ -2663,7 +2713,9 @@ window.__ModuleLoader__.load({
2663
2713
  const naturalW = rect.width / committed;
2664
2714
  const naturalH = rect.height / committed;
2665
2715
  lastNaturalRef.current = { w: naturalW, h: naturalH };
2666
- const fit = fitZoom(naturalW, naturalH, scroller.clientWidth, scroller.clientHeight);
2716
+ const fit = wholeMap === true
2717
+ ? fitAllZoom(naturalW, naturalH, scroller.clientWidth, scroller.clientHeight)
2718
+ : fitZoom(naturalW, naturalH, scroller.clientWidth, scroller.clientHeight);
2667
2719
  zoomRef.current = fit;
2668
2720
  if (fit !== committed) {
2669
2721
  scroller.scrollLeft = 0;
@@ -2691,7 +2743,11 @@ window.__ModuleLoader__.load({
2691
2743
  setSearchIndex(-1);
2692
2744
  setSearchReveal(null);
2693
2745
  searchActiveIdRef.current = null;
2694
- const id = requestAnimationFrame(applyFit);
2746
+ // rAF 会传时间戳,不能直接传 applyFit;若首帧前用户已经选择
2747
+ // 「全图」或手动缩放,也不能再用默认可读适配覆盖其选择。
2748
+ const id = requestAnimationFrame(() => {
2749
+ if (!userZoomedRef.current) applyFit();
2750
+ });
2695
2751
  return () => {
2696
2752
  cancelAnimationFrame(id);
2697
2753
  cancelZoomAnim();
@@ -2916,6 +2972,14 @@ window.__ModuleLoader__.load({
2916
2972
  applyFit();
2917
2973
  }
2918
2974
 
2975
+ // 「全图」:尽量把整棵树放入视口,允许低于可读下限;最低仍是 25%。
2976
+ // 视为手动缩放(停自动再适配),否则观察器会把视图拉回可读下限。
2977
+ function fitWholeMap() {
2978
+ userZoomedRef.current = true;
2979
+ fitStampRef.current = [];
2980
+ applyFit(true);
2981
+ }
2982
+
2919
2983
  // 016 点击节点聚焦:节点滚到「垂直居中、水平约 25%」(树向右生长,
2920
2984
  // 左侧锚点让子级铺满右侧视野),缩放比例取 focusZoom(整棵子树适配、
2921
2985
  // 上限 focusMax)。事件委托:closest 找节点盒与所在子树 row,无需给
@@ -2931,10 +2995,12 @@ window.__ModuleLoader__.load({
2931
2995
  if (!scroller) return false;
2932
2996
  const current = zoomRef.current;
2933
2997
  const rowRect = rowEl.getBoundingClientRect();
2934
- const focus = clampFocusJump(
2998
+ // 用户若先手动缩到可读下限以下,点击节点时一次回到可读范围;
2999
+ // 仅这种情况会突破通常的 ×2 聚焦跳变上限。
3000
+ const focus = readableZoom(clampFocusJump(
2935
3001
  focusZoom(rowRect.width / current, rowRect.height / current, scroller.clientWidth, scroller.clientHeight),
2936
3002
  current,
2937
- );
3003
+ ));
2938
3004
  const boxRect = boxEl.getBoundingClientRect();
2939
3005
  const scrollerRect = scroller.getBoundingClientRect();
2940
3006
  const startAnchor = {
@@ -3172,7 +3238,7 @@ window.__ModuleLoader__.load({
3172
3238
 
3173
3239
  // 037 节点焦点聊天:沿用目录树的自动发送能力,但不覆盖用户已有草稿。
3174
3240
  function submitNodeChat(text) {
3175
- return submitNodeFocusMessage(inputActions, text);
3241
+ return submitNodeFocusMessage(inputActions, text, readInputState);
3176
3242
  }
3177
3243
 
3178
3244
  // 037 右键节点:先完成与左键相同的注意力聚焦,再记录菜单锚点。
@@ -3312,13 +3378,22 @@ window.__ModuleLoader__.load({
3312
3378
  }),
3313
3379
  (0, react_jsx_runtime.jsx)("button", {
3314
3380
  type: "button",
3315
- title: "适配画布(重新计算合适比例)",
3381
+ title: "适配画布(保持可读字号 ≥12px,放不下的部分滚动浏览)",
3316
3382
  style: hover === "fit" ? { ...S.zoomFitBtn, ...S.zoomBtnHover } : S.zoomFitBtn,
3317
3383
  onClick: refit,
3318
3384
  onMouseEnter: () => setHover("fit"),
3319
3385
  onMouseLeave: () => setHover((h) => (h === "fit" ? null : h)),
3320
3386
  children: "适配",
3321
3387
  }),
3388
+ (0, react_jsx_runtime.jsx)("button", {
3389
+ type: "button",
3390
+ title: "尽量适应全图(可低于 12px;最低 25%,极大图仍需滚动)",
3391
+ style: hover === "fitAll" ? { ...S.zoomFitBtn, ...S.zoomBtnHover } : S.zoomFitBtn,
3392
+ onClick: fitWholeMap,
3393
+ onMouseEnter: () => setHover("fitAll"),
3394
+ onMouseLeave: () => setHover((h) => (h === "fitAll" ? null : h)),
3395
+ children: "全图",
3396
+ }),
3322
3397
  ] }),
3323
3398
  // 035 节点搜索条:缩放条正下方的紧凑浮层(同款容器/主题变量)。
3324
3399
  // 输入即搜;Enter/↓ 下一个、Shift+Enter/↑ 上一个(双向环绕);
@@ -3478,16 +3553,21 @@ window.__ModuleLoader__.load({
3478
3553
  * headerHeight:独立壳传入的对齐高度(null = BS Tab 模式,头部自适应)。
3479
3554
  */
3480
3555
  function MindmapWorkspace(props) {
3481
- const { mindmapFace, visible, sessionId, inputActions, nodes, nodesVersion, onAutoOpen, onClose, headerHeight, variant } = props;
3556
+ const { mindmapFace, visible, sessionId, inputActions, readInputState, nodes, nodesVersion, documents, onAutoOpen, onClose, headerHeight, variant } = props;
3482
3557
  // 只调整工作区界面;脑图节点与导出继续使用自己的字体层级。
3483
3558
  const S = workspaceStyles(variant);
3484
3559
  // 016:nodesVersion(结构指纹)作副依赖——nodes 引用不变但内容已变
3485
3560
  // (新工具结果原地落地)时强制重算;docs 新引用带动 merged →
3486
3561
  // auto-open effect 重跑(对已消费事件幂等 no-op),面板必达展开。
3487
- const docs = react.useMemo(() => reduceDocuments(nodes), [nodes, nodesVersion]);
3562
+ const documentReducer = react.useMemo(() => createDocumentReducer(), [sessionId]);
3563
+ const docs = react.useMemo(() => documents ?? documentReducer(nodes), [documents, nodes, nodesVersion, documentReducer]);
3488
3564
  // 013:本地加载占位文档(左键点 .md 秒建 tab、内容为空),与快照文档
3489
- // 合并显示;快照优先(AI 结果覆盖占位)。
3565
+ // 合并显示;直读保留到新的工具结果到达,不让历史快照盖回磁盘内容。
3490
3566
  const [localDocs, setLocalDocs] = react.useState({});
3567
+ const documentReadRef = react.useRef(0);
3568
+ const documentSessionRef = react.useRef(sessionId);
3569
+ documentSessionRef.current = sessionId;
3570
+ const [readingPath, setReadingPath] = react.useState(null);
3491
3571
  const merged = react.useMemo(() => mergeDocuments(docs, localDocs), [docs, localDocs]);
3492
3572
  // 016 加载态恢复(S2/S3 成因):openMindmap 点击时刻记录错误事件键
3493
3573
  // 基线——只有其后新出现的错误才归因到该次打开(matchDocError 的
@@ -3633,6 +3713,8 @@ window.__ModuleLoader__.load({
3633
3713
  // effect,否则清理会把刚自动选中的脑图又切回「目录」。
3634
3714
  const seen = react.useRef(null);
3635
3715
  react.useEffect(() => {
3716
+ documentReadRef.current += 1;
3717
+ setReadingPath(null);
3636
3718
  setLocalDocs({});
3637
3719
  setCurrentPath(null);
3638
3720
  setHiddenPath(null);
@@ -3645,6 +3727,7 @@ window.__ModuleLoader__.load({
3645
3727
  focusSentRef.current = null;
3646
3728
  seen.current = null;
3647
3729
  prevIdsRef.current = { path: null, ids: null };
3730
+ return () => { documentReadRef.current += 1; };
3648
3731
  }, [sessionId]);
3649
3732
 
3650
3733
  // AI 自动打开:create/open 代表用户明确的「创建 / 打开 / 查看」意图。
@@ -3654,6 +3737,10 @@ window.__ModuleLoader__.load({
3654
3737
  const targetPath = autoOpenTarget(merged, seen.current);
3655
3738
  seen.current = openingEventKeys(merged);
3656
3739
  if (targetPath) {
3740
+ if (readingPath && readingPath !== targetPath) {
3741
+ documentReadRef.current += 1;
3742
+ setReadingPath(null);
3743
+ }
3657
3744
  onAutoOpen();
3658
3745
  setHiddenPath(null);
3659
3746
  setCurrentPath(targetPath);
@@ -3705,10 +3792,9 @@ window.__ModuleLoader__.load({
3705
3792
  }
3706
3793
  }
3707
3794
  //#region 013 目录树 tab:懒加载树 + 把指令填进聊天输入框
3708
- // 草稿保护:确实读到非空草稿才让路(改走剪贴板),读不到就按既有
3709
- // 行为直填直发——宿主不暴露草稿时不能把功能整个卡死。
3795
+ // 草稿状态未知时也保留输入;目录直读照常,编辑指令交给手动发送。
3710
3796
  function draftBlocked() {
3711
- return draftBlocksAutoSend(inputActions);
3797
+ return draftBlocksAutoSend(inputActions, readInputState);
3712
3798
  }
3713
3799
 
3714
3800
  function submitChatCommand(text) {
@@ -3744,6 +3830,8 @@ window.__ModuleLoader__.load({
3744
3830
 
3745
3831
  /** 关闭脑图视图:✕ 后回到只有「目录」的状态;快照结果不自动弹回。 */
3746
3832
  function closeMindmap(path) {
3833
+ documentReadRef.current += 1;
3834
+ setReadingPath(null);
3747
3835
  setHiddenPath(path);
3748
3836
  setCurrentPath(null);
3749
3837
  setView("tree");
@@ -3756,7 +3844,13 @@ window.__ModuleLoader__.load({
3756
3844
 
3757
3845
  // 左键点 .md:先通过只读 document 路由显示文件,再在草稿为空时提交
3758
3846
  // mindmap_open 让 AI 接管编辑;已有草稿永不被覆盖。
3759
- async function openMindmap(entry) {
3847
+ async function openMindmap(entry, { submit = true, refresh = false } = {}) {
3848
+ const request = ++documentReadRef.current;
3849
+ const isCurrent = () => request === documentReadRef.current && documentSessionRef.current === sessionId;
3850
+ const snapshotEventKey = docs.byPath[entry.path]?.eventKey;
3851
+ setReadingPath(entry.path);
3852
+ setExportError("");
3853
+ if (!submit) focusSentRef.current = entry.path;
3760
3854
  const text = `用 mindmap_open 打开 ${relPathWithin(fsTree.cwd, entry.path, entry.name)}`;
3761
3855
  // 016:记录点击时刻的错误基线(errorByPath 与 latestError 的全部
3762
3856
  // 事件键)——只有其后新出现的错误才归因本次打开,旧错误不打扰。
@@ -3766,7 +3860,7 @@ window.__ModuleLoader__.load({
3766
3860
  setHiddenPath(null);
3767
3861
  setCurrentPath(entry.path);
3768
3862
  setView("mindmap");
3769
- setLocalDocs((prev) => ({
3863
+ if (!refresh) setLocalDocs((prev) => ({
3770
3864
  ...prev,
3771
3865
  [entry.path]: {
3772
3866
  path: entry.path,
@@ -3780,20 +3874,26 @@ window.__ModuleLoader__.load({
3780
3874
  try {
3781
3875
  if (!mindmapFace || typeof mindmapFace.readDocument !== "function") throw new Error("只读文档能力不可用");
3782
3876
  const loaded = await mindmapFace.readDocument(sessionId, relPathWithin(fsTree.cwd, entry.path, entry.name));
3877
+ if (!isCurrent()) return;
3783
3878
  setLocalDocs((prev) => {
3784
- const current = prev[entry.path];
3785
- if (!current || current.op !== "local") return prev;
3786
- return { ...prev, [entry.path]: { ...current, op: "local-read", content: String(loaded.content ?? ""), revision: loaded.revision ?? null } };
3879
+ const current = prev[entry.path] ?? merged.byPath[entry.path];
3880
+ if (!current) return prev;
3881
+ return { ...prev, [entry.path]: { ...current, op: "local-read", error: null, content: String(loaded.content ?? ""), revision: loaded.revision ?? null, snapshotEventKey } };
3787
3882
  });
3788
- setFilledHint(`已直接打开「${entry.name}」;需要 AI 编辑时可继续发送打开指令`);
3883
+ setFilledHint(refresh ? `已刷新「${entry.name}」` : `已直接打开「${entry.name}」;需要 AI 编辑时可继续发送打开指令`);
3789
3884
  } catch (error) {
3885
+ if (!isCurrent()) return;
3790
3886
  setLocalDocs((prev) => {
3791
3887
  const current = prev[entry.path];
3792
3888
  if (!current || current.op !== "local") return prev;
3793
3889
  return { ...prev, [entry.path]: { ...current, error: String(error?.message ?? error) } };
3794
3890
  });
3891
+ setExportError(`读取脑图失败:${String(error?.message ?? error)}`);
3795
3892
  setFilledHint("直接读取失败,可重试或让 AI 打开该文件");
3893
+ } finally {
3894
+ if (isCurrent()) setReadingPath(null);
3796
3895
  }
3896
+ if (!isCurrent() || !submit) return;
3797
3897
  // ② 草稿为空时再让 AI 接管焦点;已有草稿绝不覆盖。
3798
3898
  if (!draftBlocked() && submitChatCommand(text)) {
3799
3899
  focusSentRef.current = entry.path;
@@ -3802,11 +3902,16 @@ window.__ModuleLoader__.load({
3802
3902
  if (draftBlocked()) {
3803
3903
  if (typeof navigator !== "undefined" && navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
3804
3904
  navigator.clipboard.writeText(text).catch(() => {});
3805
- setFilledHint("检测到未发送的草稿,文件已打开;打开指令已复制到剪贴板");
3905
+ setFilledHint("已保留聊天草稿并打开文件;打开指令已复制到剪贴板");
3806
3906
  } else setFilledHint(`文件已打开,请手动发送:${text}`);
3807
3907
  }
3808
3908
  }
3809
3909
 
3910
+ function refreshDocument() {
3911
+ if (!doc) return;
3912
+ return openMindmap({ path: doc.path, name: `${stemOf(doc.path)}.md` }, { submit: false, refresh: true });
3913
+ }
3914
+
3810
3915
  /** 016 加载态恢复:错误/超时后重试——重发打开指令并重启看门狗。 */
3811
3916
  function retryOpen() {
3812
3917
  if (!doc || doc.op !== "local") return;
@@ -4187,6 +4292,13 @@ window.__ModuleLoader__.load({
4187
4292
  const exportErrorSpan = exportError
4188
4293
  ? (0, react_jsx_runtime.jsx)("span", { style: { color: "var(--dsw-alias-label-error)", fontSize: "12px" }, children: exportError })
4189
4294
  : null;
4295
+ const refreshBtn = (0, react_jsx_runtime.jsx)("button", {
4296
+ type: "button", style: S.action,
4297
+ disabled: !doc || readingPath !== null,
4298
+ onClick: refreshDocument,
4299
+ title: "从磁盘重新读取当前脑图,保留聊天草稿",
4300
+ children: readingPath === doc?.path ? "刷新中…" : "刷新脑图",
4301
+ });
4190
4302
  const approvalControls = approvalState && approvalState.mode === "session"
4191
4303
  ? (0, react_jsx_runtime.jsxs)("span", { style: { display: "inline-flex", alignItems: "center", gap: "6px", color: "var(--dsw-alias-label-tertiary)", fontSize: "12px" }, children: [
4192
4304
  (0, react_jsx_runtime.jsx)("span", { title: "授权按当前会话与脑图文件隔离", children: approvalState.grantedDocuments > 0 ? "本会话已允许写入" : "本会话尚未授权" }),
@@ -4258,13 +4370,14 @@ window.__ModuleLoader__.load({
4258
4370
  (0, react_jsx_runtime.jsx)("span", { style: S.spacer }),
4259
4371
  approvalControls,
4260
4372
  exportErrorSpan,
4373
+ refreshBtn,
4261
4374
  copyBtn,
4262
4375
  exportBtn,
4263
4376
  ] }),
4264
4377
  // 016:脑图视图走 MindmapCanvas(自带滚动 + 居中 + 右上角缩放控制条),
4265
4378
  // 不再套 S.body(避免嵌套滚动容器与双重 padding);目录/加载/空态保持原样。
4266
4379
  bodyMode === BODY_MODE.canvas
4267
- ? (0, react_jsx_runtime.jsx)(MindmapCanvas, { node: tree, theme, fitKey: doc && doc.path, reveal, inputActions })
4380
+ ? (0, react_jsx_runtime.jsx)(MindmapCanvas, { node: tree, theme, fitKey: doc && doc.path, reveal, inputActions, readInputState })
4268
4381
  : (0, react_jsx_runtime.jsx)("div", { style: S.body, children: bodyMode === BODY_MODE.tree
4269
4382
  ? renderTree()
4270
4383
  : bodyMode === BODY_MODE.loading
@@ -4294,6 +4407,7 @@ window.__ModuleLoader__.load({
4294
4407
  (0, react_jsx_runtime.jsxs)("div", { style: S.headerTop, children: [
4295
4408
  (0, react_jsx_runtime.jsx)("span", { style: S.spacer }),
4296
4409
  approvalControls,
4410
+ refreshBtn,
4297
4411
  copyBtn,
4298
4412
  exportBtn,
4299
4413
  exportErrorSpan,
@@ -4360,7 +4474,7 @@ window.__ModuleLoader__.load({
4360
4474
  : (doc && doc.op === "local")
4361
4475
  ? renderLoading()
4362
4476
  : renderTree() })
4363
- : (0, react_jsx_runtime.jsx)(MindmapCanvas, { node: tree, theme, fitKey: doc && doc.path, reveal, inputActions }),
4477
+ : (0, react_jsx_runtime.jsx)(MindmapCanvas, { node: tree, theme, fitKey: doc && doc.path, reveal, inputActions, readInputState }),
4364
4478
  tabMenu ? (0, react_jsx_runtime.jsxs)("div", {
4365
4479
  style: { ...S.treeMenu, left: tabMenu.x, top: tabMenu.y },
4366
4480
  onContextMenu: (e) => e.preventDefault(),
@@ -4389,7 +4503,7 @@ window.__ModuleLoader__.load({
4389
4503
  * 但 hooks 照常跑——auto-open effect 能在面板关着时调 onAutoOpen 把它拉起。
4390
4504
  */
4391
4505
  function MindmapDetailsPanel(props) {
4392
- const { mindmapFace, open, sessionId, inputActions, nodes, nodesVersion, onOpen, onClose } = props;
4506
+ const { mindmapFace, open, sessionId, inputActions, readInputState, nodes, nodesVersion, documents, onOpen, onClose } = props;
4393
4507
  // 014 overlay 宽度:localStorage 持久化,拖拽钳制 [280, 视口 80%]。
4394
4508
  // 窗口尺寸变化时持续钳制——只在挂载时压一次的话,窗口先放大→拖宽
4395
4509
  // 面板→再缩小会让面板保持旧像素宽,聊天区被挤没。
@@ -4537,7 +4651,9 @@ window.__ModuleLoader__.load({
4537
4651
  sessionId,
4538
4652
  nodes,
4539
4653
  nodesVersion,
4654
+ documents,
4540
4655
  inputActions,
4656
+ readInputState,
4541
4657
  mindmapFace,
4542
4658
  visible: open,
4543
4659
  onAutoOpen: onOpen,
@@ -4599,7 +4715,9 @@ window.__ModuleLoader__.load({
4599
4715
  sessionId,
4600
4716
  nodes: data.nodes,
4601
4717
  nodesVersion: data.nodesVersion,
4718
+ documents: data.documents,
4602
4719
  inputActions: data.inputActions,
4720
+ readInputState: data.readInputState,
4603
4721
  mindmapFace: data.mindmapFace,
4604
4722
  visible,
4605
4723
  onAutoOpen,
@@ -4648,7 +4766,13 @@ window.__ModuleLoader__.load({
4648
4766
  * useChat(0.1.2-rc.1+)优先、useSession(≤0.1.1)兜底。
4649
4767
  */
4650
4768
  function MindmapSlot(props) {
4651
- const { useSession, useChat, sessionId, inputActions, mindmapFace } = props;
4769
+ const { useSession, useChat, useInput, sessionId, inputActions, mindmapFace } = props;
4770
+ const inputState = useInput ? useInput((state) => state) : null;
4771
+ const inputRef = react.useRef({ sessionId, state: inputState });
4772
+ inputRef.current = { sessionId, state: inputState };
4773
+ const readInputState = react.useCallback(() => inputRef.current.sessionId === sessionId ? inputRef.current.state : null, [sessionId]);
4774
+ // 旧宿主没有 useInput 时仍探测原动作面;新宿主只读正式快照。
4775
+ const readDraftState = useInput ? readInputState : undefined;
4652
4776
  const nodesHook = useChat ?? useSession;
4653
4777
  const nodes = nodesHook ? nodesHook(conversationNodesOf) : EMPTY_NODES;
4654
4778
  // 016 可靠性加固:结构指纹作第二 selector。store 原地改数组(引用
@@ -4656,6 +4780,8 @@ window.__ModuleLoader__.load({
4656
4780
  // 重跑——「AI 打开了脑图但面板不展开」的根因。指纹是原始值字符串,
4657
4781
  // 值比较天然绕过引用相等短路;内容钩子不可用时回退空串。
4658
4782
  const nodesVersion = nodesHook ? nodesHook((s) => nodesFingerprint(conversationNodesOf(s))) : "";
4783
+ const documentReducer = react.useMemo(() => createDocumentReducer(), [sessionId]);
4784
+ const documents = react.useMemo(() => documentReducer(nodes), [nodes, nodesVersion, documentReducer]);
4659
4785
 
4660
4786
  // 026 sidebar 模式检测:betterSidebar 服务可用时走原生 Tab,否则走独立面板。
4661
4787
  const sidebar = react.useSyncExternalStore(sidebarBus.subscribe, sidebarBus.get);
@@ -4668,8 +4794,8 @@ window.__ModuleLoader__.load({
4668
4794
  // 当前 sessionId 的快照——模块级 Map 不残留旧会话的 nodes/inputActions。
4669
4795
  react.useEffect(() => {
4670
4796
  if (!sidebarMode || !sessionId) return;
4671
- sessionStore.set(sessionId, { nodes, nodesVersion, inputActions, mindmapFace });
4672
- }, [sidebarMode, sessionId, nodes, nodesVersion, inputActions, mindmapFace]);
4797
+ sessionStore.set(sessionId, { nodes, nodesVersion, documents, inputActions, readInputState: readDraftState, mindmapFace });
4798
+ }, [sidebarMode, sessionId, nodes, nodesVersion, documents, inputActions, readDraftState, mindmapFace]);
4673
4799
  // 028 会话切换 / 退出 sidebar 模式时清理旧快照。
4674
4800
  const lastSessionRef = react.useRef(null);
4675
4801
  react.useEffect(() => {
@@ -4701,7 +4827,7 @@ window.__ModuleLoader__.load({
4701
4827
  // MindmapWorkspace 的 auto-open effect 不跑。MindmapSlot 始终在头部
4702
4828
  // 挂载,在这里检测新的 create/open 结果并调 openTab 把 Tab 拉起。
4703
4829
  // 首次进入 sidebar 模式时只记基线(不弹历史文档),之后只响应新事件。
4704
- const sidebarDocs = react.useMemo(() => reduceDocuments(nodes), [nodes, nodesVersion]);
4830
+ const sidebarDocs = documents;
4705
4831
  const sidebarSeen = react.useRef(null);
4706
4832
  const sidebarInitedRef = react.useRef(false);
4707
4833
  react.useEffect(() => {
@@ -4770,8 +4896,10 @@ window.__ModuleLoader__.load({
4770
4896
  open,
4771
4897
  sessionId,
4772
4898
  inputActions,
4899
+ readInputState: readDraftState,
4773
4900
  nodes,
4774
4901
  nodesVersion,
4902
+ documents,
4775
4903
  mindmapFace,
4776
4904
  onOpen: () => setOpen(true),
4777
4905
  onClose: () => setOpen(false),
@@ -4801,12 +4929,12 @@ window.__ModuleLoader__.load({
4801
4929
  })();
4802
4930
 
4803
4931
  // sessionStore:按 sessionId 隔离的数据桥。MindmapSlot 始终在头部槽位里
4804
- // 调用 useChat/useSession 钩子获取 nodes/nodesVersion/inputActions,写入
4932
+ // 调用 useChat/useSession/useInput 获取文档和最新输入快照读取器,写入
4805
4933
  // 对应 sessionId 的快照;MindmapSidebarTab 组件用 useSyncExternalStore
4806
4934
  // 订阅自己 sessionId 的快照,拿到数据后渲染 MindmapWorkspace。
4807
4935
  // 028 生命周期清理:MindmapSlot 在会话切换(sessionId 变化)和组件卸载
4808
4936
  // 时删除对应 sessionId 的快照——模块级 Map 不残留旧会话的
4809
- // nodes/inputActions。退出 sidebar 模式(Better Sidebar 卸载)时也清理。
4937
+ // nodes/inputActions/文档缓存。退出 sidebar 模式(Better Sidebar 卸载)时也清理。
4810
4938
  const sessionStore = (() => {
4811
4939
  const sessions = new Map();
4812
4940
  const listeners = new Map();
@@ -4857,6 +4985,16 @@ window.__ModuleLoader__.load({
4857
4985
  return Array.isArray(list) ? list : [];
4858
4986
  }
4859
4987
 
4988
+ /** 页面基础地址保留反向代理前缀;API 请求始终留在当前页面的源。 */
4989
+ function mindmapApiUrl(method) {
4990
+ const location = window.location?.href;
4991
+ const base = (typeof document !== "undefined" && document.baseURI) || location;
4992
+ if (!base) return `/mindmap/api/${method}`;
4993
+ const url = new URL(`mindmap/api/${method}`, base);
4994
+ if (location && url.origin !== new URL(location).origin) throw new Error("脑图 API 的页面基础地址必须同源");
4995
+ return url.href;
4996
+ }
4997
+
4860
4998
  function apply(ctx) {
4861
4999
  const face = {};
4862
5000
 
@@ -4990,7 +5128,7 @@ window.__ModuleLoader__.load({
4990
5128
  // 同款机制——官方 host.listDirectory 在 native picker 环境必挂,见 013)。
4991
5129
  // 客户端只读目录,仍无任何写文件通道。
4992
5130
  face.listTree = async (sessionId, path) => {
4993
- const response = await fetch("/mindmap/api/tree", {
5131
+ const response = await fetch(mindmapApiUrl("tree"), {
4994
5132
  method: "POST",
4995
5133
  headers: { "content-type": "application/json" },
4996
5134
  body: JSON.stringify(typeof path === "string" && path ? { sessionId, path } : { sessionId }),
@@ -5005,7 +5143,7 @@ window.__ModuleLoader__.load({
5005
5143
  // wait for a model turn just to fetch bytes; the empty-draft path may still
5006
5144
  // ask the AI to take over editing after the document is visible.
5007
5145
  face.readDocument = async (sessionId, path) => {
5008
- const response = await fetch("/mindmap/api/document", {
5146
+ const response = await fetch(mindmapApiUrl("document"), {
5009
5147
  method: "POST",
5010
5148
  headers: { "content-type": "application/json" },
5011
5149
  body: JSON.stringify({ sessionId, path }),
@@ -5017,7 +5155,7 @@ window.__ModuleLoader__.load({
5017
5155
  return parsed.value;
5018
5156
  };
5019
5157
  face.readApprovalStatus = async (sessionId) => {
5020
- const response = await fetch("/mindmap/api/approval", {
5158
+ const response = await fetch(mindmapApiUrl("approval"), {
5021
5159
  method: "POST",
5022
5160
  headers: { "content-type": "application/json" },
5023
5161
  body: JSON.stringify({ sessionId, action: "status" }),
@@ -5029,7 +5167,7 @@ window.__ModuleLoader__.load({
5029
5167
  return parsed.value;
5030
5168
  };
5031
5169
  face.revokeApproval = async (sessionId) => {
5032
- const response = await fetch("/mindmap/api/approval", {
5170
+ const response = await fetch(mindmapApiUrl("approval"), {
5033
5171
  method: "POST",
5034
5172
  headers: { "content-type": "application/json" },
5035
5173
  body: JSON.stringify({ sessionId, action: "revoke" }),
@@ -5132,6 +5270,7 @@ window.__ModuleLoader__.load({
5132
5270
  // 038 解析兜底:永不抛的结果对 { tree, error }(供测试验证失败态分支)。
5133
5271
  parseTreeResult,
5134
5272
  reduceDocuments,
5273
+ createDocumentReducer,
5135
5274
  mergeDocuments,
5136
5275
  autoOpenTarget,
5137
5276
  openingEventKeys,
@@ -5198,6 +5337,7 @@ window.__ModuleLoader__.load({
5198
5337
  focusZoom,
5199
5338
  // 033 点击聚焦跳变钳制 + 保视野拉回位移(供测试)。
5200
5339
  clampFocusJump,
5340
+ fitAllZoom,
5201
5341
  edgePullOffsets,
5202
5342
  // 021 画布平移手势判定(供测试)。
5203
5343
  PAN,
@@ -5210,6 +5350,7 @@ window.__ModuleLoader__.load({
5210
5350
  // 023 双代兼容纯函数(供测试):会话内容节点 / settings 信封。
5211
5351
  conversationNodesOf,
5212
5352
  settingsNamespacesOf,
5353
+ mindmapApiUrl,
5213
5354
  // 021 画布组件:仅供测试驱动平移手势(不参与运行时契约)。
5214
5355
  MindmapCanvas,
5215
5356
  // 026 better-sidebar 共存:服务总线 + 会话数据桥 + Tab 壳(供测试)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mindmap",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Mindmap plugin for DeepSeek Harness: a plain markdown file in the working directory IS the mindmap; the chat edits it step by step and the right-side panel follows live.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,6 +19,7 @@
19
19
  "main": "index.js",
20
20
  "scripts": {
21
21
  "build:client": "node scripts/build-client.mjs",
22
+ "bench:client": "node scripts/benchmark-client.mjs",
22
23
  "check": "npm run build:client && node --check index.js && node --check client.js && node --check scripts/build-client.mjs && node --check test/index.test.js && node --check test/client.test.js",
23
24
  "test": "node --test",
24
25
  "verify": "npm run check && npm test",