Compare commits

...
Author SHA1 Message Date
l0ng-ai 2532723e32 fix(agents): keep unrelated chat rows stable during text selection 2026-11-23 18:24:44 +08:00
l0ng-ai 22af0931dd fix(vcs): name each repository of a shared branch in the Branches pane tooltip (#5413)
In the Git Log Branches pane with several repositories, a branch every
repository has is listed once with no repository name. Hovering it now
lists each repository with the branch it tracks there.
2026-11-23 17:21:59 +08:00
l0ng-ai 4af81625b1 fix(agents): scroll the container under the pointer and keep fold headers in place (#5411)
The wheel now scrolls only the innermost scrollable container under the
pointer: a run of tool calls from its headers, a tool output from its text,
the conversation elsewhere. A nested container at its edge no longer hands
the rest of the gesture to the conversation, and a gesture stays with the
container it started in.

Opening or closing a section keeps its header where it was. Closing one near
the end leaves temporary room below the conversation that scrolling up or new
content takes back.
2026-11-23 17:16:29 +08:00
l0ng-ai f3d18c0eb8 fix(agents): clarify settings names and align the import dialog (#5403)
* fix(agents): align and shorten the Import Sessions dialog

* fix(agents): clarify settings page names
2026-11-23 16:35:39 +08:00
l0ng-ai e662c915a2 fix(agents): show the changes scope as compact tool window tabs (#5393)
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:45:07 +08:00
l0ng-ai f57a17ec14 fix(vcs): group stashes by repository (#5380) 2026-11-23 15:45:02 +08:00
l0ng-ai 0b8d9135aa fix(github): keep the review composer readable (#5375) 2026-11-23 15:44:50 +08:00
l0ng-ai 290ef6956e fix(diff): align original and modified line numbers (#5370)
Unified Diff shows original line numbers in the first column and modified line numbers in the second. Matching rows show both. Removed and inserted rows show the number for their own revision.

Line numbers stay beside the start of their rows when code wraps, and follow scrolling inside a large removed block. Matching rows keep their original numbers when empty lines are ignored. The column order also applies when the editable side is the Git index.
2026-11-23 15:44:15 +08:00
l0ng-ai 8a4b8f45b4 fix(agents): shorten task context menu labels (#5394) 2026-11-23 15:35:46 +08:00
l0ng-ai 31b265cb41 fix(vcs): align the New Worktree dialog (#5367)
- Align the repository, checkout, branch, name, location and setup fields in one label-and-control grid. Use the standard dialog type size for labels and keep the worktree path preview beneath the Location field.
- Let the `.worktreeinclude` edit action wrap below its checkbox in narrow windows. With setup expanded, the standard dialog is about 118 logical pixels shorter, and the setup field fits without scrolling in a 440 × 520 window.
2026-11-23 15:17:34 +08:00
58 changed files with 1381 additions and 450 deletions

No files matched your search

+3 -3
View File
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
## Manage agents
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
- **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 › 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**.
**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**.
### External MCP servers
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
**Settings › Agents › MCP Connections** 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 › External MCP Servers**, 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 › MCP Connections**, and again after its definition changes.
## File format
+3 -3
View File
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
## 管理 agent
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
- **内置**:每个内置 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 连接** 中将其开启;服务器定义改变后也需要重新开启。
## 文件格式
+8 -4
View File
@@ -308,11 +308,15 @@ 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 › External MCP Servers.
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
// 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();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).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",
);
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
@@ -321,7 +325,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "External MCP Servers" })
.getByRole("heading", { name: "MCP Connections", exact: true })
.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
@@ -0,0 +1,83 @@
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,6 +385,8 @@ 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
@@ -0,0 +1,79 @@
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
@@ -0,0 +1,123 @@
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
@@ -0,0 +1,88 @@
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]);
});
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Settings › Agents › Coding Agents: one searchable list of every agent, those this machine can run first
* Agent Setup lists every agent, with 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
+2 -3
View File
@@ -1,6 +1,5 @@
/**
* Settings › Tools › Agents › Command Permissions: whitelist (auto-approve)
* and blacklist (auto-reject) command patterns evaluated on agent permission requests.
* Command Rules defines the allow and block patterns for agent permission requests.
*/
import { useMemo, useState } from "react";
import { tx } from "@/platform/i18n";
@@ -47,7 +46,7 @@ export function AgentPolicyPage() {
};
return (
<section className={styles.body} aria-label="Command Permissions">
<section className={styles.body} aria-label={tx("Command Rules")}>
<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 › Coding Agents. */
/** Settings › Agents › Agent Setup. */
import { AgentList } from "./AgentList";
import { tauriCommands, tauriRegistry, type CommandsBackend, type RegistryBackend } from "./registry";
import styles from "./AgentRegistry.module.css";
+2 -1
View File
@@ -224,11 +224,12 @@
flex: none;
}
/* Import Sessions from Other Apps: filter above a fixed-height list, so the dialog doesn't grow. */
/* Keep the import list height stable while filtering. */
.chooser {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: var(--space-3) var(--space-4) 0;
}
.chooserList {
height: 312px;
+6 -5
View File
@@ -281,8 +281,9 @@ describe("Agents docked view", () => {
]);
});
it("lists Import Sessions from Other Apps in Find Action", () => {
it("lists Import Sessions 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));
@@ -502,17 +503,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 Move to Group", () => {
it("offers the groups, a new one and a way out in the Group submenu", () => {
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 === "Move to Group");
const move = menu.find((item) => "label" in item && item.label === "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…",
"Remove from Group",
"No Group",
]);
expect(submenu[0]).toMatchObject({ checked: true });
});
@@ -520,7 +521,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 === "Move to Group") as {
const move = menu.find((item) => "label" in item && item.label === "Group") as {
submenu: { label?: string; run?: () => void }[];
};
act(() => move.submenu.find((item) => item.label === "Frontend")!.run!());
+2 -2
View File
@@ -1,4 +1,4 @@
/** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */
/** Pick external sessions and import them as agent 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 from Other Apps"
title="Import Sessions"
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 › External MCP Servers.
* reset session overrides, or jump to Settings › Agents › MCP Connections.
*/
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("External MCP Servers…")}
settingsTitle={tx("MCP Connections…")}
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 › External MCP Servers: multi-level MCP management across Global (`settings.toml`
* Settings › Agents › MCP Connections: 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>External MCP Servers</T>
<T>MCP Connections</T>
</h2>
<div className={page.headerActions}>
<Button
+4 -2
View File
@@ -202,6 +202,8 @@
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));
@@ -229,7 +231,7 @@
content-visibility: auto;
}
/* WebKit leaves a stale selection highlight on rows that skipped rendering (`useOffscreenRows`). */
.stream[data-selection] > .conversationRow[data-measured] {
.conversationRow[data-measured][data-selection] {
content-visibility: visible;
}
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
@@ -1274,7 +1276,7 @@
}
.changesScope {
flex: none;
padding: 6px 10px 2px;
padding: 0 4px;
}
.changesSummary {
flex: none;
+3 -3
View File
@@ -32,7 +32,7 @@ function FormWrapper({ children }: { children: ReactNode }) {
return <SettingsFormContext.Provider value={form}>{children}</SettingsFormContext.Provider>;
}
describe("Command Permissions sub-page", () => {
describe("Command Rules sub-page", () => {
it("registers under Agents group in settings", () => {
const dispose = activateSettingsPages();
try {
@@ -40,7 +40,7 @@ describe("Command Permissions 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 Permissions");
expect(policyNode?.title).toBe("Command Rules");
// 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 Permissions sub-page", () => {
</FormWrapper>,
);
const policy = screen.getByRole("region", { name: "Command Permissions" });
const policy = screen.getByRole("region", { name: "Command Rules" });
expect(within(policy).getByText("rm -rf *")).toBeInTheDocument();
fireEvent.change(within(policy).getByRole("textbox", { name: "Allowed command pattern" }), {
+4 -5
View File
@@ -313,7 +313,7 @@ export function activate(): () => void {
{
id: "agents.addAgent",
title: "More Agents…",
description: "Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.",
description: "Install, update, or remove agents from the ACP Registry.",
category: "Agents",
icon: "plugin",
keywords: ["agent", "acp", "registry", "install", "update"],
@@ -321,12 +321,11 @@ export function activate(): () => void {
},
{
id: "agents.mcpServers",
title: "External MCP Servers…",
description:
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
title: "MCP Connections…",
description: "Configure the MCP servers that agents can use.",
category: "Agents",
icon: "settings",
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
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 › External MCP Servers and the Composer MCP picker.
* and reactive cache for Settings › Agents › MCP Connections 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 › Coding Agents: the agents this machine runs. */
/** Settings › Agents › Agent Setup. */
export const REGISTRY_PAGE = "agents.list";
/** The Settings folder holding the agent pages. */
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
/** Settings › Agents › MCP Connections. */
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 Permissions. */
/** Settings › Agents › Command Rules. */
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 › Tools › Agents instead of choosing an agent. */
/** Picker entry that opens Settings › Agents › Agent Setup. */
export const ADD_AGENT = "__addAgent__";
/**
+16 -16
View File
@@ -4,14 +4,13 @@ import { repositoryPath } from "@/features/vcs/repositoryPaths";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { basename, dirname, relativeDir } from "@/platform/project";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tree } from "@/ui";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tabs, Tree } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChangesResizer } from "../ChangesResizer";
import styles from "../Session.module.css";
import { setChangesOptions, type ChangesScope } from "../changesOptions";
import { SegmentedControl } from "../ConfigPickers";
import { formatSentAt } from "../conversation";
import { branchLabel } from "../model";
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
@@ -386,20 +385,21 @@ export function ChangesPane({
)}
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
</div>
<div className={styles.changesScope}>
<SegmentedControl
ariaLabel={tx("Changes to show")}
options={[
{ value: "task", label: tx("Whole Task") },
{ value: "turn", label: tx("Last Turn") },
]}
value={scope}
onChange={(value) => {
setChangesOptions({ scope: value === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
/>
</div>
<Tabs
variant="compact"
className={styles.changesScope}
aria-label="Changes to show"
activeId={scope}
onSelect={(id) => {
if (id === scope) return;
setChangesOptions({ scope: id === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
items={[
{ id: "task", label: "Whole Task" },
{ id: "turn", label: "Last Turn" },
]}
/>
{(scope === "turn" || grouped || head || task.base) && (
<div className={styles.changesSummary}>
{scope === "turn" ? (
+26 -16
View File
@@ -1,4 +1,5 @@
import { createContext, useContext, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
import { createContext, useContext, useRef, useState, type ReactElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
/** Set while Find in Conversation is open: folded sections render their content, so it is found. */
export const FoldedContent = createContext(false);
@@ -9,8 +10,8 @@ export const FoldedContent = createContext(false);
*/
export const OpenFolds = createContext<Map<string, boolean> | null>(null);
/** Scrolls a section the reader just opened into view (`Stream`). */
export const RevealFold = createContext<((el: HTMLElement) => void) | 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);
/**
* A collapsed section that renders its content only once opened: most of a long conversation
@@ -35,29 +36,38 @@ export function Fold({
}) {
const always = useContext(FoldedContent);
const remembered = useContext(OpenFolds);
const reveal = useContext(RevealFold);
const keepHeader = useContext(KeepFoldHeader);
const [expanded, setExpanded] = useState(() => !!open || !!defaultOpen || (!!id && !!remembered?.get(id)));
const ref = useRef<HTMLDetailsElement>(null);
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]);
const remember = (now: boolean) => {
if (!id || !remembered) return;
if (now) remembered.set(id, true);
else remembered.delete(id);
};
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);
if (id && remembered) {
if (now) remembered.set(id, true);
else remembered.delete(id);
}
remember(now);
}}
>
{summary}
+93 -37
View File
@@ -49,7 +49,7 @@ import {
type EntryRow,
} from "./conversationRows";
import { FindBar } from "./FindBar";
import { OpenFolds, RevealFold } from "./Folds";
import { KeepFoldHeader, OpenFolds } 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);
useSelectionVisibility(ref, enabled, `.${styles.conversationRow}`);
}
interface StreamProps {
@@ -169,15 +169,31 @@ interface StreamProps {
/** Entries rendered at a time when a conversation opens at its end. */
const ENTRY_BATCH = 40;
function scrollsInside(target: EventTarget | null, root: HTMLElement): boolean {
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 {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el.scrollTop <= 0) continue;
const overflow = getComputedStyle(el).overflowY;
if (overflow === "auto" || overflow === "scroll") return true;
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;
}
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,
@@ -223,7 +239,7 @@ export function Stream({
const stopFollowing = useCallback(
(target: EventTarget | null) => {
const el = ref.current;
if (!el || el.scrollHeight <= el.clientHeight || scrollsInside(target, el)) return;
if (!el || el.scrollHeight <= el.clientHeight || scrollsUpInside(target, el)) return;
scrollingUp.current = true;
if (!position.current.stick) return;
position.current = { top: el.scrollTop, stick: false };
@@ -285,6 +301,24 @@ 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;
@@ -314,6 +348,7 @@ 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;
@@ -333,6 +368,7 @@ export function Stream({
const el = ref.current;
if (!el) return;
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
});
observer.observe(el);
@@ -340,40 +376,65 @@ export function Stream({
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions]);
// How far the end was below the view when a section was toggled, before its content renders.
const gapAtToggle = useRef(Infinity);
}, [key, positions, trimSlack]);
/**
* 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.
*/
useEffect(() => {
const el = ref.current;
if (!el) return;
const toggled = () => {
gapAtToggle.current = el.scrollHeight - el.scrollTop - el.clientHeight;
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;
};
el.addEventListener("toggle", toggled, true);
return () => el.removeEventListener("toggle", toggled, true);
}, []);
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [markUserScroll, stopFollowing]);
/**
* 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.
* 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.
*/
const revealFold = useCallback(
(fold: HTMLElement) => {
const keepFoldHeader = useCallback(
(header: HTMLElement, top: number) => {
const el = ref.current;
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) {
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) {
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
}
},
[key, positions],
[key, positions, setSlack, trimSlack],
);
/** Back to the end of the stream; following resumes from there. */
const jumpToLatest = useCallback(() => {
@@ -454,7 +515,7 @@ export function Stream({
);
return (
<OpenFolds.Provider value={openFolds}>
<RevealFold.Provider value={revealFold}>
<KeepFoldHeader.Provider value={keepFoldHeader}>
<div className={styles.streamArea}>
{finding && <FindBar streamRef={ref} focus={findFocus} onClose={onCloseFind} />}
<div
@@ -462,12 +523,6 @@ 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;
}}
@@ -497,6 +552,7 @@ 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;
@@ -586,7 +642,7 @@ export function Stream({
</div>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
</div>
</RevealFold.Provider>
</KeepFoldHeader.Provider>
</OpenFolds.Provider>
);
}
+95 -61
View File
@@ -772,30 +772,26 @@ describe("scrolling", () => {
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
});
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 }) => {
/** A stream whose height follows its fold and whose offset is clamped like a browser's. */
const foldingStream = (openHeight: number) => {
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", {
configurable: true,
get: () => Math.max(0, Math.min(top, height() - 400)),
set: (v: number) => {
top = Math.max(0, Math.min(v, height() - 400));
},
});
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" },
@@ -803,43 +799,79 @@ describe("scrolling", () => {
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
Object.defineProperty(el, "scrollHeight", {
configurable: true,
value: 1000,
});
Object.defineProperty(el, "clientHeight", {
configurable: true,
value: 400,
});
el.getBoundingClientRect = () => ({ top: 0, bottom: 400 }) as DOMRect;
const { el, summary } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 900 - el.scrollTop }) as DOMRect;
el.scrollTop = 600;
fireEvent.scroll(el);
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.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;
fireEvent.scroll(el);
// 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);
// 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);
});
it("keeps following when the view grows taller and the browser pulls the offset back", () => {
@@ -989,6 +1021,8 @@ 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);
@@ -2529,7 +2563,7 @@ describe("import sessions dialog", () => {
backend.external = sessions;
open();
await listed("Login fix");
expect(screen.getByRole("dialog", { name: "Import Sessions from Other Apps" })).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "Import Sessions" })).toBeInTheDocument();
});
it("imports the selected session and opens it", async () => {
@@ -3046,7 +3080,7 @@ describe("last turn changes", () => {
const pane = await screen.findByRole("complementary", { name: "Changes" });
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Last Turn" }));
fireEvent.click(within(pane).getByRole("tab", { name: "Last Turn" }));
await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull());
expect(within(pane).getByText("b.ts")).toBeInTheDocument();
expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument();
@@ -3059,7 +3093,7 @@ describe("last turn changes", () => {
backend.turnChanges = [];
fireEvent.click(within(pane).getByRole("button", { name: "Refresh" }));
expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Whole Task" }));
fireEvent.click(within(pane).getByRole("tab", { name: "Whole Task" }));
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
});
});
+6 -7
View File
@@ -2,24 +2,23 @@ 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: "Coding Agents",
title: "Agent Setup",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
keywords: ["agent", "acp", "registry", "install", "update", "Coding Agents"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
title: "MCP Connections",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
@@ -32,10 +31,10 @@ export function activateSettingsPages(): () => void {
},
{
id: POLICY_PAGE,
title: "Command Permissions",
title: "Command Rules",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "Command Permissions", "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 from Other Apps dialog is open. */
/** The Import Sessions dialog is open. */
importOpen: boolean;
/** External sessions being imported (`provider:sessionId`), so none is imported twice. */
importing: ReadonlySet<string>;
+13 -6
View File
@@ -1,6 +1,6 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { t, 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: "Move to Group",
label: "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: "Remove from Group",
label: "No 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 from Other Apps…",
title: "Import Sessions…",
category: "Agents",
icon: "download",
when: "projectOpen",
keywords: ["import", "claude", "codex", "history", "transcript"],
keywords: ["import", "other apps", "claude", "codex", "history", "transcript"],
run: showImportSessions,
},
{
@@ -398,7 +398,14 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
...(!auxiliaryWindow()
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
? ([
{
kind: "action",
action: "agents.moveToNewWindow",
label: t("app.window.askNew"),
arg: task.id,
},
] satisfies MenuItem[])
: []),
...(hasTaskTerminal(task, projectRoot)
? ([
+44 -13
View File
@@ -31,9 +31,6 @@
.bold {
font-weight: 600;
}
.flex {
flex: 1;
}
.ellipsis {
min-width: 0;
overflow: hidden;
@@ -440,29 +437,49 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
width: var(--submit-width);
min-width: 320px;
height: var(--submit-height);
min-height: 160px;
padding: 12px;
overflow: hidden;
resize: both;
width: 500px;
max-width: calc(100vw - 12px);
height: 200px;
max-height: calc(100vh - 12px);
padding: var(--space-3);
overflow: auto;
}
.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: 5px;
gap: var(--space-1);
}
.submitEditor {
flex: 1;
min-height: 40px;
padding: 4px 6px;
padding: var(--space-1) var(--space-2);
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;
}
@@ -470,12 +487,26 @@
border-color: var(--focus-ring);
}
.submitError {
flex: none;
flex: 0 1 auto;
min-height: 0;
max-height: 35%;
overflow: auto;
overflow-wrap: anywhere;
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,9 +5,11 @@
* 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, type CSSProperties } from "react";
import { useEffect, useState } 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";
@@ -25,26 +27,25 @@ 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={at} onClose={() => done(null)} />
<SubmitReview
number={number}
draftKey={draftKey}
anchor={anchor?.isConnected ? anchor : "center"}
onClose={() => done(null)}
/>
));
}
function SubmitReview(props: {
number: number;
draftKey: string;
anchor: Element | { x: number; y: number };
onClose: () => void;
}) {
const { number, draftKey, onClose } = props;
function SubmitReview(props: { number: number; draftKey: string; anchor: Element | "center"; onClose: () => void }) {
const { number, draftKey, anchor, 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(() => {
@@ -94,12 +95,11 @@ function SubmitReview(props: {
setBusy(false);
}
};
const anchored = "getBoundingClientRect" in props.anchor;
return (
<Popup
open
anchor={props.anchor}
placement={anchored ? "top-start" : "bottom-start"}
anchor={anchor}
placement="top-start"
onClose={(reason) => {
// A click outside does not drop a review while it is being sent.
if (reason !== "outside" || !busy) onClose();
@@ -107,26 +107,38 @@ function SubmitReview(props: {
role="dialog"
aria-label={t("Submit Review")}
className={styles.submitPopup}
style={{ "--submit-width": "500px", "--submit-height": "200px" } as CSSProperties}
resizable="both"
minWidth={260}
minHeight={160}
>
<div className={styles.submitHeader}>
<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 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>
</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);
@@ -134,7 +146,7 @@ function SubmitReview(props: {
}}
/>
{error && (
<div className={styles.submitError}>
<div className={styles.submitError} role="alert">
<T>Failed to submit review</T>
<div className={styles.secondary}>{error}</div>
</div>
+19 -10
View File
@@ -270,22 +270,31 @@
min-width: 0;
display: flex;
align-items: center;
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;
gap: var(--space-1-5);
}
.stashGroupName,
.stashTime,
.stashBranch,
.stashMessage {
flex: 1 1 auto;
min-width: 4em;
min-width: 0;
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,6 +307,25 @@
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),
+3 -1
View File
@@ -121,6 +121,7 @@ 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 {
@@ -735,7 +736,7 @@ function TwoPaneDiff({
viewerBase({
readOnly: !editable,
findBar: true,
lineNumbers: viewMode === "split" && notes === "left" ? "after" : true,
lineNumbers: viewMode === "split" ? (notes === "left" ? "after" : true) : single,
}),
collapseUnchanged ? collapsedDiffLines() : [],
changedRanges,
@@ -924,6 +925,7 @@ function TwoPaneDiff({
includable ? unifiedCommitSelection : [],
highlightChanges ? diffWords : [],
unifiedOnLeft ? unifiedLeftDiff(highlightChanges) : [],
single ? [] : unifiedLineNumbers(unifiedOnLeft),
unifiedMergeView({
original: unifiedOnLeft ? textB : textA,
highlightChanges,
+128 -113
View File
@@ -100,6 +100,7 @@ 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>();
@@ -367,128 +368,142 @@ 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.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
ref={branchInput}
aria-label="New branch name"
mono
disabled={formBusy}
value={branch ?? branchName}
onChange={(e) => setBranch(cleanBranch(e))}
/>
)}
<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);
<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);
}}
/>
<IconButton
icon="folder-open"
title="Choose Setup Script"
disabled={formBusy}
onClick={() => void browseSetupScript()}
</>
)}
<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>
<Input
id="worktree-name"
disabled={formBusy}
value={name ?? folderName}
onChange={(e) => setName(e.target.value)}
/>
<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>
</>
)}
</div>
{busy && (
<div className={styles.worktreeTarget} role="status">
{setupRequest && !skippingSetup ? tx("Creating worktree and running setup…") : tx("Creating worktree…")}
+81 -23
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 { IconButton, Select, SplitGroup, SplitHandle, SplitPanel, Tree, showContextMenu } from "@/ui";
import { Icon, 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,6 +14,15 @@ 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);
@@ -21,17 +30,41 @@ 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 [selectedStash, setSelectedStash] = useState<StashEntry | null>(null);
const [selection, setSelection] = useState<StashNode | null>(null);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
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 = matching.find((entry) => entry.index === selectedStash?.index) ?? matching[0] ?? stashes[0];
const selected = useMemo(() => new Set(current ? [stashKey(current)] : []), [current]);
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]);
useEffect(() => {
let live = true;
@@ -54,22 +87,33 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
const stashList = (
<div className={styles.treeWrap}>
<Tree<StashEntry>
roots={stashes}
getKey={stashKey}
getLabel={(s) => stashLabel(s.message).text}
getChildren={() => undefined}
isExpandable={() => false}
<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);
}}
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) => setSelectedStash(lead)}
onSelectionChange={(_keys, lead) => setSelection(lead)}
onContextMenu={(s, _keys, e) => {
if (!s || !loaded) return;
setSelectedStash(s);
if (!s || isGroup(s) || !loaded) return;
setSelection(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) },
@@ -79,16 +123,26 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
{ kind: "action", action: "vcs.clearStashes", arg: s.repo },
]);
}}
renderNode={(s) => {
const { branch, text } = stashLabel(s.message);
return (
<span className={styles.stashRow} title={`stash@{${s.index}}: ${s.message}`}>
<span className={styles.stashMessage}>
{repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""}
{text}
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);
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>}
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
</span>
);
}}
@@ -132,7 +186,7 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
onClick={() => current && void dropStash(current, current.repo)}
/>
</div>
{current ? (
{stashes.length > 0 ? (
<SplitGroup
orientation={orientation}
className={styles.split}
@@ -143,7 +197,11 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
</SplitPanel>
<SplitHandle aria-label={tx("Resize stash panes")} />
<SplitPanel id="files" minSize="25%">
<StashChanges key={`${stashIdentity(current)}:${tick}`} stash={current} />
{current ? (
<StashChanges key={`${stashIdentity(current)}:${tick}`} stash={current} />
) : (
<span className={styles.empty}>{tx("Select a stash to view its changes.")}</span>
)}
</SplitPanel>
</SplitGroup>
) : (
@@ -6,6 +6,7 @@ import {
buildBranchRows,
buildBranchTree,
buildMergedBranchTree,
mergedRefTooltip,
filterBranchTree,
isFavoriteBranch,
preferredBranchRow,
@@ -371,6 +372,22 @@ 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("front · First")).toBeInTheDocument();
expect(await screen.findByText("back · Second")).toBeInTheDocument();
expect(await screen.findByText("First")).toBeInTheDocument();
expect(await screen.findByText("Second")).toBeInTheDocument();
act(() => useVcs.setState({ repo: "/p/back" }));
await screen.findByText("front · First");
await screen.findByText("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("front · First");
const original = await screen.findByText("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("front · New")).toBeInTheDocument();
expect(screen.getByText("front · First").closest('[role="treeitem"]')).toHaveAttribute("aria-selected", "true");
expect(await screen.findByText("New")).toBeInTheDocument();
expect(screen.getByText("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("front · First");
await screen.findByText("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("front · First")).not.toBeInTheDocument();
expect(screen.queryByText("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("back · Second"), { button: 0 });
fireEvent.mouseDown(await screen.findByText("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("back · Second"), { button: 0 });
fireEvent.mouseDown(await screen.findByText("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,6 +581,24 @@ 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 => {
+19 -14
View File
@@ -316,10 +316,9 @@ class WorkingChunk extends WidgetType {
toDOM(view: EditorView) {
const block = document.createElement("div");
block.className = "cm-unifiedWorkingChunk";
if (!this.text.length) {
block.appendChild(document.createElement("br"));
return block;
}
block.dataset.diffFirstLine = String(getOriginalDoc(view.state).lineAt(this.chunk.fromA).number);
const makeRow = () => block.appendChild(document.createElement("div"));
let row = makeRow();
const tokens: Array<{ from: number; to: number; classes: string }> = [];
const lang = view.state.facet(language);
if (lang && this.text.length <= 3000)
@@ -346,16 +345,22 @@ class WorkingChunk extends WidgetType {
(insideWord ? word.toA : word?.fromA) ?? this.text.length,
);
const text = this.text.slice(at, end);
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);
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);
}
at = end;
}
if (!row.firstChild) row.appendChild(document.createElement("br"));
return block;
}
}
@@ -591,7 +596,7 @@ function viewerEditorLook(): Extension {
];
}
class LineNumber extends GutterMarker {
export class LineNumber extends GutterMarker {
constructor(readonly number: string) {
super();
}
@@ -603,7 +608,7 @@ class LineNumber extends GutterMarker {
}
}
function maxLineNumber(lines: number): number {
export function maxLineNumber(lines: number): number {
let last = 9;
while (last < lines) last = last * 10 + 9;
return last;
+33
View File
@@ -791,6 +791,36 @@
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;
@@ -801,6 +831,9 @@
color: var(--fg-muted);
overflow-wrap: anywhere;
}
.worktreeFields > .worktreeTarget {
font-size: var(--fs-small);
}
.comparisonDialog > [data-dialog-body] {
display: flex;
flex-direction: column;
+12 -5
View File
@@ -79,12 +79,19 @@ 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): LineFragment[] {
export function compareTexts(text1: string, text2: string, options: CompareOptions) {
const { policy } = options;
const fragments = options.words
? compareLinesInner(text1, text2, policy)
: compareLineFragments(text1, text2, policy);
return processBlocks(fragments, text1, text2, policy, !options.split, !!options.trimChunks);
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 };
}
/** Changed lines (ComparisonManagerImpl.compareLines). */
+6 -2
View File
@@ -130,8 +130,11 @@ 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):
@@ -155,7 +158,7 @@ function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
});
return chunks;
};
let compared: LineFragment[];
let compared: ReturnType<typeof compareTexts>;
try {
compared = compareTexts(textA, textB, idea);
} catch (error) {
@@ -165,7 +168,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.map((f) => {
const chunks = compared.fragments.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;
@@ -176,6 +179,7 @@ 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,6 +14,7 @@ import {
buildRepositoryBranchTree,
filterBranchTree,
isFavoriteBranch,
mergedRefTooltip,
type BranchTreeNode,
} from "../branches";
import { branchMenu, inRepo, mergedBranchMenu, showTagContextMenu } from "../branchMenu";
@@ -364,6 +365,7 @@ 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
@@ -0,0 +1,162 @@
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)];
}
+11 -5
View File
@@ -507,7 +507,8 @@
"Unpin ({count})": "Unpin ({count})",
"New Group": "New Group",
"Rename Group": "Rename Group",
"Remove from Group": "Remove from Group",
"Group": "Group",
"No Group": "No 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",
@@ -540,8 +541,7 @@
"Rename Agent Task Group": "Rename Agent Task Group",
"Remove Agent Task Group": "Remove Agent Task Group",
"Import Sessions…": "Import Sessions…",
"Import Sessions from Other Apps…": "Import Sessions from Other Apps…",
"Import Sessions from Other Apps": "Import Sessions from Other Apps",
"Import Sessions": "Import Sessions",
"No sessions from other apps": "No sessions from other apps",
"Already importing": "Already importing",
"Filter sessions": "Filter sessions",
@@ -1875,6 +1875,9 @@
"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",
@@ -1940,6 +1943,7 @@
"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",
@@ -1964,8 +1968,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.",
"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.",
"MCP Connections…": "MCP Connections…",
"Configure the MCP servers that agents can use.": "Configure the MCP servers that agents can use.",
"No matching remote branches": "No matching remote branches",
"Remote branches": "Remote branches",
"Fetch tags": "Fetch tags",
@@ -2648,6 +2652,7 @@
"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.",
@@ -3461,6 +3466,7 @@
"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",
"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.",
"Install, update, or remove agents from the ACP Registry.": "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",
"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.",
"Install, update, or remove agents from the ACP Registry.": "Installez, mettez à jour ou supprimez 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을 엽니다",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "설정 › 도구 › 에이전트를 엽니다: ACP Registry에서 에이전트를 설치, 업데이트 또는 제거합니다.",
"Install, update, or remove 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",
"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.",
"Install, update, or remove agents from the ACP Registry.": "Instaluj, aktualizuj lub usuwaj agentów z rejestru ACP.",
"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",
"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.",
"Install, update, or remove agents from the ACP Registry.": "Instale, atualize ou remova 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}",
+7 -6
View File
@@ -161,7 +161,7 @@
"Unpin ({count})": "Sabitlemeyi Kaldır ({count})",
"New Group": "Yeni Grup",
"Rename Group": "Grubu Yeniden Adlandır",
"Remove from Group": "Gruptan Kaldır",
"No Group": "Grup Yok",
"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,8 +194,7 @@
"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 from Other Apps…": "Diğer Uygulamalardan Oturumları İçe Aktar…",
"Import Sessions from Other Apps": "Diğer Uygulamalardan Oturumları İçe Aktar",
"Import Sessions": "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",
@@ -1388,6 +1387,7 @@
"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,6 +1447,7 @@
"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",
@@ -1466,8 +1467,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.",
"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.",
"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.",
"No matching remote branches": "Eşleşen uzak dal bulunamadı",
"Remote branches": "Uzak dallar",
"Branch name prefixes": "Dal adı önekleri",
@@ -7519,7 +7520,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",
"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.",
"Install, update, or remove agents from the ACP Registry.": "ACP Kayıt Deposu'ndan ajanları yükleyin, güncelleyin veya kaldırın.",
"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}",
+8 -6
View File
@@ -143,7 +143,7 @@
"Unpin ({count})": "取消固定({count})",
"New Group": "新增群組",
"Rename Group": "重新命名群組",
"Remove from Group": "從群組中移除",
"No Group": "不分組",
"Remove “{name}”? Its tasks move back to their status groups.": "移除「{name}」?其中的任務將回到各自的狀態分組。",
"Copy Link Address": "複製連結地址",
"Pin Agent Tasks": "固定 Agent 任務",
@@ -599,6 +599,7 @@
"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": "阻止的命令",
@@ -2788,8 +2789,7 @@
"Session finished": "工作階段已結束",
"Sessions from other apps": "來自其他應用的代理工作階段",
"Import Sessions…": "匯入工作階段…",
"Import Sessions from Other Apps…": "從其他應用匯入代理工作階段…",
"Import Sessions from Other Apps": "從其他應用匯入代理工作階段",
"Import Sessions": "匯入工作階段",
"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。",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "開啟 設定 › 工具 › Agents:從 ACP Registry 安裝、更新或移除 Agent。",
"Install, update, or remove agents from the ACP Registry.": "從 ACP Registry 安裝、更新或移除代理。",
"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,6 +7788,7 @@
"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 任務",
@@ -7863,6 +7864,7 @@
"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 伺服器的更多資訊",
@@ -7883,8 +7885,8 @@
"One KEY=VALUE entry per line.": "每行一個 KEY=VALUE 條目。",
"One Header=Value entry per line.": "每行一個 Header=Value 條目。",
"Maven project could not be configured": "無法設定 Maven 專案",
"External MCP Servers…": "外部 MCP 伺服器…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "開啟「設定 › 代理 › 外部 MCP 伺服器」:設定程式設計代理使用的使用者級和工作區級 MCP 伺服器。",
"MCP Connections…": "MCP 連線…",
"Configure the MCP servers that agents can use.": "設定代理可以使用的 MCP 伺服器。",
"Type:": "型別:",
"Command:": "命令:",
"Arguments:": "引數:",
+12 -8
View File
@@ -420,7 +420,7 @@
"Unpin ({count})": "取消固定({count})",
"New Group": "新建组",
"Rename Group": "重命名组",
"Remove from Group": "从组中移除",
"No 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,6 +889,7 @@
"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": "阻止的命令",
@@ -1989,7 +1990,7 @@
"Green": "绿色",
"Grey": "灰色",
"Greyscale": "灰度",
"Group": "组",
"Group": "分组",
"Group by Severity": "按严重性分组",
"Groups": "组",
"Gutter Icons": "装订区域图标",
@@ -2359,6 +2360,7 @@
"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": "没有要回滚的更改",
@@ -3199,8 +3201,7 @@
"Session finished": "会话已结束",
"Sessions from other apps": "来自其他应用的智能体会话",
"Import Sessions…": "导入会话…",
"Import Sessions from Other Apps…": "从其他应用导入智能体会话…",
"Import Sessions from Other Apps": "从其他应用导入智能体会话",
"Import Sessions": "导入会话",
"No sessions from other apps": "没有来自其他应用的智能体会话",
"Already importing": "正在导入",
"Filter sessions": "过滤会话",
@@ -6214,6 +6215,7 @@
"Show Branches": "显示分支",
"Update Selected": "更新所选",
"Navigate Log to Selected Branch": "在日志中导航到所选分支",
"(no tracking branch)": "(无跟踪分支)",
"Group by Repository": "按仓库分组",
"Branch or tag": "分支或标签",
"Filter branches and tags": "过滤分支和标签",
@@ -6324,7 +6326,7 @@
"More Agents…": "更多 Agent…",
"More agents…": "更多 Agent…",
"Opens Settings › Build, Execution, Deployment › Maven": "打开 设置 › 构建、执行、部署 › Maven。",
"Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.": "打开 设置 › 工具 › Agents:从 ACP Registry 安装、更新或移除 Agent。",
"Install, update, or remove agents from the ACP Registry.": "从 ACP Registry 安装、更新或移除智能体。",
"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}",
@@ -8308,6 +8310,7 @@
"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 任务",
@@ -8383,6 +8386,7 @@
"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 服务器的更多信息",
@@ -8403,8 +8407,8 @@
"One KEY=VALUE entry per line.": "每行一个 KEY=VALUE 条目。",
"One Header=Value entry per line.": "每行一个 Header=Value 条目。",
"Maven project could not be configured": "无法配置 Maven 项目",
"External MCP Servers…": "外部 MCP 服务器…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "打开“设置 › 智能体 › 外部 MCP 服务器”:配置编程智能体使用的用户级和工作区级 MCP 服务器。",
"MCP Connections…": "MCP 连接…",
"Configure the MCP servers that agents can use.": "配置智能体可以使用的 MCP 服务器。",
"Type:": "类型:",
"Command:": "命令:",
"Arguments:": "参数:",
+22 -2
View File
@@ -146,12 +146,14 @@ 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() {
function TrackedVisibilityPane({ rows = false }: { rows?: boolean }) {
const ref = useRef<HTMLDivElement>(null);
useSelectionVisibility(ref);
useSelectionVisibility(ref, true, rows ? "p" : undefined);
return (
<div ref={ref} data-testid="tracked">
<p>Tracked line</p>
<p>Second line</p>
<p>Third line</p>
</div>
);
}
@@ -194,3 +196,21 @@ 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");
});
+28 -11
View File
@@ -111,32 +111,49 @@ function textEdge(root: HTMLElement, side: "start" | "end"): { node: Node; offse
}
/**
* Marks `ref` with `data-selection` while the document's selection intersects it, and keeps the
* Marks the pane or its intersecting rows 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): void {
export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabled = true, rowSelector?: string): void {
useEffect(() => {
const el = ref.current;
if (!el || !enabled) return;
const doc = el.ownerDocument;
const win = doc.defaultView ?? window;
let frame = 0;
const selected = () => {
const marked = new Set<Element>();
const selectionRange = () => {
const sel = doc.getSelection();
return !!sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el);
return sel && !sel.isCollapsed && sel.rangeCount ? sel.getRangeAt(0) : null;
};
const update = () => {
win.cancelAnimationFrame(frame);
if (selected()) {
el.setAttribute("data-selection", "");
return;
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 (!el.hasAttribute("data-selection")) return;
if (![...marked].some((target) => !range?.intersectsNode(target))) return;
frame = win.requestAnimationFrame(() => {
frame = win.requestAnimationFrame(() => {
if (!selected()) el.removeAttribute("data-selection");
const current = selectionRange();
for (const target of marked) {
if (current?.intersectsNode(target)) continue;
target.removeAttribute("data-selection");
marked.delete(target);
}
});
});
};
@@ -145,9 +162,9 @@ export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabl
return () => {
win.cancelAnimationFrame(frame);
doc.removeEventListener("selectionchange", update);
el.removeAttribute("data-selection");
for (const target of marked) target.removeAttribute("data-selection");
};
}, [ref, enabled]);
}, [ref, enabled, rowSelector]);
}
/**