Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 4aef69e73f Merge remote-tracking branch 'origin/main' into fix/quick-documentation-layout 2026-11-20 02:51:55 +08:00
l0ng-ai 121e1fa535 fix(completion): fit the lookup to the editor and its font (#4566)
The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size.
2026-11-20 02:51:47 +08:00
lleviathe 5859cf9f5b feat(mcp): show background projects in the status bar (#4590)
A Background Projects status bar item shows how many projects the MCP server holds open without a window, only while there are any (and never in a remote window). Its popup lists each project with its badge, state and path, opens one in its own window or unloads it, and offers Unload All and MCP Server Settings. The Settings page's Open now list uses the same rows.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 02:49:08 +08:00
l0ng-ai 21b187f2d5 test: fix main's spacing-scale and model-refresh failures (#4591)
pnpm test failed on main twice: the HTTP Client's redirect list from #4519 used gap: 2px instead of --space-0-5, and the agent model-refresh test's IPC mock lacked vcsRemotes, which the session's origin lookup reads since #4554.
2026-11-20 02:47:51 +08:00
l0ng-ai 4eca76c286 fix(editor): make quick documentation fit narrow windows 2026-11-19 23:56:55 +08:00
24 змінених файлів з 722 додано та 70 видалено

No files matched your search

+2
Переглянути файл
@@ -155,6 +155,8 @@ When a project loads and unloads:
**Open now** lists the loaded projects, each with what it is doing (answering a request, kept open by a run, or how long it has been idle and when it unloads) and an **Unload** button. Unloading does not wait for **Apply**. The project loads again on the next tool call that names it, if the setting still serves it.
While any project is loaded, the **Background Projects** item in the status bar (a layers icon and the count) opens the same list. Each row has the **Open in New Window** and **Unload** icon buttons, and below the list are **Unload All** and **MCP Server Settings…**.
What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools.
A background project has no window, so some tools differ:
+2
Переглянути файл
@@ -154,6 +154,8 @@ stdio 配置大致如下(路径以你机器上的为准):
**当前已打开** 列出已加载的项目,每个项目显示它正在做什么(正在处理请求、因某个运行保持打开,或已空闲多久以及何时卸载),并带有 **卸载** 按钮。卸载不必等到 **应用**。如果设置仍然提供该项目,下一次指向它的工具调用会再次加载它。
只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。
后台项目没有窗口,所以有些工具不同:
+82
Переглянути файл
@@ -65,6 +65,7 @@ test("completion lists the server's items and inserts the chosen one", async ({
const popup = page.locator(".cm-tooltip-autocomplete");
await expect(popup.getByText("total", { exact: true })).toBeVisible();
await expect(popup.getByText("toDto", { exact: true })).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(360);
const field = popup.locator("li").filter({ has: page.locator(".cm-completionLabel", { hasText: /^total$/ }) });
await expect(field.locator(".cm-completionDetail")).toHaveCount(0);
await expect(field.locator(".cm-lsp-type")).toHaveText("BigDecimal");
@@ -83,6 +84,17 @@ test("completion lists the server's items and inserts the chosen one", async ({
const label = await method.locator(".cm-completionLabel").boundingBox();
// Subpixel rounding differs per platform/font; a mis-set inset is a whole icon column off.
expect(Math.abs(label!.x - wordStart)).toBeLessThanOrEqual(2);
const zoomedSize = await editor.locator(".cm-content").evaluate(async (content) => {
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const prefsModule = "/src/editor/core/cm/prefs.ts";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
const fontSize = Number.parseFloat(getComputedStyle(content).fontSize);
stepFontZoom(EditorView.findFromDOM(content as HTMLElement)!, 6);
return `${fontSize + 6}px`;
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize);
await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize);
await page.keyboard.type("toD");
await expect(popup.getByText("total", { exact: true })).toBeHidden();
// Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top.
@@ -98,6 +110,76 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => {
const editor = await openSample(page);
const label = "transformOrder" + "AcrossParticipatingRegions".repeat(5);
await page.evaluate((label) => {
const item: CompletionItem = {
label,
labelDetail: "(order: Order, options: TransformationOptions)",
labelDescription: "Promise<TransformationResult>",
detail: `${label}(order: Order, options: TransformationOptions): Promise<TransformationResult>`,
kind: "method",
documentation: { kind: "markdown", value: "Transforms the order." },
sortText: null,
filterText: null,
preselect: true,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
};
window.__ipc.handlers.lsp_completion = () => ({ isIncomplete: false, items: [item] });
}, label);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.type("order.");
await page.keyboard.press("Control+Space");
const popup = page.locator(".cm-tooltip-autocomplete");
const option = popup.getByRole("option").filter({
has: page.locator(".cm-completionLabel", { hasText: label }),
});
await expect(option.locator(".cm-completionLabel")).toHaveText(label);
await page.setViewportSize({ width: 580, height: 900 });
const bounds = (await editor.boundingBox())!;
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(bounds.x - box.x, box.x + box.width - (bounds.x + bounds.width));
})
.toBeLessThanOrEqual(2);
const geometry = await option.evaluate((row) => {
const label = row.querySelector<HTMLElement>(".cm-completionLabel")!;
const type = row.querySelector<HTMLElement>(".cm-lsp-type")!;
return {
nameTruncated: label.scrollWidth > label.clientWidth,
nameWidth: label.clientWidth,
typeWidth: type.clientWidth,
typeOverflow: type.getBoundingClientRect().right - row.getBoundingClientRect().right,
};
});
expect(geometry.nameTruncated).toBe(true);
expect(geometry.nameWidth).toBeGreaterThan(40);
expect(geometry.typeWidth).toBeGreaterThan(16);
expect(geometry.typeOverflow).toBeLessThanOrEqual(1);
await page.keyboard.press("F1");
await expect(popup.locator(".cm-completionInfo")).toContainText(
`${label}(order: Order, options: TransformationOptions)`,
);
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect(editor.locator(".cm-activeLine")).toContainText(`order.${label}()`);
});
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
const editor = await openSample(page);
await page.evaluate(async () => {
+73
Переглянути файл
@@ -0,0 +1,73 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
async function quickDocumentation(page: Page, markdown: string) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((value) => {
window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null });
}, markdown);
const line = editor.locator(".cm-line", { hasText: "return order.toDto()" });
await line.click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("F1");
const popup = page.getByRole("dialog", { name: "Documentation", exact: true });
await expect(popup.locator(".cm-lsp-markdown")).toBeVisible();
return popup;
}
test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => {
const popup = await quickDocumentation(page, "Returns the total.");
const back = popup.getByRole("button", { name: "Back", exact: true });
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
const bounds = (await popup.boundingBox())!;
expect(bounds.width).toBeGreaterThanOrEqual(298);
expect(bounds.width).toBeLessThan(320);
const backBounds = (await back.boundingBox())!;
const dockBounds = (await dock.boundingBox())!;
expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2);
expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16);
await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => {
const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult";
const markdown = [
`\`\`\`kotlin\n${signature}\n\`\`\``,
...Array.from({ length: 22 }, (_, i) => {
return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`;
}),
"End of pricing documentation.",
].join("\n\n");
const popup = await quickDocumentation(page, markdown);
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(508);
await page.setViewportSize({ width: 430, height: 500 });
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500);
})
.toBeLessThanOrEqual(1);
const body = popup.locator(".cm-lsp-markdown").locator("..");
const last = popup.getByText("End of pricing documentation.");
const dockBefore = (await dock.boundingBox())!;
await expect(body.locator("pre")).toContainText(signature);
const scroll = await body.evaluate((node) => {
node.scrollTop = node.scrollHeight;
return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth };
});
expect(scroll.top).toBeGreaterThan(0);
expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1);
const lastBounds = (await last.boundingBox())!;
expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1);
expect(await dock.boundingBox()).toEqual(dockBefore);
await expect(dock).toBeInViewport();
});
+17 -2
Переглянути файл
@@ -238,6 +238,10 @@
flex-direction: column;
overflow: hidden;
}
.docPopup:not([data-resized]) {
width: max-content;
min-width: min(300px, 90vw);
}
.docScope {
display: contents;
}
@@ -246,21 +250,32 @@
}
.docPopup .docFrame {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.docPopup:not([data-resized]) .docFrame {
max-width: min(600px, 90vw);
max-height: 420px;
max-width: min(500px, 90vw);
max-height: 500px;
}
.docPopup .docBody {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: var(--space-2) var(--space-4) var(--space-1);
}
.docPopup .docToolbar {
position: static;
flex: none;
align-self: flex-end;
margin: 0 var(--space-2) var(--space-1);
padding: 0;
border: 0;
}
.docPopup .docToolbar .spacer {
display: none;
}
.docWindowFrame {
height: 100%;
+14 -1
Переглянути файл
@@ -356,6 +356,19 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
const opened = useRef(focusSeq);
// The captured caret can end up outside the viewport while the popup is open.
const anchor = useMemo(
() => ({
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(popup.anchor.x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
}),
[popup.anchor],
);
useEffect(() => {
if (focusSeq !== opened.current)
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
@@ -364,7 +377,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
return (
<Popup
open
anchor={popup.anchor}
anchor={anchor}
onClose={closePopup}
aria-label="Documentation"
className={styles.docPopup}
+32 -21
Переглянути файл
@@ -25,7 +25,7 @@ import {
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view";
import { EditorView, ViewPlugin, getTooltip, keymap, showTooltip, type Rect, type ViewUpdate } from "@codemirror/view";
import {
call,
commands,
@@ -59,6 +59,8 @@ import { showHint } from "./hint";
import { inplaceRenameActive } from "./inplaceRename";
import { languageSemantics } from "./semantic";
import { remoteChange } from "@/editor/api";
import { tooltipBounds } from "@/editor/core/cm/setup";
import { completionLabelOffset } from "./theme";
interface RequestContext {
doc: number;
@@ -983,36 +985,45 @@ function sortToggle(view: EditorView): HTMLElement {
return button;
}
/** IDEA's advertiser bar under the list (one tip: "Press ↵ to insert, ⇥ to replace") and its Sort by Name toggle. */
const completionFooter = ViewPlugin.fromClass(
const completionPopup = ViewPlugin.fromClass(
class {
constructor(private view: EditorView) {}
update(u: ViewUpdate) {
if (completionStatus(u.state) !== "active") return;
this.view.requestMeasure({
read: () => null,
write: () => {
const scope = this.view.dom.ownerDocument;
const tooltips = [
...this.view.dom.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
...scope.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
];
for (const t of tooltips) {
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
if (footer) {
// CodeMirror rebuilds the option list by appending a fresh <ul>,
// which would leave an existing footer above the list.
const list = t.querySelector(":scope > ul");
if (list && list.nextElementSibling !== footer) list.after(footer);
continue;
}
key: this,
read: () => {
const { left, right } = tooltipBounds(this.view);
return {
width: `${Math.max(0, Math.floor(right - left))}px`,
fontSize: getComputedStyle(this.view.contentDOM).fontSize,
};
},
write: ({ width, fontSize }) => {
const popup = this.view.state
.facet(showTooltip)
.map((tooltip) => tooltip && getTooltip(this.view, tooltip))
.find((tooltip) => tooltip?.dom.classList.contains("cm-lsp-completion"));
if (!popup) return;
// Apply the label alignment inside CodeMirror's viewport clamp.
popup.offset = { x: -completionLabelOffset, y: 0 };
const t = popup.dom;
if (t.style.getPropertyValue("--cm-completion-max-width") !== width)
t.style.setProperty("--cm-completion-max-width", width);
// The body-level tooltip does not inherit the editor's temporary font zoom.
if (t.style.getPropertyValue("--openidea-editor-font-size") !== fontSize)
t.style.setProperty("--openidea-editor-font-size", fontSize);
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
if (!footer) {
footer = document.createElement("div");
footer.className = "cm-lsp-completion-footer";
const tip = document.createElement("span");
tip.textContent = tx("Press ↵ to insert, ⇥ to replace");
footer.append(tip, sortToggle(this.view));
t.appendChild(footer);
}
// CodeMirror appends a fresh list when the candidates change.
const list = t.querySelector(":scope > ul");
if (list && list.nextElementSibling !== footer) list.after(footer);
},
});
}
@@ -1067,7 +1078,7 @@ export function completionExtension() {
tooltipClass: () => "cm-lsp-completion",
positionInfo: positionCompletionInfo,
}),
completionFooter,
completionPopup,
lookupTracker,
serverInsertAt,
caretAfterServerInsert,
+29 -24
Переглянути файл
@@ -10,19 +10,17 @@ const tooltipSurface = {
color: "var(--fg)",
};
/**
* Row metrics that put a label one icon column right of the popup's left edge. They live on the
* popup as custom properties so every rule consuming them — including the popup's negative
* offset below — changes together. The remaining 1px is tooltipSurface's border, shared with
* the hover and signature tooltips.
*/
const completionInsets = { edge: 4, padding: 6, icon: 16, gap: 6 };
export const completionLabelOffset =
1 + completionInsets.edge + completionInsets.padding + completionInsets.icon + completionInsets.gap;
const completionRowMetrics = {
// Rows grow with the editor font size (lookup text uses the editor font, as typed text does).
"--cm-completion-row": "max(var(--h-list-row), calc(var(--openidea-editor-font-size, var(--fs-code)) * 1.7))",
"--cm-completion-edge": "4px",
"--cm-completion-inset": "6px",
"--cm-completion-icon": "16px",
"--cm-completion-gap": "6px",
"--cm-completion-edge": `${completionInsets.edge}px`,
"--cm-completion-inset": `${completionInsets.padding}px`,
"--cm-completion-icon": `${completionInsets.icon}px`,
"--cm-completion-gap": `${completionInsets.gap}px`,
};
const markdown = {
@@ -103,22 +101,19 @@ export const lspTheme = EditorView.theme({
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
// CodeMirror anchors the popup at the completed word's start. Pull it left by one row's
// leading inset so the labels, not the icon column, sit on the text. CodeMirror's horizontal
// clamp measures the border box (margins excluded), so this offset sits outside its math:
// near the right edge it leaves that much extra space, and a word starting within one inset
// of the viewport's left edge would let the popup clip there. The normal editor layout
// (gutter + project sidebar) keeps the word well clear of that edge.
marginLeft:
"calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))",
display: "flex",
flexDirection: "column",
width: "max-content",
maxWidth: "min(720px, var(--cm-completion-max-width, 100vw))",
// No overflow clipping: CodeMirror nests the documentation pane in this box and
// positions it outside it (see `positionCompletionInfo`). The footer rounds itself.
},
".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
minWidth: "420px",
maxWidth: "min(720px, 80vw)",
minWidth: "0",
maxWidth: "100%",
height: "auto",
maxHeight: "calc(var(--cm-completion-row) * 11 + 8px)",
padding: "4px 0",
},
@@ -153,9 +148,15 @@ export const lspTheme = EditorView.theme({
alignItems: "center",
justifyContent: "center",
},
".cm-lsp-completion .cm-completionLabel": { flex: "none", overflow: "hidden", textOverflow: "ellipsis" },
".cm-lsp-completion .cm-completionLabel": {
flex: "0 1 auto",
minWidth: "0",
overflow: "hidden",
textOverflow: "ellipsis",
},
".cm-lsp-completion .cm-completionDetail": {
flex: "0 1 auto",
minWidth: "0",
marginLeft: "0",
fontStyle: "normal",
color: "var(--fg-subtle)",
@@ -172,7 +173,8 @@ export const lspTheme = EditorView.theme({
marginLeft: "calc(-1 * var(--cm-completion-gap))",
},
".cm-lsp-completion .cm-lsp-type": {
flex: "1 0 auto",
flex: "0 1 auto",
minWidth: "0",
maxWidth: "60%",
marginLeft: "auto",
paddingLeft: "16px",
@@ -188,18 +190,21 @@ export const lspTheme = EditorView.theme({
},
".cm-lsp-completion-footer": {
display: "flex",
flex: "none",
flexWrap: "wrap",
alignItems: "center",
padding: "5px 12px",
backgroundColor: "var(--bg-popup-inline, var(--bg-elev))",
color: "var(--fg-subtle)",
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-small)",
whiteSpace: "nowrap",
gap: "12px",
gap: "var(--space-1) var(--space-3)",
justifyContent: "space-between",
borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)",
},
".cm-lsp-completion-sort": {
flex: "none",
maxWidth: "100%",
padding: "0",
border: "none",
background: "none",
+1
Переглянути файл
@@ -54,6 +54,7 @@ vi.mock("@/platform/ipc", async (original) => ({
agentCommands: async () => ok([]),
vcsBranchInfo: async () => ok({ head: "main" }),
vcsConfigGet: async () => ok(null),
vcsRemotes: async () => ok([]),
vcsBranches: async () => ok([]),
agentCreate: (request: NewAgentTask) => backend.create(request),
agentEntries: async () => ok([{ type: "user", text: "Earlier message", attachments: [] }] satisfies AgentEntry[]),
+1 -1
Переглянути файл
@@ -135,7 +135,7 @@
.redirects {
display: flex;
flex-direction: column;
gap: 2px;
gap: var(--space-0-5);
padding: 2px 8px;
border-bottom: 1px solid var(--border);
font-family: var(--font-mono);
+119
Переглянути файл
@@ -0,0 +1,119 @@
/* Mirrors the title bar's project popup: two-line project rows, then action rows. */
.panel {
display: flex;
flex-direction: column;
width: 400px;
padding: var(--space-1-5) 0;
font-family: var(--font-ui);
font-size: var(--fs-ui);
color: var(--fg);
outline: none;
}
.header {
padding: var(--space-1) var(--space-4);
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 600;
}
.projects {
display: flex;
flex-direction: column;
max-height: 320px;
margin: 0;
padding: 0;
overflow-y: auto;
list-style: none;
}
.project {
position: relative;
display: flex;
align-items: center;
gap: var(--space-3);
min-width: 0;
margin: 0 var(--space-1-5);
padding: var(--space-1-5) var(--space-2);
border-radius: var(--radius-selection);
}
.project:hover,
.project:focus-within {
background: var(--bg-tree-selected);
}
.text {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-3);
min-width: 0;
}
.name,
.path,
.state {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name {
color: var(--fg-strong);
}
.path,
.state {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.state {
flex: none;
max-width: 60%;
}
/* The row's actions take the place of its state while the row is hovered or focused. */
.actions {
position: absolute;
top: 50%;
right: var(--space-2);
display: flex;
gap: var(--space-0-5);
transform: translateY(-50%);
opacity: 0;
}
.project:hover .actions,
.project:focus-within .actions {
opacity: 1;
}
.project:hover .state,
.project:focus-within .state {
visibility: hidden;
}
.project:hover .path,
.project:focus-within .path {
padding-right: 52px;
}
.separator {
height: 1px;
margin: var(--space-1-5) var(--space-3);
background: var(--border);
}
.action {
display: flex;
align-items: center;
min-height: var(--h-list-row);
margin: 0 var(--space-1-5);
padding: 0 var(--space-2);
border: 0;
border-radius: var(--radius-selection);
background: none;
color: var(--fg-strong);
font: inherit;
text-align: left;
cursor: default;
}
.action:hover,
.action:focus-visible {
background: var(--bg-tree-selected);
outline: none;
}
+139
Переглянути файл
@@ -0,0 +1,139 @@
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { McpBackgroundProject } from "@/bindings";
const mocks = vi.hoisted(() => ({
list: vi.fn(),
unload: vi.fn(),
execute: vi.fn(async (_id: string, _arg?: unknown) => {}),
}));
vi.mock("@/platform/actions", async (original) => ({
...(await original<object>()),
executeAction: mocks.execute,
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: { ...real.commands, mcpBackgroundProjects: mocks.list, mcpUnloadBackgroundProject: mocks.unload },
};
});
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const { useRemote } = await import("@/platform/remote");
const { BackgroundStatus } = await import("./BackgroundStatus");
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
const project = (root: string, patch: Partial<McpBackgroundProject> = {}): McpBackgroundProject => ({
root,
idleSeconds: 0,
...patch,
});
const inventory = project("/projects/inventory");
const billing = project("/projects/billing", { keptOpenBy: { kind: "request" } });
async function show(projects: McpBackgroundProject[]) {
mocks.list.mockResolvedValue(ok(projects));
render(<BackgroundStatus />);
await act(async () => {});
}
const openPopup = async () => {
fireEvent.click(screen.getByRole("button", { name: /Background Projects/ }));
await act(async () => {});
return screen.getByRole("dialog", { name: "Background Projects" });
};
beforeEach(() => {
mocks.list.mockReset();
mocks.unload.mockReset().mockResolvedValue(ok(null));
mocks.execute.mockClear();
});
afterEach(() => {
cleanup();
useRemote.setState({ session: null });
});
describe("background projects in the status bar", () => {
it("renders nothing while no project is loaded", async () => {
await show([]);
expect(screen.queryByRole("button")).toBeNull();
});
it("shows how many projects are loaded", async () => {
await show([inventory, billing]);
expect(screen.getByRole("button", { name: /Background Projects/ })).toHaveTextContent("2");
});
it("lists each project with its name, path and state", async () => {
await show([inventory, billing]);
const popup = await openPopup();
expect(within(popup).getByText("inventory")).toBeInTheDocument();
expect(within(popup).getByText("/projects/billing")).toBeInTheDocument();
expect(within(popup).getByText("Answering a request")).toBeInTheDocument();
expect(within(popup).getByText("Last request just now")).toBeInTheDocument();
});
it("opens with the focus on the list, so no row's state gives way to its actions", async () => {
await show([inventory]);
const popup = await openPopup();
expect(popup.contains(document.activeElement)).toBe(true);
expect(document.activeElement).not.toBeInstanceOf(HTMLButtonElement);
});
it("stays hidden in a remote window, whose server serves no background projects", async () => {
useRemote.setState({
session: { root: "/srv/app" } as NonNullable<ReturnType<typeof useRemote.getState>["session"]>,
});
await show([inventory]);
expect(screen.queryByRole("button")).toBeNull();
});
it("names a project at the file system root by its path", async () => {
await show([project("/")]);
const popup = await openPopup();
expect(within(popup).getAllByText("/").length).toBe(2);
});
it("opens a project in its own window from its row", async () => {
await show([inventory, billing]);
const popup = await openPopup();
fireEvent.click(within(popup).getByRole("button", { name: "Open /projects/billing in a new window" }));
expect(mocks.execute).toHaveBeenCalledWith("file.openInNewWindow", "/projects/billing");
});
it("unloads the project of the row", async () => {
await show([inventory, billing]);
const popup = await openPopup();
fireEvent.click(within(popup).getByRole("button", { name: "Unload /projects/inventory" }));
expect(mocks.unload).toHaveBeenCalledTimes(1);
expect(mocks.unload).toHaveBeenCalledWith("/projects/inventory");
});
it("unloads every listed project once with Unload All", async () => {
await show([inventory, billing]);
const popup = await openPopup();
fireEvent.click(within(popup).getByRole("button", { name: "Unload All" }));
expect(mocks.unload.mock.calls.map((c) => c[0])).toEqual(["/projects/inventory", "/projects/billing"]);
});
it("closes the popup before it opens the MCP server settings", async () => {
await show([inventory]);
const popup = await openPopup();
mocks.execute.mockImplementationOnce(async () => {
expect(popup.isConnected).toBe(false);
});
fireEvent.click(within(popup).getByRole("button", { name: "MCP Server Settings…" }));
expect(mocks.execute).toHaveBeenCalledWith("file.settings", "agents.mcpServer");
expect(screen.queryByRole("dialog", { name: "Background Projects" })).toBeNull();
});
it("closes the popup and hides the item when the last project unloads", async () => {
await show([inventory]);
await openPopup();
mocks.list.mockResolvedValue(ok([]));
await act(async () => emitLocalIdeEvent({ type: "mcpBackgroundProjectsChanged" }));
expect(screen.queryByRole("dialog", { name: "Background Projects" })).toBeNull();
expect(screen.queryByRole("button")).toBeNull();
});
});
+112
Переглянути файл
@@ -0,0 +1,112 @@
import { useRef, useState } from "react";
import { flushSync } from "react-dom";
import { BarButton, Icon, IconButton, Popup, T } from "@/ui";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground";
import { basename } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { ProjectBadge } from "@/workbench/ProjectBadge";
import styles from "./BackgroundStatus.module.css";
/** Status bar item for the projects the MCP server holds open without a window. */
export function BackgroundStatus() {
const t = useTx();
const loaded = useBackgroundProjects();
// A remote window's commands reach its server, which serves none: the desktop's list stays out of it.
const remote = useRemote((s) => s.session !== null);
const projects = remote ? [] : loaded;
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
const count = projects.length;
// Reset during render, so the popup does not reappear with the next project that loads.
if (count === 0 && open) setOpen(false);
if (count === 0) return null;
return (
<>
<BarButton
ref={ref}
aria-expanded={open}
aria-label={t`Background Projects: ${count}`}
tooltip={t("Projects the MCP server holds open without a window")}
onClick={() => setOpen((o) => !o)}
>
<Icon name="layers" size={14} />
{count}
</BarButton>
<Popup
open={open}
anchor={ref}
placement="top-end"
offset={6}
onClose={() => setOpen(false)}
aria-label={t("Background Projects")}
>
{/* The focus starts on the list: on a row it would swap that row's state for its actions. */}
<div className={styles.panel} tabIndex={-1} data-autofocus>
<div className={styles.header}>
<T>Served without a window</T>
</div>
<ul className={styles.projects}>
{projects.map((project) => {
const path = project.root;
const name = basename(path) || path;
return (
<li key={path} className={styles.project}>
<ProjectBadge name={name} path={path} />
<div className={styles.text}>
<span className={styles.top}>
<span className={styles.name} title={name}>
{name}
</span>
<span className={styles.state}>{backgroundProjectState(project)}</span>
</span>
<span className={styles.path} title={path}>
{path}
</span>
</div>
<span className={styles.actions}>
<IconButton
icon="external-link"
size="small"
title="Open in New Window"
aria-label={t`Open ${path} in a new window`}
onClick={() => void executeAction("file.openInNewWindow", path)}
/>
<IconButton
icon="close"
size="small"
title="Unload"
aria-label={t`Unload ${path}`}
onClick={() => unloadBackgroundProject(path)}
/>
</span>
</li>
);
})}
</ul>
<div className={styles.separator} role="separator" />
<button
type="button"
className={styles.action}
onClick={() => projects.forEach((p) => unloadBackgroundProject(p.root))}
>
<T>Unload All</T>
</button>
<button
type="button"
className={styles.action}
onClick={() => {
flushSync(() => setOpen(false));
void executeAction("file.settings", "agents.mcpServer");
}}
>
<T>MCP Server Settings…</T>
</button>
</div>
</Popup>
</>
);
}
+11 -1
Переглянути файл
@@ -4,12 +4,21 @@ import { commands, call, onIdeEvent, ideEventsReady } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { registerOverlay } from "@/workbench/contributions";
import { registerOverlay, registerStatusItem } from "@/workbench/contributions";
import { BackgroundStatus } from "./BackgroundStatus";
import { McpConfirmHost } from "./ConfirmDialog";
import { denyAll, dropConfirm, handleMcpRequest } from "./requests";
export function activate(): () => void {
const offOverlay = registerOverlay({ id: "mcp.confirm", component: McpConfirmHost });
const offStatus = registerStatusItem({
id: "mcp.background",
align: "right",
priority: 4,
title: "Background Projects",
component: BackgroundStatus,
lightEdit: true,
});
const offRequests = onIdeEvent("mcpRequest", (e) => void handleMcpRequest(e.id, e.request));
const offClosed = onIdeEvent("mcpRequestClosed", (e) => dropConfirm(e.id));
const ready = () => {
@@ -104,6 +113,7 @@ export function activate(): () => void {
disposed = true;
unload();
offOverlay();
offStatus();
offRequests();
offClosed();
window.removeEventListener("beforeunload", unload);
+6 -1
Переглянути файл
@@ -73,8 +73,13 @@ vi.mock("@/platform/ipc", () => ({
mcpSetFocusedEditor: state.reportFocused,
},
}));
vi.mock("@/workbench/contributions", () => ({ registerOverlay: () => () => {}, editorService: vi.fn() }));
vi.mock("@/workbench/contributions", () => ({
registerOverlay: () => () => {},
registerStatusItem: () => () => {},
editorService: vi.fn(),
}));
vi.mock("./ConfirmDialog", () => ({ McpConfirmHost: () => null }));
vi.mock("./BackgroundStatus", () => ({ BackgroundStatus: () => null }));
const { activate } = await import("./index");
describe("MCP editor reports", () => {
+22 -13
Переглянути файл
@@ -12,43 +12,52 @@
align-items: center;
gap: var(--space-2);
}
.path {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
font-size: var(--fs-small);
}
/* Framed like the Folders list above it; rows as in the status bar's Background Projects popup. */
.projects {
display: flex;
flex-direction: column;
gap: var(--space-2);
width: 100%;
max-width: 480px;
min-width: 0;
margin: 0;
padding: 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
list-style: none;
}
.project {
display: flex;
align-items: center;
gap: var(--space-2);
gap: var(--space-3);
min-width: 0;
padding: var(--space-2) var(--space-3);
}
.project + .project {
border-top: 1px solid var(--border);
}
.projectText {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.projectName {
.projectName,
.projectPath,
.projectState {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 600;
}
.projectName {
color: var(--fg-strong);
}
.projectPath,
.projectState {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.unload {
flex: none;
}
+7 -6
Переглянути файл
@@ -1,10 +1,11 @@
/** Built-in MCP server status and client configurations. */
import { useEffect, useState } from "react";
import { commands, call, isTauri, onIdeEvent, type McpServerStatus } from "@/platform/ipc";
import { backgroundProjectState, useBackgroundProjects } from "@/platform/mcpBackground";
import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground";
import { basename, useProject } from "@/platform/project";
import { WORKFLOW_LIMITS } from "@/platform/workflowSettings";
import { useTx } from "@/platform/i18n";
import { ProjectBadge } from "@/workbench/ProjectBadge";
import { useRemote } from "@/platform/remote";
import { Button, Input, T, copyText } from "@/ui";
import { GlobListEditor, Row, SettingNumber, SettingSelect } from "../components/Form";
@@ -233,7 +234,6 @@ function BackgroundOpenNow() {
const projects = remote ? [] : loaded;
const [mode] = useSetting<string>("mcpServer.backgroundProjects");
const [enabled] = useSetting<boolean>("mcpServer.enabled");
const unload = (root: string) => void call(commands.mcpUnloadBackgroundProject(root)).catch(() => undefined);
return (
<Row
label="Open now"
@@ -255,23 +255,24 @@ function BackgroundOpenNow() {
) : (
<ul className={styles.projects}>
{projects.map((project) => {
const name = basename(project.root);
const name = basename(project.root) || project.root;
return (
<li key={project.root} className={styles.project}>
<ProjectBadge name={name} path={project.root} />
<div className={styles.projectText}>
<span className={styles.projectName} title={name}>
{name}
</span>
<span className={styles.path} title={project.root}>
<span className={styles.projectPath} title={project.root}>
{project.root}
</span>
<span className={styles.status}>{backgroundProjectState(project)}</span>
<span className={styles.projectState}>{backgroundProjectState(project)}</span>
</div>
<Button
size="small"
className={styles.unload}
aria-label={tx`Unload ${project.root}`}
onClick={() => unload(project.root)}
onClick={() => unloadBackgroundProject(project.root)}
>
<T>Unload</T>
</Button>
+7
Переглянути файл
@@ -1739,6 +1739,13 @@
"Unload {path}": "Unload {path}",
"Background projects are off": "Background projects are off",
"A remote host serves only the project open in its window": "A remote host serves only the project open in its window",
"Served without a window": "Served without a window",
"Background Projects": "Background Projects",
"Background Projects: {count}": "Background Projects: {count}",
"Projects the MCP server holds open without a window": "Projects the MCP server holds open without a window",
"Open {path} in a new window": "Open {path} in a new window",
"Unload All": "Unload All",
"MCP Server Settings…": "MCP Server Settings…",
"The MCP server is off": "The MCP server is off",
"Archived ({count})": "Archived ({count})",
"Insert": "Insert",
+7
Переглянути файл
@@ -8142,6 +8142,13 @@
"Unload {path}": "卸载 {path}",
"Background projects are off": "后台项目已关闭",
"A remote host serves only the project open in its window": "远程主机只为其窗口中打开的项目提供服务",
"Served without a window": "无窗口提供服务",
"Background Projects": "后台项目",
"Background Projects: {count}": "后台项目:{count}",
"Projects the MCP server holds open without a window": "MCP 服务器在没有窗口的情况下保持打开的项目",
"Open {path} in a new window": "在新窗口中打开 {path}",
"Unload All": "全部卸载",
"MCP Server Settings…": "MCP 服务器设置…",
"The MCP server is off": "MCP 服务器已关闭",
"Archived ({count})": "归档({count})",
"Insert": "插入",
+5
Переглянути файл
@@ -23,6 +23,11 @@ export function backgroundProjectState(project: McpBackgroundProject): string {
return tx`Idle ${n} min, unloads in ${m} min`;
}
/** Unloads one background project at once; one that is not loaded is already unloaded. */
export function unloadBackgroundProject(root: string): void {
void call(commands.mcpUnloadBackgroundProject(root)).catch(() => undefined);
}
/**
* The background projects, current: fetched on mount and when the backend reports a change, and every 30 s
* while any is loaded, every 3 s while one answers a request (the end of a request and an idle project's
+1
Переглянути файл
@@ -312,6 +312,7 @@ const ICONS = {
"page-first": "openidea/general/pageFirst",
"page-last": "openidea/general/pageLast",
sliders: "openidea/general/sliders",
layers: "openidea/general/layers",
"graphql-variables": "openidea/general/graphqlVariables",
layout: "general/layout",
split: "general/splitVertically",
+4
Переглянути файл
@@ -0,0 +1,4 @@
<!-- OpenIDEA: Layers (stacked planes) -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 2L13.5 4.75L8 7.5L2.5 4.75L8 2Z" stroke="#6C707E" stroke-linejoin="round"/><path d="M2.5 7.5L8 10.25L13.5 7.5M2.5 10.25L8 13L13.5 10.25" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 361 B

+14
Переглянути файл
@@ -0,0 +1,14 @@
.badge {
display: flex;
flex: none;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: var(--radius-selection);
background: linear-gradient(135deg, var(--project-color), var(--project-color-end));
color: var(--fg-button-primary);
font-size: var(--fs-tiny);
font-weight: 600;
letter-spacing: 0.02em;
}
+15
Переглянути файл
@@ -0,0 +1,15 @@
import { useSyncExternalStore } from "react";
import clsx from "clsx";
import { projectInitials } from "./projectColor";
import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "./tabColors";
import styles from "./ProjectBadge.module.css";
/** Square project avatar for a two-line row: the title bar widget's colour and initials. */
export function ProjectBadge({ name, path, className }: { name: string; path: string; className?: string }) {
useSyncExternalStore(subscribeTabColors, tabColorsVersion);
return (
<span className={clsx(styles.badge, className)} style={tabColorVars(name, tabColorOverride(path))} aria-hidden>
{projectInitials(name)}
</span>
);
}