Compare commits

...
Author SHA1 Message Date
l0ng-ai 21ea02c733 test(lsp): wait for merged injection diagnostics instead of reading them at once
diagnostics_merge_fragments_native_source_and_clear failed about one run in
eight on its own. The SQL server's launch fails with the test launcher and
reports its status from a runtime thread; while that thread drains the
server's event queue, the diagnostics the test emits are delivered by it, so
reading the sink straight after emitting could find no host event yet. The
test now waits (up to 5 s) for the expected host diagnostics at each step.
2026-11-15 09:53:02 +08:00
Deng Liuanddengliu 59fba1a65d refactor(agents): hide redundant Terminal actions for local project-root tasks (#3460)
A task running in the local checkout at the project root opens the same folder as the IDE's own terminal, so its status-bar Terminal button and task-menu Terminal entry are hidden there. Worktree tasks and imported sessions in another folder keep both.

Co-authored-by: dengliu <[email protected]>
2026-11-15 09:45:47 +08:00
Mr0Bread 3bfd3134c0 feat(agents): add a shortcut to cycle reasoning effort (#3454)
Cycle Agent Effort (Option+T / Alt+T in every built-in keymap) cycles the current model's advertised effort levels while focus is in New Task or a writable task conversation, through the existing config setter; the message, caret and focus are kept and Send stays available.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 08:59:01 +08:00
l0ng-ai 573adbf9ab fix(lsp): open dependency classes without sources decompiled by jdtls (#3469)
Go to declaration from Kotlin into a dependency class with no cached sources jar opened the Kotlin LSP's signature-only decompile output. When jdtls is running, the jar: location is resolved to the same class in jdtls' Java model (matching archive and package), decompiled with method bodies and navigable; the Kotlin output stays the fallback.

Refs #3447
2026-11-15 08:53:33 +08:00
Muuandmuutot d2381096fb fix(editor): re-render inheritance markers when files change (#3468)
A Python file added or removed invalidated the cached inheritance graph and markers, but nothing redrew the open documents, so a tooltip kept naming a deleted class. The file-change handler now refreshes the live marker plugins, as a settling server already did.

Co-authored-by: muutot <[email protected]>
2026-11-15 08:46:50 +08:00
Muuandmuutot 2c70c12bf2 fix(analysis): refresh Python inspections when their profile changes (#3466)
The inheritance inspections read the profile when they run, but only an edit, a file change or a settling server ran them, so turning one on or off in Settings looked inert until the file was touched. They now subscribe to profile changes, like the server diagnostics already do.

Co-authored-by: muutot <[email protected]>
2026-11-15 08:46:45 +08:00
l0ng-ai 3ef7fee3e2 fix(menu): keep New first in the File menu, with Untitled File inside it (#3467)
#3427 put New Untitled File above the New submenu, which broke the menu test
that the File menu starts with New (as in IntelliJ IDEA). It now sits in New
next to Scratch File, labelled Untitled File.
2026-11-15 08:45:04 +08:00
Sergei Melnikov deec6d05a0 fix(vcs): show the Push dialog's repositories, unpushed commits, files and diff as IntelliJ IDEA does (#3461)
Push… from one repository's branch menu lists only that repository, and a branch without upstream lists the commits no remote branch has instead of its last 50. Push all lists every repository (up-to-date ones greyed) and checks those with commits. Commits and changed files sit side by side at a fixed height, so selecting a row no longer resizes the dialog and swallows the first checkbox click; the commit details and file tree are split by a draggable divider, and a selected file's diff opens full-width below both panes with a close button and a draggable height.

Co-authored-by: pdasilem <[email protected]>
2026-11-15 08:42:50 +08:00
Muuandmuutot 4a98ce544b fix(editor): resolve an imported Python name to its declaration, not the import (#3462)
basedpyright and pyrefly analyse one root, so for a name declared in an attached dependency project they answer the file's own import statement. When the declaration request's only answer is an import line of this Python file, the name's from-import binding (aliases included) names the module; nav_resolve_module finds it, attached projects included, and the project index's declaration there becomes the target (or the module file when the index has none). A caret on the import itself keeps its existing answer.

Co-authored-by: muutot <[email protected]>
2026-11-15 08:30:14 +08:00
SunZhiQiang 396a8d4b26 feat(agents): temporary side conversations from a selection (#3411)
Selecting text in an agent conversation shows a toolbar with Reply (quotes it into the composer) and Start Side Conversation, which opens a temporary, read-only conversation beside the task. It carries the source conversation (newest first within a 100k-character budget, long tool outputs trimmed) as the context of its first message, stays out of the Agents list and the store, and is discarded with its context when its view closes. Its session is pushed to a mode that asks before changing things, and edit / delete / move / execute requests are denied; an agent without such a mode is refused.

Co-authored-by: panda-student <[email protected]>
2026-11-15 08:27:35 +08:00
l0ng-aiandpanda-student 2889b301b8 fix(ide-workspace): declare GetProcessTimes consistently (#3465)
process.rs and memory.rs declared the same kernel32 GetProcessTimes with different out-pointer types, which Windows clippy rejects (clashing_extern_declarations). Both now read the FILETIMEs as u64.

Co-authored-by: panda-student <[email protected]>
2026-11-15 08:24:15 +08:00
l0ng-ai e26e1d1d7d fix(themes): add the shell command token to the theme template and docs (#3464)
#3458 added --syn-shell-command without setting it in the Harbor Night
scheme (the template new themes start from) or regenerating plugins/themes.md,
so scripts/theme/theme.test.ts failed. Imported IntelliJ schemes map
BASH.EXTERNAL_COMMAND to it.
2026-11-15 08:23:20 +08:00
60 changed files with 2880 additions and 324 deletions

No files matched your search

+238 -31
View File
@@ -305,6 +305,11 @@ struct TaskState {
title_renamed: bool,
/// A turn is running or about to (prompts arriving now are queued).
busy: bool,
/// A temporary side conversation: lives in memory only, never persisted.
ephemeral: bool,
/// The conversation a temporary side conversation starts with, sent to the agent with
/// its first real message; the task's own entries hold only the questions.
ephemeral_context: Option<String>,
/// Background tasks the agent reported as running (`run_in_background` commands and
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
/// waits for the last one. A (re)started process runs nothing yet.
@@ -424,8 +429,14 @@ impl AgentManager {
}
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
/// Ephemeral tasks belonged to the previous page session: a fresh one starts without them.
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
*self.shared.sink.write() = Some(sink);
let stale: Vec<Arc<Task>> = self.tasks.read().values().filter(|t| t.state.lock().ephemeral).cloned().collect();
for task in &stale {
self.drop_in_memory(task);
self.shared.emit(AgentEvent::Removed { id: task.id.clone() });
}
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().task.clone()).collect();
tasks.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
tasks
@@ -655,7 +666,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
};
let file = TaskFile {
let handle = self.register(TaskFile {
task: task.clone(),
session_id: Some(session_id.to_owned()),
entries: Vec::new(),
@@ -665,9 +676,7 @@ impl AgentManager {
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
};
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(task.id.clone(), handle.clone());
});
handle.emit_task();
handle.persist();
Ok(task)
@@ -705,27 +714,8 @@ impl AgentManager {
(root, None, base, commit, before)
}
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = catalog.thought_levels;
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
}
if let Some(model) = model_of(&config)
&& let Some(levels) = levels.remove(&model)
{
config.extend(levels.into_iter().map(|mut o| {
if let Some(choice) =
req.config.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
{
o.current = Some(choice.value.clone());
}
o
}));
}
// The session's settings: what the agent offered last time, with the choices applied.
let config = self.merged_config(&spec.id, &req.config);
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
// Copies of the files the user had changed already, for rolling back the task's changes to them.
@@ -766,7 +756,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
};
let file = TaskFile {
let handle = self.register(TaskFile {
task: task.clone(),
session_id: None,
entries: Vec::new(),
@@ -776,16 +766,116 @@ impl AgentManager {
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
};
let handle = Task::restore(file, self.shared.clone());
});
handle.state.lock().busy = true;
self.tasks.write().insert(task.id.clone(), handle.clone());
handle.emit_task();
handle.persist();
self.shared.runtime.spawn(async move { handle.run(prompt).await });
Ok(task)
}
/// Builds the in-memory handle of a fresh task, registers it and announces it. The
/// caller decides what else its life starts with (a persisted file, a session, a run).
fn register(&self, file: TaskFile) -> Arc<Task> {
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(handle.id.clone(), handle.clone());
handle.emit_task();
handle
}
/// The session's settings: what the agent offered last time, with the request's
/// choices — and the chosen model's thought levels — applied.
fn merged_config(&self, provider: &str, req: &[AgentConfigChoice]) -> Vec<AgentConfigOption> {
let catalog = self.shared.paths.catalogs.cached(&self.shared, provider);
let mut levels = catalog.thought_levels;
let mut config = self.shared.config_for_new_task(catalog.config, provider);
for choice in req {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
}
if let Some(model) = model_of(&config)
&& let Some(levels) = levels.remove(&model)
{
config.extend(levels.into_iter().map(|mut o| {
if let Some(choice) = req.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value)) {
o.current = Some(choice.value.clone());
}
o
}));
}
config
}
/// Creates a temporary side conversation of `source`: an in-memory task that is never
/// persisted, whose session starts with its first real message (`prompt` only names
/// the title). `source`'s conversation rides along as the context of that message.
/// The task is read-only: its settings are pushed to a mode that asks before anything,
/// and requests that would change the project are denied regardless. Fails for an
/// agent that offers no way to ask.
pub async fn create_ephemeral(&self, req: NewAgentTask, source: &str) -> IdeResult<AgentTask> {
let spec = self
.shared
.spec(&req.provider)
.ok_or_else(|| IdeError::invalid(format!("unknown agent {}", req.provider)))?;
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);
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",
));
}
let read_only = !config::bypass_approvals(&config);
let context = context_transcript(&self.task(source)?.state.lock().conversation.main.entries);
let root = self.shared.paths.project_root.clone();
let before = blocking(move || Ok(worktree::snapshot(&root).unwrap_or_default())).await?;
let now = now_ms();
let mut capabilities = self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default();
capabilities.read_only = read_only;
let task = AgentTask {
project_root: Some(IpcPath(self.shared.paths.project_root.clone())),
id: uuid::Uuid::new_v4().simple().to_string(),
title,
provider: spec.id.clone(),
model: model_of(&config),
status: AgentStatus::Ready,
isolation: Isolation::Local,
cwd: IpcPath(self.shared.paths.project_root.clone()),
branch: None,
base: None,
base_commit: None,
error: None,
created_ms: now,
updated_ms: now,
commands: self.shared.known_commands(&spec.id),
usage: None,
queue: Vec::new(),
capabilities,
resets_ms: None,
retry: None,
background: Box::default(),
config,
};
let handle = self.register(TaskFile {
task: task.clone(),
session_id: None,
entries: Vec::new(),
wanted: req.config,
before,
saved: None,
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
});
{
let mut s = handle.state.lock();
s.ephemeral = true;
s.ephemeral_context = Some(context);
}
Ok(task)
}
/// Sends a message. While the agent works it is queued, or with `now` the current turn
/// is cancelled and the message goes next.
pub async fn prompt(&self, id: &str, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
@@ -1205,6 +1295,15 @@ impl AgentManager {
Ok(())
}
/// Removes a task from the manager's table and stops its agent. The disk (its file,
/// its worktree) is the caller's business.
fn drop_in_memory(&self, task: &Arc<Task>) {
task.kill();
self.tasks.write().remove(&task.id);
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{}.json", task.id)));
}
/// Returns an archived task to the active list without starting the agent.
pub fn unarchive(&self, id: &str) -> IdeResult<()> {
let task = self.task(id)?;
@@ -1426,6 +1525,8 @@ impl Task {
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
ephemeral: false,
ephemeral_context: None,
background_tasks: Vec::new(),
}),
live: Mutex::new(None),
@@ -1527,6 +1628,9 @@ impl Task {
if *deleted {
return;
}
if self.state.lock().ephemeral {
return;
}
let bytes = {
let s = self.state.lock();
serde_json::to_vec(&TaskFile {
@@ -1757,7 +1861,20 @@ impl Task {
if !prompt.images.is_empty() && !live.capabilities.images {
return Err(Failure::from("This agent can't read images.".to_owned()));
}
let content = self.content(&live, prompt).await;
// A temporary side conversation's context rides with its first real message; the
// conversation itself records only the question (and whatever comes after).
let prompt = {
let context = self.state.lock().ephemeral_context.take();
match context {
Some(context) => {
let mut owned = prompt.clone();
owned.text = format!("{context}\n\n---\n\n{}", owned.text);
owned
}
None => prompt.clone(),
}
};
let content = self.content(&live, &prompt).await;
let result: Result<Value, RpcError> =
live.peer.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None).await;
match result {
@@ -2211,6 +2328,29 @@ impl Task {
.collect()
})
.unwrap_or_default();
// A side conversation is read-only: deny anything that would change the project
// (its task is deleted when its pane closes, leaving nothing to review or revert).
if self.state.lock().ephemeral
&& params
.pointer("/toolCall/kind")
.or_else(|| params.pointer("/subject/toolCall/kind"))
.and_then(Value::as_str)
.is_some_and(|kind| matches!(kind, "edit" | "delete" | "move" | "execute"))
{
let reject = options.iter().find(|o| o.kind.starts_with("reject")).cloned();
let _ = self.push_entry(AgentEntry::Permission {
id,
title,
command: None,
options,
questions: Vec::new(),
chosen: Some("Denied: side conversations are read-only".to_owned()),
});
return match reject {
Some(option) => json!({ "outcome": { "outcome": "selected", "optionId": option.id } }),
None => json!({ "outcome": { "outcome": "cancelled" } }),
};
}
let asked: Vec<String> = questions
.iter()
.map(|question| question.answer_key.clone().unwrap_or_else(|| question.question.clone()))
@@ -2408,6 +2548,72 @@ fn clean(mut prompt: AgentPrompt) -> Option<AgentPrompt> {
(!prompt.text.is_empty() || !prompt.images.is_empty() || !prompt.files.is_empty()).then_some(prompt)
}
/// The character budget of a side conversation's context: the newest entries win, the
/// oldest are dropped first. Leaves room for the question and the agent's answer.
const CONTEXT_BUDGET: usize = 100_000;
/// A long tool output trimmed to its first and last few lines, with the elided middle noted.
fn trimmed_output(output: &str) -> String {
const KEPT: usize = 4;
let lines: Vec<&str> = output.lines().collect();
if lines.len() <= KEPT * 2 + 1 {
return output.to_owned();
}
let omitted = lines.len() - KEPT * 2;
let mut out = lines[..KEPT].join("\n");
out.push_str(&format!("\n… {omitted} lines omitted …\n"));
out.push_str(&lines[lines.len() - KEPT..].join("\n"));
out
}
fn context_entry(e: &AgentEntry) -> Option<String> {
match e {
AgentEntry::User { text, .. } => Some(format!("User: {text}")),
AgentEntry::Agent { text, .. } if !text.trim().is_empty() => Some(format!("Agent: {text}")),
AgentEntry::Thought { text, .. } if !text.trim().is_empty() => Some(format!("Thought: {text}")),
AgentEntry::Tool { title, output, .. } => match output.as_deref() {
Some(output) if !output.trim().is_empty() => Some(format!("Tool: {title}\n{}", trimmed_output(output))),
_ => Some(format!("Tool: {title}")),
},
AgentEntry::Error { message, .. } => Some(format!("Error: {message}")),
_ => None,
}
}
/// The conversation as the context a temporary side conversation starts with: what was
/// said, what was done (tool calls with trimmed output), errors and the agent's reasoning,
/// oldest first, within [`CONTEXT_BUDGET`].
fn context_transcript(entries: &[AgentEntry]) -> String {
// Newest wins: walk back until the budget is spent, dropping the oldest entries first.
let mut lines: Vec<String> = Vec::new();
let mut used = 0usize;
for e in entries.iter().rev() {
let Some(line) = context_entry(e) else { continue };
if used + line.len() > CONTEXT_BUDGET {
if lines.is_empty() {
// Even the newest entry alone exceeds the budget: keep its head.
lines.push(line.chars().take(CONTEXT_BUDGET).collect());
}
break;
}
used += line.len();
lines.push(line);
}
lines.reverse();
let dropped = entries.iter().rev().filter_map(context_entry).count() - lines.len();
let mut context = String::from(
"You are answering a side question in a temporary conversation. The conversation so far is below, \
for context only; answer the new question after the marker, and do not continue the main task \
unless asked.\n\n<conversation>\n",
);
if dropped > 0 {
context.push_str(&format!("(The {dropped} oldest entries are omitted.)\n\n"));
}
context.push_str(&lines.join("\n\n"));
context.push_str("\n</conversation>");
context
}
fn permission_title(params: &Value) -> String {
let call = &params["toolCall"];
let title = call.get("title").and_then(Value::as_str).filter(|t| !t.is_empty());
@@ -2608,6 +2814,7 @@ fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
rollback: meta("/openidea/rollback"),
steer: meta("/openidea/steer"),
background_tasks: meta("/openidea/backgroundTasks"),
read_only: false,
};
(capabilities, init.prompt("embeddedContext"))
}
+3
View File
@@ -36,6 +36,9 @@ pub struct AgentCapabilities {
pub steer: bool,
/// It reports its background tasks and stops them one by one.
pub background_tasks: bool,
/// The task runs read-only: it asks before anything, and requests that would change
/// the project are denied (a temporary side conversation).
pub read_only: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+189
View File
@@ -3227,3 +3227,192 @@ async fn security_policy_never_auto_approves_a_request_that_only_reads_like_a_co
"{entries:?}"
);
}
/// A temporary side conversation is created ready, without starting its session and
/// without writing anything to the store; a fresh subscriber (a reloaded page) sweeps
/// it, and deleting it just drops it from memory.
#[tokio::test(flavor = "multi_thread")]
async fn ephemeral_tasks_stay_in_memory_only() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let source = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("hello"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &source.id, AgentStatus::NeedsInput).await;
let calls_before = agent.calls.lock().len();
let task = mgr
.create_ephemeral(
NewAgentTask {
project_root: None,
prompt: text("What changed in this file?"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
},
&source.id,
)
.await
.unwrap();
// Registering it starts nothing: the session waits for its first real message.
assert_eq!(agent.calls.lock().len(), calls_before);
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
// Its first message starts the session like any task's, and still saves nothing: the
// conversation records the question, not the context that rode along to the agent.
// The fake agent's turn asks to change something, which a side conversation denies by
// itself, so the turn ends without waiting for the user.
mgr.prompt(&task.id, text("Why?"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
let question = entries.iter().find_map(|e| match e {
AgentEntry::User { text, .. } => Some(text.clone()),
_ => None,
});
assert_eq!(question.as_deref(), Some("Why?"));
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c.contains("read-only"))),
"its `cargo test` request was denied: {entries:?}"
);
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
// A fresh subscriber (a reloaded page) sweeps it: it never reaches the task list.
let events: Arc<Mutex<Vec<AgentEvent>>> = Arc::new(Mutex::new(Vec::new()));
let sink_events = events.clone();
let tasks = mgr.subscribe(Arc::new(move |e| sink_events.lock().push(e)));
assert!(!tasks.iter().any(|t| t.id == task.id));
assert!(mgr.task(&task.id).is_err());
assert!(events.lock().iter().any(|e| matches!(e, AgentEvent::Removed { id } if *id == task.id)));
mgr.shutdown();
}
/// A side conversation's context stays within its budget: long tool outputs are cut to
/// their head and tail, and entries that no longer fit are dropped oldest first.
#[test]
fn side_conversation_context_is_bounded() {
let long_output = (0..400).map(|i| format!("line {i}")).collect::<Vec<_>>().join(
"
",
);
// Each reply alone is well inside the budget; together they are past it.
let reply = |n: usize| AgentEntry::Agent { text: format!("reply {n} {}", "x".repeat(30_000)) };
let entries = vec![
AgentEntry::User {
text: "oldest question".into(),
attachments: vec![],
images: vec![],
sent_ms: None,
done_ms: None,
steered: false,
},
reply(1),
reply(2),
reply(3),
reply(4),
AgentEntry::Tool {
id: "t1".into(),
title: "grep".into(),
kind: "search".into(),
status: AgentToolStatus::Completed,
locations: vec![],
output: Some(long_output),
diffs: vec![],
},
AgentEntry::User {
text: "newest question".into(),
attachments: vec![],
images: vec![],
sent_ms: None,
done_ms: None,
steered: false,
},
];
let transcript = context_transcript(&entries);
assert!(transcript.contains("newest question"), "the newest entry is always kept");
assert!(transcript.contains("lines omitted"), "a long tool output is trimmed");
assert!(transcript.contains("line 0") && transcript.contains("line 399"), "its head and tail stay");
assert!(!transcript.contains("oldest question"), "entries past the budget are dropped oldest first");
assert!(transcript.contains("oldest entries are omitted"));
}
/// An ephemeral task denies a permission request that would change the project.
#[tokio::test(flavor = "multi_thread")]
async fn ephemeral_tasks_deny_write_permissions() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let source = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Something with a conversation to reuse"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &source.id, AgentStatus::NeedsInput).await;
let pending = mgr
.entries(&source.id, None)
.unwrap()
.iter()
.find_map(|e| match e {
AgentEntry::Permission { id, chosen: None, .. } => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("no pending permission request"));
mgr.respond(&source.id, pending, Some("no".into())).unwrap();
wait_for(&mgr, &source.id, AgentStatus::Ready).await;
let task = mgr
.create_ephemeral(
NewAgentTask {
project_root: None,
prompt: text("What changed in this file?"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
},
&source.id,
)
.await
.unwrap();
assert!(mgr.task(&task.id).unwrap().state.lock().task.capabilities.read_only);
let answer = mgr
.task(&task.id)
.unwrap()
.ask_permission(&json!({
"sessionId": "c1",
"toolCall": {"toolCallId": "c1-t2", "title": "Edit main.rs", "kind": "edit"},
"options": [
{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
{"optionId": "no", "name": "Reject", "kind": "reject_once"}
]
}))
.pointer("/outcome/optionId")
.and_then(Value::as_str)
.unwrap_or("none")
.to_owned();
assert_eq!(answer, "no", "the write request is denied");
let entries = mgr.entries(&task.id, None).unwrap();
assert!(
entries
.iter()
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(chosen), .. } if chosen.contains("read-only"))),
"{entries:?}"
);
mgr.shutdown();
}
+12
View File
@@ -261,6 +261,18 @@ pub async fn fork(host: &Host, window: &str, task: String, turns: Option<u32>) -
host.project(window)?.agents.fork(&task, turns).await
}
/// Creates a temporary side conversation of `source`: lives in memory only, never
/// persisted, not listed.
pub async fn create_ephemeral(
host: &Host,
window: &str,
request: NewAgentTask,
source: String,
) -> IdeResult<AgentTask> {
host.require_trust(window)?;
host.project(window)?.agents.create_ephemeral(request, &source).await
}
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
pub async fn rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
host.require_trust(window)?;
+18 -16
View File
@@ -715,33 +715,35 @@ mod tests {
server.set_diagnostics(a.path.clone(), vec![diag(2, 5, "a"), diag(0, 1, "outside"), diag(4, 6, "crosses")]);
let items = server.set_diagnostics(b.path.clone(), vec![diag(7, 10, "b")]);
mgr.emit_diagnostics(&server, b.path, items, Encoding::Utf16);
let latest = || {
events
.lock()
.iter()
.rev()
.find_map(|e| match e {
// The SQL server's failed launch reports its status from a runtime thread; while that
// thread drains the server's event queue, events emitted here reach the sink from it.
let latest = |want: &dyn Fn(&[ide_core::Diagnostic]) -> bool| {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
let items = events.lock().iter().rev().find_map(|e| match e {
ide_core::IdeEvent::Diagnostics { path: p, source, items }
if p.0 == path && source == &server.name =>
{
Some(items.clone())
}
_ => None,
})
.unwrap()
});
match items {
Some(items) if want(&items) => return items,
_ if std::time::Instant::now() > deadline => panic!("latest host diagnostics: {items:?}"),
_ => std::thread::sleep(Duration::from_millis(5)),
}
}
};
assert_eq!(latest().iter().map(|d| d.message.as_str()).collect::<Vec<_>>().len(), 3);
let messages = |items: &[ide_core::Diagnostic]| items.iter().map(|d| d.message.clone()).collect::<Vec<_>>();
let merged = latest(&|items| items.len() == 3);
assert!(
latest()
.iter()
.filter(|d| d.message != "native")
.all(|d| d.source.as_deref() == Some(server.name.as_str()))
merged.iter().filter(|d| d.message != "native").all(|d| d.source.as_deref() == Some(server.name.as_str()))
);
mgr.set_injections(host, 1, vec![injection(7, 10)]);
assert_eq!(latest().iter().map(|d| d.message.clone()).collect::<Vec<_>>(), ["native", "b"]);
latest(&|items| messages(items) == ["native", "b"]);
mgr.set_injections(host, 1, vec![]);
assert_eq!(latest()[0].message, "native");
assert_eq!(latest().len(), 1);
latest(&|items| messages(items) == ["native"]);
assert!(
events.lock().iter().all(|e| !matches!(e, ide_core::IdeEvent::Diagnostics { path, .. } if reserved(path)))
);
+33
View File
@@ -1767,6 +1767,38 @@ impl LspManager {
}
}
/// Library classes in `jar:` targets that have no cached sources jar: the official Kotlin
/// LSP decompiles them to signatures only (`/* compiled code */`). When jdtls is running,
/// the same class from its Java model instead, decompiled with method bodies and navigable.
/// Its documents belong to jdtls ([`Self::virtual_document`] records it).
async fn jdt_library_classes(&self, snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
let jar_class = |l: &Location| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"));
if !locs.iter().any(jar_class)
|| !self.servers.lock().iter().any(|s| s.name == jdtls::SERVER && s.running().is_some())
{
return locs;
}
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
let mut out = Vec::with_capacity(locs.len());
for loc in locs {
let entry = loc.uri.as_deref().filter(|_| jar_class(&loc)).and_then(library_source::parse);
let Some(entry) = entry else {
out.push(loc);
continue;
};
let Ok(uri) = self.java_class_file(Path::new(""), Some((entry.jar, entry.entry))).await else {
out.push(loc);
continue;
};
let range = match (&name, self.virtual_document(&uri).await) {
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
_ => Range::default(),
};
out.push(Location { path: uri.clone().into(), range, uri: Some(uri) });
}
out
}
async fn goto_in(
&self,
snap: &DocSnap,
@@ -1808,6 +1840,7 @@ impl LspManager {
let locs = library_sources(snap, &self.project_root, pos, locs).await;
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
self.note_arduino_sources(&t.server, &locs);
let locs = self.jdt_library_classes(snap, pos, locs).await;
let locs = merge_locations(first, locs);
if !locs.is_empty() {
return Ok(locs);
+96 -28
View File
@@ -296,37 +296,48 @@ fn harness_configured(
servers: &[(&str, Value)],
adjust: impl Fn(&mut LanguageServerConfig),
) -> Harness {
harness_languages(&[(lang_id, ext, servers)], adjust)
}
/// A language as `(id, extension, servers)`.
type MockLanguage<'a> = (&'a str, &'a str, &'a [(&'a str, Value)]);
/// Several languages; documents open as the first.
fn harness_languages(languages: &[MockLanguage<'_>], adjust: impl Fn(&mut LanguageServerConfig)) -> Harness {
let dir = tempfile::tempdir().unwrap();
// Edits and references report canonical paths.
let root = dunce::canonicalize(dir.path()).unwrap();
let lang = LanguageConfig {
id: LanguageId::new(lang_id),
name: "Mock".into(),
extensions: vec![ext.into()],
filenames: vec![],
first_line: None,
line_comment: None,
block_comment: None,
indent: None,
ui_mode: None,
framework_ui_modes: Vec::new(),
framework_files: Vec::new(),
formatter: None,
scratch_template: None,
tree_sitter: None,
language_servers: servers
.iter()
.map(|(n, _)| {
let mut cfg = server_cfg(n);
adjust(&mut cfg);
cfg
})
.collect(),
debugger: None,
};
let registry = Arc::new(LanguageRegistry::from_configs(vec![lang]));
let configs = languages
.iter()
.map(|(lang_id, ext, servers)| LanguageConfig {
id: LanguageId::new(*lang_id),
name: "Mock".into(),
extensions: vec![ext.to_string()],
filenames: vec![],
first_line: None,
line_comment: None,
block_comment: None,
indent: None,
ui_mode: None,
framework_ui_modes: Vec::new(),
framework_files: Vec::new(),
formatter: None,
scratch_template: None,
tree_sitter: None,
language_servers: servers
.iter()
.map(|(n, _)| {
let mut cfg = server_cfg(n);
adjust(&mut cfg);
cfg
})
.collect(),
debugger: None,
})
.collect();
let registry = Arc::new(LanguageRegistry::from_configs(configs));
let launcher = Arc::new(MockLauncher::default());
for (name, caps) in servers {
for (name, caps) in languages.iter().flat_map(|(_, _, servers)| servers.iter()) {
*launcher.state(name).caps.lock() = caps.clone();
}
let events = Arc::new(Mutex::new(Vec::new()));
@@ -335,7 +346,7 @@ fn harness_configured(
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let mgr = LspManager::with_launcher(root.clone(), registry, sink, launcher.clone());
Harness { _dir: dir, root, mgr, launcher, events, lang: LanguageId::new(lang_id) }
Harness { _dir: dir, root, mgr, launcher, events, lang: LanguageId::new(languages[0].0) }
}
impl Harness {
@@ -2946,6 +2957,63 @@ async fn library_classes_in_jars_open_as_their_source_or_decompiled() {
assert_eq!(asked[0], json!({ "command": "decompile", "arguments": [thing] }));
}
#[tokio::test(flavor = "multi_thread")]
async fn library_classes_without_sources_open_decompiled_by_a_running_jdtls() {
use std::io::Write;
let repo = tempfile::tempdir().unwrap();
let jar = dunce::canonicalize(repo.path()).unwrap().join("acme/lib/1.0/lib-1.0.jar");
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(&jar).unwrap());
zip.start_file("acme/Thing.class", zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(b"\0").unwrap();
zip.finish().unwrap();
let class = format!("jar://{}!/acme/Thing.class", uri_of(&jar).trim_start_matches("file://"));
let escaped = jar.to_string_lossy().replace('/', "%5C/");
let jdt = format!("jdt://contents/lib-1.0.jar/acme/Thing.class?=app/{escaped}%3Cacme%28Thing.class");
let decompiled =
"package acme;\n\npublic class Thing {\n public void run() {\n System.out.println();\n }\n}\n";
let mut kotlin = incremental_caps();
kotlin["executeCommandProvider"] = json!({ "commands": ["decompile"] });
let mut java = incremental_caps();
java["workspaceSymbolProvider"] = json!(true);
let h =
harness_languages(&[("kotlin", "kt", &[("kotlin-lsp", kotlin)]), ("java", "java", &[("jdtls", java)])], |_| {});
let (doc, _) = h.open("Main.kt", "val thing = Thing()\n");
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
let k = h.launcher.state("kotlin-lsp");
k.respond(
"textDocument/definition",
json!({ "uri": class, "range": {"start":{"line":0,"character":6},"end":{"line":0,"character":11}} }),
);
let r = json!({"start":{"line":2,"character":13},"end":{"line":2,"character":18}});
// jdtls not running: the Kotlin server's own target and decompiler.
let defs = h.mgr.goto(doc, Pos::new(0, 14), GotoKind::Definition).await.unwrap();
assert_eq!(defs[0].uri.as_deref(), Some(class.as_str()));
let path = h.root.join("Sample.java");
std::fs::write(&path, "class Sample {}").unwrap();
h.mgr.did_open(DocId::next(), &path, &LanguageId::new("java"), 1, "class Sample {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let j = h.launcher.state("jdtls");
j.respond(
"workspace/symbol",
json!([{ "name": "Thing", "kind": 5, "containerName": "acme", "location": { "uri": jdt, "range": r } }]),
);
j.respond("java/classFileContents", json!(decompiled));
let defs = h.mgr.goto(doc, Pos::new(0, 14), GotoKind::Definition).await.unwrap();
assert_eq!(
defs,
vec![ide_core::Location { path: jdt.clone().into(), range: rng(2, 13, 2, 18), uri: Some(jdt.clone()) }]
);
assert_eq!(j.requested("workspace/symbol")[0]["query"], "acme.Thing");
let vd = h.mgr.virtual_document(&jdt).await.unwrap();
assert_eq!(vd.text, decompiled);
assert!(k.requested("workspace/executeCommand").is_empty(), "the Kotlin stub is not asked for");
}
#[tokio::test(flavor = "multi_thread")]
async fn alternative_java_server_uses_lsp_without_jdt_commands() {
let h = harness_for("java", "java", &[("kmp-lsp", incremental_caps())], &[]);
+7 -13
View File
@@ -246,30 +246,24 @@ mod imp {
}
pub fn process_start() -> Option<std::time::SystemTime> {
#[repr(C)]
#[derive(Default)]
struct FileTime {
low: u32,
high: u32,
}
#[link(name = "kernel32")]
unsafe extern "system" {
// The same signature `memory.rs` declares: FILETIMEs read as packed u64s.
fn GetProcessTimes(
process: *mut std::ffi::c_void,
creation: *mut FileTime,
exit: *mut FileTime,
kernel: *mut FileTime,
user: *mut FileTime,
creation: *mut u64,
exit: *mut u64,
kernel: *mut u64,
user: *mut u64,
) -> i32;
}
let (mut c, mut e, mut k, mut u) = Default::default();
// SAFETY: all out-pointers are valid FILETIME structs.
// SAFETY: all out-pointers are valid 64-bit FILETIME slots.
let ok = unsafe { GetProcessTimes(GetCurrentProcess(), &mut c, &mut e, &mut k, &mut u) };
if ok == 0 {
return None;
}
let c: FileTime = c;
let ticks = ((c.high as u64) << 32) | c.low as u64; // 100 ns since 1601-01-01
let ticks = c; // 100 ns since 1601-01-01
let unix_100ns = ticks.checked_sub(116_444_736_000_000_000)?;
Some(std::time::UNIX_EPOCH + std::time::Duration::from_nanos(unix_100ns * 100))
}
+4
View File
@@ -76,6 +76,10 @@ On your own messages you can **Edit** (the messages after it are replaced; files
The shortcut does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. Outside the task conversation, the keys keep their usual editor or terminal behavior. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
**Cycle Agent Effort** defaults to `Option+T` on macOS and `Alt+T` on Windows / Linux in every built-in keymap. With focus inside New Task or your own writable task conversation, in an editor tab or the tool window, it cycles the current model's provider-advertised effort levels in order, wrapping from the last to the first. It preserves your message, selection, caret and focus, and sends nothing. Like the effort control, it changes the provider configuration; it does not promise to change a turn already running.
The shortcut is unavailable when effort is unsupported or has only one level, for archived tasks or subagent conversations, and while a popup or dialog is open. It does not take focus from the code editor or terminal. Change or remove it under **Settings › Keymap › Agents › Cycle Agent Effort**.
Right-click a link and choose **Copy Link Address** to copy its URL; **Copy** copies the selected text.
### Permissions
+4
View File
@@ -76,6 +76,10 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。在任务对话之外,按键保留原有的编辑器或终端行为。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
所有内置按键映射中,**循环切换 Agent 思考强度** 的默认快捷键都是 macOS 上的 `Option+T`、Windows / Linux 上的 `Alt+T`。焦点位于“新建任务”或你自己的可输入任务对话中时,无论显示在编辑器标签页还是工具窗口中,它都会按提供商声明的顺序切换当前模型支持的思考强度,从最后一级循环回第一级。它会保留消息、选区、光标和焦点,不发送任何内容。与思考强度控件一样,它修改的是提供商配置,不保证改变已经运行中的轮次。
不支持思考强度或仅支持一级时,以及已归档任务、子 agent 对话或打开弹出窗口、对话框时,此快捷键不可用。它不会从代码编辑器或终端抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 循环切换 Agent 思考强度**。
右键点击链接并选择 **复制链接地址** 可复制它的 URL;**复制** 复制选中的文字。
### 权限
+533
View File
@@ -0,0 +1,533 @@
import type { Locator, Page } from "@playwright/test";
import type { AgentConfigOption, AgentEntry, AgentProvider, AgentTask } from "../src/bindings";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
type Placement = "editor" | "toolWindow";
const effortId = "deliberation-budget";
const modelId = "cortex";
const draft = "draft keep this unsent";
const rebound = "Control+Meta+Shift+J";
const option = (id: string, category: string, values: [string, string][], current: string): AgentConfigOption => ({
id,
category,
name: category === "model" ? "Model" : "Reasoning",
description: null,
current,
via: "option",
values: values.map(([value, name]) => ({ value, name, description: null })),
});
const models = option(
modelId,
"model",
[
["atlas", "Atlas"],
["swift", "Swift"],
["plain", "Plain"],
["solo", "Solo"],
],
"atlas",
);
const atlas = option(
effortId,
"thought_level",
[
["budget-7", "Gentle"],
["budget-23", "Balanced"],
["budget-91", "Deep"],
],
"budget-7",
);
const swift = option(
effortId,
"thought_level",
[
["quick", "Quick"],
["thorough", "Thorough"],
],
"quick",
);
const solo = option(effortId, "thought_level", [["only", "Only"]], "only");
const provider: AgentProvider = {
id: "acceptance-provider",
name: "Acceptance Provider",
command: "acceptance",
program: "acceptance",
args: [],
defaultProgram: null,
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "custom" },
config: [models],
thoughtLevels: { atlas: [atlas], swift: [swift], plain: [], solo: [solo] },
};
const firstTask: AgentTask = {
id: "effort-first",
title: "First effort task",
provider: provider.id,
status: "ready",
isolation: "local",
model: "atlas",
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [models, atlas],
commands: [],
usage: null,
queue: [],
};
const secondTask: AgentTask = { ...firstTask, id: "effort-second", title: "Second effort task" };
const subagent: AgentEntry = {
type: "subagent",
id: "effort-child",
title: "Inspect the project",
description: null,
status: "done",
error: null,
prompt: null,
reply: null,
tools: 0,
activity: null,
startedMs: null,
endedMs: null,
cancellable: false,
};
async function seed(
page: Page,
placement: Placement,
surface: "new" | "task" = "task",
model = "atlas",
status: AgentTask["status"] = "ready",
) {
await stubDesktop(page);
await page.evaluate(
async ({ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId }) => {
// In-memory sample tasks belong to Vite's browser realm. Static Node imports create a different store and cannot seed the workbench.
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
const configFor = (model: string) => [
{ ...provider.config[0]!, current: model },
...(provider.thoughtLevels?.[model] ?? []),
];
const tasks = new Map(
[firstTask, secondTask].map((task) => [task.id, { ...task, status, model, config: configFor(model) }]),
);
const entries: AgentEntry[] = Array.from({ length: 24 }, (_, turn): AgentEntry[] => [
{ type: "user", text: `Request ${turn}`, attachments: [] },
{ type: "agent", text: `Reply ${turn}` },
]).flat();
let channel: unknown;
const handlers = window.__ipc.handlers;
// Settings writes must update the browser's project store, just as the desktop response does.
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(projectPath);
handlers.settings_set = ({ key, value }) => {
const next: Record<string, unknown> = structuredClone(useProject.getState().settings ?? {});
const path = String(key).split(".");
let node = next;
for (const segment of path.slice(0, -1)) {
node[segment] ??= {};
node = node[segment] as Record<string, unknown>;
}
const last = path.at(-1)!;
const parsed: unknown = JSON.parse(String(value));
if (parsed === null) delete node[last];
else node[last] = parsed;
useProject.setState({ settings: next });
return next;
};
handlers.agent_subscribe = ({ onEvent }) => {
channel = onEvent;
return [...tasks.values()];
};
handlers.agent_providers = () => [provider];
handlers.agent_refresh_models = () => ({
provider: provider.id,
config: provider.config,
thoughtLevels: provider.thoughtLevels,
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
});
handlers.agent_probe = () => null;
handlers.agent_commands = () => [];
handlers.agent_entries = ({ subagent: child }) =>
child ? [{ type: "agent", text: "Subagent findings" }] : [...entries, subagent];
handlers.agent_changes = () => [];
handlers.agent_grouped_changes = () => ({ uncommitted: [], commits: [] });
handlers.vcs_branch_info = () => ({ head: "main" });
handlers.vcs_branches = () => [];
handlers.agent_set_config = async ({ task: id, option, value }) => {
const previous = tasks.get(String(id))!;
const updated =
option === modelId
? { ...previous, model: String(value), config: configFor(String(value)) }
: {
...previous,
config: previous.config.map((entry) =>
entry.id === option ? { ...entry, current: String(value) } : entry,
),
};
// Mirror the backend's optimistic task event; production's subscription reducer owns the UI update.
tasks.set(updated.id, updated);
window.__ipc.send(channel, { type: "task", task: updated });
if (document.documentElement.dataset.holdConfig === "true") {
delete document.documentElement.dataset.holdConfig;
const { promise, resolve } = Promise.withResolvers<void>();
document.addEventListener("release-config", () => resolve(), { once: true });
await promise;
}
return null;
};
handlers.agent_prompt = () => null;
handlers.agent_interrupt = () => null;
await store.connect();
store.useAgents.setState({
composers: new Map(),
unread: new Set(),
docked: null,
homeOpen: false,
sessionLocation: placement,
draft: store.savedDraft({ provider: provider.id, config: { [modelId]: model } }),
});
if (surface === "new") store.openHome();
else store.openTask(firstTask.id);
},
{ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId },
);
await expect(box(page)).toBeVisible();
await page.evaluate(() => document.fonts.ready);
}
function box(page: Page) {
return page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
}
function history(page: Page) {
return page.locator("[class*='_stream_']:visible");
}
function modelButton(page: Page) {
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
}
async function expectEffort(page: Page, name: string) {
await expect(modelButton(page)).toHaveAttribute("title", new RegExp(`Reasoning: ${name}(?: ·|$)`));
}
async function selected(box: Locator) {
return box.evaluate((element) => {
const selection = window.getSelection();
if (
!selection?.anchorNode ||
!selection.focusNode ||
!element.contains(selection.anchorNode) ||
!element.contains(selection.focusNode)
)
return null;
const offset = (node: Node, at: number) => {
const range = document.createRange();
range.selectNodeContents(element);
range.setEnd(node, at);
return range.toString().length;
};
return {
anchor: offset(selection.anchorNode, selection.anchorOffset),
head: offset(selection.focusNode, selection.focusOffset),
text: selection.toString(),
};
});
}
async function selectDraft(page: Page) {
const input = box(page);
await input.fill(draft);
await input.press("Home");
for (let i = 0; i < 6; i++) await input.press("ArrowRight");
for (let i = 0; i < 4; i++) await input.press("Shift+ArrowRight");
await expect.poll(() => selected(input)).toEqual({ anchor: 6, head: 10, text: "keep" });
}
async function chooseModel(page: Page, name: string) {
await modelButton(page).click();
await page.getByRole("option", { name, exact: true }).click();
await page.keyboard.press("Escape");
await box(page).focus();
}
async function expectNoSubmission(page: Page) {
expect(await ipcCalls(page, "agent_prompt")).toEqual([]);
expect(await ipcCalls(page, "agent_interrupt")).toEqual([]);
expect(await ipcCalls(page, "agent_create")).toEqual([]);
}
for (const placement of ["editor", "toolWindow"] as const) {
test(`${placement}: existing task cycles advertised values and wraps without editing, moving focus or scrolling`, async ({
workbench: page,
}) => {
await seed(page, placement);
const stream = history(page);
await stream.click({ position: { x: 12, y: 20 } });
await stream.press("Home");
await expect.poll(() => stream.evaluate((element) => element.scrollTop)).toBe(0);
await selectDraft(page);
for (const [value, name] of [
["budget-23", "Balanced"],
["budget-91", "Deep"],
["budget-7", "Gentle"],
]) {
await page.keyboard.press("Alt+t");
await expectEffort(page, name!);
await expect(box(page)).toBeFocused();
await expect(box(page)).toHaveText(draft);
await expect.poll(() => selected(box(page))).toEqual({ anchor: 6, head: 10, text: "keep" });
await expect.poll(() => stream.evaluate((element) => element.scrollTop)).toBe(0);
expect((await ipcCalls(page, "agent_set_config")).at(-1)).toEqual({
task: firstTask.id,
option: effortId,
value,
});
await expect(page.getByRole("dialog", { name: "Model & effort settings", exact: true })).toHaveCount(0);
}
await expectNoSubmission(page);
await stream.click({ position: { x: 12, y: 20 } });
await page.keyboard.press("Alt+t");
await expectEffort(page, "Balanced");
await expect(stream).toBeFocused();
await expect.poll(() => stream.evaluate((element) => element.scrollTop)).toBe(0);
});
test(`${placement}: New Task cycles effort without changing or submitting the draft`, async ({ workbench: page }) => {
await seed(page, placement, "new");
await selectDraft(page);
// macOS Option+T may report † as key; the dispatcher's physical code must still resolve Alt+T.
await box(page).dispatchEvent("keydown", { key: "†", code: "KeyT", altKey: true, bubbles: true, cancelable: true });
await expectEffort(page, "Balanced");
await expect(box(page)).toBeFocused();
await expect(box(page)).toHaveText(draft);
await expect.poll(() => selected(box(page))).toEqual({ anchor: 6, head: 10, text: "keep" });
await expectNoSubmission(page);
});
}
for (const [surface, model, status] of [
["new", "plain", "ready"],
["new", "solo", "ready"],
["task", "plain", "ready"],
["task", "solo", "ready"],
["task", "atlas", "archived"],
] as const) {
test(`${surface} ${model} ${status}: unavailable effort leaves configuration untouched`, async ({
workbench: page,
}) => {
await seed(page, "editor", surface, model, status);
if (status === "archived") await history(page).click({ position: { x: 12, y: 20 } });
else await box(page).focus();
const before = await modelButton(page).textContent();
await page.keyboard.press("Alt+t");
await expect(modelButton(page)).toHaveText(before!);
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await expectNoSubmission(page);
});
}
test("subagent conversation never changes its hidden parent's effort", async ({ workbench: page }) => {
await seed(page, "editor");
await page.getByTitle("Open the subagent's conversation", { exact: true }).click();
await expect(page.getByRole("navigation", { name: "Subagent", exact: true })).toBeVisible();
await history(page).click({ position: { x: 12, y: 20 } });
await page.keyboard.press("Alt+t");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await page
.getByRole("navigation", { name: "Subagent", exact: true })
.getByRole("button", { name: firstTask.title, exact: true })
.click();
await expectEffort(page, "Gentle");
});
test("Settings and model popup exclude the agent shortcut", async ({ workbench: page }) => {
await seed(page, "editor");
await box(page).fill(draft);
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings", exact: true });
await search.fill("keymap");
await page.keyboard.press("Alt+t");
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await modelButton(page).click();
const popup = page.getByRole("dialog", { name: "Model & effort settings", exact: true });
await expect(popup).toBeVisible();
await popup.getByRole("slider", { name: "Reasoning" }).focus();
await page.keyboard.press("Alt+t");
await expect(popup.getByRole("slider", { name: "Reasoning" })).toHaveAttribute("aria-valuetext", "Gentle");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await page.keyboard.press("Escape");
await expectEffort(page, "Gentle");
await expect(box(page)).toHaveText(draft);
});
test("code editor and terminal do not mutate the previously focused docked agent", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
await seed(page, "toolWindow");
await box(page).fill(draft);
await editor.locator(".cm-content").click();
await page.keyboard.press("Alt+t");
await expect(editor.locator(".cm-content")).toBeFocused();
await page.keyboard.press("Alt+F12");
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
const input = terminal.getByRole("textbox", { name: "Terminal input" });
await expect(input).toBeFocused();
await page.keyboard.press("Alt+t");
await expect(input).toBeFocused();
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await expectNoSubmission(page);
});
test("hidden kept-alive editor tasks stay isolated", async ({ workbench: page }) => {
await seed(page, "editor");
await box(page).fill("first draft");
await page.evaluate(async (id) => {
// Open the existing browser store; a static Node import cannot reach the mounted workbench.
const storePath = "/src/features/agents/store.ts";
(await import(storePath)).openTask(id);
}, secondTask.id);
await box(page).fill("second draft");
await page.keyboard.press("Alt+t");
await expectEffort(page, "Balanced");
await page.getByRole("tab", { name: firstTask.title, exact: true }).click();
await expectEffort(page, "Gentle");
await expect(box(page)).toHaveText("first draft");
await box(page).focus();
await page.keyboard.press("Alt+t");
await expectEffort(page, "Balanced");
expect(await ipcCalls(page, "agent_set_config")).toEqual([
{ task: secondTask.id, option: effortId, value: "budget-23" },
{ task: firstTask.id, option: effortId, value: "budget-23" },
]);
});
test("Settings → Keymap rebinds Cycle Agent Effort and removes Alt+T", async ({ workbench: page }) => {
await seed(page, "editor");
await selectDraft(page);
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions", exact: true }).fill("Cycle Agent Effort");
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: /Cycle Agent Effort/ });
await row.dblclick();
await page.getByRole("menuitem", { name: "Add Keyboard Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: "Keyboard Shortcut: Cycle Agent Effort", exact: true });
await recorder.getByRole("textbox", { name: "First stroke" }).press(rebound);
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await expect(recorder).toBeHidden();
await row.click({ button: "right" });
await page.getByRole("menuitem", { name: "Remove ⌥T", exact: true }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
await box(page).focus();
await page.keyboard.press("Alt+t");
await expectEffort(page, "Gentle");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await page.keyboard.press(rebound);
await expectEffort(page, "Balanced");
expect(await ipcCalls(page, "agent_set_config")).toEqual([
{ task: firstTask.id, option: effortId, value: "budget-23" },
]);
await expect(box(page)).toHaveText(draft);
});
test("Find Action executes Cycle Agent Effort after closing its popup", async ({ workbench: page }) => {
await seed(page, "editor");
await selectDraft(page);
await page.keyboard.press("Meta+Shift+A");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
await search.getByRole("combobox").fill("Cycle Agent Effort");
await expect(search.getByRole("option", { name: /Cycle Agent Effort/ })).toBeVisible();
await search.getByRole("combobox").press("Enter");
await expect(search).toBeHidden();
await expectEffort(page, "Balanced");
await expect(box(page)).toHaveText(draft);
expect(await ipcCalls(page, "agent_set_config")).toEqual([
{ task: firstTask.id, option: effortId, value: "budget-23" },
]);
});
test("compact docked composer shows the cycled effort visibly", async ({ workbench: page }) => {
await page.setViewportSize({ width: 600, height: 800 });
await seed(page, "toolWindow");
await box(page).focus();
await page.keyboard.press("Alt+t");
await expect(page.getByText("Effort: Balanced", { exact: true }).filter({ visible: true })).toBeVisible();
expect(await ipcCalls(page, "agent_set_config")).toEqual([
{ task: firstTask.id, option: effortId, value: "budget-23" },
]);
});
for (const preset of [
"intellij-macos",
"intellij-windows",
"vscode-macos",
"vscode-windows",
"eclipse-macos",
"eclipse-windows",
]) {
test(`${preset}: Alt+T cycles effort using the preset's default binding`, async ({ workbench: page }) => {
await seed(page, "editor");
await page.evaluate(async (preset) => {
// The dispatcher lives in Vite's browser realm; a Node import cannot update its active keymap.
const keymapPath = "/src/platform/keymap.ts";
(await import(keymapPath)).applyKeymapSettings(preset, {});
}, preset);
await box(page).focus();
await page.keyboard.press("Alt+t");
await expectEffort(page, "Balanced");
expect(await ipcCalls(page, "agent_set_config")).toEqual([
{ task: firstTask.id, option: effortId, value: "budget-23" },
]);
});
}
for (const setting of ["effort", "model"] as const) {
test(`pending ${setting} changes do not block Send or serialize shortcut presses`, async ({ workbench: page }) => {
await seed(page, "editor");
await box(page).fill(draft);
await page.evaluate(() => {
document.documentElement.dataset.holdConfig = "true";
});
if (setting === "effort") {
await page.keyboard.press("Alt+t");
await expectEffort(page, "Balanced");
await page.keyboard.press("Alt+t");
await expectEffort(page, "Deep");
} else {
await chooseModel(page, "Swift");
await expectEffort(page, "Quick");
}
expect(await ipcCalls(page, "agent_set_config")).toEqual(
setting === "effort"
? [
{ task: firstTask.id, option: effortId, value: "budget-23" },
{ task: firstTask.id, option: effortId, value: "budget-91" },
]
: [{ task: firstTask.id, option: modelId, value: "swift" }],
);
await expect(page.getByRole("button", { name: "Send", exact: true })).toBeEnabled();
await box(page).fill("send while configuration is pending");
await box(page).press("Enter");
await expect
.poll(() => ipcCalls(page, "agent_prompt"))
.toEqual([
expect.objectContaining({
task: firstTask.id,
prompt: expect.objectContaining({ text: "send while configuration is pending" }),
}),
]);
await page.evaluate(() => document.dispatchEvent(new Event("release-config")));
});
}
@@ -9,6 +9,7 @@
"--syn-type": "#8fd4c9",
"--syn-function": "#f2d07a",
"--syn-function-call": "#d9dfe8",
"--syn-shell-command": "#e8a46a",
"--syn-comment": "#6b7a8f",
"--syn-comment-style": "normal",
"--syn-doc-comment": "#74889c",
+2 -1
View File
@@ -332,7 +332,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
266 themeable tokens: 125 in the UI theme file, 141 in the editor colour scheme file.
267 themeable tokens: 125 in the UI theme file, 142 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -429,6 +429,7 @@ a token.
| `--syn-type` | `#bcbec4` | `#000000` |
| `--syn-function` | `#56a8f5` | `#00627a` |
| `--syn-function-call` | `#bcbec4` | `#080808` |
| `--syn-shell-command` | `#c57633` | `#0073bf` |
| `--syn-comment` | `#7a7e85` | `#8c8c8c` |
| `--syn-comment-style` | `normal` | `italic` |
| `--syn-doc-comment` | `#5f826b` | `#8c8c8c` |
+13
View File
@@ -286,6 +286,19 @@ pub async fn agent_fork(
agent::fork(&state.host, window.label(), task, turns).await
}
/// Creates a temporary side conversation of `source`: lives in memory only, never
/// persisted, not listed, and its session starts with the first message sent to it.
#[tauri::command]
#[specta::specta]
pub async fn agent_create_ephemeral(
window: Window,
state: State<'_, AppState>,
request: NewAgentTask,
source: String,
) -> IdeResult<AgentTask> {
agent::create_ephemeral(&state.host, window.label(), request, source).await
}
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
#[tauri::command]
#[specta::specta]
+1
View File
@@ -148,6 +148,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
agent::agent_send_queued_now,
agent::agent_set_config,
agent::agent_fork,
agent::agent_create_ephemeral,
agent::agent_rollback,
agent::agent_probe,
agent::agent_cancel,
+2 -2
View File
@@ -217,7 +217,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
}
let mut file = vec![
act("file.newUntitled", "New Untitled File"),
sub(
"new",
"New",
@@ -227,6 +226,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
SEP,
act("file.new", "File…"),
act("file.newScratchFile", "Scratch File"),
act("file.newUntitled", "Untitled File"),
],
),
act("file.openProject", "Open…"),
@@ -1999,7 +1999,7 @@ mod tests {
};
assert_eq!(
action_ids(new),
["file.newProject", "workspace.create", "file.new", "file.newScratchFile"],
["file.newProject", "workspace.create", "file.new", "file.newScratchFile", "file.newUntitled"],
"{os:?}"
);
}
+10
View File
@@ -206,6 +206,11 @@ export const commands = {
agentSetConfig: (task: string, option: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_config", { task, option, value })),
/** Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`). */
agentFork: (task: string, turns: number | null) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
/**
* Creates a temporary side conversation of `source`: lives in memory only, never
* persisted, not listed, and its session starts with the first message sent to it.
*/
agentCreateEphemeral: (request: NewAgentTask, source: string) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create_ephemeral", { request, source })),
/** Drops the task's turns after its first `turns`; returns the message of the first dropped one. */
agentRollback: (task: string, turns: number) => typedError<{
text: string,
@@ -1887,6 +1892,11 @@ export type AgentCapabilities = {
steer?: boolean,
/** It reports its background tasks and stops them one by one. */
backgroundTasks?: boolean,
/**
* The task runs read-only: it asks before anything, and requests that would change
* the project are denied (a temporary side conversation).
*/
readOnly?: boolean,
};
/**
+7
View File
@@ -1979,6 +1979,13 @@ export class EditorController implements SlotHost {
return useTabs.getState().panes[paneId]?.tabs.find((t) => t.id === tabId)?.input ?? null;
}
/** The pane showing a tab with this input key, if any (for anchoring "open beside it"). */
paneOf(key: string): string | null {
for (const [paneId, pane] of Object.entries(useTabs.getState().panes))
if (pane.tabs.some((t) => t.input.key === key)) return paneId;
return null;
}
closePath(path: string): Promise<boolean> {
return this.removeGuarded((s) => {
const keys = new Set<string>();
+1
View File
@@ -54,6 +54,7 @@ export function activate(): void | (() => void) {
openPaths: () => ctrl.openPaths(),
openTabs: () => ctrl.openTabs(),
tabInput: (paneId, tabId) => ctrl.tabInput(paneId, tabId),
paneOf: (key) => ctrl.paneOf(key),
activeInput: () => ctrl.activeInput(),
onActiveInputChange: (fn) => ctrl.onActiveInputChange(fn),
closePath: (path) => ctrl.closePath(path),
+46
View File
@@ -86,6 +86,7 @@ import { requestHover, showPhpConstructDocumentation } from "./hover";
import { declarationSummary, renderCode } from "./markdown";
import { enclosingType } from "@/editor/navigation/lineMarkers";
import { projectPythonHierarchy, pythonImplementationTargets } from "@/editor/navigation/pythonHierarchy";
import { importBindings } from "@/editor/navigation/inheritanceGraph";
import { editorPrefs } from "@/platform/editorSettings";
import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
import { isAddCaretGesture } from "@/editor/core/cm/multiCaret";
@@ -387,6 +388,48 @@ async function pythonImplementations(doc: EditorDocContext, pos: Pos): Promise<D
return pythonImplementationTargets(hierarchy, doc.path, pos, outline).catch(() => []);
}
/** Whether `line` (0-based) of `text` is an import statement. */
function isImportLine(text: Text, line: number): boolean {
return line < text.lines && /^\s*(from|import)\s/.test(text.line(line + 1).text);
}
/**
* The declaration of a name this file imports, from the project index. A server that analyses
* only its own root answers the import statement instead, and an attached dependency project
* is outside that root — the import names the module the declaration lives in.
*/
async function importedDeclarationTargets(
view: EditorView,
doc: EditorDocContext,
name: string,
): Promise<DeclarationTarget[]> {
const binding = importBindings(view.state.doc.toString().split("\n")).get(name);
if (!binding) return [];
const module = await moduleFile(doc, binding.module).catch(() => null);
if (!module) return [];
const found = await indexDefinitions(doc.path, binding.name).catch(() => []);
const inModule = found.filter((t) => t.path === module.path);
return inModule.length ? inModule : [module];
}
/** Replaces a server answer that is only this file's import line with the declaration it binds. */
async function withImportedDeclaration(
view: EditorView,
doc: EditorDocContext,
offset: number,
locs: DeclarationTarget[],
): Promise<DeclarationTarget[]> {
const only = locs[0];
if (locs.length !== 1 || !only || only.path !== doc.path || !isImportLine(view.state.doc, only.range.start.line))
return locs;
// A caret placed on the import itself already has an answer: the module (or the submodule)
// the statement names, handled below.
if (importedModulePath(view, offset)) return locs;
const name = nameAt(view, offset);
const resolved = name ? await importedDeclarationTargets(view, doc, name) : [];
return resolved.length ? resolved : locs;
}
/** `more` after `first`, without a target whose declaration line is already there. */
function mergeTargets(first: readonly DeclarationTarget[], more: readonly DeclarationTarget[]): DeclarationTarget[] {
return dedupeLocations([
@@ -488,6 +531,9 @@ async function gotoResolved(
fromSyntax = true;
}
}
// A server that only sees its own root answers the import statement for a name it cannot
// resolve; the import names the module that declares it, also in an attached project.
if (declaration && doc.language === "python") locs = await withImportedDeclaration(view, doc, offset, locs);
if (graphTargets) locs = mergeTargets(locs, await graphTargets);
if (streamed && (await streamed.opened())) {
await streamed.complete(locs);
@@ -0,0 +1,112 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands, Location } from "@/platform/ipc";
// A name imported from an attached project: the server analyses one root, so it answers the
// import statement instead of the declaration the module holds.
const { lspGoto, navResolveModule, navIndexDefinitions, fsReadText } = vi.hoisted(() => ({
lspGoto: vi.fn<typeof commands.lspGoto>(),
navResolveModule: vi.fn<typeof commands.navResolveModule>(),
navIndexDefinitions: vi.fn<typeof commands.navIndexDefinitions>(),
fsReadText: vi.fn<typeof commands.fsReadText>(async () => ({
status: "error" as const,
error: { kind: "notFound" as const, message: "not found" },
})),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: { ...real.commands, lspGoto, navResolveModule, navIndexDefinitions, fsReadText },
};
});
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { gotoTargets } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { closePopup } = await import("./popupStore");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async () => {});
provideEditorService({ openFile } as never);
const span = (line: number, col: number) => ({ start: { line, col }, end: { line, col } });
const at = (path: string, line: number): Location => ({ path, range: span(line, 0) });
let view: EditorView;
/** Opens `text` and keeps it; returns the offset of the `occurrence`-th `name` in it. */
const openAt = (text: string, name: string, occurrence = 0) => {
view?.destroy();
view = new EditorView({
state: EditorState.create({
doc: text,
extensions: [lspDoc.of({ doc: 1, path: "/p/x.py", language: "python", uiMode: "Python", readOnly: false })],
}),
parent: document.body,
});
let from = -1;
for (let i = 0; i <= occurrence; i++) from = text.indexOf(name, from + 1);
view.dispatch({ selection: { anchor: from + 1 } });
};
beforeEach(() => {
vi.clearAllMocks();
lspGoto.mockResolvedValue({ status: "ok", data: [at("/p/x.py", 0)] });
navResolveModule.mockResolvedValue({ status: "ok", data: "/dep/base.py" });
navIndexDefinitions.mockResolvedValue({
status: "ok",
data: [{ path: "/dep/base.py", range: span(0, 6), name: "Base", kind: "class", container: null }],
} as never);
});
afterEach(() => {
closePopup();
view?.destroy();
document.body.replaceChildren();
vi.restoreAllMocks();
});
describe("go to declaration on a Python name imported from another project", () => {
it("resolves a class base name to the class, not the import", async () => {
openAt("from dep.base import Base\n\nclass X(Base):\n pass\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("resolves a plain usage to the class, not the import", async () => {
openAt("from dep.base import Base\n\n\ndef make():\n return Base()\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("resolves a base name written with an import alias", async () => {
openAt("from dep.base import Base as Parent\n\nclass X(Parent):\n pass\n", "Parent", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("resolves a subscripted base to the class it parameterises", async () => {
openAt("from dep.base import Base\n\nclass X(Base[int]):\n pass\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("opens the module when the index has no symbol of that name", async () => {
navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] } as never);
openAt("from dep.base import Thing\n\nclass X(Thing):\n pass\n", "Thing", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 0 }, focus: true });
});
it("keeps a server answer that is not the import statement", async () => {
lspGoto.mockResolvedValue({ status: "ok", data: [at("/dep/other.py", 3)] });
openAt("from dep.base import Base\n\nvalue = Base\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/other.py", { selection: { line: 3, col: 0 }, focus: true });
});
});
@@ -111,6 +111,9 @@ function watchChanges() {
if (!affectsMarkers([...e.created, ...e.modified, ...e.removed])) return;
changes++;
forgetInheritanceGraph();
// A class added, moved or removed changes the targets and tooltips of the open
// documents: re-render them instead of waiting for an edit or a settling server.
for (const plugin of live) plugin.refreshSoon();
});
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
onServerSettled(() => {
+17
View File
@@ -342,6 +342,23 @@ describe("Agents task menu", () => {
expect(menu).not.toContainEqual(expect.objectContaining({ action: "agents.openTask" }));
expect(menu[0]).toMatchObject({ action: "agents.renameTask" });
});
it("offers Terminal for worktree or off-root tasks and hides it for local-checkout tasks at the project root", () => {
const localMenu = taskMenu([{ ...task("one", "ready", "local"), projectRoot: "/project", cwd: "/project" }]);
expect(localMenu).not.toContainEqual(expect.objectContaining({ action: "terminal.openAt" }));
const worktree = { ...task("two", "ready", "worktree"), cwd: "/worktrees/two" };
const worktreeMenu = taskMenu([worktree]);
expect(worktreeMenu).toContainEqual(
expect.objectContaining({ action: "terminal.openAt", label: "Terminal", arg: "/worktrees/two" }),
);
const subfolder = { ...task("three", "ready", "local"), projectRoot: "/project", cwd: "/project/packages/api" };
const subfolderMenu = taskMenu([subfolder]);
expect(subfolderMenu).toContainEqual(
expect.objectContaining({ action: "terminal.openAt", label: "Terminal", arg: "/project/packages/api" }),
);
});
});
describe("Agents drag & drop", () => {
+5 -2
View File
@@ -167,6 +167,7 @@ export function AgentsView() {
const loaded = useAgents((s) => s.loaded);
const error = useAgents((s) => s.error);
const tasks = useAgents((s) => s.tasks);
const ephemeral = useAgents((s) => s.ephemeral);
const unread = useAgents((s) => s.unread);
const providers = useAgents((s) => s.providers);
const docked = useAgents((s) => s.docked);
@@ -214,7 +215,9 @@ export function AgentsView() {
return found;
}, [tasks, query]);
const roots = useMemo<Node[]>(() => {
const all = [...tasks.values()].filter((t) => !matches || matches.has(t.id));
// Side conversations live beside the conversation they forked, never in this list.
const listed = ephemeral.size ? new Map([...tasks].filter(([id]) => !ephemeral.has(id))) : tasks;
const all = [...listed.values()].filter((t) => !matches || matches.has(t.id));
const pinned = pinnedMembers(all, organize);
return [
...(pinned.length ? [{ kind: "pinned", tasks: pinned } as Node] : []),
@@ -224,7 +227,7 @@ export function AgentsView() {
}),
...groupTasks(ungroupedMembers(all, organize)).map((group): Node => ({ kind: "group", group })),
];
}, [tasks, organize, matches]);
}, [tasks, organize, matches, ephemeral]);
const expanded = useMemo(
() => new Set(roots.map(nodeKey).filter((k) => matches || !collapsed.has(k))),
[roots, collapsed, matches],
+12 -3
View File
@@ -1,6 +1,6 @@
/** New Task page: one prompt box with the agent and its settings; where it works under it. */
import clsx from "clsx";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import type { AgentProbe, Branch } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
@@ -8,11 +8,12 @@ import { useTx, useTxTemplate } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import { Chip, Select, T, type SelectOption } from "@/ui";
import { defaultTaskProject } from "./project";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { maybeEditorService, useEditorShown, type EditorInput } from "@/workbench/contributions";
import { Composer } from "./Composer";
import { SubmitButton } from "./SubmitButton";
import { canSend, emptyDraft } from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { useEffortFocus } from "./effortFocus";
import { providerIcon } from "./model";
import { ADD_AGENT, providerOptions as agentOptions } from "./providerOptions";
import {
@@ -94,12 +95,15 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
}, [provider?.id, provider?.installed, launch, project?.root]);
const defaults = useAgentSettings().defaults;
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
const homeRoot = useRef<HTMLDivElement>(null);
const shown = useEditorShown();
const unavailableModel = config.some(
(o) =>
o.category === "model" &&
draft.config[o.id] !== undefined &&
!o.values.some((v) => v.value === draft.config[o.id]),
);
const effortAnnouncement = useEffortFocus(homeRoot, shown && !starting && !unavailableModel, config, setDraftOption);
const agentCommands = useAgentCommands(provider?.id, null, provider?.commands ?? NO_COMMANDS);
const providerOptions: SelectOption[] = agentOptions(providers, tx, providerIcon);
// Without git under the project there are no worktrees: force the local checkout.
@@ -123,7 +127,7 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
};
return (
<div className={clsx(styles.home, docked && styles.docked)}>
<div ref={homeRoot} className={clsx(styles.home, docked && styles.docked)}>
<div className={styles.inner}>
{!docked && (
<h1 className={styles.heading}>
@@ -258,6 +262,11 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
/>
{/* Notes under the box don't take part in centring, so the box stays put as they come and go. */}
<div className={styles.notes}>
{effortAnnouncement && (
<p className={styles.note} role="status" aria-live="polite" aria-atomic="true">
{tx("Effort: {level}").replace("{level}", effortAnnouncement)}
</p>
)}
{unavailableModel && (
<p className={styles.warning} role="alert">
<T>Choose another model before starting.</T>
@@ -0,0 +1,37 @@
/* Over a conversation selection: quote it into the composer or fork a side conversation from it. */
.toolbar {
position: fixed;
z-index: 3;
display: flex;
padding: 2px;
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--bg-popup);
box-shadow: var(--shadow-popup);
opacity: 0;
pointer-events: none;
transition: opacity var(--dur-fast) var(--ease);
}
.visible {
opacity: 1;
pointer-events: auto;
}
.button {
height: var(--h-control-small);
padding: 0 var(--space-2);
border: 0;
border-radius: var(--radius-toolbar-button);
background: none;
color: var(--fg);
font-size: var(--fs-ui);
white-space: nowrap;
cursor: pointer;
}
.button:hover {
background: var(--bg-hover);
}
@media (prefers-reduced-motion: reduce) {
.toolbar {
transition: none;
}
}
@@ -0,0 +1,134 @@
import { fireEvent, render } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { AgentTask } from "@/bindings";
const actions = vi.hoisted(() => ({ execute: vi.fn() }));
vi.mock("@/platform/actions", () => ({ executeAction: actions.execute }));
import { SelectionToolbar } from "./SelectionToolbar";
const task: AgentTask = {
id: "t1",
title: "Task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/repo",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
};
interface SetupOptions {
subagent?: boolean;
task?: AgentTask;
}
/** Mounts the toolbar over a stream holding one row of selectable text. */
function setup({ subagent = false, task: agent = task }: SetupOptions) {
const stream = document.createElement("div");
stream.setAttribute("data-selection-stream", "");
const row = document.createElement("div");
const text = document.createTextNode("Selected text");
row.appendChild(text);
stream.appendChild(row);
document.body.appendChild(stream);
const view = render(<SelectionToolbar streamRef={{ current: stream }} task={agent} subagent={subagent} />);
return { row, text, view };
}
/** Selects `node`'s text as the user would, then releases the mouse over the conversation. */
function selectThenRelease(node: Node) {
const range = document.createRange();
range.selectNodeContents(node);
const selection = document.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
fireEvent.mouseUp(document, { button: 0 });
}
const sideButton = (view: ReturnType<typeof render>) => view.queryByRole("button", { name: "Start Side Conversation" });
afterEach(() => document.querySelectorAll("[data-selection-stream]").forEach((n) => n.remove()));
beforeEach(() => actions.execute.mockClear());
it("offers Reply and a side conversation on a selection", () => {
const { view, row } = setup({});
selectThenRelease(row);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
expect(sideButton(view)).toBeInTheDocument();
});
it("quotes the selection into the composer on Reply", () => {
const { view, row } = setup({});
selectThenRelease(row);
fireEvent.click(view.getByRole("button", { name: "Reply" }));
expect(actions.execute).toHaveBeenCalledWith("agents.quoteReply", { task: task.id, text: "Selected text" });
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("starts the side conversation with the selection", () => {
const { view, row } = setup({});
selectThenRelease(row);
fireEvent.click(sideButton(view)!);
expect(actions.execute).toHaveBeenCalledWith("agents.startSideConversation", {
task: task.id,
text: "Selected text",
});
});
it("hides when the selection collapses", () => {
const { view, text } = setup({});
selectThenRelease(text);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
document.getSelection()?.removeAllRanges();
fireEvent(document, new Event("selectionchange"));
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("offers no side conversation in a subagent's view", () => {
const { view, row } = setup({ subagent: true });
selectThenRelease(row);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
expect(sideButton(view)).toBeNull();
});
it("offers no side conversation while the agent runs", () => {
const { view, row } = setup({ task: { ...task, status: "running" } });
selectThenRelease(row);
expect(sideButton(view)).toBeNull();
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
});
it("shows nothing in an archived task", () => {
const { view, row } = setup({ task: { ...task, status: "archived" } });
selectThenRelease(row);
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("ignores a selection in an editable field", () => {
const { view, text, row } = setup({});
const field = document.createElement("div");
field.setAttribute("contenteditable", "true");
field.textContent = "typing here";
row.parentElement!.appendChild(field);
text.remove();
selectThenRelease(field);
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("offers no side conversation from a side conversation", () => {
const { view, row } = setup({ task: { ...task, capabilities: { ...task.capabilities!, readOnly: true } } });
selectThenRelease(row);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
expect(sideButton(view)).toBeNull();
});
+155
View File
@@ -0,0 +1,155 @@
/**
* Floating toolbar above a selection in the conversation: quote it into the composer
* ("Reply"), or start a temporary side conversation about it.
*/
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState, type RefObject } from "react";
import clsx from "clsx";
import type { AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { T } from "@/ui";
import { isBusy } from "./model";
import { selectionIn } from "./selection";
import styles from "./SelectionToolbar.module.css";
/** What a shown toolbar acts on: the selection and where it sits. */
interface Shown {
text: string;
/** Selection range and the stream's visible band, viewport-relative at the moment it was shown. */
range: { left: number; top: number; bottom: number };
stream: { left: number; right: number; top: number; bottom: number };
}
/** Toolbar dimensions before the first layout measured them; only clamping leans on them. */
const ESTIMATED = { width: 200, height: 26 };
/** Just above the selection, below it when there is no room, within the stream's visible band. */
function place(shown: Shown, size: { width: number; height: number }): { left: number; top: number } {
const margin = 6;
const { width, height } = size.width ? size : ESTIMATED;
const left = Math.min(
Math.max(shown.range.left, shown.stream.left + margin),
Math.max(shown.stream.left + margin, shown.stream.right - width - margin),
);
const above = shown.range.top - height - margin;
const top = above >= shown.stream.top + margin ? above : shown.range.bottom + margin;
return {
left,
top: Math.min(Math.max(top, shown.stream.top + margin), Math.max(margin, shown.stream.bottom - height - margin)),
};
}
export function SelectionToolbar({
streamRef,
task,
subagent,
}: {
streamRef: RefObject<HTMLDivElement | null>;
task: AgentTask;
/** The conversation shown belongs to a subagent: side conversations fork the task's own. */
subagent: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
const [shown, setShown] = useState<Shown | null>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const hide = useEffectEvent(() => setShown(null));
/** Shows the toolbar over the selection, when there is one to act on. */
const show = useEffectEvent(() => {
const stream = streamRef.current;
if (!stream || task.status === "archived") return hide();
const text = selectionIn(stream);
const selection = stream.ownerDocument.getSelection();
if (!text.trim() || !selection?.rangeCount) return hide();
const range = selection.getRangeAt(0);
const start = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;
// A selection in an editable field edits that field, not the conversation.
if (!start || start.closest("input, textarea, [contenteditable='true'], .cm-editor")) return hide();
const box = range.getBoundingClientRect();
const view = stream.getBoundingClientRect();
setShown({
text,
range: { left: box.left, top: box.top, bottom: box.bottom },
stream: { left: view.left, right: view.right, top: view.top, bottom: view.bottom },
});
});
useEffect(() => {
const stream = streamRef.current;
const doc = stream?.ownerDocument;
if (!stream || !doc) return;
// Anything that starts a new selection, or moves the conversation, hides it again.
const collapsed = () => {
const selection = doc.getSelection();
if (!selection || selection.isCollapsed) hide();
};
const down = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) hide();
};
const up = (e: MouseEvent) => {
if (e.button === 0 && !ref.current?.contains(e.target as Node)) show();
};
stream.addEventListener("scroll", hide);
doc.addEventListener("mousedown", down);
doc.addEventListener("mouseup", up);
doc.addEventListener("selectionchange", collapsed);
return () => {
stream.removeEventListener("scroll", hide);
doc.removeEventListener("mousedown", down);
doc.removeEventListener("mouseup", up);
doc.removeEventListener("selectionchange", collapsed);
};
}, [streamRef]);
// The first placement clamps against the real dimensions, known after one layout.
useLayoutEffect(() => {
const el = ref.current;
if (!el || !shown) return;
const { offsetWidth, offsetHeight } = el;
setSize((s) =>
s.width === offsetWidth && s.height === offsetHeight ? s : { width: offsetWidth, height: offsetHeight },
);
}, [shown]);
// Any live task but a side conversation itself (the read-only one); the host refuses an
// agent it can't push to a mode that asks before changing things.
const side =
!!shown && !subagent && task.status !== "archived" && !isBusy(task.status) && !task.capabilities?.readOnly;
const startSide = () => {
if (!shown) return;
setShown(null);
void executeAction("agents.startSideConversation", { task: task.id, text: shown.text });
};
return (
<div
ref={ref}
className={clsx(styles.toolbar, shown && styles.visible)}
style={shown ? place(shown, size) : undefined}
// Clicking a button keeps the selection it acts on.
onMouseDown={(e) => e.preventDefault()}
>
{shown && (
<>
<button
type="button"
className={styles.button}
onClick={() => {
if (!shown) return;
setShown(null);
void executeAction("agents.quoteReply", { task: task.id, text: shown.text });
}}
>
<T>Reply</T>
</button>
{side && (
<button type="button" className={styles.button} onClick={startSide}>
<T>Start Side Conversation</T>
</button>
)}
</>
)}
</div>
);
}
+38
View File
@@ -11,6 +11,37 @@
font-size: var(--fs-ui);
}
/* Temporary side conversation: an accent bar divides it from what it forked from. */
.sideBanner {
grid-column: 1 / -1;
/* The grid stretches auto rows; keep the bar at its content height. */
align-self: start;
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border-bottom: 1px solid var(--border);
background: var(--accent-soft);
color: var(--fg);
}
.sideBanner :global(svg) {
color: var(--accent);
flex: none;
}
.sideName {
font-weight: 600;
white-space: nowrap;
}
.sideHint {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.conversation {
container-type: inline-size;
display: flex;
@@ -430,6 +461,13 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* Quoted context a reply carried with it: dimmer, with a marker line. */
.quote {
margin: 0;
padding-left: var(--space-2);
border-left: 2px solid var(--border);
color: var(--fg-muted);
}
.editMessage {
width: 100%;
+34 -1
View File
@@ -66,6 +66,7 @@ import { ChangesResizer, useChangesWidthStyle } from "./ChangesResizer";
import { Composer } from "./Composer";
import { ReferencedText } from "./ReferenceChip";
import { selectionIn } from "./selection";
import { SelectionToolbar } from "./SelectionToolbar";
import { SubmitButton } from "./SubmitButton";
import {
canSend,
@@ -79,6 +80,7 @@ import {
workTime,
} from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { useEffortFocus } from "./effortFocus";
import { findRanges, formatDuration, formatSentAt } from "./conversation";
import { ImagePreview, imageSrc } from "./ImagePreview";
import { useAgentSettings } from "./agentSettings";
@@ -98,6 +100,7 @@ import {
branchLabel,
entriesKey,
findSubagent,
hasTaskTerminal,
isBusy,
providerIcon,
statusLabel,
@@ -120,6 +123,7 @@ import {
refreshChanges,
rollbackChanges,
scheduleChanges,
discardEphemeral,
editQueued,
forkTask,
rerunFrom,
@@ -146,6 +150,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
const entries = useAgents((s) => s.entries.get(id));
// Grouping needs commits of the task's own: local checkouts keep the flat list.
const isolation = useAgents((s) => s.tasks.get(id)?.isolation);
const ephemeral = useAgents((s) => s.ephemeral.has(id));
const grouped = useChangesOptions((s) => s.groupByCommit) && isolation === "worktree";
const sinceStart = useAgents((s) => s.changes.get(id));
const review = useAgents((s) => s.groupedChanges.get(id));
@@ -240,6 +245,22 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
}
}}
>
{ephemeral && (
<div className={styles.sideBanner}>
<Icon name="branch" size={13} />
<span className={styles.sideName}>
<T>Side conversation</T>
</span>
<span className={styles.sideHint}>
<T>Temporary and read-only: closing it discards the conversation and its context.</T>
</span>
<IconButton
icon="close"
title="Discard Side Conversation"
onClick={() => void discardEphemeral(id).catch(() => undefined)}
/>
</div>
)}
<div className={styles.conversation} hidden={docked && changesOpen}>
{view && <SubagentBar task={task} path={path} cards={cards} onNavigate={setPath} />}
<FoldedContent.Provider value={finding && shown}>
@@ -265,6 +286,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
<SessionComposer
task={task}
focusRequest={inputFocus}
focusRoot={sessionRoot}
entries={entries ?? null}
head={head}
changes={changes ?? null}
@@ -342,6 +364,7 @@ function SessionStatus({
changes,
commits,
changesOpen,
effortAnnouncement,
onToggleChanges,
}: {
task: AgentTask;
@@ -350,6 +373,7 @@ function SessionStatus({
changes: AgentChange[] | null;
commits: readonly AgentCommit[];
changesOpen: boolean;
effortAnnouncement: string | null;
onToggleChanges: () => void;
}) {
const tx = useTx();
@@ -404,6 +428,9 @@ function SessionStatus({
<T>{statusLabel(task.status)}</T>
{task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`}
</span>
<span className={styles.state} role="status" aria-live="polite" aria-atomic="true">
{effortAnnouncement ? tx("Effort: {level}").replace("{level}", effortAnnouncement) : ""}
</span>
{/* What changed sits before the meter, time and terminal, or above them when the row is full. */}
<span className={styles.statusEnd}>
{(!!changes?.length || !!commits.length) && (
@@ -434,7 +461,7 @@ function SessionStatus({
)}
<span className={styles.statusMeters}>
<Meters task={task} entries={entries} />
<StatusActions task={task} />
{hasTaskTerminal(task, projectRoot) && <StatusActions task={task} />}
</span>
</span>
</div>
@@ -1022,6 +1049,7 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
<SelectionToolbar streamRef={ref} task={task} subagent={!!subagent} />
</div>
</RevealFold.Provider>
</OpenFolds.Provider>
@@ -2698,6 +2726,7 @@ function PendingPermission({ task, entry }: { task: AgentTask; entry: Permission
function SessionComposer({
task,
focusRequest,
focusRoot,
entries,
head,
changes,
@@ -2708,6 +2737,7 @@ function SessionComposer({
}: {
task: AgentTask;
focusRequest: number;
focusRoot: RefObject<HTMLDivElement | null>;
entries: AgentEntry[] | null;
head: string | null;
changes: AgentChange[] | null;
@@ -2755,6 +2785,8 @@ function SessionComposer({
body: String(e),
}),
);
const shown = useEditorShown();
const effortAnnouncement = useEffortFocus(focusRoot, shown && task.status !== "archived", task.config, setOption);
return (
<div className={styles.composerArea}>
<SessionStatus
@@ -2765,6 +2797,7 @@ function SessionComposer({
commits={commits}
changesOpen={changesOpen}
onToggleChanges={onToggleChanges}
effortAnnouncement={effortAnnouncement}
/>
{task.status === "archived" && (
<div className={styles.banner}>
+54
View File
@@ -0,0 +1,54 @@
/** Effort actions belong to the focused, visible agent surface, never the last-used task. */
import { useLayoutEffect, useState, type RefObject } from "react";
import type { AgentConfigOption } from "@/bindings";
import { setContext } from "@/platform/context";
import { nextValue } from "./composerModel";
let focused: { cycle: () => void } | null = null;
export function cycleFocusedEffort() {
focused?.cycle();
}
export function useEffortFocus(
root: RefObject<HTMLDivElement | null>,
enabled: boolean,
config: readonly AgentConfigOption[],
onChange: (id: string, value: string) => void,
) {
const option = config.find((entry) => entry.category === "thought_level" && entry.values.length > 0);
const [announced, setAnnounced] = useState(false);
useLayoutEffect(() => {
const element = root.current;
if (!element || !enabled || !option || option.values.length <= 1) return;
const target = {
cycle: () => {
const value = nextValue(option, option.current);
if (value === null) return;
onChange(option.id, value);
setAnnounced(true);
},
};
const focus = () => {
focused = target;
setContext("agentEffortAvailable", true);
};
const clear = () => {
if (focused !== target) return;
focused = null;
setContext("agentEffortAvailable", false);
};
const blur = (event: FocusEvent) => {
if (!element.contains(event.relatedTarget as Node | null)) clear();
};
element.addEventListener("focusin", focus);
element.addEventListener("focusout", blur);
if (element.contains(document.activeElement)) focus();
return () => {
element.removeEventListener("focusin", focus);
element.removeEventListener("focusout", blur);
clear();
};
}, [root, enabled, option, onChange]);
return announced ? (option?.values.find((value) => value.value === option.current)?.name ?? null) : null;
}
+30 -4
View File
@@ -7,6 +7,7 @@ import { createElement } from "react";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { lazyComponent, lazyWhen } from "@/ui";
import { isVirtualUri } from "@/platform/virtualDocs";
import { call, commands } from "@/platform/ipc";
@@ -35,15 +36,18 @@ import {
} from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { focusedSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
import {
closeActiveTask,
closeAndNewTask,
connect,
disconnect,
discardEphemeral,
openHome,
refreshModels,
refreshProviders,
useAgents,
watchEphemeralTasks,
} from "./store";
import { TaskStatusMark } from "./TaskStatusMark";
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
@@ -122,6 +126,7 @@ export function activate(): () => void {
else if (s.settings?.agents?.newTaskApprovals !== prev.settings?.agents?.newTaskApprovals && s.project?.root)
void refreshProviders();
}),
watchEphemeralTasks(),
registerToolWindow({
id: TOOL_WINDOW,
title: "Agents",
@@ -133,9 +138,12 @@ export function activate(): () => void {
plainTitle: true,
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
useBadge: () => {
const n = useAgents(
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
);
const n = useAgents((s) => {
const ephemeral = s.ephemeral;
return [...s.tasks.values()].filter(
(t) => !ephemeral.has(t.id) && (t.status === "needsInput" || s.unread.has(t.id)),
).length;
});
return n || null;
},
}),
@@ -151,7 +159,8 @@ export function activate(): () => void {
component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor)),
title: (input) => {
const data = input.data as { task: string; title?: string };
return useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task";
const title = useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task";
return useAgents.getState().ephemeral.has(data.task) ? tx`Side conversation: ${title}` : title;
},
icon: (input) => {
const task = useAgents.getState().tasks.get((input.data as { task: string }).task);
@@ -160,7 +169,15 @@ export function activate(): () => void {
// Busy / done marker in the tab's trailing slot (#2233).
trailing: (input) => createElement(TaskStatusMark, { task: (input.data as { task: string }).task }),
// Tabs of tasks deleted meanwhile are closed when the tasks load (`connect`).
// A side conversation restored after a page reload is valid again; after an app
// restart its task is gone and this same mechanism closes the tab.
restorable: true,
// Closing a side conversation's last tab discards it (the task, context included).
onClose: (input) => {
const task = (input.data as { task: string }).task;
const s = useAgents.getState();
if (s.ephemeral.has(task) && s.docked !== task) void discardEphemeral(task);
},
// Rebuilding a long conversation on every switch back is slow.
keepAlive: true,
}),
@@ -209,6 +226,15 @@ export function activate(): () => void {
keyWhen: "agentSessionFocus && !popupOpen",
run: () => focusedSession()?.focusInput?.(),
},
{
id: "agents.cycleEffort",
title: "Cycle Agent Effort",
description: "Cycles the current model's supported effort levels without changing the message.",
category: "Agents",
when: "agentEffortAvailable",
keyWhen: "agentEffortAvailable && !popupOpen",
run: cycleFocusedEffort,
},
{
id: "agents.newTask",
title: "New Agent Task",
+4
View File
@@ -107,6 +107,10 @@ export function groupTasks(tasks: Iterable<AgentTask>): TaskGroup[] {
export const isBusy = (s: AgentStatus) => s === "running" || s === "starting" || s === "needsInput";
/** Whether `task` runs outside the project root (its own worktree, or an imported subfolder). */
export const hasTaskTerminal = (task: AgentTask, projectRoot?: string | null) =>
task.isolation === "worktree" || (!!projectRoot && task.cwd !== projectRoot);
/** `entries` with `entry` at `index` (appended when `index` is the length; gaps wait for a reload). */
export function upsertEntry(entries: AgentEntry[], index: number, entry: AgentEntry): AgentEntry[] | null {
if (index > entries.length) return null;
+29 -1
View File
@@ -7,6 +7,7 @@ const backend = vi.hoisted(() => ({
tasks: new Map<string, AgentTask>(),
entries: new Map<string, AgentEntry[]>(),
forkTask: vi.fn(),
startSideConversation: vi.fn(),
rerunFrom: vi.fn(),
quoteInComposer: vi.fn(),
notify: vi.fn(),
@@ -14,6 +15,7 @@ const backend = vi.hoisted(() => ({
vi.mock("./store", () => ({
useAgents: { getState: () => backend },
forkTask: backend.forkTask,
startSideConversation: backend.startSideConversation,
rerunFrom: backend.rerunFrom,
quoteInComposer: backend.quoteInComposer,
}));
@@ -45,7 +47,7 @@ const task: AgentTask = {
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true },
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
};
const entries: AgentEntry[] = [prompt, { type: "agent", text: "**Answer**" }];
const run = (id: string, arg: unknown = { task: task.id, turn: 0 }) =>
@@ -134,6 +136,32 @@ it("branches after the reply's turn", async () => {
expect(backend.forkTask).toHaveBeenCalledWith(task.id, 1);
});
it("starts a temporary side conversation on the selection", async () => {
backend.startSideConversation.mockResolvedValue("t2");
await run("startSideConversation", { task: task.id, text: "the selected text" });
expect(backend.startSideConversation).toHaveBeenCalledWith(task.id, "the selected text");
expect(backend.forkTask).not.toHaveBeenCalled();
expect(backend.quoteInComposer).not.toHaveBeenCalled();
});
it.each(["archived", "busy", "empty", "unknown"])("does not start a side conversation: %s", async (kind) => {
let arg: unknown = { task: task.id, text: "the selected text" };
if (kind === "archived") backend.tasks.set(task.id, { ...task, status: "archived" });
if (kind === "busy") backend.tasks.set(task.id, { ...task, status: "running" });
if (kind === "empty") arg = { task: task.id, text: " " };
if (kind === "unknown") arg = { task: "missing", text: "x" };
await run("startSideConversation", arg);
expect(backend.startSideConversation).not.toHaveBeenCalled();
});
it("reports side conversation errors", async () => {
backend.startSideConversation.mockRejectedValueOnce(new Error("Unavailable"));
await run("startSideConversation", { task: task.id, text: "the selected text" });
expect(backend.notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Couldn't start the side conversation" }),
);
});
it("reports regeneration errors and allows retry", async () => {
backend.rerunFrom.mockRejectedValueOnce(new Error("Unavailable"));
await run("regenerateReply");
+26 -2
View File
@@ -3,8 +3,8 @@ import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
import { notifications } from "@/workbench/contributions";
import { replyOperations, replyTurns, turnNumbers } from "./model";
import { forkTask, quoteInComposer, rerunFrom, retractFrom, useAgents } from "./store";
import { isBusy, replyOperations, replyTurns, turnNumbers } from "./model";
import { forkTask, quoteInComposer, rerunFrom, retractFrom, startSideConversation, useAgents } from "./store";
export interface CopyReply {
text: string;
@@ -34,6 +34,12 @@ interface ReplyTarget {
turn: number;
}
/** A selection to start a temporary side conversation from. */
export interface SideSelection {
task: string;
text: string;
}
function resolveReply(arg: unknown) {
const target = arg as ReplyTarget | undefined;
if (!target || typeof target.task !== "string" || !Number.isInteger(target.turn)) return null;
@@ -143,4 +149,22 @@ export const replyActions: Action[] = [
return runReplyOperation(task.id, "Couldn't fork the task", () => forkTask(task.id, reply.turn + 1));
},
},
{
id: "agents.startSideConversation",
title: "Start Side Conversation",
category: "Agents",
icon: "branch",
hidden: true,
run: ({ arg }) => {
const target = arg as SideSelection | undefined;
if (!target || typeof target.task !== "string" || typeof target.text !== "string" || !target.text.trim()) return;
const task = useAgents.getState().tasks.get(target.task);
// Not from a side conversation itself; the host refuses an agent without a mode that
// asks before changing things (it would edit the project and then vanish).
if (!task || task.status === "archived" || isBusy(task.status) || task.capabilities?.readOnly) return;
return runReplyOperation(task.id, "Couldn't start the side conversation", () =>
startSideConversation(task.id, target.text),
);
},
},
];
+23
View File
@@ -1816,6 +1816,29 @@ describe("meters in the task header", () => {
expect(screen.queryByText("5h 19%")).toBeNull();
expect(screen.getByText("$0.42")).toBeInTheDocument();
});
it("hides the status-bar Terminal button in the local checkout and opens the worktree's terminal otherwise", async () => {
const opened: unknown[] = [];
const disposeTerminal = registerActions([
{ id: "terminal.openAt", title: "Open in Terminal", run: ({ arg }) => void opened.push(arg) },
]);
try {
const view = render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
expect(screen.queryByRole("button", { name: "Terminal" })).toBeNull();
act(() =>
useAgents.setState({
tasks: new Map([["A", { ...task("A"), isolation: "worktree", cwd: "/worktrees/a", branch: "agent/a" }]]),
}),
);
fireEvent.click(screen.getByRole("button", { name: "Terminal" }));
expect(opened).toEqual(["/worktrees/a"]);
view.unmount();
} finally {
disposeTerminal();
}
});
});
describe("sessions from other apps", () => {
@@ -0,0 +1,202 @@
import { beforeEach, expect, it, vi } from "vitest";
import type { AgentEntry, AgentTask } from "@/bindings";
import { discardEphemeral, sendMessage, startSideConversation, useAgents } from "./store";
const ipc = vi.hoisted(() => ({ create: vi.fn(), prompt: vi.fn(), delete: vi.fn(), cancel: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
...(await original<typeof import("@/platform/ipc")>()).commands,
agentCreateEphemeral: (...args: unknown[]) => ipc.create(...args),
agentPrompt: (...args: unknown[]) => ipc.prompt(...args),
agentDelete: (...args: unknown[]) => ipc.delete(...args),
agentCancel: (...args: unknown[]) => ipc.cancel(...args),
},
}));
const editor = vi.hoisted(() => ({
open: vi.fn(),
close: vi.fn(),
/** Pane id reported for a session-key lookup; set per test ("null" when nothing is found). */
paneOf: vi.fn<(key: string) => string | null>(() => null),
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openInput: editor.open, closeInput: editor.close, paneOf: editor.paneOf }),
maybeEditorService: () => ({ activePath: () => null }),
toolWindowService: () => ({ show: vi.fn() }),
}));
const source: AgentTask = {
id: "t1",
title: "Task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/repo",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
};
const side = (id: string): AgentTask => ({ ...source, id, title: `Side of ${id}`, isolation: "local" });
const user = (text: string): AgentEntry => ({
type: "user",
text,
attachments: [],
sentMs: 0,
doneMs: 1,
steered: false,
});
const agentReply = (text: string): AgentEntry => ({ type: "agent", text });
beforeEach(() => {
ipc.create.mockReset().mockResolvedValue({ status: "ok", data: side("t2") });
ipc.prompt.mockReset().mockResolvedValue({ status: "ok", data: null });
ipc.delete.mockReset().mockResolvedValue({ status: "ok", data: null });
ipc.cancel.mockReset().mockResolvedValue({ status: "ok", data: null });
editor.open.mockReset().mockResolvedValue(undefined);
editor.close.mockReset().mockResolvedValue(true);
editor.paneOf.mockReset().mockReturnValue(null);
useAgents.setState({
tasks: new Map([["t1", source]]),
entries: new Map([["t1", [user("Fix the login bug"), agentReply("Fixed it in `auth.ts`.")]]]),
ephemeral: new Set<string>(),
composers: new Map(),
});
});
it("opens a side conversation of the task: ephemeral, local, split and quoted", async () => {
const id = await startSideConversation("t1", "the selected text");
expect(id).toBe("t2");
// The host builds the context from its own copy of the conversation.
expect(ipc.create).toHaveBeenCalledWith(
expect.objectContaining({
provider: "codex",
isolation: "local",
prompt: { text: "the selected text", files: [], images: [] },
}),
"t1",
);
const s = useAgents.getState();
expect(s.ephemeral.has("t2")).toBe(true);
expect(s.composers.get("t2")?.text).toContain("> the selected text");
expect(editor.open).toHaveBeenCalledWith(expect.objectContaining({ kind: "agent-session", key: "agent:t2" }), {
focus: true,
side: true,
});
});
it("keeps the marks across a page reload and drops them with the app", async () => {
const { watchEphemeralTasks } = await import("./store");
const stop = watchEphemeralTasks();
sessionStorage.setItem("openidea.agents.sideMarks", JSON.stringify(["t2"]));
// The store refills after the reload: the mark comes back with the task…
useAgents.setState({
loaded: true,
tasks: new Map([
["t1", source],
["t2", side("t2")],
]),
ephemeral: new Set(),
});
expect(useAgents.getState().ephemeral.has("t2")).toBe(true);
// …and when the host's copy is gone (app restart, or the task was discarded), so is the mark.
useAgents.setState((s) => {
const tasks = new Map(s.tasks);
tasks.delete("t2");
return { tasks };
});
expect(useAgents.getState().ephemeral.has("t2")).toBe(false);
expect(sessionStorage.getItem("openidea.agents.sideMarks")).toBe("[]");
stop();
});
it("sends follow-up messages as typed: the host owns the context", async () => {
await startSideConversation("t1", "the selected text");
useAgents.setState((s) => {
const composers = new Map(s.composers);
composers.set("t2", { text: "Why did you touch auth.ts?", files: [], images: [] });
return { composers };
});
await sendMessage("t2", false);
expect(ipc.prompt).toHaveBeenCalledTimes(1);
const [task, prompt] = ipc.prompt.mock.calls[0]!;
expect(task).toBe("t2");
expect(prompt.text).toBe("Why did you touch auth.ts?");
});
it("opens a nested side conversation in its parent's pane", async () => {
await startSideConversation("t1", "first");
editor.open.mockClear();
// The parent side conversation shows in a split pane: the nested one joins it there.
editor.paneOf.mockReturnValue("pane-right");
useAgents.setState((s) => {
const entries = new Map(s.entries);
entries.set(
"t2",
entries.get("t1")!.map((e) => ({ ...e })),
);
return { entries };
});
await startSideConversation("t2", "deeper question");
expect(ipc.create).toHaveBeenLastCalledWith(expect.objectContaining({ provider: "codex" }), "t2");
// No second split: it stacks in the same pane.
expect(editor.open).toHaveBeenLastCalledWith(expect.anything(), { focus: true, pane: "pane-right" });
});
it("discards a side conversation: stops it, deletes it, clears its state", async () => {
const busy = { ...side("t2"), status: "running" as const };
useAgents.setState({
tasks: new Map([
["t1", source],
["t2", busy],
]),
ephemeral: new Set(["t2"]),
entries: new Map([
["t2", []],
["t2/sub", []],
["t1", []],
]),
composers: new Map([["t2", { text: "", files: [], images: [] }]]),
unread: new Set(["t2"]),
docked: null,
});
ipc.cancel.mockImplementation(async () => {
useAgents.setState((s) => {
const tasks = new Map(s.tasks);
tasks.set("t2", { ...busy, status: "ready" });
return { tasks };
});
return { status: "ok", data: null };
});
await discardEphemeral("t2");
expect(ipc.cancel).toHaveBeenCalledWith("t2", null);
expect(ipc.delete).toHaveBeenCalledWith("t2", false);
const s = useAgents.getState();
expect(s.ephemeral.has("t2")).toBe(false);
expect(s.tasks.has("t2")).toBe(false);
expect(s.tasks.has("t1")).toBe(true);
expect(s.entries.has("t2")).toBe(false);
expect(s.entries.has("t2/sub")).toBe(false);
expect(s.composers.has("t2")).toBe(false);
expect(s.unread.has("t2")).toBe(false);
});
it("ignores discard requests for tasks that are not side conversations", async () => {
useAgents.setState({ tasks: new Map([["t1", source]]), ephemeral: new Set() });
await discardEphemeral("t1");
expect(ipc.delete).not.toHaveBeenCalled();
});
+168 -1
View File
@@ -123,6 +123,8 @@ interface AgentsState {
sessionLocation: SessionLocation;
lastTask: string | null;
homeOpen: boolean;
/** Side conversations by task id: kept out of the task list, discarded when their view closes. */
ephemeral: ReadonlySet<string>;
}
const DRAFT_KEY = "openidea.agents.draft.v2";
@@ -191,6 +193,7 @@ export const useAgents = create<AgentsState>(() => ({
sessionLocation: load<unknown>(SESSION_LOCATION_KEY, null) === "toolWindow" ? "toolWindow" : "editor",
lastTask: null,
homeOpen: false,
ephemeral: new Set<string>(),
scrollPositions: new Map(),
}));
@@ -521,6 +524,7 @@ export function disconnect() {
externalError: null,
importOpen: false,
importing: new Set(),
ephemeral: new Set<string>(),
scrollPositions: new Map(),
});
}
@@ -814,12 +818,20 @@ function showDockedTask(task: string) {
}
function saveSessionLocation(location: SessionLocation) {
const previous = useAgents.getState().sessionLocation;
useAgents.setState({ sessionLocation: location });
save(SESSION_LOCATION_KEY, location);
if (location === "toolWindow") {
for (const { input } of editorService().openTabs?.() ?? []) {
if (input.kind === SESSION_KIND || input.kind === HOME_KIND) void editorService().closeInput?.(input.key);
}
} else {
// Leaving the tool window closes the docked view: a side conversation has no view left.
const docked = useAgents.getState().docked;
if (docked && previous === "toolWindow" && useAgents.getState().ephemeral.has(docked)) {
useAgents.setState({ docked: null });
void discardEphemeral(docked);
}
}
}
@@ -835,7 +847,7 @@ export function setSessionLocation(location: SessionLocation) {
activeTask ??
(s.lastTask && s.tasks.has(s.lastTask) ? s.lastTask : null) ??
[...s.tasks.values()]
.filter((t) => t.status !== "archived")
.filter((t) => t.status !== "archived" && !s.ephemeral.has(t.id))
.sort((a, b) => (b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0))[0]?.id;
saveSessionLocation(location);
useAgents.setState({ docked: null, homeOpen: false });
@@ -1098,6 +1110,161 @@ export async function forkTask(task: string, turns: number | null): Promise<void
}
}
/**
* The side-conversation marks survive a page reload (which wipes the store) in
* `sessionStorage`: they live exactly as long as the window and its backend tasks —
* an app restart clears both. Keeps the conversations out of the task list after a
* reload and lets closing their tab still discard them.
*/
const SIDE_MARKS_KEY = "openidea.agents.sideMarks";
function sideMarkIds(): string[] {
try {
return JSON.parse(globalThis.sessionStorage?.getItem(SIDE_MARKS_KEY) ?? "[]") as string[];
} catch {
return [];
}
}
function rememberSideMark(task: string) {
try {
const ids = sideMarkIds().filter((id) => id !== task);
ids.push(task);
globalThis.sessionStorage?.setItem(SIDE_MARKS_KEY, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
function forgetSideMark(task: string) {
try {
globalThis.sessionStorage?.setItem(SIDE_MARKS_KEY, JSON.stringify(sideMarkIds().filter((id) => id !== task)));
} catch {
/* storage unavailable */
}
}
/**
* Restores the marks when the store refills after a page reload, and drops marks of
* tasks that are gone (the host's memory copy died with a restart, or was discarded).
* Call once per window; the returned function unsubscribes.
*/
export function watchEphemeralTasks(): () => void {
return useAgents.subscribe((s) => {
if (!s.loaded) return;
const saved = sideMarkIds();
const missing = saved.filter((id) => s.tasks.has(id) && !s.ephemeral.has(id));
const stale = [...s.ephemeral].filter((id) => !s.tasks.has(id) || !saved.includes(id));
if (!missing.length && !stale.length) return;
useAgents.setState((state) => {
const ephemeral = new Set(state.ephemeral);
missing.forEach((id) => ephemeral.add(id));
stale.forEach((id) => {
ephemeral.delete(id);
forgetSideMark(id);
});
return { ephemeral };
});
});
}
/**
* Opens a temporary side conversation of `task`, with `task`'s conversation as its
* context — nothing is copied or persisted; the host sends the context to the agent
* with its first message. Closing the pane discards it (`discardEphemeral`). Opening
* one from inside a side conversation keeps it in that same column.
*/
export async function startSideConversation(task: string, text: string): Promise<string> {
const s = useAgents.getState();
const source = s.tasks.get(task);
if (!source) throw new Error("the task is gone");
const created = await call(
commands.agentCreateEphemeral(
{
projectRoot: source.projectRoot,
// Only the side conversation's title comes from it; the context rides in memory.
prompt: { text, files: [], images: [] },
provider: source.provider,
config: source.config.filter((o) => o.current != null).map((o) => ({ id: o.id, value: o.current as string })),
isolation: "local" as const,
base: null,
},
task,
),
);
// One frame: the watcher must never see the mark without the task (it would drop it
// again as stale before the task lands).
useAgents.setState((s) => ({
tasks: s.tasks.has(created.id) ? s.tasks : new Map(s.tasks).set(created.id, created),
ephemeral: new Set(s.ephemeral).add(created.id),
}));
rememberSideMark(created.id);
// Nested side conversations open in their parent's column; fresh ones split beside the task.
const nested = s.ephemeral.has(task);
const options: { focus: boolean; side?: boolean; pane?: string } = { focus: true };
if (nested) {
// The click that launched this didn't move the active pane (the toolbar keeps the
// selection), so anchor explicitly: a new tab in the parent side conversation's pane.
const pane = editorService().paneOf?.(sessionKey(task));
if (pane) options.pane = pane;
else options.side = true;
} else {
options.side = true;
}
await editorService().openInput(
{ kind: SESSION_KIND, key: sessionKey(created.id), data: { task: created.id, title: created.title } },
options,
);
quoteInComposer(created.id, text);
return created.id;
}
/** Stops a side conversation and deletes it, its context included. */
export async function discardEphemeral(task: string): Promise<void> {
const s = useAgents.getState();
if (!s.ephemeral.has(task)) return;
forgetSideMark(task);
useAgents.setState((state) => {
const ephemeral = new Set(state.ephemeral);
ephemeral.delete(task);
return { ephemeral };
});
try {
if (isBusy(s.tasks.get(task)?.status ?? "ready")) {
await cancelTask(task);
await settled(task);
}
await deleteTask(task, s.tasks.get(task)?.isolation === "worktree");
} catch (e) {
console.warn("Couldn't discard the side conversation", e);
}
useAgents.setState((state) => {
const without = <V>(map: Map<string, V>) => {
const next = new Map(map);
next.delete(task);
return next;
};
const entries = new Map(state.entries);
for (const key of [...entries.keys()]) if (key === task || key.startsWith(`${task}/`)) entries.delete(key);
const entryLoads = new Map(state.entryLoads);
for (const key of [...entryLoads.keys()]) if (key === task || key.startsWith(`${task}/`)) entryLoads.delete(key);
return {
tasks: without(state.tasks),
entries,
entryLoads,
changes: without(state.changes),
groupedChanges: without(state.groupedChanges),
composers: without(state.composers),
scrollPositions: without(state.scrollPositions),
unread: state.unread.has(task) ? new Set([...state.unread].filter((id) => id !== task)) : state.unread,
docked: state.docked === task ? null : state.docked,
lastTask: state.lastTask === task ? null : state.lastTask,
lastComposer: state.lastComposer === task ? HOME : state.lastComposer,
};
});
void editorService().closeInput?.(sessionKey(task));
}
/** Puts a message back in the task's composer, above anything typed meanwhile. */
function restoreComposer(task: string, text: string, images: AgentImage[]) {
const current = composerDraft(task);
+8 -2
View File
@@ -1,10 +1,11 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { confirm, showError, confirmChecked } from "@/workbench/messages";
import { promptInput } from "@/workbench/inputDialogs";
import { isBusy } from "./model";
import { hasTaskTerminal, isBusy } from "./model";
import { groupNameError, type OrganizeGroup } from "./organize";
import {
archiveTask,
@@ -387,6 +388,7 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
if (!tasks.length) return [];
const ids = tasks.map((task) => task.id);
const task = tasks[0]!;
const projectRoot = task.projectRoot ?? useProject.getState().project?.root ?? null;
const multiple = tasks.length > 1;
const archived = tasks.filter((task) => task.status === "archived").length;
const archivable = tasks.filter(canArchive).length;
@@ -394,7 +396,11 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
...(!multiple
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
{ kind: "action", action: "terminal.openAt", label: "Terminal", icon: "terminal", arg: task.cwd },
...(hasTaskTerminal(task, projectRoot)
? ([
{ kind: "action", action: "terminal.openAt", label: "Terminal", icon: "terminal", arg: task.cwd },
] satisfies MenuItem[])
: []),
...(task.capabilities?.fork && task.status !== "archived"
? ([
{
@@ -36,6 +36,7 @@ import {
applyProfile,
enabledByDefault,
inspectionProfile,
subscribeInspectionProfile,
producerInspectionId,
} from "@/platform/inspections";
import {
@@ -380,6 +381,9 @@ function watchChanges() {
if ([...e.created, ...e.modified, ...e.removed].some(isPythonFile)) refreshAll();
});
onServerSettled(refreshAll);
// Switching an inspection on or off in Settings applies to the open documents too: the
// rules read the profile when they run, so a change must schedule a run.
subscribeInspectionProfile(refreshAll);
}
/** The producers whose inspection is on in the profile in effect. */
@@ -0,0 +1,37 @@
import { describe, expect, it, vi } from "vitest";
import type { EditorDocContext } from "@/editor/api";
// Toggling an inspection in Settings must reach the open documents: the rules read the
// profile when they run, so the extension subscribes to profile changes and schedules one.
const listeners: (() => void)[] = [];
vi.mock("@/platform/inspections", async (orig) => {
const real = await orig<typeof import("@/platform/inspections")>();
return {
...real,
subscribeInspectionProfile: (listener: () => void) => {
listeners.push(listener);
return () => listeners.splice(listeners.indexOf(listener), 1);
},
};
});
vi.mock("@/editor/lsp/diagnostics", async (orig) => ({
...(await orig<object>()),
setFileDiagnostics: () => {},
}));
const { pythonInheritanceExtension } = await import("./inheritanceInspections");
const ctx = (language: string): EditorDocContext =>
({ doc: 1, path: "/p/a.py", language, uiMode: "Python", readOnly: false, virtual: false }) as EditorDocContext;
describe("Python inheritance inspections follow the profile", () => {
it("subscribes to profile changes, and only for Python", () => {
expect(listeners).toHaveLength(0);
pythonInheritanceExtension(ctx("typescript"));
expect(listeners).toHaveLength(0);
pythonInheritanceExtension(ctx("python"));
expect(listeners).toHaveLength(1);
// A change schedules a run; the schedule itself is debounced, so calling it is safe here.
expect(() => listeners[0]!()).not.toThrow();
});
});
+1
View File
@@ -198,6 +198,7 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
"PY.DOC_COMMENT_TAG": [["FOREGROUND", "--syn-python-docstring-tag"]],
OPENIDEA_pyDocstringKeyword: [["FOREGROUND", "--syn-python-docstring-keyword"]],
"PY.BUILTIN_NAME": [["FOREGROUND", "--syn-predefined"]],
"BASH.EXTERNAL_COMMAND": [["FOREGROUND", "--syn-shell-command"]],
MARKDOWN_HEADER_LEVEL_1: [["FOREGROUND", "--syn-markup-heading"]],
MARKDOWN_CODE_SPAN: [["FOREGROUND", "--syn-markup-code"]],
MARKDOWN_LINK_TEXT: [["FOREGROUND", "--syn-link"]],
+44 -25
View File
@@ -7,7 +7,7 @@ import { useEffect, useMemo, useState } from "react";
import type { ChangedFile, Commit, RevisionChange } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Button, IconButton, Spinner, T } from "@/ui";
import { Button, IconButton, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { ComparisonTree } from "./ComparisonTree";
import { buildFileTree } from "./fileTree";
import { flatFileNodes, toLogChanges, type LogChange } from "./logChanges";
@@ -15,6 +15,7 @@ import { KIND_COLOR, dirName, fileCount } from "./model";
import styles from "./common.module.css";
const GROUP_KEY = "openidea.vcs.push.groupByDirectory";
const DETAILS_SPLIT_KEY = "openidea.vcs.push.detailsSplit";
function readGroupByDirectory(): boolean {
try {
@@ -36,10 +37,12 @@ export function PushChanges({
repo,
commits,
onShowAll,
onSelectFile,
}: {
repo: string | null;
commits: readonly Commit[];
onShowAll?: () => void;
onSelectFile?: (change: LogChange | null) => void;
}) {
const [changes, setChanges] = useState<LogChange[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -75,6 +78,35 @@ export function PushChanges({
};
const count = commits.length;
if (!count) return null;
const files = error ? (
<div className={styles.error}>{error}</div>
) : !changes ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<ComparisonTree
tree={tree}
current={current}
onSelect={(c) => {
setCurrent(c);
onSelectFile?.(c);
}}
diffFor={(c) => c.diff}
inlineDiff={!onSelectFile}
getColor={(c) => KIND_COLOR[c.kind === "untracked" ? "added" : c.kind]}
ariaLabel="Changed files"
renderDetails={(n) =>
n.file ? (
byDirectory ? null : (
<span className={styles.fileDir}>{dirName(n.file.path)}</span>
)
) : (
<span className={styles.fileDir}>{n.count}</span>
)
}
/>
);
return (
<div className={styles.pushChanges}>
<div className={styles.pushChangesTitle}>
@@ -96,31 +128,18 @@ export function PushChanges({
className={styles.pushGrouping}
/>
</div>
{count === 1 && <PushCommitDetails commit={commits[0]!} />}
{error ? (
<div className={styles.error}>{error}</div>
) : !changes ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
{count === 1 ? (
<SplitGroup orientation="vertical" storageKey={DETAILS_SPLIT_KEY} className={styles.pushDetailsSplit}>
<SplitPanel id="details" minSize="40px" defaultSize="25%" className={styles.pushDetailsPanel}>
<PushCommitDetails commit={commits[0]!} />
</SplitPanel>
<SplitHandle />
<SplitPanel id="files" minSize="80px" className={styles.pushDetailsPanel}>
{files}
</SplitPanel>
</SplitGroup>
) : (
<ComparisonTree
tree={tree}
current={current}
onSelect={setCurrent}
diffFor={(c) => c.diff}
getColor={(c) => KIND_COLOR[c.kind === "untracked" ? "added" : c.kind]}
ariaLabel="Changed files"
renderDetails={(n) =>
n.file ? (
byDirectory ? null : (
<span className={styles.fileDir}>{dirName(n.file.path)}</span>
)
) : (
<span className={styles.fileDir}>{n.count}</span>
)
}
/>
files
)}
</div>
);
+58
View File
@@ -0,0 +1,58 @@
import { useState, type ReactNode } from "react";
import { tx } from "@/platform/i18n";
import { IconButton, SplitGroup, SplitHandle, SplitPanel, lazyComponent } from "@/ui";
import { diffInput } from "./diffInput";
import type { LogChange } from "./logChanges";
import styles from "./common.module.css";
const DiffEditor = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor));
const PUSH_DIFF_SPLIT_KEY = "openidea.vcs.push.diffSplit";
export function usePushDiff(shownKey: string) {
const [state, setState] = useState<{ key: string; change: LogChange } | null>(null);
return {
diff: state?.key === shownKey ? state.change : null,
show: (change: LogChange | null) => setState(change ? { key: shownKey, change } : null),
close: () => setState(null),
};
}
interface PushDiffSplitProps {
diff: LogChange | null;
onClose: () => void;
children: ReactNode;
}
export function PushDiffSplit({ diff, onClose, children }: PushDiffSplitProps) {
return (
<SplitGroup orientation="vertical" storageKey={diff ? PUSH_DIFF_SPLIT_KEY : undefined} className={styles.pushSplit}>
<SplitPanel id="sides" minSize="120px" defaultSize="50%" className={styles.pushSplitPanel}>
{children}
</SplitPanel>
{diff && (
<>
<SplitHandle />
<SplitPanel id="diff" minSize="120px" defaultSize="50%" className={styles.pushSplitPanel}>
<PushDiff change={diff} onClose={onClose} />
</SplitPanel>
</>
)}
</SplitGroup>
);
}
function PushDiff({ change, onClose }: { change: LogChange; onClose: () => void }) {
const input = diffInput(change.diff);
return (
<div className={styles.pushDiff}>
<div className={styles.pushDiffHeader}>
<span className={styles.pushDiffPath}>{change.path}</span>
<IconButton icon="close" size="small" title={tx("Close Diff")} onClick={onClose} />
</div>
<div className={styles.pushDiffBody}>
<DiffEditor key={input.key} input={input} />
</div>
</div>
);
}
@@ -1,10 +1,12 @@
import { beforeEach, expect, it, vi } from "vitest";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { RemoteOp } from "@/bindings";
const mocks = vi.hoisted(() => ({
ops: [] as Array<{ repo: string | null; op: RemoteOp }>,
failing: new Set<string>(),
upToDate: new Set<string>(),
changes: vi.fn(),
ask: vi.fn(),
}));
@@ -32,7 +34,30 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
ok({ head: "feat-x", headCommit: "c1", upstream: "origin/feat-x", ahead: 1, behind: 0, operation: null, repo }),
vcsRemotes: (repo: string) => ok(repo === "/p/b" ? [remote("origin"), remote("fork")] : [remote("origin")]),
vcsLog: (repo: string) =>
ok([{ id: `${repo}-1`, shortId: "c1", parents: ["c0"], summary: "Work", author: "me", timeMs: 0 }]),
ok(
mocks.upToDate.has(repo)
? []
: [
{
id: `${repo}-1`,
shortId: "c1",
parents: ["c0"],
summary: "Work",
message: "Work",
author: "me",
email: "[email protected]",
timeMs: 0,
},
],
),
vcsCommitFiles: (repo: string) => {
mocks.changes(repo);
return ok([{ path: `${repo.slice(3)}.txt`, oldPath: null, kind: "modified" }]);
},
vcsCommitsChanges: (repo: string) => {
mocks.changes(repo);
return ok([{ path: `${repo.slice(3)}.txt`, oldPath: null, kind: "modified", before: "c0", after: "c1" }]);
},
vcsHasHook: () => ok(false),
vcsRemote: (repo: string | null, _request: number, op: RemoteOp) => {
mocks.ops.push({ repo, op });
@@ -56,6 +81,8 @@ let notes: Note[] = [];
beforeEach(() => {
mocks.ops = [];
mocks.failing = new Set();
mocks.upToDate = new Set();
mocks.changes.mockReset();
mocks.ask.mockReset();
mocks.ask.mockResolvedValue({ button: "force", checked: false });
notes = [];
@@ -63,6 +90,14 @@ beforeEach(() => {
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
});
afterEach(() => {
for (const cancel of screen.queryAllByRole("button", { name: "Cancel" })) fireEvent.click(cancel);
});
function check(...repos: string[]) {
for (const name of repos) fireEvent.click(screen.getByRole("checkbox", { name }));
}
it("pushes each repository to its own remote and target branch, reporting the one that failed", async () => {
mocks.failing.add("/p/b");
render(<VcsDialogHost />);
@@ -129,6 +164,40 @@ async function openPushDialog() {
await screen.findByRole("textbox", { name: "Target branch of a" });
}
it("lists every repository on Push all, checks those with commits, expands none and shows no files", async () => {
mocks.upToDate.add("/p/c");
render(<VcsDialogHost />);
await act(() => showPushDialog());
await screen.findByRole("textbox", { name: "Target branch of a" });
expect(screen.getByRole("textbox", { name: "Target branch of c" })).toBeInTheDocument();
for (const name of ["a", "b"]) expect(screen.getByRole("checkbox", { name })).toBeChecked();
expect(screen.getByRole("checkbox", { name: "c" })).not.toBeChecked();
expect(screen.queryByText("Work")).toBeNull();
expect(mocks.changes).not.toHaveBeenCalled();
check("b");
fireEvent.click(screen.getByRole("button", { name: "Push" }));
await waitFor(() => expect(mocks.ops).toHaveLength(1));
expect(mocks.ops[0]?.repo).toBe("/p/a");
});
it("shows only the repository Push was invoked from without a checkbox, its files shown at once", async () => {
render(<VcsDialogHost />);
await act(() => showPushDialog({ repo: "/p/b" }));
expect(await screen.findByText("Push Commits to b")).toBeInTheDocument();
expect(await screen.findByText("b.txt")).toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Target branch of b" })).toBeInTheDocument();
expect(screen.queryByRole("textbox", { name: "Target branch of a" })).toBeNull();
expect(screen.queryByRole("textbox", { name: "Target branch of c" })).toBeNull();
expect(screen.queryByRole("checkbox", { name: "b" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Push" }));
await waitFor(() => expect(mocks.ops).toHaveLength(1));
expect(mocks.ops[0]?.repo).toBe("/p/b");
});
it("asks to confirm each forced target and pushes nothing when one is declined", async () => {
mocks.ask.mockResolvedValueOnce({ button: "force", checked: false }).mockResolvedValueOnce({ button: null });
await openPushDialog();
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
const mocks = vi.hoisted(() => ({ log: vi.fn() }));
const commit = (id: string, summary: string) => ({
id,
shortId: id,
parents: ["c0"],
summary,
message: summary,
author: "me",
email: "[email protected]",
timeMs: 0,
});
vi.mock("../DiffEditor", () => ({
DiffEditor: ({ input }: { input: { path: string } }) => <div>diff view {input.path}</div>,
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
return {
...real,
commands: {
...real.commands,
vcsRemotes: () => ok([{ name: "origin", fetchUrl: "/remotes/origin", pushUrl: "/remotes/origin" }]),
vcsBranches: () =>
ok([
{ name: "feature", remote: false, current: true, upstream: null },
{ name: "origin/main", remote: true, current: false, upstream: null },
]),
vcsLog: (repo: string, query: unknown) => {
mocks.log(repo, query);
return ok([commit("c2", "More"), commit("c1", "Work")]);
},
vcsCommitsChanges: () => ok([{ path: "src/A.java", oldPath: null, kind: "modified", before: "c0", after: "c2" }]),
vcsCommitFiles: () => ok([{ path: "src/B.java", oldPath: null, kind: "modified" }]),
vcsHasHook: () => ok(false),
},
};
});
import { VcsDialogHost } from "../dialogs";
import { showPushDialog } from "../remoteUi";
import { useVcs } from "../store";
beforeEach(() => {
mocks.log.mockReset();
useVcs.setState({
root: "/p",
roots: ["/p"],
repo: "/p",
available: false,
branch: { head: "feature", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
branches: [],
branchesLoaded: false,
});
});
afterEach(() => {
for (const cancel of screen.queryAllByRole("button", { name: "Cancel" })) fireEvent.click(cancel);
});
it("lists only the commits no remote branch has for a branch without upstream", async () => {
render(<VcsDialogHost />);
await act(() => showPushDialog());
expect((await screen.findAllByText("Work")).length).toBeGreaterThan(0);
await waitFor(() =>
expect(mocks.log).toHaveBeenCalledWith(
"/p",
expect.objectContaining({ branch: "HEAD", range: "HEAD ^refs/remotes/origin/main", limit: 1000 }),
),
);
expect(mocks.log).not.toHaveBeenCalledWith("/p", expect.objectContaining({ range: null, limit: 50 }));
});
it("shows the selected file's diff under both panes until it is closed or another commit is picked", async () => {
render(<VcsDialogHost />);
await act(() => showPushDialog());
fireEvent.mouseDown(await screen.findByText("A.java"));
expect(await screen.findByText("src/A.java")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close Diff" }));
expect(screen.queryByText("src/A.java")).toBeNull();
fireEvent.mouseDown(screen.getByText("A.java"));
expect(await screen.findByText("src/A.java")).toBeInTheDocument();
const older = screen.getByRole("option", { name: /Work/ });
fireEvent.mouseDown(older);
fireEvent.click(older);
expect(await screen.findByText("B.java")).toBeInTheDocument();
expect(screen.queryByText("src/A.java")).toBeNull();
});
+19 -26
View File
@@ -3,7 +3,6 @@ import type { BranchInfo } from "@/bindings";
import { messageProblems, wrapAtMargin } from "../CommitView";
import { linkifyIssues } from "../issueLinks";
import {
defaultPushChecked,
isProtectedBranch,
isLeaseRejected,
isPushRejected,
@@ -105,7 +104,7 @@ describe("several repositories", () => {
expect(attentionRepo("/p", {}, {})).toBeNull();
});
it("lists repositories with something to push", () => {
it("lists every repository on a branch, up-to-date ones too", () => {
const branch = (head: string | null, upstream: string | null) => ({
head,
headCommit: "c1",
@@ -121,30 +120,7 @@ describe("several repositories", () => {
{ root: "/p/b", branch: branch("feature", null), commits: [commit] },
{ root: "/p/c", branch: branch(null, null), commits: [] },
];
const candidates = pushCandidates(repos);
expect(candidates.map((r) => r.root)).toEqual(["/p", "/p/b"]);
expect([...defaultPushChecked(candidates, "/p")]).toEqual(["/p"]);
expect([...defaultPushChecked(candidates, "/p/b")]).toEqual(["/p", "/p/b"]);
});
it("checks only the repository Push was invoked from", () => {
const branch = (head: string, upstream: string | null) => ({
head,
headCommit: "c1",
upstream,
ahead: 0,
behind: 0,
operation: null,
});
const commit = { id: "c1", shortId: "c1" } as RepoPush["commits"][number];
const candidates: RepoPush[] = [
{ root: "/p", branch: branch("main", "origin/main"), commits: [commit] },
{ root: "/p/a", branch: branch("main", "origin/main"), commits: [commit] },
{ root: "/p/b", branch: branch("feature", null), commits: [commit] },
];
expect([...defaultPushChecked(candidates, "/p/a", true)]).toEqual(["/p/a"]);
expect([...defaultPushChecked(candidates, "/p/b", true)]).toEqual(["/p/b"]);
expect([...defaultPushChecked(candidates, "/p/c", true)]).toEqual([]);
expect(pushCandidates(repos).map((r) => r.root)).toEqual(["/p", "/p/a", "/p/b"]);
});
});
@@ -202,6 +178,23 @@ describe("pushRepoCommits", () => {
expect(vcsLog).toHaveBeenLastCalledWith("/p", expect.objectContaining({ branch: "HEAD", range: null, limit: 50 }));
});
it("lists the commits no remote branch has for a branch without upstream", async () => {
vcsLog.mockReset().mockResolvedValue({ status: "ok", data: [{ id: "c1" }] });
vcsBranches.mockReset().mockResolvedValue({
status: "ok",
data: [
{ name: "feature", remote: false },
{ name: "origin/main", remote: true },
],
});
await expect(pushRepoCommits("/p", branch("feature", null))).resolves.toEqual([{ id: "c1" }]);
expect(vcsLog).toHaveBeenCalledTimes(1);
expect(vcsLog).toHaveBeenCalledWith(
"/p",
expect.objectContaining({ branch: "HEAD", range: "HEAD ^refs/remotes/origin/main", limit: 1000 }),
);
});
it("passes the upstream range through when it resolves", async () => {
vcsLog.mockReset().mockResolvedValue({ status: "ok", data: [] });
await pushRepoCommits("/p", branch("main", "origin/main"));
+49 -7
View File
@@ -138,21 +138,55 @@
flex-direction: column;
padding: 0 14px 14px;
}
/* Push dialog: commits above their changed files, split by a draggable divider; the pair fills the body. */
.pushSplit {
flex: 1;
min-height: min(540px, 60vh);
flex: 1 1 min(540px, 60vh);
min-height: 0;
}
/* The panel's own `height: 100%` doesn't resolve against a flex-basis height in WebKit: stretch instead. */
.pushSplit .pushSplitPanel {
height: auto;
align-self: stretch;
}
.pushSplitPanel > .pushListWrap {
.pushSides {
flex: 1;
min-height: 0;
padding-bottom: 8px;
}
/* Push dialogs: the outgoing commits' changed files below the commits, the diff beside them. */
.pushDiff {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 8px 14px 14px;
}
.pushDiffHeader {
display: flex;
align-items: center;
gap: 8px;
min-height: 24px;
padding-bottom: 6px;
color: var(--fg-subtle);
}
.pushDiffPath {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pushDiffBody {
flex: 1;
min-height: 0;
overflow: hidden;
border: 1px solid var(--border);
}
.pushSplitPanel > .pushListWrap,
.pushSplitPanel > .pushTreeWrap {
min-height: 0;
}
.pushTreeWrap .commitRow[data-idle],
.pushTreeWrap .commitRow[data-idle] label {
color: var(--fg-subtle);
}
.pushChanges {
flex: 1;
display: flex;
@@ -177,11 +211,19 @@
.pushGrouping {
margin-left: auto;
}
.pushDetailsSplit {
flex: 1;
min-height: 0;
}
.pushDetailsSplit .pushDetailsPanel {
height: auto;
}
.pushCommitDetails {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: 4px;
max-height: 96px;
margin: 0 14px 8px;
padding: 6px 8px;
overflow: auto;
+160 -155
View File
@@ -25,6 +25,7 @@ import { saveVcsSetting } from "./settingsUi";
import { formatTime } from "./model";
import { allRepos, lastRemoteFailure, runRemote, saveAll } from "./ops";
import { PushChanges, pushChangesKey } from "./PushChanges";
import { PushDiffSplit, usePushDiff } from "./PushDiff";
import { pushOperation, splitTracked, type PushChoice } from "./pushTarget";
import { currentRepo, currentRepoRoot, loadBranches, refreshNow, repoName, useVcs } from "./store";
import { stripRemotePrefix, TargetBranchInput } from "./TargetBranchInput";
@@ -175,6 +176,7 @@ export function outgoingQuery(upstream: string | null): { branch: string; range:
*/
export async function pushRepoCommits(root: string, branch: BranchInfo): Promise<Commit[]> {
if (!branch.head) return [];
if (!branch.upstream) return unpushedCommits(root);
const q = outgoingQuery(branch.upstream);
return logOf(q.branch, q.limit, q.range, root).catch(() => unpushedCommits(root));
}
@@ -182,11 +184,11 @@ export async function pushRepoCommits(root: string, branch: BranchInfo): Promise
const RECENT_HISTORY_LIMIT = 50;
const OUTGOING_LIMIT = 1000;
async function unpushedCommits(root: string): Promise<Commit[]> {
async function unpushedCommits(root: string | null, tip = "HEAD"): Promise<Commit[]> {
const branches = await call(commands.vcsBranches(root)).catch(() => []);
const remotes = branches.filter((b) => b.remote).map((b) => `^refs/remotes/${b.name}`);
if (!remotes.length) return logOf("HEAD", RECENT_HISTORY_LIMIT, null, root);
return logOf("HEAD", OUTGOING_LIMIT, ["HEAD", ...remotes].join(" "), root);
if (!remotes.length) return logOf(tip, RECENT_HISTORY_LIMIT, null, root);
return logOf(tip, OUTGOING_LIMIT, [tip, ...remotes].join(" "), root);
}
export interface PushTarget {
@@ -229,25 +231,11 @@ export interface RepoPush {
commits: Commit[];
}
/** Repositories with something to push: outgoing commits, or a branch without upstream. */
export function pushCandidates(repos: readonly RepoPush[]): RepoPush[] {
return repos.filter((r) => r.branch.head && (r.branch.upstream ? r.commits.length > 0 : true));
return repos.filter((r) => r.branch.head);
}
/**
* Checked by default: repositories with outgoing commits (a new branch only in the selected
* one); with `onlySelected` (Push… from one repository's branch menu), only the selected one.
*/
export function defaultPushChecked(
repos: readonly RepoPush[],
selected: string | null,
onlySelected = false,
): Set<string> {
if (onlySelected) return new Set(repos.filter((r) => r.root === selected).map((r) => r.root));
return new Set(
repos.filter((r) => (r.branch.upstream ? r.commits.length > 0 : r.root === selected)).map((r) => r.root),
);
}
const hasNothingToPush = (r: RepoPush) => !!r.branch.upstream && !r.commits.length;
/** One node of the multi-repository Push tree: a repo group with its outgoing commits. */
interface PushNode {
@@ -259,6 +247,8 @@ interface PushNode {
// A long outgoing list scrolls inside the dialog instead of growing it to the screen (IDEA: 800×450 centre panel).
const PUSH_DIALOG_MAX_HEIGHT = 720;
const PUSH_DIALOG_WIDTH = 960;
const PUSH_SPLIT_KEY = "openidea.vcs.pushSides";
interface MultiPushDialogProps {
only?: string;
@@ -266,10 +256,11 @@ interface MultiPushDialogProps {
}
function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
const roots = useVcs((s) => s.roots);
const allRoots = useVcs((s) => s.roots);
const roots = useMemo(() => (only === undefined ? allRoots : allRoots.filter((r) => r === only)), [allRoots, only]);
const [repos, setRepos] = useState<RepoPush[] | null>(null);
const [checked, setChecked] = useState<Set<string>>(() => new Set());
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());
const [expanded, setExpanded] = useState<Set<string>>(() => new Set(only === undefined ? [] : [only]));
// The selected row: a repository shows all its outgoing changes, a commit its own.
const [shown, setShown] = useState<PushNode | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -306,7 +297,22 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
}
const list = pushCandidates(loaded);
setRepos(list);
setChecked(only === undefined ? defaultPushChecked(list, currentRepo()) : defaultPushChecked(list, only, true));
// Push all checks what has outgoing commits, plus a new branch of the current repository;
// Push… from one repository checks it unless it is up to date.
const current = currentRepo();
setChecked(
new Set(
list
.filter((r) =>
only === undefined
? r.branch.upstream
? r.commits.length > 0
: r.root === current
: !hasNothingToPush(r),
)
.map((r) => r.root),
),
);
});
return () => {
alive = false;
@@ -388,15 +394,20 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
children: repo.commits.map((commit) => ({ key: `${repo.root}:${commit.id}`, repo, commit })),
}));
const shownRepo = shown?.repo ?? (repos?.length === 1 ? repos[0]! : null);
const shownRepo = shown?.repo ?? (only !== undefined ? (repos?.[0] ?? null) : null);
const shownCommits = useMemo(() => (shown?.commit ? [shown.commit] : (shownRepo?.commits ?? [])), [shown, shownRepo]);
const {
diff,
show: showDiff,
close: closeDiff,
} = usePushDiff(shownRepo ? pushChangesKey(shownRepo.root, shownCommits) : "");
return (
<Dialog
open
title="Push Commits"
title={only === undefined ? "Push Commits" : tx`Push Commits to ${repoName(only)}`}
onClose={onClose}
width={repos?.some((r) => r.commits.length) ? 860 : 620}
width={PUSH_DIALOG_WIDTH}
maxHeight={PUSH_DIALOG_MAX_HEIGHT}
className={styles.pushDialog}
resizable="both"
@@ -432,85 +443,107 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.pushTreeWrap}>
{error ? (
<div className={styles.error}>{error}</div>
) : !repos ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<Tree<PushNode>
roots={nodes}
getKey={(n) => n.key}
getLabel={(n) => (n.commit ? n.commit.summary : repoName(n.repo.root))}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={new Set(nodes.map((n) => n.key).filter((k) => !collapsed.has(k)))}
onExpandedChange={(_next, node, open) =>
setCollapsed((c) => {
const s = new Set(c);
if (open) s.delete(node.key);
else s.add(node.key);
return s;
})
}
selected={new Set(shown ? [shown.key] : [])}
multiSelect={false}
onSelectionChange={(_sel, lead) => setShown(lead)}
rowHeight={22}
aria-label="Outgoing commits"
className={styles.boxList}
empty={
<span>
<T>Everything is up to date</T>
</span>
}
renderNode={(n) =>
n.commit ? (
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
<span className={styles.commitHash}>{n.commit.shortId}</span>
<span className={styles.commitSubject}>{n.commit.summary}</span>
<span className={styles.commitMeta}>{n.commit.author}</span>
<span className={styles.commitMeta}>{formatTime(n.commit.timeMs)}</span>
</span>
<PushDiffSplit diff={diff} onClose={closeDiff}>
<SplitGroup orientation="horizontal" storageKey={PUSH_SPLIT_KEY} className={styles.pushSides}>
<SplitPanel id="commits" minSize="240px" defaultSize="50%" className={styles.pushSplitPanel}>
<div className={styles.pushTreeWrap}>
{error ? (
<div className={styles.error}>{error}</div>
) : !repos ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<span
className={styles.commitRow}
style={{ flex: 1, padding: 0 }}
// A row click toggles the checkbox, like before; only the chevron collapses.
onClick={(e) => {
if (!(e.target as HTMLElement | null)?.closest?.("label")) toggle(n.repo.root);
}}
>
<Checkbox
checked={checked.has(n.repo.root)}
onChange={() => toggle(n.repo.root)}
label={repoName(n.repo.root)}
/>
<span className={styles.commitMeta}>{n.repo.branch.head} →</span>
<PushRowTarget
name={repoName(n.repo.root)}
remotes={remotesOf[n.repo.root] ?? []}
remote={shownRemoteOf(n.repo)}
onRemote={(remote) => edit(n.repo.root, { remote })}
target={edits[n.repo.root]?.target ?? targetOf(n.repo)}
onTarget={(target) => edit(n.repo.root, { target })}
changed={pushOperation(choiceOf(n.repo, null)).op === "pushBranch"}
onEnter={() => {
if (picked.length) void push();
}}
/>
{!n.repo.branch.upstream && <span className={styles.commitMeta}>{tx("new remote branch")}</span>}
</span>
)
}
/>
)}
</div>
{shownRepo && (
<PushChanges key={pushChangesKey(shownRepo.root, shownCommits)} repo={shownRepo.root} commits={shownCommits} />
)}
<Tree<PushNode>
roots={nodes}
getKey={(n) => n.key}
getLabel={(n) => (n.commit ? n.commit.summary : repoName(n.repo.root))}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={(_next, node, open) =>
setExpanded((e) => {
const s = new Set(e);
if (open) s.add(node.key);
else s.delete(node.key);
return s;
})
}
selected={new Set(shown ? [shown.key] : [])}
multiSelect={false}
onSelectionChange={(_sel, lead) => setShown(lead)}
rowHeight={22}
aria-label="Outgoing commits"
className={styles.boxList}
empty={
<span>
<T>Everything is up to date</T>
</span>
}
renderNode={(n) =>
n.commit ? (
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
<span className={styles.commitHash}>{n.commit.shortId}</span>
<span className={styles.commitSubject}>{n.commit.summary}</span>
<span className={styles.commitMeta}>{n.commit.author}</span>
<span className={styles.commitMeta}>{formatTime(n.commit.timeMs)}</span>
</span>
) : (
<span
className={styles.commitRow}
data-idle={hasNothingToPush(n.repo) || undefined}
style={{ flex: 1, padding: 0 }}
// A row click toggles the checkbox, like before; only the chevron collapses.
onClick={(e) => {
if (only === undefined && !(e.target as HTMLElement | null)?.closest?.("label"))
toggle(n.repo.root);
}}
>
{only === undefined ? (
<Checkbox
checked={checked.has(n.repo.root)}
onChange={() => toggle(n.repo.root)}
label={repoName(n.repo.root)}
/>
) : (
<span className={styles.commitSubject}>{repoName(n.repo.root)}</span>
)}
<span className={styles.commitMeta}>{n.repo.branch.head} →</span>
<PushRowTarget
name={repoName(n.repo.root)}
remotes={remotesOf[n.repo.root] ?? []}
remote={shownRemoteOf(n.repo)}
onRemote={(remote) => edit(n.repo.root, { remote })}
target={edits[n.repo.root]?.target ?? targetOf(n.repo)}
onTarget={(target) => edit(n.repo.root, { target })}
changed={pushOperation(choiceOf(n.repo, null)).op === "pushBranch"}
onEnter={() => {
if (picked.length) void push();
}}
/>
{!n.repo.branch.upstream && (
<span className={styles.commitMeta}>{tx("new remote branch")}</span>
)}
</span>
)
}
/>
)}
</div>
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize="240px" className={styles.pushSplitPanel}>
{shownRepo && (
<PushChanges
key={pushChangesKey(shownRepo.root, shownCommits)}
repo={shownRepo.root}
commits={shownCommits}
onSelectFile={showDiff}
/>
)}
</SplitPanel>
</SplitGroup>
</PushDiffSplit>
</Dialog>
);
}
@@ -578,15 +611,11 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
const [commits, setCommits] = useState<Commit[] | null>(null);
// The commit whose changes are shown; -1: all outgoing commits.
const [shownCommit, setShownCommit] = useState(-1);
const [pushSplit, setPushSplit] = useState(loadPushSplit);
const keepPushSplit = (layout: Record<string, number>) => {
setPushSplit(layout);
savePushSplit(layout);
};
const shownCommits = useMemo(
() => (commits && shownCommit >= 0 && commits[shownCommit] ? [commits[shownCommit]] : (commits ?? [])),
[commits, shownCommit],
);
const { diff, show: showDiff, close: closeDiff } = usePushDiff(pushChangesKey(repo, shownCommits));
const [error, setError] = useState<string | null>(null);
const [force, setForce] = useState(false);
const [remotes, setRemotes] = useState<string[]>([]);
@@ -641,13 +670,14 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
if (!head) return [];
if (!explicit && upstream === tracked) {
// The tracked upstream: `@{u}` resolves it even when the name is ambiguous.
return logOf("HEAD", 1000, "@{u}..HEAD", repo).catch(() => logOf("HEAD", 50, null, repo));
return tracked
? logOf("HEAD", OUTGOING_LIMIT, "@{u}..HEAD", repo).catch(() => unpushedCommits(repo))
: unpushedCommits(repo);
}
const tip = revision ?? head;
// `remote/branch` may not exist locally yet: fall back to the recent history.
return upstream
? logOf(tip, 1000, `${upstream}..${tip}`, repo).catch(() => logOf(tip, 50, null, repo))
: logOf(tip, 50, null, repo);
? logOf(tip, OUTGOING_LIMIT, `${upstream}..${tip}`, repo).catch(() => unpushedCommits(repo, tip))
: unpushedCommits(repo, tip);
})()
.then((c) => alive && setCommits(c))
.catch((e) => alive && setError(e instanceof Error ? e.message : String(e)));
@@ -726,7 +756,7 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
open
title={head ? tx`Push Commits to ${upstream ?? "remote"}` : "Push"}
onClose={onClose}
width={commits?.length ? 860 : 620}
width={commits?.length ? PUSH_DIALOG_WIDTH : 620}
maxHeight={PUSH_DIALOG_MAX_HEIGHT}
className={styles.pushDialog}
resizable="both"
@@ -799,26 +829,23 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
{retarget && !remoteBranchNames.includes(edited) && <span className={styles.hint}> {tx("New")}</span>}
</div>
{commits?.length && !error ? (
<SplitGroup
orientation="vertical"
id="vcs-push-split"
className={styles.pushSplit}
defaultLayout={pushSplit}
onLayoutChanged={keepPushSplit}
>
<SplitPanel id="commits" minSize="72px" defaultSize="35%" className={styles.pushSplitPanel}>
{commitList}
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize="160px" className={styles.pushSplitPanel}>
<PushChanges
key={pushChangesKey(repo, shownCommits)}
repo={repo}
commits={shownCommits}
onShowAll={shownCommit >= 0 && commits.length > 1 ? () => setShownCommit(-1) : undefined}
/>
</SplitPanel>
</SplitGroup>
<PushDiffSplit diff={diff} onClose={closeDiff}>
<SplitGroup orientation="horizontal" storageKey={PUSH_SPLIT_KEY} className={styles.pushSides}>
<SplitPanel id="commits" minSize="240px" defaultSize="50%" className={styles.pushSplitPanel}>
{commitList}
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize="240px" className={styles.pushSplitPanel}>
<PushChanges
key={pushChangesKey(repo, shownCommits)}
repo={repo}
commits={shownCommits}
onShowAll={shownCommit >= 0 && commits.length > 1 ? () => setShownCommit(-1) : undefined}
onSelectFile={showDiff}
/>
</SplitPanel>
</SplitGroup>
</PushDiffSplit>
) : (
commitList
)}
@@ -826,28 +853,6 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
);
}
const PUSH_SPLIT_KEY = "openidea.vcs.pushSplit";
/** Heights of the Push dialog's commits and changed files, as the splitter left them. */
function loadPushSplit(): Record<string, number> | undefined {
try {
const v: unknown = JSON.parse(localStorage.getItem(PUSH_SPLIT_KEY) ?? "null");
return v && typeof v === "object" && Object.values(v).every((n) => typeof n === "number")
? (v as Record<string, number>)
: undefined;
} catch {
return undefined;
}
}
function savePushSplit(layout: Record<string, number>) {
try {
localStorage.setItem(PUSH_SPLIT_KEY, JSON.stringify(layout));
} catch {
/* kept for this dialog only */
}
}
const SILENT_FORCE_PUSH_KEY = "openidea.vcs.silentForcePushTargets";
function silentForcePushTargets(): string[] {
+1
View File
@@ -8,6 +8,7 @@ import { intellijMacos } from "./intellij-macos";
export const eclipseMacos: Record<string, string[]> = {
...intellijMacos,
"agents.focusInput": ["Meta+L"],
"agents.cycleEffort": ["Alt+T"],
// $Undo / $Redo stay unbound as in the parent keymap: the focused editor or view handles them.
"code.autoIndentLines": ["Meta+I"],
"navigate.back": ["Meta+[", "Button4", "SwipeRight"],
+1
View File
@@ -8,6 +8,7 @@ import { intellijWindows } from "./intellij-windows";
export const eclipseWindows: Record<string, string[]> = {
...intellijWindows,
"agents.focusInput": ["Ctrl+L"],
"agents.cycleEffort": ["Alt+T"],
// $Undo / $Redo stay unbound as in the parent keymap: the focused editor or view handles them.
"code.autoIndentLines": ["Ctrl+I"],
"navigate.back": ["Alt+Left", "Button4"],
+1
View File
@@ -373,6 +373,7 @@ export const intellijMacos: Record<string, string[]> = {
"db.showToolWindow": [],
"agents.newTask": ["Meta+Shift+I"],
"agents.focusInput": ["Meta+L"],
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
+1
View File
@@ -371,6 +371,7 @@ export const intellijWindows: Record<string, string[]> = {
"db.showToolWindow": [],
"agents.newTask": ["Ctrl+Alt+Shift+I"],
"agents.focusInput": ["Ctrl+L"],
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
+1
View File
@@ -405,6 +405,7 @@ export const vscodeMacos: Record<string, string[]> = {
// Agents (VS Code's chat: ⇧⌘I)
"agents.newTask": ["Meta+Shift+I"],
"agents.focusInput": ["Meta+L"],
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused.
+1
View File
@@ -64,6 +64,7 @@ export const vscodeWindows: Record<string, string[]> = {
// Agents (VS Code's chat: Ctrl+Shift+I)
"agents.newTask": ["Ctrl+Shift+I"],
"agents.focusInput": ["Ctrl+L"],
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
};
+1 -1
View File
@@ -203,7 +203,7 @@
"menu.workspace.create": "Workspace…",
"menu.workspace.open": "Open Workspace…",
"menu.workspace.manage": "Manage Workspace…",
"menu.file.newUntitled": "New Untitled File",
"menu.file.newUntitled": "Untitled File",
"menu.file.openInNewWindow": "Open in New Window…",
"menu.file.openFile": "Open File…",
"menu.remote.connect": "Remote Development…",
+9
View File
@@ -736,6 +736,11 @@
"Couldn't rename the task": "Couldn't rename the task",
"Start a Fresh Agent Session": "Start a Fresh Agent Session",
"Start Fresh": "Start Fresh",
"Start Side Conversation": "Start Side Conversation",
"Side conversation": "Side conversation",
"Side conversation: {title}": "Side conversation: {title}",
"Temporary and read-only: closing it discards the conversation and its context.": "Temporary and read-only: closing it discards the conversation and its context.",
"Discard Side Conversation": "Discard Side Conversation",
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.",
"Copy Path From Source Root": "Copy Path From Source Root",
"Escape text on paste in string literals": "Escape text on paste in string literals",
@@ -1033,6 +1038,7 @@
"Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper.": "Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper.",
"Remote of {name}": "Remote of {name}",
"Target branch of {name}": "Target branch of {name}",
"Close Diff": "Close Diff",
"Remote project files cannot be shown in {fileManager}": "Remote project files cannot be shown in {fileManager}",
"Reformat": "Reformat",
"Open in Window": "Open in Window",
@@ -1460,6 +1466,9 @@
"Close and New Agent Task": "Close and New Agent Task",
"Focus Agent Input": "Focus Agent Input",
"Focuses the message input of the current agent task without moving the caret.": "Focuses the message input of the current agent task without moving the caret.",
"Cycle Agent Effort": "Cycle Agent Effort",
"Cycles the current model's supported effort levels without changing the message.": "Cycles the current model's supported effort levels without changing the message.",
"Effort: {level}": "Effort: {level}",
"Closes the agent task tab in the editor; the task keeps running in the Agents tool window.": "Closes the agent task tab in the editor; the task keeps running in the Agents tool window.",
"Closes the agent task tab in the editor, then opens the New Task page.": "Closes the agent task tab in the editor, then opens the New Task page.",
"May be incomplete: plugin indexes are still updating": "May be incomplete: plugin indexes are still updating",
+9
View File
@@ -4103,6 +4103,9 @@
"Close and New Agent Task": "关闭并新建 Agent 任务",
"Focus Agent Input": "聚焦 Agent 输入框",
"Focuses the message input of the current agent task without moving the caret.": "聚焦当前 Agent 任务的消息输入框,不移动光标。",
"Cycle Agent Effort": "循环切换 Agent 思考强度",
"Cycles the current model's supported effort levels without changing the message.": "循环切换当前模型支持的思考强度,不改变消息内容。",
"Effort: {level}": "思考强度:{level}",
"Closes the agent task tab in the editor; the task keeps running in the Agents tool window.": "关闭编辑器中的 Agent 任务标签页;任务继续在 Agents 工具窗口中运行。",
"Closes the agent task tab in the editor, then opens the New Task page.": "关闭编辑器中的 Agent 任务标签页,然后打开“新建任务”页面。",
"No agent tasks yet": "还没有 Agent 任务",
@@ -7143,6 +7146,11 @@
"Couldn't rename the task": "无法重命名任务",
"Start a Fresh Agent Session": "启动全新的智能体会话",
"Start Fresh": "重新开始",
"Start Side Conversation": "开始侧边对话",
"Side conversation": "侧边对话",
"Side conversation: {title}": "侧边对话:{title}",
"Temporary and read-only: closing it discards the conversation and its context.": "临时且只读:关闭即丢弃对话及其上下文。",
"Discard Side Conversation": "丢弃侧边对话",
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "这会清空整个对话,并使用此消息启动全新的智能体会话。智能体已修改的文件保持不变。",
"Path From Source Root": "相对于源根的路径",
"Paste preview": "粘贴预览",
@@ -7404,6 +7412,7 @@
"Gradle could not be started. Configure a local installation in Gradle settings, install Gradle on PATH, or use a project with a Gradle wrapper.": "无法启动 Gradle。请在 Gradle 设置中配置本地安装,将 Gradle 安装到 PATH,或使用带有 Gradle wrapper 的项目。",
"Remote of {name}": "{name} 的远程",
"Target branch of {name}": "{name} 的目标分支",
"Close Diff": "关闭差异",
"Remote project files cannot be shown in {fileManager}": "无法在{fileManager}中显示远程项目的文件",
"Reformat": "重新格式化",
"Open in Window": "在窗口中打开",
+1 -1
View File
@@ -203,7 +203,7 @@
"menu.workspace.create": "工作区…",
"menu.workspace.open": "打开工作区…",
"menu.workspace.manage": "管理工作区…",
"menu.file.newUntitled": "新建无标题文件",
"menu.file.newUntitled": "无标题文件",
"menu.file.openInNewWindow": "在新窗口中打开…",
"menu.file.openFile": "打开文件…",
"menu.remote.connect": "远程开发…",
+2
View File
@@ -664,6 +664,8 @@ export interface EditorService {
openTabs?(): OpenEditorTab[];
/** Input of the tab `tabId` in pane `paneId` (dragging tabs between views), null if there is none. */
tabInput?(paneId: string, tabId: string): EditorInput | null;
/** The pane showing a tab with this input key, if any (for anchoring "open beside it"). */
paneOf?(key: string): string | null;
/** Input of the active tab (any kind), if any. */
activeInput?(): EditorInput | null;
/** Calls `fn` whenever the active tab changes; returns the unsubscribe. */