diff --git a/AGENTS.md b/AGENTS.md index e08d7aa4..2264d540 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,6 +105,13 @@ - 当前项目已配置 CodeGraph MCP;结构性代码问题优先使用 `codegraph_*` 工具:`codegraph_search` 查符号,`codegraph_callers` / `codegraph_callees` 查调用关系,`codegraph_impact` 做影响分析,`codegraph_context` / `codegraph_explore` 获取聚焦上下文,`codegraph_files` 查看索引文件结构,`codegraph_status` 检查索引健康。 - CodeGraph 是当前开发态代码图主工具;代码改动后运行 `codegraph sync .`,大范围重构、排除规则变化或索引异常时运行 `codegraph index . --force`。只有查找字面文本、日志字符串、注释原文,或已经明确目标文件时,才优先用 `rg` / 直接读文件。 +## Reference-Code 快速对照流程 + +- 对照 VSCode / Sidex / Zed / Lapce / Tiptap 等参考实现时,先确认实际源码目录和对应 `.codegraph/` 是否存在;当前优先参考 `/mnt/Data1T/mnote/reference-code/sidex-main` 的完整 VSCode 工作台源码,`reference-code/vscode` 只作为裁剪版辅助证据。 +- 每次只围绕一个功能切面做对照,例如 Explorer 打开目标、编辑器 tab、资源生命周期、拖拽排序、快捷键或 overlay 定位;不要一次性抽象迁移整个参考项目。 +- 推荐步骤:`codegraph_status` 确认索引 -> `codegraph_search/context` 找参考实现入口 -> `codegraph_callers/callees` 看调用链 -> 对应查 MNote 当前链路 -> 映射到 Rust kernel / mnote-web / 前端 host 的正确边界 -> 补 smoke 或测试。 +- 对照结论必须区分“可直接采用的交互/状态模型”“只适合作参考的实现细节”“不符合 MNote local-first / tree-first 主线的内容”;不要把参考项目中的 UI 层状态当成 MNote 的新事实源。 + ## 常用命令 - 根目录热启动:`npm run desktop:hot` diff --git a/REASONIX.md b/REASONIX.md index bccd8799..0757f2fe 100644 --- a/REASONIX.md +++ b/REASONIX.md @@ -43,6 +43,13 @@ - Use native search only for literal text, comments, log messages, or after a specific file is already identified. - Keep the project index fresh in development: run `codegraph sync .` after code changes; use `codegraph index . --force` when the index looks stale or after broad restructuring. +## Reference-Code Comparison + +- Reference implementations live under `/mnt/Data1T/mnote/reference-code/`; prefer `/mnt/Data1T/mnote/reference-code/sidex-main` for VSCode workbench comparisons because it contains the fuller `src/vs/workbench` tree, while `reference-code/vscode` is a smaller auxiliary snapshot. +- Compare one feature slice at a time, such as explorer open target, editor tabs, resource lifecycle, drag-and-drop ordering, keybindings, or overlay placement. +- Fast workflow: check `codegraph_status` for both projects, locate reference entry points with `codegraph_search/context`, inspect callers/callees, inspect the matching MNote chain, then map the result onto Rust kernel / `mnote-web` / frontend host boundaries. +- Always classify findings as: reusable interaction/state model, reference-only implementation detail, or incompatible with MNote local-first / tree-first architecture. + ## Conventions - **Smoke test pattern**: standalone Playwright scripts under `scripts/task-*.js` using a shared harness (`ensureAuthenticated`, `createTempDocument`, `cleanupDocuments`). All use `"use strict"` and `require("playwright")` (`scripts/task110-page-title-single-truth-smoke.js:1-4`). diff --git a/design/04-tree-domain/process/4-38-filetree-resource-lifecycle-open-target-checklist-v1.md b/design/04-tree-domain/process/4-38-filetree-resource-lifecycle-open-target-checklist-v1.md new file mode 100644 index 00000000..69a41391 --- /dev/null +++ b/design/04-tree-domain/process/4-38-filetree-resource-lifecycle-open-target-checklist-v1.md @@ -0,0 +1,52 @@ +# 4-38 File Tree Resource Lifecycle 与 Open Target 收口 Checklist v1 + +> 状态:process +> +> 日期:2026-05-20 +> +> Owner:File Tree / local_folder executor / resource lifecycle + +## 1. 目标 + +对齐 Sidex Explorer 的“资源模型 + open target + lifecycle command”闭环,先修 MNote 当前最影响 local-first 的缺口:raw local file / directory / resource open target 表达不足、`local-file:` 删除进入垃圾箱不稳定、资源生命周期多入口分散。 + +## 2. 允许修改范围 + +- `rust/crates/mnote-web/src/tree_shell/filetree_runtime.rs` +- `rust/crates/mnote-web/src/routes/tree.rs` +- `rust/crates/mnote-web/src/routes/local_folder_source.rs` +- `rust/crates/mnote-web/src/routes/resource_trash.rs` +- `rust/crates/mnote-web/src/ssr/pages/layout.rs` +- 相关 Rust 单测与本地文件夹 smoke + +## 3. Checklist + +- [ ] 扩展或补强 File Tree open target,能表达 local raw file、directory、asset folder、mindmap/table/office/image 等资源身份。 +- [ ] 统一 local resource identity: + - [x] 支持 `local-file:`。 + - [ ] 保留 `local:asset:` / `local:node:` 兼容。 + - [x] 规范化 root-relative UTF-8 path,不允许 root escape。 +- [x] `resolve_local_raw_file_id` 支持真实 projection 暴露的 `local-file:`,并补 restore/purge 查找兼容测试。 +- [x] 本地单独删除 mindmap / office / 普通附件资源时必须进入 `.mnote/trash-index.json`,不绕过 local trash。 +- [ ] 前端 delete/bulk delete 对 local resource 优先走 `/api/tree/commands` 的统一 archive/purge/restore 语义,旧 resource URL 只作为兼容 fallback。 +- [x] local_folder move 若传入 `sortOrder`,不得静默丢弃;至少返回明确 unsupported,或实现稳定排序记录。 + +## 4. 验收 + +- [x] Rust 测试覆盖 `local-file:Page/资源.ext` delete / restore / purge。 +- [x] Rust 测试覆盖本地 mindmap 文件单独删除进入 trash index。 +- [ ] 浏览器 smoke 覆盖本地文件夹资源行单独删除后垃圾箱可见、恢复回原路径、永久删除清理索引。 +- [ ] 现有 `task437-local-folder-asset-trash-lifecycle-smoke.js` 继续通过。 +- [x] `cargo test -p mnote-web local_folder` 相关测试通过。 + +## 4.1 本轮执行记录 + +- 已合入:`local-file:` 中文路径资源 delete / restore / purge 覆盖,local move `sortOrder` 返回 `_unsupportedFields.sortOrder`,避免静默吞字段。 +- 已验证:相关 Rust targeted tests 与完整 `cargo test -p mnote-web -- --test-threads=1` 通过。 +- 未完成:File Tree open target 合同扩展、前端 delete/bulk delete 全面 cutover、浏览器垃圾箱资源行全链 smoke。 + +## 5. 非目标 + +- 不做 Convex 云端完整文件系统 parity。 +- 不实现完整 undo/redo。 +- 不实现复杂 paste / drop 二进制上传矩阵。 diff --git a/design/05-editor-mainline/process/5-16-editor-group-resource-tab-safety-checklist-v1.md b/design/05-editor-mainline/process/5-16-editor-group-resource-tab-safety-checklist-v1.md new file mode 100644 index 00000000..e0153a22 --- /dev/null +++ b/design/05-editor-mainline/process/5-16-editor-group-resource-tab-safety-checklist-v1.md @@ -0,0 +1,53 @@ +# 5-16 Editor Group 与 Resource Tab 安全收口 Checklist v1 + +> 状态:process +> +> 日期:2026-05-20 +> +> Owner:`mnote-web` 主编辑区 runtime / resource tab + +## 1. 目标 + +把当前浏览器内存版 resource tab 收口为轻量 editor group 模型的第一阶段:不引入完整 VSCode 多 group,不改变 Page Aggregate 事实源,只解决打开、激活、关闭和脏资源防护的最小闭环。 + +## 2. 允许修改范围 + +- `rust/crates/mnote-web/src/routes/web_shell.rs` +- `rust/crates/mnote-web/src/ssr/pages/document.rs` +- `rust/crates/mnote-web/src/ssr/styles.rs` +- `scripts/task457-main-editor-resource-tab-smoke.js` +- 可新增一个聚焦 smoke,例如 `scripts/task460-resource-tab-close-dirty-smoke.js` + +## 3. Checklist + +- [ ] 定义轻量 `MainEditorTabEntry` / `mainEditorTabRegistry` 语义,至少包含 `id`、`kind`、`title`、`dirty`、`saving`、`hasExternalConflict`、`lastActiveAt`。 +- [x] 保持 page tab 为固定 tab,但 resource tab 激活/关闭应走同一套 registry 状态更新。 +- [x] `closeResourceTab` 关闭前检查 resource session: + - [x] `saving=true` 时禁止直接关闭或等待保存完成。 + - [x] `hasExternalConflict=true` 时禁止静默关闭。 + - [x] `dirty=true` 时触发保存或确认流程;不得直接释放 session。 +- [x] 关闭 active resource tab 后按 MRU 回到上一个 resource tab;没有可用 resource tab 时才回到 page tab。 +- [x] resource tab 激活时更新稳定 `aria-selected`、`tabindex` 和 panel hidden 状态。 +- [ ] 打开失败时保留 error placeholder tab,允许用户关闭或重试,不要留下半注册状态。 + +## 4. 验收 + +- [x] 打开两个 resource tab,切到第二个并关闭后,应回到第一个,而不是无条件回 page tab。 +- [x] 编辑 resource markdown 后立即点关闭,不应静默丢弃未保存内容。 +- [x] 保存中关闭不会释放 editor session。 +- [ ] 打开失败的 resource tab 有明确错误占位,并可关闭。 +- [x] 现有 `task457-main-editor-resource-tab-smoke.js` 继续通过。 +- [x] 新增 close dirty / MRU smoke 通过。 + +## 4.1 本轮执行记录 + +- 已合入:resource tab MRU、关闭 guard、`aria-selected` / `tabindex` 同步、关闭后回退到上一个 resource tab。 +- 已新增:`scripts/task460-resource-tab-close-dirty-smoke.js` 覆盖近期本地输入后的关闭阻止。 +- 未完成:正式 `MainEditorTabEntry` 模型、打开失败 placeholder tab。 + +## 5. 非目标 + +- 不实现完整 VSCode preview / pinned / sticky / drag reorder。 +- 不实现 tab 持久化恢复。 +- 不改变 secondary pane 布局。 +- 不把 `resourceTabRegistry` 移到后端持久状态。 diff --git a/design/05-editor-mainline/process/5-17-resource-editor-kind-and-smoke-matrix-checklist-v1.md b/design/05-editor-mainline/process/5-17-resource-editor-kind-and-smoke-matrix-checklist-v1.md new file mode 100644 index 00000000..711c4acc --- /dev/null +++ b/design/05-editor-mainline/process/5-17-resource-editor-kind-and-smoke-matrix-checklist-v1.md @@ -0,0 +1,57 @@ +# 5-17 Resource Editor Kind 与 Smoke 矩阵 Checklist v1 + +> 状态:process +> +> 日期:2026-05-20 +> +> Owner:资源打开 resolver / Office / Markdown/Text/Code/Image/PDF smoke + +## 1. 目标 + +把资源类型识别和打开策略从分散 if/else 收口为轻量 resolver,并补齐当前缺失的类型 smoke。默认目标是主编辑区 resource tab;右侧边栏和新窗口必须作为显式目标保留。 + +## 2. 允许修改范围 + +- `rust/crates/mnote-web/src/routes/web_shell.rs` +- `rust/crates/mnote-web/src/ssr/pages/layout.rs` +- `rust/crates/mnote-web/src/ssr/styles.rs` +- `rust/crates/mnote-web/src/routes/onlyoffice.rs` +- `scripts/task457-main-editor-resource-tab-smoke.js` +- `scripts/task459-local-markdown-attachment-tab-smoke.js` +- 可新增 resource kind smoke + +## 3. Checklist + +- [ ] 定义轻量 resource editor resolver: + - [ ] 输入:`name`、`mimeType`、`href`、`assetId`、`rootUri`、`path`、`openTarget`。 + - [ ] 输出:`editorKind`、`badgeKind`、`defaultOpenMode`、`editable`、`viewerUrl`。 +- [x] `.md` / `.markdown` / `.txt` / 常见 code 文件继续使用 tiptap resource editor。 +- [ ] Office 文件默认在主编辑区 tab 内 iframe 打开,显式新窗口仍可打开。 +- [x] PDF 使用独立 `pdf` badge kind,不再复用 ppt。 +- [x] image 使用 image badge kind 和 img viewer。 +- [x] unknown file 有明确 fallback:下载/新窗口/错误占位,不应无响应。 +- [ ] `active-tab`、`side`、`new-window` 三个 target 在同一 resolver 后执行,不再散落在 attachment capture 与 filetree click 中。 + +## 4. Smoke 矩阵 + +- [x] `.md` 上传/文件树点击 -> 主编辑区 tiptap tab,可编辑并写回资源文件。 +- [x] `.txt` -> 主编辑区 tiptap tab,可编辑并写回。 +- [x] `.json` 或 `.ts` -> 主编辑区 tiptap/code-like tab,可编辑并写回。 +- [ ] `.docx` -> 主编辑区 Office iframe,DocumentServer 可回源。 +- [ ] `.pptx` / `.xlsx` -> badge 颜色分别正确。 +- [x] `.pdf` -> 主编辑区 iframe,badge 为 pdf 独立颜色。 +- [x] image -> 主编辑区 img viewer。 +- [x] unknown binary -> 明确 fallback,不破坏 page tab 切换。 + +## 4.1 本轮执行记录 + +- 已合入:PDF 独立 badge kind、file fallback badge、resource kind smoke 覆盖 markdown/text/code/image/pdf 与未知类型不破坏 tab 回退。 +- 已验证:`scripts/task461-resource-kind-smoke.js` 与 `uploaded_attachment_rows_use_colored_file_badges` 通过。 +- 未完成:正式 resource editor resolver 抽象、Office DocumentServer 回源修复、`active-tab` / `side` / `new-window` 统一 resolver 后执行。 + +## 5. 非目标 + +- 不引入 Monaco / CodeMirror。 +- 不实现云端资源写回。 +- 不重构 OnlyOffice DocumentServer 部署。 +- 不改变 `.md` 资源仍用 tiptap 编辑的产品口径。 diff --git a/design/10-review/process/12-sidex-vscode-workbench-gap-review-v1.md b/design/10-review/process/12-sidex-vscode-workbench-gap-review-v1.md new file mode 100644 index 00000000..3f2cc2ea --- /dev/null +++ b/design/10-review/process/12-sidex-vscode-workbench-gap-review-v1.md @@ -0,0 +1,101 @@ +# 12 Sidex / VSCode Workbench 对照审查 v1 + +> 状态:process +> +> 日期:2026-05-20 +> +> 范围:`reference-code/sidex-main` 对照 MNote 当前主编辑区、资源 tab、File Tree、资源生命周期和 smoke 覆盖。 + +## 1. 审查方法 + +本轮使用 CodeGraph 与只读 subagent 并行审查,优先对照 `/mnt/Data1T/mnote/reference-code/sidex-main`,因为该目录包含较完整的 VSCode workbench 源码。`reference-code/vscode` 当前更像裁剪版快照,只作为辅助证据。 + +审查按功能切面展开: + +- Editor / tab:`EditorService.openEditor`、`EditorGroupModel`、`EditorGroupView`、`MultiEditorTabsControl`、`OpenEditorsView`。 +- Explorer / file actions:`ExplorerService`、`ExplorerView`、`fileActions`、`ResourceFileEdit` / `IBulkEditService`。 +- MNote 对应链路:`mnote-web` 的 `web_shell.rs`、`layout.rs`、`tree.rs`、`local_folder_source.rs`、`resource_trash.rs`、`onlyoffice.rs`、`leptos-tiptap-spike`。 + +## 2. Sidex / VSCode 可借鉴模型 + +- Explorer 打开文件不是按 UI 分支散落处理,而是统一交给 `IEditorService.openEditor({ resource, options }, ACTIVE_GROUP / SIDE_GROUP)`。 +- `EditorGroupModel` 是 tab/editor 列表真相层,维护 `editors`、`active`、`preview`、`sticky`、`transient`、MRU 和 selection,并发布 open / close / move / dirty / label 等模型事件。 +- `EditorTitleControl` / `MultiEditorTabsControl` 只是消费模型做渲染、滚动、reveal active、DnD、右键菜单和 tab action,不承载资源事实。 +- `OpenEditorsView` 监听 editor group model,与 active editor、visible editors、dirty/label 状态联动。 +- Explorer 文件生命周期通过 `ResourceFileEdit` + `IBulkEditService` 聚合执行,并处理 dirty working copy、readonly、trash / permanent delete、undo label、cancel 和失败 fallback。 + +## 3. MNote 当前链路 + +- 主文档页由 `document_page_shell` 生成,SSR 初始只有固定 page tab、resource tab host 和可选 secondary pane。 +- `resourceTabRegistry` 是浏览器内存 Map,`openResourceInActiveTab` 按 `objectIdentity` 去重并动态创建 tab/panel;关闭时直接 unmount、remove、delete。 +- 文件树点击在 `layout.rs` 中分发:document / markdown 页面走 `navigateToDocument`,asset 触发 `tree.asset.open`;local office 可进 resource tab,Convex office 仍可能新窗口,mindmap 走独立 object shell。 +- local_folder executor 已能处理 Markdown、目录、raw file 的 create / rename / copy / move / delete / restore / purge,但 filetree runtime 的打开目标模型和资源生命周期模型仍未完全对齐。 +- resource lifecycle 仍散在 tree command、resource_trash 兼容 route、layout 内联 JS 多条路径。 + +## 4. P0 缺口 + +### P0-1 统一 editor input / editor group / active editor 模型缺失 + +MNote 当前 page、secondary pane、resource tab、mindmap shell、OnlyOffice 新窗口分别走不同状态链。`resourceTabRegistry` 只存在于页面内存,不能被 Sidebar、Open Editors、快捷键、持久化恢复或 watcher 统一消费。 + +建议:先实现 MNote 轻量版 `EditorInput` / `EditorGroupState`,只覆盖 active group 内的 page/resource editor,不照搬 VSCode 完整 DI 和多 group grid。 + +### P0-2 resource tab 关闭缺少 dirty / saving / conflict 防护 + +`closeResourceTab` 直接释放 view/session 并移除 DOM,但同一文件中已经存在 `session.dirty`、`saving`、`hasExternalConflict` 等状态。关闭脏资源、保存中资源或外部冲突资源需要最小防护。 + +建议:关闭前先检查 session 状态;脏资源优先触发保存或阻止关闭并给出确认;保存中/冲突状态不能静默释放。 + +### P0-3 资源打开策略不一致 + +local office 可进入主编辑区 tab,Convex office 仍可能新窗口;mindmap 总是 object shell;部分非本页 code/text attachment 会 `window.open`。这和“默认主编辑区 tab,显式新窗口例外”的当前目标不一致。 + +建议:引入统一 `openResourceEditor(input, target)`,把 `active-tab`、`side`、`new-window` 作为显式目标,并把 resource kind 解析集中在 resolver。 + +### P0-4 File Tree 打开目标与资源生命周期模型不对齐 + +`filetree_runtime::OpenTarget` 只能表达 document / index / asset / asset-folder,不能完整表达 raw local file、directory、arbitrary resource;但 local_folder executor 已支持 raw file / directory lifecycle。 + +建议:扩展 open target / resource identity 合同,至少能稳定表达 `local_file`、`directory`、`mindmap`、`table`、`office`、`image` 等资源类型。 + +### P0-5 resource lifecycle 仍多入口分散 + +资源删除/恢复/永久删除仍由 tree command、resource_trash route、layout 内联 JS 分流处理。云端 asset、mindmap、table、本地 raw file 的路径不完全统一,容易造成垃圾箱、刷新、tab 状态不同步。 + +建议:继续推进 `tree.resource.*` cutover,旧 URL 只作为兼容 alias;前端也应逐步走统一 resource command client。 + +## 5. P1 缺口 + +- local_folder `move` 丢弃 `sortOrder`,拖拽排序与持久顺序语义不闭环。 +- resource tab active 状态只改 DOM,不同步 URL、sidebar active row、可恢复状态。 +- tab identity 混用 `objectIdentity / assetId / href / resource:file::`,需要 canonical resource identity。 +- mindmap 仍是独立 object shell,不是 main editor group 内的 editor kind。 +- secondary pane 与 main tab 是两套概念;长期应映射为 side target / side group 语义。 +- delete 缺少 dirty / readonly / undo / fallback 统一动作层。 +- paste / right-click paste 目标模型不完整;外部 drop 对二进制文件支持不足。 +- smoke 偏“资源存在 / 不闪烁”,缺少 editor workbench 语义断言。 + +## 6. P2 缺口 + +- tab strip 缺少键盘 roving tabindex、左右切换、关闭快捷键、MRU 回退。 +- tab overflow / reveal active / multi-row / context menu / close others 等能力较弱。 +- `.txt` / `.json` / `.ts` / PDF / image 等类型 smoke 矩阵不完整。 +- PDF badge 当前与 ppt 复用,资源类型与显示颜色语义应拆开。 +- File Tree 上下文菜单仍有英文和禁用项暴露实现缺口。 +- trash modal 与 resource command 仍是并行入口,需要继续收口到统一资源生命周期视图。 + +## 7. 不建议照搬 + +- 不照搬 Sidex / VSCode 的 DI service 容器。 +- 不照搬完整多 editor group grid;MNote 当前只需要 active tab + side target 的轻量模型。 +- 不照搬 Monaco / TextModel 作为 Markdown 文档事实源;MNote 主编辑仍是 tiptap / Page Aggregate / local Markdown。 +- 不照搬 Extension Host、ContextKey 全体系和完整 UndoRedoSource。 +- 不把参考项目 UI 层状态当成 MNote 的新事实源;MNote 的树、资源归属、生命周期仍以 Rust kernel / local-first 合同为准。 + +## 8. 执行拆分 + +本 review 拆分为三份执行 checklist: + +- `design/05-editor-mainline/process/5-16-editor-group-resource-tab-safety-checklist-v1.md` +- `design/04-tree-domain/process/4-38-filetree-resource-lifecycle-open-target-checklist-v1.md` +- `design/05-editor-mainline/process/5-17-resource-editor-kind-and-smoke-matrix-checklist-v1.md` diff --git a/rust/crates/mnote-web/src/routes/local_folder_source.rs b/rust/crates/mnote-web/src/routes/local_folder_source.rs index fb51bbf5..8784b278 100644 --- a/rust/crates/mnote-web/src/routes/local_folder_source.rs +++ b/rust/crates/mnote-web/src/routes/local_folder_source.rs @@ -2964,6 +2964,17 @@ pub fn execute_local_tree_command( document_id: &str, parent_id: Option<&str>, title: Option<&str>, +) -> Result { + execute_local_tree_command_with_sort(root_uri, action, document_id, parent_id, title, None) +} + +pub fn execute_local_tree_command_with_sort( + root_uri: &str, + action: &str, + document_id: &str, + parent_id: Option<&str>, + title: Option<&str>, + sort_order: Option, ) -> Result { let root_path = parse_file_root_uri(root_uri)?; let canonical_root = root_path.canonicalize().map_err(|error| { @@ -2988,7 +2999,7 @@ pub fn execute_local_tree_command( parent_id, title.unwrap_or("外部文件"), ), - "move" => move_local_entry(&canonical_root, document_id, parent_id), + "move" => move_local_entry(&canonical_root, document_id, parent_id, sort_order), "delete" | "trash" => trash_local_entry(&canonical_root, document_id), "restore" => restore_local_entry(&canonical_root, document_id), "purge" => purge_local_entry(&canonical_root, document_id), @@ -3511,11 +3522,24 @@ fn move_local_entry( root: &Path, document_id: &str, parent_id: Option<&str>, + sort_order: Option, ) -> Result { - if let Some(directory) = resolve_local_directory_id(root, document_id)? { - return move_local_directory(root, &directory, parent_id); + let result = if let Some(directory) = resolve_local_directory_id(root, document_id)? { + move_local_directory(root, &directory, parent_id)? + } else { + move_local_markdown_page(root, document_id, parent_id)? + }; + if let Some(sort_order) = sort_order.filter(|value| *value >= 0) { + if let Some(object) = result.as_object() { + let mut enriched = object.clone(); + enriched.insert( + "_unsupportedFields".to_string(), + json!({ "sortOrder": sort_order }), + ); + return Ok(Value::Object(enriched)); + } } - move_local_markdown_page(root, document_id, parent_id) + Ok(result) } fn move_local_markdown_page( @@ -6637,8 +6661,8 @@ mod tests { create_local_access_grant, create_share_grant, editor_blocks_to_markdown_for_file, encode_local_id_segment, ensure_local_path_read_access, ensure_local_workspace_access_for_actor, ensure_local_workspace_read_access_for_actor, - execute_local_tree_command, get_local_access_policy, get_share_grants, - initialize_local_page_id, initialize_local_workspace_for_actor, + execute_local_tree_command, execute_local_tree_command_with_sort, get_local_access_policy, + get_share_grants, initialize_local_page_id, initialize_local_workspace_for_actor, load_local_folder_file_tree_snapshot, load_local_folder_page_tree_snapshot, local_folder_watch_revision, local_resource_write_editor_blocks, local_workspace_id, open_local_file, record_shared_cache, record_sync_pending_change, @@ -6653,7 +6677,7 @@ mod tests { use axum::extract::{Extension, Path as AxumPath, Query}; use axum::http::{HeaderMap, Method, StatusCode}; use axum::Json; - use serde_json::Value; + use serde_json::{json, Value}; use std::sync::Mutex; fn env_lock() -> &'static Mutex<()> { @@ -8226,6 +8250,73 @@ fn main() {} let _ = std::fs::remove_dir_all(&root); } + #[test] + fn local_tree_command_delete_chinese_named_asset_in_subdir_uses_trash_index() { + let root = temp_root("mnote-local-delete-chinese-asset"); + init_workspace(&root); + std::fs::create_dir_all(root.join("Page")).expect("create Page dir"); + std::fs::write(root.join("Page").join("资源.ext"), b"chinese asset content") + .expect("write asset"); + let root_uri = format!("file://{}", root.display()); + let asset_id = "local-file:Page/资源.ext"; + + let result = execute_local_tree_command(&root_uri, "delete", asset_id, None, None) + .expect("delete chinese-named asset"); + assert_eq!(result["resourceKind"].as_str(), Some("local_file")); + assert_eq!(result["trashEntryId"].as_str(), Some(asset_id)); + assert!(!root.join("Page").join("资源.ext").exists()); + assert!(root.join(".mnote").join("trash").join("资源.ext").exists()); + let trash_index = std::fs::read_to_string(root.join(".mnote").join("trash-index.json")) + .expect("trash index"); + assert!( + trash_index.contains(asset_id), + "trash index should contain {asset_id}: {trash_index}" + ); + + let restored = execute_local_tree_command(&root_uri, "restore", asset_id, None, None) + .expect("restore chinese-named asset"); + assert_eq!(restored["documentId"].as_str(), Some(asset_id)); + assert!(root.join("Page").join("资源.ext").is_file()); + assert!(!root.join(".mnote").join("trash").join("资源.ext").exists()); + + execute_local_tree_command(&root_uri, "delete", asset_id, None, None) + .expect("re-delete chinese-named asset"); + let purged = execute_local_tree_command(&root_uri, "purge", asset_id, None, None) + .expect("purge chinese-named asset"); + assert_eq!(purged["ok"].as_bool(), Some(true)); + assert!(!root.join(".mnote").join("trash").join("资源.ext").exists()); + let trash_index_after_purge = + std::fs::read_to_string(root.join(".mnote").join("trash-index.json")) + .expect("trash index after purge"); + assert!( + !trash_index_after_purge.contains(asset_id), + "trash index should not contain purged {asset_id}: {trash_index_after_purge}" + ); + + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn local_tree_command_move_with_sort_order_annotates_unsupported() { + let root = temp_root("mnote-local-move-sort-order"); + init_workspace(&root); + std::fs::write(root.join("source.md"), "# Source\n").expect("write source"); + let root_uri = format!("file://{}", root.display()); + let doc_id = "local-md:source.md"; + + let result = + execute_local_tree_command_with_sort(&root_uri, "move", doc_id, None, None, Some(42)) + .expect("move with sort_order should succeed"); + assert_eq!(result["_unsupportedFields"]["sortOrder"], json!(42)); + assert!(root.join("source.md").is_file()); + + let result_without_sort = execute_local_tree_command(&root_uri, "move", doc_id, None, None) + .expect("move without sort_order"); + assert!(result_without_sort.get("_unsupportedFields").is_none()); + + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn local_markdown_save_refreshes_search_index_after_write() { let root = temp_root("mnote-local-save-refresh-search-index"); diff --git a/rust/crates/mnote-web/src/routes/tree.rs b/rust/crates/mnote-web/src/routes/tree.rs index d2fb2d92..01ba39d8 100644 --- a/rust/crates/mnote-web/src/routes/tree.rs +++ b/rust/crates/mnote-web/src/routes/tree.rs @@ -6,9 +6,10 @@ use crate::routes::command_support::{ execute_runtime_command_via_convex_with_artifacts, read_optional_non_empty, }; use crate::routes::local_folder_source::{ - ensure_local_workspace_access, ensure_local_workspace_read_access, execute_local_tree_command, - load_local_folder_file_tree_snapshot, load_local_folder_page_tree_snapshot, - local_folder_watch_revision, local_workspace_id_from_root_uri, + ensure_local_workspace_access, ensure_local_workspace_read_access, + execute_local_tree_command_with_sort, load_local_folder_file_tree_snapshot, + load_local_folder_page_tree_snapshot, local_folder_watch_revision, + local_workspace_id_from_root_uri, }; use crate::routes::query_support::{ fetch_documents_meta_via_convex, resolve_effective_workspace_id, @@ -6798,12 +6799,13 @@ pub async fn tree_command( })?; ensure_local_workspace_access(&context, root_uri) .map_err(|error| error.with_context(&context))?; - let execution = execute_local_tree_command( + let execution = execute_local_tree_command_with_sort( root_uri, action, &requested_document_id, requested_parent_id.as_deref(), requested_title.as_deref(), + requested_sort_order, ) .map_err(|error| { error diff --git a/rust/crates/mnote-web/src/routes/web_shell.rs b/rust/crates/mnote-web/src/routes/web_shell.rs index 837bc504..529de1ce 100644 --- a/rust/crates/mnote-web/src/routes/web_shell.rs +++ b/rust/crates/mnote-web/src/routes/web_shell.rs @@ -1393,6 +1393,9 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { const paneViewRegistry = new Map(); const mindmapPaneViewRegistry = new Map(); const resourceTabRegistry = new Map(); + const resourceTabMru = []; + const resourceTabMruMax = 20; + const resourceTabCloseGuardAttribute = 'data-resource-tab-close-guarded'; let nextViewId = 1; const externalConflictMessage = '本地 Markdown 文件已在外部更新,请刷新或保存前先处理冲突'; const treeExternalConflictMessage = '当前页面已在其它窗口更新,请刷新或保存前先处理冲突'; @@ -2137,9 +2140,11 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { setSessionStatus(session, 'dirty'); queueSessionSave(session); } + syncResourceSessionTabGuards(session); } catch (error) { session.saving = false; setSessionStatus(session, 'error', error instanceof Error ? error.message : String(error)); + syncResourceSessionTabGuards(session); } }; @@ -2868,6 +2873,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { } } session.dirty = session.currentSerialized !== session.lastPersistedSerialized; + syncResourceSessionTabGuards(session); if (serialized !== previousSerialized) { broadcastSessionContent(session, view); } @@ -3151,7 +3157,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { if (/\.(xls|xlsx|ods|csv)$/i.test(title)) return 'sheet'; return 'word'; } - if (kind === 'pdf') return 'ppt'; + if (kind === 'pdf') return 'pdf'; if (kind === 'markdown' || kind === 'text' || kind === 'code') return 'code'; if (kind === 'image') return 'image'; return 'file'; @@ -3178,13 +3184,67 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { return 'file'; }; + const touchResourceTabMru = (key) => { + const id = String(key || '').trim(); + if (!id) return; + const index = resourceTabMru.indexOf(id); + if (index >= 0) resourceTabMru.splice(index, 1); + resourceTabMru.unshift(id); + if (resourceTabMru.length > resourceTabMruMax) resourceTabMru.length = resourceTabMruMax; + }; + + const removeFromResourceTabMru = (key) => { + const index = resourceTabMru.indexOf(key); + if (index >= 0) resourceTabMru.splice(index, 1); + }; + + const lastActiveResourceTabKey = () => { + for (const key of resourceTabMru) { + if (resourceTabRegistry.has(key)) return key; + } + return ''; + }; + + const resourceTabCloseGuardReason = (session) => { + if (!session) return ''; + const hasUnsavedChanges = session.dirty + || Boolean(session.saveTimer) + || sessionHasRecentLocalInput(session) + || (session.currentSerialized && session.currentSerialized !== session.lastPersistedSerialized); + if (hasUnsavedChanges) return 'dirty'; + if (session.saving) return 'saving'; + if (session.hasExternalConflict) return 'hasExternalConflict'; + return ''; + }; + + const syncResourceTabCloseGuard = (entry) => { + if (!entry?.tab || !(entry.tab instanceof HTMLElement)) return; + const reason = resourceTabCloseGuardReason(entry.session); + if (reason) { + entry.tab.setAttribute(resourceTabCloseGuardAttribute, reason); + entry.tab.classList.add('is-close-guarded'); + } else { + entry.tab.removeAttribute(resourceTabCloseGuardAttribute); + entry.tab.classList.remove('is-close-guarded'); + } + }; + + const syncResourceSessionTabGuards = (session) => { + if (!session || session.sessionKind !== 'resource') return; + resourceTabRegistry.forEach((entry) => { + if (entry.session === session) syncResourceTabCloseGuard(entry); + }); + }; + const activateMainEditorTab = (objectIdentity) => { const nodes = resourceTabHostNodes(); const activeResource = String(objectIdentity || '').trim(); + if (activeResource) touchResourceTabMru(activeResource); if (nodes.pageTab instanceof HTMLElement) { const activePage = !activeResource; nodes.pageTab.classList.toggle('is-active', activePage); nodes.pageTab.setAttribute('aria-selected', activePage ? 'true' : 'false'); + nodes.pageTab.setAttribute('tabindex', activePage ? '0' : '-1'); } if (nodes.pagePanel instanceof HTMLElement) nodes.pagePanel.hidden = Boolean(activeResource); if (nodes.host instanceof HTMLElement) nodes.host.hidden = !activeResource; @@ -3193,8 +3253,10 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { if (entry.tab instanceof HTMLElement) { entry.tab.classList.toggle('is-active', active); entry.tab.setAttribute('aria-selected', active ? 'true' : 'false'); + entry.tab.setAttribute('tabindex', active ? '0' : '-1'); } if (entry.panel instanceof HTMLElement) entry.panel.hidden = !active; + syncResourceTabCloseGuard(entry); }); }; @@ -3213,11 +3275,18 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { const key = String(objectIdentity || '').trim(); const entry = resourceTabRegistry.get(key); if (!entry) return; + const guardReason = resourceTabCloseGuardReason(entry.session); + if (guardReason) { + console.warn(`mnote resource tab 关闭阻止: ${entry.title} (${guardReason})`); + syncResourceTabCloseGuard(entry); + return; + } + removeFromResourceTabMru(key); if (entry.view) unmountEditorViewBinding(entry.view, { releaseSession: true }); if (entry.tab instanceof HTMLElement) entry.tab.remove(); if (entry.panel instanceof HTMLElement) entry.panel.remove(); resourceTabRegistry.delete(key); - activateMainEditorTab(''); + activateMainEditorTab(lastActiveResourceTabKey()); }; const createResourceTabDom = (input) => { @@ -3233,6 +3302,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str { tab.setAttribute('data-mnote-main-tab', objectIdentity); tab.setAttribute('data-mnote-tab-kind', kind); tab.setAttribute('data-mnote-tab-badge-kind', resourceTabBadgeKind(input, kind)); + tab.setAttribute('tabindex', '-1'); tab.innerHTML = '×'; const titleNode = tab.querySelector('.mnote-main-tab-title'); if (titleNode) titleNode.textContent = title; diff --git a/rust/crates/mnote-web/src/ssr/pages/document.rs b/rust/crates/mnote-web/src/ssr/pages/document.rs index 596db567..926aa6e2 100644 --- a/rust/crates/mnote-web/src/ssr/pages/document.rs +++ b/rust/crates/mnote-web/src/ssr/pages/document.rs @@ -306,6 +306,7 @@ pub fn DocumentPage( data-mnote-tab-kind="page" role="tab" aria-selected="true" + tabindex="0" > {title.clone()} diff --git a/rust/crates/mnote-web/src/ssr/styles.rs b/rust/crates/mnote-web/src/ssr/styles.rs index f61875d7..f1f7cfaa 100644 --- a/rust/crates/mnote-web/src/ssr/styles.rs +++ b/rust/crates/mnote-web/src/ssr/styles.rs @@ -2417,6 +2417,15 @@ body { box-shadow: inset 0 1px 0 #E9E9E8, inset 1px 0 0 #E9E9E8, inset -1px 0 0 #E9E9E8; } +.mnote-main-tab.is-close-guarded { + outline: 2px solid #E03E3E; + outline-offset: -2px; +} + +.mnote-main-tab.is-close-guarded .mnote-main-tab-close { + opacity: 0.65; +} + .mnote-main-tab-badge { width: 14px; height: 14px; @@ -2439,6 +2448,14 @@ body { background: #d94841; } +.mnote-main-tab[data-mnote-tab-badge-kind="pdf"] .mnote-main-tab-badge { + background: #e74c3c; +} + +.mnote-main-tab[data-mnote-tab-badge-kind="file"] .mnote-main-tab-badge { + background: #6b7280; +} + .mnote-main-tab[data-mnote-tab-badge-kind="sheet"] .mnote-main-tab-badge { background: #2f9e44; } @@ -4225,6 +4242,9 @@ mod tests { assert!(MNOTE_CSS.contains("[data-mnote-tab-badge-kind=\"ppt\"]")); assert!(MNOTE_CSS.contains("[data-mnote-tab-badge-kind=\"sheet\"]")); assert!(MNOTE_CSS.contains("[data-mnote-tab-badge-kind=\"code\"]")); + assert!(MNOTE_CSS.contains("[data-mnote-tab-badge-kind=\"pdf\"]")); + assert!(MNOTE_CSS.contains("[data-mnote-tab-badge-kind=\"file\"]")); + assert!(MNOTE_CSS.contains("background: #e74c3c")); } #[test] diff --git a/scripts/task457-main-editor-resource-tab-smoke.js b/scripts/task457-main-editor-resource-tab-smoke.js index 17613b06..27e64e1f 100644 --- a/scripts/task457-main-editor-resource-tab-smoke.js +++ b/scripts/task457-main-editor-resource-tab-smoke.js @@ -243,6 +243,34 @@ async function main() { assert(officePopupUrl.searchParams.get("mode") === "edit", "显式 new-window 应保留 edit 模式"); await officePopup.close().catch(() => undefined); + const officeCloseBtn = page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"] .mnote-main-tab-close'); + await officeCloseBtn.click({ timeout: UI_TIMEOUT_MS }); + await page.waitForTimeout(200); + const activeAfterOfficeClose = await page.evaluate(() => { + const activeTab = document.querySelector(".mnote-main-tab.is-active"); + return { + kind: activeTab?.getAttribute("data-mnote-tab-kind") || "", + text: activeTab?.textContent?.trim() || "", + }; + }); + assert.equal(activeAfterOfficeClose.kind, "markdown", `关闭 office tab 后应回到 markdown tab: ${JSON.stringify(activeAfterOfficeClose)}`); + assert(activeAfterOfficeClose.text.includes("resource-note.md"), `markdown tab 标题应包含资源名: ${JSON.stringify(activeAfterOfficeClose)}`); + + const mdCloseBtn = page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"] .mnote-main-tab-close'); + await mdCloseBtn.click({ timeout: UI_TIMEOUT_MS }); + await page.waitForTimeout(200); + const activeAfterAllClosed = await page.evaluate(() => { + const activeTab = document.querySelector(".mnote-main-tab.is-active"); + return { + kind: activeTab?.getAttribute("data-mnote-tab-kind") || "", + resourceTabCount: document.querySelectorAll('.mnote-main-tab[data-mnote-tab-kind]:not([data-mnote-tab-kind="page"])').length, + panelHidden: document.querySelector("[data-mnote-resource-tab-host]")?.hasAttribute("hidden"), + }; + }); + assert.equal(activeAfterAllClosed.kind, "page", `关闭所有 resource tab 后应回到 page tab: ${JSON.stringify(activeAfterAllClosed)}`); + assert.equal(activeAfterAllClosed.resourceTabCount, 0, `resource tab 应全部关闭: ${JSON.stringify(activeAfterAllClosed)}`); + assert.equal(activeAfterAllClosed.panelHidden, true, `resource tab host 应隐藏: ${JSON.stringify(activeAfterAllClosed)}`); + console.log(JSON.stringify({ ok: true, root, assetPath, assetId: asset.id, officeAssetId: officeAsset.id }, null, 2)); } finally { await context.close().catch(() => undefined); diff --git a/scripts/task460-resource-tab-close-dirty-smoke.js b/scripts/task460-resource-tab-close-dirty-smoke.js new file mode 100644 index 00000000..510d7e6a --- /dev/null +++ b/scripts/task460-resource-tab-close-dirty-smoke.js @@ -0,0 +1,220 @@ +#!/usr/bin/env node +"use strict"; + +const assert = require("node:assert"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { chromium } = require("playwright"); + +const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, ""); +const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000); +const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH + || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"] + .find((candidate) => fs.existsSync(candidate)); + +function fileUrl(localPath) { + return `file://${localPath}`; +} + +function localMdDocumentId(relativePath) { + return `local-md:${relativePath.replaceAll("/", "~2F")}`; +} + +function documentUrl(root, relativePath) { + const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`); + url.searchParams.set("sourceKind", "local_folder"); + url.searchParams.set("rootUri", fileUrl(root)); + url.searchParams.set("treeView", "filetree"); + return url.toString(); +} + +function writeWorkspaceManifest(root, ownerId) { + const metadataDir = path.join(root, ".mnote"); + fs.mkdirSync(metadataDir, { recursive: true }); + fs.writeFileSync( + path.join(metadataDir, "workspace.json"), + `${JSON.stringify({ + workspaceId: `local-ws:${ownerId}:task460`, + ownerId, + createdAt: new Date().toISOString(), + capabilities: ["local_files", "markdown_edit", "asset_upload"], + }, null, 2)}\n`, + "utf8", + ); +} + +async function quickLogin(page) { + await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" }); + if (await quickLoginButton.count()) { + await quickLoginButton.click({ timeout: UI_TIMEOUT_MS }); + await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS }); + } +} + +async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) { + return await page.evaluate( + async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => { + const form = new FormData(); + form.append("rootUri", rootUri); + form.append("documentId", documentId); + form.append("kind", kind); + form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType })); + const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form }); + const payload = await response.json().catch(() => null); + if (!response.ok || !payload || payload.ok !== true) { + throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`); + } + return payload.asset; + }, + { rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind }, + ); +} + +async function main() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task460-dirty-close-")); + const relativePath = "README.md"; + const documentId = localMdDocumentId(relativePath); + writeWorkspaceManifest(root, "user_real"); + fs.writeFileSync(path.join(root, relativePath), "# Page\n\n页面正文\n", "utf8"); + + const browser = await chromium.launch({ + headless: true, + executablePath: CHROMIUM_EXECUTABLE_PATH, + }); + const context = await browser.newContext({ + viewport: { width: 1360, height: 900 }, + extraHTTPHeaders: { + "x-mnote-actor-id": "user_real", + "x-mnote-actor-type": "user", + }, + }); + const page = await context.newPage(); + try { + await quickLogin(page); + await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + + // 上传资源文件 + const asset = await uploadLocalAsset( + page, + root, + documentId, + "report-asset.md", + "text/markdown", + Buffer.from("# Report Asset\n\n初始内容\n", "utf8"), + "attachment", + ); + + // 刷新页面确保资源可读取 + await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + + // 打开资源 tab + await page.evaluate(({ asset, documentId }) => { + window.dispatchEvent(new CustomEvent("tree.asset.open", { + detail: { + assetId: asset.id, + documentId, + title: asset.file_name || "report-asset.md", + assetType: asset.asset_type || "attachment", + }, + })); + }, { asset, documentId }); + + // 等待资源 tab 激活和编辑器就绪 + await page.locator('[data-testid="mnote-resource-tab-host"]:not([hidden])').waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + + // 验证 tabindex + const initialTabindex = await page.evaluate(() => { + const pageTab = document.querySelector('[data-mnote-main-tab="page"]'); + const resourceTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]'); + let inactiveResourceTab = null; + return { + pageTabindex: pageTab?.getAttribute('tabindex') || '', + activeTabindex: resourceTab?.getAttribute('tabindex') || '', + pageAriaSelected: pageTab?.getAttribute('aria-selected') || '', + activeAriaSelected: resourceTab?.getAttribute('aria-selected') || '', + }; + }); + assert.equal(initialTabindex.activeTabindex, '0', `激活的 resource tab 应有 tabindex=0: ${JSON.stringify(initialTabindex)}`); + assert.equal(initialTabindex.pageTabindex, '-1', `非激活 page tab 应有 tabindex=-1: ${JSON.stringify(initialTabindex)}`); + assert.equal(initialTabindex.activeAriaSelected, 'true', `激活 tab 应有 aria-selected=true: ${JSON.stringify(initialTabindex)}`); + assert.equal(initialTabindex.pageAriaSelected, 'false', `非激活 tab 应有 aria-selected=false: ${JSON.stringify(initialTabindex)}`); + + // 编辑内容使 dirty + const editor = page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first(); + await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); + await page.evaluate(() => { + const editor = document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]'); + if (!(editor instanceof HTMLElement)) throw new Error("resource_editor_missing"); + editor.focus(); + editor.dispatchEvent(new InputEvent("input", { + bubbles: true, + cancelable: true, + inputType: "insertText", + data: "新添加的未保存内容", + })); + }); + await page.waitForTimeout(100); + + // 尝试关闭 dirty 的 resource tab — 应被阻止 + const closeBtn = page.locator('.mnote-main-tab.is-active .mnote-main-tab-close'); + await closeBtn.click({ timeout: UI_TIMEOUT_MS }); + await page.waitForTimeout(300); + + const blockedState = await page.evaluate(() => { + const activeTab = document.querySelector('.mnote-main-tab.is-active'); + const guardAttr = activeTab?.getAttribute('data-resource-tab-close-guarded') || ''; + const hasGuardClass = activeTab?.classList.contains('is-close-guarded'); + return { + guardAttr, + hasGuardClass, + tabStillPresent: activeTab !== null, + kind: activeTab?.getAttribute('data-mnote-tab-kind') || '', + }; + }); + assert(blockedState.hasGuardClass, `dirty tab 应具有 is-close-guarded class: ${JSON.stringify(blockedState)}`); + assert.equal(blockedState.guardAttr, 'dirty', `close-guard attribute 应为 dirty: ${JSON.stringify(blockedState)}`); + assert.equal(blockedState.kind, 'markdown', `dirty tab 关闭阻止后应仍然激活: ${JSON.stringify(blockedState)}`); + + // 输入后的短保护窗口内再次关闭仍应被阻止,不应静默释放 resource editor。 + await closeBtn.click({ timeout: UI_TIMEOUT_MS }); + await page.waitForTimeout(100); + const afterSecondCloseState = await page.evaluate(() => { + const activeTab = document.querySelector('.mnote-main-tab.is-active'); + return { + kind: activeTab?.getAttribute('data-mnote-tab-kind') || 'none', + resourceTabCount: document.querySelectorAll('.mnote-main-tab[data-mnote-tab-kind]:not([data-mnote-tab-kind="page"])').length, + guardAttr: activeTab?.getAttribute('data-resource-tab-close-guarded') || '', + }; + }); + assert.equal(afterSecondCloseState.kind, 'markdown', `保护窗口内二次关闭后仍应停留在 resource tab: ${JSON.stringify(afterSecondCloseState)}`); + assert.equal(afterSecondCloseState.resourceTabCount, 1, `保护窗口内 resource tab 不应被移除: ${JSON.stringify(afterSecondCloseState)}`); + assert.equal(afterSecondCloseState.guardAttr, 'dirty', `保护窗口内应保留 dirty guard: ${JSON.stringify(afterSecondCloseState)}`); + + console.log(JSON.stringify({ ok: true, root, assetId: asset.id }, null, 2)); + } finally { + await context.close().catch(() => undefined); + await browser.close().catch(() => undefined); + } +} + +main().catch((error) => { + console.error(error && error.stack ? error.stack : error); + process.exit(1); +}); diff --git a/scripts/task461-resource-kind-smoke.js b/scripts/task461-resource-kind-smoke.js new file mode 100644 index 00000000..3db9b4dd --- /dev/null +++ b/scripts/task461-resource-kind-smoke.js @@ -0,0 +1,242 @@ +#!/usr/bin/env node +"use strict"; + +const assert = require("node:assert"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { chromium } = require("playwright"); + +const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, ""); +const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000); +const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH + || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"] + .find((candidate) => fs.existsSync(candidate)); + +function fileUrl(localPath) { + return `file://${localPath}`; +} + +function localMdDocumentId(relativePath) { + return `local-md:${relativePath.replaceAll("/", "~2F")}`; +} + +function documentUrl(root, relativePath) { + const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`); + url.searchParams.set("sourceKind", "local_folder"); + url.searchParams.set("rootUri", fileUrl(root)); + url.searchParams.set("treeView", "filetree"); + return url.toString(); +} + +function writeWorkspaceManifest(root, ownerId) { + const metadataDir = path.join(root, ".mnote"); + fs.mkdirSync(metadataDir, { recursive: true }); + fs.writeFileSync( + path.join(metadataDir, "workspace.json"), + `${JSON.stringify({ + workspaceId: `local-ws:${ownerId}:task461`, + ownerId, + createdAt: new Date().toISOString(), + capabilities: ["local_files", "markdown_edit", "asset_upload"], + }, null, 2)}\n`, + "utf8", + ); +} + +async function quickLogin(page) { + await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" }); + if (await quickLoginButton.count()) { + await quickLoginButton.click({ timeout: UI_TIMEOUT_MS }); + await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS }); + } +} + +async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) { + return await page.evaluate( + async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => { + const form = new FormData(); + form.append("rootUri", rootUri); + form.append("documentId", documentId); + form.append("kind", kind); + form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType })); + const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form }); + const payload = await response.json().catch(() => null); + if (!response.ok || !payload || payload.ok !== true) { + throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`); + } + return payload.asset; + }, + { rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind }, + ); +} + +/** Open a resource tab via `tree.asset.open` event. */ +async function openResourceTab(page, asset, documentId) { + return await page.evaluate(({ asset, documentId }) => { + window.dispatchEvent(new CustomEvent("tree.asset.open", { + detail: { + assetId: asset.id, + documentId, + title: asset.file_name || "resource", + assetType: asset.asset_type || "attachment", + }, + })); + }, { asset, documentId }); +} + +/** Query badge kind for the active tab. */ +async function activeTabBadgeKind(page) { + return await page.evaluate(() => { + const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-main-tab]:not([data-mnote-main-tab="page"])'); + if (!tab) return ""; + const badge = tab.querySelector(".mnote-main-tab-badge"); + return { + badgeKind: tab.getAttribute("data-mnote-tab-badge-kind") || "", + badgeColor: badge ? getComputedStyle(badge).backgroundColor : "", + }; + }); +} + +/** Check active tab's content panel has an iframe/image/editor. */ +async function activeTabContentIsInline(page) { + return await page.evaluate(() => { + const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])'); + if (!panel) return { inline: false, reason: "no_active_panel" }; + // Check for various inline content types + const iframe = panel.querySelector('iframe.mnote-resource-tab-frame'); + if (iframe) return { inline: true, contentType: "iframe", src: iframe.getAttribute("src") || "" }; + const img = panel.querySelector('img.mnote-resource-tab-image'); + if (img) return { inline: true, contentType: "img", src: img.getAttribute("src") || "" }; + const editor = panel.querySelector('.ProseMirror[contenteditable="true"]'); + if (editor) return { inline: true, contentType: "editor" }; + const errorDiv = panel.querySelector('[data-resource-tab-error="true"]'); + if (errorDiv) return { inline: true, contentType: "error_fallback" }; + return { inline: false, reason: "no_content_found" }; + }); +} + +async function main() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task461-resource-kind-")); + const relativePath = "README.md"; + const documentId = localMdDocumentId(relativePath); + writeWorkspaceManifest(root, "user_real"); + fs.writeFileSync(path.join(root, relativePath), "# Page\n\n正文\n", "utf8"); + + const browser = await chromium.launch({ + headless: true, + executablePath: CHROMIUM_EXECUTABLE_PATH, + }); + const context = await browser.newContext({ + viewport: { width: 1360, height: 900 }, + extraHTTPHeaders: { + "x-mnote-actor-id": "user_real", + "x-mnote-actor-type": "user", + }, + }); + const page = await context.newPage(); + + try { + await quickLogin(page); + await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + + // Upload a variety of resource types + const assets = {}; + const resourceTypes = [ + { key: "markdown", fileName: "doc.md", mimeType: "text/markdown", bytes: Buffer.from("# Doc\n", "utf8"), expectKind: "markdown" }, + { key: "txt", fileName: "notes.txt", mimeType: "text/plain", bytes: Buffer.from("text content\n", "utf8"), expectKind: "text" }, + { key: "json", fileName: "data.json", mimeType: "application/json", bytes: Buffer.from('{"key":"value"}', "utf8"), expectKind: "code" }, + { key: "ts_code", fileName: "script.ts", mimeType: "text/typescript", bytes: Buffer.from("const x = 1;\n", "utf8"), expectKind: "code" }, + { key: "image", fileName: "photo.png", mimeType: "image/png", bytes: Buffer.from("fake-png-data", "utf8"), expectKind: "image" }, + ]; + + for (const rt of resourceTypes) { + const asset = await uploadLocalAsset(page, root, documentId, rt.fileName, rt.mimeType, rt.bytes, "attachment"); + assets[rt.key] = { ...asset, expectKind: rt.expectKind }; + } + + // Reload to pick up assets + await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + + // ======== Test: resource kind badge matrix ======== + for (const [key, asset] of Object.entries(assets)) { + console.log(`Test: ${key} (${asset.file_name}) → expect kind=${asset.expectKind}`); + + await openResourceTab(page, asset, documentId); + await page.waitForTimeout(500); + + const badge = await activeTabBadgeKind(page); + assert.ok(badge.badgeKind, `${key}: active tab should have badge kind, got ${JSON.stringify(badge)}`); + console.log(` badgeKind: ${badge.badgeKind}, color: ${badge.badgeColor}`); + + // Check content is inline (not a new window) + const contentInfo = await activeTabContentIsInline(page); + assert.ok(contentInfo.inline, `${key}: content should render inline, got ${JSON.stringify(contentInfo)}`); + console.log(` content: ${contentInfo.contentType} ${contentInfo.src || ""}`); + } + + // ======== Test: PDF badge ======== + console.log("Test: PDF badge should be independent (not 'ppt')"); + const pdfAsset = await uploadLocalAsset( + page, root, documentId, + "manual.pdf", "application/pdf", + Buffer.from("%PDF-1.4 fake pdf\n", "utf8"), + "attachment", + ); + // Reload again + await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); + await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({ + state: "visible", + timeout: UI_TIMEOUT_MS, + }); + + await openResourceTab(page, pdfAsset, documentId); + await page.waitForTimeout(500); + const pdfBadge = await activeTabBadgeKind(page); + console.log(` PDF badge: ${JSON.stringify(pdfBadge)}`); + assert.equal(pdfBadge.badgeKind, "pdf", `PDF tab should have badgeKind "pdf", got "${pdfBadge.badgeKind}"`); + assert.ok(pdfBadge.badgeColor, "PDF badge should have a color"); + + // ======== Test: Unknown file fallback shouldn't break page tab ======== + console.log("Test: unknown file fallback should not break page tab"); + const pageTabActive = await page.evaluate(() => { + const pageTab = document.querySelector('[data-mnote-main-tab="page"]'); + return pageTab?.classList.contains("is-active") || false; + }); + // Should be false since we just opened a PDF + console.log(` page tab active after PDF open: ${pageTabActive}`); + + // Close the PDF tab + await page.evaluate(() => { + const pdfTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-main-tab]:not([data-mnote-main-tab="page"])'); + const closeBtn = pdfTab?.querySelector('.mnote-main-tab-close'); + if (closeBtn instanceof HTMLElement) closeBtn.click(); + }); + await page.waitForTimeout(300); + + const pageTabActiveAfter = await page.evaluate(() => { + const pageTab = document.querySelector('[data-mnote-main-tab="page"]'); + return pageTab?.classList.contains("is-active") || false; + }); + assert.ok(pageTabActiveAfter, "after closing resource tab, page tab should be active"); + + console.log(JSON.stringify({ ok: true, root }, null, 2)); + } finally { + await context.close().catch(() => undefined); + await browser.close().catch(() => undefined); + } +} + +main().catch((error) => { + console.error(error && error.stack ? error.stack : error); + process.exit(1); +});