Compare commits

...
Author SHA1 Message Date
Deng Liu 652740a04d feat(browser): keep local navigation and inspection in a workbench panel
Host a private Wry child in the Browser tool window. Preserve its page and native history across dock visibility changes, scope navigation to the trusted local origin, and keep reviewed element context in the Agent draft.

Copilot-Session: 15919368-07bf-4a19-a395-acc76294f5da
2026-11-24 23:42:48 -05:00
Aditya Aggarwal 2b2ff678a6 feat(browser): attach an inspected local element to an agent draft 2026-11-24 23:10:32 -05:00
23 changed files with 1411 additions and 3 deletions

No files matched your search

Generated
+1
View File
@@ -6762,6 +6762,7 @@ dependencies = [
"webview2-com",
"windows",
"windows-sys 0.61.2",
"wry",
]
[[package]]
+1 -1
View File
@@ -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).
fn is_loopback(url: &reqwest::Url) -> bool {
pub 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::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
}
+6
View File
@@ -5,6 +5,12 @@ 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.
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 |
+6
View File
@@ -5,6 +5,12 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
编辑器的行为和默认快捷键沿用 IntelliJ IDEA。下文的快捷键在 macOS 上是 **macOS** 键位映射的默认值,在 Windows 和 Linux 上是 **Windows** 键位映射的默认值;任何一个都可以在 **设置 › 按键映射** 中修改(见 [键位映射](/zh/guide/keymap))。所有命令也都能在 **查找操作**(`⇧⌘A` / `Ctrl+Shift+A`)里找到。
## 浏览本地开发服务器
在受信任的本地项目中,选择**查找操作 › 打开本地浏览器**。输入指向本机回环地址的 HTTP 或 HTTPS 网址,点击**打开**。可以直接在面板中点击链接、后退、前进和重新加载。隐藏面板会保留页面和浏览历史;点击**关闭**才会结束会话。浏览范围限于原来的源;如需切换开发服务器或端口,请先关闭会话,再打开新地址。
点击**检查元素**,然后在页面中点选元素。确认选择器、起始标签和样式后,可将其添加到 Agent 草稿,不会自动发送。在页面中按 **Escape** 可退出检查并继续浏览。
## 光标与选区
| 操作 | macOS | Windows / Linux |
+222
View File
@@ -0,0 +1,222 @@
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: '<button aria-disabled="true">',
styles: "display: inline-flex;\nposition: relative;\nvisibility: visible;\npointer-events: none;",
};
test("a trusted gesture captures structure without page text or form values", async ({ page }) => {
await page.addInitScript({
content: `window.ipc = { postMessage(value) { window.lastSignal = value; } };\n${script}`,
});
await page.route("http://localhost:3000/**", (route) =>
route.fulfill({
contentType: "text/html",
body: '<main><input type="password" value="fixture-password"><button>First</button><button disabled data-note="fixture-note" style="display:inline-flex">Fixture customer</button></main><iframe srcdoc="<p>Frame</p>"></iframe>',
}),
);
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(await page.evaluate("window.lastSignal")).toBe("picked");
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/);
});
async function openBrowser(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(actions)).executeAction("web.inspectLocalPage");
});
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.getByRole("region", { name: "Browser" }).getByRole("button", { name: "Open", exact: true }).click();
}
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 page.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(inspect).toBeEnabled();
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);
});
+2
View File
@@ -15,6 +15,8 @@ dunce.workspace = true
[dependencies]
tauri = { version = "2", features = [] }
# The local browser is a raw child WebView without the desktop command bridge.
wry = "0.57"
tauri-plugin-opener = "2"
tauri-plugin-notification = "2.8.1"
tauri-plugin-dialog = { version = "2", default-features = false, features = ["xdg-portal"] }
+122
View File
@@ -0,0 +1,122 @@
// Runs at document start in the unprivileged picker. Only a physical click can fill the slot.
// The host reads the slot after a wake-up and validates its shape before showing the preview.
(() => {
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 post = window.ipc.postMessage.bind(window.ipc);
Object.defineProperty(window, "__openideaPickedElement", { get: () => picked });
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;
post("picked");
},
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();
post("cancel");
}
},
true,
);
})();
+127
View File
@@ -0,0 +1,127 @@
//! The unprivileged guest has no access to the workbench's Tauri commands or custom protocols.
use super::{BrowserBounds, unavailable};
use ide_core::IdeResult;
use tauri::Window;
use wry::{NewWindowResponse, PermissionResponse, WebView, WebViewBuilder};
pub(super) enum Signal {
Picked,
Cancel,
}
pub(super) fn builder(
url: &str,
allow_navigation: impl Fn(String) -> bool + 'static,
signal: impl Fn(Signal) + 'static,
) -> WebViewBuilder<'static> {
WebViewBuilder::new()
.with_incognito(true)
.with_visible(false)
.with_general_autofill_enabled(false)
.with_devtools(false)
.with_autoplay(false)
.with_clipboard(false)
.with_drag_drop_handler(|_| true)
.with_new_window_req_handler(|_, _| NewWindowResponse::Deny)
.with_download_started_handler(|_, _| false)
.with_permission_handler(|_| PermissionResponse::Deny)
.with_navigation_handler(allow_navigation)
.with_initialization_script(include_str!("element.js"))
// A guest signal can only wake or disarm the picker. The native owner pulls the
// captured data separately from the main frame, checks it and displays it for review.
.with_ipc_handler(move |request| match request.body().as_str() {
"picked" => signal(Signal::Picked),
"cancel" => signal(Signal::Cancel),
_ => {}
})
.with_url(url)
}
pub(super) struct Surface {
pub webview: WebView,
#[cfg(target_os = "linux")]
slot: gtk::Box,
}
impl Surface {
pub fn new(window: &Window, builder: WebViewBuilder<'_>) -> IdeResult<Self> {
#[cfg(not(target_os = "linux"))]
{
Ok(Self { webview: builder.build_as_child(window).map_err(unavailable)? })
}
#[cfg(target_os = "linux")]
{
use gtk::prelude::*;
use wry::WebViewBuilderExtUnix;
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::<gtk::Overlay>() {
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);
let webview = builder.build_gtk(&slot).map_err(unavailable)?;
overlay.add_overlay(&slot);
Ok(Self { webview, slot })
}
}
pub fn layout(&self, window: &Window, bounds: Option<BrowserBounds>) -> IdeResult<()> {
let hide = || {
#[cfg(target_os = "linux")]
gtk::prelude::WidgetExt::hide(&self.slot);
self.webview.set_visible(false).map_err(unavailable)
};
let Some(b) = bounds else {
return hide();
};
let size = window.inner_size().map_err(unavailable)?;
if b.x < 0
|| b.y < 0
|| b.width == 0
|| b.height == 0
|| (b.x as u32).saturating_add(b.width) > size.width + 1
|| (b.y as u32).saturating_add(b.height) > size.height + 1
{
return hide();
}
#[cfg(not(target_os = "linux"))]
self.webview
.set_bounds(wry::Rect {
position: wry::dpi::PhysicalPosition::new(b.x, b.y).into(),
size: wry::dpi::PhysicalSize::new(b.width, b.height).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(b.x) / scale).round() as i32);
self.slot.set_margin_top((f64::from(b.y) / scale).round() as i32);
self.slot.set_size_request(
(f64::from(b.width) / scale).round() as i32,
(f64::from(b.height) / scale).round() as i32,
);
self.slot.show();
}
self.webview.set_visible(true).map_err(unavailable)
}
}
#[cfg(target_os = "linux")]
impl Drop for Surface {
fn drop(&mut self) {
use gtk::prelude::*;
if let Some(parent) = self.slot.parent().and_then(|w| w.downcast::<gtk::Overlay>().ok()) {
parent.remove(&self.slot);
}
}
}
+315
View File
@@ -0,0 +1,315 @@
//! A raw child WebView, not a Tauri webview: the local page has no IDE protocols or commands.
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, rc::Rc, sync::Arc};
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<BrowserBounds> },
Status,
}
/// Physical pixels measured from the top left of the workbench webview.
#[derive(Clone, Copy, Deserialize, Type)]
pub struct BrowserBounds {
x: i32,
y: i32,
width: u32,
height: u32,
}
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BrowserStatus {
url: String,
can_back: bool,
can_forward: bool,
inspecting: bool,
element: Option<InspectedElement>,
}
fn local_url(value: &str) -> IdeResult<Url> {
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())
}
fn unavailable(e: impl std::fmt::Display) -> IdeError {
IdeError::unavailable(format!("Browser: {e}"))
}
struct Panel {
session: RequestId,
cancel: CancellationToken,
origin: Url,
project: Arc<ide_host::Project>,
view: guest::Surface,
loaded: Rc<Cell<bool>>,
armed: Rc<Cell<bool>>,
picked: Rc<Cell<bool>>,
}
thread_local! {
// GTK, AppKit and WebView2 require these objects to be used and destroyed on the UI thread.
static PANELS: RefCell<HashMap<String, Panel>> = RefCell::new(HashMap::new());
}
async fn on_ui<T: Send + 'static>(
window: Window,
f: impl FnOnce(&Window) -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
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<Arc<ide_host::Project>> {
let state = window.state::<AppState>();
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::<AppState>();
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 armed = Rc::new(Cell::new(false));
let picked = Rc::new(Cell::new(false));
let loaded = Rc::new(Cell::new(false));
let builder = guest::builder(
origin.as_str(),
{
let origin = origin.clone();
let token = token.clone();
move |target| !token.is_cancelled() && same_origin(&origin, &target)
},
{
let armed = armed.clone();
let picked = picked.clone();
move |signal| match signal {
guest::Signal::Picked if armed.get() => picked.set(true),
guest::Signal::Cancel => {
armed.set(false);
picked.set(false);
}
_ => {}
}
},
)
.with_on_page_load_handler({
let armed = armed.clone();
let picked = picked.clone();
let loaded = loaded.clone();
let origin = origin.clone();
let token = token.clone();
move |event, url| {
if matches!(event, wry::PageLoadEvent::Started) {
armed.set(false);
picked.set(false);
loaded.set(false);
} else if same_origin(&origin, &url) {
loaded.set(true);
} else if !url.is_empty() && url != "about:blank" {
token.cancel();
}
}
});
let view = guest::Surface::new(w, builder)?;
let panel = Panel { session, cancel: token, origin, project, view, loaded, armed, picked };
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::<AppState>().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<BrowserStatus> {
let (mut status, selection, token, project) = 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 url = if p.loaded.get() { view.url().map_err(unavailable)? } 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.load_url(&url).map_err(unavailable)?;
}
BrowserAction::Back => view.go_back().map_err(unavailable)?,
BrowserAction::Forward => view.go_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.evaluate_script(if arm {
"window.__openideaInspect?.(true)"
} else {
"window.__openideaInspect?.(false)"
})
.map_err(unavailable)?;
p.armed.set(arm);
p.picked.set(false);
}
BrowserAction::Status if local && p.armed.get() && p.picked.replace(false) => {
let (tx, rx) = oneshot::channel();
let reply = Cell::new(Some(tx));
// A guest IPC message is only a wake-up. Read the bounded, gesture-gated slot
// from the main frame, never a payload supplied by the signalling frame.
view.evaluate_script_with_callback(
"window.__openideaPickedElement?.slice(0,8193) ?? null",
move |value| {
if let Some(tx) = reply.take() {
let _ = tx.send(value);
}
},
)
.map_err(unavailable)?;
selection = Some(rx);
p.armed.set(false);
}
BrowserAction::Status => {}
}
let status = BrowserStatus {
url: if local { url } else { p.origin.to_string() },
can_back: view.can_go_back().map_err(unavailable)?,
can_forward: view.can_go_forward().map_err(unavailable)?,
inspecting: p.armed.get(),
element: None,
};
Ok((status, selection, p.cancel.clone(), p.project.clone()))
})
})
.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());
}
let json: Option<String> = serde_json::from_str(&value).map_err(unavailable)?;
if let Some(json) = json {
if json.len() > 8192 {
return Err(IdeError::invalid("Element selection too large"));
}
status.element = Some(serde_json::from_str::<Selection>(&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:[email protected]:3000"]
{
assert!(!same_origin(&origin, target), "{target}");
}
}
}
+149
View File
@@ -0,0 +1,149 @@
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<Step>,
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<InspectedElement> {
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, "<button disabled aria-disabled=\"true\">");
assert_eq!(
preview.styles,
"display: inline-flex;\nposition: static;\nvisibility: visible;\npointer-events: none;"
);
}
#[test]
fn omits_page_supplied_words_in_place_of_a_css_keyword() {
let mut value = selection();
value["display"] = json!("private content");
let preview = serde_json::from_value::<Selection>(value).unwrap().preview().unwrap();
assert!(!preview.styles.contains("private"));
assert!(preview.styles.contains("pointer-events: none;"));
}
#[test]
fn rejects_extra_content_invalid_paths_and_unbounded_styles() {
let mut value = selection();
value["outerHTML"] = json!("unreviewed text");
assert!(serde_json::from_value::<Selection>(value).is_err());
for (field, invalid) in [
("path", json!([])),
("path", json!(vec![json!({"tag":"div","index":1}); 9])),
("path", json!([{"tag":"button><a","index":1}])),
("path", json!([{"tag":"div","index":0}])),
("display", json!("url(local)")),
("position", json!("x".repeat(49))),
] {
let mut value = selection();
value[field] = invalid;
assert!(serde_json::from_value::<Selection>(value).unwrap().preview().is_err());
}
}
}
+23 -2
View File
@@ -1,9 +1,11 @@
//! Web browsers: the built-in server's URLs and launching browsers.
use crate::browser_picker::{self, BrowserAction, BrowserStatus};
use ide_command::desktop_command;
use ide_core::IdeResult;
use ide_core::{IdeResult, RequestId};
use ide_host::ops::blocking;
use ide_web::Browser;
use tauri::Window;
/// The browsers installed on this machine.
#[desktop_command(trust = always)]
@@ -29,4 +31,23 @@ pub async fn web_open(url: String, browser: Option<String>) -> IdeResult<()> {
blocking(move || ide_web::open(&url, browser.as_deref())).await
}
ide_command::desktop_domain!(web_browsers, web_open, web_serves_page);
/// Creates a private localhost browser session owned by this window and project.
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn web_browser_open(window: Window, url: String, session: RequestId) -> IdeResult<()> {
browser_picker::open(window, url, session).await
}
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn web_browser_control(
window: Window,
session: RequestId,
action: BrowserAction,
) -> IdeResult<BrowserStatus> {
browser_picker::control(window, session, action).await
}
ide_command::desktop_domain!(web_browser_control, web_browser_open, web_browsers, web_open, web_serves_page);
+2
View File
@@ -7,6 +7,7 @@
#![recursion_limit = "512"]
mod application_focus;
mod browser_picker;
mod cli;
mod commands;
#[cfg(debug_assertions)]
@@ -292,6 +293,7 @@ pub fn run() {
window_groups::frame_changed(window.app_handle(), window.label());
}
tauri::WindowEvent::Destroyed => {
browser_picker::forget(window.label());
// Also release a view that failed during startup, before the parent could watch it.
if let Some(state) = window.try_state::<AppState>()
&& let Ok(project) = state.host.project(window.label())
+2
View File
@@ -816,6 +816,8 @@ vcs_watch_commit_messages always project_host bin
vcs_worktree_include always project_host bindings async
vcs_worktrees always project_host bindings async
vcs_write_patch always project_host bindings async
web_browser_control trusted desktop bindings async
web_browser_open trusted desktop bindings async
web_browsers always desktop bindings async
web_goto always project_host bindings async
web_open always desktop bindings async
+27
View File
@@ -2213,6 +2213,9 @@ export const commands = {
vcsWorktrees: (repo: string | null) => typedError<Worktree[], IdeError>(__TAURI_INVOKE("vcs_worktrees", { repo })),
/** Create Patch › Save to file. */
vcsWritePatch: (path: string, patch: string, encoding: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_write_patch", { path, patch, encoding })),
webBrowserControl: (session: RequestId, action: BrowserAction) => typedError<BrowserStatus, IdeError>(__TAURI_INVOKE("web_browser_control", { session, action })),
/** Creates a private localhost browser session owned by this window and project. */
webBrowserOpen: (url: string, session: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("web_browser_open", { url, session })),
/** The browsers installed on this machine. */
webBrowsers: () => typedError<Browser[], IdeError>(__TAURI_INVOKE("web_browsers")),
/** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */
@@ -3856,6 +3859,24 @@ export type Browser = {
name: string,
};
export type BrowserAction = { type: "navigate"; url: string } | { type: "back" } | { type: "forward" } | { type: "reload" } | { type: "inspect" } | { type: "cancel" } | { type: "layout"; bounds: BrowserBounds | null } | { type: "status" };
/** Physical pixels measured from the top left of the workbench webview. */
export type BrowserBounds = {
x: number,
y: number,
width: number,
height: number,
};
export type BrowserStatus = {
url: string,
canBack: boolean,
canForward: boolean,
inspecting: boolean,
element: InspectedElement | null,
};
export type BuildEvent =
/** The build starts: its tree root. */
{ kind: "started"; system: BuildSystem; title: string } |
@@ -8387,6 +8408,12 @@ export type InspectSummary = {
elapsedMs: number,
};
export type InspectedElement = {
selector: string,
html: string,
styles: string,
};
export type InspectedFile = {
path: IpcPath,
relPath: string,
+3
View File
@@ -16,6 +16,7 @@ import {
maybeEditorService,
registerAgentContextSource,
registerEditorDropHandler,
provideAgentDraftAppender,
registerEditorKind,
registerMenuGroup,
registerMenuSlotItem,
@@ -34,6 +35,7 @@ import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
import { clearAgentTabFontZoom } from "./fontZoom";
import {
appendContextBlock,
closeActiveTask,
closeAndNewTask,
connect,
@@ -114,6 +116,7 @@ export function activate(): () => void {
else if (s.settings?.agents?.newTaskApprovals !== prev.settings?.agents?.newTaskApprovals && s.project?.root)
void refreshProviders();
}),
provideAgentDraftAppender(appendContextBlock),
registerToolWindow({
id: TOOL_WINDOW,
title: "Agents",
+13
View File
@@ -42,6 +42,7 @@ import {
cursorModelDefaults,
emptyDraft,
hasMention,
fenced,
isMentioned,
isPerModelOption,
mentionOf,
@@ -1664,6 +1665,18 @@ export async function setTaskSkillOverrides(task: string, overrides: Record<stri
}));
}
/** Attach a reviewed block without submitting, changing providers, or replacing draft attachments. */
export function appendContextBlock({ text, info }: { text: string; info: string }) {
const selected = activeComposerKey();
const task = useAgents.getState().tasks.get(selected);
const key = task && task.status !== "archived" ? task.id : HOME;
const existing = composerDraft(key).text;
const block = fenced(text, info);
updateComposer(key, { text: existing ? `${existing}\n\n${block}` : block });
if (key === HOME) openHome();
else openTask(key);
}
/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
function activeComposerKey(): string {
const s = useAgents.getState();
+177
View File
@@ -0,0 +1,177 @@
import { useLayoutEffect, useRef, useState } from "react";
import { useTx } from "@/platform/i18n";
import { type BrowserBounds, type RequestId } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { Button, Input } from "@/ui";
import { appendAgentDraftBlock } from "@/workbench/contributions";
import { closeBrowser, control, useBrowserSession, visit } from "./browserSession";
import styles from "./Web.module.css";
/** Native siblings sit above HTML. Hide the guest when workbench popups or dialogs need that space. */
function Viewport({ id }: { id: RequestId }) {
const slot = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const node = slot.current!;
let previous = "";
let frame = 0;
let stopped = false;
let timer: ReturnType<typeof setTimeout>;
function sync() {
frame = 0;
const rect = node.getBoundingClientRect();
const dpr = window.devicePixelRatio;
const visible =
!document.hidden &&
rect.width > 1 &&
rect.height > 1 &&
!document.querySelector('[aria-modal="true"], [data-popup]') &&
document.elementFromPoint(rect.left + 1, rect.top + 1) === node &&
document.elementFromPoint(rect.right - 1, rect.bottom - 1) === node;
const bounds: BrowserBounds | null = visible
? {
x: Math.round(rect.left * dpr),
y: Math.round(rect.top * dpr),
width: Math.round(rect.right * dpr) - Math.round(rect.left * dpr),
height: Math.round(rect.bottom * dpr) - Math.round(rect.top * dpr),
}
: null;
const key = JSON.stringify(bounds);
if (key !== previous) {
previous = key;
void control(id, { type: "layout", bounds });
}
return visible;
}
function schedule() {
if (!frame) frame = requestAnimationFrame(sync);
}
const resize = new ResizeObserver(schedule);
resize.observe(node);
const changes = new MutationObserver(schedule);
changes.observe(document.body, { childList: true, subtree: true });
window.addEventListener("resize", schedule);
document.addEventListener("scroll", schedule, true);
document.addEventListener("visibilitychange", sync);
async function poll() {
if (sync()) await control(id, { type: "status" });
if (!stopped) timer = setTimeout(() => void poll(), 400);
}
void poll();
return () => {
stopped = true;
clearTimeout(timer);
resize.disconnect();
changes.disconnect();
window.removeEventListener("resize", schedule);
document.removeEventListener("scroll", schedule, true);
document.removeEventListener("visibilitychange", sync);
cancelAnimationFrame(frame);
void control(id, { type: "layout", bounds: null });
};
}, [id]);
return <div ref={slot} className={styles.viewport} />;
}
export function BrowserView() {
const project = useProject((s) => s.project);
const remote = useRemote((s) => !!s.session);
const t = useTx();
return project?.trusted && !remote ? (
<Browser key={project.root} />
) : (
<p className={styles.message}>{t("Element inspection requires a trusted local project.")}</p>
);
}
function Browser() {
const t = useTx();
const { id, ready, location, element, error } = useBrowserSession();
const [draft, setDraft] = useState<string | null>(null);
const url = draft ?? location?.url ?? "";
const text = element ? [element.selector, element.html, element.styles].join("\n\n") : "";
return (
<section className={styles.inspector} aria-label={t("Browser")}>
<form
onSubmit={(e) => {
e.preventDefault();
const address = url.trim();
void visit(address).then(() => {
if (!useBrowserSession.getState().error) setDraft((value) => (value?.trim() === address ? null : value));
});
}}
>
<label htmlFor="browser-inspector-url">{t("Local page URL")}</label>
<Input
id="browser-inspector-url"
type="url"
required
value={url}
placeholder="http://localhost:3000"
autoComplete="off"
spellCheck={false}
onChange={(e) => setDraft(e.target.value)}
/>
<Button type="submit" disabled={!url.trim() || (id !== null && !ready)}>
{t("Open")}
</Button>
</form>
{ready && id !== null && (
<>
<div className={styles.navigation} role="group" aria-label={t("Browser")}>
<Button
disabled={!location?.canBack}
onClick={() => {
setDraft(null);
void control(id, { type: "back" });
}}
>
{t("Back")}
</Button>
<Button
disabled={!location?.canForward}
onClick={() => {
setDraft(null);
void control(id, { type: "forward" });
}}
>
{t("Forward")}
</Button>
<Button onClick={() => void control(id, { type: "reload" })}>{t("Reload")}</Button>
<Button onClick={() => void control(id, { type: location?.inspecting ? "cancel" : "inspect" })}>
{location?.inspecting ? t("Cancel") : t("Inspect Element")}
</Button>
<Button
onClick={() => {
setDraft(url);
closeBrowser();
}}
>
{t("Close")}
</Button>
</div>
{location?.inspecting && <p role="status">{t("Click an element to inspect it")}</p>}
<Viewport id={id} />
</>
)}
{error && <p role="alert">{error}</p>}
{element && (
<>
<h3>{t("Selected element")}</h3>
<pre>{text}</pre>
<Button
variant="primary"
icon="toolwindow-agents"
onClick={() => {
if (appendAgentDraftBlock({ kind: "block", info: `text ${t("Selected element")}`, text }))
useBrowserSession.setState({ element: null });
else useBrowserSession.setState({ error: t("The agent composer is unavailable.") });
}}
>
{t("Add to Agent Draft")}
</Button>
</>
)}
</section>
);
}
+48
View File
@@ -34,3 +34,51 @@
color: var(--fg-muted);
font-family: var(--font-ui);
}
.inspector {
flex: 1;
height: 100%;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 12px;
padding: 12px;
min-width: 0;
overflow: auto;
}
.inspector form {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
}
.inspector label {
grid-column: 1 / -1;
}
.navigation {
display: flex;
gap: 4px;
flex-wrap: wrap;
}
.viewport {
flex: 1 0 100px;
background: var(--bg-editor);
}
.inspector button {
justify-self: start;
align-self: flex-start;
}
.inspector h3,
.inspector p {
margin: 0;
font-size: inherit;
}
.inspector pre {
margin: 0;
padding: 10px;
white-space: pre-wrap;
overflow-wrap: anywhere;
background: var(--bg-editor);
color: var(--fg);
font-family: var(--font-mono);
user-select: text;
}
+110
View File
@@ -0,0 +1,110 @@
import { create } from "zustand";
import {
call,
commands,
isCancelled,
nextRequestId,
type BrowserAction,
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<Session>(() => empty);
let queue = Promise.resolve();
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();
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<void> {
queue = queue.then(async () => {
const current = useBrowserSession.getState;
if (current().id !== id || !current().ready) return;
try {
const location = await call(commands.webBrowserControl(id, action));
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(action.type)
) {
useBrowserSession.setState({
location,
error: "",
element:
location.element ??
(before?.url === location.url && ["status", "layout", "cancel"].includes(action.type)
? current().element
: null),
});
}
} catch (e) {
if (current().id !== id) return;
if (isCancelled(e)) closeBrowser();
else useBrowserSession.setState({ error: message(e) });
}
});
return queue;
}
+23
View File
@@ -15,6 +15,8 @@ import {
registerEditorBanner,
registerMenuGroup,
registerTextEditorWrapper,
registerToolWindow,
toolWindowService,
useTextEditorWrappers,
} from "@/workbench/contributions";
import { activeEditor, registerEditorContribution } from "@/editor/api";
@@ -31,6 +33,7 @@ import {
useWebPreview,
} from "./browsers";
import { tx } from "@/platform/i18n";
import { watchBrowserOwner } from "./browserSession";
interface OpenArg {
path?: string;
@@ -78,9 +81,20 @@ 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: "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",
@@ -88,6 +102,15 @@ export function activate(): () => void {
component: lazyComponent(() => import("./WebEditor").then((m) => m.WebEditor)),
}),
registerActions([
{
id: "web.inspectLocalPage",
title: "Open Local Browser",
category: "View",
icon: "web",
when: "projectLocal",
keywords: ["browser", "element", "inspect", "agent", "DOM", "CSS"],
run: () => toolWindowService().show("browser", true),
},
{
id: "web.openInBrowser",
title: "Open in Browser",
+8
View File
@@ -1574,6 +1574,14 @@
"Run All": "Run All",
"Restart All": "Restart All",
"Stop All": "Stop All",
"Open Local Browser": "Open Local Browser",
"Local page URL": "Local page URL",
"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",
+8
View File
@@ -2523,6 +2523,14 @@
"Open as Text": "作为文本打开",
"Open console for tool output": "为工具输出打开控制台",
"Open documents": "打开的文档",
"Open Local Browser": "打开本地浏览器",
"Local page URL": "本地页面地址",
"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": "在查找窗口中打开",
+16
View File
@@ -1021,6 +1021,22 @@ export const maybeCommitService = (): CommitService | undefined => commitService
*/
export type AgentContext = { kind: "block"; info: string; text: string } | { kind: "files"; paths: string[] };
type DraftBlock = Extract<AgentContext, { kind: "block" }>;
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;