Compare commits

..
Author SHA1 Message Date
l0ng-ai 4a9cf256bc fix(agents): show the changes scope as compact tool window tabs
The Whole Task / Last Turn switch in the agent Changes pane was a full-width
segmented pill. It now uses the compact Tabs strip that tool window sub-views
use elsewhere.
2026-11-23 15:18:24 +08:00
62 changed files with 445 additions and 1551 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 160 KiB

+3 -3
View File
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
## Manage agents
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
### External MCP servers
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
+1 -1
View File
@@ -20,7 +20,7 @@ A file holds only the values that differ from the layer below. Tables merge key
Some settings are ignored in the project file: `mcpServer`, imported color schemes (`editor.customSchemes`) and `agents.newTaskApprovals` are global only. Project trust is never read from settings.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › MCP Connections**, and again after its definition changes.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › External MCP Servers**, and again after its definition changes.
## File format
+3 -3
View File
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
## 管理 agent
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
**设置 › 智能体 › MCP 连接** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
+1 -1
View File
@@ -20,7 +20,7 @@ description: "OpenIDEA 的设置保存在哪里、全局文件与项目文件如
有些设置在项目文件中会被忽略:`mcpServer`、导入的配色方案(`editor.customSchemes`)和 `agents.newTaskApprovals` 只能全局配置。项目信任状态永远不会从设置文件中读取。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › MCP 连接** 中将其开启;服务器定义改变后也需要重新开启。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › 外部 MCP 服务器** 中将其开启;服务器定义改变后也需要重新开启。
## 文件格式
+4 -8
View File
@@ -308,15 +308,11 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
await sessionPopup.getByRole("button", { name: "Reset" }).click();
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
// 2. Jump directly from the session MCP popover's gear button to Settings › Agents › MCP Connections.
await sessionPopup.getByRole("button", { name: "MCP Connections…", exact: true }).click();
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "MCP Connections", exact: true })).toBeVisible();
await expect(settingsDialog.getByRole("treeitem", { name: "MCP Connections", exact: true })).toHaveAttribute(
"aria-selected",
"true",
);
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
@@ -325,7 +321,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "MCP Connections", exact: true })
.getByRole("heading", { name: "External MCP Servers" })
.evaluate((el) => el.scrollIntoView({ block: "start" }));
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
-83
View File
@@ -1,83 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("New Worktree keeps form fields aligned and creates the selected worktree in a short window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 740 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/acme-api";
const service = `${root}/service`;
window.__ipc.handlers.vcs_branches = () => [{ name: "main", current: true, remote: false }];
window.__ipc.handlers.vcs_tags = () => [];
window.__ipc.handlers.vcs_worktrees = ({ repo }) => [{ path: repo, branch: "main", main: true, submodule: false }];
window.__ipc.handlers.vcs_worktree_include = () => ({ exists: true });
window.__ipc.handlers.vcs_add_worktree = () => ({ copyWarning: null, setupWarning: null });
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ root, roots: [root, service], repo: root, available: true });
const context = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ context);
setContext("vcsAvailable", true);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("vcs.newWorktree");
});
const dialog = page.getByRole("dialog", { name: "New Worktree" });
const name = dialog.getByRole("textbox", { name: "Name:" });
const branch = dialog.getByRole("textbox", { name: "New branch name" });
const location = dialog.getByRole("textbox", { name: "Location:" });
const repository = dialog.getByRole("button", { name: "Repository", exact: true });
const checkout = dialog.getByRole("button", { name: "Check out", exact: true });
const setup = dialog.getByRole("checkbox", { name: "Run setup script" });
const script = dialog.getByRole("textbox", { name: "Setup script:" });
await expect(name).toHaveValue("acme-api-main-wt");
await branch.fill("review/ledger-batch");
await name.fill("ledger-review");
await location.fill("/dev/reviews");
await setup.check();
await script.fill("/dev/setup.sh");
const preview = dialog.getByText("Worktree location: /dev/reviews/ledger-review", { exact: true });
await expect(preview).toBeVisible();
for (const size of [
{ width: 1120, height: 740 },
{ width: 440, height: 520 },
]) {
await page.setViewportSize(size);
const column = (await name.boundingBox())!.x;
for (const [label, field] of [
["Name:", name],
["Location:", location],
["Repository:", repository],
["Check out:", checkout],
["Create a new branch", branch],
["Setup script:", script],
] as const) {
const caption = dialog.getByText(label, { exact: true });
await expect(caption).toBeVisible();
const captionBox = (await caption.boundingBox())!;
const fieldBox = (await field.boundingBox())!;
expect(fieldBox.x, label).toBeCloseTo(column, 0);
expect(captionBox.x + captionBox.width, label).toBeLessThanOrEqual(fieldBox.x);
expect(captionBox.y + captionBox.height / 2, label).toBeCloseTo(fieldBox.y + fieldBox.height / 2, 0);
}
expect((await preview.boundingBox())!.x).toBeCloseTo(column, 0);
}
await setup.uncheck();
await expect(script).toHaveCount(0);
await dialog.getByRole("button", { name: "Create", exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(await ipcCalls(page, "vcs_add_worktree")).toEqual([
{
repo: "/dev/acme-api",
path: "/dev/reviews/ledger-review",
commitish: "refs/heads/main",
newBranch: "review/ledger-batch",
copyConfig: true,
setup: null,
},
]);
});
-2
View File
@@ -385,8 +385,6 @@ test("edits and stages from the index in unified diffs of read-only files", asyn
const index = modal.locator('.cm-content[aria-label="Staged (index)"]');
await expect(index).toBeEditable();
await expect(index).toHaveText(/val alpha = "index"\s+val alpha = "local"/, { useInnerText: true });
await expect(modal.locator(".cm-diffNumbers-modified .cm-diffWidgetNumber")).toHaveText(["1", "3"]);
await expect(modal.locator(".cm-diffNumbers-original .cm-diffWidgetNumber")).toHaveCount(0);
const setReadOnly = (readOnly: boolean) =>
page.evaluate((readOnly) => window.__ipc.handlers.test_set_readonly?.({ readOnly }), readOnly);
await setReadOnly(false);
-79
View File
@@ -1,79 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("groups stashes by repository and keeps the selected stash actions scoped", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(async () => {
const main = "/dev/acme-api";
const service = `${main}/warehouse-api`;
const stash = (index: number, id: string, title: string) => ({
index,
id,
message: `On main: ${title}`,
base: "base",
timeMs: new Date(2025, 4, 14, 10, 30).getTime(),
});
const handlers = window.__ipc.handlers;
handlers.vcs_stashes = ({ repo }) =>
repo === service
? [stash(0, "warehouse-stash", "Review warehouse routing")]
: [stash(0, "ledger-stash", "Check totals"), stash(1, "invoice-stash", "Match invoice balances")];
handlers.vcs_commit_files = ({ repo }) => [
{ path: repo === service ? "routing.txt" : "totals.txt", kind: "modified", oldPath: null },
];
const store = "/src/features/vcs/store.ts";
const context = "/src/platform/context.ts";
const actions = "/src/platform/actions.ts";
const toolWindows = "/src/workbench/toolwindows/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
const { setContext } = await import(/* @vite-ignore */ context);
const { executeAction } = await import(/* @vite-ignore */ actions);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ toolWindows);
useVcs.setState({ available: true, root: main, repo: main, roots: [main, service] });
setContext("vcsAvailable", true);
moveToolWindow("commit", "bottom");
await executeAction("vcs.showStashes");
setToolWindowSize("bottom", 310);
});
const tree = page.getByRole("tree", { name: "Stashes", exact: true });
const main = tree.getByRole("treeitem").filter({ has: page.getByText("acme-api", { exact: true }) });
const service = tree.getByRole("treeitem", { name: /warehouse-api/ });
const apply = page
.getByRole("toolbar", { name: "Stashes", exact: true })
.getByRole("button", { name: "Apply Stash" });
const first = tree.getByRole("treeitem", { name: /Check totals/ });
await expect(service, "repository group starts expanded").toHaveAttribute("aria-expanded", "true");
await expect(main).toHaveAccessibleName(/acme-api\s*2/);
await expect(first).toHaveAttribute("aria-level", "2");
await expect(first).toHaveAttribute("aria-selected", "true");
for (const width of [1100, 440]) {
await page.setViewportSize({ width, height: 720 });
const subject = first.getByText("Check totals", { exact: true });
const date = subject.locator("xpath=following-sibling::*[1]");
await expect(date).toHaveText(/2025/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(date).toHaveCSS("font-size", await subject.evaluate((el) => getComputedStyle(el).fontSize));
const titleBox = (await subject.boundingBox())!;
const dateBox = (await date.boundingBox())!;
expect(dateBox.x - titleBox.x - titleBox.width).toBeCloseTo(6, 0);
}
await tree.focus();
await tree.press("Home");
await tree.press("ArrowLeft");
await expect(main).toHaveAttribute("aria-expanded", "false");
await expect(first).toHaveCount(0);
await expect(apply).toBeDisabled();
await expect(page.getByText("Select a stash to view its changes.")).toBeVisible();
await tree.press("ArrowRight");
await expect(first).toBeVisible();
await tree.getByText("Review warehouse routing", { exact: true }).click();
await expect(apply).toBeEnabled();
await expect(page.getByRole("tree", { name: "Changed files" }).getByText("routing.txt")).toBeVisible();
expect((await ipcCalls(page, "vcs_commit_files")).at(-1)).toEqual({
repo: "/dev/acme-api/warehouse-api",
commit: "warehouse-stash",
});
});
-123
View File
@@ -1,123 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function seedReview(page: Page) {
await stubDesktop(page);
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const context = "/src/platform/context.ts";
const repositoryStore = "/src/features/github/data/repository.ts";
const pullRequests = "/src/features/github/data/pullRequest.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { setContext } = await import(/* @vite-ignore */ context);
const { useGhRepository } = await import(/* @vite-ignore */ repositoryStore);
const { setPullRequestData } = await import(/* @vite-ignore */ pullRequests);
useProject.setState((s: { settings: { editor: unknown } }) => ({
settings: {
...s.settings,
editor: { ...(s.settings?.editor as object), fontFamily: "Courier New", fontSize: 17, lineHeight: 25 },
},
}));
const coordinates = { owner: "sample", name: "settlement" };
useGhRepository.setState({
connection: {
coordinates,
repository: { id: "repository", nameWithOwner: "sample/settlement" },
currentUser: { id: "reviewer", login: "reviewer" },
root: null,
remotes: [],
},
});
setContext("githubConnected", true);
setContext("githubCurrentBranchPullRequest", true);
setPullRequestData(7, "details", () => ({ number: 7, viewerDidAuthor: false }));
setPullRequestData(7, "pendingReview", () => ({ id: "draft-seven", state: "PENDING", commentsCount: 12 }));
});
}
async function openReview(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("github.pullRequest.submitReview", 7);
});
}
test("centers the unanchored composer, follows the editor font and reflows its review actions", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 840 });
await seedReview(page);
await openReview(page);
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const verticalCenter = () =>
popup.evaluate((el) => {
const { top, height } = el.getBoundingClientRect();
return Math.abs(top + height / 2 - innerHeight / 2);
});
await expect.poll(verticalCenter, { message: "verticalCenter at standard size" }).toBeLessThan(1);
await expect(editor).toBeFocused();
await expect(editor).toHaveCSS("font-size", "17px");
await expect(editor).toHaveCSS("line-height", "25px");
await expect(editor).toHaveCSS("font-family", /Courier New/);
await editor.fill("Please double-check the rounding step.");
const grip = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 56, grip.y + grip.height / 2 + 32);
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(540);
await page.setViewportSize({ width: 300, height: 400 });
await expect.poll(verticalCenter, { message: "verticalCenter after shrinking" }).toBeLessThan(1);
const approve = (await popup.getByRole("button", { name: "Approve", exact: true }).boundingBox())!;
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
expect(comment.y).toBeGreaterThan(approve.y);
expect(comment.x + comment.width).toBeLessThan(300);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await editor.press("Escape");
await expect(popup).toHaveCount(0);
await openReview(page);
await expect(editor).toHaveValue("Please double-check the rounding step.");
});
test("keeps anchored review controls and the comment visible after a long submission error", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 355, height: 390 });
await seedReview(page);
await page.evaluate(async () => {
const path = "/src/features/github/details/SubmitReviewPopup.tsx";
const { showSubmitReview } = await import(/* @vite-ignore */ path);
const anchor = document.createElement("button");
anchor.style.cssText = "position:fixed;top:350px;left:275px;";
anchor.textContent = "Review anchor";
document.body.append(anchor);
window.__ipc.handlers.gh_api = ({ request }) => {
const { query } = JSON.parse((request as { body: string }).body);
if (!query.includes("submitPullRequestReview")) throw Error("Unexpected GitHub request");
return JSON.stringify({ errors: [{ message: "Review request failed. " + "outdated-reference-".repeat(35) }] });
};
void showSubmitReview(7, anchor);
});
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const button = popup.getByRole("button", { name: "Comment", exact: true });
await editor.fill("Check the batch limit.");
await button.click();
const error = popup.getByRole("alert");
await expect(error).toContainText("Review request failed.");
await expect(button).toBeEnabled();
await expect(editor).toHaveValue("Check the batch limit.");
const box = (await popup.boundingBox())!;
const buttonBox = (await button.boundingBox())!;
expect(box.y + box.height).toBeLessThan(350);
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(box.y + box.height);
expect(box.x + box.width).toBeLessThanOrEqual(355);
await expect.poll(() => error.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
const calls = await ipcCalls(page, "gh_api");
expect(calls).toHaveLength(1);
const { variables } = JSON.parse((calls[0]!.request as { body: string }).body);
expect(variables).toEqual({ reviewId: "draft-seven", event: "COMMENT", body: "Check the batch limit." });
});
-88
View File
@@ -1,88 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openDiff(page: Page, left: string, right: string, options: Record<string, unknown> = {}) {
await page.evaluate(
async ({ left, right, options }) => {
localStorage.setItem(
"openidea.vcs.diffOptions",
JSON.stringify({ mode: "unified", collapse: false, ...options }),
);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("diff.compareTexts", {
path: "SettlementRules.txt",
left: { text: left, label: "Original" },
right: { text: right, label: "Modified" },
});
},
{ left, right, options },
);
return page.getByRole("toolbar", { name: "Diff" });
}
async function rowNumbers(page: Page, text: string, deleted = false) {
return page
.locator(deleted ? ".cm-deletedLine" : ".cm-line")
.filter({ hasText: text })
.evaluate((row) => {
const top = row.getBoundingClientRect().top;
const editor = row.closest(".cm-editor")!;
const read = (side: string) =>
[...editor.querySelectorAll(`.cm-diffNumbers-${side} :is(.cm-gutterElement, .cm-diffWidgetNumber)`)].find(
(number) =>
getComputedStyle(number).visibility === "visible" && Math.abs(number.getBoundingClientRect().top - top) < 1,
)?.textContent ?? null;
return [read("original"), read("modified")];
});
}
test("Unified Diff keeps original and modified numbers aligned with wrapped and removed lines", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1000, height: 640 });
const oldRule = "Obsolete settlement rule " + "requires review for each exceptional invoice. ".repeat(3);
const toolbar = await openDiff(
page,
["Settlement rules", oldRule, "Retire legacy routing", "Report totals", "Finish batch"].join("\n"),
["Settlement rules", "Validate settlement currency", "Report totals", "Finish batch"].join("\n"),
{ softWrap: true },
);
await expect(toolbar).toContainText("1 difference");
for (const width of [1000, 440]) {
await page.setViewportSize({ width, height: 640 });
await expect.poll(() => rowNumbers(page, "Obsolete settlement rule", true)).toEqual(["2", null]);
await expect.poll(() => rowNumbers(page, "Retire legacy routing", true)).toEqual(["3", null]);
await expect.poll(() => rowNumbers(page, "Validate settlement currency")).toEqual([null, "2"]);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["4", "3"]);
}
const removed = page.locator(".cm-deletedLine").filter({ hasText: "Obsolete settlement rule" });
const lineHeight = await removed.evaluate((el) => parseFloat(getComputedStyle(el).lineHeight));
expect((await removed.boundingBox())!.height).toBeGreaterThan(lineHeight * 2);
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(toolbar).toContainText("1 of 1 differences");
});
test("Unified Diff numbers account for ignored empty lines and a removal at EOF without a newline", async ({
workbench: page,
}) => {
await openDiff(
page,
"Settlement rules\n\nReport totals\nFinish batch\nRemove final rule",
"Settlement rules\nReport totals\nFinish batch",
{ ignore: "whitespaceAndLines" },
);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["3", "2"]);
await expect.poll(() => rowNumbers(page, "Finish batch")).toEqual(["4", "3"]);
await expect.poll(() => rowNumbers(page, "Remove final rule", true)).toEqual(["5", null]);
});
test("Unified Diff follows vertical scrolling inside one large removal", async ({ workbench: page }) => {
const removed = Array.from({ length: 250 }, (_, i) => `Retired workflow ${i + 1}.`);
await openDiff(page, ["Start batch", ...removed, "Finish batch"].join("\n"), "Start batch\nFinish batch");
const target = page.locator(".cm-deletedLine").filter({ hasText: "Retired workflow 229." });
await target.scrollIntoViewIfNeeded();
await expect.poll(() => rowNumbers(page, "Retired workflow 229.", true)).toEqual(["230", null]);
});
-74
View File
@@ -417,79 +417,6 @@ function leadingCommentStart(state: EditorState, a: number): number {
export type StatementMove = { spec: TransactionSpec } | "noop" | "line";
/** A `case` / `default` label whose branch body follows as its siblings (Go, JavaScript, Java). */
const CASE_LABEL = /^(Case|CaseLabel|DefaultLabel|SwitchLabel)$/;
/**
* Move Statement on a `case` label of a switch whose branches are flat
* (label, then the body as siblings): the branch, from its first stacked
* label to its last non-blank line, swaps with the neighbouring branch, as
* IDEA's case block mover does. `noop` at the first / last branch.
*/
function planCaseMove(state: EditorState, label: Node, up: boolean): StatementMove {
const doc = state.doc;
const block = label.parent!;
const close = doc.lineAt(block.to).number;
const isLabel = (l: number) => {
const n = statementStartingAt(state, l);
return !!n && CASE_LABEL.test(n.type.name) && n.parent?.from === block.from && n.parent.to === block.to;
};
const start = (l: number) => {
while (l > 1 && isLabel(l - 1)) l--;
return l;
};
// The line where the branch starting at `l` ends: its last non-blank line before the next branch or the closing brace.
const end = (l: number) => {
let k = l + 1;
while (k < close && isLabel(k)) k++;
while (k < close && !isLabel(k)) k++;
k--;
while (k > l && firstToken(state, k) === null) k--;
return k;
};
const a = start(doc.lineAt(label.from).number);
const b = end(a);
let s: number;
let e: number;
if (up) {
let p = a - 1;
while (p > 0 && doc.line(p).from > block.from && !isLabel(p)) p--;
if (p < 1 || doc.line(p).from <= block.from || !isLabel(p)) return "noop";
s = start(p);
e = end(s);
} else {
let n = b + 1;
while (n < close && !isLabel(n)) n++;
if (n >= close) return "noop";
s = n;
e = end(n);
}
const [first, second] = up
? [
{ s, e },
{ s: a, e: b },
]
: [
{ s: a, e: b },
{ s, e },
];
const from = doc.line(first.s).from;
const to = doc.line(second.e).to;
const textFirst = state.sliceDoc(from, doc.line(first.e).to);
const textSecond = state.sliceDoc(doc.line(second.s).from, to);
const between = state.sliceDoc(doc.line(first.e).to, doc.line(second.s).from);
const head = state.selection.main.head;
const movedFrom = up ? from : from + textSecond.length + between.length;
return {
spec: {
changes: { from, to, insert: textSecond + between + textFirst },
selection: EditorSelection.cursor(movedFrom + (head - doc.line(a).from)),
scrollIntoView: true,
userEvent: "move.line",
},
};
}
/**
* Move Statement as in IDEA: the statement around the caret (whole lines)
* moves past the next statement; into a block when the neighbour is a block
@@ -502,7 +429,6 @@ export function planStatementMove(state: EditorState, up: boolean): StatementMov
const head = state.selection.main.head;
const cur = statementAround(state, head);
if (!cur) return "line";
if (CASE_LABEL.test(cur.type.name) && cur.parent) return planCaseMove(state, cur, up);
const doc = state.doc;
if (/^[{}]$/.test(cur.type.name)) {
for (let g: Node | null = cur.parent; g; g = g.parent)
-29
View File
@@ -67,7 +67,6 @@ function show(view: EditorView): string {
const javascript = await languages.find((l) => l.name === "JavaScript")!.load();
const yaml = await languages.find((l) => l.name === "YAML")!.load();
const goLang = await languages.find((l) => l.name === "Go")!.load();
describe("Move Statement", () => {
it("moves a multi-line statement as a whole, never one of its lines", () => {
@@ -95,34 +94,6 @@ describe("Move Statement", () => {
expect(v.state.doc.toString()).toBe("function f() {\n a();\n}\nb();");
});
it("moves a Go switch case with its whole body past the neighbouring case", () => {
const go = make(
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tdefault:\n\t\treturn -1\n\t}\n}",
goLang,
);
moveStatementUp(go);
expect(show(go)).toBe(
"func f(n int) int {\n\tswitch n {\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\t}\n}",
);
moveStatementUp(go);
expect(go.state.doc.toString()).toContain("switch n {\n\tcase 1:\n\t\tv := 1");
moveStatementDown(go);
moveStatementDown(go);
expect(show(go)).toBe(
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\t}\n}",
);
moveStatementDown(go);
expect(go.state.doc.toString()).toContain("\t\treturn v\n\t}\n}");
});
it("moves a JavaScript case with its stacked labels and blank line kept between branches", () => {
const v = make("switch (x) {\n case 1:\n a();\n break;\n\n case 2:\n |case 3:\n b();\n}", javascript);
moveStatementUp(v);
expect(v.state.doc.toString()).toBe(
"switch (x) {\n case 2:\n case 3:\n b();\n\n case 1:\n a();\n break;\n}",
);
});
it("passes a neighbouring function as a whole", () => {
const v = make("|a();\nfunction f() {\n b();\n}", javascript);
moveStatementDown(v);
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Agent Setup lists every agent, with those this machine can run first
* Settings › Agents › Coding Agents: one searchable list of every agent, those this machine can run first
* (built in, installed from the ACP Registry, or defined in an agent file), then those it
* can install. The selected agent's page holds its actions, the settings its new tasks
* start with, and how it is launched. Launch edits are staged until Apply; installs run in
+3 -2
View File
@@ -1,5 +1,6 @@
/**
* Command Rules defines the allow and block patterns for agent permission requests.
* Settings › Tools › Agents › Command Permissions: whitelist (auto-approve)
* and blacklist (auto-reject) command patterns evaluated on agent permission requests.
*/
import { useMemo, useState } from "react";
import { tx } from "@/platform/i18n";
@@ -46,7 +47,7 @@ export function AgentPolicyPage() {
};
return (
<section className={styles.body} aria-label={tx("Command Rules")}>
<section className={styles.body} aria-label="Command Permissions">
<p className={styles.notice}>
<T>
Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected,
+1 -1
View File
@@ -1,4 +1,4 @@
/** Settings › Agents › Agent Setup. */
/** Settings › Agents › Coding Agents. */
import { AgentList } from "./AgentList";
import { tauriCommands, tauriRegistry, type CommandsBackend, type RegistryBackend } from "./registry";
import styles from "./AgentRegistry.module.css";
+1 -2
View File
@@ -224,12 +224,11 @@
flex: none;
}
/* Keep the import list height stable while filtering. */
/* Import Sessions from Other Apps: filter above a fixed-height list, so the dialog doesn't grow. */
.chooser {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: var(--space-3) var(--space-4) 0;
}
.chooserList {
height: 312px;
+5 -6
View File
@@ -281,9 +281,8 @@ describe("Agents docked view", () => {
]);
});
it("lists Import Sessions in Find Action", () => {
it("lists Import Sessions from Other Apps in Find Action", () => {
const action = taskActions.find((a) => a.id === "agents.importSessions");
expect(action?.title).toBe("Import Sessions…");
expect(action?.hidden).toBeFalsy();
expect(action?.when).toBe("projectOpen");
act(() => void action?.run({} as never));
@@ -503,17 +502,17 @@ describe("Agents pinned and grouped tasks", () => {
expect(rows.some((text) => text.includes("one"))).toBe(true);
});
it("offers the groups, a new one and a way out in the Group submenu", () => {
it("offers the groups, a new one and a way out in Move to Group", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: { two: "g1" }, pinned: [] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Group");
const move = menu.find((item) => "label" in item && item.label === "Move to Group");
expect(move).toBeDefined();
const submenu = (move as { submenu: { label?: string; checked?: boolean }[] }).submenu;
expect(submenu.map((item) => item.label ?? "separator")).toEqual([
"Frontend",
"separator",
"New Group…",
"No Group",
"Remove from Group",
]);
expect(submenu[0]).toMatchObject({ checked: true });
});
@@ -521,7 +520,7 @@ describe("Agents pinned and grouped tasks", () => {
it("moves a pinned task into a group, out of the pinned section", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: {}, pinned: ["two"] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Group") as {
const move = menu.find((item) => "label" in item && item.label === "Move to Group") as {
submenu: { label?: string; run?: () => void }[];
};
act(() => move.submenu.find((item) => item.label === "Frontend")!.run!());
+2 -2
View File
@@ -1,4 +1,4 @@
/** Pick external sessions and import them as agent tasks. */
/** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui";
import { useRowHeight } from "@/ui/density";
@@ -160,7 +160,7 @@ function ImportSessionsDialog() {
<Dialog
open
onClose={close}
title="Import Sessions"
title="Import Sessions from Other Apps"
width={560}
footerStart={
<span className={styles.chooserFooter}>
+2 -2
View File
@@ -1,7 +1,7 @@
/**
* Per-session MCP picker for the New Task and Session composers: shows inherited IDE, Project,
* Global, and Agent-Native CLI MCP servers, lets the user toggle servers for this session only,
* reset session overrides, or jump to Settings › Agents › MCP Connections.
* reset session overrides, or jump to Settings › Agents › External MCP Servers.
*/
import { useMemo, useState } from "react";
import type { McpExternalSource, McpServer } from "@/bindings";
@@ -110,7 +110,7 @@ export function McpPicker({
}}
triggerAriaLabel={tx("MCP servers")}
popupTitle={tx("Session MCP Servers")}
settingsTitle={tx("MCP Connections…")}
settingsTitle={tx("External MCP Servers…")}
settingsPage={MCP_PAGE}
counts={{ active: resolved.activeCount, total: resolved.totalCount, overrides: resolved.overrideCount }}
search={{ placeholder: tx("Filter MCP servers…"), ariaLabel: tx("Filter MCP servers"), shown: totalRows > 5 }}
+2 -2
View File
@@ -1,5 +1,5 @@
/**
* Settings › Agents › MCP Connections: multi-level MCP management across Global (`settings.toml`
* Settings › Agents › External MCP Servers: multi-level MCP management across Global (`settings.toml`
* + Keychain), Project (`.openidea/settings.toml`), and Agent CLI config directories
* (`~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`,
* `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, `.vscode/mcp.json`), with
@@ -535,7 +535,7 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB
<div className={page.page}>
<div className={page.header}>
<h2 className={page.title}>
<T>MCP Connections</T>
<T>External MCP Servers</T>
</h2>
<div className={page.headerActions}>
<Button
+1 -3
View File
@@ -202,8 +202,6 @@
overflow-x: hidden;
overflow-anchor: none;
padding: var(--space-3);
/* Room below the end that keeps the header of a section folded there in place (`Stream`). */
padding-bottom: calc(var(--space-3) + var(--stream-slack, 0px));
display: flex;
flex-direction: column;
font-size: var(--agent-fs-ui, var(--fs-ui));
@@ -231,7 +229,7 @@
content-visibility: auto;
}
/* WebKit leaves a stale selection highlight on rows that skipped rendering (`useOffscreenRows`). */
.conversationRow[data-measured][data-selection] {
.stream[data-selection] > .conversationRow[data-measured] {
content-visibility: visible;
}
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
+3 -3
View File
@@ -32,7 +32,7 @@ function FormWrapper({ children }: { children: ReactNode }) {
return <SettingsFormContext.Provider value={form}>{children}</SettingsFormContext.Provider>;
}
describe("Command Rules sub-page", () => {
describe("Command Permissions sub-page", () => {
it("registers under Agents group in settings", () => {
const dispose = activateSettingsPages();
try {
@@ -40,7 +40,7 @@ describe("Command Rules sub-page", () => {
const agentsGroup = tree.find((n) => n.title === AGENTS_GROUP);
expect(agentsGroup).toBeDefined();
const policyNode = agentsGroup?.children.find((n) => n.key === POLICY_PAGE);
expect(policyNode?.title).toBe("Command Rules");
expect(policyNode?.title).toBe("Command Permissions");
// A project's settings file can't decide what agents run without asking.
expect(policyNode?.page?.projectScope).not.toBe(true);
} finally {
@@ -56,7 +56,7 @@ describe("Command Rules sub-page", () => {
</FormWrapper>,
);
const policy = screen.getByRole("region", { name: "Command Rules" });
const policy = screen.getByRole("region", { name: "Command Permissions" });
expect(within(policy).getByText("rm -rf *")).toBeInTheDocument();
fireEvent.change(within(policy).getByRole("textbox", { name: "Allowed command pattern" }), {
+5 -4
View File
@@ -313,7 +313,7 @@ export function activate(): () => void {
{
id: "agents.addAgent",
title: "More Agents…",
description: "Install, update, or remove agents from the ACP Registry.",
description: "Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.",
category: "Agents",
icon: "plugin",
keywords: ["agent", "acp", "registry", "install", "update"],
@@ -321,11 +321,12 @@ export function activate(): () => void {
},
{
id: "agents.mcpServers",
title: "MCP Connections…",
description: "Configure the MCP servers that agents can use.",
title: "External MCP Servers…",
description:
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
category: "Agents",
icon: "settings",
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
run: () => void executeAction("file.settings", MCP_PAGE),
},
{
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* Shared MCP server model, multi-level inheritance resolution (IDE -> Project -> Global -> Agent CLI),
* and reactive cache for Settings › Agents › MCP Connections and the Composer MCP picker.
* and reactive cache for Settings › Agents › External MCP Servers and the Composer MCP picker.
*/
import { useEffect } from "react";
import { create } from "zustand";
+3 -3
View File
@@ -7,15 +7,15 @@ export const HOME_KEY = "agent:new";
export const TOOL_WINDOW = "agents";
/** MIME of a dragged agent task (a tree row or the docked conversation bar): the payload is the task id. */
export const TASK_DRAG = "application/x-openidea-agent-task";
/** Settings › Agents › Agent Setup. */
/** Settings › Agents › Coding Agents: the agents this machine runs. */
export const REGISTRY_PAGE = "agents.list";
/** The Settings folder holding the agent pages. */
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › MCP Connections. */
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Command Rules. */
/** Settings › Agents › Command Permissions. */
export const POLICY_PAGE = "agents.policy";
export const sessionKey = (task: string) => `agent:${task}`;
+1 -1
View File
@@ -3,7 +3,7 @@ import type { AgentProvider } from "@/bindings";
import type { tx as Tx } from "@/platform/i18n";
import type { SelectOption } from "@/ui";
/** Picker entry that opens Settings › Agents › Agent Setup. */
/** Picker entry that opens Settings › Tools › Agents instead of choosing an agent. */
export const ADD_AGENT = "__addAgent__";
/**
+16 -26
View File
@@ -1,5 +1,4 @@
import { createContext, useContext, useRef, useState, type ReactElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createContext, useContext, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
/** Set while Find in Conversation is open: folded sections render their content, so it is found. */
export const FoldedContent = createContext(false);
@@ -10,8 +9,8 @@ export const FoldedContent = createContext(false);
*/
export const OpenFolds = createContext<Map<string, boolean> | null>(null);
/** Puts a section's header back at `top` (viewport px) after the reader opened or closed it (`Stream`). */
export const KeepFoldHeader = createContext<((header: HTMLElement, top: number) => void) | null>(null);
/** Scrolls a section the reader just opened into view (`Stream`). */
export const RevealFold = createContext<((el: HTMLElement) => void) | null>(null);
/**
* A collapsed section that renders its content only once opened: most of a long conversation
@@ -36,38 +35,29 @@ export function Fold({
}) {
const always = useContext(FoldedContent);
const remembered = useContext(OpenFolds);
const keepHeader = useContext(KeepFoldHeader);
const reveal = useContext(RevealFold);
const [expanded, setExpanded] = useState(() => !!open || !!defaultOpen || (!!id && !!remembered?.get(id)));
const ref = useRef<HTMLDetailsElement>(null);
const remember = (now: boolean) => {
if (!id || !remembered) return;
if (now) remembered.set(id, true);
else remembered.delete(id);
};
const opened = useRef(false);
// Once its content is laid out, so its height is known.
useLayoutEffect(() => {
if (!expanded || !opened.current) return;
opened.current = false;
if (ref.current) reveal?.(ref.current);
}, [expanded, reveal]);
return (
<details
ref={ref}
className={className}
open={open || ((!!id || defaultOpen) && expanded) || undefined}
// Toggle here rather than natively: the content renders in the same frame, and the header
// is put back where it was before anything paints.
onClick={(e) => {
const details = ref.current;
const header = e.target instanceof Element ? e.target.closest("summary") : null;
if (e.defaultPrevented || !details || !header || header.parentElement !== details) return;
if ((e.target as Element).closest("a, button, input, select, textarea, label") !== null) return;
e.preventDefault();
const top = header.getBoundingClientRect().top;
const now = !details.open;
details.open = now;
remember(now);
flushSync(() => setExpanded(now));
keepHeader?.(header, top);
}}
onToggle={(e) => {
const now = e.currentTarget.open;
opened.current = now;
setExpanded(now);
remember(now);
if (id && remembered) {
if (now) remembered.set(id, true);
else remembered.delete(id);
}
}}
>
{summary}
+43 -111
View File
@@ -49,7 +49,7 @@ import {
type EntryRow,
} from "./conversationRows";
import { FindBar } from "./FindBar";
import { KeepFoldHeader, OpenFolds } from "./Folds";
import { OpenFolds, RevealFold } from "./Folds";
import { Entry } from "./messages";
import { ProcessRun, TurnFold } from "./ProcessRows";
import { type QuestionAnswer } from "./QuestionForm";
@@ -147,7 +147,7 @@ function useOffscreenRows(
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
// Keep independent of `visible`: when a kept-alive tab hides, `data-selection` must stay until
// the selection leaves and WebKit clears off-screen rows' highlights before skipping again.
useSelectionVisibility(ref, enabled, `.${styles.conversationRow}`);
useSelectionVisibility(ref, enabled);
}
interface StreamProps {
@@ -169,31 +169,15 @@ interface StreamProps {
/** Entries rendered at a time when a conversation opens at its end. */
const ENTRY_BATCH = 40;
function scrollsY(el: Element): boolean {
if (el.scrollHeight - el.clientHeight <= 1) return false;
const overflow = getComputedStyle(el).overflowY;
return overflow === "auto" || overflow === "scroll";
}
/** The innermost container under `target` that scrolls vertically: a tool output, a run of calls, or `root`. */
function scrollOwner(target: EventTarget | null, root: HTMLElement): HTMLElement {
function scrollsInside(target: EventTarget | null, root: HTMLElement): boolean {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el instanceof HTMLElement && scrollsY(el)) return el;
}
return root;
}
/** Whether a container inside `root` under `target` can still scroll up. */
function scrollsUpInside(target: EventTarget | null, root: HTMLElement): boolean {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el.scrollTop > 0 && scrollsY(el)) return true;
if (el.scrollTop <= 0) continue;
const overflow = getComputedStyle(el).overflowY;
if (overflow === "auto" || overflow === "scroll") return true;
}
return false;
}
/** A wheel gesture's events arrive closer together than this; a pause starts a new one. */
const WHEEL_GESTURE_MS = 150;
export function Stream({
loadError,
task,
@@ -215,7 +199,7 @@ export function Stream({
const restored = useRef(false);
const previousLength = useRef(entries?.length ?? 0);
/** Scrolled away from the end: offer one click back to the latest message. */
const [away, setAway] = useState(false);
const [away, setAway] = useState(() => positions.get(key)?.stick === false);
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
@@ -239,22 +223,15 @@ export function Stream({
const stopFollowing = useCallback(
(target: EventTarget | null) => {
const el = ref.current;
if (!el || el.scrollHeight <= el.clientHeight || scrollsUpInside(target, el)) return;
if (!el || el.scrollHeight <= el.clientHeight || scrollsInside(target, el)) return;
scrollingUp.current = true;
if (!position.current.stick) return;
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
},
[key, positions],
);
const updateJumpVisibility = useCallback((el: HTMLElement) => {
// An upward gesture releases following before anything moves. Only offer a jump
// when there is actual content below the viewport, excluding the fold spacer.
setAway(
!position.current.stick &&
el.scrollHeight - el.clientHeight - el.scrollTop > (parseFloat(getComputedStyle(el).paddingBottom) || 0) + 1,
);
}, []);
// Earlier entries are prepended above the view: remember where the first painted row is
// so the content stays put and the scrollbar doesn't jump under the pointer.
const anchor = useRef<{ el: Element; top: number } | null>(null);
@@ -308,31 +285,11 @@ export function Stream({
const visible = useEditorShown();
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom);
/**
* Blank space after the conversation that lets a section folded near the end keep its header
* in place. It is only ever what the view shows below the content: scrolling up or new rows
* take it back without moving anything.
*/
const slack = useRef(0);
const setSlack = useCallback((px: number) => {
slack.current = px;
if (px) ref.current?.style.setProperty("--stream-slack", `${px}px`);
else ref.current?.style.removeProperty("--stream-slack");
}, []);
const trimSlack = useCallback(() => {
const el = ref.current;
if (!el || slack.current === 0) return;
const content = el.scrollHeight - slack.current;
const next = Math.max(0, Math.min(slack.current, Math.ceil(el.scrollTop + el.clientHeight - content)));
if (next !== slack.current) setSlack(next);
}, [setSlack]);
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
if (!el) return;
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
}, [updateJumpVisibility]);
if (el && position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
}, []);
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
@@ -357,12 +314,10 @@ export function Stream({
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
trimSlack();
if (position.current.stick) {
if (!dragging.current) el.scrollTop = el.scrollHeight;
} else if (!restored.current) el.scrollTop = position.current.top;
restored.current = true;
updateJumpVisibility(el);
});
useLayoutEffect(() => {
// Prepending earlier entries moved the first painted row down: follow it, so the same
@@ -373,80 +328,52 @@ export function Stream({
anchor.current = null;
if (position.current.stick || !from.el.isConnected) return;
scroller.scrollTop += from.el.getBoundingClientRect().top - from.top;
updateJumpVisibility(scroller);
});
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
});
observer.observe(el);
return () => {
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container
* at its edge doesn't hand the rest to the conversation; a gesture stays with the container
* it started in.
*/
}, [key, positions]);
// How far the end was below the view when a section was toggled, before its content renders.
const gapAtToggle = useRef(Infinity);
useEffect(() => {
const el = ref.current;
if (!el) return;
let gesture: { owner: HTMLElement; at: number } | null = null;
const onWheel = (e: WheelEvent) => {
if (e.defaultPrevented || e.ctrlKey || e.metaKey) return;
if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
const now = performance.now();
const latched = gesture && now - gesture.at < WHEEL_GESTURE_MS && gesture.owner.isConnected;
const owner = latched ? gesture!.owner : scrollOwner(e.target, el);
gesture = { owner, at: now };
if (owner !== el) {
const room = e.deltaY < 0 ? owner.scrollTop : owner.scrollHeight - owner.clientHeight - owner.scrollTop;
if (room <= 1) e.preventDefault();
return;
}
markUserScroll();
if (e.deltaY < 0) stopFollowing(e.target);
else if (e.deltaY > 0) scrollingUp.current = false;
const toggled = () => {
gapAtToggle.current = el.scrollHeight - el.scrollTop - el.clientHeight;
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [markUserScroll, stopFollowing]);
el.addEventListener("toggle", toggled, true);
return () => el.removeEventListener("toggle", toggled, true);
}, []);
/**
* The reader opened or closed a section: put its header back where it was, in the run or
* output that scrolls it and then in the conversation. Following stops when that leaves any
* of the end out of view, so the next chunk doesn't pull the header away.
* An opened section grew the conversation below its header: with the end in view, stay at
* it; otherwise bring what it shows into view. Either way its header stays on screen, and
* following stops when that leaves the end out of view.
*/
const keepFoldHeader = useCallback(
(header: HTMLElement, top: number) => {
const revealFold = useCallback(
(fold: HTMLElement) => {
const el = ref.current;
if (!el?.contains(header)) return;
// Opened, the section fills the room left by an earlier fold first.
trimSlack();
for (let s = header.parentElement; s; s = s.parentElement) {
const moved = header.getBoundingClientRect().top - top;
if (Math.abs(moved) < 1) break;
if (s === el) {
const short = Math.ceil(el.scrollTop + moved + el.clientHeight - el.scrollHeight);
if (short > 0) setSlack(slack.current + short);
el.scrollTop += moved;
break;
}
if (scrollsY(s)) s.scrollTop += moved;
}
if (position.current.stick && el.scrollHeight - el.scrollTop - el.clientHeight >= 1) {
if (!el || dragging.current) return;
const view = el.getBoundingClientRect();
const box = fold.getBoundingClientRect();
const atEnd = position.current.stick || gapAtToggle.current < 40;
gapAtToggle.current = Infinity;
const below = atEnd ? el.scrollHeight - el.scrollTop - el.clientHeight : box.bottom - view.bottom;
if (below > 0) el.scrollTop += Math.max(0, Math.min(below, box.top - view.top));
if (atEnd && el.scrollHeight - el.scrollTop - el.clientHeight >= 40) {
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
}
updateJumpVisibility(el);
},
[key, positions, setSlack, trimSlack, updateJumpVisibility],
[key, positions],
);
/** Back to the end of the stream; following resumes from there. */
const jumpToLatest = useCallback(() => {
@@ -527,7 +454,7 @@ export function Stream({
);
return (
<OpenFolds.Provider value={openFolds}>
<KeepFoldHeader.Provider value={keepFoldHeader}>
<RevealFold.Provider value={revealFold}>
<div className={styles.streamArea}>
{finding && <FindBar streamRef={ref} focus={findFocus} onClose={onCloseFind} />}
<div
@@ -535,6 +462,12 @@ export function Stream({
// The conversation is read and copied like a document; focusable so ⌘F reaches it.
className={clsx(styles.stream, selectableText)}
tabIndex={-1}
onWheel={(e) => {
if (e.defaultPrevented) return;
markUserScroll();
if (e.deltaY < 0 && !e.ctrlKey && !e.metaKey) stopFollowing(e.target);
else if (e.deltaY > 0 && !e.ctrlKey && !e.metaKey) scrollingUp.current = false;
}}
onTouchStart={(e) => {
touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null;
}}
@@ -564,7 +497,6 @@ export function Stream({
}}
onScroll={(e) => {
const el = e.currentTarget;
trimSlack();
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const laidOut =
el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
@@ -581,7 +513,7 @@ export function Stream({
if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight;
position.current = { top: el.scrollTop, stick };
positions.set(key, position.current);
updateJumpVisibility(el);
setAway(!position.current.stick);
// Reached the top of what is painted: fetch the earlier entries, but only
// once the drag has settled.
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
@@ -654,7 +586,7 @@ export function Stream({
</div>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
</div>
</KeepFoldHeader.Provider>
</RevealFold.Provider>
</OpenFolds.Provider>
);
}
+63 -122
View File
@@ -738,31 +738,6 @@ describe("the conversation selection", () => {
});
describe("scrolling", () => {
it("hides Jump to Latest while the end is visible even when following has stopped", async () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
let height = 1000;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.style.paddingBottom = "12px";
el.scrollTop = 599.75;
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -2 });
const jump = () => screen.queryByRole("button", { name: "Jump to Latest" });
expect(jump()).toBeNull();
el.scrollTop = 594;
fireEvent.scroll(el);
expect(jump()).toBeNull();
el.scrollTop = 580;
fireEvent.scroll(el);
expect(jump()).toBeInTheDocument();
// The end moves into view when content shrinks, without a downward gesture.
height = 980;
fireEvent.scroll(el);
expect(jump()).toBeNull();
});
it("returns to the end when the user sends a message while scrolled up", async () => {
const reply = { type: "agent", text: "Initial reply" } as AgentEntry;
useAgents.setState({ entries: new Map([["A", [reply]]]) });
@@ -797,106 +772,74 @@ describe("scrolling", () => {
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
});
/** A stream whose height follows its fold and whose offset is clamped like a browser's. */
const foldingStream = (openHeight: number) => {
it.each([
{
name: "stays at the end below it",
top: 300,
bottom: 360,
scrolled: 60,
away: false,
},
{
name: "keeps its header on screen",
top: 50,
bottom: 900,
scrolled: 50,
away: true,
},
{
name: "back at the end without following",
top: 300,
bottom: 360,
scrolled: 60,
away: false,
released: true,
},
])("scrolls a section opened at the end into view: $name", async ({ top, bottom, scrolled, away, released }) => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
const fold = el.querySelector("details")!;
const slack = () => parseFloat(el.style.getPropertyValue("--stream-slack")) || 0;
const height = () => (fold.children.length > 1 ? 1000 + openHeight : 1000) + slack();
let top = 0;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
Object.defineProperty(el, "scrollTop", {
Object.defineProperty(el, "scrollHeight", {
configurable: true,
get: () => Math.max(0, Math.min(top, height() - 400)),
set: (v: number) => {
top = Math.max(0, Math.min(v, height() - 400));
},
value: 1000,
});
return { el, fold, summary: fold.querySelector("summary")!, slack };
};
it("keeps the header of a section opened at the end in place and stops following", async () => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const { el, summary } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 900 - el.scrollTop }) as DOMRect;
Object.defineProperty(el, "clientHeight", {
configurable: true,
value: 400,
});
el.getBoundingClientRect = () => ({ top: 0, bottom: 400 }) as DOMRect;
el.scrollTop = 600;
fireEvent.scroll(el);
fireEvent.click(summary);
expect(el.scrollTop).toBe(600);
expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
act(() =>
useAgents.setState({
entries: new Map([["A", [...backend.entries.get("A")!, { type: "agent", text: "More" }]]]),
}),
);
expect(el.scrollTop).toBe(600);
});
it("keeps the header of a section closed at the end in place", async () => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const { el, fold, summary, slack } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 1200 - el.scrollTop }) as DOMRect;
fireEvent.click(summary);
expect(fold.open).toBe(true);
el.scrollTop = 1100;
if (released) {
fireEvent.wheel(el, { deltaY: -50 });
el.scrollTop = 550;
fireEvent.scroll(el);
el.scrollTop = 600;
fireEvent.scroll(el);
expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
}
const fold = stream().querySelector("details")!;
fold.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;
// It grows once its content renders.
Object.defineProperty(el, "scrollHeight", {
configurable: true,
get: () => (fold.children.length > 1 ? 1000 + bottom - top : 1000),
});
fireEvent.pointerDown(fold);
fireEvent.pointerUp(fold);
fold.open = true;
act(() => {
fireEvent(fold, new Event("toggle"));
});
expect(el.scrollTop).toBe(600 + scrolled);
fireEvent.scroll(el);
// Closing it would pull the end up to 600: room below keeps the header at 100.
fireEvent.click(summary);
expect(fold.open).toBe(false);
expect(el.scrollTop).toBe(1100);
expect(slack()).toBe(500);
// Scrolling up takes the room back without moving the content.
el.scrollTop = 1000;
fireEvent.scroll(el);
expect(slack()).toBe(400);
expect(el.scrollTop).toBe(1000); // Opened again, the section fills that room first: nothing moves and no blank is left below.
fireEvent.click(summary);
expect(fold.open).toBe(true);
expect(slack()).toBe(0);
expect(el.scrollTop).toBe(1000);
});
it("scrolls the innermost container under the wheel and never hands it to the conversation", () => {
const transcript: AgentEntry[] = [tool("live", { status: "running", output: "Tool output" })];
useAgents.setState({ entries: new Map([["A", transcript]]) });
render(<SessionEditor input={input("A")} />);
const el = stream();
Object.defineProperty(el, "scrollHeight", { configurable: true, value: 1000 });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.scrollTop = 600;
fireEvent.scroll(el);
const output = screen.getByText("Tool output");
output.style.overflowY = "auto";
Object.defineProperty(output, "scrollHeight", { configurable: true, value: 300 });
Object.defineProperty(output, "clientHeight", { configurable: true, value: 100 });
let now = 0;
vi.spyOn(performance, "now").mockImplementation(() => now);
// At its top, scrolling up over it stays with it.
output.scrollTop = 0;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(false);
now = 1000;
output.scrollTop = 100;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true);
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
// A gesture that started in the conversation stays there when the output slides under it.
now = 2000;
expect(fireEvent.wheel(el, { deltaY: -4 })).toBe(true);
now = 2050;
output.scrollTop = 0;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true);
// With the end out of view, the next chunk doesn't pull the reader away from the section.
expect(screen.queryByRole("button", { name: "Jump to Latest" }) !== null).toBe(away);
});
it("keeps following when the view grows taller and the browser pulls the offset back", () => {
@@ -1046,8 +989,6 @@ describe("scrolling", () => {
value: 400,
});
output.style.overflowY = "auto";
Object.defineProperty(output, "scrollHeight", { configurable: true, value: 300 });
Object.defineProperty(output, "clientHeight", { configurable: true, value: 100 });
output.scrollTop = 100;
el.scrollTop = 600;
fireEvent.scroll(el);
@@ -2588,7 +2529,7 @@ describe("import sessions dialog", () => {
backend.external = sessions;
open();
await listed("Login fix");
expect(screen.getByRole("dialog", { name: "Import Sessions" })).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "Import Sessions from Other Apps" })).toBeInTheDocument();
});
it("imports the selected session and opens it", async () => {
+7 -6
View File
@@ -2,23 +2,24 @@ import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Agent Setup",
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "Coding Agents"],
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: MCP_PAGE,
title: "MCP Connections",
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
@@ -31,10 +32,10 @@ export function activateSettingsPages(): () => void {
},
{
id: POLICY_PAGE,
title: "Command Rules",
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "Command Permissions", "exec"],
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
+1 -1
View File
@@ -136,7 +136,7 @@ interface AgentsState {
external: ExternalSession[];
/** Why the external sessions could not be listed. */
externalError: string | null;
/** The Import Sessions dialog is open. */
/** The Import Sessions from Other Apps dialog is open. */
importOpen: boolean;
/** External sessions being imported (`provider:sessionId`), so none is imported twice. */
importing: ReadonlySet<string>;
+6 -13
View File
@@ -1,6 +1,6 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { t, tx } from "@/platform/i18n";
import { tx } from "@/platform/i18n";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
@@ -165,7 +165,7 @@ function arrangeMenu(tasks: AgentTask[], ids: string[]): MenuItem[] {
{
kind: "item",
id: "move-to-group",
label: "Group",
label: "Move to Group",
icon: "folder",
submenu: groupSubmenu(
ids,
@@ -194,7 +194,7 @@ function groupSubmenu(ids: string[], groups: OrganizeGroup[], current: Array<str
{
kind: "item",
id: "group:none",
label: "No Group",
label: "Remove from Group",
run: () => moveTasksToGroup(ids, null),
},
] satisfies MenuItem[])
@@ -213,11 +213,11 @@ export function groupMenu(group: OrganizeGroup): MenuItem[] {
export const taskActions: Action[] = [
{
id: "agents.importSessions",
title: "Import Sessions…",
title: "Import Sessions from Other Apps…",
category: "Agents",
icon: "download",
when: "projectOpen",
keywords: ["import", "other apps", "claude", "codex", "history", "transcript"],
keywords: ["import", "claude", "codex", "history", "transcript"],
run: showImportSessions,
},
{
@@ -398,14 +398,7 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
...(!auxiliaryWindow()
? ([
{
kind: "action",
action: "agents.moveToNewWindow",
label: t("app.window.askNew"),
arg: task.id,
},
] satisfies MenuItem[])
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
: []),
...(hasTaskTerminal(task, projectRoot)
? ([
+13 -44
View File
@@ -31,6 +31,9 @@
.bold {
font-weight: 600;
}
.flex {
flex: 1;
}
.ellipsis {
min-width: 0;
overflow: hidden;
@@ -437,49 +440,29 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
width: 500px;
max-width: calc(100vw - 12px);
height: 200px;
max-height: calc(100vh - 12px);
padding: var(--space-3);
overflow: auto;
width: var(--submit-width);
min-width: 320px;
height: var(--submit-height);
min-height: 160px;
padding: 12px;
overflow: hidden;
resize: both;
}
.submitHeader {
display: flex;
flex: none;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-1);
}
.submitHeading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
align-self: center;
gap: var(--space-0-5) var(--space-2);
min-width: 0;
overflow-wrap: anywhere;
}
.submitCount {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.submitHeaderActions {
display: flex;
flex: none;
align-items: center;
gap: var(--space-1);
gap: 5px;
}
.submitEditor {
flex: 1;
min-height: 40px;
padding: var(--space-1) var(--space-2);
padding: 4px 6px;
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--bg-input);
color: var(--fg);
font: inherit;
line-height: var(--lh-code);
resize: none;
outline: none;
}
@@ -487,26 +470,12 @@
border-color: var(--focus-ring);
}
.submitError {
flex: 0 1 auto;
min-height: 0;
max-height: 35%;
overflow: auto;
overflow-wrap: anywhere;
flex: none;
color: var(--danger);
}
.submitButtons {
display: flex;
flex: none;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
}
.submitButtons > button {
max-width: 100%;
height: auto;
min-height: var(--h-button);
padding-block: var(--space-1);
line-height: 1.2;
white-space: normal;
overflow-wrap: anywhere;
}
@@ -5,11 +5,9 @@
* Request Changes (not for the author) and Comment. Shown above the button that opened
* it, or centred in the window. 500×200, resizable.
*/
import { useEffect, useState } from "react";
import { useEffect, useState, type CSSProperties } from "react";
import { Button, IconButton, Popup, Spinner, T } from "@/ui";
import { resolveMonoFont } from "@/platform/fonts";
import { useTx, tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { ask } from "@/workbench/messages";
import { errorMessage } from "../api/client";
import type { GHPullRequestReviewEvent } from "../api/types";
@@ -27,25 +25,26 @@ export function showSubmitReview(number: number, anchor?: Element | null): Promi
// The details and the pending review are needed for the buttons and the header.
void loadPullRequestData(number, "details").catch(() => undefined);
void loadPullRequestData(number, "pendingReview").catch(() => undefined);
const at = anchor?.isConnected
? anchor
: { x: Math.round(window.innerWidth / 2) - 250, y: Math.round(window.innerHeight / 3) };
return openDialog<true>((done) => (
<SubmitReview
number={number}
draftKey={draftKey}
anchor={anchor?.isConnected ? anchor : "center"}
onClose={() => done(null)}
/>
<SubmitReview number={number} draftKey={draftKey} anchor={at} onClose={() => done(null)} />
));
}
function SubmitReview(props: { number: number; draftKey: string; anchor: Element | "center"; onClose: () => void }) {
const { number, draftKey, anchor, onClose } = props;
function SubmitReview(props: {
number: number;
draftKey: string;
anchor: Element | { x: number; y: number };
onClose: () => void;
}) {
const { number, draftKey, onClose } = props;
const t = useTx();
const details = usePullRequestData(number, "details").value;
const pending = usePullRequestData(number, "pendingReview").value;
const text = useReviewText((s) => s.text[draftKey] ?? "");
const activeDraftKey = useGhRepository((s) => reviewDraftKey(s.connection, number));
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -95,11 +94,12 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element
setBusy(false);
}
};
const anchored = "getBoundingClientRect" in props.anchor;
return (
<Popup
open
anchor={anchor}
placement="top-start"
anchor={props.anchor}
placement={anchored ? "top-start" : "bottom-start"}
onClose={(reason) => {
// A click outside does not drop a review while it is being sent.
if (reason !== "outside" || !busy) onClose();
@@ -107,38 +107,26 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element
role="dialog"
aria-label={t("Submit Review")}
className={styles.submitPopup}
resizable="both"
minWidth={260}
minHeight={160}
style={{ "--submit-width": "500px", "--submit-height": "200px" } as CSSProperties}
>
<div className={styles.submitHeader}>
<div className={styles.submitHeading}>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span className={styles.submitCount}>
{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}
</span>
)}
</div>
<div className={styles.submitHeaderActions}>
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span>{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}</span>
)}
<span className={styles.flex} />
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
<textarea
data-autofocus
className={styles.submitEditor}
placeholder={t("Review comment")}
aria-label={t("Review comment")}
style={{
fontFamily: family,
fontSize: size,
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={text}
onChange={(e) => {
setError(null);
@@ -146,7 +134,7 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element
}}
/>
{error && (
<div className={styles.submitError} role="alert">
<div className={styles.submitError}>
<T>Failed to submit review</T>
<div className={styles.secondary}>{error}</div>
</div>
+10 -19
View File
@@ -270,31 +270,22 @@
min-width: 0;
display: flex;
align-items: center;
gap: var(--space-1-5);
gap: var(--space-2);
}
/* The message identifies a stash: the branch gives way first, the time stays whole. */
.stashRow > .detail {
white-space: nowrap;
}
.stashRow > .stashTime {
flex: none;
}
.stashGroupName,
.stashTime,
.stashBranch,
.stashMessage {
min-width: 0;
flex: 1 1 auto;
min-width: 4em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.stashMessage {
min-width: min(4em, 100%);
}
.stashGroupName {
font-weight: 600;
}
.stashTime {
flex-shrink: 10000;
color: var(--fg-secondary);
}
.stashBranch {
max-width: 30%;
margin-inline-start: auto;
}
@container stash-list (max-width: 320px) {
.stashBranch {
display: none;
-19
View File
@@ -307,25 +307,6 @@
color: var(--fg-strong);
background: var(--bg-hover);
}
.host :global(.cm-diffNumbers) {
position: relative;
text-align: end;
font-variant-numeric: tabular-nums;
}
.host :global(.cm-diffNumbers .cm-gutterElement),
.host :global(.cm-diffWidgetNumber) {
min-inline-size: calc(var(--space-4) + var(--space-2));
padding-inline: var(--space-1) var(--space-2);
}
.host :global(.cm-diffWidgetNumbers) {
position: absolute;
inset: 0;
pointer-events: none;
}
.host :global(.cm-diffWidgetNumber) {
position: absolute;
inset-inline: 0;
}
.noHighlight :global(.cm-changedLine),
.noHighlight :global(.cm-insertedLine),
.noHighlight :global(.cm-changedText),
+1 -3
View File
@@ -121,7 +121,6 @@ import { PaddedPanes, UnalignedPanes, type DiffPanes } from "./diffScroll";
import { groupOf } from "./changes";
import { commitLineTarget, EXCLUDE_COMMIT_LINES, INCLUDE_COMMIT_LINES, inclusionGutter } from "./hunkInclusion";
import { unifiedCommitLines, unifiedCommitSelection } from "./unifiedCommitLines";
import { unifiedLineNumbers } from "./unifiedLineNumbers";
import { hunksOverlapping } from "./hunks";
import { requireDisplayedText, staleDiff, writeIndexChunk } from "./stagingDiffEdits";
import {
@@ -736,7 +735,7 @@ function TwoPaneDiff({
viewerBase({
readOnly: !editable,
findBar: true,
lineNumbers: viewMode === "split" ? (notes === "left" ? "after" : true) : single,
lineNumbers: viewMode === "split" && notes === "left" ? "after" : true,
}),
collapseUnchanged ? collapsedDiffLines() : [],
changedRanges,
@@ -925,7 +924,6 @@ function TwoPaneDiff({
includable ? unifiedCommitSelection : [],
highlightChanges ? diffWords : [],
unifiedOnLeft ? unifiedLeftDiff(highlightChanges) : [],
single ? [] : unifiedLineNumbers(unifiedOnLeft),
unifiedMergeView({
original: unifiedOnLeft ? textB : textA,
highlightChanges,
-17
View File
@@ -1,26 +1,9 @@
.root {
position: relative;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
/* Absolute in both states, so hiding and showing the log doesn't lay it out again. */
.logHost {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
}
.logHidden {
content-visibility: hidden;
z-index: -1;
}
/* WebKit leaves a stale selection highlight on a subtree whose rendering was skipped when the selection cleared. */
.logHidden[data-selection] {
content-visibility: visible;
opacity: 0;
}
.headerTabs {
min-width: 0;
border: 0;
+5 -23
View File
@@ -14,7 +14,6 @@ import {
useFrozenWhileWindowResizes,
} from "@/ui";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { useSelectionVisibility } from "@/ui/useSelectionBoundary";
import { spanStyle } from "@/ui/ansi";
import clsx from "clsx";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
@@ -35,7 +34,6 @@ import { LogScope } from "./LogScope";
import {
closeLogTab,
initLogBranchFilter,
isLogTab,
logState,
refsSignature,
reloadLog,
@@ -87,15 +85,6 @@ export function GitToolWindow() {
// window drag; they follow the window once it stops.
const root = useRef<HTMLDivElement>(null);
useFrozenWhileWindowResizes(root);
// The last log tab shown stays mounted (hidden, keeping its layout) while another tab is shown,
// so switching back to it neither rebuilds its rows, graph and branch tree nor reloads it.
const logTabs = useGitLog((s) => s.logTabs);
const logShown = isLogTab(shown, logTabs);
const [lastLog, setLastLog] = useState<string | null>(null);
if (logShown && lastLog !== shown) setLastLog(shown);
const keptLog = logShown ? shown : lastLog && isLogTab(lastLog, logTabs) ? lastLog : null;
const logHost = useRef<HTMLDivElement>(null);
useSelectionVisibility(logHost, !!keptLog);
if (!available && !external)
return (
<EmptyState title="Version control is not configured">
@@ -118,18 +107,11 @@ export function GitToolWindow() {
<ConsoleView />
) : shown === "worktrees" ? (
<WorktreesPanel className={styles.worktrees} listClassName={styles.worktreeList} />
) : null}
{keptLog && (
<div
ref={logHost}
className={clsx(styles.logHost, !logShown && styles.logHidden)}
aria-hidden={logShown ? undefined : true}
>
{/* Each log tab has its own view (its filters and commits are swapped into the store). */}
<LogScope id={keptLog}>
<LogView key={keptLog} />
</LogScope>
</div>
) : (
// Each log tab has its own view (its filters and commits are swapped into the store).
<LogScope id={shown}>
<LogView key={shown} />
</LogScope>
)}
</div>
);
+112 -127
View File
@@ -100,7 +100,6 @@ function WorktreeForm({
onRepoChange: (repo: string) => void;
}) {
const [projectRoot] = useState(() => useProject.getState().project?.root);
const [hasRepositories] = useState(() => useVcs.getState().roots.length > 1);
const [data, setData] = useState<RepositoryData>();
const [sourceRef, setSourceRef] = useState(initialSource);
const [createBranch, setCreateBranch] = useState<boolean>();
@@ -368,142 +367,128 @@ function WorktreeForm({
]}
>
<div className={styles.form}>
{!initialSource && (
<RepoPicker
repo={repo}
onChange={(next) => {
if (!submitting.current) onRepoChange(next);
}}
/>
)}
{main?.submodule && (
<div className={styles.worktreeTarget}>
{tx("This worktree has its own checkout, separate from the submodule in the parent repository.")}
</div>
)}
<div className={styles.worktreeFields}>
{!initialSource && hasRepositories && (
<>
<label className={styles.worktreeLabel} htmlFor="worktree-repository">
<T>Repository:</T>
</label>
<RepoPicker
id="worktree-repository"
repo={repo}
onChange={(next) => {
if (!submitting.current) onRepoChange(next);
}}
/>
</>
)}
<label className={styles.worktreeLabel} htmlFor="worktree-source">
<T>Check out:</T>
</label>
<Select
id="worktree-source"
aria-label="Check out"
searchable
disabled={formBusy || !data}
value={source?.ref ?? null}
placeholder="Select branch or tag"
options={(data?.sources ?? []).map((ref) => ({
value: ref.ref,
label: ref.name,
icon: ref.kind === "tag" ? "tag" : "branch",
verbatim: true,
}))}
onChange={(ref) => {
setSourceRef(ref);
setCreateBranch(undefined);
setBranch(undefined);
setError(undefined);
}}
/>
<Checkbox
className={styles.worktreeLabel}
label="Create a new branch"
disabled={formBusy}
checked={createLocal}
onChange={setCreateBranch}
/>
{createLocal && (
<Input
ref={branchInput}
aria-label="New branch name"
mono
disabled={formBusy}
value={branch ?? branchName}
onChange={(e) => setBranch(cleanBranch(e))}
/>
)}
<label className={styles.worktreeLabel} htmlFor="worktree-name">
<T>Name:</T>
</label>
<div className={styles.fieldLabel}>
<T>Check out:</T>
</div>
<Select
aria-label="Check out"
searchable
disabled={formBusy || !data}
value={source?.ref ?? null}
placeholder="Select branch or tag"
options={(data?.sources ?? []).map((ref) => ({
value: ref.ref,
label: ref.name,
icon: ref.kind === "tag" ? "tag" : "branch",
verbatim: true,
}))}
onChange={(ref) => {
setSourceRef(ref);
setCreateBranch(undefined);
setBranch(undefined);
setError(undefined);
}}
/>
<Checkbox label="Create a new branch" disabled={formBusy} checked={createLocal} onChange={setCreateBranch} />
{createLocal && (
<Input
id="worktree-name"
ref={branchInput}
aria-label="New branch name"
mono
disabled={formBusy}
value={name ?? folderName}
onChange={(e) => setName(e.target.value)}
value={branch ?? branchName}
onChange={(e) => setBranch(cleanBranch(e))}
/>
<label className={styles.worktreeLabel} htmlFor="worktree-location">
<T>Location:</T>
</label>
<div className={styles.worktreeLocation}>
<Input
id="worktree-location"
disabled={formBusy}
value={location ?? parent}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton icon="folder-open" title="Browse" disabled={formBusy} onClick={() => void browse()} />
</div>
{parent && folderName && <div className={styles.worktreeTarget}>{tx`Worktree location: ${target}`}</div>}
<div className={styles.worktreeOptions}>
<div className={styles.worktreeCopyOptions}>
<Checkbox
label="Copy local files listed in .worktreeinclude"
disabled={formBusy || !include?.exists}
checked={copyLocal}
onChange={setCopyConfig}
/>
{include && (
<Button disabled={formBusy} onClick={() => void editInclude()}>
<T>{include.exists ? "Edit .worktreeinclude…" : "Create .worktreeinclude…"}</T>
</Button>
)}
</div>
{includeError && (
<div className={styles.error} role="alert">
{includeError}
</div>
)}
<Checkbox
label="Run setup script"
disabled={formBusy}
checked={runSetup}
onChange={(enabled) => {
setRunSetup(enabled);
setError(undefined);
}}
/>
</div>
{runSetup && (
<>
<label className={styles.worktreeLabel} htmlFor="worktree-setup-script">
<T>Setup script:</T>
</label>
<div className={styles.worktreeLocation}>
<Input
id="worktree-setup-script"
disabled={formBusy}
value={setupPath}
onChange={(e) => {
setSetupPath(e.target.value);
setError(undefined);
}}
/>
<IconButton
icon="folder-open"
title="Choose Setup Script"
disabled={formBusy}
onClick={() => void browseSetupScript()}
/>
</div>
</>
)}
<label className={styles.fieldLabel} htmlFor="worktree-name">
<T>Name:</T>
</label>
<Input
id="worktree-name"
mono
disabled={formBusy}
value={name ?? folderName}
onChange={(e) => setName(e.target.value)}
/>
<label className={styles.fieldLabel} htmlFor="worktree-location">
<T>Location:</T>
</label>
<div className={styles.worktreeLocation}>
<Input
id="worktree-location"
mono
disabled={formBusy}
value={location ?? parent}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton icon="folder-open" title="Browse" disabled={formBusy} onClick={() => void browse()} />
</div>
{parent && folderName && <div className={styles.worktreeTarget}>{tx`Worktree location: ${target}`}</div>}
<div className={styles.worktreeLocation}>
<Checkbox
label="Copy local files listed in .worktreeinclude"
disabled={formBusy || !include?.exists}
checked={copyLocal}
onChange={setCopyConfig}
/>
{include && (
<Button disabled={formBusy} onClick={() => void editInclude()}>
<T>{include.exists ? "Edit .worktreeinclude…" : "Create .worktreeinclude…"}</T>
</Button>
)}
</div>
{includeError && (
<div className={styles.error} role="alert">
{includeError}
</div>
)}
<Checkbox
label="Run setup script"
disabled={formBusy}
checked={runSetup}
onChange={(enabled) => {
setRunSetup(enabled);
setError(undefined);
}}
/>
{runSetup && (
<>
<label className={styles.fieldLabel} htmlFor="worktree-setup-script">
<T>Setup script:</T>
</label>
<div className={styles.worktreeLocation}>
<Input
id="worktree-setup-script"
mono
disabled={formBusy}
value={setupPath}
onChange={(e) => {
setSetupPath(e.target.value);
setError(undefined);
}}
/>
<IconButton
icon="folder-open"
title="Choose Setup Script"
disabled={formBusy}
onClick={() => void browseSetupScript()}
/>
</div>
</>
)}
{busy && (
<div className={styles.worktreeTarget} role="status">
{setupRequest && !skippingSetup ? tx("Creating worktree and running setup…") : tx("Creating worktree…")}
+23 -81
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from "react";
import clsx from "clsx";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { Icon, IconButton, Select, SplitGroup, SplitHandle, SplitPanel, Tree, showContextMenu } from "@/ui";
import { IconButton, Select, SplitGroup, SplitHandle, SplitPanel, Tree, showContextMenu } from "@/ui";
import { useRowHeight } from "@/ui/density";
import { applyStash, dropStash, stashChanges } from "./changeOps";
import { formatTime, stashLabel } from "./model";
@@ -14,15 +14,6 @@ const stashIdentity = (stash: StashEntry) => JSON.stringify([stash.repo, stash.i
const stashKey = (stash: StashEntry) => `${stash.index}:${stashIdentity(stash)}`;
const EMPTY_STASHES: StashEntry[] = [];
interface StashGroup {
repo: string;
entries: StashEntry[];
}
type StashNode = StashGroup | StashEntry;
const isGroup = (node: StashNode): node is StashGroup => "entries" in node;
const nodeKey = (node: StashNode) => (isGroup(node) ? `repo:${node.repo}` : stashKey(node));
export function StashesPanel({ orientation = "vertical" }: { orientation?: "vertical" | "horizontal" }) {
const rowHeight = useRowHeight(22);
const project = useVcs((s) => s.root);
@@ -30,41 +21,17 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
const repo = useVcs((s) => s.repo);
const version = useVcs((s) => s.version);
const [tick, setTick] = useState(0);
const [selection, setSelection] = useState<StashNode | null>(null);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
const [selectedStash, setSelectedStash] = useState<StashEntry | null>(null);
const request = useMemo(() => ({ project, repos, repo, version, tick }), [project, repos, repo, version, tick]);
const [result, setResult] = useState<{ request: typeof request; stashes: StashEntry[]; error: string | null }>();
const loaded = result?.request === request;
const sameProject =
result?.request.project === project && result?.request.repos === repos && result?.request.repo === repo;
const stashes = sameProject ? result!.stashes : EMPTY_STASHES;
const groups = useMemo(() => {
const byRepo = new Map<string, StashGroup>();
if (repos.length > 1) {
for (const stash of stashes) {
if (!stash.repo) continue;
let group = byRepo.get(stash.repo);
if (!group) byRepo.set(stash.repo, (group = { repo: stash.repo, entries: [] }));
group.entries.push(stash);
}
}
return [...byRepo.values()];
}, [repos.length, stashes]);
const expanded = useMemo(
() => new Set(groups.filter((group) => !collapsed.has(group.repo)).map(nodeKey)),
[groups, collapsed],
);
const selectedGroup = selection && isGroup(selection) ? groups.find((group) => group.repo === selection.repo) : null;
const selectedStash = selection && !isGroup(selection) ? selection : null;
const selectedIdentity = selectedStash && stashIdentity(selectedStash);
const matching = selectedIdentity ? stashes.filter((entry) => stashIdentity(entry) === selectedIdentity) : [];
const current = selectedGroup
? undefined
: (matching.find((entry) => entry.index === selectedStash?.index) ??
matching[0] ??
stashes.find((entry) => !groups.length || !entry.repo || !collapsed.has(entry.repo)));
const selectedNode = selectedGroup ?? current;
const selected = useMemo(() => new Set(selectedNode ? [nodeKey(selectedNode)] : []), [selectedNode]);
const current = matching.find((entry) => entry.index === selectedStash?.index) ?? matching[0] ?? stashes[0];
const selected = useMemo(() => new Set(current ? [stashKey(current)] : []), [current]);
useEffect(() => {
let live = true;
@@ -87,33 +54,22 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
const stashList = (
<div className={styles.treeWrap}>
<Tree<StashNode>
roots={groups.length ? groups : stashes}
getKey={nodeKey}
getLabel={(node) => (isGroup(node) ? repoName(node.repo) : stashLabel(node.message).text)}
getChildren={(node) => (isGroup(node) ? node.entries : undefined)}
isExpandable={isGroup}
expanded={expanded}
onExpandedChange={(_keys, node, open) => {
if (!isGroup(node)) return;
setCollapsed((keys) => {
const next = new Set(keys);
if (open) next.delete(node.repo);
else next.add(node.repo);
return next;
});
if (!open && current?.repo === node.repo) setSelection(node);
}}
<Tree<StashEntry>
roots={stashes}
getKey={stashKey}
getLabel={(s) => stashLabel(s.message).text}
getChildren={() => undefined}
isExpandable={() => false}
selected={selected}
multiSelect={false}
rowHeight={rowHeight}
aria-label="Stashes"
className={styles.stashList}
empty={<span className={styles.empty}>{loaded ? (result.error ?? tx("No stashes")) : tx("Loading…")}</span>}
onSelectionChange={(_keys, lead) => setSelection(lead)}
onSelectionChange={(_keys, lead) => setSelectedStash(lead)}
onContextMenu={(s, _keys, e) => {
if (!s || isGroup(s) || !loaded) return;
setSelection(s);
if (!s || !loaded) return;
setSelectedStash(s);
showContextMenu(e, [
{ label: "Apply Stash", icon: "check", run: () => void applyStash(s, false, s.repo) },
{ label: "Pop Stash", icon: "undo", run: () => void applyStash(s, true, s.repo) },
@@ -123,26 +79,16 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
{ kind: "action", action: "vcs.clearStashes", arg: s.repo },
]);
}}
renderNode={(node) => {
if (isGroup(node)) {
return (
<span className={styles.stashRow} title={node.repo}>
<Icon name="toolwindow-git" size={16} />
<span className={styles.stashGroupName}>{repoName(node.repo)}</span>
<span className={styles.nodeCount}>{node.entries.length}</span>
</span>
);
}
const { branch, text } = stashLabel(node.message);
const time = formatTime(node.timeMs);
renderNode={(s) => {
const { branch, text } = stashLabel(s.message);
return (
<span
className={styles.stashRow}
title={[`stash@{${node.index}}: ${node.message}`, time].filter(Boolean).join("\n")}
>
<span className={styles.stashMessage}>{text}</span>
{time && <span className={styles.stashTime}>{time}</span>}
<span className={styles.stashRow} title={`stash@{${s.index}}: ${s.message}`}>
<span className={styles.stashMessage}>
{repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""}
{text}
</span>
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
</span>
);
}}
@@ -186,7 +132,7 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
onClick={() => current && void dropStash(current, current.repo)}
/>
</div>
{stashes.length > 0 ? (
{current ? (
<SplitGroup
orientation={orientation}
className={styles.split}
@@ -197,11 +143,7 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
</SplitPanel>
<SplitHandle aria-label={tx("Resize stash panes")} />
<SplitPanel id="files" minSize="25%">
{current ? (
<StashChanges key={`${stashIdentity(current)}:${tick}`} stash={current} />
) : (
<span className={styles.empty}>{tx("Select a stash to view its changes.")}</span>
)}
<StashChanges key={`${stashIdentity(current)}:${tick}`} stash={current} />
</SplitPanel>
</SplitGroup>
) : (
@@ -6,7 +6,6 @@ import {
buildBranchRows,
buildBranchTree,
buildMergedBranchTree,
mergedRefTooltip,
filterBranchTree,
isFavoriteBranch,
preferredBranchRow,
@@ -372,22 +371,6 @@ describe("buildMergedBranchTree", () => {
]);
});
it("names each repository of a shared ref in its tooltip", () => {
const tree = buildMergedBranchTree(
[
repo("/b", [b("dev", { upstream: "origin/dev" }), b("origin/dev", { remote: true })], ["v1"]),
repo("/a", [b("dev"), b("origin/dev", { remote: true }), b("solo")], ["v1"]),
],
null,
null,
);
const name = (root: string) => root.slice(1);
expect(mergedRefTooltip(find(tree, "b:dev")!, name)).toBe("a: dev (no tracking branch)\nb: dev → origin/dev");
expect(mergedRefTooltip(find(tree, "b:origin/dev")!, name)).toBe("a\nb");
expect(mergedRefTooltip(find(tree, "t:v1")!, name)).toBe("a\nb");
expect(mergedRefTooltip(find(tree, "b:solo")!, name)).toBeUndefined();
});
it("merges tags by name", () => {
const tree = buildMergedBranchTree([repo("/a", [], ["v1"]), repo("/b", [], ["v1", "v2"])], null, null);
expect(find(tree, "t:v1")?.repos).toEqual(["/a", "/b"]);
@@ -65,17 +65,17 @@ beforeEach(() => {
it("lists stashes from every root and applies the selected row in its own repository", async () => {
render(<StashesPanel />);
expect(await screen.findByText("First")).toBeInTheDocument();
expect(await screen.findByText("Second")).toBeInTheDocument();
expect(await screen.findByText("front · First")).toBeInTheDocument();
expect(await screen.findByText("back · Second")).toBeInTheDocument();
act(() => useVcs.setState({ repo: "/p/back" }));
await screen.findByText("First");
await screen.findByText("front · First");
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
expect(apply).toHaveBeenCalledWith(expect.objectContaining({ index: 0, id: "/p/front-stash" }), false, "/p/front");
});
it("keeps the selected stash when a refresh inserts a new entry above it", async () => {
render(<StashesPanel />);
const original = await screen.findByText("First");
const original = await screen.findByText("front · First");
fireEvent.mouseDown(original, { button: 0 });
list.mockImplementation(async (repo: string) => ({
status: "ok",
@@ -88,15 +88,15 @@ it("keeps the selected stash when a refresh inserts a new entry above it", async
: [],
}));
act(() => useVcs.setState((state) => ({ version: state.version + 1 })));
expect(await screen.findByText("New")).toBeInTheDocument();
expect(screen.getByText("First").closest('[role="treeitem"]')).toHaveAttribute("aria-selected", "true");
expect(await screen.findByText("front · New")).toBeInTheDocument();
expect(screen.getByText("front · First").closest('[role="treeitem"]')).toHaveAttribute("aria-selected", "true");
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
expect(apply).toHaveBeenCalledWith(expect.objectContaining({ index: 1, id: "/p/front-stash" }), false, "/p/front");
});
it("disables stale stash actions while another repository is loading", async () => {
render(<StashesPanel />);
await screen.findByText("First");
await screen.findByText("front · First");
let resolve!: (value: unknown) => void;
list.mockImplementation(
() =>
@@ -105,7 +105,7 @@ it("disables stale stash actions while another repository is loading", async ()
}),
);
act(() => useVcs.setState({ root: "/other", roots: ["/other"], repo: "/other" }));
expect(screen.queryByText("First")).not.toBeInTheDocument();
expect(screen.queryByText("front · First")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
await act(async () => {
resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0, id: "n", base: "b" }] });
@@ -117,7 +117,7 @@ it("disables stale stash actions while another repository is loading", async ()
it("shows the selected stash's files and opens their diff without applying the stash", async () => {
render(<StashesPanel />);
fireEvent.mouseDown(await screen.findByText("Second"), { button: 0 });
fireEvent.mouseDown(await screen.findByText("back · Second"), { button: 0 });
const file = await within(await screen.findByRole("tree", { name: "Changed files" })).findByText("app.ts");
expect(files).toHaveBeenCalledWith("/p/back", "/p/back-stash");
expect(apply).not.toHaveBeenCalled();
@@ -206,7 +206,7 @@ it("ignores stale file results when switching stashes", async () => {
}),
);
render(<StashesPanel />);
fireEvent.mouseDown(await screen.findByText("Second"), { button: 0 });
fireEvent.mouseDown(await screen.findByText("back · Second"), { button: 0 });
expect(await screen.findByText("app.ts")).toBeInTheDocument();
await act(async () => {
resolve({ status: "ok", data: [{ path: "stale.ts", kind: "modified", oldPath: null }] });
-18
View File
@@ -581,24 +581,6 @@ export function buildMergedBranchTree(
return withRepos(buildBranchTree(branches, favorites, [...tagRoots.keys()]));
}
/**
* Tooltip of a merged-tree ref in several repositories: one line per repository, sorted by
* name; a local branch also shows the branch it tracks there.
*/
export function mergedRefTooltip(n: BranchTreeNode, nameOf: (root: string) => string): string | undefined {
if (!n.repos || n.repos.length < 2) return undefined;
const local = n.branch && !n.branch.remote;
return n.repos
.map((root) => {
const name = nameOf(root);
if (!local) return name;
const upstream = n.branchesByRoot?.get(root)?.upstream;
return `${name}: ${n.ref} ${upstream ? `→ ${upstream}` : tx("(no tracking branch)")}`;
})
.sort((a, b) => a.localeCompare(b))
.join("\n");
}
/** Keys of the nodes on the way to branch `name` (to reveal it). */
export function branchFolderKeys(nodes: readonly BranchTreeNode[], name: string): string[] {
const walk = (list: readonly BranchTreeNode[]): string[] | null => {
+14 -19
View File
@@ -316,9 +316,10 @@ class WorkingChunk extends WidgetType {
toDOM(view: EditorView) {
const block = document.createElement("div");
block.className = "cm-unifiedWorkingChunk";
block.dataset.diffFirstLine = String(getOriginalDoc(view.state).lineAt(this.chunk.fromA).number);
const makeRow = () => block.appendChild(document.createElement("div"));
let row = makeRow();
if (!this.text.length) {
block.appendChild(document.createElement("br"));
return block;
}
const tokens: Array<{ from: number; to: number; classes: string }> = [];
const lang = view.state.facet(language);
if (lang && this.text.length <= 3000)
@@ -345,22 +346,16 @@ class WorkingChunk extends WidgetType {
(insideWord ? word.toA : word?.fromA) ?? this.text.length,
);
const text = this.text.slice(at, end);
const classes = [insideToken && token.classes, insideWord && "cm-unifiedWorkingWord"].filter(Boolean).join(" ");
for (const [index, part] of text.split("\n").entries()) {
if (index) {
if (!row.firstChild) row.appendChild(document.createElement("br"));
row = makeRow();
}
if (!part) continue;
if (classes) {
const span = row.appendChild(document.createElement("span"));
span.className = classes;
span.textContent = part;
} else row.append(part);
}
if (insideToken || insideWord) {
const span = document.createElement("span");
span.className = [insideToken && token.classes, insideWord && "cm-unifiedWorkingWord"]
.filter(Boolean)
.join(" ");
span.textContent = text;
block.appendChild(span);
} else block.append(text);
at = end;
}
if (!row.firstChild) row.appendChild(document.createElement("br"));
return block;
}
}
@@ -596,7 +591,7 @@ function viewerEditorLook(): Extension {
];
}
export class LineNumber extends GutterMarker {
class LineNumber extends GutterMarker {
constructor(readonly number: string) {
super();
}
@@ -608,7 +603,7 @@ export class LineNumber extends GutterMarker {
}
}
export function maxLineNumber(lines: number): number {
function maxLineNumber(lines: number): number {
let last = 9;
while (last < lines) last = last * 10 + 9;
return last;
-33
View File
@@ -791,36 +791,6 @@
align-items: center;
gap: var(--space-0-5);
}
.worktreeFields {
display: grid;
grid-template-columns: fit-content(44%) minmax(0, 1fr);
align-items: center;
gap: var(--space-2) var(--space-3);
}
.worktreeFields > :not(.worktreeLabel) {
grid-column: 2;
min-width: 0;
}
.worktreeLabel {
grid-column: 1;
min-width: 0;
font-size: var(--fs-ui);
overflow-wrap: anywhere;
}
.worktreeFields > .worktreeOptions {
display: flex;
flex-direction: column;
grid-column: 1 / -1;
gap: var(--space-2);
border-top: 1px solid var(--border);
padding-top: var(--space-2);
}
.worktreeCopyOptions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
}
.worktreeLocation {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
@@ -831,9 +801,6 @@
color: var(--fg-muted);
overflow-wrap: anywhere;
}
.worktreeFields > .worktreeTarget {
font-size: var(--fs-small);
}
.comparisonDialog > [data-dialog-body] {
display: flex;
flex-direction: column;
+5 -12
View File
@@ -79,19 +79,12 @@ class LineOffsets {
}
/** Line fragments of two texts with their inner word changes, as IDEA's diff viewer computes them. */
export function compareTexts(text1: string, text2: string, options: CompareOptions) {
export function compareTexts(text1: string, text2: string, options: CompareOptions): LineFragment[] {
const { policy } = options;
const raw = compareLineFragments(text1, text2, policy);
const fragments = processBlocks(
options.words ? innerFragments(raw, text1, text2, policy) : raw,
text1,
text2,
policy,
!options.split,
!!options.trimChunks,
);
// Ignored empty lines can still shift the line numbers of matching rows.
return { fragments, lineChanges: options.trimChunks ? raw : fragments };
const fragments = options.words
? compareLinesInner(text1, text2, policy)
: compareLineFragments(text1, text2, policy);
return processBlocks(fragments, text1, text2, policy, !options.split, !!options.trimChunks);
}
/** Changed lines (ComparisonManagerImpl.compareLines). */
+2 -6
View File
@@ -130,11 +130,8 @@ interface DiffInsights {
}
const insights = new WeakMap<readonly Chunk[], DiffInsights>();
const lineChanges = new WeakMap<readonly Chunk[], readonly LineFragment[]>();
const NO_INSIGHTS: DiffInsights = { moves: [], whitespaceOnly: false };
export const getDiffInsights = (chunks: readonly Chunk[]): DiffInsights => insights.get(chunks) ?? NO_INSIGHTS;
export const getDiffLineChanges = (chunks: readonly Chunk[]): readonly LineFragment[] | undefined =>
lineChanges.get(chunks);
/**
* Whether the chunk has IDEA's inner fragments (its words were compared):
@@ -158,7 +155,7 @@ function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
});
return chunks;
};
let compared: ReturnType<typeof compareTexts>;
let compared: LineFragment[];
try {
compared = compareTexts(textA, textB, idea);
} catch (error) {
@@ -168,7 +165,7 @@ function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
const coarse = build.call(Chunk, a, b, { scanLimit: 500 });
return remember(coarse.map((c) => new Chunk([], c.fromA, c.toA, c.fromB, c.toB, c.precise)));
}
const chunks = compared.fragments.map((f) => {
const chunks = compared.map((f) => {
// `to` is one past the last line's end, past the document for its last line.
const toA = f.startLine1 === f.endLine1 ? f.startOffset1 : f.endLine1 === a.lines ? a.length + 1 : f.endOffset1;
const toB = f.startLine2 === f.endLine2 ? f.startOffset2 : f.endLine2 === b.lines ? b.length + 1 : f.endOffset2;
@@ -179,7 +176,6 @@ function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
fragments.set(chunk, f);
return chunk;
});
lineChanges.set(chunks, compared.lineChanges);
return remember(chunks);
}
-2
View File
@@ -14,7 +14,6 @@ import {
buildRepositoryBranchTree,
filterBranchTree,
isFavoriteBranch,
mergedRefTooltip,
type BranchTreeNode,
} from "../branches";
import { branchMenu, inRepo, mergedBranchMenu, showTagContextMenu } from "../branchMenu";
@@ -365,7 +364,6 @@ export function BranchesPanel() {
: undefined;
return branchDetail(n, availableRepositories.length, sync);
}}
getTooltip={(n) => mergedRefTooltip(n, (r) => repoName(branchRoots[r] ?? r))}
selected={selected}
onSelectionChange={(sel) => setSelected(sel)}
onActivate={(n) => {
-162
View File
@@ -1,162 +0,0 @@
import { getChunks, getOriginalDoc } from "@codemirror/merge";
import type { EditorState, Extension, Text } from "@codemirror/state";
import { gutter, ViewPlugin, type EditorView } from "@codemirror/view";
import { LineNumber, maxLineNumber } from "./cm";
import { getDiffLineChanges } from "./diffOptions";
const originalGutter = "cm-diffNumbers-original";
const modifiedGutter = "cm-diffNumbers-modified";
interface WidgetNumbers {
gutter: HTMLElement;
rows: { number: string; top: number }[];
}
function lastStartingBefore<T>(items: readonly T[], at: number, start: (item: T) => number): T | undefined {
let from = 0;
let to = items.length;
while (from < to) {
const mid = (from + to) >>> 1;
if (start(items[mid]!) <= at) from = mid + 1;
else to = mid;
}
return items[from - 1];
}
// Merge chunk endpoints may sit after the last line, including at EOF without a final newline.
function boundaryLine(doc: Text, offset: number) {
if (offset > doc.length) return doc.lines + 1;
const line = doc.lineAt(offset);
return offset === line.from ? line.number : line.number + 1;
}
function matchingLine(state: EditorState, pos: number, number: number): number | null {
const chunks = getChunks(state)?.chunks ?? [];
const changes = getDiffLineChanges(chunks);
if (changes) {
// Fragment ranges are zero-based and half-open.
const change = lastStartingBefore(changes, number - 1, (item) => item.startLine2);
return !change ? number : number <= change.endLine2 ? null : number + change.endLine1 - change.endLine2;
}
const chunk = lastStartingBefore(chunks, pos, (item) => item.fromB);
if (!chunk) return number;
if (pos < chunk.toB) return null;
return number + boundaryLine(getOriginalDoc(state), chunk.toA) - boundaryLine(state.doc, chunk.toB);
}
const sourceChanged = (a: EditorState, b: EditorState) =>
getChunks(a)?.chunks !== getChunks(b)?.chunks || getOriginalDoc(a) !== getOriginalDoc(b);
function numbers(className: string, main: boolean): Extension {
const spacer = (view: EditorView) =>
String(maxLineNumber((main ? view.state.doc : getOriginalDoc(view.state)).lines));
return gutter({
class: `cm-diffNumbers ${className}`,
renderEmptyElements: false,
lineMarker: ({ state }, line) => {
const number = state.doc.lineAt(line.from).number;
const value = main ? number : matchingLine(state, line.from, number);
return value === null ? null : new LineNumber(String(value));
},
lineMarkerChange: (update) => sourceChanged(update.startState, update.state),
initialSpacer: (view) => new LineNumber(spacer(view)),
updateSpacer: (previous, { view }) => {
const value = spacer(view);
return (previous as LineNumber).number === value ? previous : new LineNumber(value);
},
});
}
/** Mirror the rendered widget rows into the sticky gutter, including their wrapped line heights. */
function widgetNumbers(onLeft: boolean): Extension {
return ViewPlugin.define(
(view) => {
const layer = view.dom.ownerDocument.createElement("div");
layer.className = "cm-diffWidgetNumbers";
const selector = `.${onLeft ? modifiedGutter : originalGutter}`;
const measure = {
key: layer,
read(): WidgetNumbers | null {
const gutter = view.dom.querySelector<HTMLElement>(selector);
if (!gutter) return null;
const top = gutter.getBoundingClientRect().top;
const scale = view.scaleY;
const rows: { number: string; top: number }[] = [];
const scroll = view.scrollDOM.getBoundingClientRect();
const fromY = Math.max(0, scroll.top) - view.defaultLineHeight * 2;
const toY =
Math.min(view.dom.ownerDocument.defaultView!.innerHeight, scroll.bottom) + view.defaultLineHeight * 2;
const original = getOriginalDoc(view.state);
const chunks = getChunks(view.state)?.chunks ?? [];
const widgetSelector = onLeft ? ".cm-unifiedWorkingChunk" : ".cm-deletedChunk";
for (const widget of view.contentDOM.querySelectorAll<HTMLElement>(widgetSelector)) {
const block = widget.getBoundingClientRect();
if (block.bottom < fromY || block.top > toY) continue;
const children = widget.children;
const offset = widget.firstElementChild?.classList.contains("cm-chunkButtons") ? 1 : 0;
let first: number;
if (onLeft) {
first = Number(widget.dataset.diffFirstLine);
} else {
const pos = view.posAtDOM(widget);
const chunk = lastStartingBefore(chunks, pos, (item) => item.fromB);
if (!chunk || chunk.fromB !== pos) continue;
first = original.lineAt(chunk.fromA).number;
}
// A single block widget can contain thousands of lines. Measure only the part near the viewport.
let from = offset;
let to = children.length;
while (from < to) {
const mid = (from + to) >>> 1;
if (children[mid]!.getBoundingClientRect().bottom < fromY) from = mid + 1;
else to = mid;
}
for (let i = from; i < children.length; i++) {
const rect = children[i]!.getBoundingClientRect();
if (rect.top > toY) break;
rows.push({ number: String(first + i - offset), top: (rect.top - top) / scale });
}
}
return { gutter, rows };
},
write(result: WidgetNumbers | null) {
if (!result) return;
const owner = layer.ownerDocument;
layer.replaceChildren(
...result.rows.map(({ number, top }) => {
const row = owner.createElement("div");
row.className = "cm-diffWidgetNumber";
row.textContent = number;
row.style.top = `${top}px`;
return row;
}),
);
if (layer.parentElement !== result.gutter) result.gutter.appendChild(layer);
},
};
const schedule = () => view.requestMeasure(measure);
schedule();
return {
schedule,
docViewUpdate: schedule,
update(update) {
if (update.geometryChanged || sourceChanged(update.startState, update.state)) schedule();
},
destroy() {
layer.remove();
},
};
},
{
eventObservers: {
scroll() {
this.schedule();
},
},
},
);
}
export function unifiedLineNumbers(onLeft: boolean): Extension {
return [numbers(originalGutter, onLeft), numbers(modifiedGutter, !onLeft), widgetNumbers(onLeft)];
}
+5 -11
View File
@@ -507,8 +507,7 @@
"Unpin ({count})": "Unpin ({count})",
"New Group": "New Group",
"Rename Group": "Rename Group",
"Group": "Group",
"No Group": "No Group",
"Remove from Group": "Remove from Group",
"Remove “{name}”? Its tasks move back to their status groups.": "Remove “{name}”? Its tasks move back to their status groups.",
"Copy Link Address": "Copy Link Address",
"Pin Agent Tasks": "Pin Agent Tasks",
@@ -541,7 +540,8 @@
"Rename Agent Task Group": "Rename Agent Task Group",
"Remove Agent Task Group": "Remove Agent Task Group",
"Import Sessions…": "Import Sessions…",
"Import Sessions": "Import Sessions",
"Import Sessions from Other Apps…": "Import Sessions from Other Apps…",
"Import Sessions from Other Apps": "Import Sessions from Other Apps",
"No sessions from other apps": "No sessions from other apps",
"Already importing": "Already importing",
"Filter sessions": "Filter sessions",
@@ -1875,9 +1875,6 @@
"An update for this agent is already running.": "An update for this agent is already running.",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "This is not a global npm install OpenIDEA can update. Use its original installer.",
"Coding Agents": "Coding Agents",
"Agent Setup": "Agent Setup",
"Command Rules": "Command Rules",
"Install, update, or remove agents from the ACP Registry.": "Install, update, or remove agents from the ACP Registry.",
"Install coding agents and configure how they launch, chat and connect to the IDE.": "Install coding agents and configure how they launch, chat and connect to the IDE.",
"Fork Agent Task": "Fork Agent Task",
"Couldn't fork the task": "Couldn't fork the task",
@@ -1943,7 +1940,6 @@
"Copy Server Name": "Copy Server Name",
"Delete Server": "Delete Server",
"External MCP Servers": "External MCP Servers",
"MCP Connections": "MCP Connections",
"Import MCP servers from .mcp.json and .vscode/mcp.json": "Import MCP servers from .mcp.json and .vscode/mcp.json",
"An open standard that lets AI use external tools and services. MCP servers provide tools for file operations, databases, APIs, and more.": "An open standard that lets AI use external tools and services. MCP servers provide tools for file operations, databases, APIs, and more.",
"Learn more about MCP servers": "Learn more about MCP servers",
@@ -1968,8 +1964,8 @@
"sse (Server-Sent Events)": "sse (Server-Sent Events)",
"One KEY=VALUE entry per line.": "One KEY=VALUE entry per line.",
"One Header=Value entry per line.": "One Header=Value entry per line.",
"MCP Connections…": "MCP Connections…",
"Configure the MCP servers that agents can use.": "Configure the MCP servers that agents can use.",
"External MCP Servers…": "External MCP Servers…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
"No matching remote branches": "No matching remote branches",
"Remote branches": "Remote branches",
"Fetch tags": "Fetch tags",
@@ -2652,7 +2648,6 @@
"Show Files in Separate Diff Tabs": "Show Files in Separate Diff Tabs",
"Show All Files in One Diff View": "Show All Files in One Diff View",
"No changes": "No changes",
"Select a stash to view its changes.": "Select a stash to view its changes.",
"Scopes actions": "Scopes actions",
"Scopes": "Scopes",
"No scopes. Click + to add one.": "No scopes. Click + to add one.",
@@ -3466,7 +3461,6 @@
"Rename branch {name} ({root})": "Rename branch {name} ({root})",
"rename it back to {name}": "rename it back to {name}",
"Unset upstream of {to} ({root})": "Unset upstream of {to} ({root})",
"(no tracking branch)": "(no tracking branch)",
"Group by Repository": "Group by Repository",
"Diagnose with Agent": "Diagnose with Agent",
"Adds a failed test's name, source location, expected and actual values and output to the agent message typed last, to review and send.": "Adds a failed test's name, source location, expected and actual values and output to the agent message typed last, to review and send.",
+1 -1
View File
@@ -4844,7 +4844,7 @@
"More Agents…": "Más agentes…",
"More agents…": "Más agentes…",
"Opens Settings › Build, Execution, Deployment › Maven": "Abre Configuración › Compilación, ejecución, despliegue › Maven",
"Install, update, or remove agents from the ACP Registry.": "Instala, actualiza o elimina agentes del Registro ACP.",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "Abre Configuración › Herramientas › Agentes: instala, actualiza o elimina agentes del Registro ACP.",
"Search agents": "Buscar agentes",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "Los agentes en el Registro ACP son software de terceros. Se ejecutan en esta computadora con sus permisos y pueden leer y modificar sus archivos. Instale únicamente agentes en los que confíe.",
"Cannot load the ACP Registry: {error}": "No se puede cargar el Registro ACP: {error}",
+1 -1
View File
@@ -4699,7 +4699,7 @@
"More Agents…": "Plus d'agents…",
"More agents…": "Plus d'agents…",
"Opens Settings › Build, Execution, Deployment › Maven": "Ouvre Paramètres › Build, exécution, déploiement › Maven",
"Install, update, or remove agents from the ACP Registry.": "Installez, mettez à jour ou supprimez des agents du registre ACP.",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "Ouvre Paramètres › Outils › Agents : installe, met à jour ou supprime des agents du registre ACP.",
"Search agents": "Rechercher des agents",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "Les agents du registre ACP sont des logiciels tiers. Ils s'exécutent sur cet ordinateur avec vos autorisations et peuvent lire et modifier vos fichiers. N'installez que des agents de confiance.",
"Cannot load the ACP Registry: {error}": "Impossible de charger le registre ACP : {error}",
+1 -1
View File
@@ -4916,7 +4916,7 @@
"More Agents…": "더 많은 에이전트…",
"More agents…": "더 많은 에이전트…",
"Opens Settings › Build, Execution, Deployment › Maven": "설정 › 빌드, 실행, 배포 › Maven을 엽니다",
"Install, update, or remove agents from the ACP Registry.": "ACP Registry에서 에이전트를 설치, 업데이트 또는 제거합니다.",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "설정 › 도구 › 에이전트를 엽니다: ACP Registry에서 에이전트를 설치, 업데이트 또는 제거합니다.",
"Search agents": "에이전트 검색",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "ACP Registry의 에이전트는 서드파티 소프트웨어입니다. 이 컴퓨터에서 사용자 권한으로 실행되며 파일을 읽고 변경할 수 있습니다. 신뢰할 수 있는 에이전트만 설치하세요.",
"Cannot load the ACP Registry: {error}": "ACP Registry를 로드할 수 없습니다: {error}",
+1 -1
View File
@@ -4795,7 +4795,7 @@
"More Agents…": "Więcej agentów…",
"More agents…": "Więcej agentów…",
"Opens Settings › Build, Execution, Deployment › Maven": "Otwiera Ustawienia › Budowanie, wykonanie, wdrożenie › Maven",
"Install, update, or remove agents from the ACP Registry.": "Instaluj, aktualizuj lub usuwaj agentów z rejestru ACP.",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "Otwiera Ustawienia › Narzędzia › Agenci: instaluje, aktualizuje lub usuwa agentów z rejestru ACP Registry.",
"Search agents": "Szukaj agentów",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "Agenci w rejestrze ACP Registry są oprogramowaniem firm trzecich. Działają na tym komputerze z Twoimi uprawnieniami i mogą odczytywać oraz modyfikować Twoje pliki. Instaluj wyłącznie zaufanych agentów.",
"Cannot load the ACP Registry: {error}": "Nie można wczytać rejestru ACP Registry: {error}",
+1 -1
View File
@@ -4810,7 +4810,7 @@
"More Agents…": "Mais agentes…",
"More agents…": "Mais agentes…",
"Opens Settings › Build, Execution, Deployment › Maven": "Abre Configurações › Build, Execução, Implantação › Maven",
"Install, update, or remove agents from the ACP Registry.": "Instale, atualize ou remova agentes do Registro ACP.",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "Abre Configurações › Ferramentas › Agentes: instala, atualiza ou remove agentes do Registro ACP.",
"Search agents": "Pesquisar agentes",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "Os agentes no Registro ACP são softwares de terceiros. Eles são executados neste computador com suas permissões e podem ler e alterar seus arquivos. Instale apenas agentes em que você confia.",
"Cannot load the ACP Registry: {error}": "Não é possível carregar o Registro ACP: {error}",
+6 -7
View File
@@ -161,7 +161,7 @@
"Unpin ({count})": "Sabitlemeyi Kaldır ({count})",
"New Group": "Yeni Grup",
"Rename Group": "Grubu Yeniden Adlandır",
"No Group": "Grup Yok",
"Remove from Group": "Gruptan Kaldır",
"Remove “{name}”? Its tasks move back to their status groups.": "“{name}” kaldırılsın mı? Görevleri durum gruplarına geri taşınacaktır.",
"Copy Link Address": "Bağlantı Adresini Kopyala",
"Pin Agent Tasks": "Ajan Görevlerini Sabitle",
@@ -194,7 +194,8 @@
"Rename Agent Task Group": "Ajan Görev Grubunu Yeniden Adlandır",
"Remove Agent Task Group": "Ajan Görev Grubunu Kaldır",
"Import Sessions…": "Oturumları İçe Aktar…",
"Import Sessions": "Oturumları İçe Aktar",
"Import Sessions from Other Apps…": "Diğer Uygulamalardan Oturumları İçe Aktar…",
"Import Sessions from Other Apps": "Diğer Uygulamalardan Oturumları İçe Aktar",
"No sessions from other apps": "Diğer uygulamalarda oturum bulunamadı",
"Already importing": "İçe aktarma zaten sürüyor",
"Filter sessions": "Oturumları filtrele",
@@ -1387,7 +1388,6 @@
"An update for this agent is already running.": "Bu ajan için bir güncelleme zaten sürüyor.",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "Bu, OpenIDEA'nın güncelleyebileceği genel bir npm kurulumu değil. Özgün yükleyicisini kullanın.",
"Coding Agents": "Kodlama Ajanları",
"Agent Setup": "Ajan Ayarları",
"Install coding agents and configure how they launch, chat and connect to the IDE.": "Kodlama ajanlarını yükleyin ve başlatılma, sohbet etme ve IDE'ye bağlanma yöntemlerini yapılandırın.",
"Fork Agent Task": "Ajan Görevinden Yeni Dal Oluştur",
"Couldn't fork the task": "Görevden yeni dal oluşturulamadı",
@@ -1447,7 +1447,6 @@
"Copy Server Name": "Sunucu Adını Kopyala",
"Delete Server": "Sunucuyu Sil",
"External MCP Servers": "Harici MCP Sunucuları",
"MCP Connections": "MCP Bağlantıları",
"Import MCP servers from .mcp.json and .vscode/mcp.json": "MCP sunucularını .mcp.json ve .vscode/mcp.json dosyalarından içe aktar",
"An open standard that lets AI use external tools and services. MCP servers provide tools for file operations, databases, APIs, and more.": "Yapay zekânın harici araç ve hizmetleri kullanmasını sağlayan açık bir standarttır. MCP sunucuları dosya işlemleri, veritabanları, API'ler ve daha fazlası için araçlar sunar.",
"Learn more about MCP servers": "MCP sunucuları hakkında daha fazla bilgi",
@@ -1467,8 +1466,8 @@
"sse (Server-Sent Events)": "sse (Sunucu tarafından gönderilen olaylar)",
"One KEY=VALUE entry per line.": "Her satıra bir KEY=VALUE girdisi yazın.",
"One Header=Value entry per line.": "Her satıra bir Header=Value girdisi yazın.",
"MCP Connections…": "MCP Bağlantıları…",
"Configure the MCP servers that agents can use.": "Ajanların kullanabileceği MCP sunucularını yapılandırın.",
"External MCP Servers…": "Harici MCP Sunucuları…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "Ayarlar › Ajanlar › Harici MCP Sunucuları sayfasını açar; kodlama ajanlarının kullandığı Kullanıcı ve Çalışma Alanı MCP sunucularını yapılandırır.",
"No matching remote branches": "Eşleşen uzak dal bulunamadı",
"Remote branches": "Uzak dallar",
"Branch name prefixes": "Dal adı önekleri",
@@ -7520,7 +7519,7 @@
"More Agents…": "Diğer Ajanlar…",
"More agents…": "Diğer ajanlar…",
"Opens Settings › Build, Execution, Deployment › Maven": "Ayarlar › Derleme, Yürütme, Dağıtım › Maven bölümünü açar",
"Install, update, or remove agents from the ACP Registry.": "ACP Kayıt Deposu'ndan ajanları yükleyin, güncelleyin veya kaldırın.",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "Ayarlar › Araçlar › Ajanlar bölümünü açar: ACP Kayıt Deposu'ndan ajanları yükler, günceller veya kaldırır.",
"Search agents": "Ajanları ara",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "ACP Kayıt Deposu'ndaki ajanlar üçüncü taraf yazılımlardır. Bilgisayarınızda izinlerinizle çalışır, dosyalarınızı okuyup değiştirebilirler. Yalnızca güvendiğiniz ajanları yükleyin.",
"Cannot load the ACP Registry: {error}": "ACP Kayıt Deposu yüklenemiyor: {error}",
+6 -8
View File
@@ -143,7 +143,7 @@
"Unpin ({count})": "取消固定({count})",
"New Group": "新增群組",
"Rename Group": "重新命名群組",
"No Group": "不分組",
"Remove from Group": "從群組中移除",
"Remove “{name}”? Its tasks move back to their status groups.": "移除「{name}」?其中的任務將回到各自的狀態分組。",
"Copy Link Address": "複製連結地址",
"Pin Agent Tasks": "固定 Agent 任務",
@@ -599,7 +599,6 @@
"Found on PATH": "已在 PATH 中找到",
"Leave empty to find the executable on PATH. Changes apply to new sessions.": "留空以從 PATH 查詢可執行檔案。更改對新工作階段生效。",
"Command Permissions": "命令權限",
"Command Rules": "命令規則",
"Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected, even if allowed, and support * and ? wildcards. Commands with substitutions, redirections or variable assignments always ask.": "允許的命令直接執行,無需確認,可帶額外引數。阻止的命令總會被拒絕,優先於允許清單,支援 * 和 ? 萬用字元。含命令取代、重定向或變數賦值的命令總會詢問。",
"Allowed Commands": "允許的命令",
"Blocked Commands": "阻止的命令",
@@ -2789,7 +2788,8 @@
"Session finished": "工作階段已結束",
"Sessions from other apps": "來自其他應用的代理工作階段",
"Import Sessions…": "匯入工作階段…",
"Import Sessions": "匯入工作階段",
"Import Sessions from Other Apps…": "從其他應用匯入代理工作階段…",
"Import Sessions from Other Apps": "從其他應用匯入代理工作階段",
"No sessions from other apps": "沒有來自其他應用的代理工作階段",
"Already importing": "正在匯入",
"Filter sessions": "篩選工作階段",
@@ -5830,7 +5830,7 @@
"More Agents…": "更多 Agent…",
"More agents…": "更多 Agent…",
"Opens Settings › Build, Execution, Deployment › Maven": "開啟 設定 › 建置、執行、部署 › Maven。",
"Install, update, or remove agents from the ACP Registry.": "從 ACP Registry 安裝、更新或移除代理。",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "開啟 設定 › 工具 › Agents:從 ACP Registry 安裝、更新或移除 Agent。",
"Search agents": "搜尋 Agent",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "ACP Registry 中的 Agent 是第三方軟體。它們以你的權限在本機執行,可以讀取和修改你的檔案。請只安裝你信任的 Agent。",
"Cannot load the ACP Registry: {error}": "無法載入 ACP Registry:{error}",
@@ -7788,7 +7788,6 @@
"An update for this agent is already running.": "此代理已有更新正在進行。",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "這不是 OpenIDEA 能更新的 npm 全域安裝。請使用原安裝工具更新。",
"Coding Agents": "程式設計代理",
"Agent Setup": "代理設定",
"Install coding agents and configure how they launch, chat and connect to the IDE.": "安裝程式設計 Agent,並設定其啟動方式、聊天行為以及與 IDE 的連線。",
"Fork Agent Task": "Fork Agent 任務",
"Couldn't fork the task": "無法 Fork 任務",
@@ -7864,7 +7863,6 @@
"Copy Server Name": "複製伺服器名稱",
"Delete Server": "刪除伺服器",
"External MCP Servers": "外部 MCP 伺服器",
"MCP Connections": "MCP 連線",
"Import MCP servers from .mcp.json and .vscode/mcp.json": "從 .mcp.json 和 .vscode/mcp.json 匯入 MCP 伺服器",
"An open standard that lets AI use external tools and services. MCP servers provide tools for file operations, databases, APIs, and more.": "一項允許 AI 使用外部工具和服務的開放標準。MCP 伺服器提供用於檔案操作、資料庫、API 等的工具。",
"Learn more about MCP servers": "瞭解有關 MCP 伺服器的更多資訊",
@@ -7885,8 +7883,8 @@
"One KEY=VALUE entry per line.": "每行一個 KEY=VALUE 條目。",
"One Header=Value entry per line.": "每行一個 Header=Value 條目。",
"Maven project could not be configured": "無法設定 Maven 專案",
"MCP Connections…": "MCP 連線…",
"Configure the MCP servers that agents can use.": "設定代理可以使用的 MCP 伺服器。",
"External MCP Servers…": "外部 MCP 伺服器…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "開啟「設定 › 代理 › 外部 MCP 伺服器」:設定程式設計代理使用的使用者級和工作區級 MCP 伺服器。",
"Type:": "型別:",
"Command:": "命令:",
"Arguments:": "引數:",
+8 -12
View File
@@ -420,7 +420,7 @@
"Unpin ({count})": "取消固定({count})",
"New Group": "新建组",
"Rename Group": "重命名组",
"No Group": "不分组",
"Remove from Group": "从组中移除",
"Remove “{name}”? Its tasks move back to their status groups.": "移除“{name}”?其中的任务将回到各自的状态分组。",
"Copy Link Address": "复制链接地址",
"Pin Agent Tasks": "固定 Agent 任务",
@@ -817,7 +817,7 @@
"Group actions": "分组操作",
"New Project Group": "新建项目组",
"Group name:": "组名称:",
"New Group…": "新建分组…",
"New Group…": "新建组…",
"Remove from '{current}'": "从“{current}”移除",
"Move to Group": "移动到组",
"Rename Group…": "重命名组…",
@@ -889,7 +889,6 @@
"Found on PATH": "已在 PATH 中找到",
"Leave empty to find the executable on PATH. Changes apply to new sessions.": "留空以从 PATH 查找可执行文件。更改对新会话生效。",
"Command Permissions": "命令权限",
"Command Rules": "命令规则",
"Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected, even if allowed, and support * and ? wildcards. Commands with substitutions, redirections or variable assignments always ask.": "允许的命令直接运行,无需确认,可带额外参数。阻止的命令总会被拒绝,优先于允许列表,支持 * 和 ? 通配符。含命令替换、重定向或变量赋值的命令总会询问。",
"Allowed Commands": "允许的命令",
"Blocked Commands": "阻止的命令",
@@ -1990,7 +1989,7 @@
"Green": "绿色",
"Grey": "灰色",
"Greyscale": "灰度",
"Group": "分组",
"Group": "组",
"Group by Severity": "按严重性分组",
"Groups": "组",
"Gutter Icons": "装订区域图标",
@@ -2360,7 +2359,6 @@
"No breakpoints. Click a line number to add one.": "没有断点。点击行号即可添加。",
"No build output": "没有构建输出",
"No changes": "没有更改",
"Select a stash to view its changes.": "请选择一条储藏以查看其中的更改。",
"No changes selected for commit": "未选择要提交的更改",
"No changes to create a patch from": "没有可用于创建补丁的更改",
"No changes to roll back": "没有要回滚的更改",
@@ -3201,7 +3199,8 @@
"Session finished": "会话已结束",
"Sessions from other apps": "来自其他应用的智能体会话",
"Import Sessions…": "导入会话…",
"Import Sessions": "导入会话",
"Import Sessions from Other Apps…": "从其他应用导入智能体会话…",
"Import Sessions from Other Apps": "从其他应用导入智能体会话",
"No sessions from other apps": "没有来自其他应用的智能体会话",
"Already importing": "正在导入",
"Filter sessions": "过滤会话",
@@ -6215,7 +6214,6 @@
"Show Branches": "显示分支",
"Update Selected": "更新所选",
"Navigate Log to Selected Branch": "在日志中导航到所选分支",
"(no tracking branch)": "(无跟踪分支)",
"Group by Repository": "按仓库分组",
"Branch or tag": "分支或标签",
"Filter branches and tags": "过滤分支和标签",
@@ -6326,7 +6324,7 @@
"More Agents…": "更多 Agent…",
"More agents…": "更多 Agent…",
"Opens Settings › Build, Execution, Deployment › Maven": "打开 设置 › 构建、执行、部署 › Maven。",
"Install, update, or remove agents from the ACP Registry.": "从 ACP Registry 安装、更新或移除智能体。",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "打开 设置 › 工具 › Agents:从 ACP Registry 安装、更新或移除 Agent。",
"Search agents": "搜索 Agent",
"Agents in the ACP Registry are third-party software. They run on this computer with your permissions and can read and change your files. Install only agents you trust.": "ACP Registry 中的 Agent 是第三方软件。它们以你的权限在本机运行,可以读取和修改你的文件。请只安装你信任的 Agent。",
"Cannot load the ACP Registry: {error}": "无法加载 ACP Registry:{error}",
@@ -8310,7 +8308,6 @@
"An update for this agent is already running.": "此智能体已有更新正在进行。",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "这不是 OpenIDEA 能更新的 npm 全局安装。请使用原安装工具更新。",
"Coding Agents": "编程智能体",
"Agent Setup": "智能体配置",
"Install coding agents and configure how they launch, chat and connect to the IDE.": "安装编程 Agent,并配置其启动方式、聊天行为以及与 IDE 的连接。",
"Fork Agent Task": "Fork Agent 任务",
"Couldn't fork the task": "无法 Fork 任务",
@@ -8386,7 +8383,6 @@
"Copy Server Name": "复制服务器名称",
"Delete Server": "删除服务器",
"External MCP Servers": "外部 MCP 服务器",
"MCP Connections": "MCP 连接",
"Import MCP servers from .mcp.json and .vscode/mcp.json": "从 .mcp.json 和 .vscode/mcp.json 导入 MCP 服务器",
"An open standard that lets AI use external tools and services. MCP servers provide tools for file operations, databases, APIs, and more.": "一项允许 AI 使用外部工具和服务的开放标准。MCP 服务器提供用于文件操作、数据库、API 等的工具。",
"Learn more about MCP servers": "了解有关 MCP 服务器的更多信息",
@@ -8407,8 +8403,8 @@
"One KEY=VALUE entry per line.": "每行一个 KEY=VALUE 条目。",
"One Header=Value entry per line.": "每行一个 Header=Value 条目。",
"Maven project could not be configured": "无法配置 Maven 项目",
"MCP Connections…": "MCP 连接…",
"Configure the MCP servers that agents can use.": "配置智能体可以使用的 MCP 服务器。",
"External MCP Servers…": "外部 MCP 服务器…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "打开“设置 › 智能体 › 外部 MCP 服务器”:配置编程智能体使用的用户级和工作区级 MCP 服务器。",
"Type:": "类型:",
"Command:": "命令:",
"Arguments:": "参数:",
+2 -22
View File
@@ -146,14 +146,12 @@ it("ends Select All in the pane's last selectable text, not on its edge before t
expect(window.getSelection()!.toString()).not.toContain("Reply to the agent");
});
function TrackedVisibilityPane({ rows = false }: { rows?: boolean }) {
function TrackedVisibilityPane() {
const ref = useRef<HTMLDivElement>(null);
useSelectionVisibility(ref, true, rows ? "p" : undefined);
useSelectionVisibility(ref);
return (
<div ref={ref} data-testid="tracked">
<p>Tracked line</p>
<p>Second line</p>
<p>Third line</p>
</div>
);
}
@@ -196,21 +194,3 @@ it("keeps data-selection for one rendered frame after the selection leaves", ()
window.cancelAnimationFrame = prevCancel;
}
});
it("keeps only the selected conversation rows visible and releases rows the selection leaves", async () => {
const view = render(<TrackedVisibilityPane rows />);
const tracked = view.getByTestId("tracked");
const [first, second, third] = [...tracked.children];
const select = (start: Element, end: Element) => {
window.getSelection()!.setBaseAndExtent(start.firstChild!, 0, end.firstChild!, 1);
document.dispatchEvent(new Event("selectionchange"));
};
const marked = () => [...tracked.querySelectorAll("[data-selection]")];
select(first!, second!);
expect(marked()).toEqual([first, second]);
select(third!, third!);
expect(marked()).toEqual([first, second, third]);
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
expect(marked()).toEqual([third]);
expect(tracked).not.toHaveAttribute("data-selection");
});
+11 -28
View File
@@ -111,49 +111,32 @@ function textEdge(root: HTMLElement, side: "start" | "end"): { node: Node; offse
}
/**
* Marks the pane or its intersecting rows with `data-selection` while the document's selection intersects it, and keeps the
* Marks `ref` with `data-selection` while the document's selection intersects it, and keeps the
* mark until the frame after the selection leaves. WebKit never clears the selection highlight of
* a subtree that skips rendering (`content-visibility: auto` or `hidden`); pairing `[data-selection]`
* with `content-visibility: visible` lets WebKit apply the deselection before skipping again.
*/
export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabled = true, rowSelector?: string): void {
export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabled = true): void {
useEffect(() => {
const el = ref.current;
if (!el || !enabled) return;
const doc = el.ownerDocument;
const win = doc.defaultView ?? window;
let frame = 0;
const marked = new Set<Element>();
const selectionRange = () => {
const selected = () => {
const sel = doc.getSelection();
return sel && !sel.isCollapsed && sel.rangeCount ? sel.getRangeAt(0) : null;
return !!sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el);
};
const update = () => {
win.cancelAnimationFrame(frame);
const range = selectionRange();
if (range?.intersectsNode(el)) {
// Keep unrelated history at its remembered size while selecting visible text.
let targets: Iterable<Element> = [el];
if (rowSelector) {
const node = range.commonAncestorContainer;
const row = (node instanceof Element ? node : node.parentElement)?.closest(rowSelector);
targets = row?.parentElement === el ? [row] : el.querySelectorAll(`:scope > ${rowSelector}`);
}
for (const target of targets) {
if (!range.intersectsNode(target) || marked.has(target)) continue;
marked.add(target);
target.setAttribute("data-selection", "");
}
if (selected()) {
el.setAttribute("data-selection", "");
return;
}
if (![...marked].some((target) => !range?.intersectsNode(target))) return;
if (!el.hasAttribute("data-selection")) return;
frame = win.requestAnimationFrame(() => {
frame = win.requestAnimationFrame(() => {
const current = selectionRange();
for (const target of marked) {
if (current?.intersectsNode(target)) continue;
target.removeAttribute("data-selection");
marked.delete(target);
}
if (!selected()) el.removeAttribute("data-selection");
});
});
};
@@ -162,9 +145,9 @@ export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabl
return () => {
win.cancelAnimationFrame(frame);
doc.removeEventListener("selectionchange", update);
for (const target of marked) target.removeAttribute("data-selection");
el.removeAttribute("data-selection");
};
}, [ref, enabled, rowSelector]);
}, [ref, enabled]);
}
/**