Compare commits

..
Author SHA1 Message Date
l0ng-ai 33a0dc3057 Merge remote-tracking branch 'origin/main' into pr-5788 2026-11-25 19:45:25 +08:00
l0ng-ai 9afcee1efd Merge remote-tracking branch 'origin/main' into pr-5788 2026-11-25 19:28:41 +08:00
l0ng-ai 9ae1155381 fix(browser): one-row icon toolbar, edge-to-edge page, focus the address field
- Back / Forward / Reload, the address field, Inspect Element (a toggle) and
  Close sit in one icon toolbar row; Enter opens or navigates.
- The page fills the panel below the toolbar; the element preview has its own
  section underneath.
- Visibility sampling stays inside the viewport edges, where the tool window's
  resize handle overlaps it.
- A new session focuses the address field.
2026-11-25 19:28:41 +08:00
l0ng-ai f3c55bbc78 fix(browser): keep console link clicks external, add a context-menu entry, own tool window icon
- A plain click on a console URL opens the external browser again; loopback URLs
  get 'Open in Browser Tool Window' in the Run and Debug console context menus.
- clipboard_write_image takes the parent Window, so it keeps working while a
  Browser child webview is attached.
- The Browser tool window gets its own icon; panel gaps use spacing tokens.
2026-11-25 19:15:03 +08:00
l0ng-ai b8d1f54417 Merge remote-tracking branch 'origin/main' into pr-5788 2026-11-25 19:05:48 +08:00
Deng Liu d82b65f19e feat(browser): host localhost in an unprivileged Tauri child webview
Navigate and inspect the same page in the Browser tool window. Grant capabilities to trusted webview labels instead of their parent window, retain workbench window handles while a guest is attached, and deny guest access to IDE commands and plugin resources.

Adapt the element snapshot and reviewed draft insertion from aditya-786’s work in #4735; replace the picker host as requested in its review. Related to #4494.

Copilot-Session: 15919368-07bf-4a19-a395-acc76294f5da
2026-11-25 01:02:12 -05:00
55 changed files with 1785 additions and 174 deletions

No files matched your search

