дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-20 00:25:42 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
2bddc99513 |
No files matched your search
@@ -54,45 +54,30 @@ 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());
|
||||
}
|
||||
}
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
/// 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.
|
||||
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 out: Vec<AgentConfigChoice> = wanted
|
||||
.iter()
|
||||
.filter(|c| !options.iter().any(|o| o.id == c.id && approves_everything(o, &c.value)))
|
||||
.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() });
|
||||
}
|
||||
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() });
|
||||
}
|
||||
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 {
|
||||
@@ -504,23 +489,19 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asking_choices_keep_a_side_conversation_from_changing_anything() {
|
||||
fn asking_choices_drop_and_override_values_that_approve_everything() {
|
||||
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.
|
||||
// The source task's Full Access goes; the session's own Full Access is turned to Ask.
|
||||
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));
|
||||
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"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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 change the project without asking; the side conversation asks.
|
||||
// The source task's choices may approve everything; the side conversation asks.
|
||||
let wanted = config::asking_choices(&config, &req.config);
|
||||
config::keep_asking(&mut config);
|
||||
config::ask_for_approvals(&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,14 +1052,8 @@ 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"));
|
||||
}
|
||||
if s.ephemeral && config::approves_everything(o, &value) {
|
||||
return Err(IdeError::invalid("a side conversation asks before changing anything"));
|
||||
}
|
||||
o.clone()
|
||||
};
|
||||
@@ -1149,11 +1143,7 @@ impl AgentManager {
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
{
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
json!({ "sessionId": live.session, "cwd": cwd_s, "mcpServers": mcp_servers }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -2326,8 +2316,7 @@ impl Task {
|
||||
let mut session = None;
|
||||
if let (Some(id), true) = (saved, can_load) {
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
|
||||
params["sessionId"] = json!(&id);
|
||||
let params = json!({ "sessionId": &id, "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
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);
|
||||
@@ -2340,7 +2329,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
|
||||
let params = json!({ "cwd": &cwd_s, "mcpServers": &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 },
|
||||
@@ -2431,14 +2420,6 @@ 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());
|
||||
{
|
||||
@@ -3284,22 +3265,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -170,8 +170,6 @@ 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.
|
||||
@@ -346,10 +344,9 @@ impl Shim {
|
||||
cwd: PathBuf,
|
||||
start: Start,
|
||||
pending: bool,
|
||||
params: &Value,
|
||||
mcp_config: Option<String>,
|
||||
) -> Arc<Session> {
|
||||
let mcp_off = mcp_off(params);
|
||||
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
|
||||
let mcp_config = mcp_config.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}");
|
||||
@@ -359,7 +356,6 @@ 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,
|
||||
@@ -415,8 +411,13 @@ impl Shim {
|
||||
}
|
||||
"session/new" => {
|
||||
let id = new_uuid(false);
|
||||
let session =
|
||||
self.add_session(&id, self.cwd_of(¶ms), Start::New { id: id.clone() }, false, ¶ms);
|
||||
let session = self.add_session(
|
||||
&id,
|
||||
self.cwd_of(¶ms),
|
||||
Start::New { id: id.clone() },
|
||||
false,
|
||||
mcp_config(¶ms),
|
||||
);
|
||||
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() }))
|
||||
@@ -432,7 +433,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, ¶ms);
|
||||
let session = self.add_session(id, cwd, start, pending, mcp_config(¶ms));
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
if method == "session/load" {
|
||||
session.replay(&chain);
|
||||
@@ -458,7 +459,7 @@ impl Shim {
|
||||
(start, st.settings.clone())
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(¶ms));
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -665,9 +666,6 @@ 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() };
|
||||
@@ -1499,24 +1497,6 @@ 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()?;
|
||||
|
||||
@@ -1243,13 +1243,6 @@ 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);
|
||||
|
||||
@@ -4238,17 +4238,3 @@ 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());
|
||||
}
|
||||
@@ -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, c.symbol, deps) : [];
|
||||
const found = resolver ? await superMethodsFrom(resolver, self.name, 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,37 +369,41 @@ 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 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.
|
||||
* 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.
|
||||
*/
|
||||
async function superMethodsFrom(
|
||||
resolver: InheritanceIndex,
|
||||
start: ClassInheritance,
|
||||
start: string,
|
||||
method: string,
|
||||
deps: MarkerDeps,
|
||||
depth = 3,
|
||||
): Promise<{ location: Location; owner: string }[]> {
|
||||
const bare = method.replace(/\s*[(<].*$/, "");
|
||||
const key = (c: ClassInheritance) => `${c.path}:${c.line}:${c.col}`;
|
||||
const seen = new Set<string>([key(start)]);
|
||||
const seen = new Set<string>([start]);
|
||||
let level = [start];
|
||||
for (let d = 0; d < depth && level.length; d++) {
|
||||
const next: ClassInheritance[] = [];
|
||||
const next: string[] = [];
|
||||
const found: { location: Location; owner: string }[] = [];
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -803,26 +803,6 @@ 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.
|
||||
|
||||
@@ -59,26 +59,6 @@ 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);
|
||||
});
|
||||
|
||||
@@ -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 { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { runCommitChecks } from "./commitChecks";
|
||||
import { contributedCheckProblems, currentPlan, selectionOf } from "./commitSelection";
|
||||
import { forgetAmendDraft, keepMessageAfterCommit, rememberMessage, useCommit } from "./commitStore";
|
||||
@@ -54,10 +54,7 @@ export async function commitChanges(): Promise<string | undefined> {
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
const candidates = plan.included.map((f) => ({
|
||||
path: stripSlash(f.path),
|
||||
exists: effectiveKind(f) !== "deleted" && !addedThenDeleted(f),
|
||||
}));
|
||||
const candidates = plan.included.map((f) => ({ path: stripSlash(f.path), exists: effectiveKind(f) !== "deleted" }));
|
||||
// IDEA: failed checks show in the commit panel; the next Commit ("Commit Anyway") skips them.
|
||||
const checked = !useCommit.getState().checkProblems.length;
|
||||
if (checked) {
|
||||
|
||||
@@ -57,14 +57,6 @@ 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 &&
|
||||
@@ -107,9 +99,7 @@ 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);
|
||||
// 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 kind = effectiveKind(fs) ?? "modified";
|
||||
const dir = dirName(rel);
|
||||
return {
|
||||
key: `${scope}:${path}`,
|
||||
@@ -269,7 +259,7 @@ export function buildChangeTree(
|
||||
const repoRoots = byRepo ? repos : [];
|
||||
const byGroup = new Map<GroupId, FileStatus[]>();
|
||||
for (const fs of status) {
|
||||
const g = groupOf(fs) ?? (byStaging && addedThenDeleted(fs) ? "changes" : null);
|
||||
const g = groupOf(fs);
|
||||
if (!g) continue;
|
||||
let list = byGroup.get(g);
|
||||
if (!list) byGroup.set(g, (list = []));
|
||||
@@ -410,12 +400,8 @@ export function planCommit(status: readonly FileStatus[], checks: ReadonlyMap<st
|
||||
const plan: CommitPlan = { stage: [], exclude: [], included: [], partial: [] };
|
||||
for (const fs of status) {
|
||||
if (!groupOf(fs)) {
|
||||
// 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;
|
||||
}
|
||||
// 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.
|
||||
if (fs.staged && fs.staged !== "conflicted" && fs.unstaged !== "ignored") plan.exclude.push(stripSlash(fs.path));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import type { ChangelistState, FileStatus } from "@/bindings";
|
||||
import { useWorkflowSettings, workflowSettings } from "@/platform/workflowSettings";
|
||||
import { addedThenDeleted, groupOf, type CheckState } from "./changes";
|
||||
import { groupOf, type CheckState } from "./changes";
|
||||
import { withListDefaults } from "./changelists";
|
||||
|
||||
const enabled = (vcs: { git: { stagingArea: boolean }; commit: { nonModal: boolean } }) =>
|
||||
@@ -31,8 +31,6 @@ 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");
|
||||
}
|
||||
|
||||
Reference in new issue
Заблокувати користувача