Keep history of unchanged tasks on tasks file updates (#66646)

Closes https://github.com/zed-industries/zed/issues/52659

Release Notes:

- Fixed task rerun opening task spawn menu after any tasks.json edit
This commit is contained in:
Kirill Bulatov
2026-11-12 14:53:04 +00:00
committed by GitHub
parent 78a8526196
commit eda58e5040
4 changed files with 354 additions and 61 deletions
+57 -25
View File
@@ -42,6 +42,7 @@ pub struct DebugScenarioContext {
/// Inventory tracks available tasks for a given project.
pub struct Inventory {
last_scheduled_tasks: VecDeque<(TaskSourceKind, ResolvedTask)>,
last_scheduled_task_id: Option<TaskId>,
last_scheduled_scenarios: VecDeque<(DebugScenario, DebugScenarioContext)>,
templates_from_settings: InventoryFor<TaskTemplate>,
scenarios_from_settings: InventoryFor<DebugScenario>,
@@ -51,6 +52,7 @@ impl std::fmt::Debug for Inventory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Inventory")
.field("last_scheduled_tasks", &self.last_scheduled_tasks)
.field("last_scheduled_task_id", &self.last_scheduled_task_id)
.field("last_scheduled_scenarios", &self.last_scheduled_scenarios)
.field("templates_from_settings", &self.templates_from_settings)
.field("scenarios_from_settings", &self.scenarios_from_settings)
@@ -312,6 +314,7 @@ impl Inventory {
pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
last_scheduled_tasks: VecDeque::default(),
last_scheduled_task_id: None,
last_scheduled_scenarios: VecDeque::default(),
templates_from_settings: InventoryFor::default(),
scenarios_from_settings: InventoryFor::default(),
@@ -642,7 +645,10 @@ impl Inventory {
.find(|(_, task)| &task.id == task_id)
.cloned()
} else {
self.last_scheduled_tasks.back().cloned()
self.last_scheduled_tasks
.back()
.filter(|(_, task)| Some(&task.id) == self.last_scheduled_task_id.as_ref())
.cloned()
}
}
@@ -652,6 +658,7 @@ impl Inventory {
task_source_kind: TaskSourceKind,
resolved_task: ResolvedTask,
) {
self.last_scheduled_task_id = Some(resolved_task.id.clone());
self.last_scheduled_tasks
.push_back((task_source_kind, resolved_task));
if self.last_scheduled_tasks.len() > 5_000 {
@@ -662,7 +669,16 @@ impl Inventory {
/// Deletes a resolved task from history, using its id.
/// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again.
pub fn delete_previously_used(&mut self, id: &TaskId) {
let deleted_rerun_target = self
.last_scheduled_task(None)
.is_some_and(|(_, task)| &task.id == id);
self.last_scheduled_tasks.retain(|(_, task)| &task.id != id);
if deleted_rerun_target {
self.last_scheduled_task_id = self
.last_scheduled_tasks
.back()
.map(|(_, task)| task.id.clone());
}
}
/// Returns global task templates with the provided tag.
@@ -702,6 +718,16 @@ impl Inventory {
.collect()
}
fn retain_unchanged_tasks(
&mut self,
is_updated_source: impl Fn(&TaskSourceKind) -> bool,
new_templates: &[TaskTemplate],
) {
self.last_scheduled_tasks.retain(|(kind, task)| {
!is_updated_source(kind) || new_templates.contains(task.original_task())
});
}
fn global_templates_from_settings(
&self,
) -> impl '_ + Iterator<Item = (TaskSourceKind, TaskTemplate)> {
@@ -780,23 +806,42 @@ impl Inventory {
Some(template)
});
let parsed_templates = &mut self.templates_from_settings;
let new_templates = new_templates.collect::<Vec<_>>();
match location {
TaskSettingsLocation::Global(path) => {
parsed_templates
self.retain_unchanged_tasks(
|kind| {
if let TaskSourceKind::AbsPath { abs_path, .. } = kind {
abs_path == path
} else {
false
}
},
&new_templates,
);
self.templates_from_settings
.global
.entry(path.to_owned())
.insert_entry(new_templates.collect());
self.last_scheduled_tasks.retain(|(kind, _)| {
if let TaskSourceKind::AbsPath { abs_path, .. } = kind {
abs_path != path
} else {
true
}
});
.insert_entry(new_templates);
}
TaskSettingsLocation::Worktree(location) => {
let new_templates = new_templates.collect::<Vec<_>>();
self.retain_unchanged_tasks(
|kind| {
if let TaskSourceKind::Worktree {
directory_in_worktree,
id,
..
} = kind
{
*id == location.worktree_id
&& directory_in_worktree.as_ref() == location.path
} else {
false
}
},
&new_templates,
);
let parsed_templates = &mut self.templates_from_settings;
if new_templates.is_empty() {
if let Some(worktree_tasks) =
parsed_templates.worktree.get_mut(&location.worktree_id)
@@ -810,19 +855,6 @@ impl Inventory {
.or_default()
.insert(Arc::from(location.path), new_templates);
}
self.last_scheduled_tasks.retain(|(kind, _)| {
if let TaskSourceKind::Worktree {
directory_in_worktree,
id,
..
} = kind
{
*id != location.worktree_id
|| directory_in_worktree.as_ref() != location.path
} else {
true
}
});
}
}
@@ -6,6 +6,7 @@ use serde_json::json;
use settings::SettingsLocation;
use std::path::Path;
use std::sync::Arc;
use task::{ResolvedTask, TaskId};
use util::rel_path::rel_path;
use project::task_store::{TaskSettingsLocation, TaskStore};
@@ -271,14 +272,14 @@ async fn test_task_list_sorting(cx: &mut TestAppContext) {
resolved_task_names(&inventory, None, cx).await,
vec![
"worktree_task_1".to_string(),
"1_a_task".to_string(),
"3_task".to_string(),
"1_task".to_string(),
"2_task".to_string(),
"3_task".to_string(),
"1_a_task".to_string(),
"10_hello".to_string(),
"11_hello".to_string(),
],
"After global tasks update, worktree task usage is not erased and it's the first still; global task is back to regular order as its file was updated"
"After global tasks update, usages of the tasks with unchanged definitions are kept"
);
register_task_used(&inventory, "11_hello", cx).await;
@@ -291,10 +292,10 @@ async fn test_task_list_sorting(cx: &mut TestAppContext) {
vec![
"11_hello".to_string(),
"worktree_task_1".to_string(),
"1_a_task".to_string(),
"3_task".to_string(),
"1_task".to_string(),
"2_task".to_string(),
"3_task".to_string(),
"1_a_task".to_string(),
"10_hello".to_string(),
],
);
@@ -608,6 +609,187 @@ async fn test_zed_tasks_take_precedence_over_vscode(cx: &mut TestAppContext) {
);
}
#[gpui::test]
async fn test_tasks_file_update_keeps_history_of_unchanged_tasks(cx: &mut TestAppContext) {
init_test(cx);
let inventory = cx.update(|cx| Inventory::new(cx));
let update_tasks = |tasks: String, cx: &mut TestAppContext| {
inventory.update(cx, |inventory, _| {
inventory
.update_file_based_tasks(TaskSettingsLocation::Global(tasks_file()), Some(&tasks))
.unwrap();
});
};
update_tasks(mock_tasks_from_names(["first", "second"]), cx);
register_task_used(&inventory, "first", cx).await;
let first_id = newest_task(&inventory, cx).unwrap().id;
register_task_used(&inventory, "second", cx).await;
let second_id = newest_task(&inventory, cx).unwrap().id;
update_tasks(mock_tasks_from_names(["first", "second"]), cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
Some(second_id.clone()),
"Saving the file without changes should keep the newest task"
);
assert_eq!(
resolved_task_names(&inventory, None, cx).await,
vec!["second".to_string(), "first".to_string()],
);
let edited_second = serde_json::to_string(&json!([
{ "label": "first", "command": "echo", "args": ["first"] },
{ "label": "second", "command": "echo", "args": ["edited"] },
]))
.unwrap();
update_tasks(edited_second.clone(), cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
None,
"Editing the newest task should not make the older task the rerun target"
);
assert_eq!(
task_by_id(&inventory, &second_id, cx).map(|task| task.id),
None,
"An edited task should not rerun with its old definition"
);
assert_eq!(
task_by_id(&inventory, &first_id, cx).map(|task| task.id),
Some(first_id.clone()),
"An unchanged task should stay reachable by its id"
);
assert_eq!(
resolved_task_names(&inventory, None, cx).await,
vec!["first".to_string(), "second".to_string()],
);
register_task_used(&inventory, "first", cx).await;
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
Some(first_id.clone()),
"Scheduling a task should restore the rerun target"
);
register_task_used(&inventory, "second", cx).await;
let edited_second_id = newest_task(&inventory, cx).unwrap().id;
let edited_first = serde_json::to_string(&json!([
{ "label": "first", "command": "echo", "args": ["edited"] },
{ "label": "second", "command": "echo", "args": ["edited"] },
]))
.unwrap();
update_tasks(edited_first, cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
Some(edited_second_id),
"Editing an older task should not affect the rerun target"
);
}
#[gpui::test]
async fn test_deleting_tasks_from_history_updates_rerun_target(cx: &mut TestAppContext) {
init_test(cx);
let inventory = cx.update(|cx| Inventory::new(cx));
let update_tasks = |tasks: String, cx: &mut TestAppContext| {
inventory.update(cx, |inventory, _| {
inventory
.update_file_based_tasks(TaskSettingsLocation::Global(tasks_file()), Some(&tasks))
.unwrap();
});
};
let delete_task = |task_id: &TaskId, cx: &mut TestAppContext| {
inventory.update(cx, |inventory, _| {
inventory.delete_previously_used(task_id);
});
};
update_tasks(mock_tasks_from_names(["first", "second", "third"]), cx);
register_task_used(&inventory, "first", cx).await;
let first_id = newest_task(&inventory, cx).unwrap().id;
register_task_used(&inventory, "second", cx).await;
let second_id = newest_task(&inventory, cx).unwrap().id;
register_task_used(&inventory, "third", cx).await;
let third_id = newest_task(&inventory, cx).unwrap().id;
delete_task(&third_id, cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
Some(second_id.clone()),
"Deleting the newest task should make the previous one the rerun target"
);
delete_task(&first_id, cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
Some(second_id.clone()),
"Deleting an older task should not affect the rerun target"
);
delete_task(&second_id, cx);
assert_eq!(newest_task(&inventory, cx).map(|task| task.id), None);
register_task_used(&inventory, "first", cx).await;
register_task_used(&inventory, "second", cx).await;
register_task_used(&inventory, "third", cx).await;
let edited_third = serde_json::to_string(&json!([
{ "label": "first", "command": "echo", "args": ["first"] },
{ "label": "second", "command": "echo", "args": ["second"] },
{ "label": "third", "command": "echo", "args": ["edited"] },
]))
.unwrap();
update_tasks(edited_third, cx);
delete_task(&third_id, cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
None,
"Deleting an already invalidated task should not make an older task the rerun target"
);
delete_task(&second_id, cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
None,
"Deleting an older task should not restore the invalidated rerun target"
);
}
#[gpui::test]
async fn test_worktree_tasks_file_update_keeps_history_of_unchanged_tasks(cx: &mut TestAppContext) {
init_test(cx);
let inventory = cx.update(|cx| Inventory::new(cx));
let worktree_id = WorktreeId::from_usize(0);
let update_tasks = |tasks: String, path: &str, cx: &mut TestAppContext| {
inventory.update(cx, |inventory, _| {
inventory
.update_file_based_tasks(
TaskSettingsLocation::Worktree(SettingsLocation {
worktree_id,
path: rel_path(path),
}),
Some(&tasks),
)
.unwrap();
});
};
update_tasks(mock_tasks_from_names(["task"]), ".zed", cx);
register_worktree_task_used(&inventory, worktree_id, "task", cx).await;
let task_id = newest_task(&inventory, cx).unwrap().id;
update_tasks(mock_tasks_from_names(["other"]), "nested/.zed", cx);
update_tasks(mock_tasks_from_names(["task", "new"]), ".zed", cx);
assert_eq!(
newest_task(&inventory, cx).map(|task| task.id),
Some(task_id.clone()),
);
update_tasks("[]".to_string(), ".zed", cx);
assert_eq!(newest_task(&inventory, cx).map(|task| task.id), None);
assert_eq!(
task_by_id(&inventory, &task_id, cx).map(|task| task.id),
None,
);
}
fn init_test(_cx: &mut TestAppContext) {
zlog::init_test();
TaskStore::init(None);
@@ -635,6 +817,24 @@ fn resolved_task_names(
})
}
fn newest_task(inventory: &Entity<Inventory>, cx: &mut TestAppContext) -> Option<ResolvedTask> {
inventory.read_with(cx, |inventory, _| {
inventory.last_scheduled_task(None).map(|(_, task)| task)
})
}
fn task_by_id(
inventory: &Entity<Inventory>,
task_id: &TaskId,
cx: &mut TestAppContext,
) -> Option<ResolvedTask> {
inventory.read_with(cx, |inventory, _| {
inventory
.last_scheduled_task(Some(task_id))
.map(|(_, task)| task)
})
}
fn mock_tasks_from_names<'a>(task_names: impl IntoIterator<Item = &'a str> + 'a) -> String {
serde_json::to_string(&serde_json::Value::Array(
task_names
+74 -19
View File
@@ -8,7 +8,9 @@ use collections::HashMap;
use editor::{Editor, MultiBufferOffset, ToPoint as _};
use gpui::{App, AppContext as _, Context, Entity, Task, TaskExt, Window};
use project::{Location, TaskContexts, TaskSourceKind, Worktree};
use task::{RevealTarget, TaskContext, TaskId, TaskTemplate, TaskVariables, VariableName};
use task::{
RevealTarget, SpawnInTerminal, TaskContext, TaskId, TaskTemplate, TaskVariables, VariableName,
};
use tree_sitter::{Query, StreamingIterator as _};
use workspace::Workspace;
@@ -121,26 +123,30 @@ pub fn init(cx: &mut App) {
})
{
if action.reevaluate_context {
let mut original_task = last_scheduled_task.original_task().clone();
if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
original_task.allow_concurrent_runs = allow_concurrent_runs;
}
if let Some(use_new_terminal) = action.use_new_terminal {
original_task.use_new_terminal = use_new_terminal;
}
let original_task = last_scheduled_task.original_task().clone();
let action = action.clone();
let task_contexts = task_contexts(workspace, window, cx);
cx.spawn_in(window, async move |workspace, cx| {
let task_contexts = task_contexts.await;
let default_context = TaskContext::default();
workspace
.update_in(cx, |workspace, window, cx| {
if !workspace.can_schedule_tasks(cx) {
return;
}
let task_context = task_contexts
.context_for_task(&task_source_kind, &original_task)
.unwrap_or(&default_context);
workspace.schedule_task(
task_source_kind,
&original_task,
let Some(mut resolved_task) = original_task.resolve_task(
&task_source_kind.to_id_base(),
task_context,
) else {
return;
};
apply_rerun_overrides(&action, &mut resolved_task.resolved);
workspace.schedule_resolved_task(
task_source_kind,
resolved_task,
false,
window,
cx,
@@ -150,14 +156,7 @@ pub fn init(cx: &mut App) {
})
.detach();
} else {
let resolved = &mut last_scheduled_task.resolved;
if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
resolved.allow_concurrent_runs = allow_concurrent_runs;
}
if let Some(use_new_terminal) = action.use_new_terminal {
resolved.use_new_terminal = use_new_terminal;
}
apply_rerun_overrides(action, &mut last_scheduled_task.resolved);
workspace.schedule_resolved_task(
task_source_kind,
@@ -183,6 +182,15 @@ pub fn init(cx: &mut App) {
.detach();
}
fn apply_rerun_overrides(action: &Rerun, resolved: &mut SpawnInTerminal) {
if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
resolved.allow_concurrent_runs = allow_concurrent_runs;
}
if let Some(use_new_terminal) = action.use_new_terminal {
resolved.use_new_terminal = use_new_terminal;
}
}
fn spawn_task_or_modal(
workspace: &mut Workspace,
action: &Spawn,
@@ -725,6 +733,53 @@ mod tests {
assert_reevaluated_rerun_in_project_root(&workspace, cx);
}
#[gpui::test]
async fn test_reevaluated_rerun_overrides_keep_task_definition(cx: &mut TestAppContext) {
let (project, workspace, cx) = init_project_with_worktree_task(cx).await;
assert_global_task_spawned_in_project_root(&project, &workspace, cx).await;
let spawned_task = last_scheduled_task(&workspace, cx);
cx.dispatch_action(Rerun {
reevaluate_context: true,
allow_concurrent_runs: Some(true),
use_new_terminal: Some(true),
..Rerun::default()
});
cx.run_until_parked();
let overridden_task = last_scheduled_task(&workspace, cx);
assert_eq!(overridden_task.id, spawned_task.id);
assert_eq!(
overridden_task.original_task(),
spawned_task.original_task()
);
assert!(overridden_task.resolved.allow_concurrent_runs);
assert!(overridden_task.resolved.use_new_terminal);
task_inventory(&workspace, cx)
.update(cx, |inventory, _| {
inventory.update_file_based_tasks(
TaskSettingsLocation::Global(Path::new(path!("/zed-config/tasks.json"))),
Some(GLOBAL_TASKS_JSON),
)
})
.unwrap();
let task_after_save = last_scheduled_task(&workspace, cx);
assert_eq!(
task_after_save.id, spawned_task.id,
"Saving the file without changes should keep the rerun target"
);
assert!(task_after_save.resolved.use_new_terminal);
cx.dispatch_action(Rerun {
reevaluate_context: true,
..Rerun::default()
});
cx.run_until_parked();
let rerun_without_overrides = last_scheduled_task(&workspace, cx);
assert!(!rerun_without_overrides.resolved.allow_concurrent_runs);
assert!(!rerun_without_overrides.resolved.use_new_terminal);
}
#[gpui::test]
async fn test_reevaluated_rerun_resolves_worktree_task_with_invisible_worktree_editor_active(
cx: &mut TestAppContext,
+18 -12
View File
@@ -2,7 +2,7 @@ use std::process::ExitStatus;
use anyhow::Result;
use collections::HashSet;
use gpui::{AppContext, AsyncWindowContext, Context, Entity, Task, TaskExt, WeakEntity};
use gpui::{App, AppContext, AsyncWindowContext, Context, Entity, Task, TaskExt, WeakEntity};
use language::Buffer;
use project::{TaskSourceKind, WorktreeId, trusted_worktrees::TrustedWorktrees};
use remote::ConnectionState;
@@ -26,6 +26,21 @@ pub enum ScheduledTaskResult {
type TaskCompletionHandler = Box<dyn FnOnce(ScheduledTaskResult, &mut AsyncWindowContext)>;
impl Workspace {
pub fn can_schedule_tasks(&self, cx: &App) -> bool {
match self.project.read(cx).remote_connection_state(cx) {
None | Some(ConnectionState::Connected) => true,
Some(
ConnectionState::Connecting
| ConnectionState::Disconnected
| ConnectionState::HeartbeatMissed
| ConnectionState::Reconnecting,
) => {
log::warn!("Cannot schedule tasks when disconnected from a remote host");
false
}
}
}
pub fn schedule_task(
self: &mut Workspace,
task_source_kind: TaskSourceKind,
@@ -35,17 +50,8 @@ impl Workspace {
window: &mut Window,
cx: &mut Context<Self>,
) {
match self.project.read(cx).remote_connection_state(cx) {
None | Some(ConnectionState::Connected) => {}
Some(
ConnectionState::Connecting
| ConnectionState::Disconnected
| ConnectionState::HeartbeatMissed
| ConnectionState::Reconnecting,
) => {
log::warn!("Cannot schedule tasks when disconnected from a remote host");
return;
}
if !self.can_schedule_tasks(cx) {
return;
}
if let Some(spawn_in_terminal) =