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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 401fe541a1 fix(agents): side conversations run in the agent's most careful mode 2026-11-16 19:09:13 +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
7 змінених файлів з 177 додано та 66 видалено

No files matched your search

+43 -24
Переглянути файл
@@ -54,30 +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)))
}
/// Whether `value` of `option` approves everything without asking.
pub(crate) fn approves_everything(option: &AgentConfigOption, value: &str) -> bool {
option.category.as_deref().and_then(bypass_value).is_some_and(|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 values
/// that approve everything, and an asking value for each option of `options` that approves
/// everything as it stands.
/// 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 mut out: Vec<AgentConfigChoice> = wanted
.iter()
.filter(|c| !options.iter().any(|o| o.id == c.id && approves_everything(o, &c.value)))
.cloned()
.collect();
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();
ask_for_approvals(&mut asking);
for (before, after) in options.iter().zip(&asking) {
let Some(value) = after.current.as_ref().filter(|v| before.current.as_ref() != Some(*v)) else { continue };
out.retain(|c| c.id != after.id);
out.push(AgentConfigChoice { id: after.id.clone(), value: value.clone() });
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 {
@@ -489,19 +504,23 @@ mod tests {
}
#[test]
fn asking_choices_drop_and_override_values_that_approve_everything() {
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() };
// The source task's Full Access goes; the session's own Full Access is turned to Ask.
// 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, "ask")]);
// A mode that already asks is left alone.
let mut auto = codex.clone();
auto[0].current = Some("auto".into());
assert_eq!(asking_choices(&auto, &[choice(&mode, "auto")]), [choice(&mode, "auto")]);
assert!(approves_everything(&codex[0], "full-access") && !approves_everything(&codex[0], "auto"));
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]
+42 -7
Переглянути файл
@@ -891,9 +891,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);
// The source task's choices may approve everything; the side conversation asks.
// The source task's choices may change the project without asking; the side conversation asks.
let wanted = config::asking_choices(&config, &req.config);
config::ask_for_approvals(&mut 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",
@@ -1052,8 +1052,14 @@ 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 && config::approves_everything(o, &value) {
return Err(IdeError::invalid("a side conversation asks before changing anything"));
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()
};
@@ -1143,7 +1149,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, &mcp_overrides);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
@@ -2316,7 +2326,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, &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;
self.replaying.store(false, Ordering::Release);
@@ -2329,7 +2340,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, &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 },
@@ -2420,6 +2431,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());
{
@@ -3265,6 +3284,22 @@ fn turn_starts(entries: &[AgentEntry]) -> Vec<usize> {
.collect()
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// 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, 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
}
fn is_false(b: &bool) -> bool {
!*b
}
+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);
+14
Переглянути файл
@@ -4238,3 +4238,17 @@ done
);
mgr.shutdown();
}
#[test]
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"]));
assert!(session_params("/p", &[], &BTreeMap::new()).get("_meta").is_none());
}
+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.