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

..
Автор SHA1 Повідомлення Дата
l0ng-ai d6d55ef614 fix(app): window close and WSL open in place don't drop unsaved untitled buffers 2026-11-16 19:12:47 +08:00
14 змінених файлів з 48 додано та 205 видалено

No files matched your search

+21 -28
Переглянути файл
@@ -210,23 +210,20 @@ impl Shared {
}
}
/// The MCP servers passed to a session, and the names of the ones off for it.
fn mcp_servers_for_session(
&self,
provider: &str,
init: &acp::Negotiated,
overrides: &BTreeMap<String, bool>,
) -> McpForSession {
let builtin_off = overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false);
let mut servers =
if builtin_off { Vec::new() } else { mcp_servers_for(init.mcp_stdio(), &self.paths.project_root) };
) -> Vec<Value> {
let mut servers = if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
Vec::new()
} else {
mcp_servers_for(init.mcp_stdio(), &self.paths.project_root)
};
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
let mut off = mcp::servers_off(&configured, overrides);
if builtin_off {
off.push(BUILTIN_SERVER.to_owned());
}
McpForSession { servers, off }
servers
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
@@ -1153,7 +1150,7 @@ impl AgentManager {
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
params["sessionId"] = json!(live.session);
params
},
@@ -2329,7 +2326,7 @@ impl Task {
let mut session = None;
if let (Some(id), true) = (saved, can_load) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
@@ -2343,7 +2340,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers);
let params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -3287,19 +3284,18 @@ fn turn_starts(entries: &[AgentEntry]) -> Vec<usize> {
.collect()
}
/// The MCP servers of a session, and the names of the ones off for it.
struct McpForSession {
servers: Vec<Value>,
off: Vec<String>,
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// servers, and the ones off for this session, so an agent that also loads its own
/// servers, and the ones switched off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too.
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
if !mcp.off.is_empty() {
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
fn session_params(cwd: &str, servers: &[Value], overrides: &BTreeMap<String, bool>) -> Value {
let off: Vec<&str> = overrides
.iter()
.filter(|(name, on)| !**on && name.as_str() != mcp::BUILTIN_MCP_NAME)
.map(|(name, _)| name.as_str())
.collect();
let mut params = json!({ "cwd": cwd, "mcpServers": servers });
if !off.is_empty() {
params["_meta"] = json!({ "openidea": { "mcpServersOff": off } });
}
params
}
@@ -3412,9 +3408,6 @@ mod replay_tests;
#[cfg(test)]
mod tests;
/// The name agents know the built-in server by (its tools are `mcp__OpenIDEA__…` in Claude Code).
const BUILTIN_SERVER: &str = "OpenIDEA";
// The desktop advertises its relay only while the built-in server is listening.
static MCP_EXECUTABLE: parking_lot::RwLock<Option<std::path::PathBuf>> = parking_lot::RwLock::new(None);
@@ -3429,7 +3422,7 @@ fn mcp_servers_for(supported: bool, root: &std::path::Path) -> Vec<Value> {
fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root: &std::path::Path) -> Vec<Value> {
let Some(executable) = executable.filter(|_| supported) else { return Vec::new() };
let command = ide_mcp::stdio_command(executable, root);
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": [] })]
vec![json!({ "name": "OpenIDEA", "command": command[0], "args": command[1..], "env": [] })]
}
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
-61
Переглянути файл
@@ -86,29 +86,6 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
})
}
/// The configured servers off for this session: off by default and not switched on for it, or
/// switched off for it. Named so an agent that also loads its own configuration can keep a
/// same-named server of it off too. Workspace entries take precedence, as in [`acp_mcp_servers`].
pub(crate) fn servers_off(all: &[McpServer], overrides: &BTreeMap<String, bool>) -> Vec<String> {
let mut seen = HashSet::new();
let ordered =
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
let configured: Vec<String> = ordered
.filter(|s| seen.insert(s.name.as_str()))
.filter(|s| !overrides.get(&s.name).copied().unwrap_or(s.enabled))
.map(|s| s.name.clone())
.collect();
// A server switched off that the IDE doesn't configure may still be the agent's own.
let switched = overrides
.iter()
.filter(|(name, on)| !**on && name.as_str() != BUILTIN_MCP_NAME && !seen.contains(name.as_str()))
.map(|(name, _)| name.clone());
let mut off: Vec<String> = configured.into_iter().chain(switched).collect();
off.sort();
off.dedup();
off
}
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
/// Workspace entries take precedence over User entries with the same name. Per-session
/// `overrides` (`server_name` -> `enabled`) can enable a disabled server or disable an enabled one
@@ -1039,44 +1016,6 @@ fn parse_key_values_map(val: Option<&Value>) -> BTreeMap<String, String> {
mod tests {
use super::*;
fn configured(name: &str, scope: McpScope, enabled: bool) -> McpServer {
McpServer {
id: format!("{scope:?}:{name}"),
name: name.into(),
scope,
transport: McpTransport::Stdio,
enabled,
command: Some("x".into()),
args: Vec::new(),
env: Vec::new(),
url: None,
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
}
}
#[test]
fn servers_off_follow_the_effective_state() {
let all = [
configured("default-off", McpScope::User, false),
configured("switched-on", McpScope::User, false),
configured("on", McpScope::User, true),
configured("switched-off", McpScope::User, true),
// The workspace entry decides for its name.
configured("both", McpScope::User, true),
configured("both", McpScope::Workspace, false),
];
let overrides = BTreeMap::from([
("switched-on".to_owned(), true),
("switched-off".to_owned(), false),
("agent-own".to_owned(), false),
(BUILTIN_MCP_NAME.to_owned(), false),
]);
assert_eq!(servers_off(&all, &overrides), ["agent-own", "both", "default-off", "switched-off"]);
assert_eq!(servers_off(&all[2..4], &BTreeMap::new()), Vec::<String>::new());
}
#[test]
fn crud_and_acp_filtering_by_scope_agent_and_transport() {
let mut user = BTreeMap::new();
+8 -5
Переглянути файл
@@ -4240,12 +4240,15 @@ done
}
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp);
fn session_params_name_the_servers_switched_off() {
let overrides = BTreeMap::from([
("github".to_owned(), false),
("docs".to_owned(), true),
(mcp::BUILTIN_MCP_NAME.to_owned(), false),
]);
let params = session_params("/p", &[json!({ "name": "docs" })], &overrides);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none).get("_meta").is_none());
assert!(session_params("/p", &[], &BTreeMap::new()).get("_meta").is_none());
}
-13
Переглянути файл
@@ -40,17 +40,4 @@ describe("cancellable refactoring requests", () => {
expect(isCancelled(err)).toBe(true);
expect(send).not.toHaveBeenCalled();
});
it("tells the sender once the dialog closed after the request was handed over", async () => {
const run = new AbortController();
let wanted!: () => boolean;
const reply = cancellable(run.signal, async (_id, w) => {
wanted = w;
return "sent";
});
expect(wanted()).toBe(true);
run.abort();
expect(wanted()).toBe(false);
await reply;
});
});
+3 -4
Переглянути файл
@@ -136,10 +136,9 @@ export async function extractInterface(
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
extracted = await cancellable(signal, (id, wanted) =>
lspRequest(
() => commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
wanted,
extracted = await cancellable(signal, (id) =>
lspRequest(() =>
commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
),
);
if (signal?.aborted) return { status: "stay" };
+6 -15
Переглянути файл
@@ -134,30 +134,21 @@ export async function applyEdit(view: EditorView, edit: WorkspaceEdit, signal?:
await whenAllSynced();
// The dialog closed while the editors were syncing: nothing is applied.
if (signal?.aborted) return;
await lspRequest(
() => commands.applyWorkspaceEdit(edit),
() => !signal?.aborted,
);
await lspRequest(() => commands.applyWorkspaceEdit(edit));
} catch (e) {
reportLspError(view, e, true);
}
}
/**
* Sends `send(id, wanted)` with a fresh request id that `signal` cancels. `wanted` goes to
* `lspRequest`, which syncs editors first: a dialog closed meanwhile never sends the request.
*/
export async function cancellable<T>(
signal: AbortSignal | undefined,
send: (id: number, wanted: () => boolean) => Promise<T>,
): Promise<T> {
/** Sends `send(id)` with a fresh request id that `signal` cancels. */
export async function cancellable<T>(signal: AbortSignal | undefined, send: (id: number) => Promise<T>): Promise<T> {
// Closed before the request went out: it never does (a cancel can't reach an unsent request).
if (signal?.aborted) throw new IpcError({ kind: "cancelled", message: "Cancelled" });
const id = nextRequestId();
const abort = () => void commands.cancelRequest(id);
signal?.addEventListener("abort", abort);
try {
return await send(id, () => !signal?.aborted);
return await send(id);
} finally {
signal?.removeEventListener("abort", abort);
}
@@ -195,8 +186,8 @@ export async function changeSignature(
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
changed = await cancellable(signal, (id, wanted) =>
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token), wanted),
changed = await cancellable(signal, (id) =>
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token)),
);
if (signal?.aborted) return { status: "stay" };
const fatal = changed.problems.find((p) => p.severity === "fatal");
+1 -2
Переглянути файл
@@ -200,8 +200,7 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
{items.length ? (
items.map((item, index) => (
<Block
// Keyed by file alone: switching the layout keeps each block's diff and its documents.
key={item.path}
key={`${item.path}:${mode}`}
item={item}
index={index}
items={items}
-12
Переглянути файл
@@ -354,15 +354,3 @@
[role="treeitem"][aria-selected="true"] .stageButton {
visibility: visible;
}
.inspectionFix {
margin-left: var(--space-2);
padding: 0;
border: none;
background: none;
color: var(--link);
font: inherit;
cursor: pointer;
}
.inspectionFix:hover {
text-decoration: underline;
}
+4 -33
Переглянути файл
@@ -15,7 +15,7 @@ import {
type MouseEvent,
type PointerEvent,
} from "react";
import { tx, txTemplate } from "@/platform/i18n";
import { tx } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, dirname } from "@/platform/project";
@@ -961,14 +961,6 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
);
}
const MISSING_BLANK_LINE = "Missing blank line between subject and body";
/** The quick fix for {@link MISSING_BLANK_LINE}: an empty line after the subject. */
export function addBlankLineAfterSubject(message: string): string {
const end = message.indexOf("\n");
return end < 0 ? message : `${message.slice(0, end)}\n${message.slice(end)}`;
}
/** Commit message inspections (Settings › Version Control › Commit). */
export function messageProblems(
message: string,
@@ -984,7 +976,8 @@ export function messageProblems(
const out: string[] = [];
if (c.limitSubject && (lines[0]?.length ?? 0) > c.subjectLimit)
out.push(`Subject line is longer than ${c.subjectLimit} characters`);
if (c.blankLineAfterSubject && lines.length > 1 && lines[1]!.trim() !== "") out.push(MISSING_BLANK_LINE);
if (c.blankLineAfterSubject && lines.length > 1 && lines[1]!.trim() !== "")
out.push("Missing blank line between subject and body");
if (c.limitBody) {
const long = lines.slice(1).findIndex((l) => l.length > c.bodyLimit);
if (long >= 0) out.push(`Body line ${long + 2} is longer than ${c.bodyLimit} characters`);
@@ -1167,29 +1160,7 @@ export function CommitMessageField({
)}
{problems.length > 0 && (
<div className={styles.inspections} role="status">
{problems.map((p, i) => (
<span key={p}>
{i > 0 && " · "}
{txTemplate(p)}
{p === MISSING_BLANK_LINE && (
<button
type="button"
className={styles.inspectionFix}
onClick={() => {
const el = ref.current;
const caret = el ? el.selectionStart + (el.selectionStart > first.length ? 1 : 0) : 0;
useCommit.setState({ message: addBlankLineAfterSubject(message) });
requestAnimationFrame(() => {
el?.focus();
el?.setSelectionRange(caret, caret);
});
}}
>
<T>Add blank line</T>
</button>
)}
</span>
))}
{problems.join(" · ")}
</div>
)}
{checkProblems.length > 0 && (
-5
Переглянути файл
@@ -335,11 +335,6 @@ export function DiffEditor({
};
}, [path, leftKey, rightKey, contextKey]);
// A host that picks the layout (the all-in-one diff's toolbar) switches it in place.
const asked = input_.mode;
useEffect(() => {
if (asked) setOptsState((o) => (o.mode === asked ? o : { ...o, mode: asked }));
}, [asked]);
const setOpts = (patch: Partial<DiffViewOptions>) =>
setOptsState((o) => {
const next = { ...o, ...patch };
+2 -10
Переглянути файл
@@ -103,20 +103,12 @@ describe("the all-in-one diff tab", () => {
expect(screen.getAllByTestId("block-diff")[0]).toBe(first);
});
it("switches every block between side-by-side and unified, collapsed ones too, in place", () => {
it("switches every block between side-by-side and unified", () => {
render(<CombinedDiffTab input={input} />);
const before = screen.getAllByTestId("block-diff");
act(() => {
fireEvent.click(screen.getAllByRole("button", { name: "Collapse File" })[0]!);
});
act(() => {
fireEvent.click(screen.getByRole("button", { name: "Unified Viewer" }));
});
const after = screen.getAllByTestId("block-diff");
expect(after.every((b) => b.dataset.mode === "unified")).toBe(true);
// The same diffs: switching never released their documents (and unsaved edits).
expect(after).toEqual(before);
after.forEach((b, i) => expect(b).toBe(before[i]));
expect(screen.getAllByTestId("block-diff").every((b) => b.dataset.mode === "unified")).toBe(true);
});
it("opens a file's own diff, and goes back to one tab per file", async () => {
+1 -9
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { BranchInfo } from "@/bindings";
import { addBlankLineAfterSubject, messageProblems, wrapAtMargin } from "../CommitView";
import { messageProblems, wrapAtMargin } from "../CommitView";
import { linkifyIssues } from "../issueLinks";
import {
isProtectedBranch,
@@ -41,14 +41,6 @@ describe("commit message inspections", () => {
expect(messageProblems("x".repeat(20), { ...cfg, limitSubject: false })).toEqual([]);
});
it("adds the missing blank line after the subject", () => {
const fixed = addBlankLineAfterSubject("111\n111");
expect(fixed).toBe("111\n\n111");
expect(messageProblems(fixed, cfg)).toEqual([]);
expect(addBlankLineAfterSubject("subject\nline 2\nline 3")).toBe("subject\n\nline 2\nline 3");
expect(addBlankLineAfterSubject("subject")).toBe("subject");
});
it("wraps body lines at the last space before the margin", () => {
const text = "subject\n\nhello world again";
expect(wrapAtMargin(text, text.length, 12)).toEqual({ text: "subject\n\nhello world\nagain", caret: text.length });
+1 -4
Переглянути файл
@@ -2158,8 +2158,5 @@
"The interface could not be extracted": "The interface could not be extracted",
"Extract Interface is not supported for {name}": "Extract Interface is not supported for {name}",
"Package for new interface": "Package for new interface",
"Untitled files were not saved": "Untitled files were not saved",
"Missing blank line between subject and body": "Missing blank line between subject and body",
"Body line {0} is longer than {1} characters": "Body line {0} is longer than {1} characters",
"Add blank line": "Add blank line"
"Untitled files were not saved": "Untitled files were not saved"
}
+1 -4
Переглянути файл
@@ -8541,8 +8541,5 @@
"The interface could not be extracted": "无法提取接口",
"Extract Interface is not supported for {name}": "{name} 不支持提取接口",
"Package for new interface": "新接口的软件包",
"Untitled files were not saved": "未命名文件未保存",
"Missing blank line between subject and body": "主题和正文之间缺少空行",
"Body line {0} is longer than {1} characters": "正文第 {0} 行超过 {1} 个字符",
"Add blank line": "添加空行"
"Untitled files were not saved": "未命名文件未保存"
}