+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())
}
+8
View File
@@ -5,6 +5,14 @@ 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 |
+8
View File
@@ -5,6 +5,14 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
编辑器的行为和默认快捷键沿用 IntelliJ IDEA。下文的快捷键在 macOS 上是 **macOS** 键位映射的默认值,在 Windows 和 Linux 上是 **Windows** 键位映射的默认值;任何一个都可以在 **设置 › 按键映射** 中修改(见 [键位映射](/zh/guide/keymap))。所有命令也都能在 **查找操作**(`⇧⌘A` / `Ctrl+Shift+A`)里找到。
## 浏览本地开发服务器
在受信任的本地项目中,选择**查找操作 › 打开本地浏览器**。输入指向本机回环地址的 HTTP 或 HTTPS 网址,点击**打开**。可以直接在面板中点击链接、后退、前进和重新加载。隐藏面板会保留页面和浏览历史;点击**关闭**才会结束会话。浏览范围限于原来的源;如需切换开发服务器或端口,请先关闭会话,再打开新地址。
点击运行或调试控制台中的网址仍会在外部浏览器中打开。如需在此面板中打开本机地址,右键点击该地址并选择**在浏览器工具窗口中打开**。
点击**检查元素**,然后在页面中点选元素。确认选择器、起始标签和样式后,可将其添加到 Agent 草稿,不会自动发送。在页面中按 **Escape** 可退出检查并继续浏览。
## 光标与选区
| 操作 | macOS | Windows / Linux |
+248
View File
@@ -0,0 +1,248 @@
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: 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(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);
});
+4 -3
View File
@@ -14,7 +14,8 @@ tauri-build = { version = "2", features = [] }
dunce.workspace = true
[dependencies]
tauri = { version = "2", features = [] }
# Tauri 2 gates Window::add_child behind its multiwebview feature.
tauri = { version = "2", features = ["unstable"] }
tauri-plugin-opener = "2"
tauri-plugin-notification = "2.8.1"
tauri-plugin-dialog = { version = "2", default-features = false, features = ["xdg-portal"] }
@@ -79,8 +80,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"] }
# 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"] }
# Browser history and the debug font-restriction override.
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebView", "WKWebViewConfiguration", "WKPreferences"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Wayland detection and the client size without GTK's CSD shadow (linux_window_state.rs).
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "browser",
"description": "Untrusted localhost Browser child. No core, plugin, or application commands.",
"webviews": ["browser-guest-*"],
"permissions": []
}
+2 -2
View File
@@ -1,8 +1,8 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"description": "Trusted workbench webviews only; child browser pages must not inherit their host window's permissions.",
"webviews": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
+1 -1
View File
@@ -2,6 +2,6 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "e2e-bridge",
"description": "Debug-only automation bridge",
"windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"webviews": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"permissions": ["mcp-bridge:default"]
}
+4 -1
View File
@@ -1,4 +1,7 @@
//! 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};
@@ -87,7 +90,7 @@ pub(crate) fn application_active(app: &tauri::AppHandle) -> bool {
process == std::process::id()
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
app.webview_windows().values().any(|w| w.is_focused().unwrap_or(true))
app.workbench_windows().values().any(|w| w.is_focused().unwrap_or(true))
}
#[cfg(test)]
+123
View File
@@ -0,0 +1,123 @@
// 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,
);
})();
+155
View File
@@ -0,0 +1,155 @@
//! 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<tauri::Wry>) -> IdeResult<Self> {
let webview =
window.add_child(builder, PhysicalPosition::new(0, 0), PhysicalSize::new(1, 1)).map_err(unavailable)?;
let init = || -> IdeResult<Self> {
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::<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);
// 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<gtk::Box> = slot.downgrade().into();
webview
.with_webview(move |native| {
let result = (|| -> IdeResult<()> {
let widget = native.inner();
let parent = widget
.parent()
.and_then(|p| p.downcast::<gtk::Container>().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<BrowserBounds>) -> IdeResult<()> {
let size = window.inner_size().map_err(unavailable)?;
let Some(b) = bounds.filter(|b| {
b.x >= 0
&& b.y >= 0
&& b.width > 0
&& b.height > 0
&& (b.x as u32).saturating_add(b.width) <= size.width.saturating_add(1)
&& (b.y as u32).saturating_add(b.height) <= size.height.saturating_add(1)
}) 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: PhysicalPosition::new(b.x, b.y).into(),
size: 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.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::<objc2_web_kit::WKWebView>();
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::<gtk::Overlay>().ok()) {
parent.remove(&self.slot);
}
}
}
}
+342
View File
@@ -0,0 +1,342 @@
//! 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<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())
}
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<ide_host::Project>,
view: guest::Surface,
document: Arc<Document>,
}
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 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::<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, 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<String> = 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::<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());
}
}
}
+3 -3
View File
@@ -7,13 +7,13 @@ use ide_core::IdeResult;
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
use ide_host::ops::blocking;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, WebviewWindow};
use tauri::{AppHandle, Window};
/// Writes text locally, without WebView user-activation requirements.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn clipboard_write_text(app: AppHandle, window: WebviewWindow, text: String) -> IdeResult<()> {
pub async fn clipboard_write_text(app: AppHandle, window: Window, text: String) -> IdeResult<()> {
#[cfg(windows)]
let owner = window.hwnd().map_err(|error| ide_core::IdeError::internal(error.to_string()))?.0 as usize;
#[cfg(not(windows))]
@@ -28,7 +28,7 @@ pub async fn clipboard_write_text(app: AppHandle, window: WebviewWindow, text: S
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn clipboard_write_image(app: AppHandle, window: WebviewWindow, png: String) -> IdeResult<()> {
pub async fn clipboard_write_image(app: AppHandle, window: Window, png: String) -> IdeResult<()> {
use base64::Engine;
if png.len() > 90 * 1024 * 1024 {
return Err(ide_core::IdeError::invalid("Clipboard image is too large"));
+4 -2
View File
@@ -1,5 +1,8 @@
//! Diagnostics for the memory indicator / performance overlay.
#[cfg(target_os = "macos")]
use crate::windows::WorkbenchWindows;
use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::IdeResult;
@@ -166,9 +169,8 @@ fn openidea_root(pid: u32, label: String, detail: Option<String>) -> MemoryRoot
async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot> {
use std::collections::BTreeMap;
use std::time::Duration;
use tauri::Manager;
let mut pending = Vec::new();
for (label, w) in app.webview_windows() {
for (label, w) in app.workbench_windows() {
let (tx, rx) = tokio::sync::oneshot::channel();
let sent = w.with_webview(move |pv| {
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
+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);
+22 -21
View File
@@ -2,6 +2,7 @@
use crate::menu::{self, MenuConfig, MenuState};
use crate::state::AppState;
use crate::windows::WorkbenchWindow;
use crate::windows::{self, Launch, OpenOutcome, WindowsState};
use ide_command::desktop_command;
use ide_core::{IdeError, IdeResult, RequestId};
@@ -11,7 +12,7 @@ use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::ipc::Channel;
use tauri::{AppHandle, State, WebviewWindow, Window};
use tauri::{AppHandle, State, Window};
/// Opens `path` in a new window (`new_window`) or tells the caller to open it
/// itself (`current`). A project already open in some window is focused instead.
@@ -37,7 +38,7 @@ pub async fn window_open_project(
#[specta::specta]
pub async fn window_open_files(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
files: Vec<PathBuf>,
) -> IdeResult<Vec<ide_core::IpcPath>> {
Ok(windows::open_files_window(&app, window.label(), files))
@@ -87,7 +88,7 @@ pub async fn window_new(app: AppHandle) -> IdeResult<String> {
#[specta::specta]
pub async fn window_open_settings(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
page: Option<String>,
new_projects: bool,
background: Option<String>,
@@ -102,7 +103,7 @@ pub async fn window_open_settings(
#[specta::specta]
pub async fn window_open_comparison(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
comparison: windows::ComparisonLaunch,
background: Option<String>,
) -> IdeResult<()> {
@@ -116,7 +117,7 @@ pub async fn window_open_comparison(
#[specta::specta]
pub async fn window_open_diff(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
diff: windows::DiffLaunch,
background: Option<String>,
) -> IdeResult<()> {
@@ -130,7 +131,7 @@ pub async fn window_open_diff(
#[specta::specta]
pub async fn window_open_editor(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
editor: windows::EditorLaunch,
background: Option<String>,
) -> IdeResult<()> {
@@ -144,7 +145,7 @@ pub async fn window_open_editor(
#[specta::specta]
pub async fn window_open_deployment(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
server: String,
paths: Vec<PathBuf>,
background: Option<String>,
@@ -156,14 +157,14 @@ pub async fn window_open_deployment(
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_cycle(app: AppHandle, window: WebviewWindow, forward: bool) {
pub fn window_cycle(app: AppHandle, window: WorkbenchWindow, forward: bool) {
windows::cycle(&app, window.label(), forward);
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
pub fn window_toggle_fullscreen(window: WorkbenchWindow) -> IdeResult<bool> {
crate::window_groups::toggle_fullscreen(&window)
}
@@ -171,7 +172,7 @@ pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_toggle_zoom(window: WebviewWindow) -> IdeResult<bool> {
pub fn window_toggle_zoom(window: WorkbenchWindow) -> IdeResult<bool> {
crate::window_zoom::toggle(&window)
}
@@ -182,7 +183,7 @@ pub fn window_toggle_zoom(window: WebviewWindow) -> IdeResult<bool> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()> {
pub fn window_flash_taskbar(window: WorkbenchWindow, flash: bool) -> IdeResult<()> {
if flash && window.is_focused().unwrap_or(false) {
return Ok(());
}
@@ -195,7 +196,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
pub fn window_set_smooth_scrolling(window: WorkbenchWindow, enabled: bool) -> IdeResult<()> {
#[cfg(target_os = "linux")]
window
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
@@ -209,7 +210,7 @@ pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeR
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_set_titlebar_height(window: WebviewWindow, height: f64) -> IdeResult<()> {
pub fn window_set_titlebar_height(window: WorkbenchWindow, height: f64) -> IdeResult<()> {
if !height.is_finite() || !(1.0..=1000.0).contains(&height) {
return Err(IdeError::invalid("invalid title bar height"));
}
@@ -224,7 +225,7 @@ pub fn window_set_titlebar_height(window: WebviewWindow, height: f64) -> IdeResu
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> Option<Launch> {
pub fn window_take_launch(window: WorkbenchWindow, windows: State<'_, WindowsState>) -> Option<Launch> {
windows.take_launch(window.label())
}
@@ -245,7 +246,7 @@ pub struct SettingsWindowInit {
#[specta::specta]
pub fn window_take_settings_init(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
windows: State<'_, WindowsState>,
state: State<'_, AppState>,
) -> SettingsWindowInit {
@@ -273,7 +274,7 @@ pub fn window_take_settings_init(
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_complete_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
pub fn window_complete_launch(window: WorkbenchWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
windows.complete_launch(window.label());
Ok(())
}
@@ -295,7 +296,7 @@ pub struct OpenProject {
#[specta::specta]
pub fn window_open_projects(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
state: State<'_, AppState>,
) -> IdeResult<Vec<OpenProject>> {
Ok(windows::project_window_labels(&app)
@@ -323,7 +324,7 @@ pub fn window_open_projects(
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_is_fullscreen(window: WebviewWindow) -> bool {
pub fn window_is_fullscreen(window: WorkbenchWindow) -> bool {
window.is_fullscreen().unwrap_or(false)
}
@@ -383,7 +384,7 @@ pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) {
#[tauri::command]
#[specta::specta]
pub fn menu_configure(
window: WebviewWindow,
window: WorkbenchWindow,
app: AppHandle,
menu_state: State<'_, MenuState>,
state: State<'_, AppState>,
@@ -435,7 +436,7 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn menu_set_disabled(window: WebviewWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
pub fn menu_set_disabled(window: WorkbenchWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
// The window whose menu runs: a project window also while its Settings window is focused.
if menu::native_menu_bar()
&& windows::target_window(&app).is_some_and(|target| !owns_menu_config(window.label(), target.label()))
@@ -623,7 +624,7 @@ pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeRe
#[specta::specta]
pub fn app_update_window_ready(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
ready: bool,
system_locale: String,
) -> IdeResult<()> {
+3 -3
View File
@@ -3,7 +3,7 @@
use ide_command::desktop_command;
use ide_core::{IdeError, IdeResult};
use std::path::PathBuf;
use tauri::WebviewWindow;
use tauri::Window;
/// Starts dragging `window` while the primary mouse button is still down; returns whether a drag began.
///
@@ -12,7 +12,7 @@ use tauri::WebviewWindow;
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {
pub fn window_start_drag(window: Window) -> IdeResult<bool> {
#[cfg(target_os = "macos")]
if objc2_app_kit::NSEvent::pressedMouseButtons() & 1 == 0 {
return Ok(false);
@@ -27,7 +27,7 @@ pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_drag_files(window: WebviewWindow, paths: Vec<PathBuf>) -> IdeResult<bool> {
pub async fn window_drag_files(window: Window, paths: Vec<PathBuf>) -> IdeResult<bool> {
let paths = ide_drag_out::local_paths(paths)?;
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (done_tx, done_rx) = tokio::sync::oneshot::channel();
+14 -12
View File
@@ -1,19 +1,21 @@
use crate::windows::WorkbenchWindows;
use crate::{window_groups as groups, windows::WindowsState};
use ide_command::desktop_command;
use ide_core::{IdeError, IdeResult};
use tauri::{Manager, WebviewWindow};
use tauri::{Manager, Window};
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_current(window: WebviewWindow) -> IdeResult<Vec<groups::WindowTab>> {
pub fn window_group_current(window: Window) -> IdeResult<Vec<groups::WindowTab>> {
Ok(groups::current(window.app_handle(), window.label()))
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_merge(window: WebviewWindow) -> IdeResult<()> {
pub async fn window_group_merge(window: Window) -> IdeResult<()> {
groups::merge(window.app_handle(), window.label())?;
groups::persist(window.app_handle()).await
}
@@ -23,7 +25,7 @@ pub async fn window_group_merge(window: WebviewWindow) -> IdeResult<()> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_join(window: WebviewWindow, label: String) -> IdeResult<()> {
pub async fn window_group_join(window: Window, label: String) -> IdeResult<()> {
groups::join(window.app_handle(), window.label(), &label)?;
groups::persist(window.app_handle()).await
}
@@ -31,7 +33,7 @@ pub async fn window_group_join(window: WebviewWindow, label: String) -> IdeResul
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeResult<()> {
pub async fn window_group_select(window: Window, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
groups::persist(window.app_handle()).await
}
@@ -39,7 +41,7 @@ pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeRes
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeResult<()> {
pub async fn window_group_detach(window: Window, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
groups::detach(window.app_handle(), &label)?;
groups::persist(window.app_handle()).await
@@ -48,11 +50,11 @@ pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeRes
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_close(window: WebviewWindow, label: String) -> IdeResult<()> {
pub fn window_group_close(window: Window, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
window
.app_handle()
.get_webview_window(&label)
.workbench_window(&label)
.ok_or_else(|| IdeError::not_found("Window closed"))?
.close()
.map_err(|e| IdeError::internal(e.to_string()))
@@ -62,7 +64,7 @@ pub fn window_group_close(window: WebviewWindow, label: String) -> IdeResult<()>
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_close_tabs(window: WebviewWindow, keep: String, labels: Vec<String>) -> IdeResult<()> {
pub fn window_group_close_tabs(window: Window, keep: String, labels: Vec<String>) -> IdeResult<()> {
groups::close_tabs(window.app_handle(), window.label(), &keep, labels)
}
@@ -70,14 +72,14 @@ pub fn window_group_close_tabs(window: WebviewWindow, keep: String, labels: Vec<
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_cancel_close(window: WebviewWindow) {
pub fn window_group_cancel_close(window: Window) {
groups::cancel_close(window.app_handle(), window.label());
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_reorder(window: WebviewWindow, labels: Vec<String>) -> IdeResult<()> {
pub async fn window_group_reorder(window: Window, labels: Vec<String>) -> IdeResult<()> {
window.state::<WindowsState>().groups.lock().reorder(window.label(), labels)?;
groups::select(window.app_handle(), window.label(), window.label())?;
groups::persist(window.app_handle()).await
@@ -86,7 +88,7 @@ pub async fn window_group_reorder(window: WebviewWindow, labels: Vec<String>) ->
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_restore(window: WebviewWindow) -> IdeResult<()> {
pub async fn window_group_restore(window: Window) -> IdeResult<()> {
groups::restore(window.app_handle(), window.label()).await
}
+3 -3
View File
@@ -4,7 +4,7 @@ use ide_core::{IdeError, IdeResult, RequestId};
use ide_host::ops::project::ProjectInfo;
use ide_workspace::workspace::Workspace;
use std::path::PathBuf;
use tauri::{Manager, State, WebviewWindow};
use tauri::{Manager, State, Window};
#[desktop_command(trust = always)]
#[tauri::command]
@@ -38,7 +38,7 @@ pub async fn workspace_create(path: PathBuf, name: String, projects: Vec<PathBuf
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn workspace_update(window: WebviewWindow, name: String, projects: Vec<PathBuf>) -> IdeResult<ProjectInfo> {
pub async fn workspace_update(window: Window, name: String, projects: Vec<PathBuf>) -> IdeResult<ProjectInfo> {
let host = window.state::<AppState>().host.clone();
let label = window.label().to_owned();
let info = tauri::async_runtime::spawn_blocking(move || {
@@ -57,7 +57,7 @@ pub async fn workspace_update(window: WebviewWindow, name: String, projects: Vec
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn workspace_attach(window: WebviewWindow, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
pub async fn workspace_attach(window: Window, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let host = window.state::<AppState>().host.clone();
let label = window.label().to_owned();
let root =
+5 -3
View File
@@ -1,9 +1,11 @@
use crate::windows::WorkbenchWindows;
use ide_core::{EventSink, IdeEvent, SharedSink};
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager, UserAttentionType};
use tauri::{AppHandle, Emitter, UserAttentionType};
/// Name of the single backend → UI event. Payload: [`IdeEvent`].
pub const IDE_EVENT: &str = "ide://event";
@@ -149,7 +151,7 @@ fn flash_taskbar_unless_focused(app: &AppHandle) {
if crate::application_focus::application_active(&handle) {
return;
}
for window in handle.webview_windows().values() {
for window in handle.workbench_windows().values() {
let _ = window.request_user_attention(Some(UserAttentionType::Informational));
}
});
@@ -188,7 +190,7 @@ impl EventSink for TauriSink {
{
let app = self.app.clone();
let _ = self.app.run_on_main_thread(move || {
if let Some(window) = app.get_webview_window(&label) {
if let Some(window) = app.workbench_window(&label) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
+9 -1
View File
@@ -7,6 +7,7 @@
#![recursion_limit = "512"]
mod application_focus;
mod browser_picker;
mod cli;
mod commands;
#[cfg(debug_assertions)]
@@ -48,6 +49,8 @@ mod windows_webview_keys;
#[cfg(windows)]
mod windows_webview_recovery;
use crate::windows::WorkbenchWindows;
use parking_lot::Mutex;
use state::AppState;
use std::path::{Path, PathBuf};
@@ -185,6 +188,10 @@ pub fn run() {
});
app.invoke_handler(move |request| {
let webview = request.message.webview_ref();
if browser_picker::is_guest(webview.label()) {
request.resolver.reject("Browser pages cannot invoke IDE commands");
return true;
}
if let Some(state) = webview.try_state::<AppState>() {
let label = AppState::owner_window(webview.label());
let command = request.message.command();
@@ -298,6 +305,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())
@@ -427,7 +435,7 @@ pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
let label = match windows::menu_destination(w.label(), &route.action) {
windows::MenuDestination::Own => w.label(),
windows::MenuDestination::Parent { label, raise } => {
if raise && let Some(parent) = app.get_webview_window(label) {
if raise && let Some(parent) = app.workbench_window(label) {
windows::focus(&parent);
return_to = Some(w.label());
}
+7 -6
View File
@@ -12,6 +12,7 @@ fn build_hidden(config: &mut WindowConfig) -> bool {
#[cfg(target_os = "linux")]
mod runtime {
use super::*;
use crate::windows::WorkbenchWindows;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::OnceLock;
@@ -336,8 +337,8 @@ mod runtime {
let app = window.app_handle().clone();
let label = window.label().to_owned();
let _ = window.run_on_main_thread(move || {
if let Some(parent) = crate::windows::auxiliary_parent(&label).and_then(|p| app.get_webview_window(p))
&& let Some(aux) = app.get_webview_window(&label)
if let Some(parent) = crate::windows::auxiliary_parent(&label).and_then(|p| app.workbench_window(p))
&& let Some(aux) = app.workbench_window(&label)
&& let Err(error) = crate::windows::place_over_parent(&aux, &parent)
{
tracing::warn!("cannot fit restored auxiliary window: {error}");
@@ -380,7 +381,7 @@ mod runtime {
let saved = cache.saved.entry(key(label).to_owned()).or_default();
saved.set_normal_size(Size(size.width, size.height));
drop(cache);
if let Some(webview) = app.get_webview_window(label) {
if let Some(webview) = app.workbench_window(label) {
request_presentation(webview.as_ref(), request);
}
}
@@ -419,7 +420,7 @@ mod runtime {
}
pub fn save_before_close(app: &AppHandle) {
for window in app.webview_windows().values() {
for window in app.workbench_windows().values() {
sample(&window.as_ref().window(), false, false);
}
persist(app);
@@ -464,7 +465,7 @@ mod runtime {
request: u64,
}
let Ok(presented) = serde_json::from_str::<Presented>(event.payload()) else { return };
let Some(webview) = handle.get_webview_window(&presented.label) else { return };
let Some(webview) = handle.workbench_window(&presented.label) else { return };
let window = webview.as_ref().window();
let cloned = window.clone();
let _ = window.run_on_main_thread(move || {
@@ -510,7 +511,7 @@ mod runtime {
.filter(|p| !p.presented)
.map(|p| p.presentation_request);
if let Some(request) = request
&& let Some(webview) = cloned.app_handle().get_webview_window(cloned.label())
&& let Some(webview) = cloned.app_handle().workbench_window(cloned.label())
{
request_presentation(webview.as_ref(), request);
}
+3 -1
View File
@@ -1,4 +1,6 @@
//! macOS project tabs: native window tab groups behind the page's own tab bar.
use crate::windows::WorkbenchWindows;
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
@@ -31,7 +33,7 @@ fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
/// Capture before building the new window, which takes focus itself.
pub fn new_project_tab_target(app: &AppHandle, launch: &Launch) -> IdeResult<Option<WebviewWindow>> {
let windows = app.webview_windows();
let windows = app.workbench_windows();
let active = windows
.values()
.find(|w| w.is_focused().unwrap_or(false))
+4
View File
@@ -79,6 +79,10 @@ fn with_bridge(html: &[u8]) -> Vec<u8> {
}
pub fn handle<R: Runtime>(ctx: UriSchemeContext<'_, R>, request: Request<Vec<u8>>, responder: UriSchemeResponder) {
if crate::browser_picker::is_guest(ctx.webview_label()) {
responder.respond(status(StatusCode::FORBIDDEN));
return;
}
let app = ctx.app_handle().clone();
let path = request.uri().path().to_owned();
tauri::async_runtime::spawn_blocking(move || {
+3 -1
View File
@@ -5,6 +5,8 @@
//! active. Click focuses the window that raised the toast — balloon actions stay
//! in the IDE.
use crate::windows::WorkbenchWindows;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::LazyLock;
@@ -121,7 +123,7 @@ fn activate(app: &AppHandle, id: i32) {
let Some(window_label) = STATE.take_target(id) else { return };
let app = app.clone();
let _ = app.clone().run_on_main_thread(move || {
let Some(window) = app.get_webview_window(&window_label) else { return };
let Some(window) = app.workbench_window(&window_label) else { return };
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
+3 -1
View File
@@ -1,5 +1,7 @@
//! Desktop updater coordination shared by all webviews.
use crate::windows::WorkbenchWindows;
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured};
use crate::state::AppState;
use ide_core::updates::{UpdateCheck, UpdatePolicy};
@@ -145,7 +147,7 @@ fn announce_available(app: &AppHandle) {
let live = crate::windows::project_window_labels(app);
let owner = {
let mut ready = state.updates.ready.lock();
ready.retain(|label| app.get_webview_window(label).is_some());
ready.retain(|label| app.workbench_window(label).is_some());
ready_owner(focused.as_ref().map(|window| window.label()), &live, &ready)
};
let Some(owner) = owner else { return };
+14 -12
View File
@@ -1,4 +1,6 @@
//! Desktop adapter for application-drawn project tabs. Each member retains its WebView and services.
use crate::windows::WorkbenchWindows;
use crate::{
state::AppState,
windows::{self, WindowsState},
@@ -33,7 +35,7 @@ pub fn current(app: &AppHandle, caller: &str) -> Vec<WindowTab> {
.members
.iter()
.filter_map(|label| {
let window = app.get_webview_window(label)?;
let window = app.workbench_window(label)?;
let project = host.project(label).ok();
let name = project.as_ref().map(|p| ide_host::ops::project::info(p).display_name).unwrap_or_else(|| {
// Taken its launch but not finished opening: name the tab after that project.
@@ -75,7 +77,7 @@ pub fn toggle_fullscreen(window: &WebviewWindow) -> IdeResult<bool> {
}
pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
let to = app.get_webview_window(target).ok_or_else(|| IdeError::not_found("Window closed"))?;
let to = app.workbench_window(target).ok_or_else(|| IdeError::not_found("Window closed"))?;
let state = app.state::<WindowsState>();
let previous = state.groups.lock().select(caller, target)?;
#[cfg(target_os = "macos")]
@@ -85,7 +87,7 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
if result.is_err() {
let _ = state.groups.lock().select(caller, &previous.selected);
#[cfg(target_os = "macos")]
if let Some(window) = app.get_webview_window(&previous.selected) {
if let Some(window) = app.workbench_window(&previous.selected) {
let _ = native_select(app, &previous, &window);
}
#[cfg(not(target_os = "macos"))]
@@ -103,8 +105,8 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
/// Shows `to` as the selected tab of the group's native tab group.
#[cfg(target_os = "macos")]
fn native_select(app: &AppHandle, group: &Group, to: &WebviewWindow) -> IdeResult<()> {
let members = group.members.iter().filter_map(|m| app.get_webview_window(m)).collect();
let anchor = app.get_webview_window(&group.selected).unwrap_or_else(|| to.clone());
let members = group.members.iter().filter_map(|m| app.workbench_window(m)).collect();
let anchor = app.workbench_window(&group.selected).unwrap_or_else(|| to.clone());
to.unminimize().map_err(|e| IdeError::internal(e.to_string()))?;
crate::macos::sync_tab_group(members, &anchor, to).map_err(|e| IdeError::internal(e.to_string()))
}
@@ -125,7 +127,7 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
}
// Native fullscreen puts each window in a separate Space; leave it before grouping.
for label in &members {
if let Some(window) = app.get_webview_window(label) {
if let Some(window) = app.workbench_window(label) {
window.set_fullscreen(false).map_err(|e| IdeError::internal(e.to_string()))?;
}
}
@@ -140,13 +142,13 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
changed(app);
return Ok(());
};
let window = app.get_webview_window(caller);
let window = app.workbench_window(caller);
// A tab moved out of a fullscreen group stays fullscreen in a Space of its own.
#[cfg(target_os = "macos")]
if let Some(window) = &window {
crate::macos::move_tab_to_new_window(window).map_err(err)?;
}
if let Some(next) = app.get_webview_window(&next) {
if let Some(next) = app.workbench_window(&next) {
#[cfg(target_os = "macos")]
if state.groups.lock().group(next.label()).is_some() {
select(app, next.label(), next.label())?;
@@ -170,7 +172,7 @@ pub fn destroyed(app: &AppHandle, caller: &str) {
let Some(state) = app.try_state::<WindowsState>() else { return };
let next = state.groups.lock().detach(caller);
if !state.quitting() {
if let Some(window) = next.and_then(|label| app.get_webview_window(&label)) {
if let Some(window) = next.and_then(|label| app.workbench_window(&label)) {
windows::focus(&window);
}
let app = app.clone();
@@ -238,7 +240,7 @@ fn close_next(app: &AppHandle) {
};
match next {
Ok(label) => {
if let Some(window) = app.get_webview_window(&label) {
if let Some(window) = app.workbench_window(&label) {
windows::focus(&window);
if window.close().is_ok() {
return;
@@ -249,7 +251,7 @@ fn close_next(app: &AppHandle) {
}
}
Err(keep) => {
if let Some(window) = app.get_webview_window(&keep) {
if let Some(window) = app.workbench_window(&keep) {
windows::focus(&window);
}
return;
@@ -260,7 +262,7 @@ fn close_next(app: &AppHandle) {
/// Window labels in creation order: `main`, then `project-1`, `project-2`, ….
fn labels_in_order(app: &AppHandle) -> Vec<String> {
let mut labels: Vec<String> = app.webview_windows().into_keys().collect();
let mut labels: Vec<String> = app.workbench_windows().into_keys().collect();
labels.sort_by_key(|l| (l != "main", l.rsplit('-').next().and_then(|n| n.parse::<u32>().ok()), l.clone()));
labels
}
+7 -5
View File
@@ -1,5 +1,7 @@
//! Window groups without native tabs: one member is shown at a time, and the hidden ones are kept
//! at its frame so that selecting a tab only changes which window is visible.
use crate::windows::WorkbenchWindows;
use super::Group;
use crate::windows::WindowsState;
use ide_core::{IdeError, IdeResult};
@@ -153,12 +155,12 @@ fn sync_member_frames(app: &AppHandle, selected: &str) {
if group.selected != selected {
return;
}
let Some(from) = app.get_webview_window(selected) else { return };
let Some(from) = app.workbench_window(selected) else { return };
if from.is_fullscreen().unwrap_or(false) || from.is_minimized().unwrap_or(false) {
return;
}
for member in group.members.iter().filter(|member| member.as_str() != selected) {
let Some(to) = app.get_webview_window(member) else { continue };
let Some(to) = app.workbench_window(member) else { continue };
// A visible peer is the one being presented; never move it behind the user's back.
if to.is_visible().unwrap_or(false) {
continue;
@@ -194,7 +196,7 @@ pub(super) fn frame_changed(app: &AppHandle, label: &str) {
pub(super) fn present(app: &AppHandle, previous: &Group, target: &str, to: &WebviewWindow) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
if previous.selected != target
&& let Some(from) = app.get_webview_window(&previous.selected)
&& let Some(from) = app.workbench_window(&previous.selected)
{
show_at_frame(&from, to)?;
} else {
@@ -204,7 +206,7 @@ pub(super) fn present(app: &AppHandle, previous: &Group, target: &str, to: &Webv
}
for member in &previous.members {
if member != target
&& let Some(window) = app.get_webview_window(member)
&& let Some(window) = app.workbench_window(member)
{
window.hide().map_err(err)?;
}
@@ -215,7 +217,7 @@ pub(super) fn present(app: &AppHandle, previous: &Group, target: &str, to: &Webv
/// Shows the previously selected member again after a failed selection.
pub(super) fn restore_selection(app: &AppHandle, previous: &Group) {
for member in &previous.members {
if let Some(window) = app.get_webview_window(member) {
if let Some(window) = app.workbench_window(member) {
if member == &previous.selected {
let _ = window.show();
let _ = window.set_focus();
+63 -18
View File
@@ -289,7 +289,7 @@ pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Opt
};
if let Some(remote) = launch.remote.clone() {
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(&remote.target, &remote.path));
if let Some(w) = open.and_then(|label| app.get_webview_window(&label)) {
if let Some(w) = open.and_then(|label| app.workbench_window(&label)) {
return Ok(Some(w));
}
let title = remote
@@ -309,6 +309,7 @@ pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Opt
#[derive(Default)]
pub struct WindowsState {
primary: Mutex<HashMap<String, WebviewWindow>>,
pub groups: Mutex<ide_workspace::window_groups::WindowGroups>,
pub groups_restored: AtomicBool,
/// Serialises writes of the saved session. Holds the previous run's session once read: it is
@@ -355,6 +356,47 @@ pub(crate) struct AuxGeometry {
pub maximized: bool,
}
/// Tauri's WebviewWindow lookup and command argument both stop matching as soon as a
/// window has a second webview. Keep addressing its original, trusted workbench instead.
pub(crate) trait WorkbenchWindows {
fn workbench_window(&self, label: &str) -> Option<WebviewWindow>;
fn workbench_windows(&self) -> HashMap<String, WebviewWindow>;
}
impl WorkbenchWindows for AppHandle {
fn workbench_window(&self, label: &str) -> Option<WebviewWindow> {
self.state::<WindowsState>().primary.lock().get(label).cloned()
}
fn workbench_windows(&self) -> HashMap<String, WebviewWindow> {
self.state::<WindowsState>().primary.lock().clone()
}
}
pub struct WorkbenchWindow(WebviewWindow);
impl std::ops::Deref for WorkbenchWindow {
type Target = WebviewWindow;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> tauri::ipc::CommandArg<'a, tauri::Wry> for WorkbenchWindow {
fn from_command(item: tauri::ipc::CommandItem<'a, tauri::Wry>) -> Result<Self, tauri::ipc::InvokeError> {
let view = item.message.webview_ref();
view.app_handle()
.workbench_window(view.label())
.map(Self)
.ok_or_else(|| tauri::ipc::InvokeError::from("Not a workbench webview"))
}
}
impl specta::function::FunctionArg for WorkbenchWindow {
fn to_datatype(_: &mut specta::Types) -> Option<specta::datatype::DataType> {
None
}
}
impl WindowsState {
pub fn close_requested(&self, label: &str) {
let mut requests = self.close_requests.lock();
@@ -429,6 +471,7 @@ impl WindowsState {
}
pub fn forget(&self, label: &str) {
self.primary.lock().remove(label);
self.close_settled(label);
{
let mut launches = self.launches.lock();
@@ -614,7 +657,7 @@ pub fn state_key(label: &str) -> &str {
/// `parent`'s auxiliary windows that show its project's documents.
pub fn document_windows(app: &AppHandle, parent: &str) -> Vec<String> {
app.webview_windows()
app.workbench_windows()
.into_keys()
.filter(|label| auxiliary(label).is_some_and(|(kind, p)| kind.shares_documents() && p == parent))
.collect()
@@ -624,7 +667,7 @@ pub fn document_windows(app: &AppHandle, parent: &str) -> Vec<String> {
/// Windows with documents are destroyed: the parent's leave guard has already settled their
/// unsaved changes (`closeAuxiliaryWindows` in the UI).
pub fn close_auxiliary_windows(app: &AppHandle, parent: &str) {
for (label, window) in app.webview_windows() {
for (label, window) in app.workbench_windows() {
match auxiliary(&label) {
Some((kind, p)) if p == parent && kind.shares_documents() => drop(window.destroy()),
Some((_, p)) if p == parent => drop(window.close()),
@@ -635,7 +678,7 @@ pub fn close_auxiliary_windows(app: &AppHandle, parent: &str) {
/// Project windows, excluding auxiliary windows, for counting and cycling.
pub fn project_window_labels(app: &AppHandle) -> Vec<String> {
sorted_labels(app.webview_windows().keys().map(String::as_str).filter(|l| auxiliary_parent(l).is_none()))
sorted_labels(app.workbench_windows().keys().map(String::as_str).filter(|l| auxiliary_parent(l).is_none()))
}
/// Sort key: `main` first, then `project-<n>` by n, then anything else.
@@ -755,7 +798,7 @@ pub fn continue_quit(app: &AppHandle, closed: Option<&str>) {
let next = project_window_labels(app)
.into_iter()
.filter(|label| Some(label.as_str()) != closed)
.find_map(|label| app.get_webview_window(&label));
.find_map(|label| app.workbench_window(&label));
if let Some(window) = next {
focus(&window);
if window.close().is_err() {
@@ -769,7 +812,7 @@ pub fn continue_quit(app: &AppHandle, closed: Option<&str>) {
/// The window whose open project is `root` (already canonical).
pub fn find_project_window(app: &AppHandle, root: &Path) -> Option<WebviewWindow> {
let state = app.try_state::<AppState>()?;
app.webview_windows().into_iter().filter(|(label, _)| auxiliary_parent(label).is_none()).find_map(|(label, w)| {
app.workbench_windows().into_iter().filter(|(label, _)| auxiliary_parent(label).is_none()).find_map(|(label, w)| {
let project = state.project(&label).ok()?;
(project.root == root && !project.light).then_some(w)
})
@@ -788,7 +831,7 @@ fn send_files_at(app: &AppHandle, window: &WebviewWindow, files: Vec<PathBuf>, p
/// The focused window, else the last focused, else any.
pub fn target_window(app: &AppHandle) -> Option<WebviewWindow> {
let windows = app.webview_windows();
let windows = app.workbench_windows();
if let Some(w) = windows.values().find(|w| w.is_focused().unwrap_or(false)) {
return Some(w.clone());
}
@@ -863,6 +906,7 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
app.state::<WindowsState>().primary.lock().insert(window.label().into(), window.clone());
#[cfg(target_os = "linux")]
decorate_csd(&window);
#[cfg(target_os = "macos")]
@@ -977,7 +1021,7 @@ fn create_window_for(
let tab_target = if _restoring { None } else { crate::macos::new_project_tab_target(app, &launch)? };
// The label is free only until the window exists, so concurrent opens take turns.
let creating = CREATING.lock();
let windows = app.webview_windows();
let windows = app.workbench_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = window_config(app)?;
config.label = label.clone();
@@ -1113,7 +1157,7 @@ pub fn open_remote_window(
new_window: bool,
) -> IdeResult<OpenOutcome> {
tracing::info!("open_remote_window {target:?}:{path} new_window={new_window}");
let windows = app.webview_windows();
let windows = app.workbench_windows();
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(target, path));
if let Some(w) = open.and_then(|label| windows.get(&label)) {
focus(w);
@@ -1397,18 +1441,18 @@ pub(crate) fn run_open_at(
for step in steps {
match step {
OpenStep::Focus(label) => {
if let Some(w) = app.get_webview_window(&label) {
if let Some(w) = app.workbench_window(&label) {
focus(&w);
}
}
OpenStep::Files(label, files) => match app.get_webview_window(&label) {
OpenStep::Files(label, files) => match app.workbench_window(&label) {
Some(w) => send_files_at(app, &w, files, positions),
None => windows.add_files_at(&label, files, positions),
},
OpenStep::Launch(label, mut launch) => {
launch.add_positions(positions);
windows.set_launch(&label, *launch);
if let Some(w) = app.get_webview_window(&label) {
if let Some(w) = app.workbench_window(&label) {
let _ = app.emit_to(&label, LAUNCH_EVENT, ());
focus(&w);
}
@@ -1467,7 +1511,7 @@ fn dispatch_cli(app: &AppHandle, args: Vec<String>, cwd: String) {
{
let target = target_window(app)
.filter(|window| auxiliary_parent(window.label()).is_none())
.or_else(|| project_window_labels(app).into_iter().find_map(|label| app.get_webview_window(&label)));
.or_else(|| project_window_labels(app).into_iter().find_map(|label| app.workbench_window(&label)));
if let Some(window) = target {
let _ = app.emit_to(
window.label(),
@@ -1549,7 +1593,7 @@ fn open_diff_files_at(app: &AppHandle, diff: DiffFilesLaunch, wait_for_window: b
&& matches!(holds(app, window.label()), Holds::Nothing | Holds::Project(_) | Holds::LightEdit)
};
let target = target_window(app).filter(local).or_else(|| {
project_window_labels(app).into_iter().filter_map(|label| app.get_webview_window(&label)).find(local)
project_window_labels(app).into_iter().filter_map(|label| app.workbench_window(&label)).find(local)
});
if let Some(window) = target {
app.state::<WindowsState>().add_diff(window.label(), diff);
@@ -1614,7 +1658,7 @@ fn drain_cli(app: &AppHandle) {
}
pub fn cycle(app: &AppHandle, current: &str, forward: bool) {
let windows = app.webview_windows();
let windows = app.workbench_windows();
let sorted = project_window_labels(app);
if let Some(w) = cycle_target(&sorted, current, forward).and_then(|l| windows.get(&l)) {
focus(w);
@@ -1651,7 +1695,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
} else {
format!("{}-{parent_label}", aux.kind.name())
};
if let Some(existing) = app.get_webview_window(&label) {
if let Some(existing) = app.workbench_window(&label) {
if aux.launch != Launch::default() {
windows.set_launch(&label, aux.launch);
let _ = app.emit_to(label.as_str(), LAUNCH_EVENT, ());
@@ -1659,7 +1703,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
focus(&existing);
return Ok(());
}
let parent = app.get_webview_window(&parent_label).ok_or_else(|| IdeError::not_found("no parent window"))?;
let parent = app.workbench_window(&parent_label).ok_or_else(|| IdeError::not_found("no parent window"))?;
let mut config = window_config(app)?;
config.label = label.clone();
config.title = aux.title.into();
@@ -1703,6 +1747,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
windows.primary.lock().insert(label.clone(), window.clone());
#[cfg(target_os = "linux")]
decorate_csd(&window);
#[cfg(target_os = "macos")]
@@ -1786,7 +1831,7 @@ pub fn open_settings_from_menu(app: &AppHandle, target: &WebviewWindow, action:
else {
return false;
};
let Some(parent) = app.get_webview_window(parent_label) else {
let Some(parent) = app.workbench_window(parent_label) else {
return false;
};
match open_settings_window(app, &parent, page, new_projects, None) {
+2
View File
@@ -824,6 +824,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
@@ -2263,6 +2263,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. */
@@ -3909,6 +3912,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 } |
@@ -8510,6 +8531,12 @@ export type InspectSummary = {
elapsedMs: number,
};
export type InspectedElement = {
selector: string,
html: string,
styles: string,
};
export type InspectedFile = {
path: IpcPath,
relPath: string,
-12
View File
@@ -1916,18 +1916,6 @@
flex: none;
color: var(--fg-muted);
}
.toolDir {
flex: none;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 4px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
}
.toolPath {
flex: none;
max-width: 180px;
+3
View File
@@ -17,6 +17,7 @@ import {
maybeEditorService,
registerAgentContextSource,
registerEditorDropHandler,
provideAgentDraftAppender,
registerEditorKind,
registerMenuGroup,
registerMenuSlotItem,
@@ -44,6 +45,7 @@ import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
import { clearAgentTabFontZoom } from "./fontZoom";
import {
appendContextBlock,
closeActiveTask,
closeAndNewTask,
connect,
@@ -125,6 +127,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",
+2 -4
View File
@@ -17,7 +17,7 @@ import {
type TurnRow,
} from "./conversationRows";
import { Fold } from "./Folds";
import { commandTitle, samePropsExcept, shortTitle } from "./shared";
import { samePropsExcept, shortTitle } from "./shared";
import { ThoughtEntry, ToolEntry } from "./toolEntries";
/** "Edited 2 files · Read 4 files": what a run of work did; "Reasoning" when it only thought. */
@@ -124,9 +124,7 @@ export const ProcessRun = memo(function ProcessRun({
const live = [...tools].reverse().find(({ entry }) => liveTool(entry))?.entry;
const last = row.entries.at(-1)!.entry;
const current = live
? live.kind === "execute"
? commandTitle(task, live.title || live.kind).title
: shortTitle(task, live.title || live.kind)
? shortTitle(task, live.title || live.kind)
: working && last.type === "thought"
? tx("Thinking")
: null;
@@ -1,26 +0,0 @@
import { describe, expect, it } from "vitest";
import type { AgentTask } from "@/bindings";
import { commandTitle } from "./shared";
const task = { cwd: "/repo/app" } as AgentTask;
describe("commandTitle", () => {
it("drops a cd into the task's own folder", () => {
expect(commandTitle(task, "cd /repo/app && git grep -n foo")).toEqual({ title: "git grep -n foo", dir: null });
expect(commandTitle(task, "cd . ; ls")).toEqual({ title: "ls", dir: null });
});
it("keeps another folder as the place the command ran", () => {
expect(commandTitle(task, "cd /repo/app-icons && pnpm test")).toEqual({
title: "pnpm test",
dir: "/repo/app-icons",
});
expect(commandTitle(task, `cd "/repo/my app/" && ls`)).toEqual({ title: "ls", dir: "/repo/my app" });
});
it("leaves commands without a leading cd, or that are only a cd, as they are", () => {
expect(commandTitle(task, "git status && cd x && ls")).toEqual({ title: "git status && cd x && ls", dir: null });
expect(commandTitle(task, "cd /tmp")).toEqual({ title: "cd /tmp", dir: null });
expect(commandTitle(task, "cat /repo/app/src/a.ts")).toEqual({ title: "cat src/a.ts", dir: null });
});
});
-15
View File
@@ -21,21 +21,6 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Agent-written titles with the task's own folder dropped from paths. */
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
/** A leading `cd <dir> &&` (or `;`), with the directory quoted or bare. */
const LEADING_CD = /^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)\s*/;
/**
* A command's title without the `cd <dir> &&` agents put before every call, and the folder it
* moved to when that is not the task's own: the command is what tells calls apart.
*/
export function commandTitle(task: AgentTask, title: string): { title: string; dir: string | null } {
const match = LEADING_CD.exec(title);
if (!match || match[0].length === title.length) return { title: shortTitle(task, title), dir: null };
const dir = match[1]!.replace(/^(["'])(.*)\1$/, "$2").replace(/\/+$/, "");
const rest = shortTitle(task, title.slice(match[0].length));
return { title: rest, dir: dir === task.cwd || dir === "." ? null : dir };
}
/**
* `memo`'s comparison for props rebuilt with every render without changing: a prop named in
* `by` is equal when its rule says so, any other prop when it is the same value.
+2 -11
View File
@@ -16,7 +16,7 @@ import { cancelTask } from "../store";
import { openChangeDiff } from "./ChangesTab";
import { Fold } from "./Folds";
import { liveTool } from "./conversationRows";
import { commandTitle, shortTitle, useNow } from "./shared";
import { shortTitle, useNow } from "./shared";
/** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
@@ -104,22 +104,13 @@ export const ToolEntry = memo(function ToolEntry({
const live = liveTool(entry);
const took = toolDuration(entry);
const run = entry.kind === "execute" ? toolRun(entry) : null;
// Commands lose the `cd <dir> &&` agents start them with; another folder shows as a tag.
const { title, dir } =
entry.kind === "execute"
? commandTitle(task, entry.title || entry.kind)
: { title: shortTitle(task, entry.title || entry.kind), dir: null };
const title = shortTitle(task, entry.title || entry.kind);
// A title that already names the file ("Read pom.xml") needs no second link to it.
const links =
entry.kind === "execute" ? [] : entry.locations.slice(0, 3).filter((path) => !title.includes(basename(path)));
const head = (
<>
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} className={styles.toolKindIcon} />
{dir && (
<span className={styles.toolDir} title={dir}>
{basename(dir)}
</span>
)}
<span className={styles.toolTitle} title={entry.title || entry.kind}>
{title}
</span>
+13
View File
@@ -42,6 +42,7 @@ import {
cursorModelDefaults,
emptyDraft,
hasMention,
fenced,
isMentioned,
isPerModelOption,
mentionOf,
@@ -1694,6 +1695,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();
+2 -1
View File
@@ -36,7 +36,7 @@ import {
import { pushHistory, readHistory, setConsoleHistoryBrowser } from "./expressionHistory";
import { useExpressionCompletion } from "./ExpressionCompletion";
import { findOutputLinks, type OutputLink } from "@/features/run/links";
import { debugConsoleUrl, openTarget, openUrl, runDirectory } from "@/features/run/navigate";
import { consoleLinkMenu, debugConsoleUrl, openTarget, openUrl, runDirectory } from "@/features/run/navigate";
import { segmentLine, type SegmentMark } from "@/features/run/segments";
import styles from "./DebugToolWindow.module.css";
import { WidestColumns } from "@/platform/consoleColumns";
@@ -401,6 +401,7 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
e.preventDefault();
const selection = selectedOutput();
showContextMenu(e, [
...consoleLinkMenu(e.target),
{
label: "Copy",
icon: "copy",
+2 -1
View File
@@ -22,7 +22,7 @@ import { compileConsoleRules, matchConsoleRules, styleSpans, type ConsoleRuleMat
import { useConsoleRules } from "@/workbench/contributions";
import type { ConsoleLine, ConsoleModel } from "./console";
import { findOutputLinks, type OutputLink } from "./links";
import { debugConsoleUrl, openTarget, openUrl } from "./navigate";
import { consoleLinkMenu, debugConsoleUrl, openTarget, openUrl } from "./navigate";
import { segmentLine, type SegmentMark } from "./segments";
import styles from "./Run.module.css";
import { useConsoleSelection } from "./useConsoleSelection";
@@ -450,6 +450,7 @@ export function ConsoleView({
const selection = selectedOutput();
const foldText = foldLineText(selection, lineAt(e.target));
showContextMenu(e, [
...consoleLinkMenu(e.target),
{
label: "Copy",
icon: "copy",
+37
View File
@@ -8,6 +8,7 @@ import { streamSearch } from "@/platform/textSearch";
import { joinPath, type FileTarget } from "./links";
import { findRubyTest } from "./rubyTests";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui";
async function exists(path: string): Promise<boolean> {
const slash = path.lastIndexOf("/");
@@ -176,6 +177,42 @@ export function debugConsoleUrl(e: { metaKey: boolean; ctrlKey: boolean; shiftKe
return true;
}
/** Whether `url` can open in the Browser tool window: loopback HTTP(S) without credentials, trusted local project. */
export function opensInLocalBrowser(url: string): boolean {
if (
!isTauri() ||
!useProject.getState().project?.trusted ||
useRemote.getState().session ||
!getAction("web.openLocalBrowser") ||
!URL.canParse(url)
)
return false;
const { protocol, hostname, username, password } = new URL(url);
return (
(protocol === "http:" || protocol === "https:") &&
!username &&
!password &&
(hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d+){3}$/.test(hostname))
);
}
/**
* Context-menu entries for the console link under `target`: a loopback URL can open in the
* Browser tool window. A plain click keeps opening the external browser.
*/
export function consoleLinkMenu(target: EventTarget): MenuItem[] {
const url = (target as Element).closest?.("a[href]")?.getAttribute("href");
if (!url || !opensInLocalBrowser(url)) return [];
return [
{
label: "Open in Browser Tool Window",
icon: "toolwindow-web",
run: () => void executeAction("web.openLocalBrowser", url),
},
{ kind: "separator" },
];
}
export async function openUrl(url: string): Promise<void> {
try {
if (isTauri()) {
+191
View File
@@ -0,0 +1,191 @@
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, IconButton, Input } from "@/ui";
import { appendAgentDraftBlock } from "@/workbench/contributions";
import { closeBrowser, control, useBrowserSession, visit } from "./browserSession";
import styles from "./Web.module.css";
const EDGE = 8;
/** 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]') &&
// Corners sampled a little inside: the tool window's resize handles overlap its edges.
document.elementFromPoint(rect.left + EDGE, rect.top + EDGE) === node &&
document.elementFromPoint(rect.right - EDGE, rect.bottom - EDGE) === 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") : "";
const navigate = (action: "back" | "forward") => {
setDraft(null);
if (id !== null) void control(id, { type: action });
};
return (
<section className={styles.inspector} aria-label={t("Browser")}>
<form
className={styles.toolbar}
onSubmit={(e) => {
e.preventDefault();
const address = url.trim();
if (!address || (id !== null && !ready)) return;
void visit(address).then(() => {
if (!useBrowserSession.getState().error) setDraft((value) => (value?.trim() === address ? null : value));
});
}}
>
{ready && id !== null && (
<>
<IconButton icon="arrow-left" title="Back" disabled={!location?.canBack} onClick={() => navigate("back")} />
<IconButton
icon="arrow-right"
title="Forward"
disabled={!location?.canForward}
onClick={() => navigate("forward")}
/>
<IconButton icon="refresh" title="Reload" onClick={() => void control(id, { type: "reload" })} />
</>
)}
<Input
className={styles.address}
aria-label={t("Local page URL")}
// oxlint-disable-next-line jsx-a11y/no-autofocus -- the panel opens to type an address
autoFocus={id === null}
type="url"
required
value={url}
placeholder="http://localhost:3000"
autoComplete="off"
spellCheck={false}
onChange={(e) => setDraft(e.target.value)}
/>
{ready && id !== null && (
<>
<IconButton
icon="locate"
title="Inspect Element"
pressed={!!location?.inspecting}
onClick={() => void control(id, { type: location?.inspecting ? "cancel" : "inspect" })}
/>
<IconButton
icon="close"
title="Close"
onClick={() => {
setDraft(url);
closeBrowser();
}}
/>
</>
)}
</form>
{location?.inspecting && (
<p className={styles.hint} role="status">
{t("Click an element to inspect it")}
</p>
)}
{ready && id !== null ? (
<Viewport id={id} />
) : (
!error && <p className={styles.hint}>{t("Enter a localhost URL and press Enter.")}</p>
)}
{error && (
<p className={styles.hint} role="alert">
{error}
</p>
)}
{element && (
<div className={styles.details}>
<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>
</div>
)}
</section>
);
}
+53
View File
@@ -34,3 +34,56 @@
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: auto;
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: 8px 12px;
color: var(--fg-muted);
}
.viewport {
flex: 1 0 100px;
background: var(--bg-editor);
}
.details {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--space-2);
padding: 8px 12px 12px;
border-top: 1px solid var(--border);
}
.details h3 {
margin: 0;
font-size: inherit;
}
.details pre {
align-self: stretch;
margin: 0;
padding: 8px;
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;
}
+29
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 { closeBrowser, useBrowserSession, visit, 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: "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",
@@ -88,6 +102,21 @@ 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",
+17 -2
View File
@@ -2,6 +2,7 @@ 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", () => {
@@ -19,13 +20,27 @@ describe("auxiliaryWindow", () => {
it.each(["settings", "comparison", "diff", "editor", "deployment"])(
"grants %s windows permission to close",
(kind) => {
expect(capability.windows).toContain(`${kind}-*`);
expect(bridgeCapability.windows).toContain(`${kind}-*`);
expect(capability.webviews).toContain(`${kind}-*`);
expect(bridgeCapability.webviews).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();
+10
View File
@@ -1572,6 +1572,16 @@
"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",
+10
View File
@@ -2523,6 +2523,16 @@
"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": "在查找窗口中打开",
+4
View File
@@ -0,0 +1,4 @@
<!-- Copyright 2000-2025 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 1C11.866 1 15 4.13401 15 8C15 11.866 11.866 15 8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1ZM6.3125 11C6.44266 11.5858 6.60701 12.1103 6.79785 12.5557C7.03754 13.1149 7.29769 13.5039 7.53516 13.7383C7.76816 13.9681 7.92398 14 8 14C8.07602 14 8.23184 13.9681 8.46484 13.7383C8.70231 13.5039 8.96246 13.1149 9.20215 12.5557C9.39299 12.1103 9.55734 11.5858 9.6875 11H6.3125ZM2.80469 11C3.56455 12.3131 4.80678 13.3106 6.29004 13.751C5.86191 13.0564 5.51476 12.1085 5.28906 11H2.80469ZM10.7109 11C10.4852 12.1088 10.1372 13.0564 9.70898 13.751C11.1926 13.3108 12.4353 12.3133 13.1953 11H10.7109ZM2.34277 6C2.12157 6.62568 2 7.29857 2 8C2 8.70143 2.12157 9.37432 2.34277 10H5.125C5.04416 9.36626 5 8.69501 5 8C5 7.30499 5.04416 6.63374 5.125 6H2.34277ZM6.13379 6C6.04822 6.62358 6 7.29538 6 8C6 8.70462 6.04822 9.37642 6.13379 10H9.86621C9.95178 9.37642 10 8.70462 10 8C10 7.29538 9.95178 6.62358 9.86621 6H6.13379ZM10.875 6C10.9558 6.63374 11 7.30499 11 8C11 8.69501 10.9558 9.36626 10.875 10H13.6572C13.8784 9.37432 14 8.70143 14 8C14 7.29857 13.8784 6.62568 13.6572 6H10.875ZM6.29004 2.24805C4.80666 2.68836 3.56459 3.68685 2.80469 5H5.28906C5.51484 3.89108 5.86171 2.94268 6.29004 2.24805ZM8 2C7.92398 2 7.76816 2.03186 7.53516 2.26172C7.29769 2.49608 7.03754 2.88507 6.79785 3.44434C6.60701 3.88966 6.44266 4.41423 6.3125 5H9.6875C9.55734 4.41423 9.39299 3.88966 9.20215 3.44434C8.96246 2.88507 8.70231 2.49608 8.46484 2.26172C8.23184 2.03186 8.07602 2 8 2ZM9.70898 2.24805C10.1374 2.94272 10.4851 3.89085 10.7109 5H13.1953C12.4353 3.68659 11.1928 2.68823 9.70898 2.24805Z" fill="#6C707E"/>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

@@ -0,0 +1,4 @@
<!-- Copyright 2000-2025 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 1C14.9706 1 19 5.02944 19 10C19 14.9706 14.9706 19 10 19C5.02944 19 1 14.9706 1 10C1 5.02944 5.02944 1 10 1ZM7.86621 13.5C8.05352 14.3539 8.3019 15.1125 8.58887 15.7432C8.90888 16.4463 9.24777 16.9281 9.54297 17.2129C9.83894 17.4984 9.99403 17.5 10 17.5C10.006 17.5 10.1611 17.4984 10.457 17.2129C10.7522 16.9281 11.0911 16.4463 11.4111 15.7432C11.6981 15.1125 11.9465 14.3539 12.1338 13.5H7.86621ZM3.36621 13.5C4.25779 15.1864 5.77323 16.4904 7.60547 17.1074C7.06202 16.1681 6.61554 14.9285 6.33301 13.5H3.36621ZM13.667 13.5C13.3844 14.9287 12.9371 16.1681 12.3936 17.1074C14.2262 16.4905 15.7421 15.1866 16.6338 13.5H13.667ZM2.77148 8C2.59567 8.63686 2.5 9.30722 2.5 10C2.5 10.6928 2.59567 11.3631 2.77148 12H6.10742C6.03836 11.3567 6 10.6874 6 10C6 9.31256 6.03836 8.64327 6.10742 8H2.77148ZM7.61621 8C7.5417 8.63518 7.5 9.30499 7.5 10C7.5 10.695 7.5417 11.3648 7.61621 12H12.3838C12.4583 11.3648 12.5 10.695 12.5 10C12.5 9.30499 12.4583 8.63518 12.3838 8H7.61621ZM13.8926 8C13.9616 8.64327 14 9.31256 14 10C14 10.6874 13.9616 11.3567 13.8926 12H17.2285C17.4043 11.3631 17.5 10.6928 17.5 10C17.5 9.30722 17.4043 8.63686 17.2285 8H13.8926ZM7.60547 2.8916C5.7731 3.50862 4.25784 4.81354 3.36621 6.5H6.33301C6.61562 5.07117 7.06183 3.83096 7.60547 2.8916ZM10 2.5C9.99403 2.5 9.83894 2.50158 9.54297 2.78711C9.24777 3.0719 8.90888 3.5537 8.58887 4.25684C8.3019 4.88747 8.05352 5.64606 7.86621 6.5H12.1338C11.9465 5.64606 11.6981 4.88747 11.4111 4.25684C11.0911 3.5537 10.7522 3.0719 10.457 2.78711C10.1611 2.50158 10.006 2.5 10 2.5ZM12.3936 2.8916C12.9373 3.83101 13.3843 5.07095 13.667 6.5H16.6338C15.742 4.81327 14.2263 3.50849 12.3936 2.8916Z" fill="#6C707E"/>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1,4 @@
<!-- Copyright 2000-2025 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 1C14.9706 1 19 5.02944 19 10C19 14.9706 14.9706 19 10 19C5.02944 19 1 14.9706 1 10C1 5.02944 5.02944 1 10 1ZM7.86621 13.5C8.05352 14.3539 8.3019 15.1125 8.58887 15.7432C8.90888 16.4463 9.24777 16.9281 9.54297 17.2129C9.83894 17.4984 9.99403 17.5 10 17.5C10.006 17.5 10.1611 17.4984 10.457 17.2129C10.7522 16.9281 11.0911 16.4463 11.4111 15.7432C11.6981 15.1125 11.9465 14.3539 12.1338 13.5H7.86621ZM3.36621 13.5C4.25779 15.1864 5.77323 16.4904 7.60547 17.1074C7.06202 16.1681 6.61554 14.9285 6.33301 13.5H3.36621ZM13.667 13.5C13.3844 14.9287 12.9371 16.1681 12.3936 17.1074C14.2262 16.4905 15.7421 15.1866 16.6338 13.5H13.667ZM2.77148 8C2.59567 8.63686 2.5 9.30722 2.5 10C2.5 10.6928 2.59567 11.3631 2.77148 12H6.10742C6.03836 11.3567 6 10.6874 6 10C6 9.31256 6.03836 8.64327 6.10742 8H2.77148ZM7.61621 8C7.5417 8.63518 7.5 9.30499 7.5 10C7.5 10.695 7.5417 11.3648 7.61621 12H12.3838C12.4583 11.3648 12.5 10.695 12.5 10C12.5 9.30499 12.4583 8.63518 12.3838 8H7.61621ZM13.8926 8C13.9616 8.64327 14 9.31256 14 10C14 10.6874 13.9616 11.3567 13.8926 12H17.2285C17.4043 11.3631 17.5 10.6928 17.5 10C17.5 9.30722 17.4043 8.63686 17.2285 8H13.8926ZM7.60547 2.8916C5.7731 3.50862 4.25784 4.81354 3.36621 6.5H6.33301C6.61562 5.07117 7.06183 3.83096 7.60547 2.8916ZM10 2.5C9.99403 2.5 9.83894 2.50158 9.54297 2.78711C9.24777 3.0719 8.90888 3.5537 8.58887 4.25684C8.3019 4.88747 8.05352 5.64606 7.86621 6.5H12.1338C11.9465 5.64606 11.6981 4.88747 11.4111 4.25684C11.0911 3.5537 10.7522 3.0719 10.457 2.78711C10.1611 2.50158 10.006 2.5 10 2.5ZM12.3936 2.8916C12.9373 3.83101 13.3843 5.07095 13.667 6.5H16.6338C15.742 4.81327 14.2263 3.50849 12.3936 2.8916Z" fill="#CED0D6"/>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+4
View File
@@ -0,0 +1,4 @@
<!-- Copyright 2000-2025 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 1C11.866 1 15 4.13401 15 8C15 11.866 11.866 15 8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1ZM6.3125 11C6.44266 11.5858 6.60701 12.1103 6.79785 12.5557C7.03754 13.1149 7.29769 13.5039 7.53516 13.7383C7.76816 13.9681 7.92398 14 8 14C8.07602 14 8.23184 13.9681 8.46484 13.7383C8.70231 13.5039 8.96246 13.1149 9.20215 12.5557C9.39299 12.1103 9.55734 11.5858 9.6875 11H6.3125ZM2.80469 11C3.56455 12.3131 4.80678 13.3106 6.29004 13.751C5.86191 13.0564 5.51476 12.1085 5.28906 11H2.80469ZM10.7109 11C10.4852 12.1088 10.1372 13.0564 9.70898 13.751C11.1926 13.3108 12.4353 12.3133 13.1953 11H10.7109ZM2.34277 6C2.12157 6.62568 2 7.29857 2 8C2 8.70143 2.12157 9.37432 2.34277 10H5.125C5.04416 9.36626 5 8.69501 5 8C5 7.30499 5.04416 6.63374 5.125 6H2.34277ZM6.13379 6C6.04822 6.62358 6 7.29538 6 8C6 8.70462 6.04822 9.37642 6.13379 10H9.86621C9.95178 9.37642 10 8.70462 10 8C10 7.29538 9.95178 6.62358 9.86621 6H6.13379ZM10.875 6C10.9558 6.63374 11 7.30499 11 8C11 8.69501 10.9558 9.36626 10.875 10H13.6572C13.8784 9.37432 14 8.70143 14 8C14 7.29857 13.8784 6.62568 13.6572 6H10.875ZM6.29004 2.24805C4.80666 2.68836 3.56459 3.68685 2.80469 5H5.28906C5.51484 3.89108 5.86171 2.94268 6.29004 2.24805ZM8 2C7.92398 2 7.76816 2.03186 7.53516 2.26172C7.29769 2.49608 7.03754 2.88507 6.79785 3.44434C6.60701 3.88966 6.44266 4.41423 6.3125 5H9.6875C9.55734 4.41423 9.39299 3.88966 9.20215 3.44434C8.96246 2.88507 8.70231 2.49608 8.46484 2.26172C8.23184 2.03186 8.07602 2 8 2ZM9.70898 2.24805C10.1374 2.94272 10.4851 3.89085 10.7109 5H13.1953C12.4353 3.68659 11.1928 2.68823 9.70898 2.24805Z" fill="#CED0D6"/>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

+1
View File
@@ -250,6 +250,7 @@ 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",
+16
View File
@@ -1026,6 +1026,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;