From 91da88d09d34f7b82ed70e24a4a4cd69e9a7e945 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 26 Nov 2026 10:25:25 +0800 Subject: [PATCH] revert(browser): take the Open Local Browser panel out for now (#6027) The panel needed the workbench to run as a child webview, which on macOS declines key equivalents, so Command shortcuts went to the native menu and many were lost (#5954, #5992). Reverts #5788, #5917 and the #5956 key-monitor workaround; the workbench webview is the window's own view again on every platform. The panel can come back once it no longer needs a child webview. --- crates/ide-host/src/ops/web.rs | 2 +- docs/en/guide/editor.mdx | 8 - docs/zh/guide/editor.mdx | 8 - e2e/browserElement.spec.ts | 248 ------------- src-tauri/Cargo.toml | 7 +- src-tauri/capabilities/browser.json | 7 - src-tauri/capabilities/default.json | 4 +- src-tauri/capabilities/e2e.json | 2 +- src-tauri/src/application_focus.rs | 5 +- src-tauri/src/browser_picker/element.js | 123 ------- src-tauri/src/browser_picker/guest.rs | 274 -------------- src-tauri/src/browser_picker/mod.rs | 345 ------------------ src-tauri/src/browser_picker/snapshot.rs | 149 -------- src-tauri/src/commands/clipboard.rs | 6 +- src-tauri/src/commands/perf.rs | 6 +- src-tauri/src/commands/web.rs | 25 +- src-tauri/src/commands/window.rs | 47 ++- src-tauri/src/commands/window_drag.rs | 6 +- src-tauri/src/commands/window_group.rs | 26 +- src-tauri/src/commands/workspace.rs | 6 +- src-tauri/src/events.rs | 8 +- src-tauri/src/lib.rs | 24 +- src-tauri/src/linux_window_state.rs | 13 +- src-tauri/src/macos.rs | 4 +- src-tauri/src/menu.rs | 180 +++------ .../{macos_webview_input.rs => page_swipe.rs} | 147 +------- src-tauri/src/plugin_web.rs | 4 - src-tauri/src/system_notifications.rs | 4 +- src-tauri/src/updates.rs | 4 +- src-tauri/src/window_groups.rs | 40 +- src-tauri/src/window_groups/frames.rs | 12 +- src-tauri/src/windows.rs | 87 ++--- src-tauri/tests/commands.snap | 2 - src/bindings.ts | 31 -- src/features/agents/ReferenceChip.tsx | 16 +- src/features/agents/agents.test.ts | 1 - src/features/agents/composerModel.ts | 7 +- src/features/agents/index.ts | 3 - src/features/agents/store.ts | 14 - src/features/app/__tests__/menuBridge.test.ts | 85 ----- src/features/app/menuBridge.ts | 69 +--- src/features/debugger/ui/DebugConsole.tsx | 3 +- src/features/run/ConsoleView.tsx | 3 +- src/features/run/navigate.ts | 37 -- src/features/web/BrowserView.tsx | 239 ------------ src/features/web/Web.module.css | 100 ----- src/features/web/browserSession.ts | 121 ------ src/features/web/index.ts | 29 -- src/platform/auxWindow.test.ts | 19 +- src/platform/locales/text/en.json | 10 - src/platform/locales/text/zh.json | 10 - src/ui/Tooltip.test.tsx | 56 --- src/ui/Tooltip.tsx | 59 +-- src/ui/expui/toolwindows/web.svg | 4 - src/ui/expui/toolwindows/web@20x20.svg | 4 - src/ui/expui/toolwindows/web@20x20_dark.svg | 4 - src/ui/expui/toolwindows/web_dark.svg | 4 - src/ui/icons.tsx | 1 - src/workbench/contributions.ts | 16 - 59 files changed, 203 insertions(+), 2575 deletions(-) delete mode 100644 e2e/browserElement.spec.ts delete mode 100644 src-tauri/capabilities/browser.json delete mode 100644 src-tauri/src/browser_picker/element.js delete mode 100644 src-tauri/src/browser_picker/guest.rs delete mode 100644 src-tauri/src/browser_picker/mod.rs delete mode 100644 src-tauri/src/browser_picker/snapshot.rs rename src-tauri/src/{macos_webview_input.rs => page_swipe.rs} (51%) delete mode 100644 src/features/web/BrowserView.tsx delete mode 100644 src/features/web/browserSession.ts delete mode 100644 src/ui/expui/toolwindows/web.svg delete mode 100644 src/ui/expui/toolwindows/web@20x20.svg delete mode 100644 src/ui/expui/toolwindows/web@20x20_dark.svg delete mode 100644 src/ui/expui/toolwindows/web_dark.svg diff --git a/crates/ide-host/src/ops/web.rs b/crates/ide-host/src/ops/web.rs index 929f05d4f1..53ce1b88cb 100644 --- a/crates/ide-host/src/ops/web.rs +++ b/crates/ide-host/src/ops/web.rs @@ -8,7 +8,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxySettings}; use std::time::Duration; /// Whether `url` names this machine (`localhost` or a loopback address). -pub fn is_loopback(url: &reqwest::Url) -> bool { +fn is_loopback(url: &reqwest::Url) -> bool { let host = url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']'); host.eq_ignore_ascii_case("localhost") || host.parse::().is_ok_and(|ip| ip.is_loopback()) } diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index 8a08bf0125..f98ba6b8b5 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -5,14 +5,6 @@ description: "Carets and selections, line editing, the clipboard history, foldin The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below are the defaults of the **macOS** keymap on macOS and the **Windows** keymap on Windows and Linux; you can change any of them in **Settings › Keymap** (see [Keymaps](/en/guide/keymap)). Every command is also available from **Find Action** (`⇧⌘A` / `Ctrl+Shift+A`). -## Browse a local development server - -In a trusted local project, use **Find Action › Open Local Browser**. Enter a loopback HTTP or HTTPS URL, then choose **Open**. Links, **Back**, **Forward**, and **Reload** operate on the page in the panel. Hiding the panel preserves the page and its history; **Close** ends the session. Navigation stays on the original origin. To switch development servers or ports, close the session and open the new address. - -Clicking a URL in a Run or Debug console still opens it in the external browser. To open a localhost URL in the panel instead, right-click it and choose **Open in Browser Tool Window**. - -Choose **Inspect Element**, then click an element in the page. Review its selector, opening tag and styles before choosing **Add to Agent Draft**. This appends to the draft without sending it. Press **Escape** in the page to return to normal browsing without selecting anything. - ## Carets and selections | Action | macOS | Windows / Linux | diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index 53400b69b0..fc8d662b98 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -5,14 +5,6 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 编辑器的行为和默认快捷键沿用 IntelliJ IDEA。下文的快捷键在 macOS 上是 **macOS** 键位映射的默认值,在 Windows 和 Linux 上是 **Windows** 键位映射的默认值;任何一个都可以在 **设置 › 按键映射** 中修改(见 [键位映射](/zh/guide/keymap))。所有命令也都能在 **查找操作**(`⇧⌘A` / `Ctrl+Shift+A`)里找到。 -## 浏览本地开发服务器 - -在受信任的本地项目中,选择**查找操作 › 打开本地浏览器**。输入指向本机回环地址的 HTTP 或 HTTPS 网址,点击**打开**。可以直接在面板中点击链接、后退、前进和重新加载。隐藏面板会保留页面和浏览历史;点击**关闭**才会结束会话。浏览范围限于原来的源;如需切换开发服务器或端口,请先关闭会话,再打开新地址。 - -点击运行或调试控制台中的网址仍会在外部浏览器中打开。如需在此面板中打开本机地址,右键点击该地址并选择**在浏览器工具窗口中打开**。 - -点击**检查元素**,然后在页面中点选元素。确认选择器、起始标签和样式后,可将其添加到 Agent 草稿,不会自动发送。在页面中按 **Escape** 可退出检查并继续浏览。 - ## 光标与选区 | 操作 | macOS | Windows / Linux | diff --git a/e2e/browserElement.spec.ts b/e2e/browserElement.spec.ts deleted file mode 100644 index 2114f17246..0000000000 --- a/e2e/browserElement.spec.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { readFileSync } from "node:fs"; -import type { Page } from "@playwright/test"; -import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; - -const script = readFileSync(new URL("../src-tauri/src/browser_picker/element.js", import.meta.url), "utf8"); -const element = { - selector: "main:nth-of-type(1) > button:nth-of-type(2)", - html: '', - }), - ); - await page.goto("http://localhost:3000/sample?key=fixture-key"); - const button = page.getByRole("button", { name: "Fixture customer" }); - await page.getByRole("button", { name: "First" }).click(); - expect(await page.evaluate("window.__openideaPickedElement")).toBeNull(); - await page.evaluate("window.__openideaInspect(true)"); - await button.dispatchEvent("pointerdown", { isPrimary: true, button: 0 }); - expect(await page.evaluate("window.__openideaPickedElement")).toBeNull(); - expect(await page.frames()[1]!.evaluate("window.__openideaPickedElement")).toBeUndefined(); - const rect = await button.boundingBox(); - await page.mouse.click(rect!.x + 4, rect!.y + 4); - const picked = await page.evaluate(() => String(Reflect.get(window, "__openideaPickedElement"))); - expect(JSON.parse(picked)).toMatchObject({ - path: [ - { tag: "html", index: 1 }, - { tag: "body", index: 1 }, - { tag: "main", index: 1 }, - { tag: "button", index: 2 }, - ], - disabled: true, - display: "inline-flex", - }); - expect(picked).not.toMatch(/fixture-|Fixture customer|First/); - await page.evaluate("window.__openideaInspect(true)"); - await page.keyboard.press("Escape"); - expect(await page.evaluate("window.__openideaPickedElement")).toBe("cancel"); -}); - -async function openBrowser(page: Page) { - await page.evaluate(async () => { - const actions = "/src/platform/actions.ts"; - await (await import(actions)).executeAction("web.openLocalBrowser"); - }); - await expect(page.getByRole("textbox", { name: "Local page URL" })).toBeVisible(); -} - -async function stubBrowser(page: Page) { - await page.evaluate((snapshot) => { - let history: string[] = [], - index = 0, - inspecting = false; - window.__ipc.handlers.cancel_request = () => null; - window.__ipc.handlers.web_browser_open = ({ url }) => { - history = [String(url)]; - index = 0; - }; - window.__ipc.handlers.web_browser_control = ({ action }) => { - const command = action as { type: string; url: string }; - let element = null; - switch (command.type) { - case "navigate": - history.splice(++index, Infinity, command.url); - break; - case "back": - index--; - break; - case "forward": - index++; - break; - case "inspect": - inspecting = true; - break; - case "cancel": - inspecting = false; - break; - case "status": - if (inspecting && !document.body.hasAttribute("data-hold-pick")) { - inspecting = false; - element = snapshot; - } - } - return { url: history[index], canBack: index > 0, canForward: index + 1 < history.length, inspecting, element }; - }; - }, element); -} - -async function visit(page: Page, url: string) { - await page.getByLabel("Local page URL").fill(url); - await page.getByLabel("Local page URL").press("Enter"); -} - -for (const key of ["home", "checkout-task"]) { - test(`review appends to the ${key === "home" ? "new" : "active"} Codex task draft`, async ({ - workbench: page, - }, info) => { - await stubDesktop(page); - await stubBrowser(page); - await page.evaluate(async (key) => { - const storePath = "/src/features/agents/store.ts"; - const store = await import(storePath); - const task = { - id: key, - title: "Checkout review", - provider: "codex", - status: "ready", - isolation: "local", - model: null, - cwd: "/dev/acme-api", - branch: null, - base: null, - baseCommit: null, - error: null, - createdMs: 0, - updatedMs: 0, - config: [], - commands: [], - usage: null, - queue: [], - }; - store.useAgents.setState({ - loaded: true, - sessionLocation: key === "home" ? "editor" : "toolWindow", - ...(key === "home" - ? {} - : { tasks: new Map([[key, task]]), entries: new Map([[key, []]]), docked: key, homeOpen: false }), - draft: { provider: "codex", config: {}, isolation: "local", base: null }, - }); - store.updateComposer(key, { - text: "Why is the checkout button disabled?", - files: [{ path: "/dev/acme-api/README.md", rel: "README.md", attached: true }], - }); - }, key); - await openBrowser(page); - await visit(page, "http://localhost:3000"); - await page.getByRole("button", { name: "Inspect Element", exact: true }).click(); - await expect(page.getByRole("heading", { name: "Selected element" })).toBeVisible(); - await expect(page.getByText(element.html, { exact: false })).toBeVisible(); - await page.screenshot({ path: info.outputPath("preview.png"), animations: "disabled" }); - await page.getByRole("button", { name: "Add to Agent Draft" }).click(); - const box = page.getByRole("textbox", { name: "Message", exact: true }); - await expect(box).toBeVisible(); - const draft = await page.evaluate(async (key) => { - const storePath = "/src/features/agents/store.ts"; - const store = await import(storePath); - return { - ...store.composerDraft(key), - provider: - key === "home" - ? store.useAgents.getState().draft.provider - : store.useAgents.getState().tasks.get(key)?.provider, - }; - }, key); - expect(draft).toMatchObject({ - text: expect.stringContaining("Why is the checkout button disabled?\n\n"), - files: [{ path: "/dev/acme-api/README.md", rel: "README.md", attached: true }], - provider: "codex", - }); - expect(draft.text).toContain(element.selector); - expect(draft.text).toContain(element.html); - expect(draft.text).toContain(element.styles); - await expect(box).toBeEditable(); - await page.screenshot({ path: info.outputPath("draft.png"), animations: "disabled" }); - expect(await ipcCalls(page, "agent_prompt")).toEqual([]); - expect(await ipcCalls(page, "agent_create")).toEqual([]); - }); -} - -test("cancelling or revoking trust discards a delayed selection", async ({ workbench: page }) => { - await stubDesktop(page); - await stubBrowser(page); - await page.evaluate(() => document.body.setAttribute("data-hold-pick", "")); - await openBrowser(page); - await visit(page, "http://localhost:3000"); - const inspect = page.getByRole("button", { name: "Inspect Element", exact: true }); - await inspect.click(); - await expect(inspect).toHaveAttribute("aria-pressed", "true"); - await inspect.click(); - await expect(inspect).toHaveAttribute("aria-pressed", "false"); - await expect(page.getByRole("button", { name: "Add to Agent Draft" })).toHaveCount(0); - await inspect.click(); - await page.evaluate(async () => { - const projectPath = "/src/platform/project.ts"; - const { useProject } = await import(projectPath); - useProject.setState({ project: { ...useProject.getState().project, trusted: false } }); - }); - await expect(page.getByText("Element inspection requires a trusted local project.")).toBeVisible(); - await expect(page.getByRole("button", { name: "Add to Agent Draft" })).toHaveCount(0); - expect(await ipcCalls(page, "cancel_request")).toHaveLength(1); -}); - -test("navigates the same session and keeps native history until Close", async ({ workbench: page }) => { - await stubDesktop(page); - await stubBrowser(page); - await openBrowser(page); - const panel = page.getByRole("region", { name: "Browser" }); - const address = panel.getByLabel("Local page URL"); - await visit(page, "http://localhost:3000/first"); - await expect(panel.getByRole("button", { name: "Back", exact: true })).toBeDisabled(); - await visit(page, "http://localhost:3000/next"); - await page.evaluate(async () => { - const path = "/src/workbench/contributions.ts"; - (await import(path)).toolWindowService().hide("browser"); - }); - - await expect(panel).toBeHidden(); - await openBrowser(page); - await panel.getByRole("button", { name: "Back", exact: true }).click(); - await expect(address).toHaveValue("http://localhost:3000/first"); - await panel.getByRole("button", { name: "Forward", exact: true }).click(); - await expect(address).toHaveValue("http://localhost:3000/next"); - await panel.getByRole("button", { name: "Reload", exact: true }).click(); - expect(await ipcCalls(page, "web_browser_open")).toHaveLength(1); - await panel.getByRole("button", { name: "Close", exact: true }).click(); - await expect(panel.getByRole("button", { name: "Reload", exact: true })).toHaveCount(0); - expect(await ipcCalls(page, "cancel_request")).toHaveLength(1); -}); - -test("localhost console links offer the Browser in their context menu; a plain click stays external", async ({ - workbench: page, -}) => { - await stubDesktop(page); - await stubBrowser(page); - const routed = await page.evaluate(async () => { - const path = "/src/features/run/navigate.ts"; - const { consoleLinkMenu, debugConsoleUrl } = await import(path); - const click = { metaKey: false, ctrlKey: false, shiftKey: false }; - const urls = ["https://localhost.example.org/", "http://guest@localhost:3000/", "http://127.0.0.1:3000/app"]; - const menus = urls.map((url) => { - const link = document.createElement("a"); - link.setAttribute("href", url); - link.textContent = url; - return consoleLinkMenu(link); - }); - menus[2][0].run(); - return { plain: urls.map((url) => debugConsoleUrl(click, url)), offered: menus.map((m) => m.length > 0) }; - }); - expect(routed).toEqual({ plain: [false, false, false], offered: [false, false, true] }); - await expect(page.getByLabel("Local page URL")).toHaveValue("http://127.0.0.1:3000/app"); - expect(await ipcCalls(page, "web_browser_open")).toHaveLength(1); -}); diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 41f2a37d0c..428e1dda9a 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -14,8 +14,7 @@ tauri-build = { version = "2", features = [] } dunce.workspace = true [dependencies] -# Tauri 2 gates Window::add_child behind its multiwebview feature. -tauri = { version = "2", features = ["unstable"] } +tauri = { version = "2", features = [] } tauri-plugin-opener = "2" tauri-plugin-notification = "2.8.1" tauri-plugin-dialog = { version = "2", default-features = false, features = ["xdg-portal"] } @@ -80,8 +79,8 @@ security-framework = "3.7" objc2 = "0.6" objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSLocale", "NSNotification", "NSOperation", "NSString"] } -# Browser history and the debug font-restriction override. -objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebView", "WKWebViewConfiguration", "WKPreferences"] } +# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions. +objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] } [target.'cfg(target_os = "linux")'.dependencies] # Wayland detection and the client size without GTK's CSD shadow (linux_window_state.rs). diff --git a/src-tauri/capabilities/browser.json b/src-tauri/capabilities/browser.json deleted file mode 100644 index cc985906bc..0000000000 --- a/src-tauri/capabilities/browser.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "browser", - "description": "Untrusted localhost Browser child. No core, plugin, or application commands.", - "webviews": ["browser-guest-*"], - "permissions": [] -} diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 8d8645685e..cdfcf6c434 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,8 +1,8 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Trusted workbench webviews only; child browser pages must not inherit their host window's permissions.", - "webviews": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], + "description": "Capability for the main window", + "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], "permissions": [ "core:default", "core:window:allow-start-dragging", diff --git a/src-tauri/capabilities/e2e.json b/src-tauri/capabilities/e2e.json index d670027c3f..3bfe73ecaa 100644 --- a/src-tauri/capabilities/e2e.json +++ b/src-tauri/capabilities/e2e.json @@ -2,6 +2,6 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "e2e-bridge", "description": "Debug-only automation bridge", - "webviews": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], + "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], "permissions": ["mcp-bridge:default"] } diff --git a/src-tauri/src/application_focus.rs b/src-tauri/src/application_focus.rs index 367fc41510..be929ce701 100644 --- a/src-tauri/src/application_focus.rs +++ b/src-tauri/src/application_focus.rs @@ -1,7 +1,4 @@ //! Debounced application activation, shared by every project window. -#[cfg(not(any(target_os = "macos", windows)))] -use crate::windows::WorkbenchWindows; - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use tauri::{Emitter, Manager}; @@ -90,7 +87,7 @@ pub(crate) fn application_active(app: &tauri::AppHandle) -> bool { process == std::process::id() } #[cfg(not(any(target_os = "macos", target_os = "windows")))] - app.workbench_windows().values().any(|w| w.is_focused().unwrap_or(true)) + app.webview_windows().values().any(|w| w.is_focused().unwrap_or(true)) } #[cfg(test)] diff --git a/src-tauri/src/browser_picker/element.js b/src-tauri/src/browser_picker/element.js deleted file mode 100644 index fc79783894..0000000000 --- a/src-tauri/src/browser_picker/element.js +++ /dev/null @@ -1,123 +0,0 @@ -// Runs at document start in the unprivileged picker. Only a physical click can fill the slot. -// The workbench reads this view's main-frame slot only while armed. No page-to-IDE IPC. -(() => { - if (window !== window.top) return; - let picked = null; - let armed = false; - let suppressClick = false; - const styleOf = window.getComputedStyle.bind(window); - const encode = JSON.stringify; - const slice = Function.call.bind(String.prototype.slice); - Object.defineProperty(window, "__openideaPickedElement", { - get: () => (picked === null ? null : slice(picked, 0, 8193)), - }); - let outline; - function stop() { - armed = false; - outline?.remove(); - outline = undefined; - } - Object.defineProperty(window, "__openideaInspect", { - value: (enable) => { - stop(); - picked = null; - suppressClick = false; - armed = enable === true; - }, - }); - window.addEventListener("pagehide", () => { - stop(); - picked = null; - suppressClick = false; - }); - window.addEventListener( - "pointermove", - (event) => { - if (!armed || !event.isTrusted || !(event.target instanceof Element) || !document.body) return; - if (!outline) { - outline = document.createElement("div"); - outline.setAttribute("aria-hidden", "true"); - outline.style.cssText = - "all:initial;position:fixed;pointer-events:none;z-index:2147483647;box-sizing:border-box;border:2px solid #4d90fe"; - document.body.appendChild(outline); - } - const rect = event.target.getBoundingClientRect(); - Object.assign(outline.style, { - left: rect.left + "px", - top: rect.top + "px", - width: rect.width + "px", - height: rect.height + "px", - }); - }, - true, - ); - window.addEventListener( - "pointerdown", - (event) => { - // Some disabled controls never emit the click after pointerdown. - if (event.isTrusted) suppressClick = false; - if ( - !armed || - !event.isTrusted || - !event.isPrimary || - event.button !== 0 || - !(event.target instanceof Element) || - picked !== null - ) - return; - event.preventDefault(); - event.stopImmediatePropagation(); - const element = event.target; - const path = []; - for (let node = element; node && path.length < 8; node = node.parentElement) { - const tag = node.localName; - let index = 1; - for ( - let sibling = node.previousElementSibling; - sibling && index < 65536; - sibling = sibling.previousElementSibling - ) - if (sibling.localName === tag) index++; - if (index > 65535) return; - path.unshift({ tag, index }); - } - const css = styleOf(element); - picked = encode({ - path, - disabled: element.hasAttribute("disabled"), - hidden: element.hasAttribute("hidden"), - ariaDisabled: element.getAttribute("aria-disabled") === "true", - display: css.display, - position: css.position, - visibility: css.visibility, - pointerEvents: css.pointerEvents, - }); - stop(); - suppressClick = true; - }, - true, - ); - // Suppress the click that follows the inspection gesture (links, form submits, app buttons). - window.addEventListener( - "click", - (event) => { - if (suppressClick) { - suppressClick = false; - event.preventDefault(); - event.stopImmediatePropagation(); - } - }, - true, - ); - window.addEventListener( - "keydown", - (event) => { - if (armed && event.isTrusted && event.key === "Escape") { - event.preventDefault(); - stop(); - picked = "cancel"; - } - }, - true, - ); -})(); diff --git a/src-tauri/src/browser_picker/guest.rs b/src-tauri/src/browser_picker/guest.rs deleted file mode 100644 index fe116e099f..0000000000 --- a/src-tauri/src/browser_picker/guest.rs +++ /dev/null @@ -1,274 +0,0 @@ -//! Tauri owns both views. Only the workbench webview has the application's capability. -use super::{BrowserBounds, unavailable}; -use ide_core::IdeResult; -use tauri::{PhysicalPosition, PhysicalSize, Webview, Window}; - -pub(super) struct Surface { - pub webview: Webview, - #[cfg(target_os = "linux")] - slot: gtk::Box, -} - -impl Surface { - pub fn new(window: &Window, builder: tauri::webview::WebviewBuilder) -> IdeResult { - let webview = - window.add_child(builder, PhysicalPosition::new(0, 0), PhysicalSize::new(1, 1)).map_err(unavailable)?; - let init = || -> IdeResult { - webview.hide().map_err(unavailable)?; - // On GTK add_child packs siblings in a vertical box: give the guest a positioned - // overlay instead, on Wayland as well as X11. Never replace the workbench widget. - #[cfg(target_os = "linux")] - let slot = { - use gtk::prelude::*; - let win = window.gtk_window().map_err(unavailable)?; - let root = win.child().ok_or_else(|| unavailable("missing workbench widget"))?; - let overlay = if let Some(existing) = root.downcast_ref::() { - existing.clone() - } else { - let overlay = gtk::Overlay::new(); - win.remove(&root); - overlay.add(&root); - win.add(&overlay); - overlay.show(); - overlay - }; - let slot = gtk::Box::new(gtk::Orientation::Vertical, 0); - slot.set_halign(gtk::Align::Start); - slot.set_valign(gtk::Align::Start); - // with_webview runs immediately on the UI thread. Keep GTK objects there. - let (tx, rx) = std::sync::mpsc::sync_channel(1); - let weak: gtk::glib::SendWeakRef = slot.downgrade().into(); - webview - .with_webview(move |native| { - let result = (|| -> IdeResult<()> { - let widget = native.inner(); - let parent = widget - .parent() - .and_then(|p| p.downcast::().ok()) - .ok_or_else(|| unavailable("missing guest container"))?; - let slot = weak.upgrade().ok_or_else(|| unavailable("missing guest slot"))?; - parent.remove(&widget); - slot.add(&widget); - Ok(()) - })(); - let _ = tx.send(result); - }) - .map_err(unavailable)?; - rx.recv().map_err(unavailable)??; - overlay.add_overlay(&slot); - slot - }; - Ok(Self { - webview: webview.clone(), - #[cfg(target_os = "linux")] - slot, - }) - }; - let result = init(); - if result.is_err() { - webview.close().map_err(unavailable)?; - } - result - } - - pub fn layout(&self, window: &Window, bounds: Option) -> IdeResult<()> { - let size = window.inner_size().map_err(unavailable)?; - let Some((position, rect_size)) = bounds.and_then(|b| resolve_bounds(b, size)) else { - #[cfg(target_os = "linux")] - gtk::prelude::WidgetExt::hide(&self.slot); - return self.webview.hide().map_err(unavailable); - }; - #[cfg(not(target_os = "linux"))] - self.webview - .set_bounds(tauri::Rect { position: position.into(), size: rect_size.into() }) - .map_err(unavailable)?; - #[cfg(target_os = "linux")] - { - use gtk::prelude::*; - let scale = window.scale_factor().map_err(unavailable)?; - self.slot.set_margin_start((f64::from(position.x) / scale).round() as i32); - self.slot.set_margin_top((f64::from(position.y) / scale).round() as i32); - self.slot.set_size_request( - (f64::from(rect_size.width) / scale).round() as i32, - (f64::from(rect_size.height) / scale).round() as i32, - ); - self.slot.show(); - } - self.webview.show().map_err(unavailable) - } - - pub fn history(&self) -> IdeResult<(bool, bool)> { - let (tx, rx) = std::sync::mpsc::sync_channel(1); - self.webview - .with_webview(move |native| { - #[cfg(target_os = "macos")] - // SAFETY: Tauri lends the WKWebView on its UI thread for this callback. - let result = unsafe { - let view = &*native.inner().cast::(); - Ok((view.canGoBack(), view.canGoForward())) - }; - #[cfg(windows)] - let result = (|| unsafe { - let view = native.controller().CoreWebView2()?; - let (mut back, mut forward) = (windows::core::BOOL::default(), windows::core::BOOL::default()); - view.CanGoBack(&mut back)?; - view.CanGoForward(&mut forward)?; - windows::core::Result::Ok((back.as_bool(), forward.as_bool())) - })() - .map_err(unavailable); - #[cfg(target_os = "linux")] - let result = { - use webkit2gtk::WebViewExt; - let view = native.inner(); - Ok((view.can_go_back(), view.can_go_forward())) - }; - let _ = tx.send(result); - }) - .map_err(unavailable)?; - rx.recv().map_err(unavailable)? - } -} - -impl Drop for Surface { - fn drop(&mut self) { - if let Err(error) = self.webview.close() { - tracing::debug!(%error, "browser child already closed"); - } - #[cfg(target_os = "linux")] - { - use gtk::prelude::*; - if let Some(parent) = self.slot.parent().and_then(|w| w.downcast::().ok()) { - parent.remove(&self.slot); - } - } - } -} - -/// Maps CSS viewport coordinates to window physical pixels regardless of IDE zoom or engine `devicePixelRatio` semantics. -fn resolve_bounds( - bounds: BrowserBounds, - size: PhysicalSize, -) -> Option<(PhysicalPosition, PhysicalSize)> { - if size.width == 0 - || size.height == 0 - || !bounds.x.is_finite() - || !bounds.y.is_finite() - || !bounds.width.is_finite() - || !bounds.height.is_finite() - || !bounds.viewport_width.is_finite() - || !bounds.viewport_height.is_finite() - || bounds.viewport_width <= 0.0 - || bounds.viewport_height <= 0.0 - || bounds.x < 0.0 - || bounds.y < 0.0 - || bounds.width <= 0.0 - || bounds.height <= 0.0 - { - return None; - } - let scale_x = f64::from(size.width) / bounds.viewport_width; - let scale_y = f64::from(size.height) / bounds.viewport_height; - let left = (bounds.x * scale_x).round(); - let top = (bounds.y * scale_y).round(); - let right = ((bounds.x + bounds.width) * scale_x).round(); - let bottom = ((bounds.y + bounds.height) * scale_y).round(); - let max_width = f64::from(size.width.saturating_add(1)); - let max_height = f64::from(size.height.saturating_add(1)); - if left < 0.0 || top < 0.0 || right <= left || bottom <= top || right > max_width || bottom > max_height { - return None; - } - let right = right.min(f64::from(size.width)); - let bottom = bottom.min(f64::from(size.height)); - if right <= left || bottom <= top { - return None; - } - Some(( - PhysicalPosition::new(left as i32, top as i32), - PhysicalSize::new((right - left) as u32, (bottom - top) as u32), - )) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn maps_css_bounds_with_ide_zoom_and_hidpi() { - // 1440x900 logical @ 2x Retina = 2880x1800 physical; at 125% IDE zoom CSS viewport is 1152x720. - let (pos, size) = resolve_bounds( - BrowserBounds { - x: 800.0, - y: 80.0, - width: 320.0, - height: 400.0, - viewport_width: 1152.0, - viewport_height: 720.0, - }, - PhysicalSize::new(2880, 1800), - ) - .unwrap(); - assert_eq!(pos, PhysicalPosition::new(2000, 200)); - assert_eq!(size, PhysicalSize::new(800, 1000)); - } - - #[test] - fn rejects_invalid_or_out_of_bounds_rects() { - let win = PhysicalSize::new(2000, 1200); - assert!( - resolve_bounds( - BrowserBounds { - x: -1.0, - y: 0.0, - width: 100.0, - height: 100.0, - viewport_width: 1000.0, - viewport_height: 600.0, - }, - win, - ) - .is_none() - ); - assert!( - resolve_bounds( - BrowserBounds { - x: 950.0, - y: 0.0, - width: 100.0, - height: 100.0, - viewport_width: 1000.0, - viewport_height: 600.0, - }, - win, - ) - .is_none() - ); - assert!( - resolve_bounds( - BrowserBounds { - x: 10.0, - y: 10.0, - width: 100.0, - height: 100.0, - viewport_width: 0.0, - viewport_height: 600.0, - }, - win, - ) - .is_none() - ); - assert!( - resolve_bounds( - BrowserBounds { - x: f64::NAN, - y: 10.0, - width: 100.0, - height: 100.0, - viewport_width: 1000.0, - viewport_height: 600.0, - }, - win, - ) - .is_none() - ); - } -} diff --git a/src-tauri/src/browser_picker/mod.rs b/src-tauri/src/browser_picker/mod.rs deleted file mode 100644 index a7c7354a7f..0000000000 --- a/src-tauri/src/browser_picker/mod.rs +++ /dev/null @@ -1,345 +0,0 @@ -//! An unprivileged Tauri child webview. The workbench, not the guest, owns its controls. -mod guest; -mod snapshot; -use crate::state::AppState; -use ide_core::{CancellationToken, IdeError, IdeResult, RequestId}; -use serde::{Deserialize, Serialize}; -pub use snapshot::InspectedElement; -use snapshot::Selection; -use specta::Type; -use std::{ - cell::Cell, - cell::RefCell, - collections::HashMap, - sync::{ - Arc, - atomic::{AtomicBool, AtomicU64, Ordering}, - }, -}; -use tauri::{Manager, Url, Window}; -use tokio::sync::oneshot; - -#[derive(Deserialize, Type)] -#[serde(tag = "type", rename_all = "camelCase")] -pub enum BrowserAction { - Navigate { url: String }, - Back, - Forward, - Reload, - Inspect, - Cancel, - Layout { bounds: Option }, - Status, -} - -/// CSS pixels measured from the top left of the workbench viewport, along with the viewport size. -#[derive(Clone, Copy, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct BrowserBounds { - x: f64, - y: f64, - width: f64, - height: f64, - viewport_width: f64, - viewport_height: f64, -} - -#[derive(Serialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct BrowserStatus { - url: String, - can_back: bool, - can_forward: bool, - inspecting: bool, - element: Option, -} - -fn local_url(value: &str) -> IdeResult { - Url::parse(value) - .ok() - .filter(|u| { - value.len() <= 4096 - && matches!(u.scheme(), "http" | "https") - && u.username().is_empty() - && u.password().is_none() - && ide_host::ops::web::is_loopback(u) - }) - .ok_or_else(|| IdeError::invalid("Enter a loopback HTTP or HTTPS URL without credentials")) -} - -fn same_origin(origin: &Url, value: &str) -> bool { - local_url(value).is_ok_and(|next| next.origin() == origin.origin()) -} - -const GUEST_PREFIX: &str = "browser-guest-"; - -pub(crate) fn is_guest(label: &str) -> bool { - label.starts_with(GUEST_PREFIX) -} - -#[derive(Default)] -struct Document { - generation: AtomicU64, - loaded: AtomicBool, - armed: AtomicBool, -} - -fn unavailable(e: impl std::fmt::Display) -> IdeError { - IdeError::unavailable(format!("Browser: {e}")) -} - -struct Panel { - session: RequestId, - cancel: CancellationToken, - origin: Url, - project: Arc, - view: guest::Surface, - document: Arc, -} - -thread_local! { - // GTK, AppKit and WebView2 require these objects to be used and destroyed on the UI thread. - static PANELS: RefCell> = RefCell::new(HashMap::new()); -} - -async fn on_ui( - window: Window, - f: impl FnOnce(&Window) -> IdeResult + Send + 'static, -) -> IdeResult { - let (tx, rx) = oneshot::channel(); - let owner = window.clone(); - window - .run_on_main_thread(move || { - let _ = tx.send(f(&owner)); - }) - .map_err(unavailable)?; - rx.await.map_err(unavailable)? -} - -fn local_project(window: &Window) -> IdeResult> { - let state = window.state::(); - if state.remote_dev.get(AppState::owner_window(window.label())).is_some() { - return Err(IdeError::unavailable("The browser requires a trusted local project")); - } - let project = state.project(window.label())?; - project.require_trust()?; - Ok(project) -} - -pub async fn open(window: Window, url: String, session: RequestId) -> IdeResult<()> { - let origin = local_url(&url)?; - let project = local_project(&window)?; - let state = window.state::(); - let cancel = state.begin_project_request(window.label(), session); - let token = cancel.clone(); - let opened = on_ui(window.clone(), move |w| { - if token.is_cancelled() || !Arc::ptr_eq(&project, &local_project(w)?) { - return Err(IdeError::cancelled()); - } - let document = Arc::new(Document::default()); - let builder = tauri::webview::WebviewBuilder::new( - format!("{GUEST_PREFIX}{}-{}", w.label(), session.0), - tauri::WebviewUrl::External(origin.clone()), - ) - .incognito(true) - .general_autofill_enabled(false) - .devtools(false) - .disable_drag_drop_handler() - .on_new_window(|_, _| tauri::webview::NewWindowResponse::Deny) - .on_download(|_, _| false) - .on_permission_request(|_, _| tauri::webview::PermissionResponse::Deny) - .initialization_script(include_str!("element.js")) - .on_navigation({ - let origin = origin.clone(); - let token = token.clone(); - move |target| !token.is_cancelled() && same_origin(&origin, target.as_str()) - }) - .on_page_load({ - let doc = document.clone(); - let origin = origin.clone(); - let token = token.clone(); - move |_, payload| { - let url = payload.url().as_str(); - if !same_origin(&origin, url) && !url.is_empty() && url != "about:blank" { - token.cancel(); - return; - } - if matches!(payload.event(), tauri::webview::PageLoadEvent::Started) { - doc.generation.fetch_add(1, Ordering::SeqCst); - doc.armed.store(false, Ordering::SeqCst); - doc.loaded.store(false, Ordering::SeqCst); - } else if same_origin(&origin, url) { - doc.loaded.store(true, Ordering::SeqCst); - } - } - }); - #[cfg(target_os = "macos")] - let builder = builder.allow_link_preview(false); - let view = guest::Surface::new(w, builder)?; - let panel = Panel { session, cancel: token, origin, project, view, document }; - if let Some(old) = PANELS.with_borrow_mut(|panels| panels.insert(w.label().to_owned(), panel)) { - old.cancel.cancel(); - } - Ok(()) - }) - .await; - if opened.is_err() { - state.end_request(session); - return opened; - } - let owner = window.clone(); - tauri::async_runtime::spawn(async move { - cancel.cancelled().await; - let result = on_ui(owner.clone(), move |w| { - PANELS.with_borrow_mut(|p| { - if p.get(w.label()).is_some_and(|v| v.session == session) { - p.remove(w.label()); - } - }); - Ok(()) - }) - .await; - if let Err(error) = result { - tracing::debug!(?error, "browser owner closed"); - } - owner.state::().end_request(session); - }); - Ok(()) -} - -pub fn forget(label: &str) { - if let Some(panel) = PANELS.with_borrow_mut(|panels| panels.remove(label)) { - panel.cancel.cancel(); - } -} - -pub async fn control(window: Window, session: RequestId, action: BrowserAction) -> IdeResult { - let (mut status, selection, token, project, document, generation) = on_ui(window.clone(), move |w| { - PANELS.with_borrow(|p| { - let p = p - .get(w.label()) - .filter(|p| p.session == session && !p.cancel.is_cancelled()) - .ok_or_else(IdeError::cancelled)?; - if !Arc::ptr_eq(&p.project, &local_project(w)?) { - return Err(IdeError::cancelled()); - } - let view = &p.view.webview; - let mut selection = None; - // WKWebView has no URL before its first commit; don't ask Wry to unwrap it. - let generation = p.document.generation.load(Ordering::SeqCst); - let url = if p.document.loaded.load(Ordering::SeqCst) { - view.url().map_err(unavailable)?.to_string() - } else { - String::new() - }; - let local = same_origin(&p.origin, &url); - if !local && !url.is_empty() && url != "about:blank" { - p.cancel.cancel(); - return Err(IdeError::unavailable("Browser left the allowed local origin")); - } - match action { - BrowserAction::Navigate { url } => { - if !same_origin(&p.origin, &url) { - return Err(IdeError::invalid("Close this page before opening another origin")); - } - view.navigate(local_url(&url)?).map_err(unavailable)?; - } - BrowserAction::Back => view.eval("history.back()").map_err(unavailable)?, - BrowserAction::Forward => view.eval("history.forward()").map_err(unavailable)?, - BrowserAction::Reload => view.reload().map_err(unavailable)?, - BrowserAction::Layout { bounds } => p.view.layout(w, bounds)?, - BrowserAction::Inspect | BrowserAction::Cancel => { - let arm = matches!(action, BrowserAction::Inspect); - if arm && !local { - return Err(IdeError::unavailable("The local page has not loaded")); - } - view.eval(if arm { - "window.__openideaInspect?.(true)" - } else { - "window.__openideaInspect?.(false)" - }) - .map_err(unavailable)?; - p.document.armed.store(arm, Ordering::SeqCst); - } - BrowserAction::Status if local && p.document.armed.load(Ordering::SeqCst) => { - let (tx, rx) = oneshot::channel(); - let reply = Cell::new(Some(tx)); - // Read only the gesture-gated main-frame slot through this webview's callback. - // The page cannot invoke an IDE command or emit an IDE event. - view.eval_with_callback("window.__openideaPickedElement ?? null", move |value| { - if let Some(tx) = reply.take() { - let _ = tx.send(value); - } - }) - .map_err(unavailable)?; - selection = Some(rx); - } - BrowserAction::Status => {} - } - let (can_back, can_forward) = p.view.history()?; - let status = BrowserStatus { - url: if local { url } else { p.origin.to_string() }, - can_back, - can_forward, - inspecting: p.document.armed.load(Ordering::SeqCst), - element: None, - }; - Ok((status, selection, p.cancel.clone(), p.project.clone(), p.document.clone(), generation)) - }) - }) - .await?; - if let Some(rx) = selection { - let value = tokio::select! { - biased; - _ = token.cancelled() => return Err(IdeError::cancelled()), - value = tokio::time::timeout(std::time::Duration::from_secs(3), rx) => value.map_err(unavailable)?.map_err(unavailable)?, - }; - if token.is_cancelled() || !Arc::ptr_eq(&project, &local_project(&window)?) { - return Err(IdeError::cancelled()); - } - if document.generation.load(Ordering::SeqCst) != generation { - status.inspecting = false; - return Ok(status); - } - let json: Option = serde_json::from_str(&value).map_err(unavailable)?; - if let Some(json) = json { - status.inspecting = false; - document.armed.store(false, Ordering::SeqCst); - if json == "cancel" { - return Ok(status); - } - if json.len() > 8192 { - return Err(IdeError::invalid("Element selection too large")); - } - status.element = Some(serde_json::from_str::(&json).map_err(unavailable)?.preview()?); - } - } - Ok(status) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn pins_scheme_host_and_port_and_rejects_credentials() { - let origin = local_url("http://127.0.0.1:3000/a?key=private").unwrap(); - assert!(same_origin(&origin, "http://127.0.0.1:3000/b#x")); - assert!(local_url("http://localhost/").is_ok()); - assert!(local_url("https://[::1]/").is_ok()); - for remote in [ - "http://localhost.example.org", - "http://0.0.0.0", - "file:///tmp/test", - "tauri://localhost", - "http://user@localhost", - "https://example.org", - ] { - assert!(local_url(remote).is_err(), "{remote}"); - } - for target in - ["http://127.0.0.1:3001", "http://localhost:3000", "https://127.0.0.1:3000", "http://u:p@127.0.0.1:3000"] - { - assert!(!same_origin(&origin, target), "{target}"); - } - } -} diff --git a/src-tauri/src/browser_picker/snapshot.rs b/src-tauri/src/browser_picker/snapshot.rs deleted file mode 100644 index ead6d456b9..0000000000 --- a/src-tauri/src/browser_picker/snapshot.rs +++ /dev/null @@ -1,149 +0,0 @@ -use ide_core::{IdeError, IdeResult}; -use serde::{Deserialize, Serialize}; -use specta::Type; - -/// Page text, URLs, classes, attribute values and form contents never enter the snapshot. -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub(super) struct Selection { - path: Vec, - disabled: bool, - hidden: bool, - aria_disabled: bool, - display: String, - position: String, - visibility: String, - pointer_events: String, -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct Step { - tag: String, - index: u16, -} - -#[derive(Debug, Serialize, Type)] -pub struct InspectedElement { - pub selector: String, - pub html: String, - pub styles: String, -} - -impl Selection { - pub(super) fn preview(&self) -> IdeResult { - let invalid = || IdeError::invalid("The page returned an unsupported element selection"); - if self.path.is_empty() || self.path.len() > 8 { - return Err(invalid()); - } - let mut parts = Vec::with_capacity(self.path.len()); - for step in &self.path { - if step.index == 0 - || step.tag.len() > 64 - || !step.tag.starts_with(|c: char| c.is_ascii_alphabetic()) - || !step.tag.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') - { - return Err(invalid()); - } - parts.push(format!("{}:nth-of-type({})", step.tag, step.index)); - } - let tag = &self.path.last().ok_or_else(invalid)?.tag; - let mut html = format!("<{tag}"); - if self.disabled { - html.push_str(" disabled"); - } - if self.hidden { - html.push_str(" hidden"); - } - if self.aria_disabled { - html.push_str(" aria-disabled=\"true\""); - } - html.push('>'); - let mut styles = Vec::new(); - for (name, value) in [ - ("display", &self.display), - ("position", &self.position), - ("visibility", &self.visibility), - ("pointer-events", &self.pointer_events), - ] { - if value.is_empty() - || value.len() > 48 - || !value.bytes().all(|c| c.is_ascii_alphabetic() || matches!(c, b' ' | b'-')) - { - return Err(invalid()); - } - // CSSOM keywords only. A page can replace its JS getters; arbitrary words must - // not become agent prompt text. Omit new engine-specific values until recognized. - let keywords = match name { - "display" => { - "none contents block inline run-in flow flow-root flex grid grid-lanes table list-item inline-block inline-flex inline-grid inline-table table-row-group table-header-group table-footer-group table-row table-cell table-column-group table-column table-caption ruby ruby-base ruby-text ruby-base-container ruby-text-container -webkit-box -webkit-inline-box" - } - "position" => "static relative absolute fixed sticky -webkit-sticky", - "visibility" => "visible hidden collapse", - _ => "auto none visiblePainted visibleFill visibleStroke visible painted fill stroke all bounding-box", - }; - let known = |token: &str| keywords.split(' ').any(|word| word.eq_ignore_ascii_case(token)); - let recognized = if name == "display" { - value.split(' ').take(4).count() <= 3 && value.split(' ').all(known) - } else { - known(value) - }; - if recognized { - styles.push(format!("{name}: {value};")); - } - } - Ok(InspectedElement { selector: parts.join(" > "), html, styles: styles.join("\n") }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::{Value, json}; - - fn selection() -> Value { - json!({"path": [{"tag":"main","index":1},{"tag":"button","index":2}], "disabled":true, - "hidden":false, "ariaDisabled":true, "display":"inline-flex", "position":"static", - "visibility":"visible", "pointerEvents":"none"}) - } - - #[test] - fn builds_the_preview_only_from_structured_fields() { - let capture: Selection = serde_json::from_value(selection()).unwrap(); - let preview = capture.preview().unwrap(); - assert_eq!(preview.selector, "main:nth-of-type(1) > button:nth-of-type(2)"); - assert_eq!(preview.html, " - - - - )} - - ); -} diff --git a/src/features/web/Web.module.css b/src/features/web/Web.module.css index 63a47afc30..061d78660b 100644 --- a/src/features/web/Web.module.css +++ b/src/features/web/Web.module.css @@ -34,103 +34,3 @@ color: var(--fg-muted); font-family: var(--font-ui); } -.inspector { - flex: 1; - height: 100%; - box-sizing: border-box; - display: flex; - flex-direction: column; - min-width: 0; - overflow: hidden; - font-family: var(--font-ui); -} -.toolbar { - display: flex; - align-items: center; - gap: var(--space-1); - padding: 4px 8px; - border-bottom: 1px solid var(--border); -} -.address { - flex: 1; - min-width: 0; -} -.hint { - margin: 0; - padding: 6px 10px; - color: var(--fg-muted); - font-size: var(--fs-small); -} -.viewport { - flex: 1 1 100px; - min-height: 80px; - background: var(--bg-editor); -} -.details { - flex: none; - display: flex; - flex-direction: column; - border-top: 1px solid var(--border); - background: var(--bg-editor); -} -.detailsHead { - display: flex; - align-items: center; - gap: var(--space-1-5); - height: 28px; - padding: 0 4px 0 10px; - border-bottom: 1px solid var(--border); - background: var(--bg-elev); - color: var(--fg-strong); -} -.detailsTitle { - margin: 0; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-size: var(--fs-small); - font-weight: 600; -} -.detailsDismiss { - margin-left: auto; -} -.detailsBody { - display: flex; - flex-direction: column; - gap: var(--space-1-5); - max-height: 180px; - padding: 8px 10px; - overflow: auto; -} -.selector { - color: var(--fg-secondary); - font-family: var(--font-mono); - font-size: var(--fs-tiny); - line-height: 1.4; - overflow-wrap: anywhere; - user-select: text; -} -.code { - margin: 0; - padding: 6px 8px; - border-radius: var(--radius-control); - background: var(--bg-elev); - box-shadow: inset 0 0 0 1px var(--border); - color: var(--fg-editor, var(--fg)); - font-family: var(--font-mono); - font-size: var(--fs-small); - line-height: 1.45; - white-space: pre-wrap; - overflow-wrap: anywhere; - user-select: text; -} -.detailsActions { - display: flex; - align-items: center; - justify-content: flex-end; - gap: var(--space-1-5); - padding: 6px 10px; - border-top: 1px solid var(--border); - background: var(--bg-elev); -} diff --git a/src/features/web/browserSession.ts b/src/features/web/browserSession.ts deleted file mode 100644 index 06ff023995..0000000000 --- a/src/features/web/browserSession.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { create } from "zustand"; -import { - call, - commands, - isCancelled, - nextRequestId, - type BrowserAction, - type BrowserBounds, - type BrowserStatus, - type InspectedElement, - type RequestId, -} from "@/platform/ipc"; -import { useProject } from "@/platform/project"; -import { useRemote } from "@/platform/remote"; - -interface Session { - id: RequestId | null; - ready: boolean; - location: BrowserStatus | null; - element: InspectedElement | null; - error: string; -} -const empty: Session = { id: null, ready: false, location: null, element: null, error: "" }; -export const useBrowserSession = create(() => empty); -let queue = Promise.resolve(); -let pendingLayout: { id: RequestId; bounds: BrowserBounds | null } | null = null; - -function message(e: unknown) { - return e instanceof Error ? e.message : String(e); -} - -export function closeBrowser() { - const { id } = useBrowserSession.getState(); - useBrowserSession.setState(empty); - queue = Promise.resolve(); - pendingLayout = null; - if (id !== null) - void commands.cancelRequest(id).catch((e: unknown) => { - if (!isCancelled(e)) useBrowserSession.setState({ error: message(e) }); - }); -} - -export function watchBrowserOwner() { - const project = useProject.subscribe((s, before) => { - if (!s.project?.trusted || s.project.root !== before.project?.root) closeBrowser(); - }); - const remote = useRemote.subscribe((s) => { - if (s.session) closeBrowser(); - }); - window.addEventListener("pagehide", closeBrowser); - return () => { - project(); - remote(); - window.removeEventListener("pagehide", closeBrowser); - closeBrowser(); - }; -} - -export async function visit(url: string) { - const { id } = useBrowserSession.getState(); - if (id !== null) { - await control(id, { type: "navigate", url }); - return; - } - const session = nextRequestId(); - useBrowserSession.setState({ ...empty, id: session }); - try { - await call(commands.webBrowserOpen(url, session)); - if (useBrowserSession.getState().id !== session) return; - useBrowserSession.setState({ ready: true }); - await control(session, { type: "status" }); - } catch (e) { - if (useBrowserSession.getState().id === session) { - useBrowserSession.setState({ ...empty, error: isCancelled(e) ? "" : message(e) }); - } - } -} - -// Serialize layout (including hide), toolbar actions and reads. A late reply cannot affect a new project/session. -export function control(id: RequestId, action: BrowserAction): Promise { - if (action.type === "layout" && pendingLayout?.id === id) { - pendingLayout.bounds = action.bounds; - return queue; - } - const layoutEntry = action.type === "layout" ? { id, bounds: action.bounds } : null; - pendingLayout = layoutEntry; - queue = queue.then(async () => { - if (layoutEntry && pendingLayout === layoutEntry) pendingLayout = null; - const current = useBrowserSession.getState; - if (current().id !== id || !current().ready) return; - const effective: BrowserAction = layoutEntry ? { type: "layout", bounds: layoutEntry.bounds } : action; - try { - const location = await call(commands.webBrowserControl(id, effective)); - if (current().id !== id) return; - const before = current().location; - if ( - location.element || - before?.url !== location.url || - before.canBack !== location.canBack || - before.canForward !== location.canForward || - before.inspecting !== location.inspecting || - !["status", "layout"].includes(effective.type) - ) { - useBrowserSession.setState({ - location, - error: "", - element: - location.element ?? - (before?.url === location.url && ["status", "layout", "cancel"].includes(effective.type) - ? current().element - : null), - }); - } - } catch (e) { - if (current().id !== id) return; - if (isCancelled(e)) closeBrowser(); - else useBrowserSession.setState({ error: message(e) }); - } - }); - return queue; -} diff --git a/src/features/web/index.ts b/src/features/web/index.ts index 1c9c30ccf4..67dccbe41a 100644 --- a/src/features/web/index.ts +++ b/src/features/web/index.ts @@ -15,8 +15,6 @@ import { registerEditorBanner, registerMenuGroup, registerTextEditorWrapper, - registerToolWindow, - toolWindowService, useTextEditorWrappers, } from "@/workbench/contributions"; import { activeEditor, registerEditorContribution } from "@/editor/api"; @@ -33,7 +31,6 @@ import { useWebPreview, } from "./browsers"; import { tx } from "@/platform/i18n"; -import { closeBrowser, useBrowserSession, visit, watchBrowserOwner } from "./browserSession"; interface OpenArg { path?: string; @@ -81,20 +78,9 @@ function browserMenu(path: string): MenuItem { export function activate(): () => void { void loadBrowsers(); const disposers = [ - watchBrowserOwner(), // Open tabs gain or lose the browser bar and preview when File Types change. onFileTypesChange(() => useTextEditorWrappers.setState((w) => ({ wrappers: new Map(w.wrappers) }))), registerEditorBanner(djangoTemplateBanner), - registerToolWindow({ - id: "browser", - title: "Browser", - icon: "toolwindow-web", - anchor: "right", - order: 7, - stripe: "onUse", - sessionContent: true, - component: lazyComponent(() => import("./BrowserView").then((m) => m.BrowserView)), - }), registerEditorContribution({ id: "web.djangoContent", order: 57, extensions: djangoContentWatcher }), registerTextEditorWrapper({ id: "web.html", @@ -102,21 +88,6 @@ export function activate(): () => void { component: lazyComponent(() => import("./WebEditor").then((m) => m.WebEditor)), }), registerActions([ - { - id: "web.openLocalBrowser", - title: "Open Local Browser", - category: "View", - icon: "web", - when: "projectLocal", - keywords: ["browser", "element", "inspect", "agent", "DOM", "CSS"], - run: async ({ arg }) => { - toolWindowService().show("browser", true); - if (typeof arg !== "string" || !URL.canParse(arg)) return; - const previous = useBrowserSession.getState().location; - if (previous && new URL(previous.url).origin !== new URL(arg).origin) closeBrowser(); - await visit(arg); - }, - }, { id: "web.openInBrowser", title: "Open in Browser", diff --git a/src/platform/auxWindow.test.ts b/src/platform/auxWindow.test.ts index aa9e5f4e7a..c4b0043eef 100644 --- a/src/platform/auxWindow.test.ts +++ b/src/platform/auxWindow.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest"; import { auxiliaryWindow } from "./auxWindow"; import capability from "../../src-tauri/capabilities/default.json"; import bridgeCapability from "../../src-tauri/capabilities/e2e.json"; -import browserCapability from "../../src-tauri/capabilities/browser.json"; describe("auxiliaryWindow", () => { it("reads the kind and parent from the label", () => { @@ -20,27 +19,13 @@ describe("auxiliaryWindow", () => { it.each(["settings", "comparison", "diff", "editor", "deployment"])( "grants %s windows permission to close", (kind) => { - expect(capability.webviews).toContain(`${kind}-*`); - expect(bridgeCapability.webviews).toContain(`${kind}-*`); + expect(capability.windows).toContain(`${kind}-*`); + expect(bridgeCapability.windows).toContain(`${kind}-*`); expect(capability.permissions).toContain("core:window:allow-close"); expect(capability.permissions).toContain("core:window:allow-destroy"); }, ); - it("does not confer host privileges on the Browser webview sharing its window", () => { - for (const cap of [capability, bridgeCapability, browserCapability]) { - expect(cap).not.toHaveProperty("windows"); - } - const guest = "browser-guest-project-2-12"; - const grants = [capability, bridgeCapability, browserCapability].filter((cap) => - cap.webviews.some((pattern) => - pattern.endsWith("*") ? guest.startsWith(pattern.slice(0, -1)) : guest === pattern, - ), - ); - expect(grants.map((cap) => cap.identifier)).toEqual(["browser"]); - expect(grants.flatMap((cap) => cap.permissions)).toEqual([]); - }); - it("leaves project windows and malformed labels alone", () => { for (const label of ["", "main", "project-1", "settings-", "comparison-main", "comparison-main-x"]) { expect(auxiliaryWindow(label)).toBeNull(); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 1aa7c83382..045d59fa08 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1572,16 +1572,6 @@ "Run All": "Run All", "Restart All": "Restart All", "Stop All": "Stop All", - "Open Local Browser": "Open Local Browser", - "Open in Browser Tool Window": "Open in Browser Tool Window", - "Local page URL": "Local page URL", - "Enter a localhost URL and press Enter.": "Enter a localhost URL and press Enter.", - "Inspect Element": "Inspect Element", - "Click an element to inspect it": "Click an element to inspect it", - "Element inspection requires a trusted local project.": "Element inspection requires a trusted local project.", - "Selected element": "Selected element", - "Add to Agent Draft": "Add to Agent Draft", - "The agent composer is unavailable.": "The agent composer is unavailable.", "Open in Browser": "Open in Browser", "Build Module": "Build Module", "Compile File": "Compile File", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index daa65fa6e4..5fa41fa919 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2539,16 +2539,6 @@ "Open as Text": "作为文本打开", "Open console for tool output": "为工具输出打开控制台", "Open documents": "打开的文档", - "Open Local Browser": "打开本地浏览器", - "Open in Browser Tool Window": "在浏览器工具窗口中打开", - "Local page URL": "本地页面地址", - "Enter a localhost URL and press Enter.": "输入本机地址并按 Enter。", - "Inspect Element": "检查元素", - "Click an element to inspect it": "单击要检查的元素", - "Element inspection requires a trusted local project.": "检查元素需要受信任的本地项目。", - "Selected element": "选中的元素", - "Add to Agent Draft": "添加到智能体草稿", - "The agent composer is unavailable.": "智能体消息编辑器不可用。", "Open in Browser": "在浏览器中打开", "Open in Find Tool Window": "在“查找”工具窗口中打开", "Open in Find Window": "在查找窗口中打开", diff --git a/src/ui/Tooltip.test.tsx b/src/ui/Tooltip.test.tsx index 99e313dabd..bf11767a30 100644 --- a/src/ui/Tooltip.test.tsx +++ b/src/ui/Tooltip.test.tsx @@ -184,59 +184,3 @@ it("shows a tab's cut-off title whole, with the tab's own tooltip beside it", () cleanup(); vi.useRealTimers(); }); - -it("flips above an anchor when the default bottom tooltip would overlap a native surface", async () => { - vi.useFakeTimers(); - render( - <> - - -
- , - ); - const button = screen.getByRole("button", { name: "Close" }); - const surface = screen.getByTestId("surface"); - const rect = (x: number, y: number, w: number, h: number): DOMRect => - ({ - x, - y, - left: x, - top: y, - right: x + w, - bottom: y + h, - width: w, - height: h, - toJSON: () => ({}), - }) as DOMRect; - const origClientW = Object.getOwnPropertyDescriptor(document.documentElement, "clientWidth"); - const origClientH = Object.getOwnPropertyDescriptor(document.documentElement, "clientHeight"); - Object.defineProperty(document.documentElement, "clientWidth", { configurable: true, value: 1024 }); - Object.defineProperty(document.documentElement, "clientHeight", { configurable: true, value: 768 }); - const spy = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) { - if (this === button) return rect(300, 60, 24, 24); - if (this === surface) return rect(100, 90, 300, 400); - if (this.getAttribute("role") === "tooltip") return rect(0, 0, 60, 24); - return rect(0, 0, 0, 0); - }); - - fireEvent.pointerOver(button); - await act(async () => { - vi.advanceTimersByTime(TOOLTIP_DELAY); - await Promise.resolve(); - await Promise.resolve(); - await Promise.resolve(); - }); - const tip = screen.getByRole("tooltip"); - - // Placed above the button (y = 60 - 6 - 24 = 30), clear of the native surface starting at y = 90. - expect(Number.parseFloat(tip.style.top)).toBeLessThanOrEqual(60 - 24); - spy.mockRestore(); - if (origClientW) Object.defineProperty(document.documentElement, "clientWidth", origClientW); - else Reflect.deleteProperty(document.documentElement, "clientWidth"); - if (origClientH) Object.defineProperty(document.documentElement, "clientHeight", origClientH); - else Reflect.deleteProperty(document.documentElement, "clientHeight"); - cleanup(); - vi.useRealTimers(); -}); diff --git a/src/ui/Tooltip.tsx b/src/ui/Tooltip.tsx index 57bf22ff91..e6c477cbb8 100644 --- a/src/ui/Tooltip.tsx +++ b/src/ui/Tooltip.tsx @@ -9,7 +9,7 @@ import { useEffect, useRef, useState } from "react"; import clsx from "clsx"; import { createPortal } from "react-dom"; -import { computePosition, flip, offset, shift, type Placement } from "@floating-ui/react-dom"; +import { computePosition, flip, offset, shift } from "@floating-ui/react-dom"; import styles from "./Tooltip.module.css"; import { tx } from "@/platform/i18n"; @@ -147,52 +147,17 @@ export function TooltipHost() { const tip = tipRef.current; if (!anchor || !tip) return; let cancelled = false; - const preferred: Placement = shown.stripe === "right" ? "left" : shown.stripe === "left" ? "right" : "bottom"; - const surfaces: DOMRect[] = []; - for (const el of document.querySelectorAll("[data-native-surface]")) { - const rect = el.getBoundingClientRect(); - if (rect.width > 0 && rect.height > 0) surfaces.push(rect); - } - const overlapsSurface = (x: number, y: number, width: number, height: number) => - surfaces.some((s) => x < s.right && x + width > s.left && y < s.bottom && y + height > s.top); - void (async () => { - let pos = await computePosition(anchor, tip, { - placement: preferred, - strategy: "fixed", - middleware: [ - offset(6), - flip({ padding: 6, ...(shown.stripe && { fallbackAxisSideDirection: "end" }) }), - shift({ padding: 6 }), - ], - }); - // Native child webviews paint above HTML; move the tooltip clear of them when possible. - if (surfaces.length) { - const { width, height } = tip.getBoundingClientRect(); - if (width > 0 && height > 0 && overlapsSurface(pos.x, pos.y, width, height)) { - const candidates: Placement[] = shown.stripe - ? ["top-end", "bottom-end", "top-start", "bottom-start", "top", "bottom"] - : ["top", "top-end", "top-start", "left", "right"]; - for (const placement of candidates) { - // oxlint-disable-next-line no-await-in-loop -- placements are tried in order; the first clear one wins - const next = await computePosition(anchor, tip, { - placement, - strategy: "fixed", - middleware: [offset(6), shift({ padding: 6 })], - }); - const inViewport = - next.x >= 0 && - next.y >= 0 && - next.x + width <= window.innerWidth && - next.y + height <= window.innerHeight; - if (inViewport && !overlapsSurface(next.x, next.y, width, height)) { - pos = next; - break; - } - } - } - } - if (!cancelled) setShown((s) => (s ? { ...s, x: pos.x, y: pos.y, placed: true } : s)); - })(); + void computePosition(anchor, tip, { + placement: shown.stripe === "right" ? "left" : shown.stripe === "left" ? "right" : "bottom", + strategy: "fixed", + middleware: [ + offset(6), + flip({ padding: 6, ...(shown.stripe && { fallbackAxisSideDirection: "end" }) }), + shift({ padding: 6 }), + ], + }).then(({ x, y }) => { + if (!cancelled) setShown((s) => (s ? { ...s, x, y, placed: true } : s)); + }); return () => { cancelled = true; }; diff --git a/src/ui/expui/toolwindows/web.svg b/src/ui/expui/toolwindows/web.svg deleted file mode 100644 index 897fab3922..0000000000 --- a/src/ui/expui/toolwindows/web.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ui/expui/toolwindows/web@20x20.svg b/src/ui/expui/toolwindows/web@20x20.svg deleted file mode 100644 index 7db231d00f..0000000000 --- a/src/ui/expui/toolwindows/web@20x20.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ui/expui/toolwindows/web@20x20_dark.svg b/src/ui/expui/toolwindows/web@20x20_dark.svg deleted file mode 100644 index 6c5820aa20..0000000000 --- a/src/ui/expui/toolwindows/web@20x20_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ui/expui/toolwindows/web_dark.svg b/src/ui/expui/toolwindows/web_dark.svg deleted file mode 100644 index 0ca6194ab1..0000000000 --- a/src/ui/expui/toolwindows/web_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index a2eff187fa..009ea97761 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -250,7 +250,6 @@ const ICONS = { "toolwindow-inspection": "toolwindows/toolWindowInspection", "toolwindow-duplicates": "toolwindows/toolWindowDuplicates", "toolwindow-changes": "toolwindows/changes", - "toolwindow-web": "toolwindows/web", "toolwindow-database": "openidea/toolwindows/database", "toolwindow-agents": "openidea/toolwindows/agents", "toolwindow-graphql": "openidea/toolwindows/graphql", diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index cd13c516f3..4ea297f46a 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -1029,22 +1029,6 @@ export const maybeCommitService = (): CommitService | undefined => commitService */ export type AgentContext = { kind: "block"; info: string; text: string } | { kind: "files"; paths: string[] }; -type DraftBlock = Extract; -let appendDraftBlock: ((block: DraftBlock) => void) | undefined; - -/** Shows the current composer after appending context requested in another tool window. */ -export function provideAgentDraftAppender(append: (block: DraftBlock) => void): () => void { - appendDraftBlock = append; - return () => { - if (appendDraftBlock === append) appendDraftBlock = undefined; - }; -} -export function appendAgentDraftBlock(block: DraftBlock): boolean { - if (!appendDraftBlock) return false; - appendDraftBlock(block); - return true; -} - export interface AgentContextSource { /** Typed after `@`. */ id: string;