feat(agents): redesign composer controls, branch switching, and worktree reuse (#8167)

* feat(agents): redesign composer controls, branch switching, and worktree reuse

* fix(agents): address PR #8167 review findings for worktree safety, branch checkout, and composer UX
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-05 14:03:16 +08:00
1 джерело 749c34df7a
коміт 7d30d23a56
39 files changed
+4029 -577

No files matched your search

+3 -1
Переглянути файл
@@ -80,6 +80,8 @@ fn client_capabilities() -> Value {
"subagents": {},
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
"elicitation": { "form": {} },
// Ghost-text next-prompt suggestions (`prompt_suggestions_update`).
"session": { "promptSuggestions": {} },
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
// only when the client advertises this flag (undocumented Cursor ACP extension).
"_meta": { "parameterizedModelPicker": true },
@@ -94,7 +96,7 @@ pub(crate) fn initialize_params(client_info: &Value) -> Value {
json!({
"protocolVersion": 2,
"info": client_info,
"capabilities": {},
"capabilities": { "session": { "promptSuggestions": {} } },
"clientCapabilities": client_capabilities(),
"clientInfo": client_info,
})
+3
Переглянути файл
@@ -133,11 +133,14 @@ fn the_negotiating_request_carries_both_versions() {
);
// Forms only: URL mode would open pages the agent names.
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
assert_eq!(p["clientCapabilities"]["session"], json!({ "promptSuggestions": {} }));
assert_eq!(p["capabilities"]["session"], json!({ "promptSuggestions": {} }));
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
let mut expected = sent;
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
expected["session"] = p["clientCapabilities"]["session"].clone();
assert_eq!(expected, p["clientCapabilities"]);
}
+265 -8
Переглянути файл
@@ -187,8 +187,14 @@ const STDERR_LINES: usize = 20;
/// (`session/load`): the next message starts it again where it left off.
const IDLE_RELEASE: Duration = Duration::from_secs(5 * 60);
/// Updates of a session's state rather than its conversation.
const SESSION_STATE: [&str; 5] =
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
const SESSION_STATE: [&str; 6] = [
"session_info_update",
"config_option_update",
"current_mode_update",
"available_commands_update",
"usage_update",
"prompt_suggestions_update",
];
/// A native agent's own update: it is about to retry a failed API request (see [`AgentRetry`]).
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
/// A native agent's own update: the usage limits of its account (see [`AgentLimit`]).
@@ -1694,6 +1700,7 @@ impl AgentManager {
unread: false,
recovery_window_mins: None,
automation: None,
prompt_suggestions: Box::default(),
};
let file = TaskFile {
task: task.clone(),
@@ -1791,6 +1798,7 @@ impl AgentManager {
unread: false,
recovery_window_mins: None,
automation: None,
prompt_suggestions: Box::default(),
};
let file = TaskFile {
task: task.clone(),
@@ -1879,10 +1887,21 @@ impl AgentManager {
)));
}
let dir = self.shared.paths.worktrees_dir.clone();
let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone());
let c = vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref()))
if let Some(wt_path) = req.worktree_path.map(|p| p.0) {
let (c, before) = vcs(&self.shared, move || {
let c = worktree::reuse_for_task(&root, &dir, &wt_path)?;
let before = worktree::snapshot(&c.cwd).unwrap_or_default();
Ok((c, before))
})
.await?;
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), before)
} else {
let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone());
let c =
vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref()))
.await?;
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
}
}
Isolation::Local => {
let r = root.clone();
@@ -1977,6 +1996,7 @@ impl AgentManager {
unread: false,
recovery_window_mins: None,
automation: automation_meta.clone().map(Box::new),
prompt_suggestions: Box::default(),
};
let initial_scheduled = automation_meta.as_ref().map(|m| ScheduledTurnMeta {
permissions: m.permissions,
@@ -2081,6 +2101,7 @@ impl AgentManager {
} else {
let epoch = self.shared.shutdown_epoch();
s.busy = true;
s.task.prompt_suggestions.clear();
s.pending_prompt = Some(prompt.clone());
s.active_scheduled_turn = scheduled.clone();
// A run watcher reads the status before the spawned turn shows its prompt, and
@@ -2450,6 +2471,7 @@ impl AgentManager {
interrupted: None,
unread: false,
automation: None,
prompt_suggestions: Box::default(),
..s.task.clone()
};
let (session, cut) = match session {
@@ -2533,6 +2555,7 @@ impl AgentManager {
s.history.conversation = Conversation::default();
// The fresh session reports its own usage; nothing carries over.
s.task.usage = None;
s.task.prompt_suggestions.clear();
s.pending_rollback = 0;
s.task.updated_ms = now_ms();
Self::finish_rewind(&mut s, 0, restamped);
@@ -2565,6 +2588,7 @@ impl AgentManager {
_ => None,
};
s.history.conversation.truncate(cut);
s.task.prompt_suggestions.clear();
s.task.updated_ms = now_ms();
Self::finish_rewind(&mut s, turns as usize, restamped);
(first, task.turn_dir(), s.history.turns.clone())
@@ -3291,7 +3315,12 @@ impl AgentManager {
if isolation != Isolation::Worktree || busy || !cwd.exists() {
return Ok(false);
}
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
let target_root = worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd);
let shared = self.tasks.read().values().any(|t| {
t.id != id
&& worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &t.state.lock().task.cwd.0)
== target_root
});
if shared {
return Ok(false);
}
@@ -3327,6 +3356,139 @@ impl AgentManager {
Ok(true)
}
/// Checks out (or creates and checks out) a Git branch in an idle task's working directory.
/// Rejects archived tasks, untrusted local repos, or checkouts where this task or any sibling
/// sharing the same worktree/repo is busy. Holds `BusyGuard` across the checkout to prevent
/// concurrent turns/checkouts, and updates `task.branch` (plus `base`/`base_commit` when
/// switching to an existing branch) for all worktree tasks sharing the checkout.
pub async fn checkout_branch(&self, id: &str, branch: &str, create: bool) -> IdeResult<ide_vcs::CheckoutOutcome> {
if !git_enabled(&self.shared) {
return Err(IdeError::invalid("Git is disabled for this project"));
}
let task = self.task(id)?;
let (isolation, raw_cwd) = {
let s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("cannot switch branches on an archived task"));
}
if s.busy || matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
{
return Err(IdeError::invalid("stop the current turn before switching branches"));
}
(s.task.isolation, s.task.cwd.0.clone())
};
let cwd = if isolation == Isolation::Worktree {
task.verify_worktree_cwd_confined()?
} else {
if let Some(repo) = Repo::discover(&raw_cwd)? {
let canon_repo = dunce::canonicalize(repo.root())?;
if let Some(check) = self.shared.repo_trust.read().clone()
&& !check(&canon_repo)
{
return Err(IdeError::invalid(format!(
"Git repository {} is not trusted: trust the repository root before switching branches",
canon_repo.display()
)));
}
}
raw_cwd
};
let local_repo_key = if isolation == Isolation::Local {
Repo::discover(&cwd)?.and_then(|r| dunce::canonicalize(r.root()).ok()).map(worktree::normalize_path_key)
} else {
None
};
let wt_root_key = if isolation == Isolation::Worktree {
Some(worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd))
} else {
None
};
// Collect all tasks sharing this checkout in deterministic BTreeMap ID order and acquire
// BusyGuard on every one so concurrent turns, rollbacks, or checkouts cannot race.
let (group, guards) = {
let tasks = self.tasks.read();
let mut group = Vec::new();
let mut guards = Vec::new();
for other in tasks.values() {
let matches = if other.id == id {
true
} else {
let (other_iso, other_cwd) = {
let s = other.state.lock();
(s.task.isolation, s.task.cwd.0.clone())
};
if let Some(ref target_wt) = wt_root_key {
worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &other_cwd) == *target_wt
} else if other_iso == Isolation::Local
&& let Some(ref target_repo) = local_repo_key
{
Repo::discover(&other_cwd)
.ok()
.flatten()
.and_then(|r| dunce::canonicalize(r.root()).ok())
.map(worktree::normalize_path_key)
.as_ref()
== Some(target_repo)
} else {
false
}
};
if !matches {
continue;
}
let mut s = other.state.lock();
if other.id == id && s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("cannot switch branches on an archived task"));
}
if s.busy
|| matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
{
return Err(IdeError::invalid(if other.id == id {
"stop the current turn before switching branches"
} else {
"another task sharing this checkout is currently running"
}));
}
s.busy = true;
guards.push(BusyGuard(other.clone()));
group.push(other.clone());
}
(group, guards)
};
let branch = branch.to_owned();
let (current, head_commit, outcome) =
vcs(&self.shared, move || worktree::checkout_branch(&cwd, &branch, create)).await?;
let switched = matches!(
outcome,
ide_vcs::CheckoutOutcome::Done
| ide_vcs::CheckoutOutcome::Conflicts { .. }
| ide_vcs::CheckoutOutcome::RestoreFailed { .. }
);
let mut updated = Vec::new();
if switched && isolation == Isolation::Worktree {
for member in &group {
let mut s = member.state.lock();
if s.task.isolation != Isolation::Worktree {
continue;
}
s.task.branch = Some(current.clone());
if !create {
s.task.base = Some(current.clone());
if let Some(ref commit) = head_commit {
s.task.base_commit = Some(commit.clone());
}
}
updated.push(member.clone());
}
}
drop(guards);
for member in updated {
member.persist();
member.emit_task();
}
Ok(outcome)
}
/// Forgets the task; with `remove_worktree` also deletes its worktree (the branch stays).
pub async fn delete(&self, id: &str, remove_worktree: bool) -> IdeResult<()> {
let task = self.task(id)?;
@@ -3339,8 +3501,14 @@ impl AgentManager {
s.task.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone()),
)
};
// A copy of the task (a fork) may work in the same worktree.
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
// A copy of the task (a fork) or a task reusing the worktree (even from a subdir) may
// work in the same physical worktree checkout root.
let target_root = worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &cwd);
let shared = self.tasks.read().values().any(|t| {
t.id != id
&& worktree::shared_worktree_root(&self.shared.paths.worktrees_dir, &t.state.lock().task.cwd.0)
== target_root
});
self.tasks.write().remove(id);
task.file.lock().deleted = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
@@ -3912,6 +4080,7 @@ impl Task {
/// The task from the parts of `file` other than its history, which `history` holds.
fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc<Shared>) -> Arc<Self> {
let mut task = file.task;
task.prompt_suggestions.clear();
config::add_client_options(&shared.base_id(&task.provider), &mut task.config);
let mut wanted = file.wanted;
let mut pending_model = file.pending_switch.or_else(|| {
@@ -6363,10 +6532,24 @@ impl Task {
.or(s.task.usage.take());
true
}
"prompt_suggestions_update" => {
if self.replaying.load(Ordering::Acquire) {
false
} else {
let next = prompt_suggestions_of(update);
let changed = *s.task.prompt_suggestions != next;
*s.task.prompt_suggestions = next;
changed
}
}
_ => false,
}
};
if task_changed {
if kind == "prompt_suggestions_update" {
self.emit_task();
return;
}
let (config, commands, model) = {
let s = self.state.lock();
(
@@ -7757,3 +7940,77 @@ fn sync_usage_context_size(task: &mut AgentTask) {
usage.size = tokens;
}
}
const MAX_PROMPT_SUGGESTIONS: usize = 5;
/// Extracts plain-text prompt suggestions from an ACP `prompt_suggestions_update` payload.
fn prompt_suggestions_of(update: &Value) -> Vec<String> {
let Some(items) = update.get("suggestions").and_then(Value::as_array) else {
return Vec::new();
};
let mut out = Vec::new();
for item in items {
let Some(blocks) = item.get("prompt").and_then(Value::as_array) else {
continue;
};
let mut text = String::new();
for block in blocks {
match block.get("type").and_then(Value::as_str) {
Some("text") => {
if let Some(s) = block.get("text").and_then(Value::as_str) {
text.push_str(s);
}
}
Some("resource_link") => {
let label = block
.get("name")
.and_then(Value::as_str)
.filter(|s| !s.trim().is_empty())
.or_else(|| block.get("uri").and_then(Value::as_str).and_then(|u| u.rsplit('/').next()));
if let Some(label) = label {
if !text.is_empty() && !text.ends_with(char::is_whitespace) {
text.push(' ');
}
text.push('@');
text.push_str(label.trim());
}
}
_ => {}
}
}
let trimmed = text.trim();
if !trimmed.is_empty() && !out.iter().any(|existing| existing == trimmed) {
out.push(trimmed.to_owned());
if out.len() >= MAX_PROMPT_SUGGESTIONS {
break;
}
}
}
out
}
#[cfg(test)]
mod prompt_suggestion_tests {
use super::prompt_suggestions_of;
use serde_json::json;
#[test]
fn parses_text_and_resource_link_prompt_suggestions() {
let update = json!({
"sessionUpdate": "prompt_suggestions_update",
"suggestions": [
{ "prompt": [{ "type": "text", "text": "Run the unit tests" }] },
{
"prompt": [
{ "type": "text", "text": "Explain " },
{ "type": "resource_link", "uri": "file:///repo/src/lib.rs", "name": "src/lib.rs" }
]
},
{ "prompt": [{ "type": "text", "text": " " }] },
{ "prompt": [{ "type": "text", "text": "Run the unit tests" }] }
]
});
assert_eq!(prompt_suggestions_of(&update), vec!["Run the unit tests", "Explain @src/lib.rs"]);
assert!(prompt_suggestions_of(&json!({ "suggestions": [] })).is_empty());
}
}
+8
Переглянути файл
@@ -204,6 +204,10 @@ pub struct AgentTask {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
/// Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[specta(optional)]
pub prompt_suggestions: Box<Vec<String>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -870,6 +874,10 @@ pub struct NewAgentTask {
pub isolation: Isolation,
/// Branch to start the worktree from; the current branch when `None`.
pub base: Option<String>,
/// Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only).
#[serde(default)]
#[specta(optional)]
pub worktree_path: Option<IpcPath>,
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
#[serde(default)]
pub mcp_overrides: BTreeMap<String, bool>,
+166
Переглянути файл
@@ -6684,6 +6684,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
@@ -6747,6 +6748,7 @@ async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex()
config: Vec::new(),
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
@@ -6797,6 +6799,7 @@ async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex()
config: Vec::new(),
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) }),
@@ -6825,6 +6828,7 @@ async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex()
config: Vec::new(),
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
@@ -6871,6 +6875,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
config: Vec::new(),
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::from([
@@ -7020,6 +7025,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
config: vec![AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() }],
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
@@ -7048,6 +7054,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
config: vec![],
isolation: Isolation::Local,
base: None,
worktree_path: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
@@ -7773,3 +7780,162 @@ async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() {
assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting);
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn shared_worktree_delete_preserves_checkout_across_subdirs() {
let repo = Checkout::new(Eol::Lf);
std::fs::create_dir_all(repo.dir.join("packages").join("app")).unwrap();
repo.write("packages/app/a.txt", "hello\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let root_task = mgr
.create(NewAgentTask {
provider: "claude".into(),
prompt: text("again"),
isolation: Isolation::Worktree,
idle: true,
..Default::default()
})
.await
.unwrap();
// Reuse the same worktree for a task rooted in a subdirectory of the repository.
let sub_task = mgr
.create(NewAgentTask {
project_root: Some(IpcPath(repo.dir.join("packages").join("app"))),
provider: "claude".into(),
prompt: text("again"),
isolation: Isolation::Worktree,
worktree_path: Some(root_task.cwd.clone()),
idle: true,
..Default::default()
})
.await
.unwrap();
assert_ne!(root_task.cwd.0, sub_task.cwd.0);
assert!(sub_task.cwd.0.starts_with(&root_task.cwd.0));
// Deleting the root task with `remove_worktree = true` MUST keep the shared worktree intact.
mgr.delete(&root_task.id, true).await.unwrap();
assert!(sub_task.cwd.0.exists(), "shared worktree was deleted while subdir sibling still exists");
// Deleting the final surviving task removes the worktree.
mgr.delete(&sub_task.id, true).await.unwrap();
assert!(!root_task.cwd.0.exists(), "worktree should be removed once no tasks share it");
}
#[tokio::test(flavor = "multi_thread")]
async fn checkout_branch_guards_archived_untrusted_busy_siblings_and_updates_base_commit() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.commit("init");
// Create a diverged branch with its own commit.
repo.git(&["checkout", "-q", "-b", "feat/diverged"]);
repo.write("diverged.txt", "from diverged\n");
repo.commit("diverged commit");
let diverged_head = worktree::head_of(&repo.dir).unwrap().1;
repo.git(&["checkout", "-q", "main"]);
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let wt_a = mgr
.create(NewAgentTask {
provider: "claude".into(),
prompt: text("again"),
isolation: Isolation::Worktree,
idle: true,
..Default::default()
})
.await
.unwrap();
let wt_b = mgr
.create(NewAgentTask {
provider: "claude".into(),
prompt: text("again"),
isolation: Isolation::Worktree,
worktree_path: Some(wt_a.cwd.clone()),
idle: true,
..Default::default()
})
.await
.unwrap();
let original_base_commit = wt_a.base_commit.clone();
// 1. Busy sibling blocks checkout on the shared worktree.
mgr.task(&wt_b.id).unwrap().state.lock().busy = true;
let err = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap_err();
assert!(err.to_string().contains("running"), "unexpected error: {err}");
mgr.task(&wt_b.id).unwrap().state.lock().busy = false;
// 2. Creating a new branch (`create == true`) updates `branch` on both siblings while preserving `base_commit`.
let out = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", true).await.unwrap();
assert_eq!(out, ide_vcs::CheckoutOutcome::Done);
let snap_a = mgr.task_snapshot(&wt_a.id).unwrap();
let snap_b = mgr.task_snapshot(&wt_b.id).unwrap();
assert_eq!(snap_a.branch.as_deref(), Some("feat/new-from-wt"));
assert_eq!(snap_b.branch.as_deref(), Some("feat/new-from-wt"));
assert_eq!(snap_a.base_commit, original_base_commit);
assert_eq!(snap_b.base_commit, original_base_commit);
// 3. Switching to an existing diverged branch (`create == false`) updates `branch`, `base`,
// and `base_commit` on both siblings so unrelated commits don't pollute Changes.
let out = mgr.checkout_branch(&wt_a.id, "feat/diverged", false).await.unwrap();
assert_eq!(out, ide_vcs::CheckoutOutcome::Done);
let snap_a = mgr.task_snapshot(&wt_a.id).unwrap();
let snap_b = mgr.task_snapshot(&wt_b.id).unwrap();
assert_eq!(snap_a.branch.as_deref(), Some("feat/diverged"));
assert_eq!(snap_b.branch.as_deref(), Some("feat/diverged"));
assert_eq!(snap_a.base.as_deref(), Some("feat/diverged"));
assert_eq!(snap_a.base_commit.as_deref(), Some(diverged_head.as_str()));
assert_eq!(snap_b.base_commit.as_deref(), Some(diverged_head.as_str()));
let grouped = mgr.grouped_changes(&wt_a.id).await.unwrap();
assert!(grouped.commits.is_empty(), "unrelated commits on switched branch leaked into Changes");
assert!(grouped.uncommitted.is_empty());
// 4. Archived task rejects branch checkout.
mgr.archive(&wt_a.id).unwrap();
let err = mgr.checkout_branch(&wt_a.id, "feat/new-from-wt", false).await.unwrap_err();
assert!(err.to_string().contains("archived"), "unexpected error: {err}");
// 5. Untrusted local repo rejects `checkout_branch`.
let local_task = mgr
.create(NewAgentTask {
provider: "claude".into(),
prompt: text("again"),
isolation: Isolation::Local,
idle: true,
..Default::default()
})
.await
.unwrap();
mgr.set_repo_trust_hook(Arc::new(|_| false));
let err = mgr.checkout_branch(&local_task.id, "feat/diverged", false).await.unwrap_err();
assert!(err.to_string().contains("not trusted"), "unexpected error: {err}");
}
#[tokio::test(flavor = "multi_thread")]
async fn rollback_clears_prompt_suggestions() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
{
let handle = mgr.task(&task.id).unwrap();
*handle.state.lock().task.prompt_suggestions = vec!["Follow up".into()];
}
assert_eq!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.as_slice(), ["Follow up"]);
mgr.rollback(&task.id, 0, false).await.unwrap();
assert!(mgr.task_snapshot(&task.id).unwrap().prompt_suggestions.is_empty());
}
+234 -10
Переглянути файл
@@ -287,6 +287,88 @@ pub(crate) fn create_for_task(
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
}
/// Validates and opens an existing managed worktree under `worktrees_dir` so a new task can
/// reuse it. Rejects paths outside `worktrees_dir`, non-directories, non-linked repositories,
/// or worktrees belonging to a different Git repository than `project_root`. Preserves any
/// project-relative subdirectory inside `project_root` just like [`create_for_task`].
pub(crate) fn reuse_for_task(project_root: &Path, worktrees_dir: &Path, worktree_path: &Path) -> IdeResult<Created> {
let canon_input = verify_confined_worktree_cwd(worktrees_dir, worktree_path)?;
if !canon_input.is_dir() {
return Err(IdeError::not_found(format!("worktree {} does not exist", worktree_path.display())));
}
let project_repo = repo_at(project_root)?;
let wt_repo = repo_at(&canon_input)?;
let [_, project_common] = project_repo.metadata_dirs()?;
let [wt_git_dir, wt_common] = wt_repo.metadata_dirs()?;
let canon_wt_git_dir = dunce::canonicalize(&wt_git_dir)?;
let canon_wt_common = dunce::canonicalize(&wt_common)?;
let canon_project_common = dunce::canonicalize(&project_common)?;
if canon_wt_git_dir == canon_wt_common || canon_wt_common != canon_project_common {
return Err(IdeError::invalid(format!(
"worktree {} is not a linked worktree of this repository",
worktree_path.display()
)));
}
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
if !canon_wt_root.starts_with(&canon_wt_dir)
|| canon_wt_root == canon_wt_dir
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
{
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
}
let canon_repo = dunce::canonicalize(project_repo.root())?;
let canon_proj = dunce::canonicalize(project_root)?;
let rel_subdir = if canon_proj != canon_repo {
canon_proj
.strip_prefix(&canon_repo)
.map_err(|_| {
IdeError::invalid(format!(
"{} is outside git repository {}",
canon_proj.display(),
canon_repo.display()
))
})?
.to_path_buf()
} else {
PathBuf::new()
};
let raw_cwd =
if rel_subdir.as_os_str().is_empty() { canon_wt_root.clone() } else { canon_wt_root.join(&rel_subdir) };
if !raw_cwd.is_dir() {
return Err(IdeError::invalid(format!(
"project folder {} does not exist in worktree {}",
rel_subdir.display(),
canon_wt_root.display()
)));
}
let canon_cwd = verify_confined_worktree_subdir(&canon_wt_root, &raw_cwd)?;
let (branch, base_commit) = head_of(&canon_cwd)?;
Ok(Created { path: canon_wt_root, cwd: canon_cwd, branch: branch.clone(), base: branch, base_commit })
}
/// Checks out (or creates and checks out) `branch` in `cwd` using Smart checkout so uncommitted
/// edits are stashed and restored across the switch. Returns the resulting branch name, HEAD
/// commit (when available), and checkout outcome.
pub(crate) fn checkout_branch(
cwd: &Path,
branch: &str,
create: bool,
) -> IdeResult<(String, Option<String>, ide_vcs::CheckoutOutcome)> {
let name = branch.trim();
if name.is_empty() {
return Err(IdeError::invalid("branch name cannot be empty"));
}
let repo = repo_at(cwd)?;
let options = ide_vcs::CheckoutOptions { mode: ide_vcs::CheckoutMode::Smart, ..Default::default() };
let outcome = repo.checkout_with(name, create, &options)?;
let (current, head_commit) = match head_of(cwd) {
Ok((b, commit)) => (b, Some(commit)),
Err(_) => (name.to_owned(), None),
};
Ok((current, head_commit, outcome))
}
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
let canon_cwd = dunce::canonicalize(target_cwd)?;
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
@@ -327,23 +409,60 @@ pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) ->
verify_confined_worktree_subdir(&canon_wt_root, cwd)
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Ok(rel) = path.strip_prefix(worktrees_dir)
/// Returns a canonical comparison key for the managed worktree checkout root containing `path`,
/// so two tasks pointing to different subdirs or path casings of the same worktree match.
pub(crate) fn shared_worktree_root(worktrees_dir: &Path, path: &Path) -> PathBuf {
let (root, _) = worktree_checkout_root(worktrees_dir, path);
let resolved = dunce::canonicalize(&root).unwrap_or(root);
normalize_path_key(resolved)
}
pub(crate) fn normalize_path_key(path: PathBuf) -> PathBuf {
#[cfg(windows)]
{
PathBuf::from(path.to_string_lossy().replace('/', "\\").to_lowercase())
}
#[cfg(not(windows))]
{
path
}
}
fn first_child_under(base: &Path, path: &Path) -> Option<PathBuf> {
if let Ok(rel) = path.strip_prefix(base)
&& let Some(first) = rel.components().next()
{
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
return Some(base.join(first));
}
#[cfg(windows)]
{
let base_comps: Vec<String> =
base.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
let path_comps: Vec<std::path::Component<'_>> = path.components().collect();
if path_comps.len() > base_comps.len()
&& base_comps
.iter()
.zip(path_comps.iter())
.all(|(a, b)| a == &b.as_os_str().to_string_lossy().to_lowercase())
{
return Some(base.join(path_comps[base_comps.len()]));
}
}
None
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Some(child) = first_child_under(worktrees_dir, path) {
return (child, worktrees_dir.to_path_buf());
}
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
if let Some(child) = first_child_under(&canon_wt_dir, path) {
return (child, canon_wt_dir);
}
if let Ok(canon_path) = dunce::canonicalize(path)
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
&& let Some(child) = first_child_under(&canon_wt_dir, &canon_path)
{
return (canon_wt_dir.join(first), canon_wt_dir);
return (child, canon_wt_dir);
}
}
(path.to_path_buf(), worktrees_dir.to_path_buf())
@@ -2314,4 +2433,109 @@ mod tests {
"symlink swap on worktree reuse must be rejected: {reuse_err}"
);
}
#[test]
fn reuse_for_task_validates_confinement_and_repo_membership() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let other = tmp.path().join("other");
std::fs::create_dir_all(&other).unwrap();
git(&other, &["init", "-q", "-b", "main"]);
std::fs::write(other.join("b.txt"), "world\n").unwrap();
git(&other, &["add", "."]);
git(&other, &["commit", "-q", "-m", "init other"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
// Reusing a managed worktree of the same repository succeeds and reports its live branch.
let reused = super::reuse_for_task(&repo, &wt_dir, &created.cwd).unwrap();
assert_eq!(reused.cwd, created.cwd);
assert_eq!(reused.branch, created.branch);
assert_eq!(reused.base_commit, created.base_commit);
// Paths outside `worktrees_dir` are rejected.
assert!(super::reuse_for_task(&repo, &wt_dir, &repo).is_err());
// Worktrees belonging to a different repository are rejected.
let other_wt = create_for_task(&other, &wt_dir, "task-2", "Other work", None).unwrap();
assert!(super::reuse_for_task(&repo, &wt_dir, &other_wt.cwd).is_err());
}
#[test]
fn checkout_branch_creates_and_switches_branches_in_worktree() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
let (branch, head_commit, outcome) = super::checkout_branch(&created.cwd, "feat/follow-up", true).unwrap();
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
assert_eq!(branch, "feat/follow-up");
assert_eq!(head_commit.as_deref(), Some(created.base_commit.as_str()));
let (back, back_commit, outcome) = super::checkout_branch(&created.cwd, &created.branch, false).unwrap();
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
assert_eq!(back, created.branch);
assert_eq!(back_commit.as_deref(), Some(created.base_commit.as_str()));
}
#[test]
fn reuse_for_task_resolves_subdir_consistently_and_rejects_standalone_repo() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("packages").join("app");
std::fs::create_dir_all(&sub).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(sub.join("a.txt"), "hello\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&sub, &wt_dir, "task-sub", "Subdir work", None).unwrap();
assert!(created.cwd.ends_with(Path::new("packages").join("app")));
// Passing either the worktree root or the subdir cwd resolves to the same subdir cwd.
let reused_from_root = super::reuse_for_task(&sub, &wt_dir, &created.path).unwrap();
assert_eq!(reused_from_root.cwd, created.cwd);
assert_eq!(reused_from_root.path, dunce::canonicalize(&created.path).unwrap());
let reused_from_sub = super::reuse_for_task(&sub, &wt_dir, &created.cwd).unwrap();
assert_eq!(reused_from_sub.cwd, created.cwd);
// `shared_worktree_root` matches root and subdir (and mixed casing on Windows).
assert_eq!(
super::shared_worktree_root(&wt_dir, &created.path),
super::shared_worktree_root(&wt_dir, &created.cwd)
);
#[cfg(windows)]
{
let upper = PathBuf::from(created.cwd.to_string_lossy().to_uppercase());
assert_eq!(
super::shared_worktree_root(&wt_dir, &created.path),
super::shared_worktree_root(&wt_dir, &upper)
);
}
// A standalone repo placed directly inside `worktrees_dir` (not a linked worktree) is rejected.
let standalone = wt_dir.join("standalone");
std::fs::create_dir_all(&standalone).unwrap();
git(&standalone, &["init", "-q", "-b", "main"]);
std::fs::write(standalone.join("x.txt"), "x\n").unwrap();
git(&standalone, &["add", "."]);
git(&standalone, &["commit", "-q", "-m", "standalone"]);
assert!(super::reuse_for_task(&standalone, &wt_dir, &standalone).is_err());
}
}
+1
Переглянути файл
@@ -1999,6 +1999,7 @@ impl AutomationService {
config: auto.config.clone(),
isolation,
base,
worktree_path: None,
mcp_overrides: auto.mcp_overrides.clone(),
skill_overrides: auto.skill_overrides.clone(),
memory_overrides: auto.memory_overrides.clone(),
+14
Переглянути файл
@@ -543,6 +543,19 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
project.agents.create(request).await
}
/// Checks out (or creates and checks out) a Git branch in an idle task's working directory.
#[command(trust = trusted)]
pub async fn agent_checkout_branch(
host: &Host,
window: &str,
task: String,
branch: String,
create: bool,
) -> IdeResult<ide_vcs::CheckoutOutcome> {
host.require_trust(window)?;
host.project(window)?.agents.checkout_branch(&task, &branch, create).await
}
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
#[command(trust = trusted)]
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
@@ -2941,6 +2954,7 @@ ide_command::domain!(
agent_automation_save,
agent_automation_set_enabled,
agent_automation_snapshot,
agent_checkout_branch,
agent_cli_update_check,
agent_commands,
agent_copilot_auth_status,
+2
Переглянути файл
@@ -2155,6 +2155,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo
prompt: AgentPrompt { text: "initial interactive turn".into(), files: vec![], images: vec![] },
isolation: Isolation::Local,
base: None,
worktree_path: None,
project_root: Some(IpcPath(root_a.clone())),
config: vec![],
idle: false,
@@ -3471,6 +3472,7 @@ async fn local_host_keep_alive_respects_keep_alive_setting_without_auto_start_se
prompt: AgentPrompt { text: "seed task".into(), files: vec![], images: vec![] },
isolation: Isolation::Local,
base: None,
worktree_path: None,
project_root: Some(IpcPath(root.clone())),
config: vec![],
idle: false,
+11 -11
Переглянути файл
@@ -665,7 +665,7 @@ test("supports SameTask rolling continuity, NeedsInput approval flow, and sideba
await expect(taskTree.locator('[data-tree-key="g:automated"]')).toHaveCount(0);
});
test("running composer replaces Send with Stop and keeps the Agents header focused", async ({
test("running composer keeps Stop dedicated alongside Queue and keeps the Agents header focused", async ({
workbench: page,
}, testInfo) => {
await page.setViewportSize({ width: 1280, height: 840 });
@@ -693,12 +693,10 @@ test("running composer replaces Send with Stop and keeps the Agents header focus
await page.getByRole("textbox", { name: "Message" }).fill("Follow up");
const queue = page.getByRole("button", { name: "Queue", exact: true });
await expect(queue).toBeEnabled();
await expect(stop).toHaveCount(0);
const after = (await queue.boundingBox())!;
await expect(stop).toBeEnabled();
const after = (await stop.boundingBox())!;
expect(after.x).toBeCloseTo(before.x, 0);
expect(after.width).toBeCloseTo(before.width, 0);
await page.getByRole("button", { name: "Message Actions" }).click();
await expect(page.getByRole("menuitem", { name: "Stop", exact: true })).toBeVisible();
});
test("opens persistent automation scheduling directly from a new agent task", async ({ workbench: page }) => {
@@ -713,9 +711,10 @@ test("opens persistent automation scheduling directly from a new agent task", as
const composer = page.getByRole("textbox", { name: "Message", exact: true });
await composer.fill("Review the weekly changelog");
const clock = page.getByRole("button", { name: "New Agent Automation…" });
await expect(clock).toBeVisible();
await clock.click();
await page.getByRole("button", { name: "Add Context", exact: true }).click();
const automate = page.getByRole("menuitem", { name: "New Agent Automation…", exact: true });
await expect(automate).toBeVisible();
await automate.click();
const dialog = page.getByRole("dialog", { name: "New Automation" });
await expect(dialog).toBeVisible();
await expect(dialog.getByLabel("Prompt Instructions")).toHaveValue("Review the weekly changelog");
@@ -740,11 +739,12 @@ test("schedules in-session Send Later, /loop recurring prompts, and /automate fr
const composerBox = page.getByRole("textbox", { name: "Message" });
await expect(composerBox).toBeVisible();
// 1) Type a message and schedule via the clock menu ("Send in 15 minutes")
// 1) Type a message and schedule via the Add Context › Schedule submenu ("Send in 15 minutes")
await composerBox.click();
await page.keyboard.type("Verify staging deployment health");
await page.getByRole("button", { name: "Schedule or Loop Message" }).click();
await page.getByRole("menuitem", { name: "Send in 15 minutes" }).click();
await page.getByRole("button", { name: "Add Context", exact: true }).click();
await page.getByRole("menuitem", { name: "Schedule or Loop Message", exact: true }).hover();
await page.getByRole("menuitem", { name: "Send in 15 minutes", exact: true }).click();
const strip = page.getByTestId("session-schedule-strip");
await expect(strip).toBeVisible();
+4 -2
Переглянути файл
@@ -117,7 +117,9 @@ test("erasing the @ filter restores the popup's fitting side and height", async
await editor.pressSequentially("a");
await expect(list.getByText("a.ts", { exact: true })).toBeVisible();
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
await expect.poll(() => geometry(list)).toMatchObject({ side: "above", inViewport: true, footerVisible: true });
const narrowed = await geometry(list);
expect(narrowed.height).toBeLessThan(initial.height);
await editor.press("Backspace");
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
await expect.poll(() => geometry(list)).toEqual(initial);
@@ -133,7 +135,7 @@ test("first-open @ results can grow and flip after asynchronous file search", as
await editor.press("ArrowUp");
await editor.pressSequentially("@");
await expect(list.getByRole("option").first()).toBeVisible();
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
await expect.poll(() => geometry(list)).toMatchObject({ side: "above", inViewport: true, footerVisible: true });
await expect(list.getByText("file0.ts", { exact: true })).toHaveCount(0);
await page.evaluate(() => window.dispatchEvent(new Event("test:release-composer-files")));
+1
Переглянути файл
@@ -17,6 +17,7 @@ agent_automation_snapshot always project_host bin
agent_base_text trusted project_host bindings async
agent_cancel always project_host bindings sync
agent_changes trusted project_host bindings async
agent_checkout_branch trusted project_host bindings async
agent_cli_install trusted project_host bindings async
agent_cli_update trusted project_host bindings async
agent_cli_update_check trusted project_host bindings async
+10
Переглянути файл
@@ -58,6 +58,8 @@ export const commands = {
"group" |
/** What the last turn changed, against the checkout as that turn started. */
"lastTurn" | null) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task, view })),
/** Checks out (or creates and checks out) a Git branch in an idle task's working directory. */
agentCheckoutBranch: (task: string, branch: string, create: boolean) => typedError<CheckoutOutcome, IdeError>(__TAURI_INVOKE("agent_checkout_branch", { task, branch, create })),
/** Installs a missing built-in CLI on the project host using the command shown in Agent Setup. */
agentCliInstall: (provider: string, approvedCommand: string, request: RequestId) => typedError<AgentCliInstallResult, IdeError>(__TAURI_INVOKE("agent_cli_install", { provider, approvedCommand, request })),
/** Installs the exact version offered if the selected installation still matches. */
@@ -5189,6 +5191,8 @@ export type AgentTask_Deserialize = {
recoveryWindowMins?: number | null,
/** Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`]. */
automation?: AgentTaskAutomation_Deserialize | null,
/** Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`. */
promptSuggestions?: string[],
};
export type AgentTask_Serialize = {
@@ -5254,6 +5258,8 @@ export type AgentTask_Serialize = {
recoveryWindowMins?: number | null,
/** Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`]. */
automation?: AgentTaskAutomation_Serialize | null,
/** Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`. */
promptSuggestions?: string[],
};
/** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */
@@ -13837,6 +13843,8 @@ export type NewAgentTask_Deserialize = {
isolation: Isolation,
/** Branch to start the worktree from; the current branch when `None`. */
base: string | null,
/** Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only). */
worktreePath?: IpcPath | null,
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */
mcpOverrides?: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode). */
@@ -13865,6 +13873,8 @@ export type NewAgentTask_Serialize = {
isolation: Isolation,
/** Branch to start the worktree from; the current branch when `None`. */
base: string | null,
/** Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only). */
worktreePath?: IpcPath | null,
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */
mcpOverrides: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode). */
+33
Переглянути файл
@@ -0,0 +1,33 @@
.picker {
display: inline-flex;
align-items: center;
min-width: 0;
max-width: 100%;
}
.trigger {
min-width: 0;
max-width: 100%;
color: inherit;
font-size: inherit;
}
.branchTrigger {
display: inline-flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
max-width: 100%;
}
.branchPrefix {
flex: none;
color: var(--fg-faint);
}
.branchName {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
+145
Переглянути файл
@@ -0,0 +1,145 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Branch } from "@/bindings";
import { commands } from "@/platform/ipc";
import { AgentBranchPicker } from "./AgentBranchPicker";
const branch = (name: string, opts: Partial<Branch> = {}): Branch => ({
name,
remote: false,
current: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
...opts,
});
describe("AgentBranchPicker", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("groups local and remote branches and switches locally with smart checkout", async () => {
const checkout = vi.spyOn(commands, "vcsCheckout").mockResolvedValue({
status: "ok",
data: { kind: "done" },
});
const onCheckedOut = vi.fn();
render(
<AgentBranchPicker
mode="checkout"
branches={[
branch("main", { current: true }),
branch("feat/ui"),
branch("origin/main", { remote: true }),
branch("origin/HEAD", { remote: true }),
]}
value="main"
onCheckedOut={onCheckedOut}
/>,
);
const trigger = screen.getByRole("button", { name: "Branch" });
expect(trigger).toHaveTextContent("main");
fireEvent.click(trigger);
const listbox = screen.getByRole("listbox");
expect(within(listbox).getByText("Local")).toBeVisible();
expect(within(listbox).getByText("Remote")).toBeVisible();
expect(within(listbox).queryByRole("option", { name: "origin/HEAD" })).not.toBeInTheDocument();
fireEvent.click(within(listbox).getByRole("option", { name: "feat/ui" }));
await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/ui"));
expect(checkout).toHaveBeenCalledWith(null, "feat/ui", false, { mode: "smart", diverged: null }, null);
});
it("strips the remote prefix when reporting a checked-out remote branch", async () => {
const checkout = vi.spyOn(commands, "vcsCheckout").mockResolvedValue({
status: "ok",
data: { kind: "done" },
});
const onCheckedOut = vi.fn();
render(
<AgentBranchPicker
mode="checkout"
branches={[branch("main", { current: true }), branch("origin/feat/remote", { remote: true })]}
value="main"
onCheckedOut={onCheckedOut}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Branch" }));
fireEvent.click(screen.getByRole("option", { name: "origin/feat/remote" }));
await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/remote"));
expect(checkout).toHaveBeenCalledWith(null, "origin/feat/remote", false, { mode: "smart", diverged: null }, null);
});
it("creates and checks out a new branch typed into the search field", async () => {
const checkout = vi.spyOn(commands, "vcsCheckout").mockResolvedValue({
status: "ok",
data: { kind: "done" },
});
const onCheckedOut = vi.fn();
render(
<AgentBranchPicker
mode="checkout"
branches={[branch("main", { current: true })]}
value="main"
onCheckedOut={onCheckedOut}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Branch" }));
const search = screen.getByPlaceholderText("Search…");
fireEvent.change(search, { target: { value: "feat/new-branch" } });
fireEvent.click(screen.getByRole("option", { name: 'Create branch "feat/new-branch"' }));
await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/new-branch"));
expect(checkout).toHaveBeenCalledWith(null, "feat/new-branch", true, { mode: "smart", diverged: null }, null);
});
it("shows base-branch semantics and supports remote branches without inline branch creation", () => {
const onSelectBase = vi.fn();
render(
<AgentBranchPicker
mode="base"
branches={[branch("main", { current: true }), branch("origin/main", { remote: true })]}
value="main"
onSelectBase={onSelectBase}
/>,
);
const trigger = screen.getByRole("button", { name: "Base branch" });
expect(trigger).toHaveTextContent("frommain");
fireEvent.click(trigger);
const search = screen.getByPlaceholderText("Search…");
fireEvent.change(search, { target: { value: "origin/main" } });
expect(screen.queryByRole("option", { name: /Create branch/ })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("option", { name: "origin/main" }));
expect(onSelectBase).toHaveBeenCalledExactlyOnceWith("origin/main");
});
it("switches a worktree session branch via agentCheckoutBranch", async () => {
const checkout = vi.spyOn(commands, "agentCheckoutBranch").mockResolvedValue({
status: "ok",
data: { kind: "done" },
});
const onCheckedOut = vi.fn();
render(
<AgentBranchPicker
mode="checkout"
taskId="task-42"
branches={[branch("agent/foo", { current: true }), branch("feat/bar")]}
value="agent/foo"
onCheckedOut={onCheckedOut}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Branch" }));
fireEvent.click(screen.getByRole("option", { name: "feat/bar" }));
await waitFor(() => expect(onCheckedOut).toHaveBeenCalledWith("feat/bar"));
expect(checkout).toHaveBeenCalledWith("task-42", "feat/bar", false);
});
});
+219
Переглянути файл
@@ -0,0 +1,219 @@
/**
* Searchable Git branch selector shared by the New Task page (Local checkout switching and
* Worktree base-branch selection) and active session status bars (Local & Worktree sessions).
*/
import clsx from "clsx";
import { useMemo, useState } from "react";
import type { Branch, CheckoutOutcome } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { Icon, Select, showContextMenu, type SelectOption } from "@/ui";
import { notifications } from "@/workbench/contributions";
import styles from "./AgentBranchPicker.module.css";
const CREATE_PREFIX = "__create__:";
/** Rejects whitespace and Git ref-name meta characters before offering inline branch creation. */
function isValidNewBranchName(name: string): boolean {
if (!name || name.startsWith("-") || name.startsWith("/") || name.endsWith("/") || name.endsWith(".")) return false;
if (name.includes("..") || name.includes("//") || name.includes("@{") || name.endsWith(".lock")) return false;
return !/[\s~^:?*[\\]/.test(name);
}
export interface AgentBranchPickerProps {
/** `"checkout"` switches or creates branches in place; `"base"` picks the base ref for a new worktree. */
mode: "checkout" | "base";
branches: readonly Branch[];
value: string | null;
/** Repository root for local checkouts (`null` = primary repository). */
repo?: string | null;
/** Active task id when switching inside an existing agent session. */
taskId?: string;
disabled?: boolean;
title?: string;
"aria-label"?: string;
className?: string;
onOpen?: () => void;
onSelectBase?: (branch: string) => void;
onCheckedOut?: (branch: string) => void;
}
export function AgentBranchPicker({
mode,
branches,
value,
repo = null,
taskId,
disabled = false,
title,
"aria-label": ariaLabel,
className,
onOpen,
onSelectBase,
onCheckedOut,
}: AgentBranchPickerProps) {
const tx = useTx();
const [switching, setSwitching] = useState(false);
const options = useMemo<SelectOption[]>(() => {
const local = branches.filter((b) => !b.remote);
const remote = branches.filter((b) => b.remote && !b.name.endsWith("/HEAD"));
const toOption = (b: Branch): SelectOption => ({
value: b.name,
label: b.name,
verbatim: true,
icon: "branch",
});
const out: SelectOption[] = [];
if (local.length > 0 && remote.length > 0) {
out.push({ value: "__local__", label: "Local", section: true }, ...local.map(toOption));
out.push({ value: "__remote__", label: "Remote", section: true }, ...remote.map(toOption));
} else {
out.push(...local.map(toOption), ...remote.map(toOption));
}
return out;
}, [branches]);
const reportOutcome = (target: string, outcome: CheckoutOutcome) => {
switch (outcome.kind) {
case "done":
onCheckedOut?.(target);
return;
case "conflicts":
onCheckedOut?.(target);
notifications().notify({
level: "warning",
title: tx("Switched branch with conflicts"),
body: outcome.files.join(", "),
});
return;
case "restoreFailed":
onCheckedOut?.(target);
notifications().notify({
level: "warning",
title: tx("Switched branch, but local changes could not be restored"),
body: outcome.message,
});
return;
case "checkedOutInWorktree":
notifications().notify({
level: "warning",
title: tx("Branch is already checked out in another worktree"),
body: outcome.path,
});
return;
case "localChanges":
case "untrackedFiles":
notifications().notify({
level: "warning",
title: tx("Local changes prevented switching branches"),
body: outcome.files.join(", "),
});
return;
case "localBranchAhead":
notifications().notify({
level: "warning",
title: tx("Local branch has commits not on the remote branch"),
body: `${outcome.local} → ${outcome.remote}`,
});
return;
}
};
const handleChange = (selected: string) => {
if (mode === "base") {
onSelectBase?.(selected);
return;
}
const create = selected.startsWith(CREATE_PREFIX);
const target = create ? selected.slice(CREATE_PREFIX.length) : selected;
if (!target || (!create && target === value) || switching) return;
const isRemote = !create && branches.some((b) => b.remote && b.name === target);
const localTarget = isRemote && target.includes("/") ? target.slice(target.indexOf("/") + 1) : target;
setSwitching(true);
const run = taskId
? call(commands.agentCheckoutBranch(taskId, target, create))
: call(commands.vcsCheckout(repo, target, create, { mode: "smart", diverged: null }, null));
void run
.then((outcome) => reportOutcome(localTarget, outcome))
.catch((e: unknown) =>
notifications().notify({
level: "error",
title: tx("Couldn't switch branch"),
body: String(e),
}),
)
.finally(() => setSwitching(false));
};
const customOption =
mode === "checkout"
? (query: string): SelectOption => {
const trimmed = query.trim();
const valid = isValidNewBranchName(trimmed);
return {
value: `${CREATE_PREFIX}${trimmed}`,
label: tx`Create branch "${trimmed}"`,
verbatim: true,
icon: "plus",
disabled: !valid,
};
}
: undefined;
const displayLabel = value ?? tx("Branch");
const triggerTitle = title ?? (mode === "base" ? tx`Base branch: ${displayLabel}` : tx`Branch: ${displayLabel}`);
return (
<span
className={clsx(styles.picker, className)}
onContextMenu={(e) => {
if (mode !== "checkout" || !value) return;
e.preventDefault();
e.stopPropagation();
showContextMenu(e, [
{
id: "copy-branch",
label: "Copy Branch Name",
icon: "copy",
run: () => void navigator.clipboard?.writeText(value),
},
...(!taskId
? [
{
id: "all-branches",
label: "All Branches…",
icon: "branch",
run: () => void executeAction("vcs.branches"),
},
]
: []),
]);
}}
>
<Select
variant="ghost"
className={styles.trigger}
aria-label={ariaLabel ?? (mode === "base" ? tx("Base branch") : tx("Branch"))}
title={triggerTitle}
disabled={disabled || switching}
searchable
value={value}
options={options}
customOption={customOption}
onOpen={onOpen}
onChange={handleChange}
renderValue={(current) => (
<span className={styles.branchTrigger}>
<Icon name="branch" size={13} />
{mode === "base" && <span className={styles.branchPrefix}>{tx("from")}</span>}
<span className={styles.branchName}>{current?.label ?? displayLabel}</span>
</span>
)}
/>
</span>
);
}
+195 -9
Переглянути файл
@@ -5,7 +5,7 @@
position: relative;
display: flex;
flex-direction: column;
border-radius: var(--radius-toolbar-button);
border-radius: var(--island-radius);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-popup);
cursor: text;
@@ -13,6 +13,9 @@
background var(--dur-fast) var(--ease),
box-shadow var(--dur-fast) var(--ease);
}
.composer:hover:not(:focus-within) {
box-shadow: inset 0 0 0 1px var(--border-strong);
}
.composer:focus-within {
background: var(--bg-field, var(--bg-button));
box-shadow:
@@ -26,11 +29,38 @@
0 0 0 1px var(--focus-ring);
}
/* The CodeMirror text field: the UI font, wrapping, growing with the text up to a limit. */
.fieldWrap {
position: relative;
min-width: 0;
}
.field {
position: relative;
min-width: 0;
/* Keep top breathing room outside the scroller so scrolled content never clips against the frame. */
padding-top: 7px;
padding-top: 10px;
}
.expandButton {
position: absolute;
top: 6px;
right: 6px;
z-index: 1;
opacity: 0.45;
transition: opacity var(--dur-fast) var(--ease);
}
.composer:hover .expandButton,
.composer:focus-within .expandButton,
.expanded .expandButton,
.expandButton:focus-visible {
opacity: 1;
}
.hasExpand .field :global(.cm-content) {
padding-right: 34px;
}
.expanded .field :global(.cm-scroller) {
max-height: min(65vh, 560px);
}
.expanded .field :global(.cm-content) {
min-height: min(40vh, 280px);
}
.field :global(.cm-editor) {
background: transparent;
@@ -52,8 +82,8 @@
must land in the editable text, or they focus the bare scroller and no caret appears.
A host sets --composer-min-height rather than overriding the rule, so stylesheet order can't undo it. */
.field :global(.cm-content) {
min-height: calc(var(--composer-min-height, 38px) - 7px);
padding: 2px 12px 4px;
min-height: calc(var(--composer-min-height, 44px) - 10px);
padding: 2px 12px 6px;
caret-color: var(--fg-strong);
white-space: pre-wrap;
overflow-wrap: anywhere;
@@ -69,6 +99,30 @@
.field :global(.cm-placeholder) {
color: var(--fg-faint);
}
.ghostWrap {
display: inline;
color: var(--fg-faint);
}
.ghostKey {
display: inline-flex;
align-items: center;
margin-left: 6px;
padding: 0 4px;
height: 16px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-family: var(--font-keys, inherit);
font-size: var(--fs-tiny, 11px);
line-height: 1;
vertical-align: 1px;
}
.ghostCount {
margin-left: 4px;
color: var(--fg-faint);
font-size: var(--fs-tiny, 11px);
font-variant-numeric: tabular-nums;
}
.field :global(.cm-cursor) {
border-left-color: var(--fg-strong);
}
@@ -94,9 +148,101 @@
flex-wrap: nowrap;
align-items: center;
gap: var(--space-1);
padding: 4px 6px 6px;
padding: 4px 8px 8px;
cursor: default;
}
.leading {
display: flex;
flex: none;
align-items: center;
gap: var(--space-0-5);
}
.leadingDivider {
flex: none;
width: 1px;
height: 14px;
margin: 0 2px;
background: var(--border);
}
.stashButton {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
height: var(--h-control);
padding: 0 5px;
border: 0;
border-radius: var(--radius-toolbar-button);
background: transparent;
color: var(--fg-secondary);
font-size: var(--fs-tiny, 11px);
font-variant-numeric: tabular-nums;
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.stashButton:hover,
.stashButton[aria-expanded="true"] {
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
.stashCount {
line-height: 1;
}
.stashPopup {
width: min(360px, calc(100vw - 24px));
padding: 6px 0;
}
.stashHeader {
padding: 2px 12px 6px;
color: var(--fg-secondary);
font-size: var(--fs-small);
font-weight: 600;
}
.stashList {
display: flex;
flex-direction: column;
max-height: 260px;
overflow-y: auto;
}
.stashRow {
display: flex;
align-items: flex-start;
gap: var(--space-1);
margin: 0 6px;
padding: 4px 4px 4px 8px;
border-radius: var(--radius-row);
}
.stashRow:hover {
background: var(--bg-list-selected);
}
.stashRestore {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--space-0-5);
padding: 0;
border: 0;
background: transparent;
color: var(--fg-strong);
font: inherit;
text-align: left;
cursor: pointer;
}
.stashPreview {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: var(--fs-small);
line-height: 1.35;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.stashMeta {
color: var(--fg-muted);
font-size: var(--fs-tiny, 11px);
}
.toolbar {
display: flex;
flex: 1 1 0;
@@ -113,10 +259,19 @@
}
.actions {
display: flex;
flex: none;
flex: 0 1 auto;
min-width: 0;
align-items: center;
gap: var(--space-1);
}
.actions > button {
flex: none;
}
@container agent-composer (max-width: 420px) {
.actions [data-composer-meters] {
display: none;
}
}
/* Attach/reference buttons share the send button's 24px footprint and chrome. */
/* Plain toolbar icons, framed only on hover like the rest of the IDE's toolbars. */
.composerButton {
@@ -139,6 +294,25 @@
flex: 0 1 auto;
min-width: 0;
}
.modelPrimary {
color: var(--fg-strong);
font-weight: 500;
}
.modelPrimarySplit {
padding-right: 4px;
}
.modelDot {
flex: none;
color: var(--fg-faint);
font-size: var(--fs-small);
line-height: 1;
user-select: none;
pointer-events: none;
}
.modelSettingsChip {
padding-left: 4px;
color: var(--fg-muted);
}
.configPicker > button {
min-width: 0;
max-width: 100%;
@@ -225,6 +399,12 @@
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
/* Active non-default collaboration / plan mode emphasis. */
.chipActive,
.chipActive:hover,
.chipActive[aria-expanded="true"] {
color: var(--accent);
}
.chipValue {
min-width: 0;
overflow: hidden;
@@ -401,7 +581,7 @@
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
padding: 8px 10px 0;
padding: 10px 12px 0;
cursor: default;
}
.image {
@@ -528,12 +708,18 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.selectionLines {
flex: none;
color: var(--fg-muted);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
/* `@` / `/` completion; Popup keeps the list within the viewport. */
/* `@` / `/` completion; aligned to the composer width so it never jitters or overflows narrow panes. */
.popup {
display: flex;
flex-direction: column;
width: min(560px, calc(100vw - 12px));
width: min(560px, var(--composer-popup-width, 560px), calc(100vw - 12px));
border-radius: var(--radius-popup);
cursor: default;
}
File diff suppressed because it is too large. Load diff
+39 -22
Переглянути файл
@@ -433,9 +433,15 @@ function ConfigPicker({
/>
);
}
const planActive =
!framed &&
!!value &&
((option.category === "collaboration_mode" && value.toLowerCase().includes("plan")) ||
(option.category === "mode" && modeIcon(value) === "todo"));
return (
<Select
variant={framed ? "framed" : "ghost"}
className={clsx(planActive && styles.chipActive)}
aria-label={option.name}
value={value}
placeholder={tx(option.name)}
@@ -448,7 +454,11 @@ function ConfigPicker({
: "lock"
: option.category === "mode"
? modeIcon(opt.value)
: undefined,
: option.category === "collaboration_mode"
? opt.value.toLowerCase().includes("plan")
? "todo"
: undefined
: undefined,
}))}
alignDetails
searchable={option.category === "model"}
@@ -525,11 +535,13 @@ function ModelPicker({
setOpen(which);
};
const hasSettingsChip = !unavailable && !modelRefresh?.loadingSettings && !!summary;
return (
<span ref={anchor} className={styles.modelControl}>
<button
type="button"
className={styles.chip}
className={clsx(styles.chip, styles.modelPrimary, hasSettingsChip && styles.modelPrimarySplit)}
aria-label={tx(model.name)}
aria-haspopup="dialog"
aria-expanded={open === "models"}
@@ -537,29 +549,33 @@ function ModelPicker({
onClick={() => toggle("models")}
>
<span className={styles.chipValue}>{modelName}</span>
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
{!hasSettingsChip && <Icon name="chevron-down" size={12} className={styles.chipChevron} />}
</button>
{!unavailable && modelRefresh?.loadingSettings ? (
<LoadingSettingsChip />
) : (
summary &&
!unavailable && (
<button
type="button"
className={styles.chip}
aria-label={tx`Model settings: ${summary}`}
title={
fullSummary && fullSummary !== summary
? `${tx`Configure ${modelName}…`} (${fullSummary})`
: tx`Configure ${modelName}…`
}
aria-haspopup="dialog"
aria-expanded={open === "settings"}
onClick={() => toggle("settings")}
>
<span className={styles.chipValue}>{summary}</span>
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
hasSettingsChip && (
<>
<span className={styles.modelDot} aria-hidden="true">
·
</span>
<button
type="button"
className={clsx(styles.chip, styles.modelSettingsChip)}
aria-label={tx`Model settings: ${summary}`}
title={
fullSummary && fullSummary !== summary
? `${tx`Configure ${modelName}…`} (${fullSummary})`
: tx`Configure ${modelName}…`
}
aria-haspopup="dialog"
aria-expanded={open === "settings"}
onClick={() => toggle("settings")}
>
<span className={styles.chipValue}>{summary}</span>
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
</>
)
)}
<Popup
@@ -757,6 +773,7 @@ function ModePicker({
const switchLabel = toggle.verbatimLabel ? toggle.label : tx(toggle.label);
const current = selected(mode, modeValue);
const on = allowAllValue === toggle.on;
const isPlan = !on && !!current?.value && modeIcon(current.value) === "todo";
const approvalText =
allowAll.category === "approval"
? (selected(allowAll, allowAllValue)?.name ?? (on ? tx("On") : tx("Off")))
@@ -769,7 +786,7 @@ function ModePicker({
<button
ref={anchor}
type="button"
className={styles.chip}
className={clsx(styles.chip, isPlan && styles.chipActive)}
aria-label={tx(mode.name)}
aria-haspopup="dialog"
aria-expanded={open}
+1 -1
Переглянути файл
@@ -46,7 +46,7 @@
align-items: center;
gap: var(--space-1);
min-width: 0;
padding: 0 6px;
padding: 0 8px;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
+4 -3
Переглянути файл
@@ -125,8 +125,8 @@ it.each([false, true])("opens automation scheduling from the New Task composer (
render(<HomeEditor docked={docked} />);
await chooseModel("small");
await chooseEffort("medium");
const schedule = screen.getByRole("button", { name: "New Agent Automation…" });
fireEvent.click(schedule);
fireEvent.click(screen.getByRole("button", { name: "Add Context" }));
fireEvent.click(screen.getByRole("menuitem", { name: "New Agent Automation…" }));
expect(useAutomations.getState().dialog).toMatchObject({
open: true,
prefillPrompt: "Check the project",
@@ -147,7 +147,8 @@ it("allows scheduling even with an empty New Task draft", () => {
updateComposer(HOME, { text: "" });
render(<HomeEditor />);
expect(screen.getByRole("button", { name: "Start" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "New Agent Automation…" }));
fireEvent.click(screen.getByRole("button", { name: "Add Context" }));
fireEvent.click(screen.getByRole("menuitem", { name: "New Agent Automation…" }));
expect(useAutomations.getState().dialog).toMatchObject({ open: true, prefillPrompt: "" });
closeAutomationDialog();
});
+206 -62
Переглянути файл
@@ -1,14 +1,15 @@
/** New Task page: one prompt box with the agent and its settings; where it works in a quiet line under it. */
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import type { AgentProbe, Branch } from "@/bindings";
import { useEffect, useMemo, useRef, useState } from "react";
import type { AgentProbe, AgentTask, Branch, Worktree } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import { Icon, IconButton, Select, T, tooltipAttrs, type SelectOption } from "@/ui";
import { Icon, Select, T, tooltipAttrs, type SelectOption } from "@/ui";
import { defaultTaskProject } from "./project";
import { maybeEditorService, useEditorShown, type EditorInput } from "@/workbench/contributions";
import { AgentBranchPicker } from "./AgentBranchPicker";
import { Composer } from "./Composer";
import { SubmitButton } from "./SubmitButton";
import { canSend, emptyDraft } from "./composerModel";
@@ -41,6 +42,74 @@ import { useAgentSettings } from "./agentSettings";
import { openAutomationDialog } from "./automationsModel";
import styles from "./Home.module.css";
const NO_WORKTREES: Worktree[] = [];
/** Normalizes separators, trailing slashes, and Windows drive-letter casing for worktree matching. */
export function normalizeWorktreePath(path: string): string {
const slashes = path.replace(/\\/g, "/").replace(/\/+$/, "");
return /^[A-Za-z]:(?:\/|$)/.test(slashes) ? `${slashes.slice(0, 1).toLowerCase()}${slashes.slice(1)}` : slashes;
}
function matchLiveWorktree(cwd: string, liveByPath: ReadonlyMap<string, Worktree>): Worktree | undefined {
const normCwd = normalizeWorktreePath(cwd);
const exact = liveByPath.get(normCwd);
if (exact) return exact;
for (const [wtRoot, wt] of liveByPath) {
if (normCwd.startsWith(`${wtRoot}/`)) return wt;
}
return undefined;
}
export interface ReusableWorktree {
cwd: string;
branch: string | null;
title: string;
updatedMs: number;
}
/**
* Picks up to 8 live reusable worktrees for `root`.
* When `worktreesLoaded` is true, strictly filters against `worktrees` (matching both exact
* worktree roots and subdirectory project checkouts across Windows/POSIX path formats) so
* deleted/pruned worktrees are never offered even when zero live secondary worktrees exist.
*/
export function selectReusableWorktrees(
tasks: Iterable<AgentTask>,
worktrees: readonly Worktree[],
worktreesLoaded: boolean,
root: string,
fallbackProjectRoot: string,
): ReusableWorktree[] {
const liveByPath = new Map(
worktrees.filter((w) => !w.main && !w.prunable).map((w) => [normalizeWorktreePath(w.path), w]),
);
const normRoot = root ? normalizeWorktreePath(root) : "";
const seen = new Set<string>();
const out: ReusableWorktree[] = [];
const candidates = [...tasks]
.filter((t) => {
if (t.isolation !== "worktree") return false;
const taskRoot = t.projectRoot ?? fallbackProjectRoot;
if (normRoot && taskRoot && normalizeWorktreePath(taskRoot) !== normRoot) return false;
return worktreesLoaded ? matchLiveWorktree(t.cwd, liveByPath) !== undefined : t.status !== "archived";
})
.sort((a, b) => (b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0));
for (const t of candidates) {
const live = matchLiveWorktree(t.cwd, liveByPath);
const key = live ? normalizeWorktreePath(live.path) : normalizeWorktreePath(t.cwd);
if (seen.has(key)) continue;
seen.add(key);
out.push({
cwd: t.cwd,
branch: live?.branch ?? t.branch ?? null,
title: t.title,
updatedMs: t.updatedMs ?? t.createdMs ?? 0,
});
if (out.length >= 8) break;
}
return out;
}
export function HomeEditor({ docked = false, input }: { docked?: boolean; input?: EditorInput }) {
const tx = useTx();
const txTemplate = useTxTemplate();
@@ -63,11 +132,18 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const [repoState, setRepoState] = useState<{
root: string;
branches: Branch[];
worktrees: Worktree[];
worktreesLoaded: boolean;
current: string | null;
isGit: boolean;
} | null>(null);
const branches = repoState?.root === root ? repoState.branches : [];
const current = repoState?.root === root ? repoState.current : null;
const [repoRefreshTick, setRepoRefreshTick] = useState(0);
const repoLoaded = repoState?.root === root;
const branches = repoLoaded ? repoState.branches : [];
const worktrees = repoLoaded ? repoState.worktrees : NO_WORKTREES;
const worktreesLoaded = repoLoaded && repoState.worktreesLoaded;
const current = repoLoaded ? repoState.current : null;
const tasks = useAgents((s) => s.tasks);
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
@@ -88,18 +164,40 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
if (!shown) return;
let live = true;
const repo = project?.workspace ? root : null;
void Promise.all([call(commands.vcsBranchInfo(repo)), call(commands.vcsBranches(repo))])
.then(([info, list]) => {
const loadWorktrees =
typeof commands.vcsWorktrees === "function"
? call(commands.vcsWorktrees(repo)).then(
(list) => ({ list, loaded: true }),
() => ({ list: [] as Worktree[], loaded: false }),
)
: Promise.resolve({ list: [] as Worktree[], loaded: false });
void Promise.all([call(commands.vcsBranchInfo(repo)), call(commands.vcsBranches(repo)), loadWorktrees])
.then(([info, list, wt]) => {
if (!live) return;
setRepoState({ root, branches: list.filter((b) => !b.remote), current: info.head, isGit: true });
setRepoState({
root,
branches: list,
worktrees: wt.list,
worktreesLoaded: wt.loaded,
current: info.head,
isGit: true,
});
})
.catch(() => {
if (live) setRepoState({ root, branches: [], current: null, isGit: false });
if (live)
setRepoState({
root,
branches: [],
worktrees: [],
worktreesLoaded: false,
current: null,
isGit: false,
});
});
return () => {
live = false;
};
}, [root, project?.workspace, shown]);
}, [root, project?.workspace, shown, repoRefreshTick]);
const provider = providers.find((p) => p.id === draft.provider) ?? providers[0];
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command, shown);
@@ -163,6 +261,19 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const isGit = gitOn && (project?.workspace ? repoState?.root === root && repoState.isGit : (project?.isGit ?? false));
const isolation = isGit ? draft.isolation : "local";
const base = draft.base ?? current;
const reusableWorktrees = useMemo(
() =>
isGit && repoLoaded
? selectReusableWorktrees(tasks.values(), worktrees, worktreesLoaded, root, project?.root ?? "")
: [],
[isGit, repoLoaded, tasks, worktrees, worktreesLoaded, root, project?.root],
);
const selectedWorktree =
isolation === "worktree" && draft.worktreePath
? (reusableWorktrees.find((w) => normalizeWorktreePath(w.cwd) === normalizeWorktreePath(draft.worktreePath!)) ??
null)
: null;
const isolationValue = selectedWorktree ? `wt:${selectedWorktree.cwd}` : isolation;
const canStart =
canSend(composer) &&
!!provider?.installed &&
@@ -180,7 +291,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
if (!canStart) return;
setStarting(true);
setError(null);
startTask(isolation, project?.workspace ? root : null)
startTask(isolation, project?.workspace ? root : null, selectedWorktree?.cwd ?? null)
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)))
.finally(() => setStarting(false));
};
@@ -221,15 +332,37 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
onOpenSkills={openSkills}
onOpenMemory={openMemory}
disabled={!canStart}
addMenu={
provider
addMenu={[
...(provider
? [
{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp },
{ id: "skills", label: "Skills…", icon: "skills", run: openSkills },
{ id: "memory", label: "Memory…", icon: "history", run: openMemory },
]
: undefined
}
: []),
{ kind: "separator" },
{
id: "automation",
label: "New Agent Automation…",
icon: "clock",
run: () =>
openAutomationDialog({
prefillPrompt: composer.text.trim(),
prefillSettings: {
projectRoot: root || null,
isolation,
base: isolation === "worktree" ? draft.base : null,
provider: provider?.id ?? draft.provider,
config: config.filter(
(o) => o.category !== "permissions" && o.category !== "approval" && o.category !== "mode",
),
mcpOverrides: draft.mcpOverrides,
skillOverrides: draft.skillOverrides,
memoryOverrides: draft.memoryOverrides,
},
}),
},
]}
toolbar={
<>
<span className={styles.agentPicker} {...tooltipAttrs(agentTitle, undefined, true)}>
@@ -298,36 +431,12 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
</>
}
actions={
<>
<IconButton
icon="clock"
size="small"
title="New Agent Automation…"
onClick={() =>
openAutomationDialog({
prefillPrompt: composer.text.trim(),
prefillSettings: {
projectRoot: root || null,
isolation,
base: isolation === "worktree" ? draft.base : null,
provider: provider?.id ?? draft.provider,
config: config.filter(
(o) => o.category !== "permissions" && o.category !== "approval" && o.category !== "mode",
),
mcpOverrides: draft.mcpOverrides,
skillOverrides: draft.skillOverrides,
memoryOverrides: draft.memoryOverrides,
},
})
}
/>
<SubmitButton
label={starting ? "Starting…" : "Start"}
pending={starting}
disabled={!canStart}
onClick={start}
/>
</>
<SubmitButton
label={starting ? "Starting…" : "Start"}
pending={starting}
disabled={!canStart}
onClick={start}
/>
}
/>
{/* Under the box: where the agent works. Project and checkout on the left, the branch on the right. */}
@@ -347,7 +456,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
}))}
onChange={(path) => {
setSelected(path);
updateDraft({ base: null });
updateDraft({ base: null, worktreePath: null });
}}
/>
) : projectLabel ? (
@@ -361,7 +470,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
variant="ghost"
aria-label="Isolation"
alignDetails
value={isolation}
value={isolationValue}
options={[
{
value: "local",
@@ -375,28 +484,63 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
icon: "branch",
detail: tx("away from your changes"),
},
...(reusableWorktrees.length > 0
? [
{ value: "__existing_worktrees__", label: "Existing worktrees", section: true },
...reusableWorktrees.map((wt) => ({
value: `wt:${wt.cwd}`,
label: wt.branch || basename(wt.cwd),
verbatim: true,
icon: "branch" as const,
detail: wt.title,
verbatimDetail: true,
})),
]
: []),
]}
renderValue={(o) => (o?.value === "worktree" ? tx("Worktree") : tx("Local"))}
onChange={(isolation) => updateDraft({ isolation, isolationChosen: true })}
renderValue={(o) => {
if (o?.value.startsWith("wt:")) {
return `${tx("Worktree")} · ${basename(o.value.slice(3))}`;
}
return o?.value === "worktree" ? tx("Worktree") : tx("Local");
}}
onChange={(next) => {
if (next.startsWith("wt:")) {
updateDraft({ isolation: "worktree", isolationChosen: true, worktreePath: next.slice(3) });
} else {
updateDraft({
isolation: next as "local" | "worktree",
isolationChosen: true,
worktreePath: null,
});
}
}}
/>
)}
{/* A folder that isn't a repository has no branch: the one Git found below it isn't where the agent runs. */}
{isolation === "local" && isGit && current && (
<span className={styles.project} title={current}>
<Icon name="branch" size={14} />
<span className={styles.label}>{current}</span>
</span>
)}
{isolation === "worktree" && branches.length > 0 && (
<Select
variant="ghost"
aria-label="Base branch"
searchable
value={base}
options={branches.map((b) => ({ value: b.name, label: b.name, verbatim: true, icon: "branch" }))}
onChange={(b) => updateDraft({ base: b === current ? null : b })}
<AgentBranchPicker
mode="checkout"
repo={project?.workspace ? root : null}
branches={branches}
value={current}
onCheckedOut={() => setRepoRefreshTick((n) => n + 1)}
/>
)}
{isolation === "worktree" && !selectedWorktree && branches.length > 0 && (
<AgentBranchPicker
mode="base"
branches={branches}
value={base}
onSelectBase={(b) => updateDraft({ base: b === current ? null : b })}
/>
)}
{isolation === "worktree" && selectedWorktree && (
<span className={styles.project} title={selectedWorktree.cwd}>
<Icon name="branch" size={13} />
<span className={styles.label}>{selectedWorktree.branch ?? basename(selectedWorktree.cwd)}</span>
</span>
)}
</div>
{/* Notes under the box don't take part in centring, so the box stays put as they come and go. */}
<div className={styles.notes}>
+87 -87
Переглянути файл
@@ -48,7 +48,7 @@
gap: var(--space-2);
min-width: 0;
height: var(--h-row);
padding: 0 6px;
padding: 0 12px;
overflow: hidden;
color: var(--fg-subtle);
font-size: var(--fs-small);
@@ -155,6 +155,29 @@
color: var(--fg-subtle);
}
/* Unified priority-ordered notice stack attached above the composer: consecutive rows join edge-to-edge. */
.bannerStack {
display: flex;
flex-direction: column;
}
.bannerStack:empty {
display: none;
}
.bannerStack > * {
border-radius: 0;
}
.bannerStack > * + * {
margin-top: -1px;
}
.bannerStack > :first-child {
border-top-left-radius: var(--island-radius);
border-top-right-radius: var(--island-radius);
}
.bannerStack > :last-child {
border-bottom-left-radius: var(--island-radius);
border-bottom-right-radius: var(--island-radius);
}
/* Inset session notices share the composer and permission card geometry. */
.banner {
flex: none;
@@ -163,10 +186,10 @@
align-items: center;
gap: var(--space-1) var(--space-2);
min-height: calc(var(--h-control) + var(--space-2) * 2);
padding: var(--space-1-5) var(--space-2);
padding: var(--space-1-5) var(--space-3);
background: var(--bg-feedback-warning);
border: 1px solid var(--border-feedback-warning);
border-radius: var(--radius-control);
border-radius: var(--island-radius);
color: var(--fg-strong);
}
.bannerNeutral {
@@ -538,87 +561,10 @@
overflow-wrap: anywhere;
}
/* In-place bubble editor: matches the Islands composer frame and keeps the text origin fixed. */
/* In-place bubble editor wrapper: preserves the replaced bubble's width on open. */
.editCard {
box-sizing: border-box;
display: flex;
flex-direction: column;
border-radius: var(--radius-tab);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-popup);
cursor: text;
transition:
background var(--dur-fast) var(--ease),
box-shadow var(--dur-fast) var(--ease);
}
.editCard:focus-within {
background: var(--bg-field, var(--bg-button));
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
@media (prefers-reduced-motion: reduce) {
.editCard {
transition: none;
}
}
.editField {
display: grid;
grid-template-columns: minmax(0, 1fr);
min-width: 0;
max-height: 280px;
}
.editMirror,
.editMessage {
grid-area: 1 / 1;
min-width: 0;
margin: 0;
padding: 6px 10px 4px;
border: 0;
font: inherit;
line-height: 1.4;
white-space: pre-wrap;
overflow-wrap: anywhere;
box-sizing: border-box;
}
.editMirror {
visibility: hidden;
pointer-events: none;
max-height: 280px;
overflow: hidden;
-webkit-user-select: none;
user-select: none;
}
.editMessage {
width: 100%;
height: 100%;
min-height: 0;
overflow-y: auto;
resize: none;
background: transparent;
color: var(--fg-strong);
caret-color: var(--fg-strong);
outline: none;
}
.editImages {
padding: 0 10px 4px;
}
.editImages .images {
margin-top: 0;
}
.editFooter {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 2px 6px 6px 10px;
cursor: default;
min-width: 0;
}
.editHint {
@@ -1407,30 +1353,81 @@
display: flex;
flex-direction: column;
gap: var(--space-0-5);
max-height: 180px;
overflow-y: auto;
}
.queued {
display: flex;
align-items: center;
align-items: flex-start;
gap: var(--space-1-5);
min-height: var(--h-field);
padding: 0 4px 0 8px;
padding: 4px 4px 4px 8px;
border-radius: var(--radius-row);
background: var(--bg-elev);
font-size: var(--agent-fs-ui, var(--fs-ui));
}
.queuedIcon {
flex: none;
margin-top: 4px;
}
.queuedBody {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.queuedText {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
line-height: 1.4;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.queuedAttachments {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
color: var(--fg-muted);
font-size: var(--fs-tiny, 11px);
font-variant-numeric: tabular-nums;
}
.queuedActions {
flex: none;
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
}
.queuedEditBanner {
display: flex;
align-items: center;
gap: var(--space-1-5);
min-height: calc(var(--h-control) + var(--space-1) * 2);
padding: var(--space-1) var(--space-1-5) var(--space-1) var(--space-3);
border: 1px solid var(--border-strong);
border-radius: var(--island-radius);
background: var(--bg-elev);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.queuedEditLabel {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.queuedEditHint {
color: var(--fg-muted);
}
/* Meters that don't fit wrap onto a hidden second row instead of being cut in half. */
.meters {
flex: 0 1 auto;
min-width: 0;
height: 22px;
height: var(--h-control);
overflow: hidden;
display: inline-flex;
flex-wrap: wrap;
@@ -2135,6 +2132,8 @@
display: flex;
flex-direction: column;
gap: var(--space-0-5);
max-height: 180px;
overflow-y: auto;
padding: 2px var(--space-2) 4px calc(var(--space-2) * 2);
font-size: var(--fs-small);
}
@@ -2270,12 +2269,13 @@
}
.meterButton {
composes: meter;
height: var(--h-control);
color: inherit;
font: inherit;
border: 0;
border-radius: var(--radius-control);
border-radius: var(--radius-toolbar-button);
background: transparent;
padding: 0 5px;
padding: 0 6px;
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@
align-items: center;
gap: var(--space-0-5);
min-width: 0;
padding: 0;
padding: 0 6px;
}
.pill {
+5
Переглянути файл
@@ -15,6 +15,11 @@
box-shadow: none;
}
.submit.stop:disabled {
background: transparent;
opacity: 0.65;
}
.submit.stop:not(:disabled):hover {
background: var(--bg-toolbar-hover);
}
+18 -5
Переглянути файл
@@ -1,20 +1,33 @@
import clsx from "clsx";
import { useTx } from "@/platform/i18n";
import { Button, Icon, Spinner, tooltipAttrs, type ButtonProps } from "@/ui";
import { Button, Icon, Spinner, tooltipAttrs, type ButtonProps, type IconName } from "@/ui";
import styles from "./SubmitButton.module.css";
export type SubmitButtonLabel = "Start" | "Starting…" | "Send" | "Queue" | "Steer" | "Send now" | "Stop" | "Stopping…";
function iconFor(label: SubmitButtonLabel): { name: IconName; size: number } {
if (label === "Stop" || label === "Stopping…") return { name: "stop", size: 16 };
if (label === "Queue") return { name: "list", size: 14 };
if (label === "Steer" || label === "Send now") return { name: "new-line", size: 14 };
return { name: "arrow-up", size: 14 };
}
export function SubmitButton({
label,
tooltip,
pending = false,
variant = "primary",
...props
}: Pick<ButtonProps, "disabled" | "onClick" | "variant"> & {
label: "Start" | "Starting…" | "Send" | "Queue" | "Stop";
label: SubmitButtonLabel;
tooltip?: string;
pending?: boolean;
}) {
const tx = useTx();
const name = tx(label);
const stop = label === "Stop";
const tip = tooltip ?? name;
const stop = label === "Stop" || label === "Stopping…";
const icon = iconFor(label);
return (
<Button
{...props}
@@ -22,9 +35,9 @@ export function SubmitButton({
size="small"
className={clsx(styles.submit, stop && styles.stop)}
aria-label={name}
{...tooltipAttrs(name)}
{...tooltipAttrs(tip)}
>
{pending ? <Spinner size={12} /> : <Icon name={stop ? "stop" : "arrow-up"} size={stop ? 16 : 14} />}
{pending ? <Spinner size={12} /> : <Icon name={icon.name} size={icon.size} />}
</Button>
);
}
+9 -3
Переглянути файл
@@ -173,11 +173,17 @@ describe("New Task composer commands", () => {
within(list)
.getAllByRole("option")
.map((o) => o.textContent),
).toEqual(["/compact", "/triage", "/review"]);
expect(list.textContent).toBe("Commands/compactSkills/triage/review");
).toEqual([
"/compact",
"/mcpConfigure MCP servers for this session",
"/skillsConfigure skills for this session",
"/memoryConfigure memory and instructions for this session",
"/triage",
"/review",
]);
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/compact");
fireEvent.keyDown(box, { key: "ArrowDown" });
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/triage");
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/mcp");
fireEvent.keyDown(box, { key: "ArrowUp" });
fireEvent.keyDown(box, { key: "ArrowUp" });
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/review");
+96 -1
Переглянути файл
@@ -70,7 +70,9 @@ export type Completion =
/** First (or second) argument of a leading `/command …` at `caret`. */
| { kind: "commandArg"; command: string; subcommand?: string; query: string; from: number; to: number }
/** A `!` command line's completion: an earlier command, or a path for the word at the caret. */
| { kind: "shell"; query: string; from: number; to: number; command: boolean };
| { kind: "shell"; query: string; from: number; to: number; command: boolean }
/** A `#` pull request reference (`#123` or `#auth`). */
| { kind: "pr"; query: string; from: number; to: number };
/**
* The `@file` or `/command` being typed at `caret`, if any; both may follow other text. In a
@@ -95,6 +97,16 @@ export function completionAt(text: string, caret: number): Completion | null {
to: caret,
};
}
const pr = /(^|\s)#([^\s#@]*)$/.exec(before);
if (pr) {
const query = pr[2]!;
return {
kind: "pr",
query,
from: caret - query.length - 1,
to: caret,
};
}
if (before.includes("\n")) return null;
const firstArg = /^\s*\/([A-Za-z][\w:.-]*)\s+([^\s]*)$/.exec(before);
if (firstArg) {
@@ -411,6 +423,89 @@ export function fencedBlocks(lines: readonly string[]): Fence[] {
return out;
}
/** Whether `pos` sits inside a fenced code block (including an unclosed fence being typed). */
export function insideFencedBlock(text: string, pos: number): boolean {
const lines = text.slice(0, pos).split("\n");
let openTicks = 0;
for (let i = 0; i < lines.length - 1; i++) {
const line = lines[i]!;
if (openTicks === 0) {
const m = /^(`{3,})[^`]*$/.exec(line);
if (m) openTicks = m[1]!.length;
} else if (new RegExp(`^\`{${openTicks},}\\s*$`).test(line)) {
openTicks = 0;
}
}
return openTicks > 0;
}
const UNORDERED_LIST_LINE = /^([ \t]*)([-*+])( \[[ xX]\])? (.*)$/;
const ORDERED_LIST_LINE = /^([ \t]*)(\d+)([.)]) (.*)$/;
function lineBoundsAt(text: string, pos: number): { start: number; end: number; line: string } {
const start = text.lastIndexOf("\n", Math.max(0, pos - 1)) + 1;
const nextNl = text.indexOf("\n", pos);
const end = nextNl < 0 ? text.length : nextNl;
return { start, end, line: text.slice(start, end) };
}
/**
* Markdown list continuation for a newline at `pos`: continues `- `, `* `, `- [ ] `, `1. ` on the
* next line, or exits the list by clearing the marker when the current item is empty.
*/
export function listContinuationAt(
text: string,
pos: number,
): { from: number; to: number; insert: string; caret: number } | null {
if (insideFencedBlock(text, pos)) return null;
const { start, line } = lineBoundsAt(text, pos);
const before = text.slice(start, pos);
const unordered = UNORDERED_LIST_LINE.exec(before);
if (unordered) {
const [, indent = "", bullet = "-", checkbox, body = ""] = unordered;
const after = text.slice(pos, lineBoundsAt(text, pos).end);
if (!body.trim() && !after.trim()) {
return { from: start, to: pos, insert: "", caret: start };
}
const prefix = checkbox ? `${indent}${bullet} [ ] ` : `${indent}${bullet} `;
const insert = `\n${prefix}`;
return { from: pos, to: pos, insert, caret: pos + insert.length };
}
const ordered = ORDERED_LIST_LINE.exec(before);
if (ordered) {
const [, indent = "", digits = "1", delim = ".", body = ""] = ordered;
const after = line.slice(pos - start);
if (!body.trim() && !after.trim()) {
return { from: start, to: pos, insert: "", caret: start };
}
const next = Number(digits) + 1;
const insert = `\n${indent}${next}${delim} `;
return { from: pos, to: pos, insert, caret: pos + insert.length };
}
return null;
}
/**
* Indents or outdents the line at `pos` when inside a fenced code block or on a Markdown list line.
* Returns `null` elsewhere so `Shift+Tab` keeps cycling the agent's mode.
*/
export function indentLineChange(
text: string,
pos: number,
outdent: boolean,
): { from: number; to: number; insert: string; caret: number } | null {
const { start, line } = lineBoundsAt(text, pos);
const inList = UNORDERED_LIST_LINE.test(line) || ORDERED_LIST_LINE.test(line);
if (!inList && !insideFencedBlock(text, pos)) return null;
if (!outdent) {
return { from: start, to: start, insert: " ", caret: pos + 2 };
}
const leading = /^( {2}|\t| )/.exec(line)?.[0];
if (!leading) return { from: start, to: start, insert: "", caret: pos };
const removed = leading.length;
return { from: start, to: start + removed, insert: "", caret: Math.max(start, pos - removed) };
}
/** `text` as a ``` block on its own lines, fenced longer than any run of backticks in it. */
export function fenced(text: string, info: string): string {
const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
+612
Переглянути файл
@@ -0,0 +1,612 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
import type { AgentConfigOption, AgentTask, PullRequestSummary } from "@/bindings";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
const ipcMocks = vi.hoisted(() => ({
ghPrList: vi.fn(),
agentEntries: vi.fn(),
findFiles: vi.fn(),
findDirs: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
ghPrList: (...args: unknown[]) => ipcMocks.ghPrList(...args),
agentEntries: (...args: unknown[]) => ipcMocks.agentEntries(...args),
findFiles: (...args: unknown[]) => ipcMocks.findFiles(...args),
findDirs: (...args: unknown[]) => ipcMocks.findDirs(...args),
},
};
});
import { Composer } from "./Composer";
import { ConfigPickers } from "./ConfigPickers";
import { normalizeWorktreePath, selectReusableWorktrees } from "./HomeEditor";
import { completionAt, emptyDraft, indentLineChange, insideFencedBlock, listContinuationAt } from "./composerModel";
import { setCaret, textOf, typeIn } from "./composerTesting";
import {
composerDraft,
deleteStashedPrompt,
flushComposerDrafts,
loadSavedComposerDrafts,
loadSavedStashes,
restoreStashedPrompt,
savedDraft,
setIdeContext,
stashComposerDraft,
updateComposer,
useAgents,
} from "./store";
import styles from "./Composer.module.css";
const ID = "composer-redesign-test";
beforeEach(() => {
localStorage.clear();
ipcMocks.ghPrList.mockReset().mockResolvedValue({ status: "ok", data: [] });
ipcMocks.agentEntries.mockReset().mockResolvedValue({ status: "ok", data: [] });
ipcMocks.findFiles.mockReset().mockResolvedValue({ status: "ok", data: [] });
ipcMocks.findDirs.mockReset().mockResolvedValue({ status: "ok", data: [] });
useEditorRegistry.setState({ active: null });
useAgents.setState({
tasks: new Map(),
entries: new Map(),
composers: new Map(),
queuedEdits: new Map(),
stashes: [],
ideContext: true,
});
});
afterEach(() => {
cleanup();
useEditorRegistry.setState({ active: null });
});
describe("composerModel markdown & code-block ergonomics", () => {
it("detects when the caret is inside an open or closed fenced block", () => {
expect(insideFencedBlock("plain text", 5)).toBe(false);
expect(insideFencedBlock("```ts\nconst x = 1;", 12)).toBe(true);
expect(insideFencedBlock("```ts\nconst x = 1;\n```\nafter", 26)).toBe(false);
});
it("continues unordered, checkbox, and ordered lists and exits on an empty item", () => {
expect(listContinuationAt("- first", 7)).toEqual({
from: 7,
to: 7,
insert: "\n- ",
caret: 10,
});
expect(listContinuationAt(" - [x] done", 12)).toEqual({
from: 12,
to: 12,
insert: "\n - [ ] ",
caret: 21,
});
expect(listContinuationAt("3. third", 8)).toEqual({
from: 8,
to: 8,
insert: "\n4. ",
caret: 12,
});
// Empty item clears the marker instead of adding another bullet.
expect(listContinuationAt("- first\n- ", 10)).toEqual({
from: 8,
to: 10,
insert: "",
caret: 8,
});
// Inside a fenced block, list continuation does not trigger.
expect(listContinuationAt("```md\n- item", 12)).toBeNull();
});
it("indents and outdents lines inside lists and fenced blocks, leaving plain text to cycle mode", () => {
expect(indentLineChange("plain line", 4, false)).toBeNull();
expect(indentLineChange("- item", 6, false)).toEqual({
from: 0,
to: 0,
insert: " ",
caret: 8,
});
expect(indentLineChange(" - item", 8, true)).toEqual({
from: 0,
to: 2,
insert: "",
caret: 6,
});
expect(indentLineChange("```ts\n x()", 11, true)).toEqual({
from: 6,
to: 8,
insert: "",
caret: 9,
});
});
});
describe("composer draft persistence", () => {
it("debounces keystroke persistence, flushes on demand/clear, and omits images", () => {
vi.useFakeTimers();
const setItemSpy = vi.spyOn(Storage.prototype, "setItem");
try {
updateComposer("task-1", { text: "k" });
updateComposer("task-1", { text: "ke" });
updateComposer("task-1", {
text: "keep this draft",
files: [{ path: "/p/a.ts", rel: "a.ts" }],
images: [{ mimeType: "image/png", data: "AAA", name: "shot.png" }],
});
// Rapid keystrokes must not synchronously write localStorage on every update.
expect(setItemSpy).not.toHaveBeenCalled();
vi.advanceTimersByTime(400);
expect(setItemSpy).toHaveBeenCalledTimes(1);
const loaded = loadSavedComposerDrafts();
expect(loaded.get("task-1")).toEqual({
text: "keep this draft",
files: [{ path: "/p/a.ts", rel: "a.ts" }],
images: [],
});
// Clearing flushes immediately without waiting for the debounce timer.
updateComposer("task-1", emptyDraft());
expect(loadSavedComposerDrafts().has("task-1")).toBe(false);
// Explicit flush persists immediately (e.g. on pagehide).
updateComposer("task-2", { text: "before unload" });
flushComposerDrafts();
expect(loadSavedComposerDrafts().get("task-2")?.text).toBe("before unload");
} finally {
setItemSpy.mockRestore();
vi.useRealTimers();
}
});
});
describe("Composer expand, raw paste, markdown editing, and selection lines", () => {
function renderBox(config: AgentConfigOption[] = [], onConfig = vi.fn()) {
return render(
<Composer
id={ID}
placeholder="Reply"
root="/p"
projectRoot="/p"
commands={[]}
history={[]}
config={config}
onConfig={onConfig}
onSubmit={vi.fn()}
/>,
);
}
it("toggles expanded editor height on click and collapses on Escape without losing text", () => {
renderBox();
const box = screen.getByRole("textbox", { name: "Message" });
expect(screen.queryByRole("button", { name: "Expand editor" })).toBeNull();
typeIn(box, "line 1\nline 2");
const expand = screen.getByRole("button", { name: "Expand editor" });
fireEvent.click(expand);
const collapse = screen.getByRole("button", { name: "Collapse editor" });
expect(collapse).toHaveAttribute("aria-pressed", "true");
expect(textOf(box)).toBe("line 1\nline 2");
fireEvent.keyDown(box, { key: "Escape" });
expect(screen.getByRole("button", { name: "Expand editor" })).toHaveAttribute("aria-pressed", "false");
expect(textOf(box)).toBe("line 1\nline 2");
});
it("bypasses smart paste transformations after Cmd/Ctrl+Shift+V", () => {
renderBox();
const box = screen.getByRole("textbox", { name: "Message" });
const longPaste = Array.from({ length: 35 }, (_, i) => `line ${i}`).join("\n");
fireEvent.keyDown(box, { key: "v", metaKey: true, ctrlKey: true, shiftKey: true });
const pasteEvent = new Event("paste", { bubbles: true, cancelable: true }) as ClipboardEvent;
Object.defineProperty(pasteEvent, "clipboardData", {
value: { files: [], types: ["text/plain"], getData: () => longPaste },
});
act(() => {
box.dispatchEvent(pasteEvent);
});
// Raw paste inserts plain text instead of wrapping 30+ lines in a ```text code card.
expect(textOf(box)).toBe(longPaste);
});
it("indents list items on Shift+Tab instead of cycling agent mode, and cycles mode on plain text", () => {
const onConfig = vi.fn();
const modeConfig: AgentConfigOption[] = [
{
id: "mode",
name: "Mode",
category: "mode",
description: null,
current: "ask",
via: "option",
values: [
{ value: "ask", name: "Ask", description: null },
{ value: "plan", name: "Plan", description: null },
],
},
];
renderBox(modeConfig, onConfig);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, " - item");
setCaret(box, 8);
fireEvent.keyDown(box, { key: "Tab", shiftKey: true });
expect(textOf(box)).toBe("- item");
expect(onConfig).not.toHaveBeenCalled();
typeIn(box, "plain text");
setCaret(box, 10);
fireEvent.keyDown(box, { key: "Tab", shiftKey: true });
expect(onConfig).toHaveBeenCalledWith("mode", "plan");
});
it("shows the active editor's selected line range on the Current File chip", () => {
const view = new EditorView({ doc: "a\nb\nc\nd\n" });
view.dispatch({ selection: { anchor: 2, head: 6 } });
act(() => setIdeContext(true));
act(() =>
useEditorRegistry.setState({
active: { view, ctx: { path: "/p/src/main.ts" } as TextEditorHandle["ctx"] },
}),
);
try {
renderBox();
const chip = screen.getByTitle("src/main.ts:2–3 is added to your request");
expect(chip).toHaveTextContent("main.ts2–3Current File");
} finally {
view.destroy();
}
});
});
describe("ConfigPickers active mode emphasis", () => {
it("emphasizes Plan mode with the single workbench accent while keeping Default quiet", () => {
const { rerender } = render(
<ConfigPickers
config={[
{
id: "collaboration_mode",
name: "Collaboration mode",
category: "collaboration_mode",
description: null,
current: "default",
via: "option",
values: [
{ value: "default", name: "Default", description: null },
{ value: "plan", name: "Plan", description: null },
],
},
]}
onChange={vi.fn()}
/>,
);
expect(screen.getByRole("button", { name: "Collaboration mode" }).className).not.toContain(styles.chipActive);
rerender(
<ConfigPickers
config={[
{
id: "collaboration_mode",
name: "Collaboration mode",
category: "collaboration_mode",
description: null,
current: "plan",
via: "option",
values: [
{ value: "default", name: "Default", description: null },
{ value: "plan", name: "Plan", description: null },
],
},
]}
onChange={vi.fn()}
/>,
);
expect(screen.getByRole("button", { name: "Collaboration mode" }).className).toContain(styles.chipActive);
});
});
describe("ACP prompt suggestions ghost text", () => {
it("renders ghost text with Tab hint when empty, cycles with Alt+], and accepts on Tab", () => {
const { container } = render(
<Composer
id={ID}
placeholder="Reply to the agent"
root="/p"
projectRoot="/p"
commands={[]}
history={[]}
config={[]}
suggestions={["Run the unit tests", "Explain the diff"]}
onSubmit={vi.fn()}
/>,
);
const ghost = container.querySelector("[data-prompt-suggestion]");
expect(ghost).not.toBeNull();
expect(ghost?.textContent).toContain("Run the unit tests");
expect(ghost?.textContent).toContain("Tab");
expect(ghost?.textContent).toContain("1/2");
const content = container.querySelector(".cm-content")!;
// Also matches macOS Option+] where e.key is "‘" and e.code is "BracketRight".
fireEvent.keyDown(content, { key: "‘", code: "BracketRight", altKey: true });
expect(container.querySelector("[data-prompt-suggestion]")?.textContent).toContain("Explain the diff");
expect(container.querySelector("[data-prompt-suggestion]")?.textContent).toContain("2/2");
// Option+[ cycles back via e.code "BracketLeft".
fireEvent.keyDown(content, { key: "“", code: "BracketLeft", altKey: true });
expect(container.querySelector("[data-prompt-suggestion]")?.textContent).toContain("Run the unit tests");
fireEvent.keyDown(content, { key: "]", altKey: true });
expect(container.querySelector("[data-prompt-suggestion]")?.textContent).toContain("Explain the diff");
fireEvent.keyDown(content, { key: "Tab" });
expect(composerDraft(ID).text).toBe("Explain the diff");
expect(container.querySelector("[data-prompt-suggestion]")).toBeNull();
});
});
describe("Prompt Stash", () => {
it("stashes, swaps on restore without losing current draft or images, persists, and deletes stashes", () => {
const img = { mimeType: "image/png", data: "AAA", name: "shot.png" };
updateComposer(ID, { text: "first draft", files: [{ path: "/p/a.ts", rel: "a.ts" }], images: [img] });
const first = stashComposerDraft(ID);
expect(first).not.toBeNull();
expect(composerDraft(ID).text).toBe("");
expect(composerDraft(ID).images).toEqual([]);
expect(loadSavedStashes()).toHaveLength(1);
updateComposer(ID, { text: "second draft" });
expect(restoreStashedPrompt(ID, first!.id)).toBe(true);
expect(composerDraft(ID).text).toBe("first draft");
expect(composerDraft(ID).images).toEqual([img]);
// The second draft was automatically stashed instead of overwritten.
expect(useAgents.getState().stashes).toHaveLength(1);
expect(useAgents.getState().stashes[0]!.text).toBe("second draft");
deleteStashedPrompt(useAgents.getState().stashes[0]!.id);
expect(useAgents.getState().stashes).toHaveLength(0);
expect(loadSavedStashes()).toHaveLength(0);
});
it("exposes Stash Draft in the Add Context menu and restores via the Stashed Prompts popover", async () => {
render(
<Composer
id={ID}
placeholder="Reply"
root="/p"
projectRoot="/p"
commands={[]}
history={[]}
config={[]}
onSubmit={vi.fn()}
/>,
);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "stash me");
expect(screen.queryByRole("button", { name: "Stashed Prompts" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Add Context" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Stash Draft" }));
expect(textOf(box)).toBe("");
const stashButton = screen.getByRole("button", { name: "Stashed Prompts" });
expect(stashButton).toHaveTextContent("1");
fireEvent.click(stashButton);
const dialog = await screen.findByRole("dialog", { name: "Stashed Prompts" });
fireEvent.click(within(dialog).getByRole("button", { name: /stash me/ }));
expect(textOf(box)).toBe("stash me");
expect(screen.queryByRole("button", { name: "Stashed Prompts" })).toBeNull();
});
});
describe("Composer # PR and @ Session completions", () => {
it("parses # PR triggers without interfering with @# symbols", () => {
expect(completionAt("check #12", 9)).toEqual({ kind: "pr", query: "12", from: 6, to: 9 });
expect(completionAt("check @#Foo", 11)).toEqual({ kind: "file", query: "#Foo", from: 6, to: 11 });
expect(completionAt("# Heading", 9)).toBeNull();
});
it("completes GitHub PRs on # and inserts the PR URL", async () => {
const pr: PullRequestSummary = {
number: 42,
title: "Redesign composer UX",
author: "thomas",
state: "open",
isDraft: false,
headRef: "composer_ux",
baseRef: "main",
createdAt: "2026-12-01T00:00:00Z",
updatedAt: "2026-12-05T00:00:00Z",
labels: [],
reviewDecision: null,
url: "https://github.com/openidea/idea/pull/42",
additions: 10,
deletions: 2,
};
ipcMocks.ghPrList.mockResolvedValue({ status: "ok", data: [pr] });
render(
<Composer
id={ID}
placeholder="Reply"
root="/p"
projectRoot="/p"
commands={[]}
history={[]}
config={[]}
onSubmit={vi.fn()}
/>,
);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "See #42");
const list = await screen.findByRole("listbox", { name: "Pull Requests" });
expect(within(list).getByRole("option")).toHaveTextContent("#42Redesign composer UX");
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("See https://github.com/openidea/idea/pull/42 ");
});
it("completes other sessions on @ and inserts a structured summary block", async () => {
const otherTask: AgentTask = {
id: "task-other",
title: "Fix OAuth refresh",
provider: "codex",
status: "ready",
isolation: "worktree",
model: null,
cwd: "/p",
branch: "fix/oauth-refresh",
base: "main",
baseCommit: null,
error: null,
createdMs: 1,
updatedMs: 100,
config: [],
commands: [],
usage: null,
queue: [],
};
useAgents.setState({
tasks: new Map([[otherTask.id, otherTask]]),
entries: new Map([
[
otherTask.id,
[
{ type: "user", text: "Refresh token expires early", attachments: [], steered: false },
{ type: "agent", text: "Updated token skew window to 60s." },
],
],
]),
});
render(
<Composer
id={ID}
placeholder="Reply"
root="/p"
projectRoot="/p"
commands={[]}
history={[]}
config={[]}
onSubmit={vi.fn()}
/>,
);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "@oauth");
const list = await screen.findByRole("listbox", { name: "Files" });
expect(within(list).getByRole("option")).toHaveTextContent("Fix OAuth refresh");
fireEvent.keyDown(box, { key: "Enter" });
await waitFor(() => expect(textOf(box)).toContain("Session: Fix OAuth refresh (fix/oauth-refresh)"));
expect(textOf(box)).toContain("Updated token skew window to 60s.");
});
it("skips inserting an async @session reference if the user edited the token while loading", async () => {
let resolveEntries!: (value: unknown) => void;
ipcMocks.agentEntries.mockReturnValue(
new Promise((resolve) => {
resolveEntries = resolve;
}),
);
const otherTask: AgentTask = {
id: "task-async",
title: "Async session",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/p",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 1,
updatedMs: 100,
config: [],
commands: [],
usage: null,
queue: [],
};
useAgents.setState({ tasks: new Map([[otherTask.id, otherTask]]) });
render(
<Composer
id={ID}
placeholder="Reply"
root="/p"
projectRoot="/p"
commands={[]}
history={[]}
config={[]}
onSubmit={vi.fn()}
/>,
);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "@async");
await screen.findByRole("listbox", { name: "Files" });
fireEvent.keyDown(box, { key: "Enter" });
// User deletes and replaces text before agentEntries resolves.
typeIn(box, "hi");
await act(async () => {
resolveEntries({ status: "ok", data: [{ type: "agent", text: "Late answer" }] });
});
expect(textOf(box)).toBe("hi");
});
});
describe("reusable worktree matching and persistence", () => {
const wtTask = (id: string, cwd: string, projectRoot: string, status: AgentTask["status"] = "ready"): AgentTask => ({
id,
title: id,
provider: "codex",
status,
isolation: "worktree",
model: null,
cwd,
branch: `agent/${id}`,
base: "main",
baseCommit: null,
projectRoot,
error: null,
createdMs: 1,
updatedMs: 100,
config: [],
commands: [],
usage: null,
queue: [],
});
it("never falls back to deleted worktrees when vcsWorktrees loaded empty, and matches Windows/subdir paths", () => {
const winTask = wtTask("t1", "C:\\Users\\me\\wt\\feat-1\\packages\\app", "C:\\repo\\packages\\app");
// Loaded empty live worktrees -> must return [] instead of offering deleted worktrees.
expect(selectReusableWorktrees([winTask], [], true, "c:/repo/packages/app", "")).toEqual([]);
// Live worktree with forward slashes and lowercase drive matches subdir task with backslashes.
const live = [
{ path: "c:/repo", branch: "main", head: "abc", main: true, detached: false, locked: false, prunable: false },
{
path: "c:/Users/me/wt/feat-1",
branch: "feat/live",
head: "def",
main: false,
detached: false,
locked: false,
prunable: false,
},
];
const matched = selectReusableWorktrees([winTask], live, true, "c:/repo/packages/app", "");
expect(matched).toHaveLength(1);
expect(matched[0]!.branch).toBe("feat/live");
expect(normalizeWorktreePath("C:\\wt\\a\\")).toBe("c:/wt/a");
// `savedDraft` never restores stale `worktreePath` across reloads.
expect(
savedDraft({ isolation: "worktree", isolationChosen: true, worktreePath: "/stale/wt" }).worktreePath,
).toBeNull();
});
});
+101 -2
Переглянути файл
@@ -362,7 +362,9 @@ describe.each(paths)("$name acknowledgement", (path) => {
describe("queued message actions", () => {
const item = (id: string) => ({ id, prompt: { text: id, files: [], images: [] } });
function showQueue() {
useAgents.setState({ tasks: new Map([["A", { ...task("A"), queue: [item("first"), item("second")] }]]) });
useAgents.setState({
tasks: new Map([["A", { ...task("A"), status: "running", queue: [item("first"), item("second")] }]]),
});
updateComposer("A", { text: "unsent draft" });
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
return within(screen.getByLabelText("Queued messages"));
@@ -399,7 +401,71 @@ describe("queued message actions", () => {
);
backend.unqueue.mockResolvedValue(ok(item("first")));
fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[0]!);
await waitFor(() => expect(composerDraft("A").text).toBe("first\nunsent draft"));
await waitFor(() => expect(composerDraft("A").text).toBe("first"));
expect(screen.getByText("Editing queued message")).toBeInTheDocument();
expect(screen.getByText(/Draft preserved/)).toBeInTheDocument();
backend.prompt.mockResolvedValue(ok(null));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(composerDraft("A").text).toBe("unsent draft"));
expect(backend.prompt).toHaveBeenCalledWith("A", item("first").prompt, false);
});
it("restores a preserved draft after sending an edited queued message and supports Alt+Up", async () => {
const withFiles = {
id: "second",
prompt: { text: "second queued", files: ["/project-a/a.ts"], images: [] },
};
useAgents.setState({
tasks: new Map([["A", { ...task("A"), queue: [item("first"), withFiles] }]]),
});
updateComposer("A", { text: "in progress draft" });
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
expect(screen.getByLabelText("1 attachment")).toBeInTheDocument();
backend.unqueue.mockResolvedValueOnce(ok(withFiles));
backend.prompt.mockResolvedValueOnce(ok(null));
const queue = within(screen.getByLabelText("Queued messages"));
fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[1]!);
await waitFor(() => expect(composerDraft("A").text).toBe("second queued"));
fireEvent.click(screen.getByRole("button", { name: "Send" }));
await waitFor(() => expect(composerDraft("A").text).toBe("in progress draft"));
// Alt+Up at the start of an empty composer edits the most recently queued item.
act(() => updateComposer("A", emptyDraft()));
backend.unqueue.mockResolvedValueOnce(ok(withFiles));
const box = screen.getByRole("textbox", { name: "Message" });
fireEvent.keyDown(box, { key: "ArrowUp", altKey: true });
await waitFor(() => expect(backend.unqueue).toHaveBeenCalledTimes(2));
expect(backend.unqueue).toHaveBeenLastCalledWith("A", "second");
await waitFor(() => expect(composerDraft("A").text).toBe("second queued"));
});
it("re-queues a prior edited item when opening a second queued item and avoids executing on idle cancel", async () => {
const queue = showQueue();
backend.unqueue.mockResolvedValueOnce(ok(item("first")));
fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[0]!);
await waitFor(() => expect(composerDraft("A").text).toBe("first"));
// Editing a second queued item while the first is open must re-queue the first item first.
backend.unqueue.mockResolvedValueOnce(ok(item("second")));
backend.prompt.mockResolvedValueOnce(ok(null));
fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[1]!);
await waitFor(() => expect(composerDraft("A").text).toBe("second"));
expect(backend.prompt).toHaveBeenCalledWith("A", item("first").prompt, false);
// If the task finishes (becomes ready/idle) while editing, Cancel must NOT start a new turn.
backend.prompt.mockClear();
act(() => {
useAgents.setState({
tasks: new Map([["A", { ...task("A"), status: "ready", queue: [] }]]),
});
});
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(composerDraft("A").text).toBe("unsent draft"));
expect(backend.prompt).not.toHaveBeenCalled();
expect(useAgents.getState().queuedEdits.has("A")).toBe(false);
});
});
@@ -462,4 +528,37 @@ describe("composer UI during submission", () => {
expect(textOf(screen.getByRole("textbox"))).toBe("next unsent task");
expect(useAgents.getState().history).toEqual(["submitted task"]);
});
it("does not leak stale draft.worktreePath when HomeEditor starts with no selected worktree and clears worktreePath after creation", async () => {
backend.create.mockResolvedValue(ok(task("created-wt")));
backend.close.mockResolvedValue(true);
const prevProject = useProject.getState().project;
useProject.setState({ project: { ...(prevProject ?? { root: "/project-a", name: "a" }), isGit: true } as never });
try {
useAgents.setState((s) => ({
draft: {
...s.draft,
isolation: "worktree",
isolationChosen: true,
base: "main",
worktreePath: "/stale/deleted-worktree",
},
}));
render(<HomeEditor />);
const box = screen.getByRole("textbox");
typeIn(box, "start in new worktree");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalledTimes(1));
expect(backend.create).toHaveBeenCalledWith(
expect.objectContaining({
isolation: "worktree",
base: "main",
worktreePath: null,
}),
);
expect(useAgents.getState().draft.worktreePath).toBeNull();
} finally {
useProject.setState({ project: prevProject });
}
});
});
+3 -2
Переглянути файл
@@ -4,6 +4,7 @@ import type { AgentEntry, AgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
import { EditorShownProvider } from "@/workbench/contributions";
import { SessionEditor } from "./SessionEditor";
import { textOf, typeIn } from "./composerTesting";
import { SESSION_KIND, sessionKey } from "./model";
import { focusedSession } from "./sessionFocus";
import { disconnect, useAgents } from "./store";
@@ -123,7 +124,7 @@ describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () =
const edit = screen.getAllByRole("button", { name: "Edit" })[0]!;
fireEvent.click(edit);
const draft = within(stream()).getByRole("textbox", { name: "Message" });
fireEvent.change(draft, { target: { value: "Unsent revision" } });
typeIn(draft, "Unsent revision");
draft.blur();
stream().scrollTop = stream().scrollHeight - stream().clientHeight;
fireEvent.scroll(stream());
@@ -134,7 +135,7 @@ describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () =
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
view.rerender(session(true));
expect(within(stream()).getByRole("textbox", { name: "Message" })).toHaveValue("Unsent revision");
expect(textOf(within(stream()).getByRole("textbox", { name: "Message" }))).toBe("Unsent revision");
});
it("keeps a text selection in the earlier rows while hidden", async () => {
+105 -15
Переглянути файл
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AgentEntry, AgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
const ipc = vi.hoisted(() => ({
rollback: vi.fn(),
@@ -356,7 +357,7 @@ describe("editing a sent agent message", () => {
fireEvent.keyDown(box, { key: "Enter", metaKey: true, isComposing: true });
fireEvent.keyDown(box, { key: "Enter", metaKey: true, keyCode: 229 });
expect(ipc.rollback).not.toHaveBeenCalled();
expect(textOf(box)).toBe("Edited message");
expect(textOf(box)).toBe("Edited message\n\n");
});
it("keeps the draft and shows a rollback failure beside it", async () => {
@@ -474,7 +475,7 @@ describe("editing a sent agent message", () => {
const editButton = await screen.findByRole("button", { name: "Edit" });
const bubble = container.querySelector<HTMLElement>(`.${styles.user}`)!;
vi.spyOn(bubble, "getBoundingClientRect").mockReturnValue(new DOMRect(100, 50, 272, 32));
const focusSpy = vi.spyOn(HTMLTextAreaElement.prototype, "focus");
const focusSpy = vi.spyOn(HTMLElement.prototype, "focus");
try {
await user.click(editButton);
const message = container.querySelector(`.${styles.userMessage}`)!;
@@ -484,10 +485,9 @@ describe("editing a sent agent message", () => {
const card = message.querySelector<HTMLElement>(`.${styles.editCard}`)!;
expect(card).toBeInTheDocument();
expect(card.style.getPropertyValue("--edit-width")).toBe("272px");
const box = screen.getAllByRole("textbox", { name: "Message" })[0] as HTMLTextAreaElement;
const box = screen.getAllByRole("textbox", { name: "Message" })[0]!;
expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });
expect(box.selectionStart).toBe("Original message".length);
expect(box.selectionEnd).toBe("Original message".length);
expect(textOf(box)).toBe("Original message");
} finally {
focusSpy.mockRestore();
}
@@ -522,7 +522,7 @@ describe("session composer submission", () => {
expect(textOf(box)).toBe("");
});
it("replaces disabled Send with Stop while working and switches the same button to Queue for a draft", async () => {
it("keeps Stop dedicated beside Queue while working and guards repeat clicks with Stopping…", async () => {
useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "running" }]]),
});
@@ -537,19 +537,109 @@ describe("session composer submission", () => {
expect(stop).toHaveAttribute("data-tooltip", "Stop");
expect(stop).toBeEnabled();
expect(screen.queryByRole("button", { name: "Queue" })).toBeNull();
fireEvent.click(stop);
await waitFor(() => expect(ipc.cancel).toHaveBeenCalledWith(task.id, null));
// Typing a draft shows Queue next to Stop without hiding Stop inside another menu.
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "Follow up");
expect(screen.getByRole("button", { name: "Queue" })).toBe(stop);
expect(stop).toHaveAttribute("data-tooltip", "Queue");
expect(stop).toBeEnabled();
expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Message Actions" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Stop" }));
await waitFor(() => expect(ipc.cancel).toHaveBeenCalledTimes(2));
const queue = screen.getByRole("button", { name: "Queue" });
expect(queue).toBeEnabled();
expect(screen.getByRole("button", { name: "Stop" })).toBe(stop);
// Holding Cmd/Ctrl flips Queue to Send now live, and tooltip points back to ↵ to queue (not inverted).
fireEvent.keyDown(window, { key: "Meta", metaKey: true, ctrlKey: true });
const sendNow = screen.getByRole("button", { name: "Send now" });
expect(sendNow).toBeEnabled();
expect(sendNow).toHaveAttribute("data-tooltip", "Send now (↵ to queue)");
fireEvent.keyUp(window, { key: "Meta", metaKey: false, ctrlKey: false });
expect(screen.getByRole("button", { name: "Queue" })).toBeEnabled();
// Clicking Stop transitions to disabled Stopping… and invokes cancel once.
fireEvent.click(stop);
await waitFor(() => expect(ipc.cancel).toHaveBeenCalledWith(task.id, null));
expect(screen.getByRole("button", { name: "Stopping…" })).toBeDisabled();
expect(textOf(box)).toBe("Follow up");
await screen.findByText("Original message");
});
it("preserves in-progress inline message edits when parent re-renders", async () => {
useAgents.setState({ entries: new Map([[task.id, entries]]) });
render(<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />);
const user = userEvent.setup();
await user.click(await screen.findByRole("button", { name: "Edit" }));
const editBox = screen.getAllByRole("textbox", { name: "Message" })[0]!;
typeIn(editBox, "Unsent in-progress edit");
expect(textOf(editBox)).toBe("Unsent in-progress edit");
// Trigger a parent re-render by updating task metadata and appending a new entry.
act(() => {
useAgents.setState({
tasks: new Map([[task.id, { ...task, updatedMs: 999 }]]),
entries: new Map([[task.id, [...entries, { type: "agent", text: "Streaming update" }]]]),
});
});
expect(textOf(editBox)).toBe("Unsent in-progress edit");
});
it("ignores bare Shift in modEnter mode and resets alternate modifier when task goes idle", () => {
useProject.setState({ settings: { agents: { sendWith: "modEnter", whileRunning: "queue" } } as never });
try {
useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "running" }]]),
});
render(<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "Draft");
expect(screen.getByRole("button", { name: "Queue" })).toBeEnabled();
// Bare Shift (typing capitals/symbols) must NOT flip Queue to Send now in modEnter mode.
fireEvent.keyDown(window, { key: "Shift", shiftKey: true, metaKey: false, ctrlKey: false });
expect(screen.getByRole("button", { name: "Queue" })).toBeEnabled();
expect(screen.queryByRole("button", { name: "Send now" })).toBeNull();
// Mod+Shift DOES flip Queue to Send now.
fireEvent.keyDown(window, { key: "Shift", shiftKey: true, metaKey: true, ctrlKey: true });
expect(screen.getByRole("button", { name: "Send now" })).toBeEnabled();
// Transitioning to idle and back to running without a keyup must NOT keep altHeld stuck true.
act(() => {
useAgents.setState({ tasks: new Map([[task.id, { ...task, status: "ready" }]]) });
});
act(() => {
useAgents.setState({ tasks: new Map([[task.id, { ...task, status: "running" }]]) });
});
expect(screen.getByRole("button", { name: "Queue" })).toBeEnabled();
} finally {
useProject.setState({ settings: null });
}
});
it("steers when clicking the submit button if whileRunning is steer and the agent supports it", async () => {
useProject.setState({ settings: { agents: { whileRunning: "steer" } } as never });
try {
useAgents.setState({
tasks: new Map([
[
task.id,
{
...task,
status: "running",
capabilities: { steer: true, images: true, backgroundTasks: false },
},
],
]),
});
ipc.prompt.mockResolvedValue({ status: "ok", data: null });
render(<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />);
const box = screen.getByRole("textbox", { name: "Message" });
typeIn(box, "Steer now");
const steerBtn = screen.getByRole("button", { name: "Steer" });
expect(screen.getByRole("button", { name: "Stop" })).toBeEnabled();
fireEvent.click(steerBtn);
await waitFor(() =>
expect(ipc.prompt).toHaveBeenCalledExactlyOnceWith(task.id, { text: "Steer now", files: [], images: [] }, true),
);
} finally {
useProject.setState({ settings: null });
}
});
});
+266 -87
Переглянути файл
@@ -6,23 +6,15 @@ import type {
AgentEntry,
AgentQueued,
AgentTask,
SendKey,
SessionSchedule_Serialize as SessionSchedule,
} from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx, useTx } from "@/platform/i18n";
import { isMacHost } from "@/platform/keymap";
import { isErrorKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import {
Button,
Icon,
IconButton,
Select,
T,
showContextMenu,
type IconName,
type MenuItem,
type SelectOption,
} from "@/ui";
import { Button, Icon, IconButton, Select, T, type IconName, type MenuItem, type SelectOption } from "@/ui";
import { notifications, useEditorShown } from "@/workbench/contributions";
import clsx from "clsx";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
@@ -53,6 +45,8 @@ import { useEffortFocus } from "../effortFocus";
import { age, interruptionBannerText, isBusy, isInterrupted, isWaitingForNetwork } from "../model";
import { asksInCard, type PermissionEntry } from "../permission";
import {
cancelQueuedEdit,
clearQueuedEdit,
dismissInterruptedTask,
stopTask,
editQueued,
@@ -71,12 +65,77 @@ import {
useAgentCommands,
useAgents,
} from "../store";
import { ContextMeter } from "./ContextMeter";
import { PermissionLine } from "./QuestionForm";
import { SessionStatus } from "./SessionStatus";
import { Elapsed } from "./WorkingRow";
import { useNow } from "./shared";
import { WorkingSubagents } from "./toolEntries";
const STOP_PENDING_MAX_MS = 10_000;
/** Ignore stray clicks on the button that replaces Stop right after cancellation lands. */
const STOP_LANDED_CLICK_GUARD_MS = 500;
type StopPhase = "pending" | "timedOut" | "landed" | null;
function useStopPhase(taskId: string, canStop: boolean) {
const [phase, setPhase] = useState<{ taskId: string; value: StopPhase }>({ taskId, value: null });
const stopPhase = phase.taskId === taskId ? phase.value : null;
if ((stopPhase === "pending" || stopPhase === "timedOut") && !canStop) {
setPhase({ taskId, value: "landed" });
} else if (stopPhase === "landed" && canStop) {
setPhase({ taskId, value: null });
}
const setStopPhase = (value: StopPhase) => setPhase({ taskId, value });
useEffect(() => {
if (stopPhase === "pending") {
const timer = window.setTimeout(
() => setPhase((p) => (p.taskId === taskId && p.value === "pending" ? { taskId, value: "timedOut" } : p)),
STOP_PENDING_MAX_MS,
);
return () => window.clearTimeout(timer);
}
if (stopPhase === "landed") {
const timer = window.setTimeout(
() => setPhase((p) => (p.taskId === taskId && p.value === "landed" ? { taskId, value: null } : p)),
STOP_LANDED_CLICK_GUARD_MS,
);
return () => window.clearTimeout(timer);
}
}, [taskId, stopPhase]);
return [stopPhase, setStopPhase] as const;
}
/** Tracks whether the alternate-send modifier (⌘/Ctrl in Enter mode, or ⌘⇧/Ctrl+Shift in Mod+Enter mode) is held. */
function useAlternateModifier(active: boolean, sendWith: SendKey): boolean {
const [held, setHeld] = useState(false);
const [prevActive, setPrevActive] = useState(active);
if (prevActive !== active) {
setPrevActive(active);
if (!active && held) setHeld(false);
}
useEffect(() => {
if (!active) return;
const matches = (e: KeyboardEvent) => {
const mod = isMacHost() ? e.metaKey : e.ctrlKey;
return sendWith === "enter" ? mod : mod && e.shiftKey;
};
const onKey = (e: KeyboardEvent) => setHeld(matches(e));
const reset = () => setHeld(false);
window.addEventListener("keydown", onKey);
window.addEventListener("keyup", onKey);
window.addEventListener("blur", reset);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("keyup", onKey);
window.removeEventListener("blur", reset);
};
}, [active, sendWith]);
return active && held;
}
const SESSION_WINDOW_OPTIONS: readonly SelectOption<string>[] = [
{ value: "default", label: "Default window" },
{ value: "0", label: "Off (ask)" },
@@ -387,9 +446,13 @@ export function SessionComposer({
}, [rawAgentCommands]);
const busy = isBusy(task.status);
const shellRunning = useAgents((s) => s.shellRunning.has(task.id));
const queuedEdit = useAgents((s) => s.queuedEdits.get(task.id) ?? null);
const canStop = busy || shellRunning;
const submitDisabled = !canSend(composer) || sending || configuring !== null || task.status === "archived";
const showStop = canStop && submitDisabled;
const [stopPhase, setStopPhase] = useStopPhase(task.id, canStop);
const hasDraft = canSend(composer);
const submitDisabled = !hasDraft || sending || configuring !== null || task.status === "archived";
const showStopButton = canStop || stopPhase === "pending" || stopPhase === "timedOut";
const showSubmitButton = !showStopButton || hasDraft;
// ↑ recalls this conversation's messages, newest first (excluding synthetic recovery turns).
const history = useMemo(
() => (entries ?? []).flatMap((e) => (e.type === "user" && !e.recovery && e.text ? [e.text] : [])).reverse(),
@@ -402,6 +465,39 @@ export function SessionComposer({
!!task.capabilities?.steer &&
task.status === "running" &&
(composer.images.length === 0 || !!task.capabilities.images);
const canAlternate = busy && (whileRunning === "queue" || steers);
const altHeld = useAlternateModifier(canAlternate && hasDraft, sendWith);
const defaultNow = steers;
const effectiveNow = busy && canAlternate ? defaultNow !== altHeld : false;
const submitLabel = !busy ? "Send" : effectiveNow ? (steers ? "Steer" : "Send now") : "Queue";
const primaryKey = sendWith === "enter" ? "↵" : isMacHost() ? "⌘↵" : "Ctrl+↵";
const alternateKey = sendWith === "enter" ? (isMacHost() ? "⌘↵" : "Ctrl+↵") : isMacHost() ? "⌘⇧↵" : "Ctrl+Shift+↵";
// When holding the alternate modifier, the other action is triggered by releasing back to the primary shortcut.
const altShortcut = altHeld ? primaryKey : alternateKey;
const submitTooltip = !busy
? tx("Send")
: !canAlternate
? tx("Queue")
: effectiveNow
? steers
? tx`Steer (${altShortcut} to queue)`
: tx`Send now (${altShortcut} to queue)`
: steers
? tx`Queue (${altShortcut} to steer)`
: tx`Queue (${altShortcut} to send now)`;
const onStop = () => {
if (stopPhase === "pending") return;
setStopPhase("pending");
void stopTask(task.id);
};
const onEditLastQueued = () => {
const last = task.queue.at(-1);
if (!last) return;
void editQueued(task.id, last.id).catch((e: unknown) => {
if (!isErrorKind(e, "outOfSync"))
notifications().notify({ level: "error", title: "Couldn't update the queue", body: String(e) });
});
};
const send = (now: boolean) => {
if (!canSend(composer) || sending || configChange.current || task.status === "archived") return;
const rawSlashName = /^\/([a-z0-9_-]+)/i.exec(composer.text.trim())?.[1]?.toLowerCase();
@@ -410,6 +506,7 @@ export function SessionComposer({
composer.images.length === 0 && !providerOwnsSlash ? parseScheduleSlashCommand(composer.text) : null;
if (parsedSchedule) {
if (parsedSchedule.kind === "automate") {
clearQueuedEdit(task.id);
updateComposer(task.id, emptyDraft());
openAutomationDialog({ prefillPrompt: parsedSchedule.prompt, prefillSettings: task });
return;
@@ -426,6 +523,7 @@ export function SessionComposer({
kind,
})
.then(async () => {
clearQueuedEdit(task.id);
updateComposer(task.id, emptyDraft());
await refreshAutomations();
})
@@ -480,22 +578,9 @@ export function SessionComposer({
const openMemory = () => setMemoryOpenRequest((n) => n + 1);
const shown = useEditorShown();
const effortAnnouncement = useEffortFocus(focusRoot, shown && task.status !== "archived", task.config, setOption);
const hasBanners = task.status === "archived" || isWaitingForNetwork(task) || isInterrupted(task) || !!queuedEdit;
return (
<div className={styles.composerArea}>
{task.status === "archived" && (
<div className={clsx(styles.banner, styles.bannerNeutral)}>
<span className={styles.bannerText}>
<T>This task is archived. Unarchive it to continue the conversation.</T>
</span>
<IconButton
icon="undo"
title="Unarchive"
onClick={() => void executeAction("agents.unarchiveTasks", [task.id])}
/>
</div>
)}
{isInterrupted(task) && <InterruptedBanner task={task} />}
{isWaitingForNetwork(task) && <WaitingForNetworkBanner task={task} />}
<Tray task={task} entries={entries}>
<WorkingSubagents entries={entries} onOpen={onOpenSubagent} />
<BackgroundTasks task={task} />
@@ -503,19 +588,40 @@ export function SessionComposer({
</Tray>
<SessionAssets task={task} entries={entries} head={head} onFocusComposer={() => setAssetFocus((n) => n + 1)} />
{taskSchedules.length > 0 && <SessionScheduleStrip schedules={taskSchedules} />}
{hasBanners && (
<div className={styles.bannerStack} data-composer-banner-stack="">
{task.status === "archived" && (
<div className={clsx(styles.banner, styles.bannerNeutral)}>
<span className={styles.bannerText}>
<T>This task is archived. Unarchive it to continue the conversation.</T>
</span>
<IconButton
icon="undo"
title="Unarchive"
onClick={() => void executeAction("agents.unarchiveTasks", [task.id])}
/>
</div>
)}
{isWaitingForNetwork(task) && <WaitingForNetworkBanner task={task} />}
{isInterrupted(task) && <InterruptedBanner task={task} />}
{queuedEdit && <QueuedEditBanner taskId={task.id} hasStashed={!!queuedEdit.stashed} />}
</div>
)}
<Composer
id={task.id}
focusRequest={focusRequest + assetFocus}
placeholder={
!busy
? "Reply to the agent"
: steers
? "Send into the agent's turn"
: whileRunning === "steer"
? "Queue a message for when the agent is done"
: sendWith === "enter"
? "Queue a message for when the agent is done (⌘↵ sends it now)"
: "Queue a message for when the agent is done (⌘⇧↵ sends it now)"
queuedEdit
? "Edit queued message"
: !busy
? "Reply to the agent"
: steers
? "Send into the agent's turn"
: whileRunning === "steer"
? "Queue a message for when the agent is done"
: sendWith === "enter"
? "Queue a message for when the agent is done (⌘↵ sends it now)"
: "Queue a message for when the agent is done (⌘⇧↵ sends it now)"
}
root={task.cwd}
projectRoot={task.projectRoot ?? project?.root ?? task.cwd}
@@ -524,14 +630,24 @@ export function SessionComposer({
config={task.config}
onConfig={setOption}
onSubmit={send}
onEditLastQueued={task.queue.length > 0 ? onEditLastQueued : undefined}
onOpenMcp={openMcp}
onOpenSkills={openSkills}
onOpenMemory={openMemory}
suggestions={!busy && !queuedEdit && task.status !== "archived" ? task.promptSuggestions : undefined}
disabled={task.status === "archived"}
addMenu={[
{ id: "mcp", label: "MCP Servers…", icon: "plugin", disabled: task.status === "archived", run: openMcp },
{ id: "skills", label: "Skills…", icon: "skills", disabled: task.status === "archived", run: openSkills },
{ id: "memory", label: "Memory…", icon: "history", disabled: task.status === "archived", run: openMemory },
{ kind: "separator" },
{
id: "schedule",
label: "Schedule or Loop Message",
icon: "clock",
disabled: task.status === "archived",
submenu: scheduleMenuItems(task, composer.text),
},
]}
toolbar={
<>
@@ -607,19 +723,29 @@ export function SessionComposer({
}
actions={
<>
<ScheduleSendButton
task={task}
draftText={composer.text}
stopInMenu={canStop && !showStop}
disabled={task.status === "archived"}
/>
<SubmitButton
label={showStop ? "Stop" : busy ? "Queue" : "Send"}
pending={!showStop && sending}
variant={canStop ? "secondary" : "primary"}
disabled={!showStop && submitDisabled}
onClick={() => (showStop ? void stopTask(task.id) : send(false))}
/>
<ComposerContextMeter task={task} onOpenMemory={task.status === "archived" ? undefined : openMemory} />
{showSubmitButton && (
<SubmitButton
label={submitLabel}
tooltip={submitTooltip}
pending={sending}
variant={busy && !effectiveNow ? "secondary" : "primary"}
disabled={submitDisabled}
onClick={() => {
if (stopPhase === "landed") return;
send(effectiveNow);
}}
/>
)}
{showStopButton && (
<SubmitButton
label={stopPhase === "pending" ? "Stopping…" : "Stop"}
pending={stopPhase === "pending"}
variant="secondary"
disabled={stopPhase === "pending"}
onClick={onStop}
/>
)}
</>
}
/>
@@ -629,7 +755,6 @@ export function SessionComposer({
changes={changes}
commits={commits}
onOpenChanges={onOpenChanges}
onOpenMemory={task.status === "archived" ? undefined : openMemory}
effortAnnouncement={effortAnnouncement}
/>
</div>
@@ -686,8 +811,45 @@ function Queue({ task }: { task: AgentTask }) {
);
}
function QueueRow({ task, item }: { task: string; item: AgentQueued }) {
function QueuedEditBanner({ taskId, hasStashed }: { taskId: string; hasStashed: boolean }) {
const [pending, setPending] = useState(false);
return (
<div className={styles.queuedEditBanner} role="status">
<Icon name="edit" size={12} className={styles.muted} />
<span className={styles.queuedEditLabel}>
<T>Editing queued message</T>
{hasStashed && (
<span className={styles.queuedEditHint}>
{" · "}
<T>Draft preserved</T>
</span>
)}
</span>
<Button
size="small"
variant="ghost"
disabled={pending}
onClick={() => {
setPending(true);
void cancelQueuedEdit(taskId)
.catch((e: unknown) =>
notifications().notify({ level: "error", title: "Couldn't restore the queued message", body: String(e) }),
)
.finally(() => setPending(false));
}}
>
<T>Cancel</T>
</Button>
</div>
);
}
function QueueRow({ task, item }: { task: string; item: AgentQueued }) {
const tx = useTx();
const [pending, setPending] = useState(false);
const fileCount = item.prompt.files.length;
const imageCount = item.prompt.images.length;
const attachmentCount = fileCount + imageCount;
async function run(action: (task: string, queued: string) => Promise<unknown>) {
if (pending) return;
setPending(true);
@@ -703,29 +865,63 @@ function QueueRow({ task, item }: { task: string; item: AgentQueued }) {
}
return (
<div className={styles.queued}>
<Icon name="pause" size={12} className={styles.muted} />
<span className={styles.queuedText} title={item.prompt.text}>
{item.prompt.text || <T>Image</T>}
<Icon name="pause" size={12} className={clsx(styles.muted, styles.queuedIcon)} />
<span className={styles.queuedBody}>
<span className={styles.queuedText} title={item.prompt.text}>
{item.prompt.text || <T>Image</T>}
</span>
{attachmentCount > 0 && (
<span
className={styles.queuedAttachments}
aria-label={attachmentCount === 1 ? tx("1 attachment") : tx`${attachmentCount} attachments`}
>
<Icon name="paperclip" size={11} />
{attachmentCount}
</span>
)}
</span>
<span className={styles.queuedActions}>
<IconButton icon="arrow-up" title="Send now" disabled={pending} onClick={() => void run(sendQueuedNow)} />
<IconButton icon="edit" title="Edit" disabled={pending} onClick={() => void run(editQueued)} />
<IconButton icon="close" title="Remove" disabled={pending} onClick={() => void run(removeQueued)} />
</span>
<IconButton icon="arrow-up" title="Send now" disabled={pending} onClick={() => void run(sendQueuedNow)} />
<IconButton icon="edit" title="Edit" disabled={pending} onClick={() => void run(editQueued)} />
<IconButton icon="close" title="Remove" disabled={pending} onClick={() => void run(removeQueued)} />
</div>
);
}
function ScheduleSendButton({
task,
draftText,
disabled,
stopInMenu,
}: {
task: AgentTask;
draftText: string;
disabled?: boolean;
stopInMenu: boolean;
}) {
const tx = useTx();
/**
* Compact context-window meter tucked into the composer's right rail; clicking it opens
* the unified Session Info popover with cost, context breakdown, turn tokens and limits.
*/
function ComposerContextMeter({ task, onOpenMemory }: { task: AgentTask; onOpenMemory?: () => void }) {
const show = useProject((s) => s.settings?.agents);
const busy = isBusy(task.status);
const now = useNow(60_000);
const usage = show?.showContextUsage !== false ? task.usage : null;
const reported = useAgents((s) => s.limits.get(task.provider));
const limits = show?.showUsageLimits !== false ? (reported ?? []) : [];
const cost = show?.showCost === true ? (task.usage?.cost ?? null) : null;
const turnTokens = show?.showContextUsage !== false && !busy ? (task.stats?.tokens ?? null) : null;
if (!usage && limits.length === 0 && !cost && !turnTokens) return null;
return (
<span className={styles.meters} data-composer-meters="">
<ContextMeter
key={task.id}
task={task}
usage={usage}
limits={limits}
cost={cost}
turnTokens={turnTokens}
now={now}
onOpenMemory={onOpenMemory}
/>
</span>
);
}
function scheduleMenuItems(task: AgentTask, draftText: string): MenuItem[] {
const hasDraft = !!draftText.trim();
const scheduleDelayed = async (delaySecs: number) => {
@@ -768,13 +964,7 @@ function ScheduleSendButton({
}
};
const items: MenuItem[] = [
...(stopInMenu
? [
{ kind: "item" as const, id: "stop", label: "Stop", icon: "stop", run: () => void stopTask(task.id) },
{ kind: "separator" as const },
]
: []),
return [
{
kind: "item",
id: "later-15m",
@@ -835,17 +1025,6 @@ function ScheduleSendButton({
},
},
];
return (
<IconButton
icon="clock"
size="small"
title={tx(stopInMenu ? "Message Actions" : "Schedule or Loop Message")}
aria-label={tx(stopInMenu ? "Message Actions" : "Schedule or Loop Message")}
disabled={disabled}
onClick={(e) => showContextMenu(e, items)}
/>
);
}
function SessionScheduleStrip({ schedules }: { schedules: readonly SessionSchedule[] }) {
+64 -48
Переглянути файл
@@ -1,16 +1,18 @@
import type { AgentChange, AgentCommit, AgentTask } from "@/bindings";
import { useCallback, useEffect, useRef, useState } from "react";
import type { AgentChange, AgentCommit, AgentTask, Branch } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import clsx from "clsx";
import { Icon, IconButton, showContextMenu, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { AgentBranchPicker } from "../AgentBranchPicker";
import styles from "../Session.module.css";
import { ContextMeter } from "./ContextMeter";
import { formatSentAt } from "../conversation";
import { branchLabel, hasTaskTerminal, isBusy, statusLabel } from "../model";
import { agentIcon, useAgents } from "../store";
import { taskMenu } from "../taskActions";
import { useNow } from "./shared";
/** The task's terminal, at the end of its status line. */
function StatusActions({ task }: { task: AgentTask }) {
@@ -39,7 +41,6 @@ export function SessionStatus({
commits,
effortAnnouncement,
onOpenChanges,
onOpenMemory,
}: {
task: AgentTask;
head: string | null;
@@ -47,7 +48,6 @@ export function SessionStatus({
commits: readonly AgentCommit[];
effortAnnouncement: string | null;
onOpenChanges: () => void;
onOpenMemory?: () => void;
}) {
const tx = useTx();
const icon = useAgents((s) => agentIcon(task.provider, s.providers));
@@ -56,7 +56,31 @@ export function SessionStatus({
const projectRoot = task.projectRoot ?? project?.root ?? null;
const projectName = project?.workspace && projectRoot ? basename(projectRoot) : project?.name;
const local = task.isolation !== "worktree";
const branch = local ? head : branchLabel(task.branch) || null;
const busy = isBusy(task.status);
const rawBranch = local ? head : branchLabel(task.branch) || null;
const [checkedOut, setCheckedOut] = useState<{ taskId: string; raw: string | null; branch: string } | null>(null);
const branch =
checkedOut && checkedOut.taskId === task.id && checkedOut.raw === rawBranch ? checkedOut.branch : rawBranch;
const [branchesState, setBranchesState] = useState<{ repo: string | null; list: Branch[] }>({
repo: project?.workspace ? projectRoot : null,
list: [],
});
const loadBranchesSeq = useRef(0);
const currentRepo = project?.workspace ? projectRoot : null;
useEffect(() => {
loadBranchesSeq.current += 1;
}, [currentRepo]);
const branches = branchesState.repo === currentRepo ? branchesState.list : [];
const loadBranches = useCallback(() => {
if (typeof commands.vcsBranches !== "function") return;
const seq = ++loadBranchesSeq.current;
const repo = currentRepo;
void call(commands.vcsBranches(repo))
.then((list) => {
if (loadBranchesSeq.current === seq) setBranchesState({ repo, list });
})
.catch(() => undefined);
}, [currentRepo]);
const pickedModel = task.status !== "archived" && task.config.some((o) => o.category === "model");
const added = changes?.reduce((n, c) => n + c.added, 0) ?? 0;
const removed = changes?.reduce((n, c) => n + c.removed, 0) ?? 0;
@@ -89,16 +113,39 @@ export function SessionStatus({
</span>
)}
{branch && (
// A local task's branch is the project's, which the branch widget shows.
<span className={clsx(styles.fact, local && styles.shownElsewhere)} title={branch}>
<Icon name="branch" size={13} />
<span className={styles.factText}>{branch}</span>
// A local task's branch is the project's; both local and worktree sessions can switch branches when idle.
<span className={clsx(styles.fact, local && styles.shownElsewhere)}>
<AgentBranchPicker
mode="checkout"
branches={branches}
value={branch}
repo={local ? (project?.workspace ? projectRoot : null) : null}
taskId={local ? undefined : task.id}
disabled={busy || task.status === "archived"}
title={
busy
? tx("Stop the current turn to switch branches")
: local
? tx`Branch: ${branch}`
: tx`Worktree branch: ${branch}`
}
onOpen={loadBranches}
onCheckedOut={(next) => setCheckedOut({ taskId: task.id, raw: rawBranch, branch: next })}
/>
</span>
)}
{!local && (
<span className={styles.fact}>
<button
type="button"
className={styles.statusChip}
title={tx`Worktree: ${task.cwd} (click to copy path)`}
onClick={() => {
void navigator.clipboard?.writeText(task.cwd);
notifications().notify({ level: "info", title: tx("Copied worktree path"), body: task.cwd });
}}
>
<T>Worktree</T>
</span>
</button>
)}
{task.model && !pickedModel && <span className={styles.fact}>{task.model}</span>}
{!!task.stats?.compressions && (
@@ -145,43 +192,12 @@ export function SessionStatus({
)}
</span>
)}
<span className={styles.statusMeters}>
<Meters task={task} onOpenMemory={onOpenMemory} />
{hasTaskTerminal(task, projectRoot) && <StatusActions task={task} />}
</span>
{hasTaskTerminal(task, projectRoot) && (
<span className={styles.statusMeters}>
<StatusActions task={task} />
</span>
)}
</span>
</div>
);
}
/**
* Compact context-window meter in the status bar; clicking it opens the unified
* Session Info popover with cost, context breakdown, last-turn tokens and usage limits.
*/
function Meters({ task, onOpenMemory }: { task: AgentTask; onOpenMemory?: () => void }) {
const show = useProject((s) => s.settings?.agents);
const busy = isBusy(task.status);
const now = useNow(60_000);
const usage = show?.showContextUsage !== false ? task.usage : null;
const reported = useAgents((s) => s.limits.get(task.provider));
const limits = show?.showUsageLimits !== false ? (reported ?? []) : [];
const cost = show?.showCost === true ? (task.usage?.cost ?? null) : null;
const turnTokens = show?.showContextUsage !== false && !busy ? (task.stats?.tokens ?? null) : null;
if (!usage && limits.length === 0 && !cost && !turnTokens) return null;
return (
<span className={styles.meters}>
<ContextMeter
key={task.id}
task={task}
usage={usage}
limits={limits}
cost={cost}
turnTokens={turnTokens}
now={now}
onOpenMemory={onOpenMemory}
/>
</span>
);
}
+1 -1
Переглянути файл
@@ -457,7 +457,7 @@ export function Stream({
if (!stream || !position.current.stick) return;
// A row can still hold an unsent edit or a selection after scrolling to the end.
if (
stream.querySelector(`.${styles.editMessage}`) ||
stream.querySelector(`.${styles.editCard}`) ||
stream.contains(stream.ownerDocument.activeElement) ||
selectionIn(stream)
)
+91 -68
Переглянути файл
@@ -1,41 +1,46 @@
import type { AgentEntry, AgentImage } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { call, commands, isTauri } from "@/platform/ipc";
import { isMacHost } from "@/platform/keymap";
import { basename } from "@/platform/project";
import { basename, useProject } from "@/platform/project";
import { Button, copyText, fileIconName, Icon, IconButton, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type CSSProperties, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
import { Composer } from "../Composer";
import { ImageStrip } from "../ImageStrip";
import { ReferencedText } from "../ReferenceChip";
import styles from "../Session.module.css";
import { SubmitButton } from "../SubmitButton";
import { useAgentSettings } from "../agentSettings";
import { messageTokens, parseMention } from "../composerModel";
import { canSend, messageTokens, parseMention, resolveTyped, toPrompt, type FileRef } from "../composerModel";
import { prependImagePrompt } from "../composerImages";
import { formatDuration, formatSentAt, userMessageText } from "../conversation";
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
import { canForkAt, isBusy, recoveryDividerLabel, type ReplyTimes, type ReplyTurn } from "../model";
import { useRevealedText } from "../reveal";
import {
NO_COMMANDS,
composerDraft,
forkTask,
refreshProviders,
removeComposerDraft,
rerunFrom,
resendMessage,
retrySubmittedDraft,
submittedDraft,
updateComposer,
useAgentCommands,
useAgents,
} from "../store";
import { PermissionLine, QuestionForm, QuestionRecord, type QuestionAnswer } from "./QuestionForm";
import { providerName, type RowTask, samePropsExcept, type UserEntry } from "./shared";
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
const NO_IMAGES: AgentImage[] = [];
/** When a message was sent, or when the turn behind a reply finished, and how long it took. */
function MessageTime({
sentMs,
@@ -370,7 +375,7 @@ function UserMessage({
const inPlace = !archived && rollback && turn !== null;
const canFork = turn !== null && canForkAt(task, turn, turnCount);
const text = userMessageText(entry.text);
const images = entry.images ?? [];
const images = entry.images ?? NO_IMAGES;
const startEditing = () => {
const width = bubbleRef.current?.getBoundingClientRect().width ?? 0;
setEditWidth(width > 0 ? width : null);
@@ -437,13 +442,16 @@ function UserMessage({
</div>
{editing && turn !== null ? (
<MessageEditor
key={`edit:${task.id}:${turn}`}
task={task}
turn={turn}
initial={text}
initialImages={images}
initialWidth={editWidth}
later={turn < turnCount - 1}
onCancel={() => setEditing(false)}
onSend={async (nextText, nextImages) => {
if (await rerunFrom(task.id, turn, nextText, nextImages)) setEditing(false);
onSend={async (nextText, nextImages, nextFiles) => {
if (await rerunFrom(task.id, turn, nextText, nextImages, undefined, nextFiles)) setEditing(false);
}}
/>
) : (
@@ -467,8 +475,24 @@ function UserMessage({
);
}
/** An earlier message edited where it is: sending runs the conversation again from it. */
/** File mentions already written in `text`, so they render as chips while editing. */
function mentionFilesOf(text: string, cwd: string): FileRef[] {
const seen = new Set<string>();
const out: FileRef[] = [];
for (const token of messageTokens(text)) {
if (token.kind !== "file") continue;
const mention = parseMention(token.value);
if (!mention || seen.has(mention.rel)) continue;
seen.add(mention.rel);
out.push({ path: resolveTyped(cwd, mention.rel), rel: mention.rel });
}
return out;
}
/** An earlier message edited in place using the full Composer: sending runs the conversation again from it. */
function MessageEditor({
task,
turn,
initial,
initialImages,
initialWidth,
@@ -476,6 +500,8 @@ function MessageEditor({
onCancel,
onSend,
}: {
task: RowTask;
turn: number;
initial: string;
initialImages: AgentImage[];
/** Measured width of the bubble being replaced, so editing starts in place without jumping. */
@@ -483,23 +509,28 @@ function MessageEditor({
/** Turns follow it (they are dropped on send). */
later: boolean;
onCancel: () => void;
onSend: (text: string, images: AgentImage[]) => Promise<void>;
onSend: (text: string, images: AgentImage[], files: string[]) => Promise<void>;
}) {
const tx = useTx();
const [text, setText] = useState(initial);
const [images, setImages] = useState(initialImages);
const project = useProject((s) => s.project);
const fullTask = useAgents((s) => s.tasks.get(task.id));
const agentCommands = useAgentCommands(task.provider, task.id, fullTask?.commands ?? NO_COMMANDS);
const editKey = `edit:${task.id}:${turn}`;
const draft = useAgents((s) => s.composers.get(editKey));
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
const pending = useRef(false);
const cardRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [initialSnapshot] = useState(() => ({
text: initial,
files: mentionFilesOf(initial, task.cwd),
images: initialImages,
}));
useLayoutEffect(() => {
const box = textareaRef.current;
if (!box) return;
// Avoid native autoFocus scroll jumps; only nudge if the expanded footer sits past the bottom edge.
box.focus({ preventScroll: true });
box.setSelectionRange(box.value.length, box.value.length);
updateComposer(editKey, initialSnapshot);
const card = cardRef.current;
// Focus without native autoFocus scroll jumps; only nudge if the expanded footer sits past the bottom edge.
card?.querySelector<HTMLElement>(".cm-content")?.focus({ preventScroll: true });
const scroller = card?.closest(`.${styles.stream}`);
if (card && scroller instanceof HTMLElement) {
const view = scroller.getBoundingClientRect();
@@ -509,14 +540,19 @@ function MessageEditor({
if (nudge > 0) scroller.scrollTop += nudge;
}
}
}, []);
return () => removeComposerDraft(editKey);
}, [editKey, initialSnapshot]);
const canSubmit = !!draft && canSend(draft);
const send = async () => {
if ((!text.trim() && images.length === 0) || pending.current) return;
const current = composerDraft(editKey);
if (!canSend(current) || pending.current) return;
const prompt = toPrompt(current);
pending.current = true;
setSending(true);
setError(null);
try {
await onSend(text.trim(), images);
await onSend(prompt.text, prompt.images, prompt.files);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
notifications().notify({
@@ -533,54 +569,41 @@ function MessageEditor({
return (
<>
<div ref={cardRef} className={styles.editCard} style={cardStyle}>
<div className={styles.editField}>
<div className={styles.editMirror} aria-hidden="true">
{text.endsWith("\n") ? `${text}\u200b` : text || "\u200b"}
</div>
<textarea
ref={textareaRef}
className={styles.editMessage}
value={text}
rows={1}
readOnly={sending}
aria-label={tx("Message")}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
if (!pending.current) onCancel();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void send();
}
}}
/>
</div>
{images.length > 0 && (
<div className={styles.editImages}>
<ImageStrip
images={images}
onRemove={sending ? undefined : (i) => setImages(images.filter((_, j) => j !== i))}
/>
</div>
)}
<div className={styles.editFooter}>
<span className={styles.editHint} aria-hidden="true">
<kbd>{isMacHost() ? "⌘" : "Ctrl"}</kbd>
<kbd>↵</kbd>
</span>
<span className={styles.editButtons}>
<IconButton icon="close" title="Cancel" disabled={sending} onClick={onCancel} />
<SubmitButton
label="Send"
pending={sending}
disabled={(!text.trim() && images.length === 0) || sending}
onClick={() => void send()}
/>
</span>
</div>
<Composer
id={editKey}
placeholder="Edit message"
root={task.cwd}
projectRoot={fullTask?.projectRoot ?? project?.root ?? task.cwd}
commands={agentCommands}
history={[]}
config={[]}
sendWithOverride="modEnter"
hideContextSuggestion
hideStash
readOnly={sending}
disabled={!canSubmit || sending}
onSubmit={() => void send()}
onEscape={() => {
if (!pending.current) onCancel();
}}
toolbar={
<span className={styles.editHint} aria-hidden="true">
<kbd>{isMacHost() ? "⌘" : "Ctrl"}</kbd>
<kbd>↵</kbd>
</span>
}
actions={
<span className={styles.editButtons}>
<IconButton icon="close" title="Cancel" disabled={sending} onClick={onCancel} />
<SubmitButton
label="Send"
pending={sending}
disabled={!canSubmit || sending}
onClick={() => void send()}
/>
</span>
}
/>
</div>
{error && (
<div className={clsx(styles.error, styles.editError)} role="alert">
+315 -20
Переглянути файл
@@ -17,6 +17,7 @@ import type {
AgentModelCatalog,
AgentPrompt,
AgentProvider,
AgentQueued,
AgentSkillMode,
AgentTask,
ExternalSession,
@@ -100,6 +101,8 @@ export interface Draft {
isolationChosen?: boolean;
/** `null`: the current branch. */
base: string | null;
/** Existing managed worktree path to reuse instead of creating a new one (`isolation === "worktree"`). */
worktreePath?: string | null;
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`) for the next task. */
mcpOverrides?: Record<string, boolean>;
/** Per-session skill modes (`skill name` -> mode) for the next task. */
@@ -113,6 +116,20 @@ export const HOME = "home";
export type SessionLocation = "editor" | "toolWindow";
export interface QueuedEditState {
original: AgentQueued;
stashed: ComposerDraft | null;
}
export interface StashedPrompt {
id: string;
text: string;
files: FileRef[];
/** Retained in memory for the session; stripped from localStorage to respect quota. */
images?: AgentImage[];
savedAtMs: number;
}
interface AgentsState {
loaded: boolean;
/** Tasks running a `!` command from their composer. */
@@ -141,6 +158,10 @@ interface AgentsState {
limits: Map<string, AgentLimit[]>;
draft: Draft;
composers: Map<string, ComposerDraft>;
/** Active non-destructive edits of queued messages, preserving any in-progress draft. */
queuedEdits: Map<string, QueuedEditState>;
/** Saved prompt stashes shared across composers, newest first. */
stashes: StashedPrompt[];
/** The composer typed in last: where "Send to Agent" adds references. */
lastComposer: string;
/** First messages of past tasks, newest first (New Task page ↑). */
@@ -170,6 +191,11 @@ interface AgentsState {
}
const DRAFT_KEY = "openidea.agents.draft.v2";
const COMPOSER_DRAFTS_KEY = "openidea.agents.composers.v1";
const STASHES_KEY = "openidea.agents.stashes.v1";
const MAX_SAVED_DRAFTS = 50;
const MAX_SAVED_DRAFT_CHARS = 120_000;
const MAX_STASHES = 50;
const HISTORY_KEY = "openidea.agents.history.v1";
const HISTORY_SIZE = 50;
const SESSION_LOCATION_KEY = "openidea.agents.sessionLocation.v1";
@@ -193,6 +219,120 @@ function save(key: string, value: unknown) {
}
}
interface SavedComposerDraft {
text: string;
files: FileRef[];
}
/** Loads persisted text/file drafts from localStorage (images are omitted to respect storage quota). */
export function loadSavedComposerDrafts(): Map<string, ComposerDraft> {
const saved = load<Record<string, SavedComposerDraft>>(COMPOSER_DRAFTS_KEY, {});
const out = new Map<string, ComposerDraft>();
if (!saved || typeof saved !== "object") return out;
for (const [key, entry] of Object.entries(saved)) {
if (!entry || typeof entry.text !== "string") continue;
const files = Array.isArray(entry.files)
? entry.files.filter(
(f): f is FileRef => !!f && typeof f === "object" && typeof f.path === "string" && typeof f.rel === "string",
)
: [];
const draft: ComposerDraft = { text: entry.text, files, images: [] };
if (canSend(draft) && draft.text.length <= MAX_SAVED_DRAFT_CHARS) out.set(key, draft);
if (out.size >= MAX_SAVED_DRAFTS) break;
}
return out;
}
const COMPOSER_SAVE_DEBOUNCE_MS = 350;
let pendingComposerDrafts: Map<string, ComposerDraft> | null = null;
let composerSaveTimer: ReturnType<typeof setTimeout> | null = null;
function writeComposerDrafts(composers: Map<string, ComposerDraft>) {
const entries: [string, SavedComposerDraft][] = [];
for (const [key, draft] of composers) {
if (
key.startsWith("edit:") ||
(!draft.text.trim() && !draft.files.some((f) => f.attached)) ||
draft.text.length > MAX_SAVED_DRAFT_CHARS
) {
continue;
}
entries.push([key, { text: draft.text, files: draft.files }]);
}
const trimmed = entries.slice(-MAX_SAVED_DRAFTS);
save(COMPOSER_DRAFTS_KEY, Object.fromEntries(trimmed));
}
/** Immediately writes any debounced composer draft changes to localStorage. */
export function flushComposerDrafts() {
if (composerSaveTimer !== null) {
clearTimeout(composerSaveTimer);
composerSaveTimer = null;
}
if (!pendingComposerDrafts) return;
const toSave = pendingComposerDrafts;
pendingComposerDrafts = null;
writeComposerDrafts(toSave);
}
function scheduleSaveComposerDrafts(composers: Map<string, ComposerDraft>) {
pendingComposerDrafts = composers;
if (composerSaveTimer !== null) clearTimeout(composerSaveTimer);
composerSaveTimer = setTimeout(() => {
composerSaveTimer = null;
const toSave = pendingComposerDrafts;
pendingComposerDrafts = null;
if (toSave) writeComposerDrafts(toSave);
}, COMPOSER_SAVE_DEBOUNCE_MS);
}
function saveComposerDraftsImmediate(composers: Map<string, ComposerDraft>) {
if (composerSaveTimer !== null) {
clearTimeout(composerSaveTimer);
composerSaveTimer = null;
}
pendingComposerDrafts = null;
writeComposerDrafts(composers);
}
if (typeof window !== "undefined") {
window.addEventListener("pagehide", flushComposerDrafts);
}
function saveStashes(stashes: readonly StashedPrompt[]) {
// Omit base64 images from localStorage to respect storage quota while keeping them in memory.
save(
STASHES_KEY,
stashes.map(({ images: _images, ...persisted }) => persisted),
);
}
export function loadSavedStashes(): StashedPrompt[] {
const saved = load<StashedPrompt[]>(STASHES_KEY, []);
if (!Array.isArray(saved)) return [];
return saved
.filter(
(s): s is StashedPrompt =>
!!s &&
typeof s === "object" &&
typeof s.id === "string" &&
typeof s.text === "string" &&
typeof s.savedAtMs === "number",
)
.map((s) => ({
id: s.id,
text: s.text,
files: Array.isArray(s.files)
? s.files.filter(
(f): f is FileRef =>
!!f && typeof f === "object" && typeof f.path === "string" && typeof f.rel === "string",
)
: [],
savedAtMs: s.savedAtMs,
}))
.slice(0, MAX_STASHES);
}
const fallbackDraft: Draft = {
provider: "claude",
config: {},
@@ -205,7 +345,8 @@ const fallbackDraft: Draft = {
* saved before that choice was recorded carried the old default (`worktree`) instead.
*/
export function savedDraft(saved: Partial<Draft>): Draft {
const draft = { ...fallbackDraft, ...saved };
const { worktreePath: _ignored, ...rest } = saved;
const draft = { ...fallbackDraft, ...rest, worktreePath: null };
return draft.isolationChosen ? draft : { ...draft, isolation: "local" };
}
@@ -226,7 +367,9 @@ export const useAgents = create<AgentsState>(() => ({
modelRequests: new Set(),
modelRequestTargets: new Map(),
draft: savedDraft(load<Partial<Draft>>(DRAFT_KEY, {})),
composers: new Map(),
composers: loadSavedComposerDrafts(),
queuedEdits: new Map(),
stashes: loadSavedStashes(),
lastComposer: HOME,
history: load<string[]>(HISTORY_KEY, []),
organize: EMPTY_ORGANIZE,
@@ -261,7 +404,9 @@ export function updateDraft(patch: Partial<Draft>) {
...patch,
};
useAgents.setState({ draft });
save(DRAFT_KEY, draft);
// Never persist `worktreePath` across reloads: worktrees may be deleted or pruned between sessions.
const { worktreePath: _ephemeral, ...persisted } = draft;
save(DRAFT_KEY, persisted);
}
/** What Settings › Agents says new tasks of `provider` start with, by option id. */
@@ -373,22 +518,128 @@ export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
useAgents.setState({ lastComposer: key });
return;
}
useAgents.setState((s) => ({
composers: new Map(s.composers).set(key, {
useAgents.setState((s) => {
const composers = new Map(s.composers);
const next: ComposerDraft = {
...(s.composers.get(key) ?? emptyDraft()),
...patch,
}),
lastComposer: key,
}));
};
composers.set(key, next);
if (!key.startsWith("edit:")) {
const empty = !next.text.trim() && !next.files.some((f) => f.attached);
if (empty) saveComposerDraftsImmediate(composers);
else scheduleSaveComposerDrafts(composers);
}
return {
composers,
...(key.startsWith("edit:") ? {} : { lastComposer: key }),
};
});
}
/** Drops an ephemeral composer draft (such as an inline message edit) without touching storage. */
export function removeComposerDraft(key: string) {
useAgents.setState((s) => {
if (!s.composers.has(key)) return s;
const composers = new Map(s.composers);
composers.delete(key);
return { composers };
});
}
/** Clears any active queued-message edit state for `task` (e.g. when composer is consumed or stashed). */
export function clearQueuedEdit(task: string) {
useAgents.setState((s) => {
if (!s.queuedEdits.has(task)) return s;
const queuedEdits = new Map(s.queuedEdits);
queuedEdits.delete(task);
return { queuedEdits };
});
}
/** Stashes the current draft from composer `key` and clears the composer. */
export function stashComposerDraft(key: string): StashedPrompt | null {
const draft = composerDraft(key);
if (!draft.text.trim() && !draft.files.some((f) => f.attached) && draft.images.length === 0) return null;
const id =
typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const entry: StashedPrompt = {
id,
text: draft.text,
files: draft.files,
...(draft.images.length > 0 ? { images: draft.images } : {}),
savedAtMs: Date.now(),
};
useAgents.setState((s) => {
const stashes = [entry, ...s.stashes].slice(0, MAX_STASHES);
saveStashes(stashes);
const queuedEdits = s.queuedEdits.has(key) ? new Map(s.queuedEdits) : s.queuedEdits;
queuedEdits.delete(key);
return { stashes, queuedEdits };
});
updateComposer(key, emptyDraft());
focusComposer(key);
return entry;
}
/** Restores a stashed prompt into composer `key`, stashing any existing unsent draft first. */
export function restoreStashedPrompt(key: string, stashId: string): boolean {
const target = useAgents.getState().stashes.find((s) => s.id === stashId);
if (!target) return false;
const current = composerDraft(key);
const swap: StashedPrompt | null =
current.text.trim() || current.files.some((f) => f.attached) || current.images.length > 0
? {
id:
typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
text: current.text,
files: current.files,
...(current.images.length > 0 ? { images: current.images } : {}),
savedAtMs: Date.now(),
}
: null;
useAgents.setState((s) => {
const remaining = s.stashes.filter((entry) => entry.id !== stashId);
const stashes = (swap ? [swap, ...remaining] : remaining).slice(0, MAX_STASHES);
saveStashes(stashes);
const queuedEdits = s.queuedEdits.has(key) ? new Map(s.queuedEdits) : s.queuedEdits;
queuedEdits.delete(key);
return { stashes, queuedEdits };
});
updateComposer(key, { text: target.text, files: target.files, images: target.images ?? [] });
focusComposer(key);
return true;
}
/** Deletes a saved prompt stash by id. */
export function deleteStashedPrompt(stashId: string) {
useAgents.setState((s) => {
const stashes = s.stashes.filter((entry) => entry.id !== stashId);
if (stashes.length === s.stashes.length) return s;
saveStashes(stashes);
return { stashes };
});
}
/** An acknowledgement consumes only the submitted revision, in the same project connection. */
function clearSubmittedComposer(key: string, submitted: ComposerDraft, started: number) {
useAgents.setState((s) =>
generation === started && s.composers.get(key) === submitted
? { composers: new Map(s.composers).set(key, emptyDraft()) }
: s,
);
useAgents.setState((s) => {
if (generation !== started) return s;
const queuedEdit = s.queuedEdits.get(key);
const queuedEdits = queuedEdit ? new Map(s.queuedEdits) : s.queuedEdits;
if (queuedEdit) queuedEdits.delete(key);
if (s.composers.get(key) !== submitted) {
return queuedEdit ? { queuedEdits } : s;
}
const composers = new Map(s.composers);
composers.set(key, queuedEdit?.stashed ?? emptyDraft());
saveComposerDraftsImmediate(composers);
return { composers, queuedEdits };
});
}
/** Session tabs on screen; a task can be shown in more than one split. */
@@ -823,6 +1074,7 @@ export function disconnect() {
modelCatalogs: new Map(),
modelRequests: new Set(),
modelRequestTargets: new Map(),
queuedEdits: new Map(),
organize: EMPTY_ORGANIZE,
organizeRoot: null,
docked: null,
@@ -881,6 +1133,9 @@ function onEvent(e: AgentEvent) {
tasks.delete(e.id);
const composers = new Map(s.composers);
composers.delete(e.id);
saveComposerDraftsImmediate(composers);
const queuedEdits = new Map(s.queuedEdits);
queuedEdits.delete(e.id);
const unread = new Set(s.unread);
unread.delete(e.id);
// A deleted task leaves its group and the pinned area.
@@ -890,6 +1145,7 @@ function onEvent(e: AgentEvent) {
useAgents.setState({
tasks,
composers,
queuedEdits,
unread,
...withoutTaskCache(s, e.id),
organize,
@@ -1343,6 +1599,7 @@ export function openHome(prompt?: string) {
export async function startTask(
isolation: Isolation = useAgents.getState().draft.isolation,
projectRoot: string | null = null,
worktreePath?: string | null,
): Promise<void> {
const { draft, providers } = useAgents.getState();
const composer = composerDraft(HOME);
@@ -1372,6 +1629,8 @@ export async function startTask(
: o.current;
return value !== null && o.values.some((v) => v.value === value) ? [{ id: o.id, value }] : [];
});
const reusedWorktree =
isolation === "worktree" ? (worktreePath !== undefined ? worktreePath : (draft.worktreePath ?? null)) : null;
try {
const task = await call(
commands.agentCreate({
@@ -1380,7 +1639,8 @@ export async function startTask(
provider: draft.provider,
config,
isolation,
base: isolation === "worktree" ? draft.base : null,
base: isolation === "worktree" && !reusedWorktree ? draft.base : null,
worktreePath: reusedWorktree,
mcpOverrides: draft.mcpOverrides ?? {},
skillOverrides: draft.skillOverrides ?? {},
memoryOverrides: draft.memoryOverrides ?? null,
@@ -1394,7 +1654,7 @@ export async function startTask(
tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task),
entries: new Map(s.entries).set(task.id, s.entries.get(task.id) ?? []),
}));
updateDraft({ projectRoot });
updateDraft({ projectRoot, worktreePath: null });
remember(composer.text.trim());
clearSubmittedComposer(HOME, composer, started);
const closed = await editorService().closeInput?.(HOME_KEY);
@@ -1837,6 +2097,7 @@ export async function rerunFrom(
text: string,
images: AgentImage[] = [],
confirmRewind?: { title: string; later?: boolean },
files: string[] = [],
): Promise<boolean> {
if (turn === 0) {
if (
@@ -1865,7 +2126,7 @@ export async function rerunFrom(
try {
await stopForEdit(task);
await call(commands.agentRollback(task, turn, true));
await call(commands.agentPrompt(task, { text, files: [], images }, false));
await call(commands.agentPrompt(task, { text, files, images }, false));
} catch (e) {
restoreComposer(task, text, images);
throw e;
@@ -1908,19 +2169,53 @@ function settled(task: string, timeoutMs = 15_000): Promise<void> {
export const resendMessage = (task: string, text: string) =>
call(commands.agentPrompt(task, { text, files: [], images: [] }, false));
/** Takes a queued message back into the composer to edit it. */
/** Takes a queued message into the composer to edit it without losing any current draft or prior edit. */
export async function editQueued(task: string, queued: string): Promise<void> {
const item = await call(commands.agentUnqueue(task, queued));
const prior = useAgents.getState().queuedEdits.get(task);
if (prior) {
const status = useAgents.getState().tasks.get(task)?.status;
if (status && isBusy(status)) {
await call(commands.agentPrompt(task, prior.original.prompt, false)).catch(() => {
/* best-effort re-queue of prior item before opening the next one */
});
}
}
const current = composerDraft(task);
const cwd = useAgents.getState().tasks.get(task)?.cwd ?? "";
const files: FileRef[] = item.prompt.files.map((path) => {
const rel = path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path;
const rel = path.startsWith(`${cwd}/`) || path.startsWith(`${cwd}\\`) ? path.slice(cwd.length + 1) : path;
return isMentioned(item.prompt.text, rel) ? { path, rel } : { path, rel: basename(path), attached: true };
});
const stashed = prior ? prior.stashed : canSend(current) ? current : null;
useAgents.setState((s) => ({
queuedEdits: new Map(s.queuedEdits).set(task, { original: item, stashed }),
}));
updateComposer(task, {
...prependImagePrompt(current, item.prompt),
files: [...files, ...current.files],
text: item.prompt.text,
files,
images: item.prompt.images,
});
focusComposer(task);
}
/** Cancels an in-progress queued message edit, re-queueing the original while still busy and restoring any stashed draft. */
export async function cancelQueuedEdit(task: string): Promise<void> {
const edit = useAgents.getState().queuedEdits.get(task);
if (!edit) return;
const status = useAgents.getState().tasks.get(task)?.status;
// Only re-queue when the task is still running/busy; if the task went idle while editing,
// calling `agentPrompt` would unexpectedly start a new turn instead of canceling.
if (status && isBusy(status)) {
await call(commands.agentPrompt(task, edit.original.prompt, false));
}
useAgents.setState((s) => {
const queuedEdits = new Map(s.queuedEdits);
queuedEdits.delete(task);
return { queuedEdits };
});
updateComposer(task, edit.stashed ?? emptyDraft());
focusComposer(task);
}
export const removeQueued = (task: string, queued: string) => call(commands.agentUnqueue(task, queued));
+42 -2
Переглянути файл
@@ -2316,7 +2316,6 @@
"One KEY=VALUE entry per line.": "One KEY=VALUE entry per line.",
"One Header=Value entry per line.": "One Header=Value entry per line.",
"Agent Settings": "Agent Settings",
"Message Actions": "Message Actions",
"MCP Connections…": "MCP Connections…",
"Configure the MCP servers that agents can use.": "Configure the MCP servers that agents can use.",
"No matching remote branches": "No matching remote branches",
@@ -5810,5 +5809,46 @@
"Configure Hermes auto-memory in Settings › Agents › Rules & Memory.": "Configure Hermes auto-memory in Settings › Agents › Rules & Memory.",
"All coding agents": "All coding agents",
"Show diagnostic source and code on hover": "Show diagnostic source and code on hover",
"Shows the language server and rule code beneath each problem in editor tooltips. The Problems tool window always shows them.": "Shows the language server and rule code beneath each problem in editor tooltips. The Problems tool window always shows them."
"Shows the language server and rule code beneath each problem in editor tooltips. The Problems tool window always shows them.": "Shows the language server and rule code beneath each problem in editor tooltips. The Problems tool window always shows them.",
"{rel}:{suggestedLines} is added to your request": "{rel}:{suggestedLines} is added to your request",
"Collapse editor": "Collapse editor",
"Expand editor": "Expand editor",
"Steer ({altShortcut} to queue)": "Steer ({altShortcut} to queue)",
"Send now ({altShortcut} to queue)": "Send now ({altShortcut} to queue)",
"Queue ({altShortcut} to steer)": "Queue ({altShortcut} to steer)",
"Queue ({altShortcut} to send now)": "Queue ({altShortcut} to send now)",
"Edit queued message": "Edit queued message",
"Stopping…": "Stopping…",
"Editing queued message": "Editing queued message",
"Draft preserved": "Draft preserved",
"Couldn't restore the queued message": "Couldn't restore the queued message",
"1 attachment": "1 attachment",
"{attachmentCount} attachments": "{attachmentCount} attachments",
"Stash Draft": "Stash Draft",
"Stashed Prompts": "Stashed Prompts",
"Stashed Prompts ({length})": "Stashed Prompts ({length})",
"Attached files": "Attached files",
"Delete Stash": "Delete Stash",
"Edit message": "Edit message",
"Switched branch with conflicts": "Switched branch with conflicts",
"Switched branch, but local changes could not be restored": "Switched branch, but local changes could not be restored",
"Branch is already checked out in another worktree": "Branch is already checked out in another worktree",
"Local changes prevented switching branches": "Local changes prevented switching branches",
"Local branch has commits not on the remote branch": "Local branch has commits not on the remote branch",
"Couldn't switch branch": "Couldn't switch branch",
"Create branch \"{trimmed}\"": "Create branch \"{trimmed}\"",
"Base branch: {displayLabel}": "Base branch: {displayLabel}",
"Branch: {displayLabel}": "Branch: {displayLabel}",
"All Branches…": "All Branches…",
"Existing worktrees": "Existing worktrees",
"Stop the current turn to switch branches": "Stop the current turn to switch branches",
"Worktree branch: {branch}": "Worktree branch: {branch}",
"Worktree: {cwd} (click to copy path)": "Worktree: {cwd} (click to copy path)",
"Copied worktree path": "Copied worktree path",
"Sessions": "Sessions",
"Steer": "Steer",
"1 file": "1 file",
"{count} files": "{count} files",
"1 image": "1 image",
"{imageCount} images": "{imageCount} images"
}
+41 -2
Переглянути файл
@@ -9192,7 +9192,6 @@
"One Header=Value entry per line.": "每行一个 Header=Value 条目。",
"Maven project could not be configured": "无法配置 Maven 项目",
"Agent Settings": "智能体设置",
"Message Actions": "消息操作",
"MCP Connections…": "MCP 连接…",
"Configure the MCP servers that agents can use.": "配置智能体可以使用的 MCP 服务器。",
"Type:": "类型:",
@@ -12701,5 +12700,45 @@
"Configure Hermes auto-memory in Settings › Agents › Rules & Memory.": "请在「设置 › 智能体 › 规则与记忆」中配置 Hermes 自动记忆。",
"All coding agents": "所有编程智能体",
"Show diagnostic source and code on hover": "悬停时显示诊断来源和规则码",
"Shows the language server and rule code beneath each problem in editor tooltips. The Problems tool window always shows them.": "在编辑器悬浮提示中每条问题下方显示语言服务器和规则码。问题工具窗口始终显示。"
"Shows the language server and rule code beneath each problem in editor tooltips. The Problems tool window always shows them.": "在编辑器悬浮提示中每条问题下方显示语言服务器和规则码。问题工具窗口始终显示。",
"{rel}:{suggestedLines} is added to your request": "{rel}:{suggestedLines} 已添加到你的请求中",
"Collapse editor": "收起编辑器",
"Expand editor": "展开编辑器",
"Steer ({altShortcut} to queue)": "立即引导({altShortcut} 加入队列)",
"Send now ({altShortcut} to queue)": "立即发送({altShortcut} 加入队列)",
"Queue ({altShortcut} to steer)": "加入队列({altShortcut} 立即引导)",
"Queue ({altShortcut} to send now)": "加入队列({altShortcut} 立即发送)",
"Edit queued message": "编辑队列中的消息",
"Stopping…": "正在停止…",
"Editing queued message": "正在编辑队列中的消息",
"Draft preserved": "已保留原草稿",
"Couldn't restore the queued message": "无法恢复队列中的消息",
"1 attachment": "1 个附件",
"{attachmentCount} attachments": "{attachmentCount} 个附件",
"Stash Draft": "暂存草稿",
"Stashed Prompts": "已暂存的提示词",
"Stashed Prompts ({length})": "已暂存的提示词({length})",
"Attached files": "附加的文件",
"Delete Stash": "删除暂存",
"Edit message": "编辑消息",
"Switched branch with conflicts": "已切换分支,但存在冲突",
"Switched branch, but local changes could not be restored": "已切换分支,但未能恢复本地更改",
"Branch is already checked out in another worktree": "该分支已在另一个工作树中签出",
"Local changes prevented switching branches": "本地更改阻止了切换分支",
"Local branch has commits not on the remote branch": "本地分支包含远程分支上没有的提交",
"Couldn't switch branch": "无法切换分支",
"Create branch \"{trimmed}\"": "创建分支“{trimmed}”",
"Base branch: {displayLabel}": "基础分支:{displayLabel}",
"Branch: {displayLabel}": "分支:{displayLabel}",
"All Branches…": "所有分支…",
"Existing worktrees": "已有工作树",
"Stop the current turn to switch branches": "停止当前回合后即可切换分支",
"Worktree branch: {branch}": "工作树分支:{branch}",
"Worktree: {cwd} (click to copy path)": "工作树:{cwd}(点击复制路径)",
"Copied worktree path": "已复制工作树路径",
"Sessions": "会话",
"Steer": "立即引导",
"1 file": "1 个文件",
"1 image": "1 张图片",
"{imageCount} images": "{imageCount} 张图片"
}