diff --git a/Agent.md b/Agent.md index 4aabfcfb9..f9c33a29e 100644 --- a/Agent.md +++ b/Agent.md @@ -60,7 +60,7 @@ What EMRG does today — capabilities, not a changelog. Foreground daemon: `python -m emrg`. - Python: `uv run pytest tests/ -v` — re-count with `uv run --no-sync python3 scripts/check-doc-count.py --measure`. Import check: `uv run python -c "from emrg.client.app import run_client"` -GUI: `cd emrg/gui && npm test` (280: 107 daemon_client + 22 conn-manager + 7 integration + 7 nav-policy + 11 gui-state + 10 build-config + 10 config_fields + 16 boot-contract + 3 preload-api + 2 theme-guard + 2 image-hash + 8 switch-session + 19 atp_login + 4 gui-op-log + 9 theme-setting + 5 window-title + 4 frame-route + 11 browser-policy + 5 browser-wiring + 13 settings_store + 5 preview-annotation-wiring) — syntax: `node --check main.js preload.js daemon_client.js` +GUI: `cd emrg/gui && npm test` (282: 107 daemon_client + 22 conn-manager + 7 integration + 7 nav-policy + 11 gui-state + 10 build-config + 10 config_fields + 16 boot-contract + 3 preload-api + 2 theme-guard + 2 image-hash + 8 switch-session + 19 atp_login + 4 gui-op-log + 9 theme-setting + 5 window-title + 4 frame-route + 12 browser-policy + 5 browser-wiring + 13 settings_store + 6 annotation-wiring) — syntax: `node --check main.js preload.js daemon_client.js` Renderer: `cd emrg/gui/renderer && npm run typecheck && npm test` (1283: 5 snapshot-store + 13 utils + 3 ErrorBoundary + 2 App + 12 commands + 4 copywriting + 14 i18n + 33 markdown + 22 selection + 41 transcript + 11 conversationType + 4 MarkdownText + 65 TranscriptView + 22 history + 30 historyReplay + 8 userImages + 43 composer + 97 Composer + 14 sidebar + 32 workspaceView + 18 WorkspaceView + 10 dialog + 6 Dialog + 9 ConfirmDialog + 9 RenameDialog + 13 dialogLists + 3 HelpDialog + 9 MemoryDialog + 8 SkillsDialog + 8 openSession + 6 WelcomeDialog + 20 OpenSessionDialog + 14 NewSessionDialog + 7 rewind + 8 RewindDialog + 7 GithubDeviceDialog + 82 daemonBridge + 13 DaemonBridgeProvider + 69 Shell + 19 page + 51 EditorPanel + 25 DialogHost + 48 SettingsPanel + 18 TaskFormDialog + 5 RantDialog + 8 vendorMarkdown + 10 highlightTheme + 8 ApprovalDialog + 20 SandboxRootsDialog + 42 cockpit + 4 editorSelectionCascade + 9 fileTree + 24 FileTree + 5 contextMenu + 1 residue + 24 StatusBand + 24 UsageRanking + 9 usageRanking + 6 SearchOverlay + 5 ResizeHandle + 8 IconRail + 6 SessionColumn + 5 EmrgMark + 38 editorDoc + 27 CodeEditor + 26 annotation + 14 AnnotationMode) - CI: pytest on ubuntu **and windows-2025**, the GUI suites, and an actionlint gate over `.github/workflows/`; re-trigger a dropped push with `scripts/re-trigger-ci.sh `, never an empty commit - Merge gates, run before merging — `uv run --no-sync python3 scripts/check-vote-count.py` · `scripts/check-pr-base.py` · `scripts/check-merge-freshness.py` · `scripts/check-merge-order.py` · `scripts/check-merge-landing-diff.py` · `scripts/check-merge-pairs.py` / `scripts/check-merge-sequence.py` · `scripts/check-merge-tree-health.py` (the merged tree passes one guard) · `scripts/check-merge-plan-suite.py` — all under `uv run --no-sync python3` diff --git a/emrg/gui/preview-preload.js b/emrg/gui/annotation-preload.js similarity index 88% rename from emrg/gui/preview-preload.js rename to emrg/gui/annotation-preload.js index 7d5ac27bf..cc5f290c3 100644 --- a/emrg/gui/preview-preload.js +++ b/emrg/gui/annotation-preload.js @@ -1,13 +1,23 @@ "use strict"; /** - * preview-preload.js — annotate the HTML preview (host 2026-12-03T18:38:18). + * annotation-preload.js — annotate a local page in the editor's browser mode (host 2026-12-03T20:55). * - * The preview is its own WebContentsView, composited by the main process *above* the app's own + * Browser mode is a `WebContentsView`, composited by the main process *above* the app's own * window. That is why the app's floating panel cannot hang over it: a DOM layer in the renderer - * sits under whatever the main process adds with `addChildView`. So the panel for a previewed page - * has to be drawn inside the page, and this file is where that happens. + * sits under whatever the main process adds with `addChildView`. So the panel for a page has to + * be drawn inside the page, and this file is where that happens. * - * Two properties make that safe, and both are why nothing else lives here. + * A network page gets none of it. Electron cannot swap a preload on navigation, so this one is + * mounted for every address the view loads and asks the address first: unless the document is a + * local `file:` page it returns before building a panel or installing a listener. What a remote + * page therefore never has is an annotation interface. What it cannot have at all is a way to + * make an annotation travel — that gate is in the **main process**, which takes a batch only + * from this view's own webContents, only while the address it recorded is a `file:` one, and + * which computes the file from that address instead of believing one a page reports. The two + * scheme tests are therefore not two carriers of one rule: this one decides whether to draw, + * the main process decides what leaves. + * + * Two properties make drawing safe, and both are why nothing else lives here. * * **No `contextBridge`.** The page gets no function, no object, no `window.emrg`. This file runs in * a preload's own world with DOM access, draws its interface behind a closed shadow root, and is @@ -252,7 +262,7 @@ function main() { .filter((i) => i.body.trim().length > 0) .map((i) => ({ paragraph: i.paragraph, body: i.body.trim(), selector: i.selector })); if (payload.length === 0) return; - ipcRenderer.send("emrg:previewAnnotate", { items: payload }); + ipcRenderer.send("emrg:pageAnnotate", { items: payload }); items.length = 0; render(); ui.host.remove(); @@ -340,7 +350,13 @@ function main() { }); } -if (document.readyState === "loading") { +// The address is asked before anything is built, and a page that is not a local file gets +// nothing: no panel, no listener, no message. `location.protocol` is read here rather than a +// helper being required because a sandboxed preload has no `require` for local files — which is +// also why this check decides only whether to *draw*, and the main process decides what leaves. +if (location.protocol !== "file:") { + // A network page. Draw nothing. +} else if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", main, { once: true }); } else { main(); diff --git a/emrg/gui/browser-policy.js b/emrg/gui/browser-policy.js index 2de42c339..c32154a0d 100644 --- a/emrg/gui/browser-policy.js +++ b/emrg/gui/browser-policy.js @@ -7,8 +7,9 @@ * `window.emrg` bridge — and this browser, which exists to do the opposite: draw a remote * page inside the app. Two things keep the second from being a hole in the first: * - * - it is a **different** `WebContentsView`, built with `sandbox: true`, - * `contextIsolation: true` and no preload, so nothing it loads can reach the bridge; + * - it is a **different** `WebContentsView`, built with `sandbox: true` and + * `contextIsolation: true`, and the one preload it carries mounts nothing in a network page + * (`annotationAllowed`), so nothing it loads can reach the bridge; * - every policy below is installed on the browser's **own partition**, never on the * default session. `setPermissionRequestHandler`, `will-download`, * `setCertificateVerifyProc` and `clearStorageData` hang off a `Session`, so a handler @@ -52,6 +53,21 @@ function schemeOf(url) { } } +/** + * Whether the annotation layer belongs in the page at this address: only a local `file:` page. + * + * The layer draws a floating panel inside the page — the app's own window is composited *under* + * a `WebContentsView`, so inside the document is the only place a panel can hang over a page. + * That is a favour to the host reading a page they are editing, and it stops at `file:`. A + * network page is somebody else's code: no interface of ours is drawn into it, and — because + * `annotation-preload.js` asks this first and returns before installing anything — no listener + * is left in it either. Electron cannot swap a preload on navigation, so this predicate, asked + * in the document, is the boundary rather than a property of the view. + */ +function annotationAllowed(url) { + return typeof url === "string" && /^file:/i.test(url); +} + /** Whether a page may go to this URL at all. */ function navAllowed(url) { if (typeof url !== "string" || url.length === 0) return false; @@ -302,6 +318,7 @@ module.exports = { BROWSER_PARTITION, NAV_SCHEMES, addressTarget, + annotationAllowed, blocksMainFrameNavigation, browserNavPolicy, browserRect, diff --git a/emrg/gui/main.js b/emrg/gui/main.js index 6b0d70aa5..b160f0036 100644 --- a/emrg/gui/main.js +++ b/emrg/gui/main.js @@ -37,6 +37,7 @@ const { pageStillCurrent, permissionGranted, saveDialogOptions, + annotationAllowed, } = require("./browser-policy"); const { frameSessionId } = require("./frame-route"); const { makeConfigPrivate } = require("./config_mode"); @@ -146,15 +147,8 @@ function main() { } } - // P2.3(rant 12:20:35):HTML 预览 WebContentsView——懒创建、单实例复用、右对齐 bounds 同步。 - // renderer 崩溃 reload 后由 renderer 侧拉取(emrg:getPreviewState)恢复(main 是真相源)。 - let previewView = null; // WebContentsView 实例(首次打开 HTML tab 才创建) - let previewAdded = false; // 已 addChildView(防重复添加) - let previewPath = null; // 当前加载的预览文件绝对路径(null = 无) - let previewVisible = false; // 当前是否显示(激活 HTML tab) - let previewLayout = { width: 280, collapsed: false, contentTop: 0 }; // renderer 上报的面板布局 - // 内嵌浏览器:与预览视图各自一个 view。它有自己的分区(cookie/登录态独立、跨重启保留), - // 切换 tab 只隐藏、不销毁,所以切回来页面还在原处(要求 2)。 + // 内嵌浏览器:编辑器里 .html tab 的页面就是这个视图。它有自己的分区(cookie/登录态独立、 + // 跨重启保留),切换 tab 只隐藏、不销毁,所以切回来页面还在原处(要求 2)。 let browserView = null; let browserAdded = false; let browserVisible = false; @@ -196,16 +190,13 @@ function main() { }); win.loadFile(path.join(__dirname, "renderer", "dist", "index.html")); // P2.3:窗口尺寸变化 → 预览 bounds 跟随(右对齐矩形) - win.on("resize", () => { updatePreviewBounds(); updateBrowserBounds(); }); + win.on("resize", () => updateBrowserBounds()); // G87:窗口状态持久化 restoreWindowBounds(win); win.on("close", () => saveWindowBounds(win)); // G101:renderer 崩溃恢复 win.webContents.on("render-process-gone", () => { logger.warn("[gui] renderer gone — reloading"); - // P2.3:预览 view 是独立 WebContents,崩溃不影响它;reload 完成后 renderer - // 经 emrg:getPreviewState 拉取当前预览路径重新开 Tab(恢复 bounds/loadURL 一致, - // 防预览与 Tab 栏不匹配,R5-④) win.loadFile(path.join(__dirname, "renderer", "dist", "index.html")); }); win.webContents.on("unresponsive", () => { @@ -1099,9 +1090,6 @@ vision = false }; }); - // ── P2.3 + P3.4(rant 12:20:35):HTML 预览 WebContentsView ────────── - // 混合模型:非 HTML 走 renderer DOM 查看器;.html/.htm 走内嵌浏览器预览。 - // 懒创建(R7-⑤)+ 单实例复用(一次只显示一个预览,切换 = 重新加载 R7-⑥)。 // Rant 2026-11-20T18:01:52: the editor's two file channels. // // A probe, not a read: the panel already holds the text, so the only thing it cannot @@ -1138,48 +1126,26 @@ vision = false }; }); - ipcMain.handle("emrg:previewHtml", async (_e, { path: p } = {}) => showPreview(p)); - - // 预览页的批注(宿主 2026-12-03T18:38:18):浮框在预览视图里画,这里是它唯一的上行口。 - // 发送者必须是预览视图本身——别的 webContents 自称「这是预览里的批注」不算;文件路径取 - // 主进程记着的 previewPath,页面报什么地址都不信。 - ipcMain.on("emrg:previewAnnotate", (event, payload) => { - if (!previewView || previewView.webContents !== event.sender) return; - if (!previewPath) return; + // 页面上选中的文字(宿主 2026-12-03T20:55):批注浮框画在浏览器视图自己的文档里——那是 + // 一个原生子视图,应用的 DOM 图层盖不住它。上行口只有这一个,三个前提都在主进程这一侧: + // 发送者必须是浏览器视图本身、它此刻载着的必须是一个本地 file: 页面、文件路径由这里从那个 + // 地址算出来。页面报什么地址、自称是哪个文件,都不采信。 + ipcMain.on("emrg:pageAnnotate", (event, payload) => { + if (!browserView || browserView.webContents !== event.sender) return; + if (!annotationAllowed(browserUrl)) return; const items = Array.isArray(payload && payload.items) ? payload.items : []; if (!items.length) return; - if (win && !win.isDestroyed()) { - win.webContents.send("emrg:previewAnnotate", { file: previewPath, items }); + let file = null; + try { + file = fileURLToPath(browserUrl); + } catch { + return; } - }); - - ipcMain.handle("emrg:closePreview", async (_e, { path: p } = {}) => { - // 关闭/切走 HTML tab → 隐藏预览(懒销毁:窗口关闭自动回收,R5-⑤) - const target = typeof p === "string" && p.trim() ? path.resolve(p.trim()) : null; - if (previewVisible && (!target || previewPath === target)) { - previewVisible = false; - previewPath = null; - updatePreviewBounds(); + if (win && !win.isDestroyed()) { + win.webContents.send("emrg:pageAnnotation", { file, items }); } - return { ok: true }; - }); - - // renderer 上报面板布局(宽度/折叠/内容区顶部 = Tab 栏高)→ main 调 setBounds(R2-⑧) - ipcMain.handle("emrg:panelResized", async (_e, { width, collapsed, contentTop } = {}) => { - previewLayout = { - width: typeof width === "number" && width > 0 ? width : previewLayout.width, - collapsed: collapsed === true, - contentTop: typeof contentTop === "number" && contentTop >= 0 ? contentTop : previewLayout.contentTop, - }; - updatePreviewBounds(); - return { ok: true }; }); - // renderer 崩溃 reload 后拉取当前预览状态(main 是真相源,R5-④ 恢复通道) - ipcMain.handle("emrg:getPreviewState", async () => ({ - path: previewVisible && previewPath ? previewPath : null, - })); - // ── 内嵌浏览器(rant 2026-11-25T11:10:45)───────────────────────── // 浏览器 tab 的四个通道:显示、隐藏、地址栏导航,以及 renderer 量出的那一格。 // 这一格由 renderer 给而不是由这里算:原生 view 盖在 DOM 上的位置,只有量过它的人知道。 @@ -2128,90 +2094,12 @@ vision = false } } - // ── P2.3 + P3.4:HTML 预览 WebContentsView ──────────────────────── - - /** 懒创建预览 view(R7-⑤):sandbox + contextIsolation 对齐主窗口;安全清单(缺口 8): - * setWindowOpenHandler 禁新窗 + will-frame-navigate 仅允许 file:// 主框架导航(防 HTML - * 内跳转远程 URL)。程序化 loadURL 不走 will-frame-navigate——入口只有 showPreview, - * 已校验扩展名 + 绝对路径 + 文件存在,无绕过路径。 */ - function ensurePreviewView() { - if (previewView) return previewView; - previewView = new WebContentsView({ - // 宿主 2026-12-03T18:38:18:预览页上的批注浮框画在这个文档内部(应用自己的浮层压不住 - // 一个 contentView 子视图)。preload 因此存在,但它**不挂 contextBridge**:页面拿不到 - // 任何对象,浮框与 IPC 都在 preload 自己的世界里。 - webPreferences: { - sandbox: true, - contextIsolation: true, - nodeIntegration: false, - preload: path.join(__dirname, "preview-preload.js"), - }, - }); - previewView.webContents.setWindowOpenHandler(() => ({ action: "deny" })); - // 同一条:Electron 31 传的是 details 对象,位置参数读出来全是 undefined——这道 - // 「只许 file:// 主框架导航」的防线在写成位置参数时一次都没生效。 - previewView.webContents.on("will-frame-navigate", (details) => { - if (details.isMainFrame === true && !String(details.url).startsWith("file:")) { - details.preventDefault(); - } - }); - return previewView; - } - - /** 右对齐矩形(R4-②):x = winW - panelW、y = contentTop(Tab 栏高)、w = panelW、 - * h = winH - contentTop。折叠 → 置不可见区域(0 尺寸 + 不可见)。纯函数,便于单测。 */ - function previewRect(winW, winH, layout) { - if (layout.collapsed) return { x: winW, y: 0, width: 0, height: 0 }; - const width = Math.max(40, Math.min(layout.width || 280, winW)); - const contentTop = layout.contentTop || 0; - return { - x: Math.max(0, winW - width), - y: contentTop, - width, - height: Math.max(0, winH - contentTop), - }; - } - - function updatePreviewBounds() { - if (!previewView || !win || win.isDestroyed()) return; - if (!previewVisible) { previewView.setVisible(false); return; } - const cb = win.getContentBounds(); - const r = previewRect(cb.width, cb.height, previewLayout); - previewView.setBounds(r); - previewView.setVisible(true); - } - - /** 显示 HTML 预览:校验 → 懒创建 → loadURL(切换 = 重新加载 R7-⑥)→ bounds 同步 */ - async function showPreview(p) { - if (typeof p !== "string" || !p.trim()) return { ok: false, error: "invalid path" }; - const abs = path.resolve(p.trim()); - if (!/\.html?$/i.test(abs)) return { ok: false, error: "not_html" }; - if (!fs.existsSync(abs)) return { ok: false, error: "file_not_found" }; - try { - const view = ensurePreviewView(); - if (!previewAdded && win && !win.isDestroyed()) { - win.contentView.addChildView(view); - previewAdded = true; - } - if (previewPath !== abs) { - await view.webContents.loadURL(pathToFileURL(abs).href); - previewPath = abs; - } - previewVisible = true; - updatePreviewBounds(); - return { ok: true }; - } catch (e) { - logger.warn(`[gui] preview load failed: ${e.message}`); - return { ok: false, error: String(e.message || "load_failed") }; - } - } - // ── 内嵌浏览器(rant 2026-11-25T11:10:45)────────────────────────── // - // 预览视图只画本地文件,并显式拒掉一切新窗口与外链导航;这个视图正相反,它存在的理由就是 - // 在应用里显示远程页面。挡住它变成 nav-policy 那条规则的漏洞的是两件事:它是一个**独立** - // 的 view(sandbox + contextIsolation + 无 preload,页面碰不到 window.emrg),以及下面 - // 这些策略全部装在它自己的分区上,绝不落到默认 session。 + // 这个视图存在的理由就是在应用里显示远程页面。挡住它变成 nav-policy 那条规则的漏洞的是 + // 两件事:它是一个**独立**的 view(sandbox + contextIsolation,页面碰不到 window.emrg; + // 它挂的那个 preload 在非 file: 文档里一件事都不做),以及下面这些策略全部装在它自己的 + // 分区上,绝不落到默认 session。 /** 把浏览器的策略装到它自己的分区上。 * @@ -2270,6 +2158,11 @@ vision = false sandbox: true, contextIsolation: true, nodeIntegration: false, + // 只为本地页面上的批注而挂,而它只能挂在视图上:Electron 没有「按导航换 preload」 + // 这回事。所以边界由文档自己判——preload 在任何非 `file:` 文档里第一件事就是返回, + // 一个监听器也不装;主进程也不采信页面的话,只认自己记着的那个地址。远程页面因此 + // 既拿不到界面,也发不出消息,browser-policy.js 那条边界没有松。 + preload: path.join(__dirname, "annotation-preload.js"), }, }); applyBrowserPolicy(browserSession, view.webContents); @@ -2452,11 +2345,7 @@ vision = false stopHeartbeat(); // rant 2026-08-21T12:44:34:退出清理心跳定时器 persistGuiStateNow(); // P4:退出前冲刷未落盘的打开会话状态(防抖 timer 取消) connManager?.closeAll(); // P2:关闭全部会话连接 + daemon 级连接 - // P2.3:窗口关闭自动销毁子 view(R5-⑤ 无需手动清理);复位状态防二次使用 - previewView = null; - previewAdded = false; - previewPath = null; - previewVisible = false; + // 窗口关闭自动销毁子 view(R5-⑤ 无需手动清理);复位状态防二次使用 browserView = null; browserAdded = false; browserVisible = false; diff --git a/emrg/gui/package.json b/emrg/gui/package.json index eb96acbae..6f404e471 100644 --- a/emrg/gui/package.json +++ b/emrg/gui/package.json @@ -35,7 +35,7 @@ "files": [ "main.js", "preload.js", - "preview-preload.js", + "annotation-preload.js", "renderer/**", "!renderer/node_modules{,/**/*}", "!renderer/src{,/**/*}", diff --git a/emrg/gui/preload.js b/emrg/gui/preload.js index 5f2091f1b..b8d335283 100644 --- a/emrg/gui/preload.js +++ b/emrg/gui/preload.js @@ -64,10 +64,6 @@ const api = { // rant 2026-11-20T18:01:52:右栏编辑器的两条文件通道——探测磁盘有没有变、把改动写回 statFile: (payload) => ipcRenderer.invoke("emrg:statFile", payload), writeFile: (payload) => ipcRenderer.invoke("emrg:writeFile", payload), - previewHtml: (payload) => ipcRenderer.invoke("emrg:previewHtml", payload), // P2.3:HTML 预览(WebContentsView) - closePreview: (payload) => ipcRenderer.invoke("emrg:closePreview", payload), // P2.3:关闭/切走 HTML 预览 - panelResized: (payload) => ipcRenderer.invoke("emrg:panelResized", payload), // P2.3:面板布局上报 → bounds 同步 - getPreviewState: () => ipcRenderer.invoke("emrg:getPreviewState"), // P2.3:renderer 崩溃恢复拉取 // rant 2026-11-25T11:10:45:HTML tab 的浏览器模式。show/hide 是页面本身的生命(隐藏不销毁), // navigate 是地址栏,bounds 是 renderer 量出的那一格——原生 view 盖在 DOM 上的位置只有它知道。 showBrowser: (payload) => ipcRenderer.invoke("emrg:showBrowser", payload), @@ -135,13 +131,13 @@ const api = { ipcRenderer.on("emrg:event", listener); return () => ipcRenderer.removeListener("emrg:event", listener); }, - // 宿主 2026-12-03T18:38:18:预览页里的批注。浮框画在那个视图自己的文档内部(应用的图层 - // 压不住一个 contentView 子视图),由 preview-preload.js 发上来、main 转发到这里。 - // 只过纯文本:段落、意见、元素路径,没有节点也没有可求值的表达式。 - onPreviewAnnotation: (cb) => { + // 宿主 2026-12-03T20:55:浏览器模式里本地页面上的批注。浮框画在那个视图自己的文档内部 + // (应用的图层压不住一个 contentView 子视图),由 annotation-preload.js 发上来、main 转发 + // 到这里。只过纯文本:段落、意见、元素路径,没有节点也没有可求值的表达式。 + onPageAnnotation: (cb) => { const listener = (_e, payload) => cb(payload); - ipcRenderer.on("emrg:previewAnnotate", listener); - return () => ipcRenderer.removeListener("emrg:previewAnnotate", listener); + ipcRenderer.on("emrg:pageAnnotation", listener); + return () => ipcRenderer.removeListener("emrg:pageAnnotation", listener); }, }; diff --git a/emrg/gui/renderer/src/components/Shell.tsx b/emrg/gui/renderer/src/components/Shell.tsx index 045a37cc0..ae64cdd7a 100644 --- a/emrg/gui/renderer/src/components/Shell.tsx +++ b/emrg/gui/renderer/src/components/Shell.tsx @@ -265,18 +265,19 @@ export function Shell() { return () => window.removeEventListener("resize", onResize); }, []); - // A batch of annotations made on a previewed page (host 2026-12-03T18:38:18). That panel is - // drawn inside the page — the app's own layer sits under a `contentView` child, so it cannot - // cover one — and it arrives as text over IPC. It leaves through the composer, the same door the - // transcript's own batch uses: queueing, the user record and the session all live on that path. + // A batch of annotations made on a local page in the editor's browser mode (host + // 2026-12-03T20:55). That panel is drawn inside the page — the app's own layer sits under a + // `contentView` child, so it cannot cover one — and it arrives as text over IPC. It leaves + // through the composer, the same door the transcript's own batch uses: queueing, the user + // record and the session all live on that path. useEffect(() => { const emrg = ( window as unknown as { - emrg?: { onPreviewAnnotation?: (cb: (payload: unknown) => void) => () => void }; + emrg?: { onPageAnnotation?: (cb: (payload: unknown) => void) => () => void }; } ).emrg; - if (!emrg?.onPreviewAnnotation) return; - return emrg.onPreviewAnnotation((raw) => { + if (!emrg?.onPageAnnotation) return; + return emrg.onPageAnnotation((raw) => { const data = raw as { file?: unknown; items?: unknown } | null; const file = typeof data?.file === "string" ? data.file : ""; const rows: { paragraph: string; body: string; source?: string }[] = []; diff --git a/emrg/gui/test/annotation-wiring.test.js b/emrg/gui/test/annotation-wiring.test.js new file mode 100644 index 000000000..1a9b57b2a --- /dev/null +++ b/emrg/gui/test/annotation-wiring.test.js @@ -0,0 +1,118 @@ +"use strict"; +/** + * annotation-wiring.test.js — 浏览器模式批注的接线守卫(宿主 2026-12-03T20:55)。 + * + * 批注浮框只能画在浏览器视图自己的文档内部:那个视图由主进程合成在应用窗口**之上**,渲染层 + * 里的任何 DOM 图层都盖不住它。这个文件钉住那条路的四段: + * + * 1. 视图挂着这个 preload,而且它在打包清单里——v0.3.88 的教训是 preload 在仓里、包里没有, + * 界面因此根本不存在,而当时测试全绿; + * 2. 非 file: 文档里它一件事都不做:浮框与选择监听都只在地址判断之后建; + * 3. 上行只认这个视图自己的 webContents,主进程记着的地址必须是本地文件,文件路径由主进程 + * 从那个地址算出来——页面报的地址、自称的文件,一次都不采信; + * 4. preload 不给页面任何东西:没有 contextBridge、没有 exposeInMainWorld(注释里提到这些 + * 名字不算调用,所以先剥注释再断言)。 + * + * 它同时钉住那个打不开的预览面板已经不在了:一套没有入口的功能,不该靠「没人调用」保持安静。 + */ + +const { test } = require("node:test"); +const assert = require("node:assert"); +const fs = require("node:fs"); +const path = require("node:path"); + +const GUI = path.join(__dirname, ".."); +const MAIN = fs.readFileSync(path.join(GUI, "main.js"), "utf8"); +const APP_PRELOAD = fs.readFileSync(path.join(GUI, "preload.js"), "utf8"); +const PAGE_PRELOAD = fs.readFileSync(path.join(GUI, "annotation-preload.js"), "utf8"); +const SHELL = fs.readFileSync( + path.join(GUI, "renderer", "src", "components", "Shell.tsx"), + "utf8", +); + +/** 一个函数体:从 `function (` 到该函数自己的收尾行。 */ +function functionBody(source, name) { + const at = source.indexOf(`function ${name}(`); + assert.ok(at >= 0, `main.js 里找不到 ${name}`); + const end = source.indexOf("\n }", at); + return source.slice(at, end > at ? end : undefined); +} + +/** 去掉注释,留下会执行的代码——注释里提到一个名字不是一次调用。 */ +function codeOnly(source) { + return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, ""); +} + +test("the browser view loads the annotation preload, and the package ships it", () => { + const view = functionBody(MAIN, "ensureBrowserView"); + assert.match(view, /preload:\s*path\.join\(__dirname, "annotation-preload\.js"\)/); + // 一个 preload 不是被 `require` 载入的,所以没有哪条扫描会替它进包;它漏在清单外的症状是 + // 功能整个不存在,而不是一个报错。 + const pkg = JSON.parse(fs.readFileSync(path.join(GUI, "package.json"), "utf8")); + const files = (pkg.build && pkg.build.files) || []; + assert.ok(files.includes("annotation-preload.js"), "build.files 必须点名这个 preload"); +}); + +test("a network page gets no interface: the address is asked before anything is built", () => { + const guard = PAGE_PRELOAD.indexOf('location.protocol !== "file:"'); + assert.ok(guard >= 0, "preload 要先问地址"); + const call = PAGE_PRELOAD.indexOf("main();"); + assert.ok(call > guard, "main() 只在那个判断的 else 里跑"); + assert.strictEqual(PAGE_PRELOAD.lastIndexOf("main();"), call, "只有一处调用点"); + // 浮框与选择监听都建在 main() 里面,所以「唯一的调用点在那个判断的 else 里」就是这一条的全部。 +}); + +test("only this view's own webContents can send a batch up, and the file comes from main", () => { + const at = MAIN.indexOf('ipcMain.on("emrg:pageAnnotate"'); + assert.ok(at >= 0, "main.js 里没有 emrg:pageAnnotate 的接收处"); + const body = MAIN.slice(at, at + 1200); + assert.match(body, /browserView\.webContents !== event\.sender/, "发送者必须是这个视图本身"); + assert.match(body, /annotationAllowed\(browserUrl\)/, "地址必须是本地文件,判断来自策略模块"); + // 文件路径由主进程从自己记着的地址算,页面报上来的文件名不算。 + assert.match(body, /fileURLToPath\(browserUrl\)/); + assert.doesNotMatch(body, /payload\.(file|path)/, "页面自报的路径不进这条链路"); + assert.match(body, /win\.webContents\.send\("emrg:pageAnnotation"/); +}); + +test("the annotation preload hands the page nothing at all", () => { + const code = codeOnly(PAGE_PRELOAD); + assert.doesNotMatch(code, /contextBridge/); + assert.doesNotMatch(code, /exposeInMainWorld/); + assert.doesNotMatch(code, /window\.emrg\s*=/); +}); + +test("the app subscribes once and the batch leaves through the composer", () => { + assert.match(APP_PRELOAD, /onPageAnnotation:/); + assert.match(APP_PRELOAD, /ipcRenderer\.on\("emrg:pageAnnotation"/); + assert.match(APP_PRELOAD, /removeListener\("emrg:pageAnnotation"/); + assert.match(SHELL, /onPageAnnotation/); + // 同一扇门:组装好的消息交给输入框那条路,而不是在这里自己发。 + assert.match(SHELL, /composeMessage\(rows\)/); + assert.match(SHELL, /setComposerSend\(/); +}); + +test("the preview panel nobody could open is gone", () => { + // 宿主 2026-12-03:那个面板没有任何入口——没有按钮、没有菜单、没有快捷键能打开它,批注被 + // 装在一个打不开的视图里。删掉之后,这些通道不该以任何形式留在代码里。 + assert.ok(!fs.existsSync(path.join(GUI, "preview-preload.js")), "preview-preload.js 还在"); + for (const channel of [ + "emrg:previewHtml", + "emrg:closePreview", + "emrg:panelResized", + "emrg:getPreviewState", + "emrg:previewAnnotate", + "ensurePreviewView", + "showPreview", + ]) { + assert.ok(MAIN.indexOf(channel) < 0, `main.js 里还留着 ${channel}`); + } + for (const api of [ + "previewHtml", + "closePreview", + "panelResized", + "getPreviewState", + "onPreviewAnnotation", + ]) { + assert.ok(APP_PRELOAD.indexOf(api) < 0, `preload.js 还暴露着 ${api}`); + } +}); diff --git a/emrg/gui/test/browser-policy.test.js b/emrg/gui/test/browser-policy.test.js index 902d2c3bb..3b21205e5 100644 --- a/emrg/gui/test/browser-policy.test.js +++ b/emrg/gui/test/browser-policy.test.js @@ -14,6 +14,7 @@ const assert = require("node:assert"); const { BROWSER_PARTITION, addressTarget, + annotationAllowed, blocksMainFrameNavigation, browserNavPolicy, browserRect, @@ -281,3 +282,18 @@ test("the page on screen stays until the file behind it changes (issue #3229)", // Nothing loaded at all is not "still current". assert.strictEqual(pageStillCurrent({ target: null, loaded: null, loadedMtimeMs: null, mtimeMs: null }), false); }); + +test("only a local page carries the annotation layer", () => { + // 宿主 2026-12-03T20:55:批注浮框画在浏览器视图自己的文档里,而那个视图也载远程页面。 + // 这里钉住「本地文件才有」这一半;另一半在 annotation-wiring.test.js(非 file: 文档里 + // preload 一件事都不做)。 + assert.strictEqual(annotationAllowed("file:///Users/me/report.html"), true); + assert.strictEqual(annotationAllowed("FILE:///Users/me/report.html"), true); + assert.strictEqual(annotationAllowed("http://localhost:3000/a.html"), false); + assert.strictEqual(annotationAllowed("https://example.com/a.html"), false); + assert.strictEqual(annotationAllowed("about:blank"), false); + // 一个地址都没有的时候不是「也许本地」:没有地址就是不许。 + assert.strictEqual(annotationAllowed(""), false); + assert.strictEqual(annotationAllowed(null), false); + assert.strictEqual(annotationAllowed(undefined), false); +}); diff --git a/emrg/gui/test/browser-wiring.test.js b/emrg/gui/test/browser-wiring.test.js index d2d09472c..83f0234c5 100644 --- a/emrg/gui/test/browser-wiring.test.js +++ b/emrg/gui/test/browser-wiring.test.js @@ -143,13 +143,6 @@ test("both views read frame navigation off the event object Electron 31 passes", "positional arguments are undefined in Electron 31 — the policy then never fires", ); - const preview = functionRegion("ensurePreviewView"); - assert.match(preview, /will-frame-navigate/, "the preview view installs the handler"); - assert.match(preview, /details\.isMainFrame/, "isMainFrame is read off the event object"); - assert.match(preview, /details\.url/, "the URL is read off the event object"); - assert.doesNotMatch( - codeOnly(preview), - POSITIONAL, - "the preview's file-only rule was dead while it read positional arguments", - ); + const preview = functionRegion("ensureBrowserView"); + assert.match(preview, /will-frame-navigate|applyBrowserPolicy/, "the browser's handlers hang off its own view"); }); diff --git a/emrg/gui/test/build-config.test.js b/emrg/gui/test/build-config.test.js index f57e87d9a..129de9b3e 100644 --- a/emrg/gui/test/build-config.test.js +++ b/emrg/gui/test/build-config.test.js @@ -104,9 +104,9 @@ test("every main.js/preload.js local require is covered by files whitelist", () test("every preload named by a path.join(__dirname, ...) in main.js is covered by files whitelist", () => { // 一个 preload 不是被 `require` 载入的,所以上面那条扫描看不见它:main.js 写的是 - // `preload: path.join(__dirname, "preview-preload.js")`,文件在仓里、构建时却没进包。 + // `preload: path.join(__dirname, "annotation-preload.js")`,文件在仓里、构建时却没进包。 // 实测 2026-12-03:v0.3.88 装好的 app.asar 里 `asar list | grep -c preview-preload` = 0, - // 预览页因此没有批注界面,而当时所有测试都是绿的——它漏在清单外,不在代码里。 + // 页面上的批注界面因此不存在,而当时所有测试都是绿的——它漏在清单外,不在代码里。 const files = (PKG.build && PKG.build.files) || []; const src = fs.readFileSync(path.join(GUI_ROOT, "main.js"), "utf-8"); const found = []; diff --git a/emrg/gui/test/preload-api.test.js b/emrg/gui/test/preload-api.test.js index efbe3a445..5fef3df9f 100644 --- a/emrg/gui/test/preload-api.test.js +++ b/emrg/gui/test/preload-api.test.js @@ -61,10 +61,6 @@ const EXPECTED_INVOKE_METHODS = [ // 两者都由 main 执行(renderer 没有直接写盘权限),所以各占一个 invoke 通道。 "statFile", "writeFile", - "previewHtml", - "closePreview", - "panelResized", - "getPreviewState", // rant 2026-11-25T11:10:45:HTML tab 的浏览器模式——显示/隐藏、地址栏导航、视图那一格 "showBrowser", "hideBrowser", @@ -125,9 +121,9 @@ const EXPECTED_INVOKE_METHODS = [ const EXPECTED_EVENT_SUBSCRIPTIONS = { onEvent: "emrg:event", - // 宿主 2026-12-03T18:38:18:预览页里画的批注浮框(应用图层压不住一个 contentView 子视图, - // 所以它画在那个文档内部),main 把这批纯文本转给应用渲染层。 - onPreviewAnnotation: "emrg:previewAnnotate", + // 宿主 2026-12-03T20:55:浏览器模式里本地页面上的批注浮框(应用图层压不住一个 + // contentView 子视图,所以它画在那个文档内部),main 把这批纯文本转给应用渲染层。 + onPageAnnotation: "emrg:pageAnnotation", }; /** 提取 api 对象字面量块(const api = { ... };) */ diff --git a/emrg/gui/test/preview-annotation-wiring.test.js b/emrg/gui/test/preview-annotation-wiring.test.js deleted file mode 100644 index 9a2c1e4ae..000000000 --- a/emrg/gui/test/preview-annotation-wiring.test.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; -/** - * preview-annotation-wiring.test.js — 预览页批注的接线守卫(宿主 2026-12-03T18:38:18)。 - * - * 预览是一个 `WebContentsView` 子视图,由主进程合成在应用窗口**之上**:渲染层里的任何 DOM - * 图层都盖不住它。所以批注浮框只能画在那个文档内部,而这个文件钉住这条路的三段接线: - * - * 1. 预览视图挂着批注 preload,**内嵌浏览器视图没有**——后者页面碰不到 window.emrg 是它 - * 存在的边界(main.js 的注释把这条写成了规则),顺手带上就等于破掉它; - * 2. 上行只认预览视图自己的 webContents:别的发送者自称「这是预览里的批注」不算; - * 3. preload 不给页面任何东西——没有 contextBridge、没有 exposeInMainWorld,浮框与 IPC - * 全在 preload 自己的世界里(注释里提到这些名字不算调用,所以先剥注释再断言)。 - */ - -const { test } = require("node:test"); -const assert = require("node:assert"); -const fs = require("node:fs"); -const path = require("node:path"); - -const GUI = path.join(__dirname, ".."); -const MAIN = fs.readFileSync(path.join(GUI, "main.js"), "utf8"); -const APP_PRELOAD = fs.readFileSync(path.join(GUI, "preload.js"), "utf8"); -const PREVIEW_PRELOAD = fs.readFileSync(path.join(GUI, "preview-preload.js"), "utf8"); -const SHELL = fs.readFileSync( - path.join(GUI, "renderer", "src", "components", "Shell.tsx"), - "utf8", -); - -/** 一个函数体:从 `function (` 到该函数自己的收尾行。 */ -function functionBody(source, name) { - const at = source.indexOf(`function ${name}(`); - assert.ok(at >= 0, `main.js 里找不到 ${name}`); - const end = source.indexOf("\n }", at); - return source.slice(at, end > at ? end : undefined); -} - -/** 去掉注释,留下会执行的代码——注释里提到一个名字不是一次调用。 */ -function codeOnly(source) { - return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, ""); -} - -test("the preview view loads the annotation preload", () => { - const preview = functionBody(MAIN, "ensurePreviewView"); - assert.match(preview, /preload:\s*path\.join\(__dirname, "preview-preload\.js"\)/); -}); - -test("the embedded browser keeps none, so a remote page still reaches nothing", () => { - const browser = functionBody(MAIN, "ensureBrowserView"); - assert.doesNotMatch(codeOnly(browser), /preload/); -}); - -test("the preview preload hands the page nothing at all", () => { - const code = codeOnly(PREVIEW_PRELOAD); - assert.doesNotMatch(code, /contextBridge/); - assert.doesNotMatch(code, /exposeInMainWorld/); - assert.doesNotMatch(code, /window\.emrg\s*=/); -}); - -test("only the preview view's own webContents can send a batch up, and the file comes from main", () => { - const at = MAIN.indexOf('ipcMain.on("emrg:previewAnnotate"'); - assert.ok(at >= 0, "main.js 里没有 emrg:previewAnnotate 的接收处"); - const body = MAIN.slice(at, at + 900); - assert.match(body, /previewView\.webContents !== event\.sender/); - // 文件路径取主进程记着的 previewPath,不信页面报上来的地址 - assert.match(body, /file:\s*previewPath/); - assert.match(body, /win\.webContents\.send\("emrg:previewAnnotate"/); -}); - -test("the app subscribes once and the batch leaves through the composer", () => { - assert.match(APP_PRELOAD, /onPreviewAnnotation:/); - assert.match(APP_PRELOAD, /ipcRenderer\.on\("emrg:previewAnnotate"/); - assert.match(APP_PRELOAD, /removeListener\("emrg:previewAnnotate"/); - assert.match(SHELL, /onPreviewAnnotation/); - // 同一扇门:组装好的消息交给输入框那条路,而不是在这里自己发 - assert.match(SHELL, /composeMessage\(rows\)/); - assert.match(SHELL, /setComposerSend\(/); -});