diff --git a/crates/ide-host/src/automations/mod.rs b/crates/ide-host/src/automations/mod.rs index fd2540f903..d3945bcd70 100644 --- a/crates/ide-host/src/automations/mod.rs +++ b/crates/ide-host/src/automations/mod.rs @@ -603,7 +603,7 @@ impl AutomationService { }) .cloned() .collect(); - out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms)); + out.sort_by(compare_automations_by_schedule); out } @@ -3146,6 +3146,32 @@ fn is_actively_scheduled(a: &AgentAutomation) -> bool { } } +/// Orders automations as an upcoming schedule queue: +/// 1. Enabled schedules with a future `next_run_ms` (soonest first), +/// 2. Enabled idle/manual schedules with no upcoming firing (most recently updated first), +/// 3. Paused automations (most recently updated first). +fn compare_automations_by_schedule(a: &AgentAutomation, b: &AgentAutomation) -> std::cmp::Ordering { + let tier = |x: &AgentAutomation| -> u8 { + if !x.enabled { + 2 + } else if x.next_run_ms.is_some() { + 0 + } else { + 1 + } + }; + tier(a) + .cmp(&tier(b)) + .then_with(|| { + match (a.enabled.then_some(a.next_run_ms).flatten(), b.enabled.then_some(b.next_run_ms).flatten()) { + (Some(na), Some(nb)) => na.total_cmp(&nb), + _ => std::cmp::Ordering::Equal, + } + }) + .then_with(|| b.updated_ms.total_cmp(&a.updated_ms)) + .then_with(|| a.name.cmp(&b.name)) +} + /// Disables a `OneShot` automation whose seed timestamp has elapsed once no active run remains /// and the agent did not schedule a future `next_run_override_ms`. fn finalize_exhausted_oneshot_locked(state: &mut StoredState, automation_id: &str, now: f64) -> bool { diff --git a/crates/ide-host/tests/agent_automations.rs b/crates/ide-host/tests/agent_automations.rs index 585ba84587..e7285d83f0 100644 --- a/crates/ide-host/tests/agent_automations.rs +++ b/crates/ide-host/tests/agent_automations.rs @@ -616,6 +616,82 @@ async fn crud_boot_service_lifecycle_and_markdown_roundtrip() { assert!(!imported.enabled, "imported .automation.md must default to disabled"); assert_eq!(imported.max_runs, Some(50)); + // Add a sooner OneShot schedule and verify `list()` orders by soonest `next_run_ms` first, + // followed by enabled idle/manual schedules, then paused automations at the bottom. + let sooner_ms = cron_auto.next_run_ms.unwrap() - 60_000.0; + let sooner_auto = agent_automation_save( + &host, + "main", + SaveAutomationInput { + id: None, + name: "Sooner OneShot".into(), + enabled: true, + prompt: AgentPrompt { text: "soon".into(), files: vec![], images: vec![] }, + workspace: AutomationWorkspace::Project { + root: IpcPath(root.clone()), + isolation: Isolation::Local, + base: None, + auto_clean_worktree: false, + }, + continuity: AutomationContinuity::NewTask, + provider: "mock-acp".into(), + config: vec![], + permissions: AutomationPermissionMode::Default, + mcp_overrides: Default::default(), + skill_overrides: Default::default(), + memory_overrides: None, + trigger: AutomationTrigger::OneShot { run_at_ms: sooner_ms }, + allow_agent_schedule: false, + clear_override: false, + misfire_policy: None, + disable_after_ms: None, + max_runs: None, + }, + ) + .await + .unwrap(); + let enabled_manual = agent_automation_save( + &host, + "main", + SaveAutomationInput { + id: None, + name: "Enabled Manual".into(), + enabled: true, + prompt: AgentPrompt { text: "manual".into(), files: vec![], images: vec![] }, + workspace: AutomationWorkspace::Project { + root: IpcPath(root.clone()), + isolation: Isolation::Local, + base: None, + auto_clean_worktree: false, + }, + continuity: AutomationContinuity::NewTask, + provider: "mock-acp".into(), + config: vec![], + permissions: AutomationPermissionMode::Default, + mcp_overrides: Default::default(), + skill_overrides: Default::default(), + memory_overrides: None, + trigger: AutomationTrigger::Manual, + allow_agent_schedule: false, + clear_override: false, + misfire_policy: None, + disable_after_ms: None, + max_runs: None, + }, + ) + .await + .unwrap(); + let ordered_ids: Vec = host.automations.list(Some(&root)).into_iter().map(|a| a.id).collect(); + assert_eq!( + ordered_ids[..3], + [sooner_auto.id.clone(), cron_auto.id.clone(), enabled_manual.id.clone()], + "active schedules must sort soonest next_run_ms first, then enabled idle, then paused: {ordered_ids:?}" + ); + assert!( + ordered_ids[3..].contains(&imported.id) && ordered_ids[3..].contains(&manual.id), + "paused automations must appear after active/enabled schedules: {ordered_ids:?}" + ); + // Turning off autoStartService in settings unregisters the OS boot service immediately host.global_settings .set(SettingsScope::Global, "agents.automations.autoStartService", serde_json::json!(false)) @@ -634,6 +710,8 @@ async fn crud_boot_service_lifecycle_and_markdown_roundtrip() { assert!(paused >= 1); assert!(!service_file.exists()); + agent_automation_delete(&host, "main", sooner_auto.id).await.unwrap(); + agent_automation_delete(&host, "main", enabled_manual.id).await.unwrap(); agent_automation_delete(&host, "main", manual.id).await.unwrap(); agent_automation_delete(&host, "main", cron_auto.id).await.unwrap(); agent_automation_delete(&host, "main", imported.id).await.unwrap(); diff --git a/e2e/agentAutomations.spec.ts b/e2e/agentAutomations.spec.ts index ef0d7e2712..26f8f58b64 100644 --- a/e2e/agentAutomations.spec.ts +++ b/e2e/agentAutomations.spec.ts @@ -560,14 +560,13 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom await importDialog.getByRole("button", { name: "Import Disabled" }).click(); await expect(editor).toContainText("Imported Security Audit"); - await expect(editor.locator('[data-testid^="automation-row-"]').first()).toContainText("Paused"); + const importedRow = editor.locator('[data-testid^="automation-row-"]', { hasText: "Imported Security Audit" }); + await expect(importedRow).toContainText("Paused"); + // Active schedule sorts ahead of paused imported schedule + await expect(editor.locator('[data-testid^="automation-row-"]').first()).toContainText("Morning PR & CI Triage"); // Delete Imported Security Audit via More Actions › Delete… confirmation dialog - await editor - .locator('[data-testid^="automation-row-"]') - .first() - .getByRole("button", { name: "More Actions" }) - .click(); + await importedRow.getByRole("button", { name: "More Actions" }).click(); await page.getByRole("menuitem", { name: "Delete…" }).click(); await page.getByRole("dialog", { name: "Delete Automation" }).getByRole("button", { name: "Delete" }).click(); await expect(editor).not.toContainText("Imported Security Audit"); @@ -891,7 +890,7 @@ test("supports Weekly day picker, Local Autonomous warning, ChatOnly workspace, await page.getByRole("menuitem", { name: "Duplicate" }).click(); await expect(editor).toContainText("Weekly Release Notes (Copy)"); - const copyRow = editor.locator('[data-testid^="automation-row-"]').first(); + const copyRow = editor.locator('[data-testid^="automation-row-"]', { hasText: "Weekly Release Notes (Copy)" }); await copyRow.getByRole("button", { name: "Resume Schedule" }).click(); await expect(page.getByTestId("scheduler-host-pill")).toContainText("2 active schedules"); await copyRow.getByRole("button", { name: "Pause Schedule" }).click(); diff --git a/src/features/agents/AutomationsEditor.tsx b/src/features/agents/AutomationsEditor.tsx index 9193836a34..b0b4b9290c 100644 --- a/src/features/agents/AutomationsEditor.tsx +++ b/src/features/agents/AutomationsEditor.tsx @@ -27,6 +27,7 @@ import { import { notifications, type EditorInput } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; import { + compareAutomationsBySchedule, defaultAutomationsBackend, describeTrigger, formatShortTimestamp, @@ -99,14 +100,16 @@ export function AutomationsEditor({ const filteredAutomations = useMemo(() => { const q = query.trim().toLowerCase(); - return snapshot.automations.filter((a) => { - if (!q) return true; - return ( - a.name.toLowerCase().includes(q) || - a.prompt.text.toLowerCase().includes(q) || - a.provider.toLowerCase().includes(q) - ); - }); + return snapshot.automations + .filter((a) => { + if (!q) return true; + return ( + a.name.toLowerCase().includes(q) || + a.prompt.text.toLowerCase().includes(q) || + a.provider.toLowerCase().includes(q) + ); + }) + .sort(compareAutomationsBySchedule); }, [snapshot.automations, query]); const filteredRuns = useMemo(() => { diff --git a/src/features/agents/automations.test.tsx b/src/features/agents/automations.test.tsx index 1a7112fb84..8404d571ea 100644 --- a/src/features/agents/automations.test.tsx +++ b/src/features/agents/automations.test.tsx @@ -13,6 +13,7 @@ import { EMPTY_AUTOMATION_SNAPSHOT, automatedTaskVisible, closeAutomationDialog, + compareAutomationsBySchedule, describeTrigger, formatLoopInterval, latestAutomatedTaskIds, @@ -527,4 +528,73 @@ describe("Agent Automations model & UI", () => { ), ); }); + + it("sorts Schedules by soonest upcoming nextRunMs first, then enabled idle, then paused", async () => { + const now = Date.now(); + const base: AgentAutomation_Serialize = { + id: "base", + name: "Base", + enabled: true, + prompt: { text: "run", files: [], images: [] }, + workspace: { kind: "chatOnly" }, + continuity: "sameTask", + provider: "claude", + config: [], + permissions: "assisted", + trigger: { kind: "daily", hour: 20, minute: 0, timeZone: "UTC" }, + allowAgentSchedule: false, + runCount: 0, + unreadRuns: 0, + createdMs: now - 10_000, + updatedMs: now - 10_000, + }; + const pausedRecent: AgentAutomation_Serialize = { + ...base, + id: "paused", + name: "Paused Recent", + enabled: false, + nextRunMs: null, + updatedMs: now, + }; + const laterActive: AgentAutomation_Serialize = { + ...base, + id: "later", + name: "Evening Check-in", + enabled: true, + nextRunMs: now + 5 * 3_600_000, + updatedMs: now - 1_000, + }; + const enabledIdle: AgentAutomation_Serialize = { + ...base, + id: "idle", + name: "Manual Idle", + enabled: true, + trigger: { kind: "manual" }, + nextRunMs: null, + updatedMs: now - 2_000, + }; + const soonestOverride: AgentAutomation_Serialize = { + ...base, + id: "soonest", + name: "Daily Farm Override", + enabled: true, + allowAgentSchedule: true, + nextRunMs: now + 30 * 60_000, + nextRunOverrideMs: now + 30 * 60_000, + updatedMs: now - 50_000, + }; + + const sorted = [pausedRecent, laterActive, enabledIdle, soonestOverride].sort(compareAutomationsBySchedule); + expect(sorted.map((a) => a.id)).toEqual(["soonest", "later", "idle", "paused"]); + + const { backend } = makeMockBackend({ + automations: [pausedRecent, laterActive, enabledIdle, soonestOverride], + }); + render(); + await waitFor(() => expect(screen.getByText("Daily Farm Override")).toBeTruthy()); + const renderedIds = Array.from(document.querySelectorAll('[data-testid^="automation-row-"]')).map( + (el) => el.dataset.testid?.replace("automation-row-", ""), + ); + expect(renderedIds).toEqual(["soonest", "later", "idle", "paused"]); + }); }); diff --git a/src/features/agents/automationsModel.ts b/src/features/agents/automationsModel.ts index 45902187c4..38660371b7 100644 --- a/src/features/agents/automationsModel.ts +++ b/src/features/agents/automationsModel.ts @@ -268,6 +268,25 @@ export function isAutomationActivelyScheduled(a: AgentAutomation_Serialize): boo return true; } +/** + * Orders schedules as an upcoming timeline: + * 1. Enabled schedules with an upcoming `nextRunMs` (soonest first), + * 2. Enabled idle/manual schedules with no `nextRunMs` (most recently updated first), + * 3. Paused automations (most recently updated first). + */ +export function compareAutomationsBySchedule(a: AgentAutomation_Serialize, b: AgentAutomation_Serialize): number { + const tier = (x: AgentAutomation_Serialize) => (!x.enabled ? 2 : x.nextRunMs != null ? 0 : 1); + const tDiff = tier(a) - tier(b); + if (tDiff !== 0) return tDiff; + if (a.enabled && b.enabled && a.nextRunMs != null && b.nextRunMs != null) { + const nextDiff = a.nextRunMs - b.nextRunMs; + if (nextDiff !== 0) return nextDiff; + } + const updDiff = (b.updatedMs ?? 0) - (a.updatedMs ?? 0); + if (updDiff !== 0) return updDiff; + return a.name.localeCompare(b.name); +} + export function triggersEqual(a: AutomationTrigger, b: AutomationTrigger): boolean { if (a.kind !== b.kind) return false; switch (a.kind) { @@ -309,7 +328,7 @@ function buildFallbackSnapshot(remote: boolean): AutomationSnapshot_Serialize { } const bootRegistered = fallbackState.autoStartService && activeSchedules > 0; return { - automations: [...fallbackState.automations], + automations: [...fallbackState.automations].sort(compareAutomationsBySchedule), runs: [...fallbackState.runs], runsNextCursor: null, sessionSchedules: [...fallbackState.sessionSchedules],