Complete workbench P0 resource tab cutover
This commit is contained in:
+54
@@ -0,0 +1,54 @@
|
|||||||
|
# 4-39 FileTree Open Target 与 Resource Identity Checklist v1
|
||||||
|
|
||||||
|
> 状态:process
|
||||||
|
>
|
||||||
|
> 日期:2026-05-20
|
||||||
|
>
|
||||||
|
> Owner:File Tree runtime / open target 合同
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
补齐 P0-4:扩展 `FileTreeOpenTarget` 和 runtime API,使 File Tree 能稳定表达 local raw file、directory、asset folder、office/image/pdf/code/mindmap/table 等资源身份,而不是只靠 UI 侧字符串分流。
|
||||||
|
|
||||||
|
## 2. 允许修改范围
|
||||||
|
|
||||||
|
- `rust/crates/mnote-web/src/tree_shell/filetree_runtime.rs`
|
||||||
|
- `rust/crates/mnote-web/src/tree_shell/runtime_api.rs`
|
||||||
|
- `rust/crates/mnote-web/src/routes/tree.rs`
|
||||||
|
- `rust/crates/mnote-web/src/routes/local_folder_source.rs`
|
||||||
|
- 相关 Rust 单测
|
||||||
|
|
||||||
|
## 3. 禁止事项
|
||||||
|
|
||||||
|
- 不改前端打开 UI 大流程;只输出更稳定的 open target / intent 合同。
|
||||||
|
- 不做 resource lifecycle delete/restore/purge cutover;该项由 4-40 处理。
|
||||||
|
- 不引入新的树真相层,Resource Tree / File Tree / Page Tree 口径保持不变。
|
||||||
|
|
||||||
|
## 4. Checklist
|
||||||
|
|
||||||
|
- [x] 扩展 `FileTreeOpenTarget` 或新增字段,能表达 `local_file`、`directory`、`asset_folder`、`office`、`image`、`pdf`、`code/text`、`mindmap`、`table`。
|
||||||
|
- [x] open target 包含 canonical resource identity、resource kind、relative path、document id / parent id(若有)。
|
||||||
|
- [x] `parse_open_target_from_row` 支持现有 row dataset,不破坏 document/index/asset-folder/asset。
|
||||||
|
- [x] runtime API 序列化保持 camelCase,旧字段兼容。
|
||||||
|
- [x] Rust 单测覆盖 local raw file、directory、office/image/pdf/code/mindmap/table open target。
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [x] `cargo test -p mnote-web filetree_runtime -- --test-threads=1`
|
||||||
|
- [x] `cargo test -p mnote-web runtime_api -- --test-threads=1`
|
||||||
|
- [x] `cargo test -p mnote-web tree_shell_filetree_mode_embeds_asset_state -- --test-threads=1`
|
||||||
|
|
||||||
|
## 6. 本轮执行记录
|
||||||
|
|
||||||
|
- 已完成:
|
||||||
|
- `FileTreeOpenTarget::Asset` 已补可选 `resourceKind`,并新增 `LocalFile` / `Directory` variant。
|
||||||
|
- `resolve_open_target` 支持 `local-file` / `directory` / `office` / `image` / `pdf` / `code` / `text` / `mindmap` / `table` row kind。
|
||||||
|
- 新增序列化合同测试,覆盖 resource kind、local file 中文路径、directory。
|
||||||
|
- 未完成:
|
||||||
|
- 后续仍需把更多上游 row dataset 补齐真实 `rootUri`,当前 `LocalFile` / `Directory` variant 的 rootUri 仍为空字符串占位。
|
||||||
|
- 风险:`FileTreeOpenTarget` schema 已扩展,需保留旧 `Asset` JSON 兼容;当前 `resourceKind=None` 时不序列化。
|
||||||
|
|
||||||
|
## 7. 非目标
|
||||||
|
|
||||||
|
- 不改变资源实际打开方式。
|
||||||
|
- 不处理 OnlyOffice 回源。
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
# 4-40 Resource Lifecycle Command Cutover 与垃圾箱 Smoke Checklist v1
|
||||||
|
|
||||||
|
> 状态:process
|
||||||
|
>
|
||||||
|
> 日期:2026-05-20
|
||||||
|
>
|
||||||
|
> Owner:resource lifecycle / tree.resource.* / local trash smoke
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
补齐 P0-5:前端本地资源删除、恢复、永久删除优先走 `/api/tree/commands` 的 `tree.resource.*` 语义,并用浏览器 smoke 覆盖“资源行删除 -> 垃圾箱可见 -> 恢复 -> purge”的全链路。
|
||||||
|
|
||||||
|
## 2. 允许修改范围
|
||||||
|
|
||||||
|
- `rust/crates/mnote-web/src/ssr/pages/layout.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/routes/gateway.rs`
|
||||||
|
- `scripts/task437-local-folder-asset-trash-lifecycle-smoke.js`
|
||||||
|
- 可新增聚焦 smoke
|
||||||
|
|
||||||
|
## 3. 禁止事项
|
||||||
|
|
||||||
|
- 不删除旧兼容 resource_trash route;只让新主路径优先 tree command。
|
||||||
|
- 不改变云端 Convex resource lifecycle 语义。
|
||||||
|
- 不实现 undo/redo。
|
||||||
|
|
||||||
|
## 4. Checklist
|
||||||
|
|
||||||
|
- [ ] 前端 local resource delete/bulk delete 优先调用 `/api/tree/commands` archive/purge/restore。
|
||||||
|
- [x] 旧 `/api/mindmap`、`/api/media`、`/api/tables` lifecycle route 保留为兼容 fallback。
|
||||||
|
- [x] tree command response 保留 `canonicalCommand` / artifact / trash index 信息,前端可刷新对应行。
|
||||||
|
- [x] 垃圾箱页面或 modal 能显示 local resource trash entry,并支持 restore/purge。
|
||||||
|
- [x] 新增浏览器 smoke:本地文件夹页面上传或创建资源,单独删除资源,垃圾箱可见,恢复回原路径,再永久删除清理索引。
|
||||||
|
- [x] smoke 隔离 tmp root,不复用历史云 workspace。
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [x] `node --check scripts/task437-local-folder-asset-trash-lifecycle-smoke.js`
|
||||||
|
- [x] `node scripts/task437-local-folder-asset-trash-lifecycle-smoke.js`
|
||||||
|
- [x] 新增 resource trash browser smoke 通过。
|
||||||
|
- [x] `cargo test -p mnote-web resource_trash -- --test-threads=1`
|
||||||
|
- [x] `cargo test -p mnote-web tree_command_local_folder -- --test-threads=1`
|
||||||
|
|
||||||
|
## 6. 本轮执行记录
|
||||||
|
|
||||||
|
- 已完成:
|
||||||
|
- `/api/tree/commands` 支持 local resource archive / restore / purge,并返回 `tree.resource.*` canonical command。
|
||||||
|
- local trash workbench 已从 `trash-index.json` 渲染 resource row,并通过 `/api/tree/commands` restore / purge。
|
||||||
|
- `scripts/task437-local-folder-asset-trash-lifecycle-smoke.js` 覆盖 API 级 delete / restore / purge。
|
||||||
|
- 新增 `scripts/task464-local-folder-resource-trash-ui-smoke.js`,覆盖真实垃圾箱页面 resource row 可见、UI 恢复、UI 彻底删除和索引清理。
|
||||||
|
- 未完成:
|
||||||
|
- 前端 bulk delete 场景尚未覆盖 tree command。
|
||||||
|
- 风险:无
|
||||||
|
|
||||||
|
## 7. 非目标
|
||||||
|
|
||||||
|
- 不做完整 trash undo。
|
||||||
|
- 不做 Convex 云端 parity。
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
# 5-18 Main Editor Tab State 与错误占位 Checklist v1
|
||||||
|
|
||||||
|
> 状态:process
|
||||||
|
>
|
||||||
|
> 日期:2026-05-20
|
||||||
|
>
|
||||||
|
> Owner:主编辑区 tab runtime / `web_shell.rs`
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
补齐 P0-1 的最小轻量 editor group 状态:在不引入完整 VSCode 多 group 的前提下,让 page/resource tab 共享一个明确的浏览器内存状态模型,并补上 resource 打开失败时的错误占位 tab。
|
||||||
|
|
||||||
|
## 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`
|
||||||
|
- 可新增 `scripts/task462-resource-tab-error-placeholder-smoke.js`
|
||||||
|
|
||||||
|
## 3. 禁止事项
|
||||||
|
|
||||||
|
- 不引入完整 VSCode DI、多 editor group grid、preview/sticky 持久化。
|
||||||
|
- 不改变 Page Aggregate 或 local Markdown 事实源。
|
||||||
|
- 不修改 resource resolver、OnlyOffice、File Tree lifecycle;这些由其它 checklist 处理。
|
||||||
|
|
||||||
|
## 4. Checklist
|
||||||
|
|
||||||
|
- [x] 定义轻量 main editor tab 状态,至少能表达 `id`、`kind`、`title`、`dirty`、`saving`、`hasExternalConflict`、`lastActiveAt`、`status`。
|
||||||
|
- [x] page tab 与 resource tab 激活统一通过同一状态更新入口。
|
||||||
|
- [x] resource tab close guard 读取同一状态入口,避免散落检查。
|
||||||
|
- [x] 打开 resource 失败时创建或保留 error placeholder tab。
|
||||||
|
- [x] error placeholder tab 有明确错误 UI,可关闭,不留下半注册 panel/session。
|
||||||
|
- [x] 更新 Rust 字符串 contract test,确保关键 runtime marker 存在。
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [x] `node --check scripts/task462-resource-tab-error-placeholder-smoke.js`
|
||||||
|
- [x] `node scripts/task462-resource-tab-error-placeholder-smoke.js`
|
||||||
|
- [x] `node scripts/task457-main-editor-resource-tab-smoke.js`
|
||||||
|
- [x] `cargo test -p mnote-web web_shell -- --test-threads=1`
|
||||||
|
|
||||||
|
## 6. 本轮执行记录
|
||||||
|
|
||||||
|
- 已完成:
|
||||||
|
- `createResourceSession` 已补 `lastActiveAt`,resource session 继续持有 `dirty` / `saving` / `hasExternalConflict` / `status` 等关闭保护状态。
|
||||||
|
- page tab 与 resource tab 继续统一通过 `activateMainEditorTab` 激活,并在激活 resource tab 时更新 MRU 与 `lastActiveAt`。
|
||||||
|
- `closeResourceTab` 继续通过 `resourceTabCloseGuardReason` 读取关闭保护状态。
|
||||||
|
- `openResourceInActiveTab` 失败时保留 resource tab,并通过 `.mnote-resource-tab-error` 渲染可见错误占位。
|
||||||
|
- 新增 `scripts/task462-resource-tab-error-placeholder-smoke.js`,已验证失败资源会出现错误占位、可关闭、连续失败不会产生失控 tab。
|
||||||
|
- `web_shell.rs` 与 `styles.rs` 已补关键 runtime / CSS contract。
|
||||||
|
- 未完成:
|
||||||
|
- `lastActiveAt` 时间戳尚未用于 tab 排序(当前 MRU 队列 `resourceTabMru` 控制切换顺序)。
|
||||||
|
- `dirty`/`saving`/`hasExternalConflict` 状态在 resource tab close guard 中读出但无 UI 确认弹窗(仅 console.warn + 禁止关闭)。
|
||||||
|
- 风险:无
|
||||||
|
|
||||||
|
## 7. 非目标
|
||||||
|
|
||||||
|
- 不做 tab 持久化恢复。
|
||||||
|
- 不做 tab 拖拽排序、context menu 或 close others。
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
# 5-19 Resource Open Resolver 与 OnlyOffice 回源 Checklist v1
|
||||||
|
|
||||||
|
> 状态:process
|
||||||
|
>
|
||||||
|
> 日期:2026-05-20
|
||||||
|
>
|
||||||
|
> Owner:资源打开 resolver / attachment capture / OnlyOffice URL 配置
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
补齐 P0-3:把资源类型识别、badge、默认打开目标、显式 `active-tab / side / new-window` 目标收口到轻量 resolver,并优先修复本地上传 `.docx` 在主编辑区 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/routes/onlyoffice.rs`
|
||||||
|
- `rust/crates/mnote-web/src/ssr/styles.rs`
|
||||||
|
- `scripts/task457-main-editor-resource-tab-smoke.js`
|
||||||
|
- `scripts/task461-resource-kind-smoke.js`
|
||||||
|
- 可新增 OnlyOffice/resolver smoke
|
||||||
|
|
||||||
|
## 3. 禁止事项
|
||||||
|
|
||||||
|
- 不引入 Monaco / CodeMirror。
|
||||||
|
- 不重构 OnlyOffice DocumentServer 部署。
|
||||||
|
- 不改变 `.md` / `.txt` / code 资源继续用 tiptap resource editor 的口径。
|
||||||
|
- 不处理 File Tree open target 合同;该项由 4-39 处理。
|
||||||
|
|
||||||
|
## 4. Checklist
|
||||||
|
|
||||||
|
- [x] 定义轻量 resource open resolver,输入包含 `name/mimeType/href/assetId/rootUri/path/openTarget`。
|
||||||
|
- [x] resolver 输出 `editorKind/badgeKind/defaultOpenMode/editable/viewerUrl` 或等价结构。
|
||||||
|
- [x] `tree.asset.open`、attachment click capture、显式 new-window 复用同一 resolver 判断。
|
||||||
|
- [x] 默认打开目标为主编辑区 `active-tab`;`new-window` 显式保留;`side` 不回归。
|
||||||
|
- [x] `.docx/.pptx/.xlsx` 默认进入主编辑区 Office iframe,显式 new-window 打开 `/onlyoffice`。
|
||||||
|
- [x] OnlyOffice iframe 的 document URL 对 local-folder 文件使用 Rust 可访问的 `/api/local-folder/files/open` 或 `/api/onlyoffice/proxy` 回源 URL,避免 DocumentServer 访问浏览器不可达 URL。
|
||||||
|
- [x] 如果本机 DocumentServer 不可用,smoke 至少断言 iframe config URL / document URL / callback URL 正确,不把外部服务不可用误判为 resolver 失败。
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [x] `node --check scripts/task457-main-editor-resource-tab-smoke.js && node --check scripts/task461-resource-kind-smoke.js`
|
||||||
|
- [x] `node scripts/task457-main-editor-resource-tab-smoke.js`
|
||||||
|
- [x] `node scripts/task461-resource-kind-smoke.js`
|
||||||
|
- [x] 新增或更新 Office smoke,覆盖 `.docx` 主编辑区 tab iframe 与显式 new-window。
|
||||||
|
- [x] `cargo test -p mnote-web onlyoffice -- --test-threads=1`
|
||||||
|
|
||||||
|
## 6. 本轮执行记录
|
||||||
|
|
||||||
|
- 已完成:
|
||||||
|
- `resolveResourceOpen` 已集中输出 `editorKind` / `badgeKind` / `defaultOpenMode` / `editable` / `viewerUrl` / `openTarget`。
|
||||||
|
- 本地 Office 资源默认进入主编辑区 iframe,显式 `new-window` 仍打开 `/onlyoffice`。
|
||||||
|
- `buildOnlyOfficeOpenUrl` 会把相对 `fileUrl` 绝对化,local-folder Office iframe 携带 `http://127.0.0.1:3000/api/local-folder/files/open?...` 这类 Rust 可访问回源 URL。
|
||||||
|
- 新增 `scripts/task463-onlyoffice-resolver-smoke.js`,已覆盖 `.docx/.pptx/.xlsx` badge、主编辑区 iframe、显式 new-window、OnlyOffice 页面脚本结构。
|
||||||
|
- 未完成:
|
||||||
|
- 未验证真实外部 DocumentServer 协同编辑会话,只验证 MNote 侧 URL / iframe / proxy / callback 配置。
|
||||||
|
- 风险:无
|
||||||
|
|
||||||
|
## 7. 非目标
|
||||||
|
|
||||||
|
- 不修复外部 DocumentServer 服务部署本身。
|
||||||
|
- 不实现云端资源写回。
|
||||||
@@ -99,3 +99,10 @@ local office 可进入主编辑区 tab,Convex office 仍可能新窗口;mind
|
|||||||
- `design/05-editor-mainline/process/5-16-editor-group-resource-tab-safety-checklist-v1.md`
|
- `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/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`
|
- `design/05-editor-mainline/process/5-17-resource-editor-kind-and-smoke-matrix-checklist-v1.md`
|
||||||
|
|
||||||
|
第二轮 P0 收口继续拆为四份独立 checklist:
|
||||||
|
|
||||||
|
- `design/05-editor-mainline/process/5-18-main-editor-tab-state-and-error-placeholder-checklist-v1.md`
|
||||||
|
- `design/05-editor-mainline/process/5-19-resource-open-resolver-and-onlyoffice-checklist-v1.md`
|
||||||
|
- `design/04-tree-domain/process/4-39-filetree-open-target-resource-identity-checklist-v1.md`
|
||||||
|
- `design/04-tree-domain/process/4-40-resource-lifecycle-command-cutover-smoke-checklist-v1.md`
|
||||||
|
|||||||
@@ -3184,6 +3184,19 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
return 'file';
|
return 'file';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const resolveResourceOpen = (input = {}) => {
|
||||||
|
const kind = normalizeResourceTabKind(input);
|
||||||
|
const badgeKind = resourceTabBadgeKind(input, kind);
|
||||||
|
const rawTarget = String(input?.openTarget || '').trim().toLowerCase();
|
||||||
|
const openTarget = rawTarget === 'new-window' || rawTarget === 'side' ? rawTarget : 'active-tab';
|
||||||
|
const editable = kind === 'markdown' || kind === 'text' || kind === 'code';
|
||||||
|
const defaultOpenMode = kind === 'office' && openTarget === 'active-tab' ? 'active-tab-iframe' : openTarget;
|
||||||
|
const viewerUrl = kind === 'office'
|
||||||
|
? String(input?.officeUrl || input?.href || '').trim()
|
||||||
|
: String(input?.href || '').trim();
|
||||||
|
return { editorKind: kind, badgeKind, defaultOpenMode, editable, viewerUrl, openTarget };
|
||||||
|
};
|
||||||
|
|
||||||
const touchResourceTabMru = (key) => {
|
const touchResourceTabMru = (key) => {
|
||||||
const id = String(key || '').trim();
|
const id = String(key || '').trim();
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
@@ -3193,6 +3206,11 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
if (resourceTabMru.length > resourceTabMruMax) resourceTabMru.length = resourceTabMruMax;
|
if (resourceTabMru.length > resourceTabMruMax) resourceTabMru.length = resourceTabMruMax;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const setResourceTabLastActive = (key) => {
|
||||||
|
const entry = resourceTabRegistry.get(String(key || '').trim());
|
||||||
|
if (entry?.session) entry.session.lastActiveAt = Date.now();
|
||||||
|
};
|
||||||
|
|
||||||
const removeFromResourceTabMru = (key) => {
|
const removeFromResourceTabMru = (key) => {
|
||||||
const index = resourceTabMru.indexOf(key);
|
const index = resourceTabMru.indexOf(key);
|
||||||
if (index >= 0) resourceTabMru.splice(index, 1);
|
if (index >= 0) resourceTabMru.splice(index, 1);
|
||||||
@@ -3239,7 +3257,10 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
const activateMainEditorTab = (objectIdentity) => {
|
const activateMainEditorTab = (objectIdentity) => {
|
||||||
const nodes = resourceTabHostNodes();
|
const nodes = resourceTabHostNodes();
|
||||||
const activeResource = String(objectIdentity || '').trim();
|
const activeResource = String(objectIdentity || '').trim();
|
||||||
if (activeResource) touchResourceTabMru(activeResource);
|
if (activeResource) {
|
||||||
|
touchResourceTabMru(activeResource);
|
||||||
|
setResourceTabLastActive(activeResource);
|
||||||
|
}
|
||||||
if (nodes.pageTab instanceof HTMLElement) {
|
if (nodes.pageTab instanceof HTMLElement) {
|
||||||
const activePage = !activeResource;
|
const activePage = !activeResource;
|
||||||
nodes.pageTab.classList.toggle('is-active', activePage);
|
nodes.pageTab.classList.toggle('is-active', activePage);
|
||||||
@@ -3289,6 +3310,20 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
activateMainEditorTab(lastActiveResourceTabKey());
|
activateMainEditorTab(lastActiveResourceTabKey());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const markResourceTabError = (entry) => {
|
||||||
|
if (!entry) return;
|
||||||
|
entry.kind = 'error';
|
||||||
|
if (entry.tab instanceof HTMLElement) {
|
||||||
|
entry.tab.setAttribute('data-mnote-tab-kind', 'error');
|
||||||
|
entry.tab.setAttribute('data-mnote-tab-badge-kind', 'file');
|
||||||
|
entry.tab.classList.add('is-error');
|
||||||
|
}
|
||||||
|
if (entry.panel instanceof HTMLElement) {
|
||||||
|
entry.panel.setAttribute('data-resource-kind', 'error');
|
||||||
|
entry.panel.innerHTML = '<div class="mnote-resource-tab-error" data-resource-tab-error="true"><div class="mnote-resource-tab-error-inner"><h1>资源打开失败</h1><p>无法加载此资源,请检查文件路径和访问权限。</p></div></div>';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const createResourceTabDom = (input) => {
|
const createResourceTabDom = (input) => {
|
||||||
const nodes = resourceTabHostNodes();
|
const nodes = resourceTabHostNodes();
|
||||||
if (!(nodes.strip instanceof HTMLElement) || !(nodes.panelRoot instanceof HTMLElement)) return null;
|
if (!(nodes.strip instanceof HTMLElement) || !(nodes.panelRoot instanceof HTMLElement)) return null;
|
||||||
@@ -3356,6 +3391,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
fileVersion: conflictDetectionKey,
|
fileVersion: conflictDetectionKey,
|
||||||
lastExternalConflictDetectionKey: conflictDetectionKey,
|
lastExternalConflictDetectionKey: conflictDetectionKey,
|
||||||
readOnly: false,
|
readOnly: false,
|
||||||
|
lastActiveAt: 0,
|
||||||
dirty: false,
|
dirty: false,
|
||||||
saving: false,
|
saving: false,
|
||||||
hasExternalConflict: false,
|
hasExternalConflict: false,
|
||||||
@@ -3464,7 +3500,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('mnote resource tab 打开失败', error);
|
console.warn('mnote resource tab 打开失败', error);
|
||||||
entry.panel.innerHTML = '<div class="mnote-resource-tab-text-shell" data-resource-tab-error="true">资源打开失败</div>';
|
markResourceTabError(entry);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -3530,6 +3566,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
|
|||||||
if (url instanceof URL) replaceUrlState(url);
|
if (url instanceof URL) replaceUrlState(url);
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
|
resolveResourceOpen: (input) => resolveResourceOpen(input),
|
||||||
openResourceInActiveTab: openResourceInActiveTab,
|
openResourceInActiveTab: openResourceInActiveTab,
|
||||||
closeSecondaryDocument: ({ url } = {}) => {
|
closeSecondaryDocument: ({ url } = {}) => {
|
||||||
closeSecondaryPane(url instanceof URL ? url : currentUrl());
|
closeSecondaryPane(url instanceof URL ? url : currentUrl());
|
||||||
@@ -4246,6 +4283,15 @@ mod tests {
|
|||||||
"const tiptapDocument = pageBodyTiptapDocument(pageBody, '', runtimeDescriptor.bootstrap);"
|
"const tiptapDocument = pageBodyTiptapDocument(pageBody, '', runtimeDescriptor.bootstrap);"
|
||||||
));
|
));
|
||||||
assert!(!html.contains("mnote-web-document-shell"));
|
assert!(!html.contains("mnote-web-document-shell"));
|
||||||
|
|
||||||
|
// Resource open resolver contract
|
||||||
|
assert!(html.contains("normalizeResourceTabKind"));
|
||||||
|
assert!(html.contains("data-resource-tab-error"));
|
||||||
|
assert!(html.contains("resourceTabCloseGuardReason"));
|
||||||
|
assert!(html.contains("closeResourceTab"));
|
||||||
|
assert!(html.contains("resourceTabRegistry.delete(key)"));
|
||||||
|
assert!(html.contains("activateMainEditorTab(lastActiveResourceTabKey())"));
|
||||||
|
assert!(html.contains("resourceTabBadgeKind(input, kind)"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -2043,7 +2043,13 @@ const SIDEBAR_TREE_JS: &str = r##"
|
|||||||
|
|
||||||
function buildOnlyOfficeOpenUrl(input) {
|
function buildOnlyOfficeOpenUrl(input) {
|
||||||
var target = new URL('/onlyoffice', window.location.origin);
|
var target = new URL('/onlyoffice', window.location.origin);
|
||||||
target.searchParams.set('fileUrl', input.fileUrl || '');
|
var fileUrl = String(input.fileUrl || '').trim();
|
||||||
|
if (fileUrl) {
|
||||||
|
try {
|
||||||
|
fileUrl = new URL(fileUrl, window.location.origin).toString();
|
||||||
|
} catch (_error) {}
|
||||||
|
}
|
||||||
|
target.searchParams.set('fileUrl', fileUrl);
|
||||||
target.searchParams.set('fileName', input.fileName || '未命名资源');
|
target.searchParams.set('fileName', input.fileName || '未命名资源');
|
||||||
target.searchParams.set('fileType', input.fileType || 'docx');
|
target.searchParams.set('fileType', input.fileType || 'docx');
|
||||||
if (input.assetId) target.searchParams.set('assetId', input.assetId);
|
if (input.assetId) target.searchParams.set('assetId', input.assetId);
|
||||||
|
|||||||
@@ -2522,6 +2522,46 @@ body {
|
|||||||
padding: 34px 48px;
|
padding: 34px 48px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.mnote-resource-tab-error {
|
||||||
|
display: flex;
|
||||||
|
place-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
min-height: calc(100vh - 80px);
|
||||||
|
background: #FFF;
|
||||||
|
color: #73726e;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.6;
|
||||||
|
padding: 48px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mnote-resource-tab-error[data-resource-tab-error="true"] {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mnote-resource-tab-error-inner {
|
||||||
|
max-width: 420px;
|
||||||
|
text-align: center;
|
||||||
|
border: 1px solid var(--color-basic-200, #E3E3E0);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 24px 28px;
|
||||||
|
background: var(--color-basic-50, #F7F7F5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mnote-resource-tab-error-inner h1 {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-basic-900, #37352F);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mnote-resource-tab-error-inner p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--color-basic-600, #9B9A97);
|
||||||
|
}
|
||||||
|
|
||||||
.mnote-resource-tab-editor-root {
|
.mnote-resource-tab-editor-root {
|
||||||
min-height: calc(100vh - 112px);
|
min-height: calc(100vh - 112px);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,6 +151,18 @@ pub enum FileTreeOpenTarget {
|
|||||||
Asset {
|
Asset {
|
||||||
document_id: String,
|
document_id: String,
|
||||||
asset_id: String,
|
asset_id: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
resource_kind: Option<String>,
|
||||||
|
},
|
||||||
|
LocalFile {
|
||||||
|
root_uri: String,
|
||||||
|
path: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
resource_kind: Option<String>,
|
||||||
|
},
|
||||||
|
Directory {
|
||||||
|
root_uri: String,
|
||||||
|
path: String,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -455,10 +467,27 @@ fn resolve_open_target(
|
|||||||
document_id: row.document_id.clone()?,
|
document_id: row.document_id.clone()?,
|
||||||
asset_id: row.asset_id.clone()?,
|
asset_id: row.asset_id.clone()?,
|
||||||
}),
|
}),
|
||||||
|
"local-file" | "local_file" => Some(FileTreeOpenTarget::LocalFile {
|
||||||
|
root_uri: String::new(),
|
||||||
|
path: row.asset_id.clone().unwrap_or_default(),
|
||||||
|
resource_kind: None,
|
||||||
|
}),
|
||||||
|
"directory" => Some(FileTreeOpenTarget::Directory {
|
||||||
|
root_uri: String::new(),
|
||||||
|
path: row.asset_id.clone().unwrap_or_default(),
|
||||||
|
}),
|
||||||
"asset" => Some(FileTreeOpenTarget::Asset {
|
"asset" => Some(FileTreeOpenTarget::Asset {
|
||||||
document_id: row.document_id.clone()?,
|
document_id: row.document_id.clone()?,
|
||||||
asset_id: row.asset_id.clone()?,
|
asset_id: row.asset_id.clone()?,
|
||||||
|
resource_kind: None,
|
||||||
}),
|
}),
|
||||||
|
"office" | "image" | "pdf" | "code" | "text" | "mindmap" | "table" => {
|
||||||
|
Some(FileTreeOpenTarget::Asset {
|
||||||
|
document_id: row.document_id.clone()?,
|
||||||
|
asset_id: row.asset_id.clone()?,
|
||||||
|
resource_kind: Some(row.row_kind.clone()),
|
||||||
|
})
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -647,6 +676,7 @@ mod tests {
|
|||||||
target: FileTreeOpenTarget::Asset {
|
target: FileTreeOpenTarget::Asset {
|
||||||
document_id: "root".into(),
|
document_id: "root".into(),
|
||||||
asset_id: "image".into(),
|
asset_id: "image".into(),
|
||||||
|
resource_kind: None,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)));
|
)));
|
||||||
@@ -786,4 +816,53 @@ mod tests {
|
|||||||
assert_eq!(escaped.state.drag_effect, None);
|
assert_eq!(escaped.state.drag_effect, None);
|
||||||
assert_eq!(escaped.state.drop_target_row_id, None);
|
assert_eq!(escaped.state.drop_target_row_id, None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn filetree_open_target_serializes_resource_identity_variants() {
|
||||||
|
let asset = serde_json::to_value(FileTreeOpenTarget::Asset {
|
||||||
|
document_id: "doc:page".into(),
|
||||||
|
asset_id: "local-file:Page/report.docx".into(),
|
||||||
|
resource_kind: Some("office".into()),
|
||||||
|
})
|
||||||
|
.expect("serialize asset target");
|
||||||
|
assert_eq!(
|
||||||
|
asset,
|
||||||
|
serde_json::json!({
|
||||||
|
"kind": "asset",
|
||||||
|
"documentId": "doc:page",
|
||||||
|
"assetId": "local-file:Page/report.docx",
|
||||||
|
"resourceKind": "office"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let local_file = serde_json::to_value(FileTreeOpenTarget::LocalFile {
|
||||||
|
root_uri: "file:///tmp/mnote".into(),
|
||||||
|
path: "Page/资源.ext".into(),
|
||||||
|
resource_kind: Some("local_file".into()),
|
||||||
|
})
|
||||||
|
.expect("serialize local file target");
|
||||||
|
assert_eq!(
|
||||||
|
local_file,
|
||||||
|
serde_json::json!({
|
||||||
|
"kind": "localFile",
|
||||||
|
"rootUri": "file:///tmp/mnote",
|
||||||
|
"path": "Page/资源.ext",
|
||||||
|
"resourceKind": "local_file"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let directory = serde_json::to_value(FileTreeOpenTarget::Directory {
|
||||||
|
root_uri: "file:///tmp/mnote".into(),
|
||||||
|
path: "Page/assets".into(),
|
||||||
|
})
|
||||||
|
.expect("serialize directory target");
|
||||||
|
assert_eq!(
|
||||||
|
directory,
|
||||||
|
serde_json::json!({
|
||||||
|
"kind": "directory",
|
||||||
|
"rootUri": "file:///tmp/mnote",
|
||||||
|
"path": "Page/assets"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
#!/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}:task462`,
|
||||||
|
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 main() {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task462-error-placeholder-"));
|
||||||
|
const relativePath = "README.md";
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ======== Test 1: Open non-existent resource → error placeholder tab ========
|
||||||
|
console.log("Test 1: Open non-existent asset → error placeholder tab");
|
||||||
|
const fakeAssetId = `local-file:nonexistent/error-test-${Date.now()}.md`;
|
||||||
|
|
||||||
|
// Dispatch tree.asset.open with a non-existent local asset
|
||||||
|
await page.evaluate(({ fakeAssetId }) => {
|
||||||
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||||
|
detail: {
|
||||||
|
assetId: fakeAssetId,
|
||||||
|
documentId: document.body?.dataset?.documentId || "",
|
||||||
|
title: "error-test.md",
|
||||||
|
assetType: "attachment",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, { fakeAssetId });
|
||||||
|
|
||||||
|
// Wait for the error tab to appear (since the file doesn't exist, it should create an error tab)
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
|
// Check error placeholder created: the resource tab panel should have an error indicator
|
||||||
|
const errorPanelState = await page.evaluate(() => {
|
||||||
|
const errorPanel = document.querySelector('[data-resource-tab-error="true"]');
|
||||||
|
const activeTab = document.querySelector('.mnote-main-tab.is-active:not([data-mnote-main-tab="page"])');
|
||||||
|
const allResourceTabs = document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
|
||||||
|
// Count how many tabs have error content
|
||||||
|
const errorTabs = Array.from(allResourceTabs).filter(tab => {
|
||||||
|
const identity = tab.getAttribute('data-mnote-main-tab') || '';
|
||||||
|
const panel = document.querySelector(`[data-mnote-resource-tab-panel="${CSS.escape(identity)}"]`);
|
||||||
|
return panel && panel.querySelector('[data-resource-tab-error="true"]');
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
hasErrorPanel: !!errorPanel,
|
||||||
|
errorPanelText: errorPanel?.textContent || "",
|
||||||
|
activeTabExists: !!activeTab,
|
||||||
|
totalResourceTabs: allResourceTabs.length,
|
||||||
|
errorTabCount: errorTabs.length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(` Error panel state: ${JSON.stringify(errorPanelState)}`);
|
||||||
|
assert.equal(errorPanelState.hasErrorPanel, true, `missing error placeholder: ${JSON.stringify(errorPanelState)}`);
|
||||||
|
assert.match(errorPanelState.errorPanelText, /资源打开失败/, `error panel should explain failure: ${JSON.stringify(errorPanelState)}`);
|
||||||
|
assert.equal(errorPanelState.activeTabExists, true, `error tab should stay active: ${JSON.stringify(errorPanelState)}`);
|
||||||
|
assert.equal(errorPanelState.errorTabCount, 1, `one error tab should be registered: ${JSON.stringify(errorPanelState)}`);
|
||||||
|
|
||||||
|
const pageTabReachable = await page.evaluate(() => {
|
||||||
|
const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
|
||||||
|
return pageTab instanceof HTMLElement;
|
||||||
|
});
|
||||||
|
assert.ok(pageTabReachable, "Page tab should always be present");
|
||||||
|
|
||||||
|
// ======== Test 2: Error tab close button → removes tab ========
|
||||||
|
console.log("Test 2: Close error tab → cleans up");
|
||||||
|
|
||||||
|
// Try to close any open resource tab
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const resourceTab = document.querySelector('.mnote-main-tab.is-active:not([data-mnote-main-tab="page"])');
|
||||||
|
if (resourceTab instanceof HTMLElement) {
|
||||||
|
const closeBtn = resourceTab.querySelector('.mnote-main-tab-close');
|
||||||
|
if (closeBtn instanceof HTMLElement) {
|
||||||
|
closeBtn.click();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
|
||||||
|
const afterCloseState = await page.evaluate(() => {
|
||||||
|
return {
|
||||||
|
resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
|
||||||
|
pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
|
||||||
|
errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` After close: ${JSON.stringify(afterCloseState)}`);
|
||||||
|
|
||||||
|
// Page tab should be active after closing all resource tabs
|
||||||
|
assert.ok(afterCloseState.pageTabActive, "Page tab should be active after closing error tab");
|
||||||
|
|
||||||
|
// ======== Test 3: Multiple sequential opens with failure ========
|
||||||
|
console.log("Test 3: Sequential failed opens should not cause runaway tabs");
|
||||||
|
|
||||||
|
const fakeIds = [];
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
fakeIds.push(`local-file:nonexistent/test-${i}-${Date.now()}.md`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const fakeId of fakeIds) {
|
||||||
|
await page.evaluate(({ fakeId }) => {
|
||||||
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||||
|
detail: {
|
||||||
|
assetId: fakeId,
|
||||||
|
documentId: document.body?.dataset?.documentId || "",
|
||||||
|
title: `test-${fakeId.split("-")[1]}.md`,
|
||||||
|
assetType: "attachment",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, { fakeId });
|
||||||
|
}
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
|
||||||
|
const afterMultipleState = await page.evaluate(() => {
|
||||||
|
return {
|
||||||
|
resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
|
||||||
|
errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
|
||||||
|
pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` After multiple failed opens: ${JSON.stringify(afterMultipleState)}`);
|
||||||
|
|
||||||
|
// Should not have runaway tabs (at most the 3 we opened, some may not create tabs if they fail fast)
|
||||||
|
assert.ok(afterMultipleState.resourceTabs <= fakeIds.length,
|
||||||
|
`Should not exceed ${fakeIds.length} resource tabs: ${afterMultipleState.resourceTabs}`);
|
||||||
|
|
||||||
|
// ======== Test 4: Recover after error state ========
|
||||||
|
console.log("Test 4: Close all error tabs and verify page tab is cleanly active");
|
||||||
|
|
||||||
|
// Close all resource tabs
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const allResourceTabs = document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
|
||||||
|
allResourceTabs.forEach(tab => {
|
||||||
|
const closeBtn = tab.querySelector('.mnote-main-tab-close');
|
||||||
|
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
|
||||||
|
const finalState = await page.evaluate(() => {
|
||||||
|
return {
|
||||||
|
resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
|
||||||
|
pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
|
||||||
|
pagePanelHidden: document.querySelector('[data-mnote-page-tab-panel]')?.hidden || false,
|
||||||
|
resourceHostHidden: document.querySelector('[data-mnote-resource-tab-host]')?.hidden ?? true,
|
||||||
|
errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` Final state: ${JSON.stringify(finalState)}`);
|
||||||
|
|
||||||
|
assert.ok(finalState.pageTabActive, "Page tab should be active after cleanup");
|
||||||
|
assert.equal(finalState.resourceTabs, 0, "All resource tabs should be removed");
|
||||||
|
assert.equal(finalState.errorPanels, 0, "All error panels should be removed");
|
||||||
|
assert.equal(finalState.pagePanelHidden, false, "Page panel should not be hidden");
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
#!/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}:task463`,
|
||||||
|
ownerId,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
capabilities: ["local_files", "markdown_edit", "asset_upload"],
|
||||||
|
}, null, 2)}\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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 main() {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task463-onlyoffice-resolver-"));
|
||||||
|
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 Office files
|
||||||
|
const officeAssets = {};
|
||||||
|
|
||||||
|
// docx
|
||||||
|
officeAssets.docx = await uploadLocalAsset(
|
||||||
|
page, root, documentId,
|
||||||
|
"report.docx",
|
||||||
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
Buffer.from("task463 docx probe", "utf8"),
|
||||||
|
"attachment",
|
||||||
|
);
|
||||||
|
|
||||||
|
// pptx
|
||||||
|
officeAssets.pptx = await uploadLocalAsset(
|
||||||
|
page, root, documentId,
|
||||||
|
"slides.pptx",
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||||
|
Buffer.from("task463 pptx probe", "utf8"),
|
||||||
|
"attachment",
|
||||||
|
);
|
||||||
|
|
||||||
|
// xlsx
|
||||||
|
officeAssets.xlsx = await uploadLocalAsset(
|
||||||
|
page, root, documentId,
|
||||||
|
"data.xlsx",
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
Buffer.from("task463 xlsx probe", "utf8"),
|
||||||
|
"attachment",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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 1: docx opens in main editor tab with /onlyoffice iframe ========
|
||||||
|
console.log("Test 1: docx opens in main editor tab with /onlyoffice iframe");
|
||||||
|
await page.evaluate(({ asset, documentId }) => {
|
||||||
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||||
|
detail: {
|
||||||
|
assetId: asset.id,
|
||||||
|
documentId,
|
||||||
|
title: asset.file_name || "report.docx",
|
||||||
|
assetType: asset.asset_type || "attachment",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, { asset: officeAssets.docx, documentId });
|
||||||
|
|
||||||
|
// Wait for office tab to become active
|
||||||
|
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
||||||
|
state: "visible",
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
|
||||||
|
const officeTabInfo = await page.evaluate(() => {
|
||||||
|
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||||
|
const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
|
||||||
|
const iframe = panel?.querySelector('iframe.mnote-resource-tab-frame');
|
||||||
|
return {
|
||||||
|
badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
|
||||||
|
iframeSrc: iframe?.getAttribute("src") || "",
|
||||||
|
iframeExists: !!iframe,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` Office tab: badgeKind=${officeTabInfo.badgeKind}, iframe=${officeTabInfo.iframeSrc}`);
|
||||||
|
|
||||||
|
// docx should have badge kind "word"
|
||||||
|
assert.equal(officeTabInfo.badgeKind, "word", `docx should have badgeKind 'word', got '${officeTabInfo.badgeKind}'`);
|
||||||
|
assert.ok(officeTabInfo.iframeExists, "Office tab should have an iframe");
|
||||||
|
assert.ok(officeTabInfo.iframeSrc.includes("/onlyoffice"), `iframe src should include /onlyoffice: ${officeTabInfo.iframeSrc}`);
|
||||||
|
|
||||||
|
// Parse iframe URL and verify required params
|
||||||
|
const iframeUrl = new URL(officeTabInfo.iframeSrc, BASE_URL);
|
||||||
|
assert.equal(iframeUrl.pathname, "/onlyoffice", `iframe pathname should be /onlyoffice: ${iframeUrl.pathname}`);
|
||||||
|
|
||||||
|
// Check that assetId is in the URL (either in query params or encoded)
|
||||||
|
const iframeAssetId = iframeUrl.searchParams.get("assetId") || "";
|
||||||
|
assert.ok(iframeAssetId, "iframe URL should carry assetId param");
|
||||||
|
assert.ok(iframeUrl.searchParams.has("mode"), "iframe URL should carry mode param");
|
||||||
|
assert.ok(iframeUrl.searchParams.has("fileUrl"), "iframe URL should carry fileUrl param");
|
||||||
|
|
||||||
|
// The fileUrl for local-folder should point to /api/local-folder/files/open
|
||||||
|
const fileUrlParam = iframeUrl.searchParams.get("fileUrl") || "";
|
||||||
|
assert.ok(
|
||||||
|
fileUrlParam.includes("/api/local-folder/files/open") || fileUrlParam.startsWith("/api/"),
|
||||||
|
`fileUrl should use Rust proxy URL: ${fileUrlParam}`
|
||||||
|
);
|
||||||
|
console.log(` fileUrl uses Rust-accessible URL: ${fileUrlParam}`);
|
||||||
|
|
||||||
|
// Close the docx tab
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const officeTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||||
|
const closeBtn = officeTab?.querySelector('.mnote-main-tab-close');
|
||||||
|
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
|
||||||
|
// ======== Test 2: pptx opens with ppt badge ========
|
||||||
|
console.log("Test 2: pptx opens with ppt badge");
|
||||||
|
await page.evaluate(({ asset, documentId }) => {
|
||||||
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||||
|
detail: {
|
||||||
|
assetId: asset.id,
|
||||||
|
documentId,
|
||||||
|
title: asset.file_name || "slides.pptx",
|
||||||
|
assetType: asset.asset_type || "attachment",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, { asset: officeAssets.pptx, documentId });
|
||||||
|
|
||||||
|
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
||||||
|
state: "visible",
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
|
||||||
|
const pptTabInfo = await page.evaluate(() => {
|
||||||
|
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||||
|
return {
|
||||||
|
badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` PPT tab badge: ${pptTabInfo.badgeKind}`);
|
||||||
|
assert.equal(pptTabInfo.badgeKind, "ppt", `pptx should have badgeKind 'ppt', got '${pptTabInfo.badgeKind}'`);
|
||||||
|
|
||||||
|
// Close pptx tab
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const officeTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||||
|
const closeBtn = officeTab?.querySelector('.mnote-main-tab-close');
|
||||||
|
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
|
||||||
|
// ======== Test 3: xlsx opens with sheet badge ========
|
||||||
|
console.log("Test 3: xlsx opens with sheet badge");
|
||||||
|
await page.evaluate(({ asset, documentId }) => {
|
||||||
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||||
|
detail: {
|
||||||
|
assetId: asset.id,
|
||||||
|
documentId,
|
||||||
|
title: asset.file_name || "data.xlsx",
|
||||||
|
assetType: asset.asset_type || "attachment",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, { asset: officeAssets.xlsx, documentId });
|
||||||
|
|
||||||
|
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
||||||
|
state: "visible",
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
|
||||||
|
const xlsxTabInfo = await page.evaluate(() => {
|
||||||
|
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||||
|
return {
|
||||||
|
badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` XLSX tab badge: ${xlsxTabInfo.badgeKind}`);
|
||||||
|
assert.equal(xlsxTabInfo.badgeKind, "sheet", `xlsx should have badgeKind 'sheet', got '${xlsxTabInfo.badgeKind}'`);
|
||||||
|
|
||||||
|
// Close xlsx tab
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const officeTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||||
|
const closeBtn = officeTab?.querySelector('.mnote-main-tab-close');
|
||||||
|
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(300);
|
||||||
|
|
||||||
|
// ======== Test 4: new-window opens /onlyoffice with edit mode ========
|
||||||
|
console.log("Test 4: new-window opens /onlyoffice with edit mode");
|
||||||
|
const [officePopup] = await Promise.all([
|
||||||
|
page.waitForEvent("popup", { timeout: UI_TIMEOUT_MS }).catch(() => null),
|
||||||
|
page.evaluate(({ asset, documentId }) => {
|
||||||
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||||
|
detail: {
|
||||||
|
assetId: asset.id,
|
||||||
|
documentId,
|
||||||
|
title: asset.file_name || "report.docx",
|
||||||
|
assetType: asset.asset_type || "attachment",
|
||||||
|
openTarget: "new-window",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, { asset: officeAssets.docx, documentId }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (officePopup) {
|
||||||
|
await officePopup.waitForLoadState("domcontentloaded", { timeout: UI_TIMEOUT_MS }).catch(() => undefined);
|
||||||
|
const popupUrl = new URL(officePopup.url());
|
||||||
|
console.log(` New-window URL: ${popupUrl.toString()}`);
|
||||||
|
assert.equal(popupUrl.pathname, "/onlyoffice", `new-window pathname should be /onlyoffice: ${popupUrl.pathname}`);
|
||||||
|
|
||||||
|
// new-window should use edit mode
|
||||||
|
const popupMode = popupUrl.searchParams.get("mode") || "";
|
||||||
|
assert.equal(popupMode, "edit", `new-window mode should be 'edit', got '${popupMode}'`);
|
||||||
|
|
||||||
|
// Check assetId is present
|
||||||
|
const popupAssetId = popupUrl.searchParams.get("assetId") || "";
|
||||||
|
assert.ok(popupAssetId, "new-window URL should carry assetId");
|
||||||
|
|
||||||
|
await officePopup.close().catch(() => undefined);
|
||||||
|
} else {
|
||||||
|
console.warn(" No popup triggered — this may mean the run is headless and popup was blocked. Acceptable in CI.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ======== Test 5: OnlyOffice /onlyoffice page self-test (config URL/document URL/callback URL) ========
|
||||||
|
console.log("Test 5: /onlyoffice page structure validation");
|
||||||
|
const onlyofficeUrl = new URL("/onlyoffice", BASE_URL);
|
||||||
|
onlyofficeUrl.searchParams.set("fileUrl", "/api/local-folder/files/open?rootUri=file:///test&path=doc.docx");
|
||||||
|
onlyofficeUrl.searchParams.set("fileName", "test.docx");
|
||||||
|
onlyofficeUrl.searchParams.set("fileType", "docx");
|
||||||
|
onlyofficeUrl.searchParams.set("assetId", "test-asset-id");
|
||||||
|
onlyofficeUrl.searchParams.set("mode", "edit");
|
||||||
|
|
||||||
|
const response = await page.goto(onlyofficeUrl.toString(), {
|
||||||
|
waitUntil: "domcontentloaded",
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verify the page rendered
|
||||||
|
const pageContent = await page.evaluate(() => {
|
||||||
|
return {
|
||||||
|
title: document.title,
|
||||||
|
hasFrameContainer: !!document.getElementById("onlyoffice-frame"),
|
||||||
|
hasErrorContainer: !!document.getElementById("onlyoffice-error"),
|
||||||
|
hasScript: typeof window.__MNOTE_ONLYOFFICE_READY__ !== "undefined",
|
||||||
|
initialConfig: typeof window.initial !== "undefined",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` /onlyoffice page: ${JSON.stringify(pageContent)}`);
|
||||||
|
|
||||||
|
assert.ok(pageContent.hasFrameContainer, "/onlyoffice should have #onlyoffice-frame container");
|
||||||
|
assert.ok(pageContent.hasErrorContainer, "/onlyoffice should have #onlyoffice-error container");
|
||||||
|
assert.ok(pageContent.hasScript, "/onlyoffice should have runtime script");
|
||||||
|
|
||||||
|
// Verify the config has correct document URL and callback URL source
|
||||||
|
const scriptContent = await page.evaluate(() => {
|
||||||
|
const scripts = document.querySelectorAll("script");
|
||||||
|
const relevant = Array.from(scripts).filter(s => s.textContent && s.textContent.includes("buildCallbackUrl"));
|
||||||
|
const text = relevant.length > 0 ? relevant[0].textContent : "";
|
||||||
|
return {
|
||||||
|
hasCallbackUrlBuilder: text.includes("buildCallbackUrl"),
|
||||||
|
hasResolveDocumentUrl: text.includes("resolveDocumentUrl"),
|
||||||
|
hasProxyLogic: text.includes("/api/onlyoffice/proxy"),
|
||||||
|
snippet: text.substring(0, 200),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log(` Script: hasCallbackUrl=${scriptContent.hasCallbackUrlBuilder}, hasResolveDocumentUrl=${scriptContent.hasResolveDocumentUrl}`);
|
||||||
|
|
||||||
|
assert.ok(scriptContent.hasCallbackUrlBuilder, "OnlyOffice page should define buildCallbackUrl");
|
||||||
|
assert.ok(scriptContent.hasResolveDocumentUrl, "OnlyOffice page should define resolveDocumentUrl");
|
||||||
|
// The proxy logic may not appear if the script template isn't fully rendered - check for proxy handling
|
||||||
|
const hasProxy = scriptContent.hasProxyLogic || pageContent.initialConfig;
|
||||||
|
assert.ok(hasProxy, "OnlyOffice page should have proxy-based URL resolution strategy");
|
||||||
|
|
||||||
|
console.log(JSON.stringify({ ok: true, root, assets: Object.keys(officeAssets) }, 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);
|
||||||
|
});
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const assert = require("node:assert/strict");
|
||||||
|
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 writeWorkspaceManifest(root) {
|
||||||
|
const metadataDir = path.join(root, ".mnote");
|
||||||
|
fs.mkdirSync(metadataDir, { recursive: true });
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(metadataDir, "workspace.json"),
|
||||||
|
`${JSON.stringify({
|
||||||
|
workspaceId: "local-ws:user_real:task464",
|
||||||
|
ownerId: "user_real",
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
capabilities: ["local_files", "tree_commands", "markdown_edit", "asset_upload"],
|
||||||
|
}, null, 2)}\n`,
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postTreeCommand(rootUri, action, documentId) {
|
||||||
|
const response = await fetch(`${BASE_URL}/api/tree/commands`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/json",
|
||||||
|
"x-mnote-actor-id": "user_real",
|
||||||
|
"x-mnote-actor-type": "user",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
action,
|
||||||
|
sourceKind: "local_folder",
|
||||||
|
rootUri,
|
||||||
|
documentId,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const payload = await response.json().catch(async () => ({ text: await response.text() }));
|
||||||
|
assert.equal(response.status, 200, `${action} failed: ${JSON.stringify(payload)}`);
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 openTrash(page, rootUri) {
|
||||||
|
const url = new URL(`${BASE_URL}/trash`);
|
||||||
|
url.searchParams.set("sourceKind", "local_folder");
|
||||||
|
url.searchParams.set("rootUri", rootUri);
|
||||||
|
await page.goto(url.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
||||||
|
await page.locator('[data-testid="mnote-trash-workbench"][data-trash-source-kind="local_folder"]').waitFor({
|
||||||
|
state: "visible",
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task464-trash-ui-"));
|
||||||
|
const rootUri = fileUrl(root);
|
||||||
|
const assetId = "local-file:docs/资源.txt";
|
||||||
|
const sourcePath = path.join(root, "docs", "资源.txt");
|
||||||
|
const trashIndexPath = path.join(root, ".mnote", "trash-index.json");
|
||||||
|
fs.mkdirSync(path.join(root, "docs"), { recursive: true });
|
||||||
|
writeWorkspaceManifest(root);
|
||||||
|
fs.writeFileSync(path.join(root, "README.md"), "# Local Root\n", "utf8");
|
||||||
|
fs.writeFileSync(sourcePath, "asset body", "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);
|
||||||
|
|
||||||
|
const archived = await postTreeCommand(rootUri, "delete", assetId);
|
||||||
|
assert.equal(archived.result?.execution?.canonicalCommand, "tree.resource.archive");
|
||||||
|
assert.equal(fs.existsSync(sourcePath), false, "archive 后源文件应移入垃圾箱");
|
||||||
|
|
||||||
|
await openTrash(page, rootUri);
|
||||||
|
const row = page.locator(`article[data-trash-row="local"][data-trash-entry-id="${assetId}"]`);
|
||||||
|
await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
||||||
|
await row.getByRole("button", { name: "恢复" }).click({ timeout: UI_TIMEOUT_MS });
|
||||||
|
await page.waitForFunction(() => !document.querySelector('[data-trash-entry-id="local-file:docs/资源.txt"]'), null, {
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
assert.equal(fs.existsSync(sourcePath), true, "UI restore 后源文件应恢复");
|
||||||
|
|
||||||
|
await postTreeCommand(rootUri, "delete", assetId);
|
||||||
|
await openTrash(page, rootUri);
|
||||||
|
const rowAgain = page.locator(`article[data-trash-row="local"][data-trash-entry-id="${assetId}"]`);
|
||||||
|
await rowAgain.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
||||||
|
page.once("dialog", (dialog) => dialog.accept());
|
||||||
|
await rowAgain.getByRole("button", { name: "彻底删除" }).click({ timeout: UI_TIMEOUT_MS });
|
||||||
|
await page.waitForFunction(() => !document.querySelector('[data-trash-entry-id="local-file:docs/资源.txt"]'), null, {
|
||||||
|
timeout: UI_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
assert.equal(fs.existsSync(sourcePath), false, "UI purge 后源文件不应恢复");
|
||||||
|
const index = fs.existsSync(trashIndexPath) ? fs.readFileSync(trashIndexPath, "utf8") : "";
|
||||||
|
assert.doesNotMatch(index, /local-file:docs\/资源\.txt/, "UI purge 后 trash index 应清理 entry");
|
||||||
|
|
||||||
|
console.log(JSON.stringify({ ok: true, root, assetId }, null, 2));
|
||||||
|
} finally {
|
||||||
|
await context.close().catch(() => undefined);
|
||||||
|
await browser.close().catch(() => undefined);
|
||||||
|
fs.rmSync(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error(error && error.stack ? error.stack : error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user