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

..
Автор SHA1 Повідомлення Дата
l0ng-ai a3708fa7bc fix(refactor): a dialog closed while editors sync never sends its request 2026-11-16 19:25:30 +08:00
l0ng-ai 2277c1cdfd fix(vcs): translate commit message hints and offer Add blank line (#3749)
The commit message inspections were shown as untranslated English text with
no way to act on them, so the subject/body hint read like an error that
blocked line breaks. They now go through the text catalog, and the missing
blank line hint has an Add blank line fix that inserts it and keeps the caret.

Fixes #3732
2026-11-16 19:19:50 +08:00
l0ng-ai a537223233 fix(agents): deny the MCP servers off by default and the built-in one when off (#3748)
Session denials came only from explicit per-session false overrides. They now follow each configured server's effective state (workspace entries first), keep switched-off names the IDE doesn't configure, and add the built-in server's agent-facing name OpenIDEA when it is off.
2026-11-16 19:19:03 +08:00
l0ng-ai 19c7947fc4 fix(vcs): switching the all-in-one diff's layout keeps its blocks and their edits (#3747)
Block keys included the layout, so switching it remounted every block and a collapsed one released its document. Blocks are keyed by file; DiffEditor follows the layout the host asks for in place.
2026-11-16 19:16:39 +08:00
l0ng-ai 98f9fc0063 fix(app): window close and WSL open in place don't drop unsaved untitled buffers (#3746)
The window close path saved without checking that untitled buffers were saved, and WSL open in place asked the leave guard as if untitled buffers stayed with the window. The close path now shares the post-save untitled check, and WSL is resolved before the guard.
2026-11-16 19:13:00 +08:00
l0ng-ai 0d5ef48a94 fix(refactor): closed refactoring dialogs never apply or send their request (#3745)
applyEdit waited for editor sync and then applied regardless of the dialog's signal; cancellable sent its request even when the signal was already aborted. Both now check the signal.
2026-11-16 19:11:14 +08:00
l0ng-ai 444b620985 fix(agents): side conversations run in the agent's most careful mode (#3744)
A side conversation's denial of project changes only works in a mode that asks first, but Claude Code's Accept Edits and Codex's Ask were kept, and a refused switch still started the session. Side conversations now take the agent's most careful mode (Codex Read Only, Claude Code default, then plan/ask), don't start when the agent's settings don't end up there, and refuse a mode change that doesn't ask.
2026-11-16 19:09:27 +08:00
l0ng-ai 0c45a96d84 fix(build): artifact layout never goes through links in its output folder (#3743)
The cleanup of recorded files and the copy into a user-chosen artifact output folder followed links, so a folder of the output replaced by a link to the sources made the build delete or overwrite source files. Recorded paths through a link are skipped, a file link in an artifact file's place is replaced, and a folder that links elsewhere stops the layout.
2026-11-16 19:07:31 +08:00
l0ng-ai fd8f8d6dd0 fix(agents): an MCP server switched off for a Claude session stays off (#3742)
Switching a server off in the session's MCP picker only left it out of the servers passed to the session, so a server Claude Code also loads from its own configuration kept running. The session parameters now name the servers switched off (_meta.openidea.mcpServersOff) and the Claude Code session denies their tools with --disallowedTools mcp__<server>.
2026-11-16 18:51:59 +08:00
l0ng-ai c1bec5182c fix(navigation): Python super methods walk up from the class itself (#3741)
The graph walk behind a Python method's super-method icon started from the class name and continued by base names, so same-named classes elsewhere contributed unrelated super methods. It now walks concrete class declarations, resolving each base from the file that names it.
2026-11-16 18:47:43 +08:00
l0ng-ai dcb4835a87 fix(vcs): the staging area commits a staged addition deleted from disk (#3740)
A file added to the index and then deleted from disk is no change against HEAD, so the change lists leave it out; the staging area applied the same rule and listed it nowhere, keeping Commit disabled or silently leaving the staged addition out of the commit. With the staging area on, it is now listed under Staged (added) and Unstaged (deleted) and committed as staged.
2026-11-16 18:46:03 +08:00
l0ng-ai f74bc7abac fix(vcs): collapsing a file in the all-files diff keeps its unsaved edits (#3739)
Collapsing a block unmounted its diff editor and released the working-tree document, which with autosave off drops its unsaved edits. A loaded block now keeps its diff while collapsed, hidden.
2026-11-16 18:43:09 +08:00
l0ng-ai c871c164c1 fix(ui): editor hints and balloons stay inside the window (#3738)
An editor hint is the tooltip element itself, so the editor theme's .cm-tooltip max-width (same specificity, loaded later) replaced its 480 px limit and long messages ran past the window edge; the limit now applies to .cm-tooltip.cm-lsp-hint. The balloon stack keeps 16 px from the left as well and balloons narrow to fit, so they are no longer cut off in a narrow window.
2026-11-16 18:40:53 +08:00
l0ng-ai db65b12afe fix(app): Close Project asks about untitled buffers instead of dropping them (#3737)
The unsaved-changes guard left untitled buffers out because they follow the window into another project opened in place, but it also ran for Close Project, Disconnect from Remote Host, closing to Welcome and opening a remote project in place, where they don't follow, so they were dropped without a question. The guard now knows where the window goes; only another local project in place leaves them alone, otherwise they count, Save asks for their paths and a cancelled Save As keeps the project open.
2026-11-16 18:37:29 +08:00
l0ng-ai 0cc873565a fix(refactor): closing a Java refactoring dialog cancels it; identifiers in any script (#3734)
Closing Change Signature or Extract Interface while it was checking for conflicts left the check running, and its edit was applied (or its Problems Detected asked) after the dialog was gone; closing now cancels the request in flight and nothing is confirmed, previewed or applied afterwards. The identifier check was ASCII-only and rejected valid Java names in other scripts; it now follows Java's identifier rules.
2026-11-16 18:31:59 +08:00
l0ng-ai 7cc100367d fix(mcp): http_run_request sends the request the user approved (#3733)
The tool prepared the request to show its resolved URL in the confirmation, then prepared it again to send it, re-reading the environment files: changed in the meantime, they could send the private-environment headers to a destination the user never approved. ide_http::send now sends a prepared request as is, and the tool sends exactly the one it showed.
2026-11-16 18:30:06 +08:00
l0ng-ai 39c0f6676e fix(agents): side conversations never replay a mode that approves everything (#3731)
A side conversation's task config was moved to a mode that asks, but its session replayed the source task's choices unchanged, so one started from a Full Access / bypass-permissions task ran in that mode and wrote without asking. The replayed choices now drop values that approve everything and turn such a mode (including the agent's own starting mode) to one that asks; setting such a value in a side conversation is refused.
2026-11-16 18:27:22 +08:00
l0ng-ai f19d5dc3f9 fix(build): never wipe an artifact's chosen output folder (#3730)
Artifact layout deleted the whole output folder before copying, so an output folder set to the project folder (or one shared with other output) lost everything in it. A user-chosen folder is no longer cleared: the layout records the files it wrote (with the folder they were for) in the build cache and later removes only recorded files it no longer produces. The IDE's own staging folder is still laid out afresh.
2026-11-16 18:24:28 +08:00
43 змінених файлів з 696 додано та 128 видалено

No files matched your search

+61 -2
Переглянути файл
@@ -2,8 +2,8 @@
//! the agent reports them over ACP.
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentUsage,
AgentCommand, AgentCommandSource, AgentConfigChoice, AgentConfigOption, AgentConfigValue, AgentConfigVia,
AgentCost, AgentLimit, AgentModelPricing, AgentUsage,
};
use serde_json::{Value, json};
@@ -54,6 +54,45 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
}
/// Mode values that ask before anything changes the project, most careful first: Codex's
/// Read Only (its Ask still edits the workspace), Claude Code's default (its Accept Edits
/// doesn't ask), then plan modes.
const ASKING_MODES: [&str; 4] = ["read-only", "default", "plan", "ask"];
/// Moves `config` to settings that ask before anything changes the project (a side
/// conversation): approvals that approve everything ask, and the mode is the most careful one.
pub(crate) fn keep_asking(config: &mut [AgentConfigOption]) {
ask_for_approvals(config);
for option in config.iter_mut().filter(|o| o.category.as_deref() == Some("mode")) {
if let Some(mode) = ASKING_MODES.iter().find(|m| option.values.iter().any(|v| v.value == **m)) {
option.current = Some((*mode).to_owned());
}
}
}
/// The choices that keep a session asking before it changes anything: `wanted` without its
/// mode and approval choices, and the [`keep_asking`] value of each such option of `options`.
pub(crate) fn asking_choices(options: &[AgentConfigOption], wanted: &[AgentConfigChoice]) -> Vec<AgentConfigChoice> {
let guarded = |o: &AgentConfigOption| o.category.as_deref().and_then(bypass_value).is_some();
let mut out: Vec<AgentConfigChoice> =
wanted.iter().filter(|c| !options.iter().any(|o| o.id == c.id && guarded(o))).cloned().collect();
let mut asking = options.to_vec();
keep_asking(&mut asking);
for option in asking.iter().filter(|o| guarded(o)) {
if let Some(value) = &option.current {
out.push(AgentConfigChoice { id: option.id.clone(), value: value.clone() });
}
}
out
}
/// Whether `config` is what [`keep_asking`] makes of it.
pub(crate) fn keeps_asking(config: &[AgentConfigOption]) -> bool {
let mut asking = config.to_vec();
keep_asking(&mut asking);
asking.iter().zip(config).all(|(a, b)| a.current == b.current)
}
/// For an option of `category` that can approve everything, what tells its approving values.
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
match category {
@@ -464,6 +503,26 @@ mod tests {
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
}
#[test]
fn asking_choices_keep_a_side_conversation_from_changing_anything() {
let codex = options_of(&json!({"modes": {"currentModeId": "full-access",
"availableModes": [{"id": "read-only"}, {"id": "ask"}, {"id": "auto"}, {"id": "full-access"}]}}));
let mode = codex[0].id.clone();
let choice = |id: &str, value: &str| AgentConfigChoice { id: id.into(), value: value.into() };
// Codex goes to Read Only (its Ask edits the workspace), whatever the source task chose.
let wanted = asking_choices(&codex, &[choice(&mode, "full-access"), choice("model", "gpt")]);
assert_eq!(wanted, [choice("model", "gpt"), choice(&mode, "read-only")]);
assert_eq!(asking_choices(&codex, &[choice(&mode, "ask")]), [choice(&mode, "read-only")]);
// Claude Code's Accept Edits doesn't ask: default does.
let claude = options_of(&json!({"modes": {"currentModeId": "acceptEdits",
"availableModes": [{"id": "default"}, {"id": "acceptEdits"}, {"id": "plan"}, {"id": "bypassPermissions"}]}}));
assert_eq!(asking_choices(&claude, &[]), [choice(&claude[0].id, "default")]);
assert!(!keeps_asking(&claude));
let mut safe = claude.clone();
keep_asking(&mut safe);
assert!(keeps_asking(&safe));
}
#[test]
fn effort_and_fast_categories_are_inferred_from_ids() {
let mut c = options_of(&json!({
+64 -14
Переглянути файл
@@ -210,20 +210,23 @@ 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>,
) -> 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)
};
) -> 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) };
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));
servers
let mut off = mcp::servers_off(&configured, overrides);
if builtin_off {
off.push(BUILTIN_SERVER.to_owned());
}
McpForSession { servers, off }
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
@@ -891,7 +894,9 @@ impl AgentManager {
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the topic first"))?;
let title = title_of(&prompt);
let mut config = self.merged_config(&spec.id, &req.config);
config::ask_for_approvals(&mut config);
// The source task's choices may change the project without asking; the side conversation asks.
let wanted = config::asking_choices(&config, &req.config);
config::keep_asking(&mut config);
if config::bypass_approvals(&config) {
return Err(IdeError::invalid(
"this agent has no mode that asks before changing things, so it can't run a side conversation",
@@ -933,7 +938,7 @@ impl AgentManager {
task: task.clone(),
session_id: None,
entries: Vec::new(),
wanted: req.config,
wanted,
before,
saved: None,
touched: None,
@@ -1050,6 +1055,15 @@ impl AgentManager {
if !o.values.iter().any(|v| v.value == value) {
return Err(IdeError::invalid(format!("{} has no value {value}", o.name)));
}
if s.ephemeral {
let mut next = s.task.config.clone();
if let Some(n) = next.iter_mut().find(|n| n.id == option) {
n.current = Some(value.clone());
}
if !config::keeps_asking(&next) {
return Err(IdeError::invalid("a side conversation asks before changing anything"));
}
}
o.clone()
};
let previous = target.current.clone();
@@ -1138,7 +1152,11 @@ impl AgentManager {
.peer
.request(
"session/fork",
json!({ "sessionId": live.session, "cwd": cwd_s, "mcpServers": mcp_servers }),
{
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
@@ -2311,7 +2329,8 @@ impl Task {
let mut session = None;
if let (Some(id), true) = (saved, can_load) {
self.replaying.store(true, Ordering::Release);
let params = json!({ "sessionId": &id, "cwd": &cwd_s, "mcpServers": &mcp_servers });
let mut params = session_params(&cwd_s, &mcp_servers);
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;
self.replaying.store(false, Ordering::Release);
@@ -2324,7 +2343,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = json!({ "cwd": &cwd_s, "mcpServers": &mcp_servers });
let params = session_params(&cwd_s, &mcp_servers);
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 },
@@ -2365,7 +2384,10 @@ impl Task {
}
let (mut options, mut wanted) = {
let s = self.state.lock();
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
let options = if known { reported } else { s.task.config.clone() };
// A side conversation asks before anything, whatever mode the agent starts in.
let wanted = if s.ephemeral { config::asking_choices(&options, &s.wanted) } else { s.wanted.clone() };
(options, wanted)
};
config::add_client_options(provider_id, &mut options);
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
@@ -2412,6 +2434,14 @@ impl Task {
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
}
}
// A side conversation never runs in a mode that changes things without asking: when the
// agent refused the switch, it doesn't start.
if self.state.lock().ephemeral && !config::keeps_asking(&options) {
return Err(SessionOpenError {
message: "The agent didn't switch to a mode that asks before changing anything, so the side conversation can't start".into(),
allow_acp_fallback: false,
});
}
let model = model_of(&options).filter(|_| model_options);
self.shared.remember(provider_id, Some(&options), None, model.as_deref());
{
@@ -3257,6 +3287,23 @@ 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
/// 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 } });
}
params
}
fn is_false(b: &bool) -> bool {
!*b
}
@@ -3365,6 +3412,9 @@ 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);
@@ -3379,7 +3429,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": "OpenIDEA", "command": command[0], "args": command[1..], "env": [] })]
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": [] })]
}
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
+61
Переглянути файл
@@ -86,6 +86,29 @@ 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
@@ -1016,6 +1039,44 @@ 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();
+31 -11
Переглянути файл
@@ -170,6 +170,8 @@ struct Session {
id: String,
cwd: PathBuf,
mcp_config: Option<tempfile::TempPath>,
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
mcp_off: Vec<String>,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -344,9 +346,10 @@ impl Shim {
cwd: PathBuf,
start: Start,
pending: bool,
mcp_config: Option<String>,
params: &Value,
) -> Arc<Session> {
let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
let mcp_off = mcp_off(params);
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
Ok(path) => Some(path),
Err(e) => {
tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}");
@@ -356,6 +359,7 @@ impl Shim {
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -411,13 +415,8 @@ impl Shim {
}
"session/new" => {
let id = new_uuid(false);
let session = self.add_session(
&id,
self.cwd_of(&params),
Start::New { id: id.clone() },
false,
mcp_config(&params),
);
let session =
self.add_session(&id, self.cwd_of(&params), Start::New { id: id.clone() }, false, &params);
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
session.announce_commands();
Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() }))
@@ -433,7 +432,7 @@ impl Shim {
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
};
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
let session = self.add_session(id, cwd, start, pending, mcp_config(&params));
let session = self.add_session(id, cwd, start, pending, &params);
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
if method == "session/load" {
session.replay(&chain);
@@ -459,7 +458,7 @@ impl Shim {
(start, st.settings.clone())
};
self.save_pending(&id, Some(&start));
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(&params));
let session = self.add_session(&id, source.cwd.clone(), start, true, &params);
session.st.lock().settings = settings;
let options = session.st.lock().settings.options();
Ok(json!({ "sessionId": id, "configOptions": options }))
@@ -666,6 +665,9 @@ impl Session {
if let Some(config) = &self.mcp_config {
args.extend(["--mcp-config".to_owned(), config.to_string_lossy().into_owned()]);
}
if !self.mcp_off.is_empty() {
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
@@ -1497,6 +1499,24 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
Ok(file.into_temp_path())
}
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
fn mcp_off(params: &Value) -> Vec<String> {
params
.pointer("/_meta/openidea/mcpServersOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(|name| {
let name: String =
name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
format!("mcp__{name}")
})
.collect()
}
/// ACP `mcpServers` as Claude Code's `--mcp-config` JSON (`None` when there are none).
fn mcp_config(params: &Value) -> Option<String> {
let servers = params.get("mcpServers")?.as_array()?;
+7
Переглянути файл
@@ -1243,6 +1243,13 @@ async fn skipped_questions_have_no_answers() {
assert_eq!(cancelled, None);
}
#[test]
fn servers_switched_off_become_disallowed_tools() {
assert!(mcp_off(&json!({})).is_empty());
let off = mcp_off(&json!({ "_meta": { "openidea": { "mcpServersOff": ["github", "my server.v2"] } } }));
assert_eq!(off, ["mcp__github", "mcp__my_server_v2"]);
}
#[test]
fn mcp_servers_become_an_mcp_config() {
assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None);
+11
Переглянути файл
@@ -4238,3 +4238,14 @@ done
);
mgr.shutdown();
}
#[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);
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());
}
+29 -1
Переглянути файл
@@ -487,6 +487,10 @@ impl Action {
}
fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
// A link in the artifact's place is replaced, not written through.
if fs::symlink_metadata(to).is_ok_and(|m| m.file_type().is_symlink()) {
fs::remove_file(to).map_err(|e| IdeError::internal(format!("cannot replace {} ({e})", to.display())))?;
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
@@ -504,6 +508,12 @@ fn copy_tree(from: &Path, to: &Path, written: &mut Vec<PathBuf>, cancel: &Cancel
let Ok(t) = e.file_type() else { continue };
let target = to.join(e.file_name());
if t.is_dir() {
if fs::symlink_metadata(&target).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(IdeError::invalid(format!(
"{} links to another folder; the artifact is not laid out through it",
target.display()
)));
}
copy_tree(&e.path(), &target, written, cancel)?;
} else if t.is_file() {
copy_file(&e.path(), &target)?;
@@ -531,7 +541,14 @@ fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResul
continue;
}
let file = into.join(&rel);
if file.is_file() {
// Never through a link: a folder of the output that now links elsewhere (or a file that
// is a link) leads out of what the layout wrote.
let mut at = into.to_path_buf();
let linked = rel.components().any(|c| {
at.push(c);
fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink())
});
if !linked && file.is_file() {
let _ = fs::remove_file(&file);
let mut dir = file.parent();
while let Some(d) = dir.filter(|d| *d != into && d.starts_with(into)) {
@@ -899,6 +916,17 @@ mod tests {
write(&tmp.path().join("outside.txt"), "x");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(tmp.path().join("outside.txt").is_file());
// Nor through a folder of the output that now links elsewhere.
#[cfg(unix)]
{
write(&project.join("assets/x.txt"), "laid out");
write(&record, &format!("{}\nassets/x.txt", project.display()));
fs::remove_dir_all(project.join("assets")).unwrap();
std::os::unix::fs::symlink(project.join("src"), project.join("assets")).unwrap();
write(&project.join("src/x.txt"), "source");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("src/x.txt").is_file());
}
// Nor does one made for another output folder.
write(&project.join("c.jar"), "mine");
write(&record, "/elsewhere\nc.jar");
+5 -2
Переглянути файл
@@ -167,7 +167,10 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
}
call.confirm(&subject, Some(detail)).await?;
let exchange = ide_http::run(input, &call.cancel).await?;
// Exactly the request the user approved: preparing it again would read the
// environment files again, which may name another destination by now.
let redact_url = prepared.url.clone();
let exchange = ide_http::send(prepared, Some(&path), &call.cancel).await?;
let history = call.project().http_history.clone();
let saved = exchange.clone();
let _ = call.host().blocking(move || history.add(&saved)).await;
@@ -188,7 +191,7 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
"status": response.map(|r| r.status),
"statusText": response.map(|r| r.status_text.clone()),
"totalMs": response.map(|r| r.total_ms).or(exchange.entry.total_ms),
"error": redact_transport_error(exchange.entry.error.clone(), &prepared.url),
"error": redact_transport_error(exchange.entry.error.clone(), &redact_url),
"body": body,
"bodyTruncated": body_truncated,
}))
+11 -1
Переглянути файл
@@ -34,6 +34,16 @@ pub struct RunInput<'a> {
/// variables, missing includes) fail; transport errors are part of the exchange.
pub async fn run(input: RunInput<'_>, cancel: &CancellationToken) -> IdeResult<HttpExchange> {
let request = prepare(&input)?;
send(request, input.file, cancel).await
}
/// Sends an already prepared request (one the user approved as shown); `file` is the
/// request file it came from, for the history.
pub async fn send(
request: PreparedRequest,
file: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<HttpExchange> {
let time_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64() * 1000.0)
@@ -57,7 +67,7 @@ pub async fn run(input: RunInput<'_>, cancel: &CancellationToken) -> IdeResult<H
url: request.url.clone(),
status: response.as_ref().map(|r| r.status),
total_ms: response.as_ref().map(|r| r.total_ms),
file: input.file.map(IpcPath::from),
file: file.map(IpcPath::from),
error,
},
request,
+2 -1
Переглянути файл
@@ -295,9 +295,10 @@ export const lspTheme = EditorView.theme({
padding: "6px 10px",
borderRadius: "var(--radius-popup)",
boxShadow: "var(--shadow-popup)",
maxWidth: "480px",
whiteSpace: "pre-wrap",
},
// The hint is the tooltip element itself: beat the editor theme's `.cm-tooltip` width.
".cm-tooltip.cm-lsp-hint": { maxWidth: "min(480px, 100%)" },
".cm-lsp-hint-error": {
backgroundColor: "var(--bg-feedback-error, color-mix(in srgb, var(--danger) 8%, var(--bg-popup)))",
borderColor: "color-mix(in srgb, var(--danger) 35%, var(--border-popup))",
+20 -24
Переглянути файл
@@ -316,7 +316,7 @@ export async function fillMarkers(
const c = up[i]!;
const self = classOf(c);
if (!self) continue;
const found = resolver ? await superMethodsFrom(resolver, self.name, c.symbol, deps) : [];
const found = resolver ? await superMethodsFrom(resolver, self, c.symbol, deps) : [];
if (!found.length) continue;
const known = supers[i]!;
// Same merge rule as ↓: add the graph's super methods to what the server answered.
@@ -369,41 +369,37 @@ function mergeLocations(first: readonly Location[], more: readonly Location[]):
return [...first, ...more.filter((l) => !first.some((f) => sameDeclarationLine(f, l)))];
}
/** Identifies one class declaration in the inheritance graph. */
/**
* Super methods of `method` declared by a class in `byName`, walking the inheritance
* graph's bases up to a few levels. Empty when no base declares the method.
* Super methods of `method` declared by a base of the class declaration `start`, walking the
* inheritance graph's concrete declarations up to a few levels: a base resolves from the file
* that names it, so an unrelated class of the same name never joins the walk. Empty when no
* base declares the method.
*/
async function superMethodsFrom(
resolver: InheritanceIndex,
start: string,
start: ClassInheritance,
method: string,
deps: MarkerDeps,
depth = 3,
): Promise<{ location: Location; owner: string }[]> {
const bare = method.replace(/\s*[(<].*$/, "");
const seen = new Set<string>([start]);
const key = (c: ClassInheritance) => `${c.path}:${c.line}:${c.col}`;
const seen = new Set<string>([key(start)]);
let level = [start];
for (let d = 0; d < depth && level.length; d++) {
const next: string[] = [];
const next: ClassInheritance[] = [];
const found: { location: Location; owner: string }[] = [];
for (const name of level) {
for (const cls of resolver.byName.get(name) ?? []) {
for (const base of cls.bases) {
if (!seen.add(base)) continue;
// Same rule as the graph: a base the imports name, else a unique one.
const declarations = await resolver.resolve(base, cls.path);
let answered = false;
for (const baseCls of declarations) {
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
const m = methodInOutline(outline, baseCls, bare);
if (m) {
found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
answered = true;
}
}
// Not found in a base that declares nothing: keep walking its own bases.
if (!answered) next.push(base);
for (const cls of level) {
for (const base of cls.bases) {
// Same rule as the graph: a base the imports name, else a unique one.
for (const baseCls of await resolver.resolve(base, cls.path)) {
if (seen.has(key(baseCls))) continue;
seen.add(key(baseCls));
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
const m = methodInOutline(outline, baseCls, bare);
if (m) found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
// Not declared there: keep walking that class's own bases.
else next.push(baseCls);
}
}
}
+20
Переглянути файл
@@ -803,6 +803,26 @@ describe("python inheritance fallback", () => {
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind])).toEqual([[0, "overridden"]]);
});
it("walks up from the class itself, not every class of its name", async () => {
// a.py: `class BaseA` with `foo`, `class Child(BaseA)` with `foo`; b.py the same with BaseB.
const outline = (base: string) => [
item(base, "class", 0, 2, [item("foo", "method", 1, 1)], 6),
item("Child", "class", 3, 5, [item("foo", "method", 4, 4)], 6),
];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "BaseA", bases: [] },
{ path: "/p/a.py", line: 3, col: 6, name: "Child", bases: ["BaseA"] },
{ path: "/p/b.py", line: 0, col: 6, name: "BaseB", bases: [] },
{ path: "/p/b.py", line: 3, col: 6, name: "Child", bases: ["BaseB"] },
];
const { deps } = pythonServer(graph, { "/p/a.py": outline("BaseA"), "/p/b.py": outline("BaseB") });
const candidates = markerCandidates(outline("BaseA"), () => "");
const cache = emptyCache();
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
const up = cachedMarkers(candidates, ALL, cache).find((m) => m.line === 4 && m.kind === "overriding");
expect(up?.targets.map((t) => [t.path, t.range.start.line])).toEqual([["/p/a.py", 1]]);
});
it("resolves an ambiguous base name through the subclass file's imports", async () => {
// Two modules declare `Config`; `from pkg.b import Config` picks one of them, so
// only b.py's Config is marked as subclassed.
+7 -2
Переглянути файл
@@ -1,5 +1,5 @@
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
import { useState } from "react";
import { useEffect, useRef, useState } from "react";
import type { MethodSignature } from "@/bindings";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
import { useTx } from "@/platform/i18n";
@@ -46,7 +46,11 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
const ready = !busy && !problem && signatureChanged(info, signature);
const current = Math.min(selected, rows.length - 1);
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
const running = useRef<AbortController | null>(null);
useEffect(() => () => running.current?.abort(), []);
const close = () => {
running.current?.abort();
useSignatureDialog.setState({ request: null });
request.view.focus();
};
@@ -72,9 +76,10 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
};
const submit = async (preview: boolean) => {
if (!ready) return;
const run = (running.current = new AbortController());
setBusy(true);
setError(null);
const outcome = await changeSignature(request, signature, delegate, preview);
const outcome = await changeSignature(request, signature, delegate, preview, run.signal);
if (useSignatureDialog.getState().request !== request) return;
setBusy(false);
if (outcome.status === "done") close();
+7 -2
Переглянути файл
@@ -1,5 +1,5 @@
/** IDEA's Extract Interface dialog for Java classes (`extractInterface.ts`). */
import { useState } from "react";
import { useEffect, useRef, useState } from "react";
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
import { useTx } from "@/platform/i18n";
import {
@@ -39,7 +39,11 @@ function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest })
const ready = !busy && !problem && !!target;
const allChecked = checked.size === info.members.length;
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
const running = useRef<AbortController | null>(null);
useEffect(() => () => running.current?.abort(), []);
const close = () => {
running.current?.abort();
useExtractInterfaceDialog.setState({ request: null });
request.view.focus();
};
@@ -52,10 +56,11 @@ function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest })
});
const submit = async (preview: boolean) => {
if (!ready) return;
const run = (running.current = new AbortController());
setBusy(true);
setError(null);
const members = info.members.map((m) => m.handleIdentifier).filter((id) => checked.has(id));
const outcome = await extractInterface(request, trimmed, target, members, preview);
const outcome = await extractInterface(request, trimmed, target, members, preview, run.signal);
if (useExtractInterfaceDialog.getState().request !== request) return;
setBusy(false);
if (outcome.status === "done") close();
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { describe, expect, it, vi } from "vitest";
const cancelRequest = vi.fn(async (_id: number) => ({ status: "ok", data: null }));
vi.mock("@/platform/ipc", async (original) => {
const ipc = await original<typeof import("@/platform/ipc")>();
return { ...ipc, commands: { ...ipc.commands, cancelRequest } };
});
const { cancellable } = await import("./signature");
const { isCancelled } = await import("@/platform/ipc");
describe("cancellable refactoring requests", () => {
it("cancels the request in flight when the dialog closes", async () => {
const run = new AbortController();
let sent = -1;
let answer!: (v: string) => void;
const reply = cancellable(run.signal, (id) => {
sent = id;
return new Promise<string>((r) => (answer = r));
});
run.abort();
expect(cancelRequest).toHaveBeenCalledWith(sent);
answer("late");
await expect(reply).resolves.toBe("late");
});
it("leaves a request alone once it answered", async () => {
cancelRequest.mockClear();
const run = new AbortController();
await cancellable(run.signal, async () => "done");
run.abort();
expect(cancelRequest).not.toHaveBeenCalled();
});
it("never sends a request the dialog closed before", async () => {
const run = new AbortController();
run.abort();
const send = vi.fn(async () => "sent");
const err = await cancellable(run.signal, send).catch((e: unknown) => e);
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;
});
});
+4
Переглянути файл
@@ -25,5 +25,9 @@ describe("extract interface", () => {
expect(interfaceProblem("Shape", "Shape", 1)).toBe("Interface name should differ from the class name");
expect(interfaceProblem("HasArea", "Shape", 0)).toBe("Select the members to form the interface");
expect(interfaceProblem("HasArea", "Shape", 2)).toBeNull();
// Java identifiers take letters of any script.
expect(interfaceProblem("处理器", "Shape", 1)).toBeNull();
expect(interfaceProblem("Größe", "Shape", 1)).toBeNull();
expect(interfaceProblem("a-b", "Shape", 1)).toBe("Interface name is not a valid identifier");
});
});
+16 -11
Переглянути файл
@@ -17,7 +17,7 @@ import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { editorService } from "@/workbench/contributions";
import { cannotPerform } from "./catalog";
import { applyEdit, confirmProblems } from "./signature";
import { JAVA_NAME, applyEdit, cancellable, confirmProblems } from "./signature";
/** Languages whose server extracts interfaces through the dialog. */
export const EXTRACT_INTERFACE_LANGUAGES = new Set(["java"]);
@@ -51,8 +51,6 @@ export function memberLabel(m: InterfaceMember): string {
return `${m.name}${params}: ${m.typeName}`;
}
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
/** Why the interface can't be extracted yet, or null. */
export function interfaceProblem(name: string, className: string, members: number): string | null {
if (!name) return "No interface name specified";
@@ -127,6 +125,8 @@ export async function extractInterface(
pkg: PackageChoice,
members: readonly string[],
preview: boolean,
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
signal?: AbortSignal,
): Promise<InterfaceOutcome> {
const { view } = request;
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
@@ -136,27 +136,32 @@ export async function extractInterface(
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
extracted = await lspRequest(() =>
commands.lspExtractInterface(nextRequestId(), request.doc, request.pos, [...members], name, pkg.json, token),
extracted = await cancellable(signal, (id, wanted) =>
lspRequest(
() => commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
wanted,
),
);
if (signal?.aborted) return { status: "stay" };
const fatal = extracted.problems.find((p) => p.severity === "fatal");
if (fatal || (!extracted.edit && !extracted.confirmation))
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
if (!extracted.confirmation) break;
if (!(await confirmProblems(extracted.problems.map((p) => p.message)))) return { status: "stay" };
if (!(await confirmProblems(extracted.problems.map((p) => p.message))) || signal?.aborted)
return { status: "stay" };
confirmation = extracted.confirmation;
}
} catch (e) {
if (isCancelled(e)) return { status: "stay" };
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
return { status: "stay", error: errorText(e) };
}
const edit = extracted.edit!;
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) return { status: "stay", error: "Nothing to change" };
const created = edit.files.find((f) => f.kind === "create")?.path;
const apply = async () => {
await applyEdit(view, edit);
if (created) await editorService().openFile(created, { focus: true });
const apply = async (cancel?: AbortSignal) => {
await applyEdit(view, edit, cancel);
if (created && !cancel?.aborted) await editorService().openFile(created, { focus: true });
};
if (preview) {
openPopup({
@@ -167,7 +172,7 @@ export async function extractInterface(
onConfirm: () => void apply(),
});
} else {
await apply();
await apply(signal);
}
return { status: "done" };
}
+4
Переглянути файл
@@ -23,6 +23,10 @@ describe("change signature", () => {
it("tells what keeps the signature from being submitted", () => {
expect(signatureProblem(info)).toBeNull();
expect(signatureProblem({ ...info, methodName: "2x" })).toBe("Method name is not a valid identifier");
expect(signatureProblem({ ...info, methodName: "处理" })).toBeNull();
expect(
signatureProblem({ ...info, parameters: info.parameters.map((p, i) => ({ ...p, name: `数量${i}` })) }),
).toBeNull();
expect(signatureProblem({ ...info, returnType: " " })).toBe("Return type is not specified");
const dup = { ...info, parameters: [info.parameters[0]!, { ...info.parameters[1]!, name: "a" }] };
expect(signatureProblem(dup)).toBe("Duplicate parameter name");
+39 -9
Переглянути файл
@@ -15,7 +15,7 @@ import { showHint } from "@/editor/lsp/hint";
import { openPopup } from "@/editor/lsp/popupStore";
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { IpcError, commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { ask } from "@/workbench/messages";
import { cannotPerform } from "./catalog";
@@ -50,7 +50,8 @@ export function signatureText(sig: {
return head + throws;
}
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
/** A Java identifier: letters of any script, `$` and `_`, then digits and combining marks too. */
export const JAVA_NAME = /^[\p{L}\p{Nl}\p{Sc}\p{Pc}][\p{L}\p{Nl}\p{Sc}\p{Pc}\p{Nd}\p{Mn}\p{Mc}]*$/u;
/** Why the edited signature can't be submitted yet, or null. */
export function signatureProblem(sig: MethodSignature): string | null {
@@ -128,15 +129,40 @@ export async function startChangeSignature(view: EditorView): Promise<void> {
}
}
export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
export async function applyEdit(view: EditorView, edit: WorkspaceEdit, signal?: AbortSignal) {
try {
await whenAllSynced();
await lspRequest(() => commands.applyWorkspaceEdit(edit));
// The dialog closed while the editors were syncing: nothing is applied.
if (signal?.aborted) return;
await lspRequest(
() => commands.applyWorkspaceEdit(edit),
() => !signal?.aborted,
);
} 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> {
// 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);
} finally {
signal?.removeEventListener("abort", abort);
}
}
export async function confirmProblems(messages: readonly string[]): Promise<boolean> {
const { button } = await ask({
title: "Problems Detected",
@@ -158,6 +184,8 @@ export async function changeSignature(
signature: MethodSignature,
delegate: boolean,
preview: boolean,
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
signal?: AbortSignal,
): Promise<SignatureOutcome> {
const { view } = request;
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
@@ -167,18 +195,20 @@ export async function changeSignature(
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
changed = await lspRequest(() =>
commands.lspChangeSignature(nextRequestId(), request.doc, request.pos, signature, delegate, token),
changed = await cancellable(signal, (id, wanted) =>
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token), wanted),
);
if (signal?.aborted) return { status: "stay" };
const fatal = changed.problems.find((p) => p.severity === "fatal");
if (fatal || (!changed.edit && !changed.confirmation))
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
if (!changed.confirmation) break;
if (!(await confirmProblems(changed.problems.map((p) => p.message)))) return { status: "stay" };
if (!(await confirmProblems(changed.problems.map((p) => p.message))) || signal?.aborted)
return { status: "stay" };
confirmation = changed.confirmation;
}
} catch (e) {
if (isCancelled(e)) return { status: "stay" };
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
return { status: "stay", error: errorText(e) };
}
const edit = changed.edit!;
@@ -193,7 +223,7 @@ export async function changeSignature(
onConfirm: () => void applyEdit(view, edit),
});
} else {
await applyEdit(view, edit);
await applyEdit(view, edit, signal);
}
return { status: "done" };
}
+29
Переглянути файл
@@ -281,3 +281,32 @@ it("confirmLeave asks about running processes before closing", async () => {
expect(asked[0]?.title).toContain("app");
expect(asked[0]?.body).toContain("app");
});
it("counts untitled buffers only when leaving for Welcome, and stays when one isn't saved", async () => {
const service = await import("@/workbench/contributions");
const { confirmLeave } = await import("../closeGuard");
let untitled = [7];
const spy = vi.spyOn(service, "maybeEditorService").mockReturnValue({
dirtyDocumentIds: () => [7],
untitledDirtyDocumentIds: () => untitled,
saveAll: vi.fn(async () => {}),
} as never);
try {
// Another project in place keeps the buffer: nothing to ask.
const kept = deps([]);
await expect(confirmLeave(kept.d, "openidea", true)).resolves.toBe(true);
expect(kept.asked).toHaveLength(0);
// Close Project asks; Save with the Save As cancelled keeps the project open, quietly.
const left = deps([{ button: "save", checked: false }]);
await expect(confirmLeave(left.d, "openidea", false)).resolves.toBe(false);
expect(left.asked[0]?.body).toContain("1");
expect(left.d.saveAll).toHaveBeenCalled();
// Saved: the project closes.
untitled = [];
const saved = deps([{ button: "save", checked: false }]);
left.d.saveAll = vi.fn(async () => {});
await expect(confirmLeave(saved.d, "openidea", false)).resolves.toBe(true);
} finally {
spy.mockRestore();
}
});
+17
Переглянути файл
@@ -115,6 +115,23 @@ describe("native window close", () => {
expect(forget).not.toHaveBeenCalled();
});
it("stays open when an untitled buffer's Save As is cancelled", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
vi.mocked(services.maybeEditorService).mockReturnValue({
forgetSavedTabs: forget,
keepSavedTabs: keep,
dirtyDocumentIds: () => [],
untitledDirtyDocumentIds: () => ["untitled:1"],
cancelClose: vi.fn(),
} as never);
deps.prepareClose = async () => ({ dirty: 1, discard: vi.fn(), commit: vi.fn(), cancel: vi.fn() });
deps.ask = async () => ({ button: "save", checked: false });
const prevented = await close({});
expect(deps.saveAll).toHaveBeenCalledOnce();
expect(prevented).toHaveBeenCalledOnce();
expect(ipc.commands.windowGroupCancelClose).toHaveBeenCalled();
});
it("restores saved tabs if returning to Welcome fails", async () => {
vi.mocked(ipc.commands.closeProject).mockRejectedValue(new Error("close failed"));
const prevented = await close({ closeTabsWithWindow: true });
+2
Переглянути файл
@@ -148,6 +148,8 @@ describe("openProjectInWindow", () => {
expect(wslResolve).toHaveBeenCalledWith(share);
expect(connectRemote).toHaveBeenCalledWith(target, linuxPath);
expect(openProject).not.toHaveBeenCalled();
// The remote window doesn't keep untitled buffers, so the guard counts them.
expect(confirmLeaveProject).toHaveBeenCalledWith(false);
});
it("asks for a new window when this one already has a project", async () => {
+24 -8
Переглянути файл
@@ -12,7 +12,7 @@
* `general.closeWithoutWelcome` is on, in which case it closes. When
* `general.closeTabsWithWindow` is on, that close drops the saved editor tabs.
*/
import { commands, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
import { IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
import { t } from "@/platform/i18n";
import { closeProject, provideLeaveProjectGuard, useProject } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
@@ -171,6 +171,7 @@ const defaultDeps: CloseDeps = {
while ((await liveProcesses()).length > 0) await new Promise((r) => setTimeout(r, 100));
},
onSaveFailed: (e) =>
!isCancelled(e) &&
notifications().notify({
level: "error",
title: t("app.unsaved.saveFailed"),
@@ -224,7 +225,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
const s = useProject.getState();
// The last project or LightEdit window can return to Welcome. Otherwise it closes.
if (returnsToWelcome(ctx.quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings)) {
if (await confirmLeave(deps)) {
if (await confirmLeave(deps, undefined, false)) {
forgot = forgetTabs();
try {
await closeProject();
@@ -249,7 +250,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
dirty: dirtyCount(),
project: s.project?.displayName || s.project?.name || null,
},
deps,
savingUntitled(deps),
);
if (!ok) {
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
@@ -269,6 +270,18 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
}
}
/** Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the window open. */
function savingUntitled(deps: CloseDeps): CloseDeps {
return {
...deps,
saveAll: async () => {
await deps.saveAll();
if (maybeEditorService()?.untitledDirtyDocumentIds?.().length)
throw new IpcError({ kind: "cancelled", message: "Untitled files were not saved" });
},
};
}
/**
* Unsaved changes before this window opens another project in place or closes it. `project` names
* the project in the prompt when this window doesn't hold it (a comparison window).
@@ -276,16 +289,19 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
export async function confirmLeave(
deps: CloseDeps = defaultDeps,
project = (useProject.getState().project?.displayName || useProject.getState().project?.name) ?? null,
keepUntitled = true,
): Promise<boolean> {
if (!(await closeDocumentWindows())) return false;
const confirmTerminate = workflowSettings().run.confirmTerminate;
// Untitled buffers follow the window across projects: they are neither
// counted nor saved by this guard (the window keeps them open).
const untitled = new Set(maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []);
// Untitled buffers follow the window into another project: they are neither counted nor
// saved then (the window keeps them open). Closing to Welcome drops them, so they count.
const untitled = new Set(keepUntitled ? (maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []) : []);
const saveDeps: CloseDeps =
untitled.size > 0
? { ...deps, saveAll: () => Promise.resolve(maybeEditorService()?.saveAll({ skipUntitled: true })) }
: deps;
: keepUntitled
? deps
: savingUntitled(deps);
return decideClose(
{
quitting: false,
@@ -331,7 +347,7 @@ export function installCloseGuard(deps: CloseDeps = defaultDeps): () => void {
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root || s.lightEdit !== prev.lightEdit) dirtyDocs.clear();
}),
provideLeaveProjectGuard(() => confirmLeave(deps)),
provideLeaveProjectGuard((keepUntitled) => confirmLeave(deps, undefined, keepUntitled)),
];
let unlisten: (() => void) | undefined;
let disposed = false;
+3 -3
Переглянути файл
@@ -55,10 +55,10 @@ function openFailed(path: string, e: unknown) {
/** Opens project `path` in this window; true once it is this window's project. */
async function openHere(path: string): Promise<boolean> {
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
if (!(await confirmLeaveProject())) return false;
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
const wsl = await commands.wslResolve(path).catch(() => null);
if (!(await confirmLeaveProject(!wsl))) return false;
try {
// A folder of a WSL distro runs there, not as a network folder.
const wsl = await commands.wslResolve(path).catch(() => null);
if (wsl) await connectRemote(wsl.target, wsl.path);
else await openProject(path);
return true;
+1 -1
Переглянути файл
@@ -79,7 +79,7 @@ export function activate(): () => void {
keywords: ["ssh", "remote", "close"],
when: "projectOpen",
run: async () => {
if (!(await confirmLeaveProject())) return;
if (!(await confirmLeaveProject(false))) return;
try {
await disconnectRemote();
} catch (e) {
+3
Переглянути файл
@@ -71,6 +71,9 @@
display: flex;
flex-direction: column;
}
.body[hidden] {
display: none;
}
/* Space a block takes before its diff loads, so the scrollbar is roughly right. */
.placeholder {
height: 160px;
+11 -9
Переглянути файл
@@ -98,14 +98,15 @@ function Block({
/>
)}
</div>
{!collapsed &&
(near ? (
<div className={styles.body}>
<DiffEditor input={input} fit />
</div>
) : (
<div className={styles.placeholder} />
))}
{/* A collapsed block keeps its loaded diff, hidden: unmounting it would release the
working-tree document and, with autosave off, drop its unsaved edits. */}
{near ? (
<div className={styles.body} hidden={collapsed}>
<DiffEditor input={input} fit />
</div>
) : (
!collapsed && <div className={styles.placeholder} />
)}
</section>
);
}
@@ -199,7 +200,8 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) {
{items.length ? (
items.map((item, index) => (
<Block
key={`${item.path}:${mode}`}
// Keyed by file alone: switching the layout keeps each block's diff and its documents.
key={item.path}
item={item}
index={index}
items={items}
+12
Переглянути файл
@@ -354,3 +354,15 @@
[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;
}
+33 -4
Переглянути файл
@@ -15,7 +15,7 @@ import {
type MouseEvent,
type PointerEvent,
} from "react";
import { tx } from "@/platform/i18n";
import { tx, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, dirname } from "@/platform/project";
@@ -961,6 +961,14 @@ 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,
@@ -976,8 +984,7 @@ 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 between subject and body");
if (c.blankLineAfterSubject && lines.length > 1 && lines[1]!.trim() !== "") out.push(MISSING_BLANK_LINE);
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`);
@@ -1160,7 +1167,29 @@ export function CommitMessageField({
)}
{problems.length > 0 && (
<div className={styles.inspections} role="status">
{problems.join(" · ")}
{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>
))}
</div>
)}
{checkProblems.length > 0 && (
+5
Переглянути файл
@@ -335,6 +335,11 @@ 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 };
+18 -6
Переглянути файл
@@ -83,28 +83,40 @@ describe("the all-in-one diff tab", () => {
expect(screen.getAllByText("src")).toHaveLength(2);
});
it("collapses a file and all files", () => {
it("collapses a file and all files, keeping their diffs (and unsaved edits) loaded", () => {
render(<CombinedDiffTab input={input} />);
const shown = () => screen.queryAllByTestId("block-diff").filter((b) => !b.closest("[hidden]"));
const first = screen.getAllByTestId("block-diff")[0]!;
act(() => {
fireEvent.click(screen.getAllByRole("button", { name: "Collapse File" })[0]!);
});
expect(screen.getAllByTestId("block-diff")).toHaveLength(2);
expect(shown()).toHaveLength(2);
act(() => {
fireEvent.click(screen.getByRole("button", { name: "Collapse All Files" }));
});
expect(screen.queryAllByTestId("block-diff")).toHaveLength(0);
expect(shown()).toHaveLength(0);
act(() => {
fireEvent.click(screen.getByRole("button", { name: "Expand All Files" }));
});
expect(screen.getAllByTestId("block-diff")).toHaveLength(3);
expect(shown()).toHaveLength(3);
// The same diff all along: collapsing never released its document.
expect(screen.getAllByTestId("block-diff")[0]).toBe(first);
});
it("switches every block between side-by-side and unified", () => {
it("switches every block between side-by-side and unified, collapsed ones too, in place", () => {
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" }));
});
expect(screen.getAllByTestId("block-diff").every((b) => b.dataset.mode === "unified")).toBe(true);
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]));
});
it("opens a file's own diff, and goes back to one tab per file", async () => {
+20
Переглянути файл
@@ -59,6 +59,26 @@ describe("staging area inclusion", () => {
expect(plan.stage).toEqual(["/p/src/Unstaged.kt", "/p/src/Gone.kt"]);
});
it("lists and commits a staged addition deleted from disk; the change lists leave it out", () => {
const gone = file("src/New.txt", "added", "deleted");
const status = [gone, unstagedOnly];
expect(isCommitAll(status)).toBe(false);
const plan = planCommit(status, stagingChecks(status));
expect(plan.included.map((f) => f.relPath)).toEqual(["src/New.txt"]);
expect(plan.exclude).toEqual([]);
// Staged shows the addition, Unstaged the deletion.
const tree = buildChangeTree(status, "/p", false, undefined, [], true);
const kinds = (group: string) =>
tree.find((n) => n.group === group)?.children?.flatMap((n) => (n.label === "New.txt" ? [n.kind] : []));
expect(kinds("staged")).toEqual(["added"]);
expect(kinds("unstaged")).toEqual(["deleted"]);
// Without the staging area it is no change against HEAD: listed nowhere, never committed.
expect(buildChangeTree(status, "/p", false).flatMap((n) => n.files.map((f) => f.relPath))).toEqual([
"src/Unstaged.kt",
]);
expect(planCommit(status, new Map([[unstagedOnly.path, "all" as const]])).exclude).toEqual(["/p/src/New.txt"]);
});
it("is not Commit All when only unversioned files changed", () => {
expect(isCommitAll([untracked])).toBe(false);
});
+9 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { BranchInfo } from "@/bindings";
import { messageProblems, wrapAtMargin } from "../CommitView";
import { addBlankLineAfterSubject, messageProblems, wrapAtMargin } from "../CommitView";
import { linkifyIssues } from "../issueLinks";
import {
isProtectedBranch,
@@ -41,6 +41,14 @@ 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 });
+5 -2
Переглянути файл
@@ -4,7 +4,7 @@ import type { FileStatus, Stash } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { groupOf, remainingOverrides, renamedFromPath } from "./changes";
import { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
import { runCommitChecks } from "./commitChecks";
import { contributedCheckProblems, currentPlan, selectionOf } from "./commitSelection";
import { forgetAmendDraft, keepMessageAfterCommit, rememberMessage, useCommit } from "./commitStore";
@@ -54,7 +54,10 @@ export async function commitChanges(): Promise<string | undefined> {
});
return undefined;
}
const candidates = plan.included.map((f) => ({ path: stripSlash(f.path), exists: effectiveKind(f) !== "deleted" }));
const candidates = plan.included.map((f) => ({
path: stripSlash(f.path),
exists: effectiveKind(f) !== "deleted" && !addedThenDeleted(f),
}));
// IDEA: failed checks show in the commit panel; the next Commit ("Commit Anyway") skips them.
const checked = !useCommit.getState().checkProblems.length;
if (checked) {
+18 -4
Переглянути файл
@@ -57,6 +57,14 @@ export function groupOf(fs: FileStatus): GroupId | null {
return "changes";
}
/**
* Added to the index, then deleted from disk: no change against HEAD, so the change list leaves
* it out, but the staging area shows the staged addition (and the deletion, unstaged).
*/
export function addedThenDeleted(fs: Pick<FileStatus, "staged" | "unstaged">): boolean {
return fs.staged === "added" && fs.unstaged === "deleted";
}
export function isPartiallyStaged(fs: FileStatus): boolean {
return (
!!fs.staged &&
@@ -99,7 +107,9 @@ const KIND_ORDER: GroupId[] = ["conflicts", "changes", "unversioned"];
function fileNode(fs: FileStatus, root: string, group: GroupId, flat: boolean, scope: string = group): ChangeNode {
const path = stripSlash(fs.path);
const rel = relTo(root, path);
const kind = effectiveKind(fs) ?? "modified";
// Under Staged / Unstaged, a file without an overall kind (added, then deleted) shows its side's.
const side = group === "staged" ? fs.staged : group === "unstaged" ? fs.unstaged : null;
const kind = effectiveKind(fs) ?? (side === "added" || side === "deleted" ? side : "modified");
const dir = dirName(rel);
return {
key: `${scope}:${path}`,
@@ -259,7 +269,7 @@ export function buildChangeTree(
const repoRoots = byRepo ? repos : [];
const byGroup = new Map<GroupId, FileStatus[]>();
for (const fs of status) {
const g = groupOf(fs);
const g = groupOf(fs) ?? (byStaging && addedThenDeleted(fs) ? "changes" : null);
if (!g) continue;
let list = byGroup.get(g);
if (!list) byGroup.set(g, (list = []));
@@ -400,8 +410,12 @@ export function planCommit(status: readonly FileStatus[], checks: ReadonlyMap<st
const plan: CommitPlan = { stage: [], exclude: [], included: [], partial: [] };
for (const fs of status) {
if (!groupOf(fs)) {
// Listed nowhere, yet staged: added to the index, then deleted from disk. It is no
// change against HEAD, so the commit must not pick up the staged addition.
// Added to the index, then deleted from disk: no change against HEAD, so the commit
// leaves the staged addition out, unless the staging area commits it (checked "staged").
if (addedThenDeleted(fs) && (checks.get(fs.path) ?? checks.get(stripSlash(fs.path))) === "staged") {
plan.included.push(fs);
continue;
}
if (fs.staged && fs.staged !== "conflicted" && fs.unstaged !== "ignored") plan.exclude.push(stripSlash(fs.path));
continue;
}
+3 -1
Переглянути файл
@@ -5,7 +5,7 @@
*/
import type { ChangelistState, FileStatus } from "@/bindings";
import { useWorkflowSettings, workflowSettings } from "@/platform/workflowSettings";
import { groupOf, type CheckState } from "./changes";
import { addedThenDeleted, groupOf, type CheckState } from "./changes";
import { withListDefaults } from "./changelists";
const enabled = (vcs: { git: { stagingArea: boolean }; commit: { nonModal: boolean } }) =>
@@ -31,6 +31,8 @@ export function stagingChecks(status: readonly FileStatus[]): Map<string, CheckS
const all = isCommitAll(status);
const out = new Map<string, CheckState>();
for (const f of status) {
// A staged addition deleted from disk is committed as staged (nothing against HEAD for Commit All).
if (addedThenDeleted(f) && !all) out.set(f.path, "staged");
if (groupOf(f) !== "changes") continue;
out.set(f.path, all ? "all" : staged(f) ? "staged" : "none");
}
+5 -1
Переглянути файл
@@ -2157,5 +2157,9 @@
"Extract Interface from '{name}'": "Extract Interface from '{name}'",
"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"
"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"
}
+5 -1
Переглянути файл
@@ -8540,5 +8540,9 @@
"Extract Interface from '{name}'": "从 '{name}' 提取接口",
"The interface could not be extracted": "无法提取接口",
"Extract Interface is not supported for {name}": "{name} 不支持提取接口",
"Package for new interface": "新接口的软件包"
"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": "添加空行"
}
+11 -5
Переглянути файл
@@ -25,20 +25,26 @@ export const useProject = create<ProjectState>(() => ({
useProject.subscribe((s) => setContext("projectOpening", s.openingPath !== null));
let leaveGuard: (() => Promise<boolean>) | null = null;
/** `keepUntitled`: the window opens another project in place and keeps its untitled buffers. */
type LeaveGuard = (keepUntitled: boolean) => Promise<boolean>;
let leaveGuard: LeaveGuard | null = null;
/** Installs the check run before this window leaves its project (unsaved changes). */
export function provideLeaveProjectGuard(guard: () => Promise<boolean>): () => void {
export function provideLeaveProjectGuard(guard: LeaveGuard): () => void {
leaveGuard = guard;
return () => {
if (leaveGuard === guard) leaveGuard = null;
};
}
/** False when the user chose to stay (another project in place, Close Project). */
export function confirmLeaveProject(): Promise<boolean> {
/**
* False when the user chose to stay (another project in place, Close Project). Untitled buffers
* follow the window only into another local project (`keepUntitled`); leaving for Welcome or a
* remote host asks about them too.
*/
export function confirmLeaveProject(keepUntitled = true): Promise<boolean> {
const s = useProject.getState();
return (s.project || s.lightEdit) && leaveGuard ? leaveGuard() : Promise.resolve(true);
return (s.project || s.lightEdit) && leaveGuard ? leaveGuard(keepUntitled) : Promise.resolve(true);
}
let startupLaunch: Promise<void> | null = null;
+1
Переглянути файл
@@ -105,6 +105,7 @@
display: flex;
gap: 10px;
width: 340px;
max-width: 100%;
/* Never grow past the window: the close button must stay reachable. */
max-height: calc(100vh - 48px);
padding: 14px 34px 14px 14px;
+3
Переглянути файл
@@ -2,6 +2,8 @@
position: fixed;
/* Inside the editor island's bottom-right corner, clear of the right stripe. */
right: 78px;
/* A narrow window narrows the balloons instead of pushing them off its left edge. */
left: 16px;
bottom: calc(var(--h-statusbar) + 16px);
/* Balloons belong to the main window: modal dialogs cover them, like IDEA. */
z-index: calc(var(--z-dialog) - 1);
@@ -12,6 +14,7 @@
pointer-events: none;
}
.balloon {
max-width: 100%;
pointer-events: auto;
animation: slideIn var(--dur) var(--ease);
}
+2 -1
Переглянути файл
@@ -65,7 +65,8 @@ export async function openRemoteProject(
await call(commands.windowOpenRemote(target, path, true));
return true;
}
if (!(await confirmLeaveProject())) return false;
// The remote host's project doesn't take this window's untitled buffers.
if (!(await confirmLeaveProject(false))) return false;
try {
await here();
return true;
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ export function registerShellActions(): () => void {
category: "File",
when: "projectOpen",
run: async () => {
if (!useProject.getState().project || !(await confirmLeaveProject())) return;
if (!useProject.getState().project || !(await confirmLeaveProject(false))) return;
try {
await closeProject();
} catch (e) {